diff options
Diffstat (limited to 'modules')
385 files changed, 8123 insertions, 32035 deletions
diff --git a/modules/basis_universal/register_types.cpp b/modules/basis_universal/register_types.cpp index 12f9c6fc00..a3c662ba08 100644 --- a/modules/basis_universal/register_types.cpp +++ b/modules/basis_universal/register_types.cpp @@ -32,7 +32,6 @@ #include "core/os/os.h" #include "servers/rendering_server.h" -#include "texture_basisu.h" #ifdef TOOLS_ENABLED #include <encoder/basisu_comp.h> @@ -272,7 +271,6 @@ void register_basis_universal_types() { Image::basis_universal_packer = basis_universal_packer; #endif Image::basis_universal_unpacker = basis_universal_unpacker; - //GDREGISTER_CLASS(TextureBasisU); } void unregister_basis_universal_types() { diff --git a/modules/basis_universal/texture_basisu.cpp b/modules/basis_universal/texture_basisu.cpp deleted file mode 100644 index 1ac4df8d19..0000000000 --- a/modules/basis_universal/texture_basisu.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/*************************************************************************/ -/* texture_basisu.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "texture_basisu.h" -#if 0 -#include "core/os/os.h" - -#ifdef TOOLS_ENABLED -#include <encoder/basisu_comp.h> -#endif - -#include <transcoder/basisu_transcoder.h> - -void TextureBasisU::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_basisu_data", "data"), &TextureBasisU::set_basisu_data); - ClassDB::bind_method(D_METHOD("get_basisu_data"), &TextureBasisU::get_data); - ClassDB::bind_method(D_METHOD("import"), &TextureBasisU::import); - - ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "basisu_data"), "set_basisu_data", "get_basisu_data"); -}; - -int TextureBasisU::get_width() const { - return tex_size.x; -}; - -int TextureBasisU::get_height() const { - return tex_size.y; -}; - -RID TextureBasisU::get_rid() const { - return texture; -}; - - -bool TextureBasisU::has_alpha() const { - return false; -}; - -void TextureBasisU::set_flags(uint32_t p_flags) { - flags = p_flags; - RenderingServer::get_singleton()->texture_set_flags(texture, p_flags); -}; - -uint32_t TextureBasisU::get_flags() const { - return flags; -}; - - -void TextureBasisU::set_basisu_data(const Vector<uint8_t>& p_data) { - -#ifdef TOOLS_ENABLED - data = p_data; -#endif - - const uint8_t* r = p_data.ptr(); - const void* ptr = r.ptr(); - int size = p_data.size(); - - basist::transcoder_texture_format format; - Image::Format imgfmt; - - if (OS::get_singleton()->has_feature("s3tc")) { - format = basist::cTFBC3; // get this from renderer - imgfmt = Image::FORMAT_DXT5; - - } else if (OS::get_singleton()->has_feature("etc2")) { - format = basist::cTFETC2; - imgfmt = Image::FORMAT_ETC2_RGBA8; - }; - - basist::basisu_transcoder tr(nullptr); - - ERR_FAIL_COND(!tr.validate_header(ptr, size)); - - basist::basisu_image_info info; - tr.get_image_info(ptr, size, info, 0); - tex_size = Size2(info.m_width, info.m_height); - - int block_size = basist::basis_get_bytes_per_block(format); - Vector<uint8_t> gpudata; - gpudata.resize(info.m_total_blocks * block_size); - - { - uint8_t* w = gpudata.ptrw(); - uint8_t* dst = w.ptr(); - for (int i=0; i<gpudata.size(); i++) - dst[i] = 0x00; - - int ofs = 0; - tr.start_transcoding(ptr, size); - for (int i=0; i<info.m_total_levels; i++) { - basist::basisu_image_level_info level; - tr.get_image_level_info(ptr, size, level, 0, i); - - bool ret = tr.transcode_image_level(ptr, size, 0, i, dst + ofs, level.m_total_blocks - i, format); - if (!ret) { - printf("failed! on level %i\n", i); - break; - }; - - ofs += level.m_total_blocks * block_size; - }; - }; - - Ref<Image> img; - img.instantiate(); - img->create(info.m_width, info.m_height, info.m_total_levels > 1, imgfmt, gpudata); - - RenderingServer::get_singleton()->texture_allocate(texture, tex_size.x, tex_size.y, 0, img->get_format(), RS::TEXTURE_TYPE_2D, flags); - RenderingServer::get_singleton()->texture_set_data(texture, img); -}; - -Error TextureBasisU::import(const Ref<Image>& p_img) { - -#ifdef TOOLS_ENABLED - - Vector<uint8_t> budata; - - { - Image::Format format = p_img->get_format(); - if (format != Image::FORMAT_RGB8 && format != Image::FORMAT_RGBA8) { - ERR_FAIL_V(ERR_INVALID_PARAMETER); - return ERR_INVALID_PARAMETER; - }; - - Ref<Image> copy = p_img->duplicate(); - if (format == Image::FORMAT_RGB8) - copy->convert(Image::FORMAT_RGBA8); - - basisu::image buimg(p_img->get_width(), p_img->get_height()); - int size = p_img->get_width() * p_img->get_height() * 4; - - Vector<uint8_t> vec = copy->get_data(); - { - const uint8_t* r = vec.ptr(); - memcpy(buimg.get_ptr(), r.ptr(), size); - }; - - basisu::basis_compressor_params params; - params.m_max_endpoint_clusters = 512; - params.m_max_selector_clusters = 512; - params.m_multithreading = true; - - basisu::job_pool jpool(1); - params.m_pJob_pool = &jpool; - - params.m_mip_gen = p_img->get_mipmap_count() > 0; - params.m_source_images.push_back(buimg); - - basisu::basis_compressor c; - c.init(params); - - int buerr = c.process(); - if (buerr != basisu::basis_compressor::cECSuccess) { - ERR_FAIL_V(ERR_INVALID_PARAMETER); - return ERR_INVALID_PARAMETER; - }; - - const basisu::uint8_vec& buvec = c.get_output_basis_file(); - budata.resize(buvec.size()); - - { - uint8_t* w = budata.ptrw(); - memcpy(w.ptr(), &buvec[0], budata.size()); - }; - }; - - set_basisu_data(budata); - - return OK; -#else - - return ERR_UNAVAILABLE; -#endif -}; - - -Vector<uint8_t> TextureBasisU::get_basisu_data() const { - return data; -}; - -TextureBasisU::TextureBasisU() { - texture = RenderingServer::get_singleton()->texture_create(); -}; - - -TextureBasisU::~TextureBasisU() { - RenderingServer::get_singleton()->free(texture); -}; - -#endif diff --git a/modules/bullet/SCsub b/modules/bullet/SCsub deleted file mode 100644 index 09509abc44..0000000000 --- a/modules/bullet/SCsub +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env python - -Import("env") -Import("env_modules") - -env_bullet = env_modules.Clone() - -# Thirdparty source files - -thirdparty_obj = [] - -if env["builtin_bullet"]: - # Build only "Bullet2" API (not "Bullet3" folders). - # Sync file list with relevant upstream CMakeLists.txt for each folder. - if env["float"] == "64": - env.Append(CPPDEFINES=["BT_USE_DOUBLE_PRECISION=1"]) - thirdparty_dir = "#thirdparty/bullet/" - - bullet2_src = [ - # BulletCollision - "BulletCollision/BroadphaseCollision/btAxisSweep3.cpp", - "BulletCollision/BroadphaseCollision/btBroadphaseProxy.cpp", - "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.cpp", - "BulletCollision/BroadphaseCollision/btDbvt.cpp", - "BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp", - "BulletCollision/BroadphaseCollision/btDispatcher.cpp", - "BulletCollision/BroadphaseCollision/btOverlappingPairCache.cpp", - "BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp", - "BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp", - "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp", - "BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp", - "BulletCollision/CollisionDispatch/btCollisionDispatcherMt.cpp", - "BulletCollision/CollisionDispatch/btCollisionObject.cpp", - "BulletCollision/CollisionDispatch/btCollisionWorld.cpp", - "BulletCollision/CollisionDispatch/btCollisionWorldImporter.cpp", - "BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btCompoundCompoundCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp", - "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btGhostObject.cpp", - "BulletCollision/CollisionDispatch/btHashedSimplePairCache.cpp", - "BulletCollision/CollisionDispatch/btInternalEdgeUtility.cpp", - "BulletCollision/CollisionDispatch/btManifoldResult.cpp", - "BulletCollision/CollisionDispatch/btSimulationIslandManager.cpp", - "BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp", - "BulletCollision/CollisionDispatch/btUnionFind.cpp", - "BulletCollision/CollisionDispatch/SphereTriangleDetector.cpp", - "BulletCollision/CollisionShapes/btBoxShape.cpp", - "BulletCollision/CollisionShapes/btBox2dShape.cpp", - "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.cpp", - "BulletCollision/CollisionShapes/btCapsuleShape.cpp", - "BulletCollision/CollisionShapes/btCollisionShape.cpp", - "BulletCollision/CollisionShapes/btCompoundShape.cpp", - "BulletCollision/CollisionShapes/btConcaveShape.cpp", - "BulletCollision/CollisionShapes/btConeShape.cpp", - "BulletCollision/CollisionShapes/btConvexHullShape.cpp", - "BulletCollision/CollisionShapes/btConvexInternalShape.cpp", - "BulletCollision/CollisionShapes/btConvexPointCloudShape.cpp", - "BulletCollision/CollisionShapes/btConvexPolyhedron.cpp", - "BulletCollision/CollisionShapes/btConvexShape.cpp", - "BulletCollision/CollisionShapes/btConvex2dShape.cpp", - "BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp", - "BulletCollision/CollisionShapes/btCylinderShape.cpp", - "BulletCollision/CollisionShapes/btEmptyShape.cpp", - "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.cpp", - "BulletCollision/CollisionShapes/btMiniSDF.cpp", - "BulletCollision/CollisionShapes/btMinkowskiSumShape.cpp", - "BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp", - "BulletCollision/CollisionShapes/btMultiSphereShape.cpp", - "BulletCollision/CollisionShapes/btOptimizedBvh.cpp", - "BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp", - "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp", - "BulletCollision/CollisionShapes/btSdfCollisionShape.cpp", - "BulletCollision/CollisionShapes/btShapeHull.cpp", - "BulletCollision/CollisionShapes/btSphereShape.cpp", - "BulletCollision/CollisionShapes/btStaticPlaneShape.cpp", - "BulletCollision/CollisionShapes/btStridingMeshInterface.cpp", - "BulletCollision/CollisionShapes/btTetrahedronShape.cpp", - "BulletCollision/CollisionShapes/btTriangleBuffer.cpp", - "BulletCollision/CollisionShapes/btTriangleCallback.cpp", - "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.cpp", - "BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp", - "BulletCollision/CollisionShapes/btTriangleMesh.cpp", - "BulletCollision/CollisionShapes/btTriangleMeshShape.cpp", - "BulletCollision/CollisionShapes/btUniformScalingShape.cpp", - "BulletCollision/Gimpact/btContactProcessing.cpp", - "BulletCollision/Gimpact/btGenericPoolAllocator.cpp", - "BulletCollision/Gimpact/btGImpactBvh.cpp", - "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.cpp", - "BulletCollision/Gimpact/btGImpactQuantizedBvh.cpp", - "BulletCollision/Gimpact/btGImpactShape.cpp", - "BulletCollision/Gimpact/btTriangleShapeEx.cpp", - "BulletCollision/Gimpact/gim_box_set.cpp", - "BulletCollision/Gimpact/gim_contact.cpp", - "BulletCollision/Gimpact/gim_memory.cpp", - "BulletCollision/Gimpact/gim_tri_collision.cpp", - "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp", - "BulletCollision/NarrowPhaseCollision/btConvexCast.cpp", - "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.cpp", - "BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp", - "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp", - "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp", - "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.cpp", - "BulletCollision/NarrowPhaseCollision/btPersistentManifold.cpp", - "BulletCollision/NarrowPhaseCollision/btRaycastCallback.cpp", - "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp", - "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp", - "BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp", - # BulletDynamics - "BulletDynamics/Character/btKinematicCharacterController.cpp", - "BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp", - "BulletDynamics/ConstraintSolver/btContactConstraint.cpp", - "BulletDynamics/ConstraintSolver/btFixedConstraint.cpp", - "BulletDynamics/ConstraintSolver/btGearConstraint.cpp", - "BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.cpp", - "BulletDynamics/ConstraintSolver/btGeneric6DofSpringConstraint.cpp", - "BulletDynamics/ConstraintSolver/btGeneric6DofSpring2Constraint.cpp", - "BulletDynamics/ConstraintSolver/btHinge2Constraint.cpp", - "BulletDynamics/ConstraintSolver/btHingeConstraint.cpp", - "BulletDynamics/ConstraintSolver/btPoint2PointConstraint.cpp", - "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp", - "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolverMt.cpp", - "BulletDynamics/ConstraintSolver/btBatchedConstraints.cpp", - "BulletDynamics/ConstraintSolver/btNNCGConstraintSolver.cpp", - "BulletDynamics/ConstraintSolver/btSliderConstraint.cpp", - "BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.cpp", - "BulletDynamics/ConstraintSolver/btTypedConstraint.cpp", - "BulletDynamics/ConstraintSolver/btUniversalConstraint.cpp", - "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp", - "BulletDynamics/Dynamics/btDiscreteDynamicsWorldMt.cpp", - "BulletDynamics/Dynamics/btSimulationIslandManagerMt.cpp", - "BulletDynamics/Dynamics/btRigidBody.cpp", - "BulletDynamics/Dynamics/btSimpleDynamicsWorld.cpp", - # "BulletDynamics/Dynamics/Bullet-C-API.cpp", - "BulletDynamics/Vehicle/btRaycastVehicle.cpp", - "BulletDynamics/Vehicle/btWheelInfo.cpp", - "BulletDynamics/Featherstone/btMultiBody.cpp", - "BulletDynamics/Featherstone/btMultiBodyConstraint.cpp", - "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.cpp", - "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.cpp", - "BulletDynamics/Featherstone/btMultiBodyFixedConstraint.cpp", - "BulletDynamics/Featherstone/btMultiBodyGearConstraint.cpp", - "BulletDynamics/Featherstone/btMultiBodyJointLimitConstraint.cpp", - "BulletDynamics/Featherstone/btMultiBodyJointMotor.cpp", - "BulletDynamics/Featherstone/btMultiBodyMLCPConstraintSolver.cpp", - "BulletDynamics/Featherstone/btMultiBodyPoint2Point.cpp", - "BulletDynamics/Featherstone/btMultiBodySliderConstraint.cpp", - "BulletDynamics/Featherstone/btMultiBodySphericalJointMotor.cpp", - "BulletDynamics/MLCPSolvers/btDantzigLCP.cpp", - "BulletDynamics/MLCPSolvers/btMLCPSolver.cpp", - "BulletDynamics/MLCPSolvers/btLemkeAlgorithm.cpp", - # BulletInverseDynamics - "BulletInverseDynamics/IDMath.cpp", - "BulletInverseDynamics/MultiBodyTree.cpp", - "BulletInverseDynamics/details/MultiBodyTreeInitCache.cpp", - "BulletInverseDynamics/details/MultiBodyTreeImpl.cpp", - # BulletSoftBody - "BulletSoftBody/btSoftBody.cpp", - "BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.cpp", - "BulletSoftBody/btSoftBodyHelpers.cpp", - "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp", - "BulletSoftBody/btSoftRigidCollisionAlgorithm.cpp", - "BulletSoftBody/btSoftRigidDynamicsWorld.cpp", - "BulletSoftBody/btSoftMultiBodyDynamicsWorld.cpp", - "BulletSoftBody/btSoftSoftCollisionAlgorithm.cpp", - "BulletSoftBody/btDefaultSoftBodySolver.cpp", - "BulletSoftBody/btDeformableBackwardEulerObjective.cpp", - "BulletSoftBody/btDeformableBodySolver.cpp", - "BulletSoftBody/btDeformableMultiBodyConstraintSolver.cpp", - "BulletSoftBody/btDeformableContactProjection.cpp", - "BulletSoftBody/btDeformableMultiBodyDynamicsWorld.cpp", - "BulletSoftBody/btDeformableContactConstraint.cpp", - "BulletSoftBody/poly34.cpp", - # clew - "clew/clew.c", - # LinearMath - "LinearMath/btAlignedAllocator.cpp", - "LinearMath/btConvexHull.cpp", - "LinearMath/btConvexHullComputer.cpp", - "LinearMath/btGeometryUtil.cpp", - "LinearMath/btPolarDecomposition.cpp", - "LinearMath/btQuickprof.cpp", - "LinearMath/btReducedVector.cpp", - "LinearMath/btSerializer.cpp", - "LinearMath/btSerializer64.cpp", - "LinearMath/btThreads.cpp", - "LinearMath/btVector3.cpp", - "LinearMath/TaskScheduler/btTaskScheduler.cpp", - "LinearMath/TaskScheduler/btThreadSupportPosix.cpp", - "LinearMath/TaskScheduler/btThreadSupportWin32.cpp", - ] - - thirdparty_sources = [thirdparty_dir + file for file in bullet2_src] - - env_bullet.Prepend(CPPPATH=[thirdparty_dir]) - if env["target"] == "debug" or env["target"] == "release_debug": - env_bullet.Append(CPPDEFINES=["DEBUG"]) - - env_bullet.Append(CPPDEFINES=["BT_USE_OLD_DAMPING_METHOD", "BT_THREADSAFE"]) - - env_thirdparty = env_bullet.Clone() - env_thirdparty.disable_warnings() - env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources) - env.modules_sources += thirdparty_obj - - -# Godot source files - -module_obj = [] - -env_bullet.add_source_files(module_obj, "*.cpp") -env.modules_sources += module_obj - -# Needed to force rebuilding the module files when the thirdparty library is updated. -env.Depends(module_obj, thirdparty_obj) diff --git a/modules/bullet/area_bullet.cpp b/modules/bullet/area_bullet.cpp deleted file mode 100644 index f816691cde..0000000000 --- a/modules/bullet/area_bullet.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/*************************************************************************/ -/* area_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "area_bullet.h" - -#include "bullet_physics_server.h" -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "collision_object_bullet.h" -#include "space_bullet.h" - -#include <BulletCollision/CollisionDispatch/btGhostObject.h> -#include <btBulletCollisionCommon.h> - -AreaBullet::AreaBullet() : - RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA) { - btGhost = bulletnew(btGhostObject); - reload_shapes(); - setupBulletCollisionObject(btGhost); - /// Collision objects with a callback still have collision response with dynamic rigid bodies. - /// In order to use collision objects as trigger, you have to disable the collision response. - set_collision_enabled(false); - - for (int i = 0; i < 5; ++i) { - call_event_res_ptr[i] = &call_event_res[i]; - } -} - -AreaBullet::~AreaBullet() { - // signal are handled by godot, so just clear without notify - for (int i = 0; i < overlapping_shapes.size(); i++) { - overlapping_shapes[i].other_object->on_exit_area(this); - } -} - -void AreaBullet::dispatch_callbacks() { - if (!isScratched) { - return; - } - isScratched = false; - - // Reverse order so items can be removed. - for (int i = overlapping_shapes.size() - 1; i >= 0; i--) { - OverlappingShapeData &overlapping_shape = overlapping_shapes.write[i]; - - switch (overlapping_shape.state) { - case OVERLAP_STATE_ENTER: - overlapping_shape.state = OVERLAP_STATE_INSIDE; - call_event(overlapping_shape, PhysicsServer3D::AREA_BODY_ADDED); - if (_overlapping_shape_count(overlapping_shape.other_object) == 1) { - // This object's first shape being added. - overlapping_shape.other_object->on_enter_area(this); - } - break; - case OVERLAP_STATE_EXIT: - call_event(overlapping_shape, PhysicsServer3D::AREA_BODY_REMOVED); - if (_overlapping_shape_count(overlapping_shape.other_object) == 1) { - // This object's last shape being removed. - overlapping_shape.other_object->on_exit_area(this); - } - overlapping_shapes.remove_at(i); // Remove after callback - break; - case OVERLAP_STATE_INSIDE: { - if (overlapping_shape.other_object->getType() == TYPE_RIGID_BODY) { - RigidBodyBullet *body = static_cast<RigidBodyBullet *>(overlapping_shape.other_object); - body->scratch_space_override_modificator(); - } - break; - } - case OVERLAP_STATE_DIRTY: - break; - } - } -} - -void AreaBullet::call_event(const OverlappingShapeData &p_overlapping_shape, PhysicsServer3D::AreaBodyStatus p_status) { - InOutEventCallback &event = eventsCallbacks[static_cast<int>(p_overlapping_shape.other_object->getType())]; - - if (!event.event_callback.is_valid()) { - event.event_callback = Callable(); - return; - } - - call_event_res[0] = p_status; - call_event_res[1] = p_overlapping_shape.other_object->get_self(); // RID - call_event_res[2] = p_overlapping_shape.other_object->get_instance_id(); // Object ID - call_event_res[3] = p_overlapping_shape.other_shape_id; // Other object's shape ID - call_event_res[4] = p_overlapping_shape.our_shape_id; // This area's shape ID - - Callable::CallError outResp; - Variant ret; - event.event_callback.call((const Variant **)call_event_res, 5, ret, outResp); -} - -int AreaBullet::_overlapping_shape_count(CollisionObjectBullet *p_other_object) { - int count = 0; - for (int i = 0; i < overlapping_shapes.size(); i++) { - if (overlapping_shapes[i].other_object == p_other_object) { - count++; - } - } - return count; -} - -int AreaBullet::_find_overlapping_shape(CollisionObjectBullet *p_other_object, uint32_t p_other_shape_id, uint32_t p_our_shape_id) { - for (int i = 0; i < overlapping_shapes.size(); i++) { - const OverlappingShapeData &overlapping_shape = overlapping_shapes[i]; - if (overlapping_shape.other_object == p_other_object && overlapping_shape.other_shape_id == p_other_shape_id && overlapping_shape.our_shape_id == p_our_shape_id) { - return i; - } - } - return -1; -} - -void AreaBullet::mark_all_overlaps_dirty() { - OverlappingShapeData *overlapping_shapes_w = overlapping_shapes.ptrw(); - for (int i = 0; i < overlapping_shapes.size(); i++) { - // Don't overwrite OVERLAP_STATE_ENTER state. - if (overlapping_shapes_w[i].state != OVERLAP_STATE_ENTER) { - overlapping_shapes_w[i].state = OVERLAP_STATE_DIRTY; - } - } -} - -void AreaBullet::mark_object_overlaps_inside(CollisionObjectBullet *p_other_object) { - OverlappingShapeData *overlapping_shapes_w = overlapping_shapes.ptrw(); - for (int i = 0; i < overlapping_shapes.size(); i++) { - if (overlapping_shapes_w[i].other_object == p_other_object && overlapping_shapes_w[i].state == OVERLAP_STATE_DIRTY) { - overlapping_shapes_w[i].state = OVERLAP_STATE_INSIDE; - } - } -} - -void AreaBullet::set_overlap(CollisionObjectBullet *p_other_object, uint32_t p_other_shape_id, uint32_t p_our_shape_id) { - int i = _find_overlapping_shape(p_other_object, p_other_shape_id, p_our_shape_id); - if (i == -1) { // Not found, create new one. - OverlappingShapeData overlapping_shape(p_other_object, OVERLAP_STATE_ENTER, p_other_shape_id, p_our_shape_id); - overlapping_shapes.push_back(overlapping_shape); - p_other_object->notify_new_overlap(this); - isScratched = true; - } else { - overlapping_shapes.ptrw()[i].state = OVERLAP_STATE_INSIDE; - } -} - -void AreaBullet::mark_all_dirty_overlaps_as_exit() { - OverlappingShapeData *overlapping_shapes_w = overlapping_shapes.ptrw(); - for (int i = 0; i < overlapping_shapes.size(); i++) { - if (overlapping_shapes[i].state == OVERLAP_STATE_DIRTY) { - overlapping_shapes_w[i].state = OVERLAP_STATE_EXIT; - isScratched = true; - } - } -} - -void AreaBullet::remove_object_overlaps(CollisionObjectBullet *p_object) { - // Reverse order so items can be removed. - for (int i = overlapping_shapes.size() - 1; i >= 0; i--) { - if (overlapping_shapes[i].other_object == p_object) { - overlapping_shapes.remove_at(i); - } - } -} - -void AreaBullet::clear_overlaps() { - for (int i = 0; i < overlapping_shapes.size(); i++) { - call_event(overlapping_shapes[i], PhysicsServer3D::AREA_BODY_REMOVED); - overlapping_shapes[i].other_object->on_exit_area(this); - } - overlapping_shapes.clear(); -} - -void AreaBullet::set_monitorable(bool p_monitorable) { - monitorable = p_monitorable; - updated = true; -} - -bool AreaBullet::is_monitoring() const { - return get_godot_object_flags() & GOF_IS_MONITORING_AREA; -} - -void AreaBullet::main_shape_changed() { - CRASH_COND(!get_main_shape()); - btGhost->setCollisionShape(get_main_shape()); - updated = true; -} - -void AreaBullet::reload_body() { - if (space) { - space->remove_area(this); - space->add_area(this); - } -} - -void AreaBullet::set_space(SpaceBullet *p_space) { - // Clear the old space if there is one - if (space) { - clear_overlaps(); - isScratched = false; - - // Remove this object form the physics world - space->remove_area(this); - } - - space = p_space; - - if (space) { - space->add_area(this); - } -} - -void AreaBullet::on_collision_filters_change() { - if (space) { - space->reload_collision_filters(this); - } - updated = true; -} - -void AreaBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) { - switch (p_param) { - case PhysicsServer3D::AREA_PARAM_GRAVITY: - set_spOv_gravityMag(p_value); - break; - case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: - set_spOv_gravityVec(p_value); - break; - case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: - set_spOv_linearDump(p_value); - break; - case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: - set_spOv_angularDump(p_value); - break; - case PhysicsServer3D::AREA_PARAM_PRIORITY: - set_spOv_priority(p_value); - break; - case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: - set_spOv_gravityPoint(p_value); - break; - case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: - set_spOv_gravityPointDistanceScale(p_value); - break; - case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: - set_spOv_gravityPointAttenuation(p_value); - break; - default: - WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param)); - } - isScratched = true; -} - -Variant AreaBullet::get_param(PhysicsServer3D::AreaParameter p_param) const { - switch (p_param) { - case PhysicsServer3D::AREA_PARAM_GRAVITY: - return spOv_gravityMag; - case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: - return spOv_gravityVec; - case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: - return spOv_linearDump; - case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: - return spOv_angularDump; - case PhysicsServer3D::AREA_PARAM_PRIORITY: - return spOv_priority; - case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: - return spOv_gravityPoint; - case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: - return spOv_gravityPointDistanceScale; - case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: - return spOv_gravityPointAttenuation; - default: - WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param)); - return Variant(); - } -} - -void AreaBullet::set_event_callback(Type p_callbackObjectType, const Callable &p_callback) { - InOutEventCallback &ev = eventsCallbacks[static_cast<int>(p_callbackObjectType)]; - ev.event_callback = p_callback; - - /// Set if monitoring - if (!eventsCallbacks[0].event_callback.is_null() || !eventsCallbacks[1].event_callback.is_null()) { - set_godot_object_flags(get_godot_object_flags() | GOF_IS_MONITORING_AREA); - } else { - set_godot_object_flags(get_godot_object_flags() & (~GOF_IS_MONITORING_AREA)); - clear_overlaps(); - } -} - -bool AreaBullet::has_event_callback(Type p_callbackObjectType) { - return !eventsCallbacks[static_cast<int>(p_callbackObjectType)].event_callback.is_null(); -} - -void AreaBullet::on_enter_area(AreaBullet *p_area) { -} - -void AreaBullet::on_exit_area(AreaBullet *p_area) { - CollisionObjectBullet::on_exit_area(p_area); -} diff --git a/modules/bullet/area_bullet.h b/modules/bullet/area_bullet.h deleted file mode 100644 index 740378d0e3..0000000000 --- a/modules/bullet/area_bullet.h +++ /dev/null @@ -1,162 +0,0 @@ -/*************************************************************************/ -/* area_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 AREA_BULLET_H -#define AREA_BULLET_H - -#include "collision_object_bullet.h" -#include "core/templates/vector.h" -#include "servers/physics_server_3d.h" -#include "space_bullet.h" - -class btGhostObject; - -class AreaBullet : public RigidCollisionObjectBullet { -public: - struct InOutEventCallback { - Callable event_callback; - - InOutEventCallback() {} - }; - - enum OverlapState { - OVERLAP_STATE_DIRTY = 0, // Mark processed overlaps - OVERLAP_STATE_INSIDE, // Mark old overlap - OVERLAP_STATE_ENTER, // Mark just enter overlap - OVERLAP_STATE_EXIT // Mark ended overlaps - }; - - struct OverlappingShapeData { - CollisionObjectBullet *other_object = nullptr; - OverlapState state = OVERLAP_STATE_DIRTY; - uint32_t other_shape_id = 0; - uint32_t our_shape_id = 0; - - OverlappingShapeData() {} - - OverlappingShapeData(CollisionObjectBullet *p_other_object, OverlapState p_state, uint32_t p_other_shape_id, uint32_t p_our_shape_id) : - other_object(p_other_object), - state(p_state), - other_shape_id(p_other_shape_id), - our_shape_id(p_our_shape_id) {} - }; - -private: - // These are used by function callEvent. Instead to create this each call I create if one time. - Variant call_event_res[5]; - Variant *call_event_res_ptr[5] = {}; - - btGhostObject *btGhost = nullptr; - Vector<OverlappingShapeData> overlapping_shapes; - int _overlapping_shape_count(CollisionObjectBullet *p_other_object); - int _find_overlapping_shape(CollisionObjectBullet *p_other_object, uint32_t p_other_shape_id, uint32_t p_our_shape_id); - bool monitorable = true; - - PhysicsServer3D::AreaSpaceOverrideMode spOv_mode = PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED; - bool spOv_gravityPoint = false; - real_t spOv_gravityPointDistanceScale = 0.0; - real_t spOv_gravityPointAttenuation = 1.0; - Vector3 spOv_gravityVec = Vector3(0, -1, 0); - real_t spOv_gravityMag = 10.0; - real_t spOv_linearDump = 0.1; - real_t spOv_angularDump = 0.1; - int spOv_priority = 0; - - bool isScratched = false; - - InOutEventCallback eventsCallbacks[2]; - -public: - AreaBullet(); - ~AreaBullet(); - - _FORCE_INLINE_ btGhostObject *get_bt_ghost() const { return btGhost; } - - void set_monitorable(bool p_monitorable); - _FORCE_INLINE_ bool is_monitorable() const { return monitorable; } - - bool is_monitoring() const; - - _FORCE_INLINE_ void set_spOv_mode(PhysicsServer3D::AreaSpaceOverrideMode p_mode) { spOv_mode = p_mode; } - _FORCE_INLINE_ PhysicsServer3D::AreaSpaceOverrideMode get_spOv_mode() { return spOv_mode; } - - _FORCE_INLINE_ void set_spOv_gravityPoint(bool p_isGP) { spOv_gravityPoint = p_isGP; } - _FORCE_INLINE_ bool is_spOv_gravityPoint() { return spOv_gravityPoint; } - - _FORCE_INLINE_ void set_spOv_gravityPointDistanceScale(real_t p_GPDS) { spOv_gravityPointDistanceScale = p_GPDS; } - _FORCE_INLINE_ real_t get_spOv_gravityPointDistanceScale() { return spOv_gravityPointDistanceScale; } - - _FORCE_INLINE_ void set_spOv_gravityPointAttenuation(real_t p_GPA) { spOv_gravityPointAttenuation = p_GPA; } - _FORCE_INLINE_ real_t get_spOv_gravityPointAttenuation() { return spOv_gravityPointAttenuation; } - - _FORCE_INLINE_ void set_spOv_gravityVec(Vector3 p_vec) { spOv_gravityVec = p_vec; } - _FORCE_INLINE_ const Vector3 &get_spOv_gravityVec() const { return spOv_gravityVec; } - - _FORCE_INLINE_ void set_spOv_gravityMag(real_t p_gravityMag) { spOv_gravityMag = p_gravityMag; } - _FORCE_INLINE_ real_t get_spOv_gravityMag() { return spOv_gravityMag; } - - _FORCE_INLINE_ void set_spOv_linearDump(real_t p_linearDump) { spOv_linearDump = p_linearDump; } - _FORCE_INLINE_ real_t get_spOv_linearDamp() { return spOv_linearDump; } - - _FORCE_INLINE_ void set_spOv_angularDump(real_t p_angularDump) { spOv_angularDump = p_angularDump; } - _FORCE_INLINE_ real_t get_spOv_angularDamp() { return spOv_angularDump; } - - _FORCE_INLINE_ void set_spOv_priority(int p_priority) { spOv_priority = p_priority; } - _FORCE_INLINE_ int get_spOv_priority() { return spOv_priority; } - - virtual void main_shape_changed(); - virtual void reload_body(); - virtual void set_space(SpaceBullet *p_space); - - virtual void dispatch_callbacks(); - void call_event(const OverlappingShapeData &p_overlapping_shape, PhysicsServer3D::AreaBodyStatus p_status); - - virtual void on_collision_filters_change(); - virtual void on_collision_checker_start() {} - virtual void on_collision_checker_end() { updated = false; } - - void mark_all_overlaps_dirty(); - void mark_object_overlaps_inside(CollisionObjectBullet *p_other_object); - void set_overlap(CollisionObjectBullet *p_other_object, uint32_t p_other_shape_id, uint32_t p_our_shape_id); - void mark_all_dirty_overlaps_as_exit(); - void remove_object_overlaps(CollisionObjectBullet *p_object); - void clear_overlaps(); - - void set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value); - Variant get_param(PhysicsServer3D::AreaParameter p_param) const; - - void set_event_callback(Type p_callbackObjectType, const Callable &p_callback); - bool has_event_callback(Type p_callbackObjectType); - - virtual void on_enter_area(AreaBullet *p_area); - virtual void on_exit_area(AreaBullet *p_area); -}; - -#endif // AREA_BULLET_H diff --git a/modules/bullet/btRayShape.cpp b/modules/bullet/btRayShape.cpp deleted file mode 100644 index 14bc7442a7..0000000000 --- a/modules/bullet/btRayShape.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/*************************************************************************/ -/* btRayShape.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "btRayShape.h" - -#include "core/math/math_funcs.h" - -#include <LinearMath/btAabbUtil2.h> - -btRayShape::btRayShape(btScalar length) : - btConvexInternalShape() { - m_shapeType = CUSTOM_CONVEX_SHAPE_TYPE; - setLength(length); -} - -btRayShape::~btRayShape() { -} - -void btRayShape::setLength(btScalar p_length) { - m_length = p_length; - reload_cache(); -} - -void btRayShape::setMargin(btScalar margin) { - btConvexInternalShape::setMargin(margin); - reload_cache(); -} - -void btRayShape::setSlipsOnSlope(bool p_slipsOnSlope) { - slipsOnSlope = p_slipsOnSlope; -} - -btVector3 btRayShape::localGetSupportingVertex(const btVector3 &vec) const { - return localGetSupportingVertexWithoutMargin(vec) + (m_shapeAxis * m_collisionMargin); -} - -btVector3 btRayShape::localGetSupportingVertexWithoutMargin(const btVector3 &vec) const { - if (vec.z() > 0) { - return m_shapeAxis * m_cacheScaledLength; - } else { - return btVector3(0, 0, 0); - } -} - -void btRayShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3 *vectors, btVector3 *supportVerticesOut, int numVectors) const { - for (int i = 0; i < numVectors; ++i) { - supportVerticesOut[i] = localGetSupportingVertexWithoutMargin(vectors[i]); - } -} - -void btRayShape::getAabb(const btTransform &t, btVector3 &aabbMin, btVector3 &aabbMax) const { - btVector3 localAabbMin(0, 0, 0); - btVector3 localAabbMax(m_shapeAxis * m_cacheScaledLength); - btTransformAabb(localAabbMin, localAabbMax, m_collisionMargin, t, aabbMin, aabbMax); -} - -void btRayShape::calculateLocalInertia(btScalar mass, btVector3 &inertia) const { - inertia.setZero(); -} - -int btRayShape::getNumPreferredPenetrationDirections() const { - return 0; -} - -void btRayShape::getPreferredPenetrationDirection(int index, btVector3 &penetrationVector) const { - penetrationVector.setZero(); -} - -void btRayShape::reload_cache() { - m_cacheScaledLength = m_length * m_localScaling[2]; - - m_cacheSupportPoint.setIdentity(); - m_cacheSupportPoint.setOrigin(m_shapeAxis * m_cacheScaledLength); -} diff --git a/modules/bullet/btRayShape.h b/modules/bullet/btRayShape.h deleted file mode 100644 index 90e4524d64..0000000000 --- a/modules/bullet/btRayShape.h +++ /dev/null @@ -1,91 +0,0 @@ -/*************************************************************************/ -/* btRayShape.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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. */ -/*************************************************************************/ - -/// IMPORTANT The class name and filename was created by following Bullet writing rules for an easy (eventually) porting to bullet -/// This shape is a custom shape that is not present to Bullet physics engine -#ifndef BTRAYSHAPE_H -#define BTRAYSHAPE_H - -#include <BulletCollision/CollisionShapes/btConvexInternalShape.h> - -/// Ray shape around z axis -ATTRIBUTE_ALIGNED16(class) -btRayShape : public btConvexInternalShape { - btScalar m_length = 0; - bool slipsOnSlope = false; - /// The default axis is the z - btVector3 m_shapeAxis = btVector3(0, 0, 1); - - btTransform m_cacheSupportPoint; - btScalar m_cacheScaledLength; - -public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - - btRayShape(btScalar length); - virtual ~btRayShape(); - - void setLength(btScalar p_length); - btScalar getLength() const { return m_length; } - - virtual void setMargin(btScalar margin); - - void setSlipsOnSlope(bool p_slipsOnSlope); - bool getSlipsOnSlope() const { return slipsOnSlope; } - - const btTransform &getSupportPoint() const { return m_cacheSupportPoint; } - const btScalar &getScaledLength() const { return m_cacheScaledLength; } - - virtual btVector3 localGetSupportingVertex(const btVector3 &vec) const; -#ifndef __SPU__ - virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3 &vec) const; -#endif //#ifndef __SPU__ - - virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3 *vectors, btVector3 *supportVerticesOut, int numVectors) const; - - ///getAabb returns the axis aligned bounding box in the coordinate frame of the given transform t. - virtual void getAabb(const btTransform &t, btVector3 &aabbMin, btVector3 &aabbMax) const; - -#ifndef __SPU__ - virtual void calculateLocalInertia(btScalar mass, btVector3 & inertia) const; - - virtual const char *getName() const { - return "RayZ"; - } -#endif //__SPU__ - - virtual int getNumPreferredPenetrationDirections() const; - virtual void getPreferredPenetrationDirection(int index, btVector3 &penetrationVector) const; - -private: - void reload_cache(); -}; - -#endif // BTRAYSHAPE_H diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp deleted file mode 100644 index 7e9e621032..0000000000 --- a/modules/bullet/bullet_physics_server.cpp +++ /dev/null @@ -1,1535 +0,0 @@ -/*************************************************************************/ -/* bullet_physics_server.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "bullet_physics_server.h" - -#include "bullet_utilities.h" -#include "cone_twist_joint_bullet.h" -#include "core/error/error_macros.h" -#include "core/object/class_db.h" -#include "core/string/ustring.h" -#include "generic_6dof_joint_bullet.h" -#include "hinge_joint_bullet.h" -#include "pin_joint_bullet.h" -#include "shape_bullet.h" -#include "slider_joint_bullet.h" - -#include <LinearMath/btVector3.h> - -#include <assert.h> - -#define CreateThenReturnRID(owner, ridData) \ - RID rid = owner.make_rid(ridData); \ - ridData->set_self(rid); \ - ridData->_set_physics_server(this); \ - return rid; - -// <--------------- Joint creation asserts -/// Assert the body is assigned to a space -#define JointAssertSpace(body, bIndex, ret) \ - if (!body->get_space()) { \ - ERR_PRINT("Before create a joint the Body" + String(bIndex) + " must be added to a space!"); \ - return ret; \ - } - -/// Assert the two bodies of joint are in the same space -#define JointAssertSameSpace(bodyA, bodyB, ret) \ - if (bodyA->get_space() != bodyB->get_space()) { \ - ERR_PRINT("In order to create a joint the Body_A and Body_B must be in the same space!"); \ - return RID(); \ - } - -#define AddJointToSpace(body, joint) \ - body->get_space()->add_constraint(joint, joint->is_disabled_collisions_between_bodies()); -// <--------------- Joint creation asserts - -void BulletPhysicsServer3D::_bind_methods() { - //ClassDB::bind_method(D_METHOD("DoTest"), &BulletPhysicsServer3D::DoTest); -} - -BulletPhysicsServer3D::BulletPhysicsServer3D() : - PhysicsServer3D() {} - -BulletPhysicsServer3D::~BulletPhysicsServer3D() {} - -RID BulletPhysicsServer3D::shape_create(ShapeType p_shape) { - ShapeBullet *shape = nullptr; - - switch (p_shape) { - case SHAPE_WORLD_BOUNDARY: { - shape = bulletnew(WorldBoundaryShapeBullet); - } break; - case SHAPE_SPHERE: { - shape = bulletnew(SphereShapeBullet); - } break; - case SHAPE_BOX: { - shape = bulletnew(BoxShapeBullet); - } break; - case SHAPE_CAPSULE: { - shape = bulletnew(CapsuleShapeBullet); - } break; - case SHAPE_CYLINDER: { - shape = bulletnew(CylinderShapeBullet); - } break; - case SHAPE_CONVEX_POLYGON: { - shape = bulletnew(ConvexPolygonShapeBullet); - } break; - case SHAPE_CONCAVE_POLYGON: { - shape = bulletnew(ConcavePolygonShapeBullet); - } break; - case SHAPE_HEIGHTMAP: { - shape = bulletnew(HeightMapShapeBullet); - } break; - case SHAPE_RAY: { - shape = bulletnew(RayShapeBullet); - } break; - case SHAPE_CUSTOM: - default: - ERR_FAIL_V(RID()); - break; - } - - CreateThenReturnRID(shape_owner, shape) -} - -void BulletPhysicsServer3D::shape_set_data(RID p_shape, const Variant &p_data) { - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND(!shape); - shape->set_data(p_data); -} - -void BulletPhysicsServer3D::shape_set_custom_solver_bias(RID p_shape, real_t p_bias) { - //WARN_PRINT("Bias not supported by Bullet physics engine"); -} - -PhysicsServer3D::ShapeType BulletPhysicsServer3D::shape_get_type(RID p_shape) const { - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND_V(!shape, PhysicsServer3D::SHAPE_CUSTOM); - return shape->get_type(); -} - -Variant BulletPhysicsServer3D::shape_get_data(RID p_shape) const { - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND_V(!shape, Variant()); - return shape->get_data(); -} - -void BulletPhysicsServer3D::shape_set_margin(RID p_shape, real_t p_margin) { - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND(!shape); - shape->set_margin(p_margin); -} - -real_t BulletPhysicsServer3D::shape_get_margin(RID p_shape) const { - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND_V(!shape, 0.0); - return shape->get_margin(); -} - -real_t BulletPhysicsServer3D::shape_get_custom_solver_bias(RID p_shape) const { - //WARN_PRINT("Bias not supported by Bullet physics engine"); - return 0.; -} - -RID BulletPhysicsServer3D::space_create() { - SpaceBullet *space = bulletnew(SpaceBullet); - CreateThenReturnRID(space_owner, space); -} - -void BulletPhysicsServer3D::space_set_active(RID p_space, bool p_active) { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND(!space); - - if (space_is_active(p_space) == p_active) { - return; - } - - if (p_active) { - ++active_spaces_count; - active_spaces.push_back(space); - } else { - --active_spaces_count; - active_spaces.erase(space); - } -} - -bool BulletPhysicsServer3D::space_is_active(RID p_space) const { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND_V(!space, false); - - return -1 != active_spaces.find(space); -} - -void BulletPhysicsServer3D::space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND(!space); - space->set_param(p_param, p_value); -} - -real_t BulletPhysicsServer3D::space_get_param(RID p_space, SpaceParameter p_param) const { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND_V(!space, 0); - return space->get_param(p_param); -} - -PhysicsDirectSpaceState3D *BulletPhysicsServer3D::space_get_direct_state(RID p_space) { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND_V(!space, nullptr); - - return space->get_direct_state(); -} - -void BulletPhysicsServer3D::space_set_debug_contacts(RID p_space, int p_max_contacts) { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND(!space); - - space->set_debug_contacts(p_max_contacts); -} - -Vector<Vector3> BulletPhysicsServer3D::space_get_contacts(RID p_space) const { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND_V(!space, Vector<Vector3>()); - - return space->get_debug_contacts(); -} - -int BulletPhysicsServer3D::space_get_contact_count(RID p_space) const { - SpaceBullet *space = space_owner.get_or_null(p_space); - ERR_FAIL_COND_V(!space, 0); - - return space->get_debug_contact_count(); -} - -RID BulletPhysicsServer3D::area_create() { - AreaBullet *area = bulletnew(AreaBullet); - area->set_collision_layer(1); - area->set_collision_mask(1); - CreateThenReturnRID(area_owner, area) -} - -void BulletPhysicsServer3D::area_set_space(RID p_area, RID p_space) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - SpaceBullet *space = nullptr; - if (p_space.is_valid()) { - space = space_owner.get_or_null(p_space); - ERR_FAIL_COND(!space); - } - area->set_space(space); -} - -RID BulletPhysicsServer3D::area_get_space(RID p_area) const { - AreaBullet *area = area_owner.get_or_null(p_area); - return area->get_space()->get_self(); -} - -void BulletPhysicsServer3D::area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - area->set_spOv_mode(p_mode); -} - -PhysicsServer3D::AreaSpaceOverrideMode BulletPhysicsServer3D::area_get_space_override_mode(RID p_area) const { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND_V(!area, PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED); - - return area->get_spOv_mode(); -} - -void BulletPhysicsServer3D::area_add_shape(RID p_area, RID p_shape, const Transform3D &p_transform, bool p_disabled) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND(!shape); - - area->add_shape(shape, p_transform, p_disabled); -} - -void BulletPhysicsServer3D::area_set_shape(RID p_area, int p_shape_idx, RID p_shape) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND(!shape); - - area->set_shape(p_shape_idx, shape); -} - -void BulletPhysicsServer3D::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform3D &p_transform) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - area->set_shape_transform(p_shape_idx, p_transform); -} - -int BulletPhysicsServer3D::area_get_shape_count(RID p_area) const { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND_V(!area, 0); - - return area->get_shape_count(); -} - -RID BulletPhysicsServer3D::area_get_shape(RID p_area, int p_shape_idx) const { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND_V(!area, RID()); - - return area->get_shape(p_shape_idx)->get_self(); -} - -Transform3D BulletPhysicsServer3D::area_get_shape_transform(RID p_area, int p_shape_idx) const { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND_V(!area, Transform3D()); - - return area->get_shape_transform(p_shape_idx); -} - -void BulletPhysicsServer3D::area_remove_shape(RID p_area, int p_shape_idx) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - return area->remove_shape_full(p_shape_idx); -} - -void BulletPhysicsServer3D::area_clear_shapes(RID p_area) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - for (int i = area->get_shape_count(); 0 < i; --i) { - area->remove_shape_full(0); - } -} - -void BulletPhysicsServer3D::area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - area->set_shape_disabled(p_shape_idx, p_disabled); -} - -void BulletPhysicsServer3D::area_attach_object_instance_id(RID p_area, ObjectID p_id) { - if (space_owner.owns(p_area)) { - return; - } - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - area->set_instance_id(p_id); -} - -ObjectID BulletPhysicsServer3D::area_get_object_instance_id(RID p_area) const { - if (space_owner.owns(p_area)) { - return ObjectID(); - } - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND_V(!area, ObjectID()); - return area->get_instance_id(); -} - -void BulletPhysicsServer3D::area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) { - if (space_owner.owns(p_area)) { - SpaceBullet *space = space_owner.get_or_null(p_area); - if (space) { - space->set_param(p_param, p_value); - } - } else { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - area->set_param(p_param, p_value); - } -} - -Variant BulletPhysicsServer3D::area_get_param(RID p_area, AreaParameter p_param) const { - if (space_owner.owns(p_area)) { - SpaceBullet *space = space_owner.get_or_null(p_area); - return space->get_param(p_param); - } else { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND_V(!area, Variant()); - - return area->get_param(p_param); - } -} - -void BulletPhysicsServer3D::area_set_transform(RID p_area, const Transform3D &p_transform) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - area->set_transform(p_transform); -} - -Transform3D BulletPhysicsServer3D::area_get_transform(RID p_area) const { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND_V(!area, Transform3D()); - return area->get_transform(); -} - -void BulletPhysicsServer3D::area_set_collision_mask(RID p_area, uint32_t p_mask) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - area->set_collision_mask(p_mask); -} - -void BulletPhysicsServer3D::area_set_collision_layer(RID p_area, uint32_t p_layer) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - area->set_collision_layer(p_layer); -} - -void BulletPhysicsServer3D::area_set_monitorable(RID p_area, bool p_monitorable) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - area->set_monitorable(p_monitorable); -} - -void BulletPhysicsServer3D::area_set_monitor_callback(RID p_area, const Callable &p_callback) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - area->set_event_callback(CollisionObjectBullet::TYPE_RIGID_BODY, p_callback.is_valid() ? p_callback : Callable()); -} - -void BulletPhysicsServer3D::area_set_area_monitor_callback(RID p_area, const Callable &p_callback) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - - area->set_event_callback(CollisionObjectBullet::TYPE_AREA, p_callback.is_valid() ? p_callback : Callable()); -} - -void BulletPhysicsServer3D::area_set_ray_pickable(RID p_area, bool p_enable) { - AreaBullet *area = area_owner.get_or_null(p_area); - ERR_FAIL_COND(!area); - area->set_ray_pickable(p_enable); -} - -RID BulletPhysicsServer3D::body_create(BodyMode p_mode, bool p_init_sleeping) { - RigidBodyBullet *body = bulletnew(RigidBodyBullet); - body->set_mode(p_mode); - body->set_collision_layer(1); - body->set_collision_mask(1); - if (p_init_sleeping) { - body->set_state(BODY_STATE_SLEEPING, p_init_sleeping); - } - CreateThenReturnRID(rigid_body_owner, body); -} - -void BulletPhysicsServer3D::body_set_space(RID p_body, RID p_space) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - SpaceBullet *space = nullptr; - - if (p_space.is_valid()) { - space = space_owner.get_or_null(p_space); - ERR_FAIL_COND(!space); - } - - if (body->get_space() == space) { - return; //pointless - } - - body->set_space(space); -} - -RID BulletPhysicsServer3D::body_get_space(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, RID()); - - SpaceBullet *space = body->get_space(); - if (!space) { - return RID(); - } - return space->get_self(); -} - -void BulletPhysicsServer3D::body_set_mode(RID p_body, PhysicsServer3D::BodyMode p_mode) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_mode(p_mode); -} - -PhysicsServer3D::BodyMode BulletPhysicsServer3D::body_get_mode(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, BODY_MODE_STATIC); - return body->get_mode(); -} - -void BulletPhysicsServer3D::body_add_shape(RID p_body, RID p_shape, const Transform3D &p_transform, bool p_disabled) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND(!shape); - - body->add_shape(shape, p_transform, p_disabled); -} - -void BulletPhysicsServer3D::body_set_shape(RID p_body, int p_shape_idx, RID p_shape) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - ShapeBullet *shape = shape_owner.get_or_null(p_shape); - ERR_FAIL_COND(!shape); - - body->set_shape(p_shape_idx, shape); -} - -void BulletPhysicsServer3D::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform3D &p_transform) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_shape_transform(p_shape_idx, p_transform); -} - -int BulletPhysicsServer3D::body_get_shape_count(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - return body->get_shape_count(); -} - -RID BulletPhysicsServer3D::body_get_shape(RID p_body, int p_shape_idx) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, RID()); - - ShapeBullet *shape = body->get_shape(p_shape_idx); - ERR_FAIL_COND_V(!shape, RID()); - - return shape->get_self(); -} - -Transform3D BulletPhysicsServer3D::body_get_shape_transform(RID p_body, int p_shape_idx) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, Transform3D()); - return body->get_shape_transform(p_shape_idx); -} - -void BulletPhysicsServer3D::body_set_shape_disabled(RID p_body, int p_shape_idx, bool p_disabled) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_shape_disabled(p_shape_idx, p_disabled); -} - -void BulletPhysicsServer3D::body_remove_shape(RID p_body, int p_shape_idx) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->remove_shape_full(p_shape_idx); -} - -void BulletPhysicsServer3D::body_clear_shapes(RID p_body) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->remove_all_shapes(); -} - -void BulletPhysicsServer3D::body_attach_object_instance_id(RID p_body, ObjectID p_id) { - CollisionObjectBullet *body = get_collision_object(p_body); - ERR_FAIL_COND(!body); - - body->set_instance_id(p_id); -} - -ObjectID BulletPhysicsServer3D::body_get_object_instance_id(RID p_body) const { - CollisionObjectBullet *body = get_collision_object(p_body); - ERR_FAIL_COND_V(!body, ObjectID()); - - return body->get_instance_id(); -} - -void BulletPhysicsServer3D::body_set_enable_continuous_collision_detection(RID p_body, bool p_enable) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_continuous_collision_detection(p_enable); -} - -bool BulletPhysicsServer3D::body_is_continuous_collision_detection_enabled(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, false); - - return body->is_continuous_collision_detection_enabled(); -} - -void BulletPhysicsServer3D::body_set_collision_layer(RID p_body, uint32_t p_layer) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_collision_layer(p_layer); -} - -uint32_t BulletPhysicsServer3D::body_get_collision_layer(RID p_body) const { - const RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - - return body->get_collision_layer(); -} - -void BulletPhysicsServer3D::body_set_collision_mask(RID p_body, uint32_t p_mask) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_collision_mask(p_mask); -} - -uint32_t BulletPhysicsServer3D::body_get_collision_mask(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - - return body->get_collision_mask(); -} - -void BulletPhysicsServer3D::body_set_user_flags(RID p_body, uint32_t p_flags) { - // This function is not currently supported -} - -uint32_t BulletPhysicsServer3D::body_get_user_flags(RID p_body) const { - // This function is not currently supported - return 0; -} - -void BulletPhysicsServer3D::body_set_param(RID p_body, BodyParameter p_param, real_t p_value) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_param(p_param, p_value); -} - -real_t BulletPhysicsServer3D::body_get_param(RID p_body, BodyParameter p_param) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - - return body->get_param(p_param); -} - -void BulletPhysicsServer3D::body_set_kinematic_safe_margin(RID p_body, real_t p_margin) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - if (body->get_kinematic_utilities()) { - body->get_kinematic_utilities()->setSafeMargin(p_margin); - } -} - -real_t BulletPhysicsServer3D::body_get_kinematic_safe_margin(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - - if (body->get_kinematic_utilities()) { - return body->get_kinematic_utilities()->safe_margin; - } - - return 0; -} - -void BulletPhysicsServer3D::body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_state(p_state, p_variant); -} - -Variant BulletPhysicsServer3D::body_get_state(RID p_body, BodyState p_state) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, Variant()); - - return body->get_state(p_state); -} - -void BulletPhysicsServer3D::body_set_applied_force(RID p_body, const Vector3 &p_force) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_applied_force(p_force); -} - -Vector3 BulletPhysicsServer3D::body_get_applied_force(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, Vector3()); - return body->get_applied_force(); -} - -void BulletPhysicsServer3D::body_set_applied_torque(RID p_body, const Vector3 &p_torque) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_applied_torque(p_torque); -} - -Vector3 BulletPhysicsServer3D::body_get_applied_torque(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, Vector3()); - - return body->get_applied_torque(); -} - -void BulletPhysicsServer3D::body_add_central_force(RID p_body, const Vector3 &p_force) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->apply_central_force(p_force); -} - -void BulletPhysicsServer3D::body_add_force(RID p_body, const Vector3 &p_force, const Vector3 &p_position) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->apply_force(p_force, p_position); -} - -void BulletPhysicsServer3D::body_add_torque(RID p_body, const Vector3 &p_torque) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->apply_torque(p_torque); -} - -void BulletPhysicsServer3D::body_apply_central_impulse(RID p_body, const Vector3 &p_impulse) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->apply_central_impulse(p_impulse); -} - -void BulletPhysicsServer3D::body_apply_impulse(RID p_body, const Vector3 &p_impulse, const Vector3 &p_position) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->apply_impulse(p_impulse, p_position); -} - -void BulletPhysicsServer3D::body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->apply_torque_impulse(p_impulse); -} - -void BulletPhysicsServer3D::body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - Vector3 v = body->get_linear_velocity(); - Vector3 axis = p_axis_velocity.normalized(); - v -= axis * axis.dot(v); - v += p_axis_velocity; - body->set_linear_velocity(v); -} - -void BulletPhysicsServer3D::body_set_axis_lock(RID p_body, BodyAxis p_axis, bool p_lock) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_axis_lock(p_axis, p_lock); -} - -bool BulletPhysicsServer3D::body_is_axis_locked(RID p_body, BodyAxis p_axis) const { - const RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - return body->is_axis_locked(p_axis); -} - -void BulletPhysicsServer3D::body_add_collision_exception(RID p_body, RID p_body_b) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - RigidBodyBullet *other_body = rigid_body_owner.get_or_null(p_body_b); - ERR_FAIL_COND(!other_body); - - body->add_collision_exception(other_body); -} - -void BulletPhysicsServer3D::body_remove_collision_exception(RID p_body, RID p_body_b) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - RigidBodyBullet *other_body = rigid_body_owner.get_or_null(p_body_b); - ERR_FAIL_COND(!other_body); - - body->remove_collision_exception(other_body); -} - -void BulletPhysicsServer3D::body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - for (int i = 0; i < body->get_exceptions().size(); i++) { - p_exceptions->push_back(body->get_exceptions()[i]); - } -} - -void BulletPhysicsServer3D::body_set_max_contacts_reported(RID p_body, int p_contacts) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_max_collisions_detection(p_contacts); -} - -int BulletPhysicsServer3D::body_get_max_contacts_reported(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - - return body->get_max_collisions_detection(); -} - -void BulletPhysicsServer3D::body_set_contacts_reported_depth_threshold(RID p_body, real_t p_threshold) { - // Not supported by bullet and even Godot -} - -real_t BulletPhysicsServer3D::body_get_contacts_reported_depth_threshold(RID p_body) const { - // Not supported by bullet and even Godot - return 0.; -} - -void BulletPhysicsServer3D::body_set_omit_force_integration(RID p_body, bool p_omit) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_omit_forces_integration(p_omit); -} - -bool BulletPhysicsServer3D::body_is_omitting_force_integration(RID p_body) const { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, false); - - return body->get_omit_forces_integration(); -} - -void BulletPhysicsServer3D::body_set_force_integration_callback(RID p_body, const Callable &p_callable, const Variant &p_udata) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_force_integration_callback(p_callable, p_udata); -} - -void BulletPhysicsServer3D::body_set_ray_pickable(RID p_body, bool p_enable) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_ray_pickable(p_enable); -} - -PhysicsDirectBodyState3D *BulletPhysicsServer3D::body_get_direct_state(RID p_body) { - if (!rigid_body_owner.owns(p_body)) { - return nullptr; - } - - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, nullptr); - - if (!body->get_space()) { - return nullptr; - } - - return BulletPhysicsDirectBodyState3D::get_singleton(body); -} - -bool BulletPhysicsServer3D::body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result, bool p_exclude_raycast_shapes, const Set<RID> &p_exclude) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, false); - ERR_FAIL_COND_V(!body->get_space(), false); - - return body->get_space()->test_body_motion(body, p_from, p_motion, p_infinite_inertia, r_result, p_exclude_raycast_shapes, p_exclude); -} - -int BulletPhysicsServer3D::body_test_ray_separation(RID p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, real_t p_margin) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - ERR_FAIL_COND_V(!body->get_space(), 0); - - return body->get_space()->test_ray_separation(body, p_transform, p_infinite_inertia, r_recover_motion, r_results, p_result_max, p_margin); -} - -RID BulletPhysicsServer3D::soft_body_create(bool p_init_sleeping) { - SoftBodyBullet *body = bulletnew(SoftBodyBullet); - body->set_collision_layer(1); - body->set_collision_mask(1); - if (p_init_sleeping) { - body->set_activation_state(false); - } - CreateThenReturnRID(soft_body_owner, body); -} - -void BulletPhysicsServer3D::soft_body_update_rendering_server(RID p_body, RenderingServerHandler *p_rendering_server_handler) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->update_rendering_server(p_rendering_server_handler); -} - -void BulletPhysicsServer3D::soft_body_set_space(RID p_body, RID p_space) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - SpaceBullet *space = nullptr; - - if (p_space.is_valid()) { - space = space_owner.get_or_null(p_space); - ERR_FAIL_COND(!space); - } - - if (body->get_space() == space) { - return; //pointless - } - - body->set_space(space); -} - -RID BulletPhysicsServer3D::soft_body_get_space(RID p_body) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, RID()); - - SpaceBullet *space = body->get_space(); - if (!space) { - return RID(); - } - return space->get_self(); -} - -void BulletPhysicsServer3D::soft_body_set_mesh(RID p_body, RID p_mesh) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_soft_mesh(p_mesh); -} - -AABB BulletPhysicsServer::soft_body_get_bounds(RID p_body) const { - SoftBodyBullet *body = soft_body_owner.get(p_body); - ERR_FAIL_COND_V(!body, AABB()); - - return body->get_bounds(); -} - -void BulletPhysicsServer3D::soft_body_set_collision_layer(RID p_body, uint32_t p_layer) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_collision_layer(p_layer); -} - -uint32_t BulletPhysicsServer3D::soft_body_get_collision_layer(RID p_body) const { - const SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - - return body->get_collision_layer(); -} - -void BulletPhysicsServer3D::soft_body_set_collision_mask(RID p_body, uint32_t p_mask) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_collision_mask(p_mask); -} - -uint32_t BulletPhysicsServer3D::soft_body_get_collision_mask(RID p_body) const { - const SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0); - - return body->get_collision_mask(); -} - -void BulletPhysicsServer3D::soft_body_add_collision_exception(RID p_body, RID p_body_b) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - CollisionObjectBullet *other_body = rigid_body_owner.get_or_null(p_body_b); - if (!other_body) { - other_body = soft_body_owner.get_or_null(p_body_b); - } - ERR_FAIL_COND(!other_body); - - body->add_collision_exception(other_body); -} - -void BulletPhysicsServer3D::soft_body_remove_collision_exception(RID p_body, RID p_body_b) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - CollisionObjectBullet *other_body = rigid_body_owner.get_or_null(p_body_b); - if (!other_body) { - other_body = soft_body_owner.get_or_null(p_body_b); - } - ERR_FAIL_COND(!other_body); - - body->remove_collision_exception(other_body); -} - -void BulletPhysicsServer3D::soft_body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - for (int i = 0; i < body->get_exceptions().size(); i++) { - p_exceptions->push_back(body->get_exceptions()[i]); - } -} - -void BulletPhysicsServer3D::soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) { - // FIXME: Must be implemented. - WARN_PRINT("soft_body_state is not implemented yet in Bullet backend."); -} - -Variant BulletPhysicsServer3D::soft_body_get_state(RID p_body, BodyState p_state) const { - // FIXME: Must be implemented. - WARN_PRINT("soft_body_state is not implemented yet in Bullet backend."); - return Variant(); -} - -void BulletPhysicsServer3D::soft_body_set_transform(RID p_body, const Transform3D &p_transform) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - - body->set_soft_transform(p_transform); -} - -void BulletPhysicsServer3D::soft_body_set_ray_pickable(RID p_body, bool p_enable) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_ray_pickable(p_enable); -} - -void BulletPhysicsServer3D::soft_body_set_simulation_precision(RID p_body, int p_simulation_precision) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_simulation_precision(p_simulation_precision); -} - -int BulletPhysicsServer3D::soft_body_get_simulation_precision(RID p_body) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0.f); - return body->get_simulation_precision(); -} - -void BulletPhysicsServer3D::soft_body_set_total_mass(RID p_body, real_t p_total_mass) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_total_mass(p_total_mass); -} - -real_t BulletPhysicsServer3D::soft_body_get_total_mass(RID p_body) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0.f); - return body->get_total_mass(); -} - -void BulletPhysicsServer3D::soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_linear_stiffness(p_stiffness); -} - -real_t BulletPhysicsServer3D::soft_body_get_linear_stiffness(RID p_body) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0.f); - return body->get_linear_stiffness(); -} - -void BulletPhysicsServer3D::soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_pressure_coefficient(p_pressure_coefficient); -} - -real_t BulletPhysicsServer3D::soft_body_get_pressure_coefficient(RID p_body) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0.f); - return body->get_pressure_coefficient(); -} - -void BulletPhysicsServer3D::soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_damping_coefficient(p_damping_coefficient); -} - -real_t BulletPhysicsServer3D::soft_body_get_damping_coefficient(RID p_body) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0.f); - return body->get_damping_coefficient(); -} - -void BulletPhysicsServer3D::soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_drag_coefficient(p_drag_coefficient); -} - -real_t BulletPhysicsServer3D::soft_body_get_drag_coefficient(RID p_body) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0.f); - return body->get_drag_coefficient(); -} - -void BulletPhysicsServer3D::soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_node_position(p_point_index, p_global_position); -} - -Vector3 BulletPhysicsServer3D::soft_body_get_point_global_position(RID p_body, int p_point_index) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, Vector3(0., 0., 0.)); - Vector3 pos; - body->get_node_position(p_point_index, pos); - return pos; -} - -void BulletPhysicsServer3D::soft_body_remove_all_pinned_points(RID p_body) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->reset_all_node_mass(); -} - -void BulletPhysicsServer3D::soft_body_pin_point(RID p_body, int p_point_index, bool p_pin) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND(!body); - body->set_node_mass(p_point_index, p_pin ? 0 : 1); -} - -bool BulletPhysicsServer3D::soft_body_is_point_pinned(RID p_body, int p_point_index) const { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_body); - ERR_FAIL_COND_V(!body, 0.f); - return body->get_node_mass(p_point_index); -} - -PhysicsServer3D::JointType BulletPhysicsServer3D::joint_get_type(RID p_joint) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, JOINT_PIN); - return joint->get_type(); -} - -void BulletPhysicsServer3D::joint_set_solver_priority(RID p_joint, int p_priority) { - // Joint priority not supported by bullet -} - -int BulletPhysicsServer3D::joint_get_solver_priority(RID p_joint) const { - // Joint priority not supported by bullet - return 0; -} - -void BulletPhysicsServer3D::joint_disable_collisions_between_bodies(RID p_joint, const bool p_disable) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - - joint->disable_collisions_between_bodies(p_disable); -} - -bool BulletPhysicsServer3D::joint_is_disabled_collisions_between_bodies(RID p_joint) const { - JointBullet *joint(joint_owner.get_or_null(p_joint)); - ERR_FAIL_COND_V(!joint, false); - - return joint->is_disabled_collisions_between_bodies(); -} - -RID BulletPhysicsServer3D::joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B) { - RigidBodyBullet *body_A = rigid_body_owner.get_or_null(p_body_A); - ERR_FAIL_COND_V(!body_A, RID()); - - JointAssertSpace(body_A, "A", RID()); - - RigidBodyBullet *body_B = nullptr; - if (p_body_B.is_valid()) { - body_B = rigid_body_owner.get_or_null(p_body_B); - JointAssertSpace(body_B, "B", RID()); - JointAssertSameSpace(body_A, body_B, RID()); - } - - ERR_FAIL_COND_V(body_A == body_B, RID()); - - JointBullet *joint = bulletnew(PinJointBullet(body_A, p_local_A, body_B, p_local_B)); - AddJointToSpace(body_A, joint); - - CreateThenReturnRID(joint_owner, joint); -} - -void BulletPhysicsServer3D::pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_PIN); - PinJointBullet *pin_joint = static_cast<PinJointBullet *>(joint); - pin_joint->set_param(p_param, p_value); -} - -real_t BulletPhysicsServer3D::pin_joint_get_param(RID p_joint, PinJointParam p_param) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, 0); - ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, 0); - PinJointBullet *pin_joint = static_cast<PinJointBullet *>(joint); - return pin_joint->get_param(p_param); -} - -void BulletPhysicsServer3D::pin_joint_set_local_a(RID p_joint, const Vector3 &p_A) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_PIN); - PinJointBullet *pin_joint = static_cast<PinJointBullet *>(joint); - pin_joint->setPivotInA(p_A); -} - -Vector3 BulletPhysicsServer3D::pin_joint_get_local_a(RID p_joint) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, Vector3()); - ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, Vector3()); - PinJointBullet *pin_joint = static_cast<PinJointBullet *>(joint); - return pin_joint->getPivotInA(); -} - -void BulletPhysicsServer3D::pin_joint_set_local_b(RID p_joint, const Vector3 &p_B) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_PIN); - PinJointBullet *pin_joint = static_cast<PinJointBullet *>(joint); - pin_joint->setPivotInB(p_B); -} - -Vector3 BulletPhysicsServer3D::pin_joint_get_local_b(RID p_joint) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, Vector3()); - ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, Vector3()); - PinJointBullet *pin_joint = static_cast<PinJointBullet *>(joint); - return pin_joint->getPivotInB(); -} - -RID BulletPhysicsServer3D::joint_create_hinge(RID p_body_A, const Transform3D &p_hinge_A, RID p_body_B, const Transform3D &p_hinge_B) { - RigidBodyBullet *body_A = rigid_body_owner.get_or_null(p_body_A); - ERR_FAIL_COND_V(!body_A, RID()); - JointAssertSpace(body_A, "A", RID()); - - RigidBodyBullet *body_B = nullptr; - if (p_body_B.is_valid()) { - body_B = rigid_body_owner.get_or_null(p_body_B); - JointAssertSpace(body_B, "B", RID()); - JointAssertSameSpace(body_A, body_B, RID()); - } - - ERR_FAIL_COND_V(body_A == body_B, RID()); - - JointBullet *joint = bulletnew(HingeJointBullet(body_A, body_B, p_hinge_A, p_hinge_B)); - AddJointToSpace(body_A, joint); - - CreateThenReturnRID(joint_owner, joint); -} - -RID BulletPhysicsServer3D::joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B) { - RigidBodyBullet *body_A = rigid_body_owner.get_or_null(p_body_A); - ERR_FAIL_COND_V(!body_A, RID()); - JointAssertSpace(body_A, "A", RID()); - - RigidBodyBullet *body_B = nullptr; - if (p_body_B.is_valid()) { - body_B = rigid_body_owner.get_or_null(p_body_B); - JointAssertSpace(body_B, "B", RID()); - JointAssertSameSpace(body_A, body_B, RID()); - } - - ERR_FAIL_COND_V(body_A == body_B, RID()); - - JointBullet *joint = bulletnew(HingeJointBullet(body_A, body_B, p_pivot_A, p_pivot_B, p_axis_A, p_axis_B)); - AddJointToSpace(body_A, joint); - - CreateThenReturnRID(joint_owner, joint); -} - -void BulletPhysicsServer3D::hinge_joint_set_param(RID p_joint, HingeJointParam p_param, real_t p_value) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_HINGE); - HingeJointBullet *hinge_joint = static_cast<HingeJointBullet *>(joint); - hinge_joint->set_param(p_param, p_value); -} - -real_t BulletPhysicsServer3D::hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, 0); - ERR_FAIL_COND_V(joint->get_type() != JOINT_HINGE, 0); - HingeJointBullet *hinge_joint = static_cast<HingeJointBullet *>(joint); - return hinge_joint->get_param(p_param); -} - -void BulletPhysicsServer3D::hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_HINGE); - HingeJointBullet *hinge_joint = static_cast<HingeJointBullet *>(joint); - hinge_joint->set_flag(p_flag, p_value); -} - -bool BulletPhysicsServer3D::hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, false); - ERR_FAIL_COND_V(joint->get_type() != JOINT_HINGE, false); - HingeJointBullet *hinge_joint = static_cast<HingeJointBullet *>(joint); - return hinge_joint->get_flag(p_flag); -} - -RID BulletPhysicsServer3D::joint_create_slider(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) { - RigidBodyBullet *body_A = rigid_body_owner.get_or_null(p_body_A); - ERR_FAIL_COND_V(!body_A, RID()); - JointAssertSpace(body_A, "A", RID()); - - RigidBodyBullet *body_B = nullptr; - if (p_body_B.is_valid()) { - body_B = rigid_body_owner.get_or_null(p_body_B); - JointAssertSpace(body_B, "B", RID()); - JointAssertSameSpace(body_A, body_B, RID()); - } - - ERR_FAIL_COND_V(body_A == body_B, RID()); - - JointBullet *joint = bulletnew(SliderJointBullet(body_A, body_B, p_local_frame_A, p_local_frame_B)); - AddJointToSpace(body_A, joint); - - CreateThenReturnRID(joint_owner, joint); -} - -void BulletPhysicsServer3D::slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_SLIDER); - SliderJointBullet *slider_joint = static_cast<SliderJointBullet *>(joint); - slider_joint->set_param(p_param, p_value); -} - -real_t BulletPhysicsServer3D::slider_joint_get_param(RID p_joint, SliderJointParam p_param) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, 0); - ERR_FAIL_COND_V(joint->get_type() != JOINT_SLIDER, 0); - SliderJointBullet *slider_joint = static_cast<SliderJointBullet *>(joint); - return slider_joint->get_param(p_param); -} - -RID BulletPhysicsServer3D::joint_create_cone_twist(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) { - RigidBodyBullet *body_A = rigid_body_owner.get_or_null(p_body_A); - ERR_FAIL_COND_V(!body_A, RID()); - JointAssertSpace(body_A, "A", RID()); - - RigidBodyBullet *body_B = nullptr; - if (p_body_B.is_valid()) { - body_B = rigid_body_owner.get_or_null(p_body_B); - JointAssertSpace(body_B, "B", RID()); - JointAssertSameSpace(body_A, body_B, RID()); - } - - JointBullet *joint = bulletnew(ConeTwistJointBullet(body_A, body_B, p_local_frame_A, p_local_frame_B)); - AddJointToSpace(body_A, joint); - - CreateThenReturnRID(joint_owner, joint); -} - -void BulletPhysicsServer3D::cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, real_t p_value) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_CONE_TWIST); - ConeTwistJointBullet *coneTwist_joint = static_cast<ConeTwistJointBullet *>(joint); - coneTwist_joint->set_param(p_param, p_value); -} - -real_t BulletPhysicsServer3D::cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, 0.); - ERR_FAIL_COND_V(joint->get_type() != JOINT_CONE_TWIST, 0.); - ConeTwistJointBullet *coneTwist_joint = static_cast<ConeTwistJointBullet *>(joint); - return coneTwist_joint->get_param(p_param); -} - -RID BulletPhysicsServer3D::joint_create_generic_6dof(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) { - RigidBodyBullet *body_A = rigid_body_owner.get_or_null(p_body_A); - ERR_FAIL_COND_V(!body_A, RID()); - JointAssertSpace(body_A, "A", RID()); - - RigidBodyBullet *body_B = nullptr; - if (p_body_B.is_valid()) { - body_B = rigid_body_owner.get_or_null(p_body_B); - JointAssertSpace(body_B, "B", RID()); - JointAssertSameSpace(body_A, body_B, RID()); - } - - ERR_FAIL_COND_V(body_A == body_B, RID()); - - JointBullet *joint = bulletnew(Generic6DOFJointBullet(body_A, body_B, p_local_frame_A, p_local_frame_B)); - AddJointToSpace(body_A, joint); - - CreateThenReturnRID(joint_owner, joint); -} - -void BulletPhysicsServer3D::generic_6dof_joint_set_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param, real_t p_value) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_6DOF); - Generic6DOFJointBullet *generic_6dof_joint = static_cast<Generic6DOFJointBullet *>(joint); - generic_6dof_joint->set_param(p_axis, p_param, p_value); -} - -real_t BulletPhysicsServer3D::generic_6dof_joint_get_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, 0); - ERR_FAIL_COND_V(joint->get_type() != JOINT_6DOF, 0); - Generic6DOFJointBullet *generic_6dof_joint = static_cast<Generic6DOFJointBullet *>(joint); - return generic_6dof_joint->get_param(p_axis, p_param); -} - -void BulletPhysicsServer3D::generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag, bool p_enable) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type() != JOINT_6DOF); - Generic6DOFJointBullet *generic_6dof_joint = static_cast<Generic6DOFJointBullet *>(joint); - generic_6dof_joint->set_flag(p_axis, p_flag, p_enable); -} - -bool BulletPhysicsServer3D::generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag) { - JointBullet *joint = joint_owner.get_or_null(p_joint); - ERR_FAIL_COND_V(!joint, false); - ERR_FAIL_COND_V(joint->get_type() != JOINT_6DOF, false); - Generic6DOFJointBullet *generic_6dof_joint = static_cast<Generic6DOFJointBullet *>(joint); - return generic_6dof_joint->get_flag(p_axis, p_flag); -} - -void BulletPhysicsServer3D::free(RID p_rid) { - if (shape_owner.owns(p_rid)) { - ShapeBullet *shape = shape_owner.get_or_null(p_rid); - - // Notify the shape is configured - for (const KeyValue<ShapeOwnerBullet *, int> &element : shape->get_owners()) { - static_cast<ShapeOwnerBullet *>(element.key)->remove_shape_full(shape); - } - - shape_owner.free(p_rid); - bulletdelete(shape); - } else if (rigid_body_owner.owns(p_rid)) { - RigidBodyBullet *body = rigid_body_owner.get_or_null(p_rid); - - body->set_space(nullptr); - - body->remove_all_shapes(true, true); - - rigid_body_owner.free(p_rid); - bulletdelete(body); - - } else if (soft_body_owner.owns(p_rid)) { - SoftBodyBullet *body = soft_body_owner.get_or_null(p_rid); - - body->set_space(nullptr); - - soft_body_owner.free(p_rid); - bulletdelete(body); - - } else if (area_owner.owns(p_rid)) { - AreaBullet *area = area_owner.get_or_null(p_rid); - - area->set_space(nullptr); - - area->remove_all_shapes(true, true); - - area_owner.free(p_rid); - bulletdelete(area); - - } else if (joint_owner.owns(p_rid)) { - JointBullet *joint = joint_owner.get_or_null(p_rid); - joint->destroy_internal_constraint(); - joint_owner.free(p_rid); - bulletdelete(joint); - - } else if (space_owner.owns(p_rid)) { - SpaceBullet *space = space_owner.get_or_null(p_rid); - - space->remove_all_collision_objects(); - - space_set_active(p_rid, false); - space_owner.free(p_rid); - bulletdelete(space); - } else { - ERR_FAIL_MSG("Invalid ID."); - } -} - -void BulletPhysicsServer3D::init() { - BulletPhysicsDirectBodyState3D::initSingleton(); -} - -void BulletPhysicsServer3D::step(real_t p_deltaTime) { - if (!active) { - return; - } - - BulletPhysicsDirectBodyState3D::singleton_setDeltaTime(p_deltaTime); - - for (int i = 0; i < active_spaces_count; ++i) { - active_spaces[i]->step(p_deltaTime); - } -} - -void BulletPhysicsServer3D::flush_queries() { - if (!active) { - return; - } - - for (int i = 0; i < active_spaces_count; ++i) { - active_spaces[i]->flush_queries(); - } -} - -void BulletPhysicsServer3D::finish() { - BulletPhysicsDirectBodyState3D::destroySingleton(); -} - -int BulletPhysicsServer3D::get_process_info(ProcessInfo p_info) { - return 0; -} - -SpaceBullet *BulletPhysicsServer3D::get_space(RID p_rid) const { - ERR_FAIL_COND_V_MSG(space_owner.owns(p_rid) == false, nullptr, "The RID is not valid."); - return space_owner.get_or_null(p_rid); -} - -ShapeBullet *BulletPhysicsServer3D::get_shape(RID p_rid) const { - ERR_FAIL_COND_V_MSG(shape_owner.owns(p_rid) == false, nullptr, "The RID is not valid."); - return shape_owner.get_or_null(p_rid); -} - -CollisionObjectBullet *BulletPhysicsServer3D::get_collision_object(RID p_object) const { - if (rigid_body_owner.owns(p_object)) { - return rigid_body_owner.get_or_null(p_object); - } - if (area_owner.owns(p_object)) { - return area_owner.get_or_null(p_object); - } - if (soft_body_owner.owns(p_object)) { - return soft_body_owner.get_or_null(p_object); - } - ERR_FAIL_V_MSG(nullptr, "The RID is no valid."); -} - -RigidCollisionObjectBullet *BulletPhysicsServer3D::get_rigid_collision_object(RID p_object) const { - if (rigid_body_owner.owns(p_object)) { - return rigid_body_owner.get_or_null(p_object); - } - if (area_owner.owns(p_object)) { - return area_owner.get_or_null(p_object); - } - ERR_FAIL_V_MSG(nullptr, "The RID is no valid."); -} - -JointBullet *BulletPhysicsServer3D::get_joint(RID p_rid) const { - ERR_FAIL_COND_V_MSG(joint_owner.owns(p_rid) == false, nullptr, "The RID is not valid."); - return joint_owner.get_or_null(p_rid); -} diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h deleted file mode 100644 index 06a6f62bcd..0000000000 --- a/modules/bullet/bullet_physics_server.h +++ /dev/null @@ -1,394 +0,0 @@ -/*************************************************************************/ -/* bullet_physics_server.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 BULLET_PHYSICS_SERVER_H -#define BULLET_PHYSICS_SERVER_H - -#include "area_bullet.h" -#include "core/templates/rid.h" -#include "core/templates/rid_owner.h" -#include "joint_bullet.h" -#include "rigid_body_bullet.h" -#include "servers/physics_server_3d.h" -#include "shape_bullet.h" -#include "soft_body_bullet.h" -#include "space_bullet.h" - -class BulletPhysicsServer3D : public PhysicsServer3D { - GDCLASS(BulletPhysicsServer3D, PhysicsServer3D); - - friend class BulletPhysicsDirectSpaceState; - - bool active = true; - char active_spaces_count = 0; - Vector<SpaceBullet *> active_spaces; - - mutable RID_PtrOwner<SpaceBullet> space_owner; - mutable RID_PtrOwner<ShapeBullet> shape_owner; - mutable RID_PtrOwner<AreaBullet> area_owner; - mutable RID_PtrOwner<RigidBodyBullet> rigid_body_owner; - mutable RID_PtrOwner<SoftBodyBullet> soft_body_owner; - mutable RID_PtrOwner<JointBullet> joint_owner; - -protected: - static void _bind_methods(); - -public: - BulletPhysicsServer3D(); - ~BulletPhysicsServer3D(); - - _FORCE_INLINE_ RID_PtrOwner<SpaceBullet> *get_space_owner() { - return &space_owner; - } - _FORCE_INLINE_ RID_PtrOwner<ShapeBullet> *get_shape_owner() { - return &shape_owner; - } - _FORCE_INLINE_ RID_PtrOwner<AreaBullet> *get_area_owner() { - return &area_owner; - } - _FORCE_INLINE_ RID_PtrOwner<RigidBodyBullet> *get_rigid_body_owner() { - return &rigid_body_owner; - } - _FORCE_INLINE_ RID_PtrOwner<SoftBodyBullet> *get_soft_body_owner() { - return &soft_body_owner; - } - _FORCE_INLINE_ RID_PtrOwner<JointBullet> *get_joint_owner() { - return &joint_owner; - } - - /* SHAPE API */ - virtual RID shape_create(ShapeType p_shape) override; - virtual void shape_set_data(RID p_shape, const Variant &p_data) override; - virtual ShapeType shape_get_type(RID p_shape) const override; - virtual Variant shape_get_data(RID p_shape) const override; - - virtual void shape_set_margin(RID p_shape, real_t p_margin) override; - virtual real_t shape_get_margin(RID p_shape) const override; - - /// Not supported - virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias) override; - /// Not supported - virtual real_t shape_get_custom_solver_bias(RID p_shape) const override; - - /* SPACE API */ - - virtual RID space_create() override; - virtual void space_set_active(RID p_space, bool p_active) override; - virtual bool space_is_active(RID p_space) const override; - - /// Not supported - virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) override; - /// Not supported - virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const override; - - virtual PhysicsDirectSpaceState3D *space_get_direct_state(RID p_space) override; - - virtual void space_set_debug_contacts(RID p_space, int p_max_contacts) override; - virtual Vector<Vector3> space_get_contacts(RID p_space) const override; - virtual int space_get_contact_count(RID p_space) const override; - - /* AREA API */ - - /// Bullet Physics Engine not support "Area", this must be handled by the game developer in another way. - /// Since godot Physics use the concept of area even to define the main world, the API area_set_param is used to set initial physics world information. - /// The API area_set_param is a bit hacky, and allow Godot to set some parameters on Bullet's world, a different use print a warning to console. - /// All other APIs returns a warning message if used - - virtual RID area_create() override; - - virtual void area_set_space(RID p_area, RID p_space) override; - - virtual RID area_get_space(RID p_area) const override; - - virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) override; - virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const override; - - virtual void area_add_shape(RID p_area, RID p_shape, const Transform3D &p_transform = Transform3D(), bool p_disabled = false) override; - virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape) override; - virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform3D &p_transform) override; - virtual int area_get_shape_count(RID p_area) const override; - virtual RID area_get_shape(RID p_area, int p_shape_idx) const override; - virtual Transform3D area_get_shape_transform(RID p_area, int p_shape_idx) const override; - virtual void area_remove_shape(RID p_area, int p_shape_idx) override; - virtual void area_clear_shapes(RID p_area) override; - virtual void area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled) override; - virtual void area_attach_object_instance_id(RID p_area, ObjectID p_id) override; - virtual ObjectID area_get_object_instance_id(RID p_area) const override; - - /// If you pass as p_area the SpaceBullet you can set some parameters as specified below - /// AREA_PARAM_GRAVITY - /// AREA_PARAM_GRAVITY_VECTOR - /// Otherwise you can set area parameters - virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) override; - virtual Variant area_get_param(RID p_area, AreaParameter p_param) const override; - - virtual void area_set_transform(RID p_area, const Transform3D &p_transform) override; - virtual Transform3D area_get_transform(RID p_area) const override; - - virtual void area_set_collision_mask(RID p_area, uint32_t p_mask) override; - virtual void area_set_collision_layer(RID p_area, uint32_t p_layer) override; - - virtual void area_set_monitorable(RID p_area, bool p_monitorable) override; - virtual void area_set_monitor_callback(RID p_area, const Callable &p_callback) override; - virtual void area_set_area_monitor_callback(RID p_area, const Callable &p_callback) override; - virtual void area_set_ray_pickable(RID p_area, bool p_enable) override; - - /* RIGID BODY API */ - - virtual RID body_create(BodyMode p_mode = BODY_MODE_DYNAMIC, bool p_init_sleeping = false) override; - - virtual void body_set_space(RID p_body, RID p_space) override; - virtual RID body_get_space(RID p_body) const override; - - virtual void body_set_mode(RID p_body, BodyMode p_mode) override; - virtual BodyMode body_get_mode(RID p_body) const override; - - virtual void body_add_shape(RID p_body, RID p_shape, const Transform3D &p_transform = Transform3D(), bool p_disabled = false) override; - // Not supported, Please remove and add new shape - virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape) override; - virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform3D &p_transform) override; - - virtual int body_get_shape_count(RID p_body) const override; - virtual RID body_get_shape(RID p_body, int p_shape_idx) const override; - virtual Transform3D body_get_shape_transform(RID p_body, int p_shape_idx) const override; - - virtual void body_set_shape_disabled(RID p_body, int p_shape_idx, bool p_disabled) override; - - virtual void body_remove_shape(RID p_body, int p_shape_idx) override; - virtual void body_clear_shapes(RID p_body) override; - - // Used for Rigid and Soft Bodies - virtual void body_attach_object_instance_id(RID p_body, ObjectID p_id) override; - virtual ObjectID body_get_object_instance_id(RID p_body) const override; - - virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable) override; - virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const override; - - virtual void body_set_collision_layer(RID p_body, uint32_t p_layer) override; - virtual uint32_t body_get_collision_layer(RID p_body) const override; - - virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) override; - virtual uint32_t body_get_collision_mask(RID p_body) const override; - - /// This is not supported by physics server - virtual void body_set_user_flags(RID p_body, uint32_t p_flags) override; - /// This is not supported by physics server - virtual uint32_t body_get_user_flags(RID p_body) const override; - - virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value) override; - virtual real_t body_get_param(RID p_body, BodyParameter p_param) const override; - - virtual void body_set_kinematic_safe_margin(RID p_body, real_t p_margin) override; - virtual real_t body_get_kinematic_safe_margin(RID p_body) const override; - - virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) override; - virtual Variant body_get_state(RID p_body, BodyState p_state) const override; - - virtual void body_set_applied_force(RID p_body, const Vector3 &p_force) override; - virtual Vector3 body_get_applied_force(RID p_body) const override; - - virtual void body_set_applied_torque(RID p_body, const Vector3 &p_torque) override; - virtual Vector3 body_get_applied_torque(RID p_body) const override; - - virtual void body_add_central_force(RID p_body, const Vector3 &p_force) override; - virtual void body_add_force(RID p_body, const Vector3 &p_force, const Vector3 &p_position = Vector3()) override; - virtual void body_add_torque(RID p_body, const Vector3 &p_torque) override; - - virtual void body_apply_central_impulse(RID p_body, const Vector3 &p_impulse) override; - virtual void body_apply_impulse(RID p_body, const Vector3 &p_impulse, const Vector3 &p_position = Vector3()) override; - virtual void body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) override; - virtual void body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity) override; - - virtual void body_set_axis_lock(RID p_body, BodyAxis p_axis, bool p_lock) override; - virtual bool body_is_axis_locked(RID p_body, BodyAxis p_axis) const override; - - virtual void body_add_collision_exception(RID p_body, RID p_body_b) override; - virtual void body_remove_collision_exception(RID p_body, RID p_body_b) override; - virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) override; - - virtual void body_set_max_contacts_reported(RID p_body, int p_contacts) override; - virtual int body_get_max_contacts_reported(RID p_body) const override; - - virtual void body_set_contacts_reported_depth_threshold(RID p_body, real_t p_threshold) override; - virtual real_t body_get_contacts_reported_depth_threshold(RID p_body) const override; - - virtual void body_set_omit_force_integration(RID p_body, bool p_omit) override; - virtual bool body_is_omitting_force_integration(RID p_body) const override; - - virtual void body_set_force_integration_callback(RID p_body, const Callable &p_callable, const Variant &p_udata = Variant()) override; - - virtual void body_set_ray_pickable(RID p_body, bool p_enable) override; - - // this function only works on physics process, errors and returns null otherwise - virtual PhysicsDirectBodyState3D *body_get_direct_state(RID p_body) override; - - virtual bool body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = nullptr, bool p_exclude_raycast_shapes = true, const Set<RID> &p_exclude = Set<RID>()) override; - virtual int body_test_ray_separation(RID p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, real_t p_margin = 0.001) override; - - /* SOFT BODY API */ - - virtual RID soft_body_create(bool p_init_sleeping = false) override; - - virtual void soft_body_update_rendering_server(RID p_body, RenderingServerHandler *p_rendering_server_handler) override; - - virtual void soft_body_set_space(RID p_body, RID p_space) override; - virtual RID soft_body_get_space(RID p_body) const override; - - virtual void soft_body_set_mesh(RID p_body, RID p_mesh) override; - - virtual AABB soft_body_get_bounds(RID p_body) const override; - - virtual void soft_body_set_collision_layer(RID p_body, uint32_t p_layer) override; - virtual uint32_t soft_body_get_collision_layer(RID p_body) const override; - - virtual void soft_body_set_collision_mask(RID p_body, uint32_t p_mask) override; - virtual uint32_t soft_body_get_collision_mask(RID p_body) const override; - - virtual void soft_body_add_collision_exception(RID p_body, RID p_body_b) override; - virtual void soft_body_remove_collision_exception(RID p_body, RID p_body_b) override; - virtual void soft_body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) override; - - virtual void soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) override; - virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const override; - - /// Special function. This function has bad performance - virtual void soft_body_set_transform(RID p_body, const Transform3D &p_transform) override; - - virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable) override; - - virtual void soft_body_set_simulation_precision(RID p_body, int p_simulation_precision) override; - virtual int soft_body_get_simulation_precision(RID p_body) const override; - - virtual void soft_body_set_total_mass(RID p_body, real_t p_total_mass) override; - virtual real_t soft_body_get_total_mass(RID p_body) const override; - - virtual void soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness) override; - virtual real_t soft_body_get_linear_stiffness(RID p_body) const override; - - virtual void soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient) override; - virtual real_t soft_body_get_pressure_coefficient(RID p_body) const override; - - virtual void soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient) override; - virtual real_t soft_body_get_damping_coefficient(RID p_body) const override; - - virtual void soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient) override; - virtual real_t soft_body_get_drag_coefficient(RID p_body) const override; - - virtual void soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position) override; - virtual Vector3 soft_body_get_point_global_position(RID p_body, int p_point_index) const override; - - virtual void soft_body_remove_all_pinned_points(RID p_body) override; - virtual void soft_body_pin_point(RID p_body, int p_point_index, bool p_pin) override; - virtual bool soft_body_is_point_pinned(RID p_body, int p_point_index) const override; - - /* JOINT API */ - - virtual JointType joint_get_type(RID p_joint) const override; - - virtual void joint_set_solver_priority(RID p_joint, int p_priority) override; - virtual int joint_get_solver_priority(RID p_joint) const override; - - virtual void joint_disable_collisions_between_bodies(RID p_joint, const bool p_disable) override; - virtual bool joint_is_disabled_collisions_between_bodies(RID p_joint) const override; - - virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B) override; - - virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) override; - virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const override; - - virtual void pin_joint_set_local_a(RID p_joint, const Vector3 &p_A) override; - virtual Vector3 pin_joint_get_local_a(RID p_joint) const override; - - virtual void pin_joint_set_local_b(RID p_joint, const Vector3 &p_B) override; - virtual Vector3 pin_joint_get_local_b(RID p_joint) const override; - - virtual RID joint_create_hinge(RID p_body_A, const Transform3D &p_hinge_A, RID p_body_B, const Transform3D &p_hinge_B) override; - virtual RID joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B) override; - - virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, real_t p_value) override; - virtual real_t hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const override; - - virtual void hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value) override; - virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const override; - - /// Reference frame is A - virtual RID joint_create_slider(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) override; - - virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value) override; - virtual real_t slider_joint_get_param(RID p_joint, SliderJointParam p_param) const override; - - /// Reference frame is A - virtual RID joint_create_cone_twist(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) override; - - virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, real_t p_value) override; - virtual real_t cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const override; - - /// Reference frame is A - virtual RID joint_create_generic_6dof(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) override; - - virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param, real_t p_value) override; - virtual real_t generic_6dof_joint_get_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param) override; - - virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag, bool p_enable) override; - virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag) override; - - /* MISC */ - - virtual void free(RID p_rid) override; - - virtual void set_active(bool p_active) override { - active = p_active; - } - - static bool singleton_isActive() { - return static_cast<BulletPhysicsServer3D *>(get_singleton())->active; - } - - bool isActive() { - return active; - } - - virtual void init() override; - virtual void step(real_t p_deltaTime) override; - virtual void flush_queries() override; - virtual void finish() override; - - virtual bool is_flushing_queries() const override { return false; } - - virtual int get_process_info(ProcessInfo p_info) override; - - SpaceBullet *get_space(RID p_rid) const; - ShapeBullet *get_shape(RID p_rid) const; - CollisionObjectBullet *get_collision_object(RID p_object) const; - RigidCollisionObjectBullet *get_rigid_collision_object(RID p_object) const; - JointBullet *get_joint(RID p_rid) const; -}; - -#endif // BULLET_PHYSICS_SERVER_H diff --git a/modules/bullet/bullet_types_converter.cpp b/modules/bullet/bullet_types_converter.cpp deleted file mode 100644 index a0698683e8..0000000000 --- a/modules/bullet/bullet_types_converter.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/*************************************************************************/ -/* bullet_types_converter.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "bullet_types_converter.h" - -// ++ BULLET to GODOT ++++++++++ -void B_TO_G(btVector3 const &inVal, Vector3 &outVal) { - outVal[0] = inVal[0]; - outVal[1] = inVal[1]; - outVal[2] = inVal[2]; -} - -void INVERT_B_TO_G(btVector3 const &inVal, Vector3 &outVal) { - outVal[0] = inVal[0] != 0. ? 1. / inVal[0] : 0.; - outVal[1] = inVal[1] != 0. ? 1. / inVal[1] : 0.; - outVal[2] = inVal[2] != 0. ? 1. / inVal[2] : 0.; -} - -void B_TO_G(btMatrix3x3 const &inVal, Basis &outVal) { - B_TO_G(inVal[0], outVal[0]); - B_TO_G(inVal[1], outVal[1]); - B_TO_G(inVal[2], outVal[2]); -} - -void INVERT_B_TO_G(btMatrix3x3 const &inVal, Basis &outVal) { - INVERT_B_TO_G(inVal[0], outVal[0]); - INVERT_B_TO_G(inVal[1], outVal[1]); - INVERT_B_TO_G(inVal[2], outVal[2]); -} - -void B_TO_G(btTransform const &inVal, Transform3D &outVal) { - B_TO_G(inVal.getBasis(), outVal.basis); - B_TO_G(inVal.getOrigin(), outVal.origin); -} - -// ++ GODOT to BULLET ++++++++++ -void G_TO_B(Vector3 const &inVal, btVector3 &outVal) { - outVal[0] = inVal[0]; - outVal[1] = inVal[1]; - outVal[2] = inVal[2]; -} - -void INVERT_G_TO_B(Vector3 const &inVal, btVector3 &outVal) { - outVal[0] = inVal[0] != 0. ? 1. / inVal[0] : 0.; - outVal[1] = inVal[1] != 0. ? 1. / inVal[1] : 0.; - outVal[2] = inVal[2] != 0. ? 1. / inVal[2] : 0.; -} - -void G_TO_B(Basis const &inVal, btMatrix3x3 &outVal) { - G_TO_B(inVal[0], outVal[0]); - G_TO_B(inVal[1], outVal[1]); - G_TO_B(inVal[2], outVal[2]); -} - -void INVERT_G_TO_B(Basis const &inVal, btMatrix3x3 &outVal) { - INVERT_G_TO_B(inVal[0], outVal[0]); - INVERT_G_TO_B(inVal[1], outVal[1]); - INVERT_G_TO_B(inVal[2], outVal[2]); -} - -void G_TO_B(Transform3D const &inVal, btTransform &outVal) { - G_TO_B(inVal.basis, outVal.getBasis()); - G_TO_B(inVal.origin, outVal.getOrigin()); -} - -void UNSCALE_BT_BASIS(btTransform &scaledBasis) { - btMatrix3x3 &basis(scaledBasis.getBasis()); - btVector3 column0 = basis.getColumn(0); - btVector3 column1 = basis.getColumn(1); - btVector3 column2 = basis.getColumn(2); - - // Check for zero scaling. - if (column0.fuzzyZero()) { - if (column1.fuzzyZero()) { - if (column2.fuzzyZero()) { - // All dimensions are fuzzy zero. Create a default basis. - column0 = btVector3(1, 0, 0); - column1 = btVector3(0, 1, 0); - column2 = btVector3(0, 0, 1); - } else { // Column 2 scale not fuzzy zero. - // Create two vectors orthogonal to row 2. - // Ensure that a default basis is created if row 2 = <0, 0, 1> - column1 = btVector3(0, column2[2], -column2[1]); - column0 = column1.cross(column2); - } - } else { // Column 1 scale not fuzzy zero. - if (column2.fuzzyZero()) { - // Create two vectors orthogonal to column 1. - // Ensure that a default basis is created if column 1 = <0, 1, 0> - column0 = btVector3(column1[1], -column1[0], 0); - column2 = column0.cross(column1); - } else { // Column 1 and column 2 scales not fuzzy zero. - // Create column 0 orthogonal to column 1 and column 2. - column0 = column1.cross(column2); - } - } - } else { // Column 0 scale not fuzzy zero. - if (column1.fuzzyZero()) { - if (column2.fuzzyZero()) { - // Create two vectors orthogonal to column 0. - // Ensure that a default basis is created if column 0 = <1, 0, 0> - column2 = btVector3(-column0[2], 0, column0[0]); - column1 = column2.cross(column0); - } else { // Column 0 and column 2 scales not fuzzy zero. - // Create column 1 orthogonal to column 0 and column 2. - column1 = column2.cross(column0); - } - } else { // Column 0 and column 1 scales not fuzzy zero. - if (column2.fuzzyZero()) { - // Create column 2 orthogonal to column 0 and column 1. - column2 = column0.cross(column1); - } - } - } - - // Normalize - column0.normalize(); - column1.normalize(); - column2.normalize(); - - basis.setValue(column0[0], column1[0], column2[0], - column0[1], column1[1], column2[1], - column0[2], column1[2], column2[2]); -} diff --git a/modules/bullet/bullet_types_converter.h b/modules/bullet/bullet_types_converter.h deleted file mode 100644 index 4ee855c266..0000000000 --- a/modules/bullet/bullet_types_converter.h +++ /dev/null @@ -1,59 +0,0 @@ -/*************************************************************************/ -/* bullet_types_converter.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 BULLET_TYPES_CONVERTER_H -#define BULLET_TYPES_CONVERTER_H - -#include "core/math/basis.h" -#include "core/math/transform_3d.h" -#include "core/math/vector3.h" -#include "core/typedefs.h" - -#include <LinearMath/btMatrix3x3.h> -#include <LinearMath/btTransform.h> -#include <LinearMath/btVector3.h> - -// Bullet to Godot -extern void B_TO_G(btVector3 const &inVal, Vector3 &outVal); -extern void INVERT_B_TO_G(btVector3 const &inVal, Vector3 &outVal); -extern void B_TO_G(btMatrix3x3 const &inVal, Basis &outVal); -extern void INVERT_B_TO_G(btMatrix3x3 const &inVal, Basis &outVal); -extern void B_TO_G(btTransform const &inVal, Transform3D &outVal); - -// Godot TO Bullet -extern void G_TO_B(Vector3 const &inVal, btVector3 &outVal); -extern void INVERT_G_TO_B(Vector3 const &inVal, btVector3 &outVal); -extern void G_TO_B(Basis const &inVal, btMatrix3x3 &outVal); -extern void INVERT_G_TO_B(Basis const &inVal, btMatrix3x3 &outVal); -extern void G_TO_B(Transform3D const &inVal, btTransform &outVal); - -extern void UNSCALE_BT_BASIS(btTransform &scaledBasis); - -#endif // BULLET_TYPES_CONVERTER_H diff --git a/modules/bullet/bullet_utilities.h b/modules/bullet/bullet_utilities.h deleted file mode 100644 index ab24cb5de6..0000000000 --- a/modules/bullet/bullet_utilities.h +++ /dev/null @@ -1,43 +0,0 @@ -/*************************************************************************/ -/* bullet_utilities.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 BULLET_UTILITIES_H -#define BULLET_UTILITIES_H - -#define bulletnew(cl) \ - new cl - -#define bulletdelete(cl) \ - { \ - delete cl; \ - cl = nullptr; \ - } - -#endif // BULLET_UTILITIES_H diff --git a/modules/bullet/collision_object_bullet.cpp b/modules/bullet/collision_object_bullet.cpp deleted file mode 100644 index bc8e1a0718..0000000000 --- a/modules/bullet/collision_object_bullet.cpp +++ /dev/null @@ -1,396 +0,0 @@ -/*************************************************************************/ -/* collision_object_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "collision_object_bullet.h" - -#include "area_bullet.h" -#include "bullet_physics_server.h" -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "shape_bullet.h" -#include "space_bullet.h" - -#include <btBulletCollisionCommon.h> - -// 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() {} - -void CollisionObjectBullet::ShapeWrapper::set_transform(const Transform3D &p_transform) { - G_TO_B(p_transform.get_basis().get_scale_abs(), scale); - G_TO_B(p_transform, transform); - UNSCALE_BT_BASIS(transform); -} - -void CollisionObjectBullet::ShapeWrapper::set_transform(const btTransform &p_transform) { - transform = p_transform; -} - -btTransform CollisionObjectBullet::ShapeWrapper::get_adjusted_transform() const { - if (shape->get_type() == PhysicsServer3D::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) { - bt_shape = shape->create_bt_shape(scale * body_scale); - } else { - bt_shape = ShapeBullet::create_shape_empty(); - } - } -} - -CollisionObjectBullet::CollisionObjectBullet(Type p_type) : - RIDBullet(), - type(p_type) {} - -CollisionObjectBullet::~CollisionObjectBullet() { - for (int i = 0; i < areasOverlapped.size(); i++) { - areasOverlapped[i]->remove_object_overlaps(this); - } - destroyBulletCollisionObject(); -} - -bool equal(real_t first, real_t second) { - return Math::abs(first - second) <= 0.001f; -} - -void CollisionObjectBullet::set_body_scale(const Vector3 &p_new_scale) { - if (!equal(p_new_scale[0], body_scale[0]) || !equal(p_new_scale[1], body_scale[1]) || !equal(p_new_scale[2], body_scale[2])) { - body_scale = p_new_scale; - body_scale_changed(); - } -} - -btVector3 CollisionObjectBullet::get_bt_body_scale() const { - btVector3 s; - G_TO_B(body_scale, s); - return s; -} - -void CollisionObjectBullet::body_scale_changed() { - force_shape_reset = true; -} - -void CollisionObjectBullet::destroyBulletCollisionObject() { - bulletdelete(bt_collision_object); -} - -void CollisionObjectBullet::setupBulletCollisionObject(btCollisionObject *p_collisionObject) { - bt_collision_object = p_collisionObject; - bt_collision_object->setUserPointer(this); - bt_collision_object->setUserIndex(type); - // Force the enabling of collision and avoid problems - set_collision_enabled(collisionsEnabled); - p_collisionObject->setCollisionFlags(p_collisionObject->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK); -} - -void CollisionObjectBullet::add_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject) { - exceptions.insert(p_ignoreCollisionObject->get_self()); - if (!bt_collision_object) { - return; - } - bt_collision_object->setIgnoreCollisionCheck(p_ignoreCollisionObject->bt_collision_object, true); - if (space) { - space->get_broadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bt_collision_object->getBroadphaseHandle(), space->get_dispatcher()); - } -} - -void CollisionObjectBullet::remove_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject) { - exceptions.erase(p_ignoreCollisionObject->get_self()); - if (!bt_collision_object) { - return; - } - bt_collision_object->setIgnoreCollisionCheck(p_ignoreCollisionObject->bt_collision_object, false); - if (space) { - space->get_broadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bt_collision_object->getBroadphaseHandle(), space->get_dispatcher()); - } -} - -bool CollisionObjectBullet::has_collision_exception(const CollisionObjectBullet *p_otherCollisionObject) const { - return exceptions.has(p_otherCollisionObject->get_self()); -} - -void CollisionObjectBullet::set_collision_enabled(bool p_enabled) { - collisionsEnabled = p_enabled; - if (!bt_collision_object) { - return; - } - if (collisionsEnabled) { - bt_collision_object->setCollisionFlags(bt_collision_object->getCollisionFlags() & (~btCollisionObject::CF_NO_CONTACT_RESPONSE)); - } else { - bt_collision_object->setCollisionFlags(bt_collision_object->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE); - } -} - -bool CollisionObjectBullet::is_collisions_response_enabled() { - return collisionsEnabled; -} - -void CollisionObjectBullet::notify_new_overlap(AreaBullet *p_area) { - if (areasOverlapped.find(p_area) == -1) { - areasOverlapped.push_back(p_area); - } -} - -void CollisionObjectBullet::on_exit_area(AreaBullet *p_area) { - areasOverlapped.erase(p_area); -} - -void CollisionObjectBullet::set_godot_object_flags(int flags) { - bt_collision_object->setUserIndex2(flags); - updated = true; -} - -int CollisionObjectBullet::get_godot_object_flags() const { - return bt_collision_object->getUserIndex2(); -} - -void CollisionObjectBullet::set_transform(const Transform3D &p_global_transform) { - set_body_scale(p_global_transform.basis.get_scale_abs()); - - btTransform bt_transform; - G_TO_B(p_global_transform, bt_transform); - UNSCALE_BT_BASIS(bt_transform); - - set_transform__bullet(bt_transform); -} - -Transform3D CollisionObjectBullet::get_transform() const { - Transform3D t; - B_TO_G(get_transform__bullet(), t); - t.basis.scale(body_scale); - return t; -} - -void CollisionObjectBullet::set_transform__bullet(const btTransform &p_global_transform) { - bt_collision_object->setWorldTransform(p_global_transform); - notify_transform_changed(); -} - -const btTransform &CollisionObjectBullet::get_transform__bullet() const { - return bt_collision_object->getWorldTransform(); -} - -void CollisionObjectBullet::notify_transform_changed() { - updated = true; -} - -RigidCollisionObjectBullet::~RigidCollisionObjectBullet() { - remove_all_shapes(true, true); - if (mainShape && mainShape->isCompound()) { - bulletdelete(mainShape); - } -} - -void RigidCollisionObjectBullet::add_shape(ShapeBullet *p_shape, const Transform3D &p_transform, bool p_disabled) { - shapes.push_back(ShapeWrapper(p_shape, p_transform, !p_disabled)); - p_shape->add_owner(this); - reload_shapes(); -} - -void RigidCollisionObjectBullet::set_shape(int p_index, ShapeBullet *p_shape) { - ShapeWrapper &shp = shapes.write[p_index]; - shp.shape->remove_owner(this); - p_shape->add_owner(this); - shp.shape = p_shape; - reload_shapes(); -} - -int RigidCollisionObjectBullet::get_shape_count() const { - return shapes.size(); -} - -ShapeBullet *RigidCollisionObjectBullet::get_shape(int p_index) const { - return shapes[p_index].shape; -} - -btCollisionShape *RigidCollisionObjectBullet::get_bt_shape(int p_index) const { - return shapes[p_index].bt_shape; -} - -int RigidCollisionObjectBullet::find_shape(ShapeBullet *p_shape) const { - const int size = shapes.size(); - for (int i = 0; i < size; ++i) { - if (shapes[i].shape == p_shape) { - return i; - } - } - return -1; -} - -void RigidCollisionObjectBullet::remove_shape_full(ShapeBullet *p_shape) { - // Remove the shape, all the times it appears - // Reverse order required for delete. - for (int i = shapes.size() - 1; 0 <= i; --i) { - if (p_shape == shapes[i].shape) { - internal_shape_destroy(i); - shapes.remove_at(i); - } - } - reload_shapes(); -} - -void RigidCollisionObjectBullet::remove_shape_full(int p_index) { - ERR_FAIL_INDEX(p_index, get_shape_count()); - internal_shape_destroy(p_index); - shapes.remove_at(p_index); - reload_shapes(); -} - -void RigidCollisionObjectBullet::remove_all_shapes(bool p_permanentlyFromThisBody, bool p_force_not_reload) { - // Reverse order required for delete. - for (int i = shapes.size() - 1; 0 <= i; --i) { - internal_shape_destroy(i, p_permanentlyFromThisBody); - } - shapes.clear(); - if (!p_force_not_reload) { - reload_shapes(); - } -} - -void RigidCollisionObjectBullet::set_shape_transform(int p_index, const Transform3D &p_transform) { - ERR_FAIL_INDEX(p_index, get_shape_count()); - - shapes.write[p_index].set_transform(p_transform); - shape_changed(p_index); -} - -const btTransform &RigidCollisionObjectBullet::get_bt_shape_transform(int p_index) const { - return shapes[p_index].transform; -} - -Transform3D RigidCollisionObjectBullet::get_shape_transform(int p_index) const { - Transform3D trs; - B_TO_G(shapes[p_index].transform, trs); - return trs; -} - -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); -} - -bool RigidCollisionObjectBullet::is_shape_disabled(int p_index) { - return !shapes[p_index].active; -} - -void RigidCollisionObjectBullet::shape_changed(int p_shape_index) { - ShapeWrapper &shp = shapes.write[p_shape_index]; - if (shp.bt_shape == mainShape) { - mainShape = nullptr; - } - bulletdelete(shp.bt_shape); - reload_shapes(); -} - -void RigidCollisionObjectBullet::reload_shapes() { - if (mainShape && mainShape->isCompound()) { - // Destroy compound - bulletdelete(mainShape); - } - - mainShape = nullptr; - - ShapeWrapper *shpWrapper; - const int shape_count = shapes.size(); - - // Reset shape if required - if (force_shape_reset) { - for (int i(0); i < shape_count; ++i) { - shpWrapper = &shapes.write[i]; - bulletdelete(shpWrapper->bt_shape); - } - force_shape_reset = false; - } - - const btVector3 body_scale(get_bt_body_scale()); - - // Try to optimize by not using compound - if (1 == shape_count) { - shpWrapper = &shapes.write[0]; - 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(); - return; - } - } - - // Optimization not possible use a compound shape - btCompoundShape *compoundShape = bulletnew(btCompoundShape(enableDynamicAabbTree, shape_count)); - - for (int i(0); i < shape_count; ++i) { - shpWrapper = &shapes.write[i]; - shpWrapper->claim_bt_shape(body_scale); - btTransform scaled_shape_transform(shpWrapper->get_adjusted_transform()); - scaled_shape_transform.getOrigin() *= body_scale; - compoundShape->addChildShape(scaled_shape_transform, shpWrapper->bt_shape); - } - - compoundShape->recalculateLocalAabb(); - mainShape = compoundShape; - main_shape_changed(); -} - -void RigidCollisionObjectBullet::body_scale_changed() { - CollisionObjectBullet::body_scale_changed(); - reload_shapes(); -} - -void RigidCollisionObjectBullet::internal_shape_destroy(int p_index, bool p_permanentlyFromThisBody) { - ShapeWrapper &shp = shapes.write[p_index]; - shp.shape->remove_owner(this, p_permanentlyFromThisBody); - if (shp.bt_shape == mainShape) { - mainShape = nullptr; - } - bulletdelete(shp.bt_shape); -} diff --git a/modules/bullet/collision_object_bullet.h b/modules/bullet/collision_object_bullet.h deleted file mode 100644 index 8e9c34df27..0000000000 --- a/modules/bullet/collision_object_bullet.h +++ /dev/null @@ -1,255 +0,0 @@ -/*************************************************************************/ -/* collision_object_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 COLLISION_OBJECT_BULLET_H -#define COLLISION_OBJECT_BULLET_H - -#include "core/math/transform_3d.h" -#include "core/math/vector3.h" -#include "core/object/class_db.h" -#include "core/templates/vset.h" -#include "shape_owner_bullet.h" - -#include <LinearMath/btTransform.h> - -class AreaBullet; -class ShapeBullet; -class btCollisionObject; -class btCompoundShape; -class btCollisionShape; -class SpaceBullet; - -class CollisionObjectBullet : public RIDBullet { -public: - enum GodotObjectFlags { - GOF_IS_MONITORING_AREA = 1 << 0 - // FLAG2 = 1 << 1, - // FLAG3 = 1 << 2, - // FLAG4 = 1 << 3, - // FLAG5 = 1 << 4, - // FLAG6 = 1 << 5 - // etc.. - }; - enum Type { - TYPE_AREA = 0, - TYPE_RIGID_BODY, - TYPE_SOFT_BODY, - TYPE_KINEMATIC_GHOST_BODY - }; - - struct ShapeWrapper { - ShapeBullet *shape = nullptr; - btCollisionShape *bt_shape = nullptr; - btTransform transform; - btVector3 scale; - bool active = true; - - ShapeWrapper() {} - - ShapeWrapper(ShapeBullet *p_shape, const btTransform &p_transform, bool p_active) : - shape(p_shape), - active(p_active) { - set_transform(p_transform); - } - - ShapeWrapper(ShapeBullet *p_shape, const Transform3D &p_transform, bool p_active) : - shape(p_shape), - active(p_active) { - set_transform(p_transform); - } - ~ShapeWrapper(); - - ShapeWrapper(const ShapeWrapper &otherShape) { - operator=(otherShape); - } - - void operator=(const ShapeWrapper &otherShape) { - shape = otherShape.shape; - bt_shape = otherShape.bt_shape; - transform = otherShape.transform; - scale = otherShape.scale; - active = otherShape.active; - } - - void set_transform(const Transform3D &p_transform); - void set_transform(const btTransform &p_transform); - btTransform get_adjusted_transform() const; - - void claim_bt_shape(const btVector3 &body_scale); - }; - -protected: - Type type = TYPE_AREA; - ObjectID instance_id; - uint32_t collisionLayer = 0; - uint32_t collisionMask = 0; - bool collisionsEnabled = true; - bool m_isStatic = false; - bool ray_pickable = false; - btCollisionObject *bt_collision_object = nullptr; - Vector3 body_scale = Vector3(1, 1, 1); - bool force_shape_reset = false; - SpaceBullet *space = nullptr; - - VSet<RID> exceptions; - - /// This array is used to know all areas where this Object is overlapped in - /// New area is added when overlap with new area (AreaBullet::addOverlap), then is removed when it exit (CollisionObjectBullet::onExitArea) - /// This array is used mainly to know which area hold the pointer of this object - Vector<AreaBullet *> areasOverlapped; - bool updated = false; - -public: - CollisionObjectBullet(Type p_type); - virtual ~CollisionObjectBullet(); - - Type getType() { return type; } - -protected: - void destroyBulletCollisionObject(); - void setupBulletCollisionObject(btCollisionObject *p_collisionObject); - -public: - _FORCE_INLINE_ btCollisionObject *get_bt_collision_object() { return bt_collision_object; } - - _FORCE_INLINE_ void set_instance_id(const ObjectID &p_instance_id) { instance_id = p_instance_id; } - _FORCE_INLINE_ ObjectID get_instance_id() const { return instance_id; } - - _FORCE_INLINE_ bool is_static() const { return m_isStatic; } - - _FORCE_INLINE_ void set_ray_pickable(bool p_enable) { ray_pickable = p_enable; } - _FORCE_INLINE_ bool is_ray_pickable() const { return ray_pickable; } - - void set_body_scale(const Vector3 &p_new_scale); - const Vector3 &get_body_scale() const { return body_scale; } - btVector3 get_bt_body_scale() const; - virtual void body_scale_changed(); - - void add_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject); - void remove_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject); - bool has_collision_exception(const CollisionObjectBullet *p_otherCollisionObject) const; - _FORCE_INLINE_ const VSet<RID> &get_exceptions() const { return exceptions; } - - _FORCE_INLINE_ void set_collision_layer(uint32_t p_layer) { - 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) { - if (collisionMask != p_mask) { - collisionMask = p_mask; - on_collision_filters_change(); - } - } - _FORCE_INLINE_ uint32_t get_collision_mask() const { return collisionMask; } - - virtual void on_collision_filters_change() = 0; - - _FORCE_INLINE_ bool test_collision_mask(CollisionObjectBullet *p_other) const { - return collisionLayer & p_other->collisionMask || p_other->collisionLayer & collisionMask; - } - - virtual void reload_body() = 0; - virtual void set_space(SpaceBullet *p_space) = 0; - _FORCE_INLINE_ SpaceBullet *get_space() const { return space; } - - virtual void on_collision_checker_start() = 0; - virtual void on_collision_checker_end() = 0; - - virtual void dispatch_callbacks() = 0; - - void set_collision_enabled(bool p_enabled); - bool is_collisions_response_enabled(); - - void notify_new_overlap(AreaBullet *p_area); - virtual void on_enter_area(AreaBullet *p_area) = 0; - virtual void on_exit_area(AreaBullet *p_area); - - void set_godot_object_flags(int flags); - int get_godot_object_flags() const; - - void set_transform(const Transform3D &p_global_transform); - Transform3D get_transform() const; - virtual void set_transform__bullet(const btTransform &p_global_transform); - virtual const btTransform &get_transform__bullet() const; - virtual void notify_transform_changed(); - - bool is_updated() const { return updated; } -}; - -class RigidCollisionObjectBullet : public CollisionObjectBullet, public ShapeOwnerBullet { -protected: - btCollisionShape *mainShape = nullptr; - Vector<ShapeWrapper> shapes; - -public: - RigidCollisionObjectBullet(Type p_type) : - CollisionObjectBullet(p_type) {} - ~RigidCollisionObjectBullet(); - - _FORCE_INLINE_ const Vector<ShapeWrapper> &get_shapes_wrappers() const { return shapes; } - - _FORCE_INLINE_ btCollisionShape *get_main_shape() const { return mainShape; } - - void add_shape(ShapeBullet *p_shape, const Transform3D &p_transform = Transform3D(), bool p_disabled = false); - void set_shape(int p_index, ShapeBullet *p_shape); - - int get_shape_count() const; - ShapeBullet *get_shape(int p_index) const; - btCollisionShape *get_bt_shape(int p_index) const; - - int find_shape(ShapeBullet *p_shape) const; - - virtual void remove_shape_full(ShapeBullet *p_shape); - void remove_shape_full(int p_index); - void remove_all_shapes(bool p_permanentlyFromThisBody = false, bool p_force_not_reload = false); - - void set_shape_transform(int p_index, const Transform3D &p_transform); - - const btTransform &get_bt_shape_transform(int p_index) const; - Transform3D get_shape_transform(int p_index) const; - - void set_shape_disabled(int p_index, bool p_disabled); - bool is_shape_disabled(int p_index); - - virtual void shape_changed(int p_shape_index); - virtual void reload_shapes(); - - virtual void main_shape_changed() = 0; - virtual void body_scale_changed(); - -private: - void internal_shape_destroy(int p_index, bool p_permanentlyFromThisBody = false); -}; - -#endif // COLLISION_OBJECT_BULLET_H diff --git a/modules/bullet/cone_twist_joint_bullet.cpp b/modules/bullet/cone_twist_joint_bullet.cpp deleted file mode 100644 index fc73036713..0000000000 --- a/modules/bullet/cone_twist_joint_bullet.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/*************************************************************************/ -/* cone_twist_joint_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "cone_twist_joint_bullet.h" - -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "rigid_body_bullet.h" - -#include <BulletDynamics/ConstraintSolver/btConeTwistConstraint.h> - -ConeTwistJointBullet::ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &rbAFrame, const Transform3D &rbBFrame) : - JointBullet() { - Transform3D scaled_AFrame(rbAFrame.scaled(rbA->get_body_scale())); - scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); - - btTransform btFrameA; - G_TO_B(scaled_AFrame, btFrameA); - - if (rbB) { - Transform3D scaled_BFrame(rbBFrame.scaled(rbB->get_body_scale())); - scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); - - btTransform btFrameB; - G_TO_B(scaled_BFrame, btFrameB); - - coneConstraint = bulletnew(btConeTwistConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btFrameA, btFrameB)); - } else { - coneConstraint = bulletnew(btConeTwistConstraint(*rbA->get_bt_rigid_body(), btFrameA)); - } - setup(coneConstraint); -} - -void ConeTwistJointBullet::set_param(PhysicsServer3D::ConeTwistJointParam p_param, real_t p_value) { - switch (p_param) { - case PhysicsServer3D::CONE_TWIST_JOINT_SWING_SPAN: - coneConstraint->setLimit(5, p_value); - coneConstraint->setLimit(4, p_value); - break; - case PhysicsServer3D::CONE_TWIST_JOINT_TWIST_SPAN: - coneConstraint->setLimit(3, p_value); - break; - case PhysicsServer3D::CONE_TWIST_JOINT_BIAS: - coneConstraint->setLimit(coneConstraint->getSwingSpan1(), coneConstraint->getSwingSpan2(), coneConstraint->getTwistSpan(), coneConstraint->getLimitSoftness(), p_value, coneConstraint->getRelaxationFactor()); - break; - case PhysicsServer3D::CONE_TWIST_JOINT_SOFTNESS: - coneConstraint->setLimit(coneConstraint->getSwingSpan1(), coneConstraint->getSwingSpan2(), coneConstraint->getTwistSpan(), p_value, coneConstraint->getBiasFactor(), coneConstraint->getRelaxationFactor()); - break; - case PhysicsServer3D::CONE_TWIST_JOINT_RELAXATION: - coneConstraint->setLimit(coneConstraint->getSwingSpan1(), coneConstraint->getSwingSpan2(), coneConstraint->getTwistSpan(), coneConstraint->getLimitSoftness(), coneConstraint->getBiasFactor(), p_value); - break; - case PhysicsServer3D::CONE_TWIST_MAX: - // Internal size value, nothing to do. - break; - } -} - -real_t ConeTwistJointBullet::get_param(PhysicsServer3D::ConeTwistJointParam p_param) const { - switch (p_param) { - case PhysicsServer3D::CONE_TWIST_JOINT_SWING_SPAN: - return coneConstraint->getSwingSpan1(); - case PhysicsServer3D::CONE_TWIST_JOINT_TWIST_SPAN: - return coneConstraint->getTwistSpan(); - case PhysicsServer3D::CONE_TWIST_JOINT_BIAS: - return coneConstraint->getBiasFactor(); - case PhysicsServer3D::CONE_TWIST_JOINT_SOFTNESS: - return coneConstraint->getLimitSoftness(); - case PhysicsServer3D::CONE_TWIST_JOINT_RELAXATION: - return coneConstraint->getRelaxationFactor(); - case PhysicsServer3D::CONE_TWIST_MAX: - // Internal size value, nothing to do. - return 0; - } - // Compiler doesn't seem to notice that all code paths are fulfilled... - return 0; -} diff --git a/modules/bullet/cone_twist_joint_bullet.h b/modules/bullet/cone_twist_joint_bullet.h deleted file mode 100644 index c81e11f144..0000000000 --- a/modules/bullet/cone_twist_joint_bullet.h +++ /dev/null @@ -1,50 +0,0 @@ -/*************************************************************************/ -/* cone_twist_joint_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 CONE_TWIST_JOINT_BULLET_H -#define CONE_TWIST_JOINT_BULLET_H - -#include "joint_bullet.h" - -class RigidBodyBullet; - -class ConeTwistJointBullet : public JointBullet { - class btConeTwistConstraint *coneConstraint; - -public: - ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &rbAFrame, const Transform3D &rbBFrame); - - virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_CONE_TWIST; } - - void set_param(PhysicsServer3D::ConeTwistJointParam p_param, real_t p_value); - real_t get_param(PhysicsServer3D::ConeTwistJointParam p_param) const; -}; - -#endif // CONE_TWIST_JOINT_BULLET_H diff --git a/modules/bullet/config.py b/modules/bullet/config.py deleted file mode 100644 index 83605f1f9b..0000000000 --- a/modules/bullet/config.py +++ /dev/null @@ -1,8 +0,0 @@ -def can_build(env, platform): - # API Changed and bullet is disabled at the moment - return False - # Later change to return not env["disable_3d"] - - -def configure(env): - pass diff --git a/modules/bullet/constraint_bullet.cpp b/modules/bullet/constraint_bullet.cpp deleted file mode 100644 index c788f09cb9..0000000000 --- a/modules/bullet/constraint_bullet.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/*************************************************************************/ -/* constraint_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "constraint_bullet.h" - -#include "collision_object_bullet.h" -#include "space_bullet.h" - -ConstraintBullet::ConstraintBullet() {} - -void ConstraintBullet::setup(btTypedConstraint *p_constraint) { - constraint = p_constraint; - constraint->setUserConstraintPtr(this); -} - -void ConstraintBullet::set_space(SpaceBullet *p_space) { - space = p_space; -} - -void ConstraintBullet::destroy_internal_constraint() { - space->remove_constraint(this); -} - -void ConstraintBullet::disable_collisions_between_bodies(const bool p_disabled) { - disabled_collisions_between_bodies = p_disabled; - - if (space) { - space->remove_constraint(this); - space->add_constraint(this, disabled_collisions_between_bodies); - } -} diff --git a/modules/bullet/generic_6dof_joint_bullet.cpp b/modules/bullet/generic_6dof_joint_bullet.cpp deleted file mode 100644 index 0210064dc8..0000000000 --- a/modules/bullet/generic_6dof_joint_bullet.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/*************************************************************************/ -/* generic_6dof_joint_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "generic_6dof_joint_bullet.h" - -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "rigid_body_bullet.h" - -#include <BulletDynamics/ConstraintSolver/btGeneric6DofSpring2Constraint.h> - -Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB) : - JointBullet() { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < PhysicsServer3D::G6DOF_JOINT_FLAG_MAX; j++) { - flags[i][j] = false; - } - } - - Transform3D scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); - - scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); - - btTransform btFrameA; - G_TO_B(scaled_AFrame, btFrameA); - - if (rbB) { - Transform3D scaled_BFrame(frameInB.scaled(rbB->get_body_scale())); - - scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); - - btTransform btFrameB; - G_TO_B(scaled_BFrame, btFrameB); - - sixDOFConstraint = bulletnew(btGeneric6DofSpring2Constraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btFrameA, btFrameB)); - } else { - sixDOFConstraint = bulletnew(btGeneric6DofSpring2Constraint(*rbA->get_bt_rigid_body(), btFrameA)); - } - - setup(sixDOFConstraint); -} - -Transform3D Generic6DOFJointBullet::getFrameOffsetA() const { - btTransform btTrs = sixDOFConstraint->getFrameOffsetA(); - Transform3D gTrs; - B_TO_G(btTrs, gTrs); - return gTrs; -} - -Transform3D Generic6DOFJointBullet::getFrameOffsetB() const { - btTransform btTrs = sixDOFConstraint->getFrameOffsetB(); - Transform3D gTrs; - B_TO_G(btTrs, gTrs); - return gTrs; -} - -Transform3D Generic6DOFJointBullet::getFrameOffsetA() { - btTransform btTrs = sixDOFConstraint->getFrameOffsetA(); - Transform3D gTrs; - B_TO_G(btTrs, gTrs); - return gTrs; -} - -Transform3D Generic6DOFJointBullet::getFrameOffsetB() { - btTransform btTrs = sixDOFConstraint->getFrameOffsetB(); - Transform3D gTrs; - B_TO_G(btTrs, gTrs); - return gTrs; -} - -void Generic6DOFJointBullet::set_linear_lower_limit(const Vector3 &linearLower) { - btVector3 btVec; - G_TO_B(linearLower, btVec); - sixDOFConstraint->setLinearLowerLimit(btVec); -} - -void Generic6DOFJointBullet::set_linear_upper_limit(const Vector3 &linearUpper) { - btVector3 btVec; - G_TO_B(linearUpper, btVec); - sixDOFConstraint->setLinearUpperLimit(btVec); -} - -void Generic6DOFJointBullet::set_angular_lower_limit(const Vector3 &angularLower) { - btVector3 btVec; - G_TO_B(angularLower, btVec); - sixDOFConstraint->setAngularLowerLimit(btVec); -} - -void Generic6DOFJointBullet::set_angular_upper_limit(const Vector3 &angularUpper) { - btVector3 btVec; - G_TO_B(angularUpper, btVec); - sixDOFConstraint->setAngularUpperLimit(btVec); -} - -void Generic6DOFJointBullet::set_param(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisParam p_param, real_t p_value) { - ERR_FAIL_INDEX(p_axis, 3); - switch (p_param) { - case PhysicsServer3D::G6DOF_JOINT_LINEAR_LOWER_LIMIT: - limits_lower[0][p_axis] = p_value; - set_flag(p_axis, PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT, flags[p_axis][PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT]); // Reload bullet parameter - break; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_UPPER_LIMIT: - limits_upper[0][p_axis] = p_value; - set_flag(p_axis, PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT, flags[p_axis][PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT]); // Reload bullet parameter - break; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_MOTOR_TARGET_VELOCITY: - sixDOFConstraint->getTranslationalLimitMotor()->m_targetVelocity.m_floats[p_axis] = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_MOTOR_FORCE_LIMIT: - sixDOFConstraint->getTranslationalLimitMotor()->m_maxMotorForce.m_floats[p_axis] = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_SPRING_DAMPING: - sixDOFConstraint->getTranslationalLimitMotor()->m_springDamping.m_floats[p_axis] = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_SPRING_STIFFNESS: - sixDOFConstraint->getTranslationalLimitMotor()->m_springStiffness.m_floats[p_axis] = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_SPRING_EQUILIBRIUM_POINT: - sixDOFConstraint->getTranslationalLimitMotor()->m_equilibriumPoint.m_floats[p_axis] = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_LOWER_LIMIT: - limits_lower[1][p_axis] = p_value; - set_flag(p_axis, PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT, flags[p_axis][PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT]); // Reload bullet parameter - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_UPPER_LIMIT: - limits_upper[1][p_axis] = p_value; - set_flag(p_axis, PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT, flags[p_axis][PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT]); // Reload bullet parameter - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_RESTITUTION: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_bounce = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_ERP: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_stopERP = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_targetVelocity = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_maxMotorForce = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_SPRING_STIFFNESS: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_springStiffness = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_SPRING_DAMPING: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_springDamping = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_SPRING_EQUILIBRIUM_POINT: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_equilibriumPoint = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_MAX: - // Internal size value, nothing to do. - break; - default: - WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated."); - break; - } -} - -real_t Generic6DOFJointBullet::get_param(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisParam p_param) const { - ERR_FAIL_INDEX_V(p_axis, 3, 0.); - switch (p_param) { - case PhysicsServer3D::G6DOF_JOINT_LINEAR_LOWER_LIMIT: - return limits_lower[0][p_axis]; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_UPPER_LIMIT: - return limits_upper[0][p_axis]; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_MOTOR_TARGET_VELOCITY: - return sixDOFConstraint->getTranslationalLimitMotor()->m_targetVelocity.m_floats[p_axis]; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_MOTOR_FORCE_LIMIT: - return sixDOFConstraint->getTranslationalLimitMotor()->m_maxMotorForce.m_floats[p_axis]; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_SPRING_DAMPING: - return sixDOFConstraint->getTranslationalLimitMotor()->m_springDamping.m_floats[p_axis]; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_SPRING_STIFFNESS: - return sixDOFConstraint->getTranslationalLimitMotor()->m_springStiffness.m_floats[p_axis]; - case PhysicsServer3D::G6DOF_JOINT_LINEAR_SPRING_EQUILIBRIUM_POINT: - return sixDOFConstraint->getTranslationalLimitMotor()->m_equilibriumPoint.m_floats[p_axis]; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_LOWER_LIMIT: - return limits_lower[1][p_axis]; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_UPPER_LIMIT: - return limits_upper[1][p_axis]; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_RESTITUTION: - return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_bounce; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_ERP: - return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_stopERP; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY: - return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_targetVelocity; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT: - return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_maxMotorForce; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_SPRING_STIFFNESS: - return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_springStiffness; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_SPRING_DAMPING: - return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_springDamping; - case PhysicsServer3D::G6DOF_JOINT_ANGULAR_SPRING_EQUILIBRIUM_POINT: - return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_equilibriumPoint; - case PhysicsServer3D::G6DOF_JOINT_MAX: - // Internal size value, nothing to do. - return 0; - default: - WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated."); - return 0; - } -} - -void Generic6DOFJointBullet::set_flag(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisFlag p_flag, bool p_value) { - ERR_FAIL_INDEX(p_axis, 3); - - flags[p_axis][p_flag] = p_value; - - switch (p_flag) { - case PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT: - if (flags[p_axis][p_flag]) { - sixDOFConstraint->setLimit(p_axis, limits_lower[0][p_axis], limits_upper[0][p_axis]); - } else { - sixDOFConstraint->setLimit(p_axis, 0, -1); // Free - } - break; - case PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT: - if (flags[p_axis][p_flag]) { - sixDOFConstraint->setLimit(p_axis + 3, limits_lower[1][p_axis], limits_upper[1][p_axis]); - } else { - sixDOFConstraint->setLimit(p_axis + 3, 0, -1); // Free - } - break; - case PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_SPRING: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_enableSpring = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_LINEAR_SPRING: - sixDOFConstraint->getTranslationalLimitMotor()->m_enableSpring[p_axis] = p_value; - break; - case PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_MOTOR: - sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_enableMotor = flags[p_axis][p_flag]; - break; - case PhysicsServer3D::G6DOF_JOINT_FLAG_ENABLE_LINEAR_MOTOR: - sixDOFConstraint->getTranslationalLimitMotor()->m_enableMotor[p_axis] = flags[p_axis][p_flag]; - break; - case PhysicsServer3D::G6DOF_JOINT_FLAG_MAX: - // Internal size value, nothing to do. - break; - } -} - -bool Generic6DOFJointBullet::get_flag(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisFlag p_flag) const { - ERR_FAIL_INDEX_V(p_axis, 3, false); - return flags[p_axis][p_flag]; -} diff --git a/modules/bullet/generic_6dof_joint_bullet.h b/modules/bullet/generic_6dof_joint_bullet.h deleted file mode 100644 index cc4ccf7ac4..0000000000 --- a/modules/bullet/generic_6dof_joint_bullet.h +++ /dev/null @@ -1,69 +0,0 @@ -/*************************************************************************/ -/* generic_6dof_joint_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 GENERIC_6DOF_JOINT_BULLET_H -#define GENERIC_6DOF_JOINT_BULLET_H - -#include "joint_bullet.h" - -class RigidBodyBullet; - -class Generic6DOFJointBullet : public JointBullet { - class btGeneric6DofSpring2Constraint *sixDOFConstraint; - - // First is linear second is angular - Vector3 limits_lower[2]; - Vector3 limits_upper[2]; - bool flags[3][PhysicsServer3D::G6DOF_JOINT_FLAG_MAX]; - -public: - Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB); - - virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_6DOF; } - - Transform3D getFrameOffsetA() const; - Transform3D getFrameOffsetB() const; - Transform3D getFrameOffsetA(); - Transform3D getFrameOffsetB(); - - void set_linear_lower_limit(const Vector3 &linearLower); - void set_linear_upper_limit(const Vector3 &linearUpper); - - void set_angular_lower_limit(const Vector3 &angularLower); - void set_angular_upper_limit(const Vector3 &angularUpper); - - void set_param(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisParam p_param, real_t p_value); - real_t get_param(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisParam p_param) const; - - void set_flag(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisFlag p_flag, bool p_value); - bool get_flag(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisFlag p_flag) const; -}; - -#endif // GENERIC_6DOF_JOINT_BULLET_H diff --git a/modules/bullet/godot_collision_configuration.cpp b/modules/bullet/godot_collision_configuration.cpp deleted file mode 100644 index 354c4e271b..0000000000 --- a/modules/bullet/godot_collision_configuration.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/*************************************************************************/ -/* godot_collision_configuration.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "godot_collision_configuration.h" - -#include "godot_ray_world_algorithm.h" - -#include <BulletCollision/BroadphaseCollision/btBroadphaseProxy.h> -#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h> - -GodotCollisionConfiguration::GodotCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo) : - btDefaultCollisionConfiguration(constructionInfo) { - void *mem = nullptr; - - mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::CreateFunc), 16); - m_rayWorldCF = new (mem) GodotRayWorldAlgorithm::CreateFunc(world); - - mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::SwappedCreateFunc), 16); - m_swappedRayWorldCF = new (mem) GodotRayWorldAlgorithm::SwappedCreateFunc(world); -} - -GodotCollisionConfiguration::~GodotCollisionConfiguration() { - m_rayWorldCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree(m_rayWorldCF); - - m_swappedRayWorldCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree(m_swappedRayWorldCF); -} - -btCollisionAlgorithmCreateFunc *GodotCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported - return m_emptyCreateFunc; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; - } else { - return btDefaultCollisionConfiguration::getCollisionAlgorithmCreateFunc(proxyType0, proxyType1); - } -} - -btCollisionAlgorithmCreateFunc *GodotCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported - return m_emptyCreateFunc; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; - } else { - return btDefaultCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(proxyType0, proxyType1); - } -} - -GodotSoftCollisionConfiguration::GodotSoftCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo) : - btSoftBodyRigidBodyCollisionConfiguration(constructionInfo) { - void *mem = nullptr; - - mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::CreateFunc), 16); - m_rayWorldCF = new (mem) GodotRayWorldAlgorithm::CreateFunc(world); - - mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::SwappedCreateFunc), 16); - m_swappedRayWorldCF = new (mem) GodotRayWorldAlgorithm::SwappedCreateFunc(world); -} - -GodotSoftCollisionConfiguration::~GodotSoftCollisionConfiguration() { - m_rayWorldCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree(m_rayWorldCF); - - m_swappedRayWorldCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree(m_swappedRayWorldCF); -} - -btCollisionAlgorithmCreateFunc *GodotSoftCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported - return m_emptyCreateFunc; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; - } else { - return btSoftBodyRigidBodyCollisionConfiguration::getCollisionAlgorithmCreateFunc(proxyType0, proxyType1); - } -} - -btCollisionAlgorithmCreateFunc *GodotSoftCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) { - if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - // This collision is not supported - return m_emptyCreateFunc; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) { - return m_rayWorldCF; - } else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) { - return m_swappedRayWorldCF; - } else { - return btSoftBodyRigidBodyCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(proxyType0, proxyType1); - } -} diff --git a/modules/bullet/godot_collision_configuration.h b/modules/bullet/godot_collision_configuration.h deleted file mode 100644 index 7e29f6e03a..0000000000 --- a/modules/bullet/godot_collision_configuration.h +++ /dev/null @@ -1,63 +0,0 @@ -/*************************************************************************/ -/* godot_collision_configuration.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_COLLISION_CONFIGURATION_H -#define GODOT_COLLISION_CONFIGURATION_H - -#include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h> -#include <BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h> - -class btDiscreteDynamicsWorld; - -class GodotCollisionConfiguration : public btDefaultCollisionConfiguration { - btCollisionAlgorithmCreateFunc *m_rayWorldCF; - btCollisionAlgorithmCreateFunc *m_swappedRayWorldCF; - -public: - GodotCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo = btDefaultCollisionConstructionInfo()); - virtual ~GodotCollisionConfiguration(); - - virtual btCollisionAlgorithmCreateFunc *getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1); - virtual btCollisionAlgorithmCreateFunc *getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1); -}; - -class GodotSoftCollisionConfiguration : public btSoftBodyRigidBodyCollisionConfiguration { - btCollisionAlgorithmCreateFunc *m_rayWorldCF; - btCollisionAlgorithmCreateFunc *m_swappedRayWorldCF; - -public: - GodotSoftCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo = btDefaultCollisionConstructionInfo()); - virtual ~GodotSoftCollisionConfiguration(); - - virtual btCollisionAlgorithmCreateFunc *getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1); - virtual btCollisionAlgorithmCreateFunc *getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1); -}; - -#endif // GODOT_COLLISION_CONFIGURATION_H diff --git a/modules/bullet/godot_collision_dispatcher.cpp b/modules/bullet/godot_collision_dispatcher.cpp deleted file mode 100644 index 2ab1c7dd84..0000000000 --- a/modules/bullet/godot_collision_dispatcher.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/*************************************************************************/ -/* godot_collision_dispatcher.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "godot_collision_dispatcher.h" - -#include "collision_object_bullet.h" - -const int GodotCollisionDispatcher::CASTED_TYPE_AREA = static_cast<int>(CollisionObjectBullet::TYPE_AREA); - -GodotCollisionDispatcher::GodotCollisionDispatcher(btCollisionConfiguration *collisionConfiguration) : - btCollisionDispatcher(collisionConfiguration) {} - -bool GodotCollisionDispatcher::needsCollision(const btCollisionObject *body0, const btCollisionObject *body1) { - if (body0->getUserIndex() == CASTED_TYPE_AREA || body1->getUserIndex() == CASTED_TYPE_AREA) { - // Avoid area narrow phase - return false; - } - return btCollisionDispatcher::needsCollision(body0, body1); -} - -bool GodotCollisionDispatcher::needsResponse(const btCollisionObject *body0, const btCollisionObject *body1) { - if (body0->getUserIndex() == CASTED_TYPE_AREA || body1->getUserIndex() == CASTED_TYPE_AREA) { - // Avoid area narrow phase - return false; - } - return btCollisionDispatcher::needsResponse(body0, body1); -} diff --git a/modules/bullet/godot_collision_dispatcher.h b/modules/bullet/godot_collision_dispatcher.h deleted file mode 100644 index 97cae1ce6a..0000000000 --- a/modules/bullet/godot_collision_dispatcher.h +++ /dev/null @@ -1,47 +0,0 @@ -/*************************************************************************/ -/* godot_collision_dispatcher.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_COLLISION_DISPATCHER_H -#define GODOT_COLLISION_DISPATCHER_H - -#include <btBulletDynamicsCommon.h> - -/// This class is required to implement custom collision behaviour in the narrowphase -class GodotCollisionDispatcher : public btCollisionDispatcher { -private: - static const int CASTED_TYPE_AREA; - -public: - GodotCollisionDispatcher(btCollisionConfiguration *collisionConfiguration); - virtual bool needsCollision(const btCollisionObject *body0, const btCollisionObject *body1); - virtual bool needsResponse(const btCollisionObject *body0, const btCollisionObject *body1); -}; - -#endif // GODOT_COLLISION_DISPATCHER_H diff --git a/modules/bullet/godot_motion_state.h b/modules/bullet/godot_motion_state.h deleted file mode 100644 index f1a5e0e3b5..0000000000 --- a/modules/bullet/godot_motion_state.h +++ /dev/null @@ -1,96 +0,0 @@ -/*************************************************************************/ -/* godot_motion_state.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_MOTION_STATE_H -#define GODOT_MOTION_STATE_H - -#include "rigid_body_bullet.h" - -#include <LinearMath/btMotionState.h> - -class RigidBodyBullet; - -// This class is responsible to move kinematic actor -// and sincronize rendering engine with Bullet -/// DOC: -/// http://www.bulletphysics.org/mediawiki-1.5.8/index.php/MotionStates#What.27s_a_MotionState.3F -class GodotMotionState : public btMotionState { - /// This data is used to store the new world position for kinematic body - btTransform bodyKinematicWorldTransf; - /// This data is used to store last world position - btTransform bodyCurrentWorldTransform; - - RigidBodyBullet *owner = nullptr; - -public: - GodotMotionState(RigidBodyBullet *p_owner) : - bodyKinematicWorldTransf(btMatrix3x3(1., 0., 0., 0., 1., 0., 0., 0., 1.), btVector3(0., 0., 0.)), - bodyCurrentWorldTransform(btMatrix3x3(1., 0., 0., 0., 1., 0., 0., 0., 1.), btVector3(0., 0., 0.)), - owner(p_owner) {} - - /// IMPORTANT DON'T USE THIS FUNCTION TO KNOW THE CURRENT BODY TRANSFORM - /// This class is used internally by Bullet - /// Use GodotMotionState::getCurrentWorldTransform to know current position - /// - /// This function is used by Bullet to get the position of object in the world - /// if the body is kinematic Bullet will move the object to this location - /// if the body is static Bullet doesn't move at all - virtual void getWorldTransform(btTransform &worldTrans) const { - worldTrans = bodyKinematicWorldTransf; - } - - /// IMPORTANT: to move the body use: moveBody - /// IMPORTANT: DON'T CALL THIS FUNCTION, IT IS CALLED BY BULLET TO UPDATE RENDERING ENGINE - /// - /// This function is called each time by Bullet and set the current position of body - /// inside the physics world. - /// Don't allow Godot rendering scene takes world transform from this object because - /// the correct transform is set by Bullet only after the last step when there are sub steps - /// This function must update Godot transform rendering scene for this object. - virtual void setWorldTransform(const btTransform &worldTrans) { - bodyCurrentWorldTransform = worldTrans; - - owner->notify_transform_changed(); - } - -public: - /// Use this function to move kinematic body - /// -- or set initial transform before body creation. - void moveBody(const btTransform &newWorldTransform) { - bodyKinematicWorldTransf = newWorldTransform; - } - - /// It returns the current body transform from last Bullet update - const btTransform &getCurrentWorldTransform() const { - return bodyCurrentWorldTransform; - } -}; - -#endif // GODOT_MOTION_STATE_H diff --git a/modules/bullet/godot_ray_world_algorithm.cpp b/modules/bullet/godot_ray_world_algorithm.cpp deleted file mode 100644 index 697ca12e7b..0000000000 --- a/modules/bullet/godot_ray_world_algorithm.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/*************************************************************************/ -/* godot_ray_world_algorithm.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "godot_ray_world_algorithm.h" - -#include "btRayShape.h" -#include "collision_object_bullet.h" - -#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h> - -// Epsilon to account for floating point inaccuracies -#define RAY_PENETRATION_DEPTH_EPSILON 0.01 - -GodotRayWorldAlgorithm::CreateFunc::CreateFunc(const btDiscreteDynamicsWorld *world) : - m_world(world) {} - -GodotRayWorldAlgorithm::SwappedCreateFunc::SwappedCreateFunc(const btDiscreteDynamicsWorld *world) : - m_world(world) {} - -GodotRayWorldAlgorithm::GodotRayWorldAlgorithm(const btDiscreteDynamicsWorld *world, btPersistentManifold *mf, const btCollisionAlgorithmConstructionInfo &ci, const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap, bool isSwapped) : - btActivatingCollisionAlgorithm(ci, body0Wrap, body1Wrap), - m_world(world), - m_manifoldPtr(mf), - m_isSwapped(isSwapped) {} - -GodotRayWorldAlgorithm::~GodotRayWorldAlgorithm() { - if (m_ownManifold && m_manifoldPtr) { - m_dispatcher->releaseManifold(m_manifoldPtr); - } -} - -void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap, const btDispatcherInfo &dispatchInfo, btManifoldResult *resultOut) { - if (!m_manifoldPtr) { - if (m_isSwapped) { - m_manifoldPtr = m_dispatcher->getNewManifold(body1Wrap->getCollisionObject(), body0Wrap->getCollisionObject()); - } else { - m_manifoldPtr = m_dispatcher->getNewManifold(body0Wrap->getCollisionObject(), body1Wrap->getCollisionObject()); - } - m_ownManifold = true; - } - m_manifoldPtr->clearManifold(); - resultOut->setPersistentManifold(m_manifoldPtr); - - const btRayShape *ray_shape; - btTransform ray_transform; - - const btCollisionObjectWrapper *other_co_wrapper; - - if (m_isSwapped) { - ray_shape = static_cast<const btRayShape *>(body1Wrap->getCollisionShape()); - ray_transform = body1Wrap->getWorldTransform(); - - other_co_wrapper = body0Wrap; - } else { - ray_shape = static_cast<const btRayShape *>(body0Wrap->getCollisionShape()); - ray_transform = body0Wrap->getWorldTransform(); - - other_co_wrapper = body1Wrap; - } - - btTransform to(ray_transform * ray_shape->getSupportPoint()); - - btCollisionWorld::ClosestRayResultCallback btResult(ray_transform.getOrigin(), to.getOrigin()); - - m_world->rayTestSingleInternal(ray_transform, to, other_co_wrapper, btResult); - - if (btResult.hasHit()) { - btScalar depth(ray_shape->getScaledLength() * (btResult.m_closestHitFraction - 1)); - - if (depth > -RAY_PENETRATION_DEPTH_EPSILON) { - depth = 0.0; - } - - if (ray_shape->getSlipsOnSlope()) { - resultOut->addContactPoint(btResult.m_hitNormalWorld, btResult.m_hitPointWorld, depth); - } else { - resultOut->addContactPoint((ray_transform.getOrigin() - to.getOrigin()).normalize(), btResult.m_hitPointWorld, depth); - } - } -} - -btScalar GodotRayWorldAlgorithm::calculateTimeOfImpact(btCollisionObject *body0, btCollisionObject *body1, const btDispatcherInfo &dispatchInfo, btManifoldResult *resultOut) { - return 1; -} diff --git a/modules/bullet/godot_ray_world_algorithm.h b/modules/bullet/godot_ray_world_algorithm.h deleted file mode 100644 index 94bdefb720..0000000000 --- a/modules/bullet/godot_ray_world_algorithm.h +++ /dev/null @@ -1,80 +0,0 @@ -/*************************************************************************/ -/* godot_ray_world_algorithm.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_RAY_WORLD_ALGORITHM_H -#define GODOT_RAY_WORLD_ALGORITHM_H - -#include <BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h> -#include <BulletCollision/CollisionDispatch/btCollisionCreateFunc.h> -#include <BulletCollision/CollisionDispatch/btCollisionDispatcher.h> - -class btDiscreteDynamicsWorld; - -class GodotRayWorldAlgorithm : public btActivatingCollisionAlgorithm { - const btDiscreteDynamicsWorld *m_world; - btPersistentManifold *m_manifoldPtr; - bool m_ownManifold = false; - bool m_isSwapped = false; - -public: - GodotRayWorldAlgorithm(const btDiscreteDynamicsWorld *world, btPersistentManifold *mf, const btCollisionAlgorithmConstructionInfo &ci, const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap, bool isSwapped); - virtual ~GodotRayWorldAlgorithm(); - - virtual void processCollision(const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap, const btDispatcherInfo &dispatchInfo, btManifoldResult *resultOut); - virtual btScalar calculateTimeOfImpact(btCollisionObject *body0, btCollisionObject *body1, const btDispatcherInfo &dispatchInfo, btManifoldResult *resultOut); - - virtual void getAllContactManifolds(btManifoldArray &manifoldArray) { - ///should we use m_ownManifold to avoid adding duplicates? - if (m_manifoldPtr && m_ownManifold) { - manifoldArray.push_back(m_manifoldPtr); - } - } - struct CreateFunc : public btCollisionAlgorithmCreateFunc { - const btDiscreteDynamicsWorld *m_world; - CreateFunc(const btDiscreteDynamicsWorld *world); - - virtual btCollisionAlgorithm *CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo &ci, const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap) { - void *mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(GodotRayWorldAlgorithm)); - return new (mem) GodotRayWorldAlgorithm(m_world, ci.m_manifold, ci, body0Wrap, body1Wrap, false); - } - }; - - struct SwappedCreateFunc : public btCollisionAlgorithmCreateFunc { - const btDiscreteDynamicsWorld *m_world; - SwappedCreateFunc(const btDiscreteDynamicsWorld *world); - - virtual btCollisionAlgorithm *CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo &ci, const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap) { - void *mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(GodotRayWorldAlgorithm)); - return new (mem) GodotRayWorldAlgorithm(m_world, ci.m_manifold, ci, body0Wrap, body1Wrap, true); - } - }; -}; - -#endif // GODOT_RAY_WORLD_ALGORITHM_H diff --git a/modules/bullet/godot_result_callbacks.cpp b/modules/bullet/godot_result_callbacks.cpp deleted file mode 100644 index 35b26fc2ec..0000000000 --- a/modules/bullet/godot_result_callbacks.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/*************************************************************************/ -/* godot_result_callbacks.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "godot_result_callbacks.h" - -#include "area_bullet.h" -#include "bullet_types_converter.h" -#include "collision_object_bullet.h" -#include "rigid_body_bullet.h" - -#include <BulletCollision/CollisionDispatch/btInternalEdgeUtility.h> - -bool godotContactAddedCallback(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) { - if (!colObj1Wrap->getCollisionObject()->getCollisionShape()->isCompound()) { - btAdjustInternalEdgeContacts(cp, colObj1Wrap, colObj0Wrap, partId1, index1); - } - return true; -} - -bool GodotFilterCallback::needBroadphaseCollision(btBroadphaseProxy *proxy0, btBroadphaseProxy *proxy1) const { - return (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) || (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask); -} - -bool GodotClosestRayResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { - btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - - if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) { - return false; - } - } else { - if (!collide_with_bodies) { - return false; - } - } - - if (m_pickRay && !gObj->is_ray_pickable()) { - return false; - } - - if (m_exclude->has(gObj->get_self())) { - return false; - } - - return true; - } else { - return false; - } -} - -bool GodotAllConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (count >= m_resultMax) { - return false; - } - - if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { - btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - if (m_exclude->has(gObj->get_self())) { - return false; - } - - return true; - } else { - return false; - } -} - -btScalar GodotAllConvexResultCallback::addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace) { - if (count >= m_resultMax) { - return 1; // not used by bullet - } - - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(convexResult.m_hitCollisionObject->getUserPointer()); - - PhysicsDirectSpaceState3D::ShapeResult &result = m_results[count]; - - // Triangle index is an odd name but contains the compound shape ID. - // A shape part of -1 indicates the index is a shape index and not a triangle index. - if (convexResult.m_localShapeInfo && convexResult.m_localShapeInfo->m_shapePart == -1) { - result.shape = convexResult.m_localShapeInfo->m_triangleIndex; - } else { - result.shape = 0; - } - - result.rid = gObj->get_self(); - result.collider_id = gObj->get_instance_id(); - result.collider = result.collider_id.is_null() ? nullptr : ObjectDB::get_instance(result.collider_id); - - ++count; - return 1; // not used by bullet -} - -bool GodotKinClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { - btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - if (gObj == m_self_object) { - return false; - } else { - // A kinematic body can't be stopped by a rigid body since the mass of kinematic body is infinite - if (m_infinite_inertia && !btObj->isStaticOrKinematicObject()) { - return false; - } - - if (gObj->getType() == CollisionObjectBullet::TYPE_AREA) { - return false; - } - - if (m_self_object->has_collision_exception(gObj) || gObj->has_collision_exception(m_self_object)) { - return false; - } - - if (m_exclude->has(gObj->get_self())) { - return false; - } - } - return true; - } else { - return false; - } -} - -bool GodotClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { - btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - - if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) { - return false; - } - } else { - if (!collide_with_bodies) { - return false; - } - } - - if (m_exclude->has(gObj->get_self())) { - return false; - } - return true; - } else { - return false; - } -} - -btScalar GodotClosestConvexResultCallback::addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace) { - // Triangle index is an odd name but contains the compound shape ID. - // A shape part of -1 indicates the index is a shape index and not a triangle index. - if (convexResult.m_localShapeInfo && convexResult.m_localShapeInfo->m_shapePart == -1) { - m_shapeId = convexResult.m_localShapeInfo->m_triangleIndex; - } else { - m_shapeId = 0; - } - - return btCollisionWorld::ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace); -} - -bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (m_count >= m_resultMax) { - return false; - } - - if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { - btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - - if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) { - return false; - } - } else { - if (!collide_with_bodies) { - return false; - } - } - - if (m_exclude->has(gObj->get_self())) { - return false; - } - return true; - } else { - return false; - } -} - -btScalar GodotAllContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) { - if (m_count >= m_resultMax) { - return cp.getDistance(); - } - - if (cp.getDistance() <= 0) { - PhysicsDirectSpaceState3D::ShapeResult &result = m_results[m_count]; - // Penetrated - - CollisionObjectBullet *colObj; - if (m_self_object == colObj0Wrap->getCollisionObject()) { - colObj = static_cast<CollisionObjectBullet *>(colObj1Wrap->getCollisionObject()->getUserPointer()); - // Checking for compound shape because the index might be uninitialized otherwise. - // A partId of -1 indicates the index is a shape index and not a triangle index. - if (colObj1Wrap->getCollisionObject()->getCollisionShape()->isCompound() && cp.m_partId1 == -1) { - result.shape = cp.m_index1; - } else { - result.shape = 0; - } - } else { - colObj = static_cast<CollisionObjectBullet *>(colObj0Wrap->getCollisionObject()->getUserPointer()); - // Checking for compound shape because the index might be uninitialized otherwise. - // A partId of -1 indicates the index is a shape index and not a triangle index. - if (colObj0Wrap->getCollisionObject()->getCollisionShape()->isCompound() && cp.m_partId0 == -1) { - result.shape = cp.m_index0; - } else { - result.shape = 0; - } - } - - result.collider_id = colObj->get_instance_id(); - result.collider = result.collider_id.is_null() ? nullptr : ObjectDB::get_instance(result.collider_id); - result.rid = colObj->get_self(); - ++m_count; - } - - return cp.getDistance(); -} - -bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (m_count >= m_resultMax) { - return false; - } - - if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { - btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - - if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) { - return false; - } - } else { - if (!collide_with_bodies) { - return false; - } - } - - if (m_exclude->has(gObj->get_self())) { - return false; - } - return true; - } else { - return false; - } -} - -btScalar GodotContactPairContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) { - if (m_count >= m_resultMax) { - return 1; // not used by bullet - } - - if (m_self_object == colObj0Wrap->getCollisionObject()) { - B_TO_G(cp.m_localPointA, m_results[m_count * 2 + 0]); // Local contact - B_TO_G(cp.m_localPointB, m_results[m_count * 2 + 1]); - } else { - B_TO_G(cp.m_localPointB, m_results[m_count * 2 + 0]); // Local contact - B_TO_G(cp.m_localPointA, m_results[m_count * 2 + 1]); - } - - ++m_count; - - return 1; // Not used by bullet -} - -bool GodotRestInfoContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { - btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - - if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) { - if (!collide_with_areas) { - return false; - } - } else { - if (!collide_with_bodies) { - return false; - } - } - - if (m_exclude->has(gObj->get_self())) { - return false; - } - return true; - } else { - return false; - } -} - -btScalar GodotRestInfoContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) { - if (cp.getDistance() <= m_min_distance) { - m_min_distance = cp.getDistance(); - - CollisionObjectBullet *colObj; - if (m_self_object == colObj0Wrap->getCollisionObject()) { - colObj = static_cast<CollisionObjectBullet *>(colObj1Wrap->getCollisionObject()->getUserPointer()); - // Checking for compound shape because the index might be uninitialized otherwise. - // A partId of -1 indicates the index is a shape index and not a triangle index. - if (colObj1Wrap->getCollisionObject()->getCollisionShape()->isCompound() && cp.m_partId1 == -1) { - m_result->shape = cp.m_index1; - } else { - m_result->shape = 0; - } - B_TO_G(cp.getPositionWorldOnB(), m_result->point); - B_TO_G(cp.m_normalWorldOnB, m_result->normal); - m_rest_info_bt_point = cp.getPositionWorldOnB(); - m_rest_info_collision_object = colObj1Wrap->getCollisionObject(); - } else { - colObj = static_cast<CollisionObjectBullet *>(colObj0Wrap->getCollisionObject()->getUserPointer()); - // Checking for compound shape because the index might be uninitialized otherwise. - // A partId of -1 indicates the index is a shape index and not a triangle index. - if (colObj0Wrap->getCollisionObject()->getCollisionShape()->isCompound() && cp.m_partId0 == -1) { - m_result->shape = cp.m_index0; - } else { - m_result->shape = 0; - } - B_TO_G(cp.m_normalWorldOnB * -1, m_result->normal); - m_rest_info_bt_point = cp.getPositionWorldOnA(); - m_rest_info_collision_object = colObj0Wrap->getCollisionObject(); - } - - m_result->collider_id = colObj->get_instance_id(); - m_result->rid = colObj->get_self(); - - m_collided = true; - } - - return 1; // Not used by bullet -} - -void GodotDeepPenetrationContactResultCallback::addContactPoint(const btVector3 &normalOnBInWorld, const btVector3 &pointInWorldOnB, btScalar depth) { - if (m_penetration_distance > depth) { // Has penetration? - - const bool isSwapped = m_manifoldPtr->getBody0() != m_body0Wrap->getCollisionObject(); - m_penetration_distance = depth; - m_other_compound_shape_index = isSwapped ? m_index0 : m_index1; - m_pointWorld = isSwapped ? (pointInWorldOnB + (normalOnBInWorld * depth)) : pointInWorldOnB; - - m_pointNormalWorld = isSwapped ? normalOnBInWorld * -1 : normalOnBInWorld; - } -} diff --git a/modules/bullet/godot_result_callbacks.h b/modules/bullet/godot_result_callbacks.h deleted file mode 100644 index dd64762529..0000000000 --- a/modules/bullet/godot_result_callbacks.h +++ /dev/null @@ -1,225 +0,0 @@ -/*************************************************************************/ -/* godot_result_callbacks.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_RESULT_CALLBACKS_H -#define GODOT_RESULT_CALLBACKS_H - -#include "servers/physics_server_3d.h" - -#include <BulletCollision/BroadphaseCollision/btBroadphaseProxy.h> -#include <btBulletDynamicsCommon.h> - -class RigidBodyBullet; - -/// This callback is injected inside bullet server and allow me to smooth contacts against trimesh -bool godotContactAddedCallback(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1); - -/// This class is required to implement custom collision behaviour in the broadphase -struct GodotFilterCallback : public btOverlapFilterCallback { - // return true when pairs need collision - virtual bool needBroadphaseCollision(btBroadphaseProxy *proxy0, btBroadphaseProxy *proxy1) const; -}; - -/// It performs an additional check allow exclusions. -struct GodotClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback { - const Set<RID> *m_exclude; - bool m_pickRay = false; - int m_shapeId = 0; - - bool collide_with_bodies = false; - bool collide_with_areas = false; - -public: - GodotClosestRayResultCallback(const btVector3 &rayFromWorld, const btVector3 &rayToWorld, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) : - btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld), - m_exclude(p_exclude), - collide_with_bodies(p_collide_with_bodies), - collide_with_areas(p_collide_with_areas) {} - - virtual bool needsCollision(btBroadphaseProxy *proxy0) const; - - virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult &rayResult, bool normalInWorldSpace) { - // Triangle index is an odd name but contains the compound shape ID. - // A shape part of -1 indicates the index is a shape index and not a triangle index. - if (rayResult.m_localShapeInfo && rayResult.m_localShapeInfo->m_shapePart == -1) { - m_shapeId = rayResult.m_localShapeInfo->m_triangleIndex; - } else { - m_shapeId = 0; - } - return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace); - } -}; - -// store all colliding object -struct GodotAllConvexResultCallback : public btCollisionWorld::ConvexResultCallback { -public: - PhysicsDirectSpaceState3D::ShapeResult *m_results = nullptr; - int m_resultMax = 0; - const Set<RID> *m_exclude; - int count = 0; - - GodotAllConvexResultCallback(PhysicsDirectSpaceState3D::ShapeResult *p_results, int p_resultMax, const Set<RID> *p_exclude) : - m_results(p_results), - m_resultMax(p_resultMax), - m_exclude(p_exclude) {} - - virtual bool needsCollision(btBroadphaseProxy *proxy0) const; - - virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace); -}; - -struct GodotKinClosestConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback { -public: - const RigidBodyBullet *m_self_object; - const Set<RID> *m_exclude; - const bool m_infinite_inertia; - - GodotKinClosestConvexResultCallback(const btVector3 &convexFromWorld, const btVector3 &convexToWorld, const RigidBodyBullet *p_self_object, bool p_infinite_inertia, const Set<RID> *p_exclude) : - btCollisionWorld::ClosestConvexResultCallback(convexFromWorld, convexToWorld), - m_self_object(p_self_object), - m_exclude(p_exclude), - m_infinite_inertia(p_infinite_inertia) {} - - virtual bool needsCollision(btBroadphaseProxy *proxy0) const; -}; - -struct GodotClosestConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback { -public: - const Set<RID> *m_exclude; - int m_shapeId = 0; - - bool collide_with_bodies = false; - bool collide_with_areas = false; - - GodotClosestConvexResultCallback(const btVector3 &convexFromWorld, const btVector3 &convexToWorld, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) : - btCollisionWorld::ClosestConvexResultCallback(convexFromWorld, convexToWorld), - m_exclude(p_exclude), - collide_with_bodies(p_collide_with_bodies), - collide_with_areas(p_collide_with_areas) {} - - virtual bool needsCollision(btBroadphaseProxy *proxy0) const; - - virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace); -}; - -struct GodotAllContactResultCallback : public btCollisionWorld::ContactResultCallback { -public: - const btCollisionObject *m_self_object; - PhysicsDirectSpaceState3D::ShapeResult *m_results = nullptr; - int m_resultMax = 0; - const Set<RID> *m_exclude; - int m_count = 0; - - bool collide_with_bodies = false; - bool collide_with_areas = false; - - GodotAllContactResultCallback(btCollisionObject *p_self_object, PhysicsDirectSpaceState3D::ShapeResult *p_results, int p_resultMax, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) : - m_self_object(p_self_object), - m_results(p_results), - m_resultMax(p_resultMax), - m_exclude(p_exclude), - collide_with_bodies(p_collide_with_bodies), - collide_with_areas(p_collide_with_areas) {} - - virtual bool needsCollision(btBroadphaseProxy *proxy0) const; - - virtual btScalar addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1); -}; - -/// Returns the list of contacts pairs in this order: Local contact, other body contact -struct GodotContactPairContactResultCallback : public btCollisionWorld::ContactResultCallback { -public: - const btCollisionObject *m_self_object; - Vector3 *m_results = nullptr; - int m_resultMax = 0; - const Set<RID> *m_exclude; - int m_count = 0; - - bool collide_with_bodies = false; - bool collide_with_areas = false; - - GodotContactPairContactResultCallback(btCollisionObject *p_self_object, Vector3 *p_results, int p_resultMax, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) : - m_self_object(p_self_object), - m_results(p_results), - m_resultMax(p_resultMax), - m_exclude(p_exclude), - collide_with_bodies(p_collide_with_bodies), - collide_with_areas(p_collide_with_areas) {} - - virtual bool needsCollision(btBroadphaseProxy *proxy0) const; - - virtual btScalar addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1); -}; - -struct GodotRestInfoContactResultCallback : public btCollisionWorld::ContactResultCallback { -public: - const btCollisionObject *m_self_object; - PhysicsDirectSpaceState3D::ShapeRestInfo *m_result = nullptr; - const Set<RID> *m_exclude; - bool m_collided = false; - real_t m_min_distance = 0.0; - const btCollisionObject *m_rest_info_collision_object = nullptr; - btVector3 m_rest_info_bt_point; - bool collide_with_bodies = false; - bool collide_with_areas = false; - - GodotRestInfoContactResultCallback(btCollisionObject *p_self_object, PhysicsDirectSpaceState3D::ShapeRestInfo *p_result, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) : - m_self_object(p_self_object), - m_result(p_result), - m_exclude(p_exclude), - collide_with_bodies(p_collide_with_bodies), - collide_with_areas(p_collide_with_areas) {} - - virtual bool needsCollision(btBroadphaseProxy *proxy0) const; - - virtual btScalar addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1); -}; - -struct GodotDeepPenetrationContactResultCallback : public btManifoldResult { - btVector3 m_pointNormalWorld; - btVector3 m_pointWorld; - btScalar m_penetration_distance = 0; - int m_other_compound_shape_index = 0; - - GodotDeepPenetrationContactResultCallback(const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap) : - btManifoldResult(body0Wrap, body1Wrap) {} - - void reset() { - m_penetration_distance = 0; - } - - bool hasHit() { - return m_penetration_distance < 0; - } - - virtual void addContactPoint(const btVector3 &normalOnBInWorld, const btVector3 &pointInWorldOnB, btScalar depth); -}; - -#endif // GODOT_RESULT_CALLBACKS_H diff --git a/modules/bullet/hinge_joint_bullet.cpp b/modules/bullet/hinge_joint_bullet.cpp deleted file mode 100644 index 0b1bb7890d..0000000000 --- a/modules/bullet/hinge_joint_bullet.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/*************************************************************************/ -/* hinge_joint_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "hinge_joint_bullet.h" - -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "rigid_body_bullet.h" - -#include <BulletDynamics/ConstraintSolver/btHingeConstraint.h> - -HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameA, const Transform3D &frameB) : - JointBullet() { - Transform3D scaled_AFrame(frameA.scaled(rbA->get_body_scale())); - scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); - - btTransform btFrameA; - G_TO_B(scaled_AFrame, btFrameA); - - if (rbB) { - Transform3D scaled_BFrame(frameB.scaled(rbB->get_body_scale())); - scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); - - btTransform btFrameB; - G_TO_B(scaled_BFrame, btFrameB); - - hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btFrameA, btFrameB)); - } else { - hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), btFrameA)); - } - - setup(hingeConstraint); -} - -HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, const Vector3 &axisInA, const Vector3 &axisInB) : - JointBullet() { - btVector3 btPivotA; - btVector3 btAxisA; - G_TO_B(pivotInA * rbA->get_body_scale(), btPivotA); - G_TO_B(axisInA * rbA->get_body_scale(), btAxisA); - - if (rbB) { - btVector3 btPivotB; - btVector3 btAxisB; - G_TO_B(pivotInB * rbB->get_body_scale(), btPivotB); - G_TO_B(axisInB * rbB->get_body_scale(), btAxisB); - - hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btPivotA, btPivotB, btAxisA, btAxisB)); - } else { - hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), btPivotA, btAxisA)); - } - - setup(hingeConstraint); -} - -real_t HingeJointBullet::get_hinge_angle() { - return hingeConstraint->getHingeAngle(); -} - -void HingeJointBullet::set_param(PhysicsServer3D::HingeJointParam p_param, real_t p_value) { - switch (p_param) { - case PhysicsServer3D::HINGE_JOINT_BIAS: - WARN_DEPRECATED_MSG("The HingeJoint3D parameter \"bias\" is deprecated."); - break; - case PhysicsServer3D::HINGE_JOINT_LIMIT_UPPER: - hingeConstraint->setLimit(hingeConstraint->getLowerLimit(), p_value, hingeConstraint->getLimitSoftness(), hingeConstraint->getLimitBiasFactor(), hingeConstraint->getLimitRelaxationFactor()); - break; - case PhysicsServer3D::HINGE_JOINT_LIMIT_LOWER: - hingeConstraint->setLimit(p_value, hingeConstraint->getUpperLimit(), hingeConstraint->getLimitSoftness(), hingeConstraint->getLimitBiasFactor(), hingeConstraint->getLimitRelaxationFactor()); - break; - case PhysicsServer3D::HINGE_JOINT_LIMIT_BIAS: - hingeConstraint->setLimit(hingeConstraint->getLowerLimit(), hingeConstraint->getUpperLimit(), hingeConstraint->getLimitSoftness(), p_value, hingeConstraint->getLimitRelaxationFactor()); - break; - case PhysicsServer3D::HINGE_JOINT_LIMIT_SOFTNESS: - hingeConstraint->setLimit(hingeConstraint->getLowerLimit(), hingeConstraint->getUpperLimit(), p_value, hingeConstraint->getLimitBiasFactor(), hingeConstraint->getLimitRelaxationFactor()); - break; - case PhysicsServer3D::HINGE_JOINT_LIMIT_RELAXATION: - hingeConstraint->setLimit(hingeConstraint->getLowerLimit(), hingeConstraint->getUpperLimit(), hingeConstraint->getLimitSoftness(), hingeConstraint->getLimitBiasFactor(), p_value); - break; - case PhysicsServer3D::HINGE_JOINT_MOTOR_TARGET_VELOCITY: - hingeConstraint->setMotorTargetVelocity(p_value); - break; - case PhysicsServer3D::HINGE_JOINT_MOTOR_MAX_IMPULSE: - hingeConstraint->setMaxMotorImpulse(p_value); - break; - case PhysicsServer3D::HINGE_JOINT_MAX: - // Internal size value, nothing to do. - break; - } -} - -real_t HingeJointBullet::get_param(PhysicsServer3D::HingeJointParam p_param) const { - switch (p_param) { - case PhysicsServer3D::HINGE_JOINT_BIAS: - WARN_DEPRECATED_MSG("The HingeJoint3D parameter \"bias\" is deprecated."); - return 0; - case PhysicsServer3D::HINGE_JOINT_LIMIT_UPPER: - return hingeConstraint->getUpperLimit(); - case PhysicsServer3D::HINGE_JOINT_LIMIT_LOWER: - return hingeConstraint->getLowerLimit(); - case PhysicsServer3D::HINGE_JOINT_LIMIT_BIAS: - return hingeConstraint->getLimitBiasFactor(); - case PhysicsServer3D::HINGE_JOINT_LIMIT_SOFTNESS: - return hingeConstraint->getLimitSoftness(); - case PhysicsServer3D::HINGE_JOINT_LIMIT_RELAXATION: - return hingeConstraint->getLimitRelaxationFactor(); - case PhysicsServer3D::HINGE_JOINT_MOTOR_TARGET_VELOCITY: - return hingeConstraint->getMotorTargetVelocity(); - case PhysicsServer3D::HINGE_JOINT_MOTOR_MAX_IMPULSE: - return hingeConstraint->getMaxMotorImpulse(); - case PhysicsServer3D::HINGE_JOINT_MAX: - // Internal size value, nothing to do. - return 0; - } - // Compiler doesn't seem to notice that all code paths are fulfilled... - return 0; -} - -void HingeJointBullet::set_flag(PhysicsServer3D::HingeJointFlag p_flag, bool p_value) { - switch (p_flag) { - case PhysicsServer3D::HINGE_JOINT_FLAG_USE_LIMIT: - if (!p_value) { - hingeConstraint->setLimit(-Math_PI, Math_PI); - } - break; - case PhysicsServer3D::HINGE_JOINT_FLAG_ENABLE_MOTOR: - hingeConstraint->enableMotor(p_value); - break; - case PhysicsServer3D::HINGE_JOINT_FLAG_MAX: - break; // Can't happen, but silences warning - } -} - -bool HingeJointBullet::get_flag(PhysicsServer3D::HingeJointFlag p_flag) const { - switch (p_flag) { - case PhysicsServer3D::HINGE_JOINT_FLAG_USE_LIMIT: - return true; - case PhysicsServer3D::HINGE_JOINT_FLAG_ENABLE_MOTOR: - return hingeConstraint->getEnableAngularMotor(); - default: - return false; - } -} diff --git a/modules/bullet/hinge_joint_bullet.h b/modules/bullet/hinge_joint_bullet.h deleted file mode 100644 index 5575be564f..0000000000 --- a/modules/bullet/hinge_joint_bullet.h +++ /dev/null @@ -1,54 +0,0 @@ -/*************************************************************************/ -/* hinge_joint_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 HINGE_JOINT_BULLET_H -#define HINGE_JOINT_BULLET_H - -#include "joint_bullet.h" - -class HingeJointBullet : public JointBullet { - class btHingeConstraint *hingeConstraint; - -public: - HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameA, const Transform3D &frameB); - HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, const Vector3 &axisInA, const Vector3 &axisInB); - - virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_HINGE; } - - real_t get_hinge_angle(); - - void set_param(PhysicsServer3D::HingeJointParam p_param, real_t p_value); - real_t get_param(PhysicsServer3D::HingeJointParam p_param) const; - - void set_flag(PhysicsServer3D::HingeJointFlag p_flag, bool p_value); - bool get_flag(PhysicsServer3D::HingeJointFlag p_flag) const; -}; - -#endif // HINGE_JOINT_BULLET_H diff --git a/modules/bullet/pin_joint_bullet.cpp b/modules/bullet/pin_joint_bullet.cpp deleted file mode 100644 index 72fdd5c408..0000000000 --- a/modules/bullet/pin_joint_bullet.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/*************************************************************************/ -/* pin_joint_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "pin_joint_bullet.h" - -#include "bullet_types_converter.h" -#include "rigid_body_bullet.h" - -#include <BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h> - -PinJointBullet::PinJointBullet(RigidBodyBullet *p_body_a, const Vector3 &p_pos_a, RigidBodyBullet *p_body_b, const Vector3 &p_pos_b) : - JointBullet() { - if (p_body_b) { - btVector3 btPivotA; - btVector3 btPivotB; - G_TO_B(p_pos_a * p_body_a->get_body_scale(), btPivotA); - G_TO_B(p_pos_b * p_body_b->get_body_scale(), btPivotB); - p2pConstraint = bulletnew(btPoint2PointConstraint(*p_body_a->get_bt_rigid_body(), - *p_body_b->get_bt_rigid_body(), - btPivotA, - btPivotB)); - } else { - btVector3 btPivotA; - G_TO_B(p_pos_a, btPivotA); - p2pConstraint = bulletnew(btPoint2PointConstraint(*p_body_a->get_bt_rigid_body(), btPivotA)); - } - - setup(p2pConstraint); -} - -PinJointBullet::~PinJointBullet() {} - -void PinJointBullet::set_param(PhysicsServer3D::PinJointParam p_param, real_t p_value) { - switch (p_param) { - case PhysicsServer3D::PIN_JOINT_BIAS: - p2pConstraint->m_setting.m_tau = p_value; - break; - case PhysicsServer3D::PIN_JOINT_DAMPING: - p2pConstraint->m_setting.m_damping = p_value; - break; - case PhysicsServer3D::PIN_JOINT_IMPULSE_CLAMP: - p2pConstraint->m_setting.m_impulseClamp = p_value; - break; - } -} - -real_t PinJointBullet::get_param(PhysicsServer3D::PinJointParam p_param) const { - switch (p_param) { - case PhysicsServer3D::PIN_JOINT_BIAS: - return p2pConstraint->m_setting.m_tau; - case PhysicsServer3D::PIN_JOINT_DAMPING: - return p2pConstraint->m_setting.m_damping; - case PhysicsServer3D::PIN_JOINT_IMPULSE_CLAMP: - return p2pConstraint->m_setting.m_impulseClamp; - } - // Compiler doesn't seem to notice that all code paths are fulfilled... - return 0; -} - -void PinJointBullet::setPivotInA(const Vector3 &p_pos) { - btVector3 btVec; - G_TO_B(p_pos, btVec); - p2pConstraint->setPivotA(btVec); -} - -void PinJointBullet::setPivotInB(const Vector3 &p_pos) { - btVector3 btVec; - G_TO_B(p_pos, btVec); - p2pConstraint->setPivotB(btVec); -} - -Vector3 PinJointBullet::getPivotInA() { - btVector3 vec = p2pConstraint->getPivotInA(); - Vector3 gVec; - B_TO_G(vec, gVec); - return gVec; -} - -Vector3 PinJointBullet::getPivotInB() { - btVector3 vec = p2pConstraint->getPivotInB(); - Vector3 gVec; - B_TO_G(vec, gVec); - return gVec; -} diff --git a/modules/bullet/pin_joint_bullet.h b/modules/bullet/pin_joint_bullet.h deleted file mode 100644 index 0a688d55f9..0000000000 --- a/modules/bullet/pin_joint_bullet.h +++ /dev/null @@ -1,57 +0,0 @@ -/*************************************************************************/ -/* pin_joint_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 PIN_JOINT_BULLET_H -#define PIN_JOINT_BULLET_H - -#include "joint_bullet.h" - -class RigidBodyBullet; - -class PinJointBullet : public JointBullet { - class btPoint2PointConstraint *p2pConstraint; - -public: - PinJointBullet(RigidBodyBullet *p_body_a, const Vector3 &p_pos_a, RigidBodyBullet *p_body_b, const Vector3 &p_pos_b); - ~PinJointBullet(); - - virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_PIN; } - - void set_param(PhysicsServer3D::PinJointParam p_param, real_t p_value); - real_t get_param(PhysicsServer3D::PinJointParam p_param) const; - - void setPivotInA(const Vector3 &p_pos); - void setPivotInB(const Vector3 &p_pos); - - Vector3 getPivotInA(); - Vector3 getPivotInB(); -}; - -#endif // PIN_JOINT_BULLET_H diff --git a/modules/bullet/register_types.cpp b/modules/bullet/register_types.cpp deleted file mode 100644 index d5d0ee2cf4..0000000000 --- a/modules/bullet/register_types.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/*************************************************************************/ -/* register_types.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "bullet_physics_server.h" -#include "core/config/project_settings.h" -#include "core/object/class_db.h" - -#ifndef _3D_DISABLED -PhysicsServer3D *_createBulletPhysicsCallback() { - return memnew(BulletPhysicsServer3D); -} -#endif - -void register_bullet_types() { -#ifndef _3D_DISABLED - PhysicsServer3DManager::register_server("Bullet", &_createBulletPhysicsCallback); - PhysicsServer3DManager::set_default_server("Bullet", 1); - - GLOBAL_DEF("physics/3d/active_soft_world", true); - ProjectSettings::get_singleton()->set_custom_property_info("physics/3d/active_soft_world", PropertyInfo(Variant::BOOL, "physics/3d/active_soft_world")); -#endif -} - -void unregister_bullet_types() { -} diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp deleted file mode 100644 index 0603963332..0000000000 --- a/modules/bullet/rigid_body_bullet.cpp +++ /dev/null @@ -1,1050 +0,0 @@ -/*************************************************************************/ -/* rigid_body_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "rigid_body_bullet.h" - -#include "btRayShape.h" -#include "bullet_physics_server.h" -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "godot_motion_state.h" -#include "joint_bullet.h" - -#include <BulletCollision/CollisionDispatch/btGhostObject.h> -#include <BulletCollision/CollisionShapes/btConvexPointCloudShape.h> -#include <BulletDynamics/Dynamics/btRigidBody.h> -#include <btBulletCollisionCommon.h> - -BulletPhysicsDirectBodyState3D *BulletPhysicsDirectBodyState3D::singleton = nullptr; - -Vector3 BulletPhysicsDirectBodyState3D::get_total_gravity() const { - Vector3 gVec; - B_TO_G(body->btBody->getGravity(), gVec); - return gVec; -} - -real_t BulletPhysicsDirectBodyState3D::get_total_angular_damp() const { - return body->btBody->getAngularDamping(); -} - -real_t BulletPhysicsDirectBodyState3D::get_total_linear_damp() const { - return body->btBody->getLinearDamping(); -} - -Vector3 BulletPhysicsDirectBodyState3D::get_center_of_mass() const { - Vector3 gVec; - B_TO_G(body->btBody->getCenterOfMassPosition(), gVec); - return gVec; -} - -Basis BulletPhysicsDirectBodyState3D::get_principal_inertia_axes() const { - return Basis(); -} - -real_t BulletPhysicsDirectBodyState3D::get_inverse_mass() const { - return body->btBody->getInvMass(); -} - -Vector3 BulletPhysicsDirectBodyState3D::get_inverse_inertia() const { - Vector3 gVec; - B_TO_G(body->btBody->getInvInertiaDiagLocal(), gVec); - return gVec; -} - -Basis BulletPhysicsDirectBodyState3D::get_inverse_inertia_tensor() const { - Basis gInertia; - B_TO_G(body->btBody->getInvInertiaTensorWorld(), gInertia); - return gInertia; -} - -void BulletPhysicsDirectBodyState3D::set_linear_velocity(const Vector3 &p_velocity) { - body->set_linear_velocity(p_velocity); -} - -Vector3 BulletPhysicsDirectBodyState3D::get_linear_velocity() const { - return body->get_linear_velocity(); -} - -void BulletPhysicsDirectBodyState3D::set_angular_velocity(const Vector3 &p_velocity) { - body->set_angular_velocity(p_velocity); -} - -Vector3 BulletPhysicsDirectBodyState3D::get_angular_velocity() const { - return body->get_angular_velocity(); -} - -void BulletPhysicsDirectBodyState3D::set_transform(const Transform3D &p_transform) { - body->set_transform(p_transform); -} - -Transform3D BulletPhysicsDirectBodyState3D::get_transform() const { - return body->get_transform(); -} - -Vector3 BulletPhysicsDirectBodyState3D::get_velocity_at_local_position(const Vector3 &p_position) const { - btVector3 local_position; - G_TO_B(p_position, local_position); - - Vector3 velocity; - B_TO_G(body->btBody->getVelocityInLocalPoint(local_position), velocity); - - return velocity; -} - -void BulletPhysicsDirectBodyState3D::add_central_force(const Vector3 &p_force) { - body->apply_central_force(p_force); -} - -void BulletPhysicsDirectBodyState3D::add_force(const Vector3 &p_force, const Vector3 &p_position) { - body->apply_force(p_force, p_position); -} - -void BulletPhysicsDirectBodyState3D::add_torque(const Vector3 &p_torque) { - body->apply_torque(p_torque); -} - -void BulletPhysicsDirectBodyState3D::apply_central_impulse(const Vector3 &p_impulse) { - body->apply_central_impulse(p_impulse); -} - -void BulletPhysicsDirectBodyState3D::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) { - body->apply_impulse(p_impulse, p_position); -} - -void BulletPhysicsDirectBodyState3D::apply_torque_impulse(const Vector3 &p_impulse) { - body->apply_torque_impulse(p_impulse); -} - -void BulletPhysicsDirectBodyState3D::set_sleep_state(bool p_sleep) { - body->set_activation_state(!p_sleep); -} - -bool BulletPhysicsDirectBodyState3D::is_sleeping() const { - return !body->is_active(); -} - -int BulletPhysicsDirectBodyState3D::get_contact_count() const { - return body->collisionsCount; -} - -Vector3 BulletPhysicsDirectBodyState3D::get_contact_local_position(int p_contact_idx) const { - return body->collisions[p_contact_idx].hitLocalLocation; -} - -Vector3 BulletPhysicsDirectBodyState3D::get_contact_local_normal(int p_contact_idx) const { - return body->collisions[p_contact_idx].hitNormal; -} - -real_t BulletPhysicsDirectBodyState3D::get_contact_impulse(int p_contact_idx) const { - return body->collisions[p_contact_idx].appliedImpulse; -} - -int BulletPhysicsDirectBodyState3D::get_contact_local_shape(int p_contact_idx) const { - return body->collisions[p_contact_idx].local_shape; -} - -RID BulletPhysicsDirectBodyState3D::get_contact_collider(int p_contact_idx) const { - return body->collisions[p_contact_idx].otherObject->get_self(); -} - -Vector3 BulletPhysicsDirectBodyState3D::get_contact_collider_position(int p_contact_idx) const { - return body->collisions[p_contact_idx].hitWorldLocation; -} - -ObjectID BulletPhysicsDirectBodyState3D::get_contact_collider_id(int p_contact_idx) const { - return body->collisions[p_contact_idx].otherObject->get_instance_id(); -} - -int BulletPhysicsDirectBodyState3D::get_contact_collider_shape(int p_contact_idx) const { - return body->collisions[p_contact_idx].other_object_shape; -} - -Vector3 BulletPhysicsDirectBodyState3D::get_contact_collider_velocity_at_position(int p_contact_idx) const { - RigidBodyBullet::CollisionData &colDat = body->collisions.write[p_contact_idx]; - - btVector3 hitLocation; - G_TO_B(colDat.hitLocalLocation, hitLocation); - - Vector3 velocityAtPoint; - B_TO_G(colDat.otherObject->get_bt_rigid_body()->getVelocityInLocalPoint(hitLocation), velocityAtPoint); - - return velocityAtPoint; -} - -PhysicsDirectSpaceState3D *BulletPhysicsDirectBodyState3D::get_space_state() { - return body->get_space()->get_direct_state(); -} - -RigidBodyBullet::KinematicUtilities::KinematicUtilities(RigidBodyBullet *p_owner) : - owner(p_owner), - safe_margin(0.001) { -} - -RigidBodyBullet::KinematicUtilities::~KinematicUtilities() { - just_delete_shapes(shapes.size()); // don't need to resize -} - -void RigidBodyBullet::KinematicUtilities::setSafeMargin(btScalar p_margin) { - safe_margin = p_margin; - copyAllOwnerShapes(); -} - -void RigidBodyBullet::KinematicUtilities::copyAllOwnerShapes() { - const Vector<CollisionObjectBullet::ShapeWrapper> &shapes_wrappers(owner->get_shapes_wrappers()); - const int shapes_count = shapes_wrappers.size(); - - just_delete_shapes(shapes_count); - - const CollisionObjectBullet::ShapeWrapper *shape_wrapper; - - btVector3 owner_scale(owner->get_bt_body_scale()); - - for (int i = shapes_count - 1; 0 <= i; --i) { - shape_wrapper = &shapes_wrappers[i]; - if (!shape_wrapper->active) { - continue; - } - - shapes.write[i].transform = shape_wrapper->transform; - shapes.write[i].transform.getOrigin() *= owner_scale; - switch (shape_wrapper->shape->get_type()) { - case PhysicsServer3D::SHAPE_SPHERE: - case PhysicsServer3D::SHAPE_BOX: - case PhysicsServer3D::SHAPE_CAPSULE: - case PhysicsServer3D::SHAPE_CYLINDER: - case PhysicsServer3D::SHAPE_CONVEX_POLYGON: - case PhysicsServer3D::SHAPE_RAY: { - shapes.write[i].shape = static_cast<btConvexShape *>(shape_wrapper->shape->create_bt_shape(owner_scale * shape_wrapper->scale, safe_margin)); - } break; - default: - WARN_PRINT("This shape is not supported for kinematic collision."); - shapes.write[i].shape = nullptr; - } - } -} - -void RigidBodyBullet::KinematicUtilities::just_delete_shapes(int new_size) { - for (int i = shapes.size() - 1; 0 <= i; --i) { - if (shapes[i].shape) { - bulletdelete(shapes.write[i].shape); - } - } - shapes.resize(new_size); -} - -RigidBodyBullet::RigidBodyBullet() : - RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_RIGID_BODY) { - godotMotionState = bulletnew(GodotMotionState(this)); - - // Initial properties - const btVector3 localInertia(0, 0, 0); - btRigidBody::btRigidBodyConstructionInfo cInfo(mass, godotMotionState, nullptr, localInertia); - - btBody = bulletnew(btRigidBody(cInfo)); - btBody->setFriction(1.0); - reload_shapes(); - setupBulletCollisionObject(btBody); - - set_mode(PhysicsServer3D::BODY_MODE_DYNAMIC); - reload_axis_lock(); - - areasWhereIam.resize(maxAreasWhereIam); - for (int i = areasWhereIam.size() - 1; 0 <= i; --i) { - areasWhereIam.write[i] = nullptr; - } - btBody->setSleepingThresholds(0.2, 0.2); - - prev_collision_traces = &collision_traces_1; - curr_collision_traces = &collision_traces_2; -} - -RigidBodyBullet::~RigidBodyBullet() { - bulletdelete(godotMotionState); - - if (force_integration_callback) { - memdelete(force_integration_callback); - } - - destroy_kinematic_utilities(); -} - -void RigidBodyBullet::init_kinematic_utilities() { - kinematic_utilities = memnew(KinematicUtilities(this)); - reload_kinematic_shapes(); -} - -void RigidBodyBullet::destroy_kinematic_utilities() { - if (kinematic_utilities) { - memdelete(kinematic_utilities); - kinematic_utilities = nullptr; - } -} - -void RigidBodyBullet::main_shape_changed() { - CRASH_COND(!get_main_shape()); - btBody->setCollisionShape(get_main_shape()); - set_continuous_collision_detection(is_continuous_collision_detection_enabled()); // Reset -} - -void RigidBodyBullet::reload_body() { - if (space) { - space->remove_rigid_body(this); - if (get_main_shape()) { - space->add_rigid_body(this); - } - } -} - -void RigidBodyBullet::set_space(SpaceBullet *p_space) { - // Clear the old space if there is one - if (space) { - can_integrate_forces = false; - isScratchedSpaceOverrideModificator = false; - // Remove any constraints - space->remove_rigid_body_constraints(this); - // Remove this object form the physics world - space->remove_rigid_body(this); - } - - space = p_space; - - if (space) { - space->add_rigid_body(this); - } -} - -void RigidBodyBullet::dispatch_callbacks() { - /// The check isFirstTransformChanged is necessary in order to call integrated forces only when the first transform is sent - if ((btBody->isKinematicObject() || btBody->isActive() || previousActiveState != btBody->isActive()) && force_integration_callback && can_integrate_forces) { - if (omit_forces_integration) { - btBody->clearForces(); - } - - BulletPhysicsDirectBodyState3D *bodyDirect = BulletPhysicsDirectBodyState3D::get_singleton(this); - - Variant variantBodyDirect = bodyDirect; - - Object *obj = force_integration_callback->callable.get_object(); - if (!obj) { - // Remove integration callback - set_force_integration_callback(Callable()); - } else { - const Variant *vp[2] = { &variantBodyDirect, &force_integration_callback->udata }; - - Callable::CallError responseCallError; - int argc = (force_integration_callback->udata.get_type() == Variant::NIL) ? 1 : 2; - Variant rv; - force_integration_callback->callable.call(vp, argc, rv, responseCallError); - } - } - - if (isScratchedSpaceOverrideModificator || 0 < countGravityPointSpaces) { - isScratchedSpaceOverrideModificator = false; - reload_space_override_modificator(); - } - - /// Lock axis - btBody->setLinearVelocity(btBody->getLinearVelocity() * btBody->getLinearFactor()); - btBody->setAngularVelocity(btBody->getAngularVelocity() * btBody->getAngularFactor()); - - previousActiveState = btBody->isActive(); -} - -void RigidBodyBullet::set_force_integration_callback(const Callable &p_callable, const Variant &p_udata) { - if (force_integration_callback) { - memdelete(force_integration_callback); - force_integration_callback = nullptr; - } - - if (p_callable.get_object()) { - force_integration_callback = memnew(ForceIntegrationCallback); - force_integration_callback->callable = p_callable; - force_integration_callback->udata = p_udata; - } -} - -void RigidBodyBullet::scratch_space_override_modificator() { - isScratchedSpaceOverrideModificator = true; -} - -void RigidBodyBullet::on_collision_filters_change() { - if (space) { - space->reload_collision_filters(this); - } - - set_activation_state(true); -} - -void RigidBodyBullet::on_collision_checker_start() { - prev_collision_count = collisionsCount; - collisionsCount = 0; - - // Swap array - Vector<RigidBodyBullet *> *s = prev_collision_traces; - prev_collision_traces = curr_collision_traces; - curr_collision_traces = s; -} - -void RigidBodyBullet::on_collision_checker_end() { - // Always true if active and not a static or kinematic body - updated = btBody->isActive() && !btBody->isStaticOrKinematicObject(); -} - -bool RigidBodyBullet::add_collision_object(RigidBodyBullet *p_otherObject, const Vector3 &p_hitWorldLocation, const Vector3 &p_hitLocalLocation, const Vector3 &p_hitNormal, const real_t &p_appliedImpulse, int p_other_shape_index, int p_local_shape_index) { - if (collisionsCount >= maxCollisionsDetection) { - return false; - } - - CollisionData &cd = collisions.write[collisionsCount]; - cd.hitLocalLocation = p_hitLocalLocation; - cd.otherObject = p_otherObject; - cd.hitWorldLocation = p_hitWorldLocation; - cd.hitNormal = p_hitNormal; - cd.appliedImpulse = p_appliedImpulse; - cd.other_object_shape = p_other_shape_index; - cd.local_shape = p_local_shape_index; - - curr_collision_traces->write[collisionsCount] = p_otherObject; - - ++collisionsCount; - return true; -} - -bool RigidBodyBullet::was_colliding(RigidBodyBullet *p_other_object) { - for (int i = prev_collision_count - 1; 0 <= i; --i) { - if ((*prev_collision_traces)[i] == p_other_object) { - return true; - } - } - return false; -} - -void RigidBodyBullet::set_activation_state(bool p_active) { - if (p_active) { - btBody->activate(); - } else { - btBody->setActivationState(WANTS_DEACTIVATION); - } -} - -bool RigidBodyBullet::is_active() const { - return btBody->isActive(); -} - -void RigidBodyBullet::set_omit_forces_integration(bool p_omit) { - omit_forces_integration = p_omit; -} - -void RigidBodyBullet::set_param(PhysicsServer3D::BodyParameter p_param, real_t p_value) { - switch (p_param) { - case PhysicsServer3D::BODY_PARAM_BOUNCE: - btBody->setRestitution(p_value); - break; - case PhysicsServer3D::BODY_PARAM_FRICTION: - btBody->setFriction(p_value); - break; - case PhysicsServer3D::BODY_PARAM_MASS: { - ERR_FAIL_COND(p_value < 0); - mass = p_value; - _internal_set_mass(p_value); - break; - } - case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP: - linearDamp = p_value; - // Mark for updating total linear damping. - scratch_space_override_modificator(); - break; - case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP: - angularDamp = p_value; - // Mark for updating total angular damping. - scratch_space_override_modificator(); - break; - case PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE: - gravity_scale = p_value; - // The Bullet gravity will be is set by reload_space_override_modificator. - // Mark for updating total gravity scale. - scratch_space_override_modificator(); - break; - default: - WARN_PRINT("Parameter " + itos(p_param) + " not supported by bullet. Value: " + itos(p_value)); - } -} - -real_t RigidBodyBullet::get_param(PhysicsServer3D::BodyParameter p_param) const { - switch (p_param) { - case PhysicsServer3D::BODY_PARAM_BOUNCE: - return btBody->getRestitution(); - case PhysicsServer3D::BODY_PARAM_FRICTION: - return btBody->getFriction(); - case PhysicsServer3D::BODY_PARAM_MASS: { - const btScalar invMass = btBody->getInvMass(); - return 0 == invMass ? 0 : 1 / invMass; - } - case PhysicsServer3D::BODY_PARAM_LINEAR_DAMP: - return linearDamp; - case PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP: - return angularDamp; - case PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE: - return gravity_scale; - default: - WARN_PRINT("Parameter " + itos(p_param) + " not supported by bullet"); - return 0; - } -} - -void RigidBodyBullet::set_mode(PhysicsServer3D::BodyMode p_mode) { - // This is necessary to block force_integration until next move - can_integrate_forces = false; - destroy_kinematic_utilities(); - // The mode change is relevant to its mass - mode = p_mode; - switch (p_mode) { - case PhysicsServer3D::BODY_MODE_KINEMATIC: - reload_axis_lock(); - _internal_set_mass(0); - init_kinematic_utilities(); - break; - case PhysicsServer3D::BODY_MODE_STATIC: - reload_axis_lock(); - _internal_set_mass(0); - break; - case PhysicsServer3D::BODY_MODE_DYNAMIC: - reload_axis_lock(); - _internal_set_mass(0 == mass ? 1 : mass); - scratch_space_override_modificator(); - break; - case PhysicsServer3D::MODE_DYNAMIC_LINEAR: - reload_axis_lock(); - _internal_set_mass(0 == mass ? 1 : mass); - scratch_space_override_modificator(); - break; - } - - btBody->setAngularVelocity(btVector3(0, 0, 0)); - btBody->setLinearVelocity(btVector3(0, 0, 0)); -} - -PhysicsServer3D::BodyMode RigidBodyBullet::get_mode() const { - return mode; -} - -void RigidBodyBullet::set_state(PhysicsServer3D::BodyState p_state, const Variant &p_variant) { - switch (p_state) { - case PhysicsServer3D::BODY_STATE_TRANSFORM: - set_transform(p_variant); - break; - case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: - set_linear_velocity(p_variant); - break; - case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: - set_angular_velocity(p_variant); - break; - case PhysicsServer3D::BODY_STATE_SLEEPING: - set_activation_state(!bool(p_variant)); - break; - case PhysicsServer3D::BODY_STATE_CAN_SLEEP: - can_sleep = bool(p_variant); - if (!can_sleep) { - // Can't sleep - btBody->forceActivationState(DISABLE_DEACTIVATION); - } else { - btBody->forceActivationState(ACTIVE_TAG); - } - break; - } -} - -Variant RigidBodyBullet::get_state(PhysicsServer3D::BodyState p_state) const { - switch (p_state) { - case PhysicsServer3D::BODY_STATE_TRANSFORM: - return get_transform(); - case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: - return get_linear_velocity(); - case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: - return get_angular_velocity(); - case PhysicsServer3D::BODY_STATE_SLEEPING: - return !is_active(); - case PhysicsServer3D::BODY_STATE_CAN_SLEEP: - return can_sleep; - default: - WARN_PRINT("This state " + itos(p_state) + " is not supported by Bullet"); - return Variant(); - } -} - -void RigidBodyBullet::apply_central_impulse(const Vector3 &p_impulse) { - btVector3 btImpulse; - G_TO_B(p_impulse, btImpulse); - if (Vector3() != p_impulse) { - btBody->activate(); - } - btBody->applyCentralImpulse(btImpulse); -} - -void RigidBodyBullet::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) { - btVector3 btImpulse; - btVector3 btPosition; - G_TO_B(p_impulse, btImpulse); - G_TO_B(p_position, btPosition); - if (Vector3() != p_impulse) { - btBody->activate(); - } - btBody->applyImpulse(btImpulse, btPosition); -} - -void RigidBodyBullet::apply_torque_impulse(const Vector3 &p_impulse) { - btVector3 btImp; - G_TO_B(p_impulse, btImp); - if (Vector3() != p_impulse) { - btBody->activate(); - } - btBody->applyTorqueImpulse(btImp); -} - -void RigidBodyBullet::apply_force(const Vector3 &p_force, const Vector3 &p_position) { - btVector3 btForce; - btVector3 btPosition; - G_TO_B(p_force, btForce); - G_TO_B(p_position, btPosition); - if (Vector3() != p_force) { - btBody->activate(); - } - btBody->applyForce(btForce, btPosition); -} - -void RigidBodyBullet::apply_central_force(const Vector3 &p_force) { - btVector3 btForce; - G_TO_B(p_force, btForce); - if (Vector3() != p_force) { - btBody->activate(); - } - btBody->applyCentralForce(btForce); -} - -void RigidBodyBullet::apply_torque(const Vector3 &p_torque) { - btVector3 btTorq; - G_TO_B(p_torque, btTorq); - if (Vector3() != p_torque) { - btBody->activate(); - } - btBody->applyTorque(btTorq); -} - -void RigidBodyBullet::set_applied_force(const Vector3 &p_force) { - btVector3 btVec = btBody->getTotalTorque(); - - if (Vector3() != p_force) { - btBody->activate(); - } - - btBody->clearForces(); - btBody->applyTorque(btVec); - - G_TO_B(p_force, btVec); - btBody->applyCentralForce(btVec); -} - -Vector3 RigidBodyBullet::get_applied_force() const { - Vector3 gTotForc; - B_TO_G(btBody->getTotalForce(), gTotForc); - return gTotForc; -} - -void RigidBodyBullet::set_applied_torque(const Vector3 &p_torque) { - btVector3 btVec = btBody->getTotalForce(); - - if (Vector3() != p_torque) { - btBody->activate(); - } - - btBody->clearForces(); - btBody->applyCentralForce(btVec); - - G_TO_B(p_torque, btVec); - btBody->applyTorque(btVec); -} - -Vector3 RigidBodyBullet::get_applied_torque() const { - Vector3 gTotTorq; - B_TO_G(btBody->getTotalTorque(), gTotTorq); - return gTotTorq; -} - -void RigidBodyBullet::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool lock) { - if (lock) { - locked_axis |= p_axis; - } else { - locked_axis &= ~p_axis; - } - - reload_axis_lock(); -} - -bool RigidBodyBullet::is_axis_locked(PhysicsServer3D::BodyAxis p_axis) const { - return locked_axis & p_axis; -} - -void RigidBodyBullet::reload_axis_lock() { - btBody->setLinearFactor(btVector3(btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_X)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Y)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Z)))); - if (PhysicsServer3D::MODE_DYNAMIC_LINEAR == mode) { - /// When character angular is always locked - btBody->setAngularFactor(btVector3(0., 0., 0.)); - } else { - btBody->setAngularFactor(btVector3(btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_X)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_Y)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_ANGULAR_Z)))); - } -} - -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(1e-7); - - /// Calculate using the rule write 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(1.0); - if (btBody->getCollisionShape()) { - btVector3 center; - btBody->getCollisionShape()->getBoundingSphere(center, radius); - } - btBody->setCcdSweptSphereRadius(radius * 0.2); - } else { - btBody->setCcdMotionThreshold(0.); - btBody->setCcdSweptSphereRadius(0.); - } -} - -bool RigidBodyBullet::is_continuous_collision_detection_enabled() const { - return 0. < btBody->getCcdMotionThreshold(); -} - -void RigidBodyBullet::set_linear_velocity(const Vector3 &p_velocity) { - btVector3 btVec; - G_TO_B(p_velocity, btVec); - if (Vector3() != p_velocity) { - btBody->activate(); - } - btBody->setLinearVelocity(btVec); -} - -Vector3 RigidBodyBullet::get_linear_velocity() const { - Vector3 gVec; - B_TO_G(btBody->getLinearVelocity(), gVec); - return gVec; -} - -void RigidBodyBullet::set_angular_velocity(const Vector3 &p_velocity) { - btVector3 btVec; - G_TO_B(p_velocity, btVec); - if (Vector3() != p_velocity) { - btBody->activate(); - } - btBody->setAngularVelocity(btVec); -} - -Vector3 RigidBodyBullet::get_angular_velocity() const { - Vector3 gVec; - B_TO_G(btBody->getAngularVelocity(), gVec); - return gVec; -} - -void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transform) { - if (mode == PhysicsServer3D::BODY_MODE_KINEMATIC) { - if (space && space->get_delta_time() != 0) { - btBody->setLinearVelocity((p_global_transform.getOrigin() - btBody->getWorldTransform().getOrigin()) / space->get_delta_time()); - } - // The kinematic use MotionState class - godotMotionState->moveBody(p_global_transform); - } else { - // Is necessary to avoid wrong location on the rendering side on the next frame - godotMotionState->setWorldTransform(p_global_transform); - } - CollisionObjectBullet::set_transform__bullet(p_global_transform); -} - -const btTransform &RigidBodyBullet::get_transform__bullet() const { - if (is_static()) { - return RigidCollisionObjectBullet::get_transform__bullet(); - } else { - return godotMotionState->getCurrentWorldTransform(); - } -} - -void RigidBodyBullet::reload_shapes() { - RigidCollisionObjectBullet::reload_shapes(); - - const btScalar invMass = btBody->getInvMass(); - const btScalar mass = invMass == 0 ? 0 : 1 / invMass; - - if (mainShape) { - // inertia initialised zero here because some of bullet's collision - // shapes incorrectly do not set the vector in calculateLocalIntertia. - // Arbitrary zero is preferable to undefined behaviour. - btVector3 inertia(0, 0, 0); - if (EMPTY_SHAPE_PROXYTYPE != mainShape->getShapeType()) { // Necessary to avoid assertion of the empty shape - mainShape->calculateLocalInertia(mass, inertia); - } - btBody->setMassProps(mass, inertia); - } - btBody->updateInertiaTensor(); - - reload_kinematic_shapes(); - set_continuous_collision_detection(is_continuous_collision_detection_enabled()); - reload_body(); -} - -void RigidBodyBullet::on_enter_area(AreaBullet *p_area) { - /// Add this area to the array in an ordered way - ++areaWhereIamCount; - if (areaWhereIamCount >= maxAreasWhereIam) { - --areaWhereIamCount; - return; - } - for (int i = 0; i < areaWhereIamCount; ++i) { - if (nullptr == areasWhereIam[i]) { - // This area has the highest priority - areasWhereIam.write[i] = p_area; - break; - } else { - if (areasWhereIam[i]->get_spOv_priority() > p_area->get_spOv_priority()) { - // The position was found, just shift all elements - for (int j = areaWhereIamCount; j > i; j--) { - areasWhereIam.write[j] = areasWhereIam[j - 1]; - } - areasWhereIam.write[i] = p_area; - break; - } - } - } - if (PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) { - scratch_space_override_modificator(); - } - - if (p_area->is_spOv_gravityPoint()) { - ++countGravityPointSpaces; - ERR_FAIL_COND(countGravityPointSpaces <= 0); - } -} - -void RigidBodyBullet::on_exit_area(AreaBullet *p_area) { - RigidCollisionObjectBullet::on_exit_area(p_area); - /// Remove this area and keep the order - /// N.B. Since I don't want resize the array I can't use the "erase" function - bool wasTheAreaFound = false; - for (int i = 0; i < areaWhereIamCount; ++i) { - if (p_area == areasWhereIam[i]) { - // The area was found, just shift down all elements - for (int j = i; j < areaWhereIamCount; ++j) { - areasWhereIam.write[j] = areasWhereIam[j + 1]; - } - wasTheAreaFound = true; - break; - } - } - if (wasTheAreaFound) { - if (p_area->is_spOv_gravityPoint()) { - --countGravityPointSpaces; - ERR_FAIL_COND(countGravityPointSpaces < 0); - } - - --areaWhereIamCount; - areasWhereIam.write[areaWhereIamCount] = nullptr; // Even if this is not required, I clear the last element to be safe - if (PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) { - scratch_space_override_modificator(); - } - } -} - -void RigidBodyBullet::reload_space_override_modificator() { - if (mode == PhysicsServer3D::BODY_MODE_STATIC) { - return; - } - - Vector3 newGravity(0.0, 0.0, 0.0); - real_t newLinearDamp = MAX(0.0, linearDamp); - real_t newAngularDamp = MAX(0.0, angularDamp); - - AreaBullet *currentArea; - // Variable used to calculate new gravity for gravity point areas, it is pointed by currentGravity pointer - Vector3 support_gravity(0, 0, 0); - - bool stopped = false; - for (int i = areaWhereIamCount - 1; (0 <= i) && !stopped; --i) { - currentArea = areasWhereIam[i]; - - if (!currentArea || PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) { - continue; - } - - /// Here is calculated the gravity - if (currentArea->is_spOv_gravityPoint()) { - /// It calculates the direction of new gravity - support_gravity = currentArea->get_transform().xform(currentArea->get_spOv_gravityVec()) - get_transform().get_origin(); - real_t distanceMag = support_gravity.length(); - // Normalized in this way to avoid the double call of function "length()" - if (distanceMag == 0) { - support_gravity.x = 0; - support_gravity.y = 0; - support_gravity.z = 0; - } else { - support_gravity.x /= distanceMag; - support_gravity.y /= distanceMag; - support_gravity.z /= distanceMag; - } - - /// Here is calculated the final gravity - if (currentArea->get_spOv_gravityPointDistanceScale() > 0) { - // Scaled gravity by distance - support_gravity *= currentArea->get_spOv_gravityMag() / Math::pow(distanceMag * currentArea->get_spOv_gravityPointDistanceScale() + 1, 2); - } else { - // Unscaled gravity - support_gravity *= currentArea->get_spOv_gravityMag(); - } - } else { - support_gravity = currentArea->get_spOv_gravityVec() * currentArea->get_spOv_gravityMag(); - } - - switch (currentArea->get_spOv_mode()) { - case PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED: - /// This area does not affect gravity/damp. These are generally areas - /// that exist only to detect collisions, and objects entering or exiting them. - break; - case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE: - /// This area adds its gravity/damp values to whatever has been - /// calculated so far. This way, many overlapping areas can combine - /// their physics to make interesting - newGravity += support_gravity; - newLinearDamp += currentArea->get_spOv_linearDamp(); - newAngularDamp += currentArea->get_spOv_angularDamp(); - break; - case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: - /// This area adds its gravity/damp values to whatever has been calculated - /// so far. Then stops taking into account the rest of the areas, even the - /// default one. - newGravity += support_gravity; - newLinearDamp += currentArea->get_spOv_linearDamp(); - newAngularDamp += currentArea->get_spOv_angularDamp(); - stopped = true; - break; - case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE: - /// This area replaces any gravity/damp, even the default one, and - /// stops taking into account the rest of the areas. - newGravity = support_gravity; - newLinearDamp = currentArea->get_spOv_linearDamp(); - newAngularDamp = currentArea->get_spOv_angularDamp(); - stopped = true; - break; - case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: - /// This area replaces any gravity/damp calculated so far, but keeps - /// calculating the rest of the areas, down to the default one. - newGravity = support_gravity; - newLinearDamp = currentArea->get_spOv_linearDamp(); - newAngularDamp = currentArea->get_spOv_angularDamp(); - break; - } - } - - // Add default gravity and damping from space. - if (!stopped) { - newGravity += space->get_gravity_direction() * space->get_gravity_magnitude(); - newLinearDamp += space->get_linear_damp(); - newAngularDamp += space->get_angular_damp(); - } - - btVector3 newBtGravity; - G_TO_B(newGravity * gravity_scale, newBtGravity); - - btBody->setGravity(newBtGravity); - btBody->setDamping(newLinearDamp, newAngularDamp); -} - -void RigidBodyBullet::reload_kinematic_shapes() { - if (!kinematic_utilities) { - return; - } - kinematic_utilities->copyAllOwnerShapes(); -} - -void RigidBodyBullet::notify_transform_changed() { - RigidCollisionObjectBullet::notify_transform_changed(); - can_integrate_forces = true; -} - -void RigidBodyBullet::_internal_set_mass(real_t p_mass) { - btVector3 localInertia(0, 0, 0); - - int clearedCurrentFlags = btBody->getCollisionFlags(); - clearedCurrentFlags &= ~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_CHARACTER_OBJECT); - - // Rigidbody is dynamic if and only if mass is non Zero, otherwise static - const bool isDynamic = p_mass != 0.f; - if (isDynamic) { - if (PhysicsServer3D::BODY_MODE_DYNAMIC != mode && PhysicsServer3D::MODE_DYNAMIC_LINEAR != mode) { - return; - } - - m_isStatic = false; - if (mainShape) { - mainShape->calculateLocalInertia(p_mass, localInertia); - } - - if (PhysicsServer3D::BODY_MODE_DYNAMIC == mode) { - btBody->setCollisionFlags(clearedCurrentFlags); // Just set the flags without Kin and Static - } else { - btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_CHARACTER_OBJECT); - } - - if (can_sleep) { - btBody->forceActivationState(ACTIVE_TAG); // ACTIVE_TAG 1 - } else { - btBody->forceActivationState(DISABLE_DEACTIVATION); // DISABLE_DEACTIVATION 4 - } - } else { - if (PhysicsServer3D::BODY_MODE_STATIC != mode && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) { - return; - } - - m_isStatic = true; - if (PhysicsServer3D::BODY_MODE_STATIC == mode) { - btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_STATIC_OBJECT); - } else { - btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_KINEMATIC_OBJECT); - set_transform__bullet(btBody->getWorldTransform()); // Set current Transform using kinematic method - } - btBody->forceActivationState(DISABLE_SIMULATION); // DISABLE_SIMULATION 5 - } - - btBody->setMassProps(p_mass, localInertia); - btBody->updateInertiaTensor(); - - reload_body(); -} diff --git a/modules/bullet/rigid_body_bullet.h b/modules/bullet/rigid_body_bullet.h deleted file mode 100644 index cd433c968f..0000000000 --- a/modules/bullet/rigid_body_bullet.h +++ /dev/null @@ -1,328 +0,0 @@ -/*************************************************************************/ -/* rigid_body_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 RIGID_BODY_BULLET_H -#define RIGID_BODY_BULLET_H - -#include "collision_object_bullet.h" -#include "space_bullet.h" - -#include <BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h> -#include <LinearMath/btTransform.h> - -class AreaBullet; -class SpaceBullet; -class btRigidBody; -class GodotMotionState; -class BulletPhysicsDirectBodyState3D; - -/// This class could be used in multi thread with few changes but currently -/// is set to be only in one single thread. -/// -/// In the system there is only one object at a time that manage all bodies and is -/// created by BulletPhysicsServer3D and is held by the "singleton" variable of this class -/// Each time something require it, the body must be set again. -class BulletPhysicsDirectBodyState3D : public PhysicsDirectBodyState3D { - GDCLASS(BulletPhysicsDirectBodyState3D, PhysicsDirectBodyState3D); - - static BulletPhysicsDirectBodyState3D *singleton; - -public: - /// This class avoid the creation of more object of this class - static void initSingleton() { - if (!singleton) { - singleton = memnew(BulletPhysicsDirectBodyState3D); - } - } - - static void destroySingleton() { - memdelete(singleton); - singleton = nullptr; - } - - static void singleton_setDeltaTime(real_t p_deltaTime) { - singleton->deltaTime = p_deltaTime; - } - - static BulletPhysicsDirectBodyState3D *get_singleton(RigidBodyBullet *p_body) { - singleton->body = p_body; - return singleton; - } - -public: - RigidBodyBullet *body = nullptr; - real_t deltaTime = 0.0; - -private: - BulletPhysicsDirectBodyState3D() {} - -public: - virtual Vector3 get_total_gravity() const override; - virtual real_t get_total_angular_damp() const override; - virtual real_t get_total_linear_damp() const override; - - virtual Vector3 get_center_of_mass() const override; - virtual Basis get_principal_inertia_axes() const override; - // get the mass - virtual real_t get_inverse_mass() const override; - // get density of this body space - virtual Vector3 get_inverse_inertia() const override; - // get density of this body space - virtual Basis get_inverse_inertia_tensor() const override; - - virtual void set_linear_velocity(const Vector3 &p_velocity) override; - virtual Vector3 get_linear_velocity() const override; - - virtual void set_angular_velocity(const Vector3 &p_velocity) override; - virtual Vector3 get_angular_velocity() const override; - - virtual void set_transform(const Transform3D &p_transform) override; - virtual Transform3D get_transform() const override; - - virtual Vector3 get_velocity_at_local_position(const Vector3 &p_position) const override; - - virtual void add_central_force(const Vector3 &p_force) override; - virtual void add_force(const Vector3 &p_force, const Vector3 &p_position = Vector3()) override; - virtual void add_torque(const Vector3 &p_torque) override; - virtual void apply_central_impulse(const Vector3 &p_impulse) override; - virtual void apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position = Vector3()) override; - virtual void apply_torque_impulse(const Vector3 &p_impulse) override; - - virtual void set_sleep_state(bool p_sleep) override; - virtual bool is_sleeping() const override; - - virtual int get_contact_count() const override; - - virtual Vector3 get_contact_local_position(int p_contact_idx) const override; - virtual Vector3 get_contact_local_normal(int p_contact_idx) const override; - virtual real_t get_contact_impulse(int p_contact_idx) const override; - virtual int get_contact_local_shape(int p_contact_idx) const override; - - virtual RID get_contact_collider(int p_contact_idx) const override; - virtual Vector3 get_contact_collider_position(int p_contact_idx) const override; - virtual ObjectID get_contact_collider_id(int p_contact_idx) const override; - virtual int get_contact_collider_shape(int p_contact_idx) const override; - virtual Vector3 get_contact_collider_velocity_at_position(int p_contact_idx) const override; - - virtual real_t get_step() const override { return deltaTime; } - virtual void integrate_forces() override { - // Skip the execution of this function - } - - virtual PhysicsDirectSpaceState3D *get_space_state() override; -}; - -class RigidBodyBullet : public RigidCollisionObjectBullet { -public: - struct CollisionData { - RigidBodyBullet *otherObject = nullptr; - int other_object_shape = 0; - int local_shape = 0; - Vector3 hitLocalLocation; - Vector3 hitWorldLocation; - Vector3 hitNormal; - real_t appliedImpulse = 0.0; - }; - - struct ForceIntegrationCallback { - Callable callable; - Variant udata; - }; - - /// Used to hold shapes - struct KinematicShape { - class btConvexShape *shape = nullptr; - btTransform transform; - - KinematicShape() {} - bool is_active() const { return shape; } - }; - - struct KinematicUtilities { - RigidBodyBullet *owner = nullptr; - btScalar safe_margin; - Vector<KinematicShape> shapes; - - KinematicUtilities(RigidBodyBullet *p_owner); - ~KinematicUtilities(); - - void setSafeMargin(btScalar p_margin); - /// Used to set the default shape to ghost - void copyAllOwnerShapes(); - - private: - void just_delete_shapes(int new_size); - }; - -private: - friend class BulletPhysicsDirectBodyState3D; - - // This is required only for Kinematic movement - KinematicUtilities *kinematic_utilities = nullptr; - - PhysicsServer3D::BodyMode mode; - GodotMotionState *godotMotionState; - btRigidBody *btBody; - uint16_t locked_axis = 0; - real_t mass = 1.0; - real_t gravity_scale = 1.0; - real_t linearDamp = 0.0; - real_t angularDamp = 0.0; - bool can_sleep = true; - bool omit_forces_integration = false; - bool can_integrate_forces = false; - - Vector<CollisionData> collisions; - Vector<RigidBodyBullet *> collision_traces_1; - Vector<RigidBodyBullet *> collision_traces_2; - Vector<RigidBodyBullet *> *prev_collision_traces; - Vector<RigidBodyBullet *> *curr_collision_traces; - - // these parameters are used to avoid vector resize - int maxCollisionsDetection = 0; - int collisionsCount = 0; - int prev_collision_count = 0; - - Vector<AreaBullet *> areasWhereIam; - // these parameters are used to avoid vector resize - int maxAreasWhereIam = 10; - int areaWhereIamCount = 0; - // Used to know if the area is used as gravity point - int countGravityPointSpaces = 0; - bool isScratchedSpaceOverrideModificator = false; - - bool previousActiveState = true; // Last check state - - ForceIntegrationCallback *force_integration_callback = nullptr; - -public: - RigidBodyBullet(); - ~RigidBodyBullet(); - - void init_kinematic_utilities(); - void destroy_kinematic_utilities(); - _FORCE_INLINE_ KinematicUtilities *get_kinematic_utilities() const { return kinematic_utilities; } - - _FORCE_INLINE_ btRigidBody *get_bt_rigid_body() { return btBody; } - - virtual void main_shape_changed(); - virtual void reload_body(); - virtual void set_space(SpaceBullet *p_space); - - virtual void dispatch_callbacks(); - void set_force_integration_callback(const Callable &p_callable, const Variant &p_udata = Variant()); - void scratch_space_override_modificator(); - - virtual void on_collision_filters_change(); - virtual void on_collision_checker_start(); - virtual void on_collision_checker_end(); - - void set_max_collisions_detection(int p_maxCollisionsDetection) { - ERR_FAIL_COND(0 > p_maxCollisionsDetection); - - maxCollisionsDetection = p_maxCollisionsDetection; - - collisions.resize(p_maxCollisionsDetection); - collision_traces_1.resize(p_maxCollisionsDetection); - collision_traces_2.resize(p_maxCollisionsDetection); - - collisionsCount = 0; - prev_collision_count = MIN(prev_collision_count, p_maxCollisionsDetection); - } - int get_max_collisions_detection() { - return maxCollisionsDetection; - } - - bool can_add_collision() { return collisionsCount < maxCollisionsDetection; } - bool add_collision_object(RigidBodyBullet *p_otherObject, const Vector3 &p_hitWorldLocation, const Vector3 &p_hitLocalLocation, const Vector3 &p_hitNormal, const real_t &p_appliedImpulse, int p_other_shape_index, int p_local_shape_index); - bool was_colliding(RigidBodyBullet *p_other_object); - - void set_activation_state(bool p_active); - bool is_active() const; - - void set_omit_forces_integration(bool p_omit); - _FORCE_INLINE_ bool get_omit_forces_integration() const { return omit_forces_integration; } - - void set_param(PhysicsServer3D::BodyParameter p_param, real_t); - real_t get_param(PhysicsServer3D::BodyParameter p_param) const; - - void set_mode(PhysicsServer3D::BodyMode p_mode); - PhysicsServer3D::BodyMode get_mode() const; - - void set_state(PhysicsServer3D::BodyState p_state, const Variant &p_variant); - Variant get_state(PhysicsServer3D::BodyState p_state) const; - - void apply_central_impulse(const Vector3 &p_impulse); - void apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position = Vector3()); - void apply_torque_impulse(const Vector3 &p_impulse); - - void apply_central_force(const Vector3 &p_force); - void apply_force(const Vector3 &p_force, const Vector3 &p_position = Vector3()); - void apply_torque(const Vector3 &p_torque); - - void set_applied_force(const Vector3 &p_force); - Vector3 get_applied_force() const; - void set_applied_torque(const Vector3 &p_torque); - Vector3 get_applied_torque() const; - - void set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool lock); - bool is_axis_locked(PhysicsServer3D::BodyAxis p_axis) const; - void reload_axis_lock(); - - /// Doc: - /// https://web.archive.org/web/20180404091446/https://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; - - void set_linear_velocity(const Vector3 &p_velocity); - Vector3 get_linear_velocity() const; - - void set_angular_velocity(const Vector3 &p_velocity); - Vector3 get_angular_velocity() const; - - virtual void set_transform__bullet(const btTransform &p_global_transform); - virtual const btTransform &get_transform__bullet() const; - - virtual void reload_shapes(); - - virtual void on_enter_area(AreaBullet *p_area); - virtual void on_exit_area(AreaBullet *p_area); - void reload_space_override_modificator(); - - /// Kinematic - void reload_kinematic_shapes(); - - virtual void notify_transform_changed(); - -private: - void _internal_set_mass(real_t p_mass); -}; - -#endif // RIGID_BODY_BULLET_H diff --git a/modules/bullet/shape_bullet.cpp b/modules/bullet/shape_bullet.cpp deleted file mode 100644 index 77a583ad86..0000000000 --- a/modules/bullet/shape_bullet.cpp +++ /dev/null @@ -1,595 +0,0 @@ -/*************************************************************************/ -/* shape_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "shape_bullet.h" - -#include "btRayShape.h" -#include "bullet_physics_server.h" -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "core/config/project_settings.h" -#include "shape_owner_bullet.h" - -#include <BulletCollision/CollisionDispatch/btInternalEdgeUtility.h> -#include <BulletCollision/CollisionShapes/btConvexPointCloudShape.h> -#include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h> -#include <btBulletCollisionCommon.h> - -ShapeBullet::ShapeBullet() {} - -ShapeBullet::~ShapeBullet() {} - -btCollisionShape *ShapeBullet::create_bt_shape(const Vector3 &p_implicit_scale, real_t p_extra_edge) { - btVector3 s; - G_TO_B(p_implicit_scale, s); - return create_bt_shape(s, p_extra_edge); -} - -btCollisionShape *ShapeBullet::prepare(btCollisionShape *p_btShape) const { - p_btShape->setUserPointer(const_cast<ShapeBullet *>(this)); - p_btShape->setMargin(margin); - return p_btShape; -} - -void ShapeBullet::notifyShapeChanged() { - for (const KeyValue<ShapeOwnerBullet *, int> &E : owners) { - ShapeOwnerBullet *owner = static_cast<ShapeOwnerBullet *>(E.key); - owner->shape_changed(owner->find_shape(this)); - } -} - -void ShapeBullet::add_owner(ShapeOwnerBullet *p_owner) { - Map<ShapeOwnerBullet *, int>::Element *E = owners.find(p_owner); - if (E) { - E->get()++; - } else { - owners[p_owner] = 1; // add new owner - } -} - -void ShapeBullet::remove_owner(ShapeOwnerBullet *p_owner, bool p_permanentlyFromThisBody) { - Map<ShapeOwnerBullet *, int>::Element *E = owners.find(p_owner); - if (!E) { - return; - } - E->get()--; - if (p_permanentlyFromThisBody || 0 >= E->get()) { - owners.erase(E); - } -} - -bool ShapeBullet::is_owner(ShapeOwnerBullet *p_owner) const { - return owners.has(p_owner); -} - -const Map<ShapeOwnerBullet *, int> &ShapeBullet::get_owners() const { - return owners; -} - -void ShapeBullet::set_margin(real_t p_margin) { - margin = p_margin; - notifyShapeChanged(); -} - -real_t ShapeBullet::get_margin() const { - return margin; -} - -btEmptyShape *ShapeBullet::create_shape_empty() { - return bulletnew(btEmptyShape); -} - -btStaticPlaneShape *ShapeBullet::create_shape_world_boundary(const btVector3 &planeNormal, btScalar planeConstant) { - return bulletnew(btStaticPlaneShape(planeNormal, planeConstant)); -} - -btSphereShape *ShapeBullet::create_shape_sphere(btScalar radius) { - return bulletnew(btSphereShape(radius)); -} - -btBoxShape *ShapeBullet::create_shape_box(const btVector3 &boxHalfExtents) { - return bulletnew(btBoxShape(boxHalfExtents)); -} - -btCapsuleShape *ShapeBullet::create_shape_capsule(btScalar radius, btScalar height) { - return bulletnew(btCapsuleShape(radius, height)); -} - -btCylinderShape *ShapeBullet::create_shape_cylinder(btScalar radius, btScalar height) { - return bulletnew(btCylinderShape(btVector3(radius, height / 2.0, radius))); -} - -btConvexPointCloudShape *ShapeBullet::create_shape_convex(btAlignedObjectArray<btVector3> &p_vertices, const btVector3 &p_local_scaling) { - return bulletnew(btConvexPointCloudShape(&p_vertices[0], p_vertices.size(), p_local_scaling)); -} - -btScaledBvhTriangleMeshShape *ShapeBullet::create_shape_concave(btBvhTriangleMeshShape *p_mesh_shape, const btVector3 &p_local_scaling) { - if (p_mesh_shape) { - return bulletnew(btScaledBvhTriangleMeshShape(p_mesh_shape, p_local_scaling)); - } else { - return nullptr; - } -} - -btHeightfieldTerrainShape *ShapeBullet::create_shape_height_field(Vector<float> &p_heights, int p_width, int p_depth, real_t p_min_height, real_t p_max_height) { - const btScalar ignoredHeightScale(1); - const int YAxis = 1; // 0=X, 1=Y, 2=Z - const bool flipQuadEdges = false; - const void *heightsPtr = p_heights.ptr(); - - 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 PhysicsServer3D.shape_create(PhysicsServer3D.SHAPE_HEIGHTMAP) - if (heightsPtr) { - heightfield->buildAccelerator(16); - } - - return heightfield; -} - -btRayShape *ShapeBullet::create_shape_ray(real_t p_length, bool p_slips_on_slope) { - btRayShape *r(bulletnew(btRayShape(p_length))); - r->setSlipsOnSlope(p_slips_on_slope); - return r; -} - -/* World boundary */ - -WorldBoundaryShapeBullet::WorldBoundaryShapeBullet() : - ShapeBullet() {} - -void WorldBoundaryShapeBullet::set_data(const Variant &p_data) { - setup(p_data); -} - -Variant WorldBoundaryShapeBullet::get_data() const { - return plane; -} - -PhysicsServer3D::ShapeType WorldBoundaryShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_WORLD_BOUNDARY; -} - -void WorldBoundaryShapeBullet::setup(const Plane &p_plane) { - plane = p_plane; - notifyShapeChanged(); -} - -btCollisionShape *WorldBoundaryShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - btVector3 btPlaneNormal; - G_TO_B(plane.normal, btPlaneNormal); - return prepare(WorldBoundaryShapeBullet::create_shape_world_boundary(btPlaneNormal, plane.d)); -} - -/* Sphere */ - -SphereShapeBullet::SphereShapeBullet() : - ShapeBullet() {} - -void SphereShapeBullet::set_data(const Variant &p_data) { - setup(p_data); -} - -Variant SphereShapeBullet::get_data() const { - return radius; -} - -PhysicsServer3D::ShapeType SphereShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_SPHERE; -} - -void SphereShapeBullet::setup(real_t p_radius) { - radius = p_radius; - notifyShapeChanged(); -} - -btCollisionShape *SphereShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - return prepare(ShapeBullet::create_shape_sphere(radius * p_implicit_scale[0] + p_extra_edge)); -} - -/* Box */ -BoxShapeBullet::BoxShapeBullet() : - ShapeBullet() {} - -void BoxShapeBullet::set_data(const Variant &p_data) { - setup(p_data); -} - -Variant BoxShapeBullet::get_data() const { - Vector3 g_half_extents; - B_TO_G(half_extents, g_half_extents); - return g_half_extents; -} - -PhysicsServer3D::ShapeType BoxShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_BOX; -} - -void BoxShapeBullet::setup(const Vector3 &p_half_extents) { - G_TO_B(p_half_extents, half_extents); - notifyShapeChanged(); -} - -btCollisionShape *BoxShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - return prepare(ShapeBullet::create_shape_box((half_extents * p_implicit_scale) + btVector3(p_extra_edge, p_extra_edge, p_extra_edge))); -} - -/* Capsule */ - -CapsuleShapeBullet::CapsuleShapeBullet() : - ShapeBullet() {} - -void CapsuleShapeBullet::set_data(const Variant &p_data) { - Dictionary d = p_data; - ERR_FAIL_COND(!d.has("radius")); - ERR_FAIL_COND(!d.has("height")); - setup(d["height"], d["radius"]); -} - -Variant CapsuleShapeBullet::get_data() const { - Dictionary d; - d["radius"] = radius; - d["height"] = height; - return d; -} - -PhysicsServer3D::ShapeType CapsuleShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_CAPSULE; -} - -void CapsuleShapeBullet::setup(real_t p_height, real_t p_radius) { - radius = p_radius; - height = p_height; - notifyShapeChanged(); -} - -btCollisionShape *CapsuleShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - return prepare(ShapeBullet::create_shape_capsule(radius * p_implicit_scale[0] + p_extra_edge, height * p_implicit_scale[1])); -} - -/* Cylinder */ - -CylinderShapeBullet::CylinderShapeBullet() : - ShapeBullet() {} - -void CylinderShapeBullet::set_data(const Variant &p_data) { - Dictionary d = p_data; - ERR_FAIL_COND(!d.has("radius")); - ERR_FAIL_COND(!d.has("height")); - setup(d["height"], d["radius"]); -} - -Variant CylinderShapeBullet::get_data() const { - Dictionary d; - d["radius"] = radius; - d["height"] = height; - return d; -} - -PhysicsServer3D::ShapeType CylinderShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_CYLINDER; -} - -void CylinderShapeBullet::setup(real_t p_height, real_t p_radius) { - radius = p_radius; - height = p_height; - notifyShapeChanged(); -} - -btCollisionShape *CylinderShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_margin) { - return prepare(ShapeBullet::create_shape_cylinder(radius * p_implicit_scale[0] + p_margin, height * p_implicit_scale[1] + p_margin)); -} - -/* Convex polygon */ - -ConvexPolygonShapeBullet::ConvexPolygonShapeBullet() : - ShapeBullet() {} - -void ConvexPolygonShapeBullet::set_data(const Variant &p_data) { - setup(p_data); -} - -void ConvexPolygonShapeBullet::get_vertices(Vector<Vector3> &out_vertices) { - const int n_of_vertices = vertices.size(); - out_vertices.resize(n_of_vertices); - for (int i = n_of_vertices - 1; 0 <= i; --i) { - B_TO_G(vertices[i], out_vertices.write[i]); - } -} - -Variant ConvexPolygonShapeBullet::get_data() const { - ConvexPolygonShapeBullet *variable_self = const_cast<ConvexPolygonShapeBullet *>(this); - Vector<Vector3> out_vertices; - variable_self->get_vertices(out_vertices); - return out_vertices; -} - -PhysicsServer3D::ShapeType ConvexPolygonShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_CONVEX_POLYGON; -} - -void ConvexPolygonShapeBullet::setup(const Vector<Vector3> &p_vertices) { - // Make a copy of vertices - const int n_of_vertices = p_vertices.size(); - vertices.resize(n_of_vertices); - for (int i = n_of_vertices - 1; 0 <= i; --i) { - G_TO_B(p_vertices[i], vertices[i]); - } - notifyShapeChanged(); -} - -btCollisionShape *ConvexPolygonShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - if (!vertices.size()) { - // This is necessary since 0 vertices - return prepare(ShapeBullet::create_shape_empty()); - } - btCollisionShape *cs(ShapeBullet::create_shape_convex(vertices)); - cs->setLocalScaling(p_implicit_scale); - prepare(cs); - return cs; -} - -/* Concave polygon */ - -ConcavePolygonShapeBullet::ConcavePolygonShapeBullet() : - ShapeBullet() {} - -ConcavePolygonShapeBullet::~ConcavePolygonShapeBullet() { - if (meshShape) { - delete meshShape->getMeshInterface(); - delete meshShape->getTriangleInfoMap(); - bulletdelete(meshShape); - } - faces = Vector<Vector3>(); -} - -void ConcavePolygonShapeBullet::set_data(const Variant &p_data) { - Dictionary d = p_data; - ERR_FAIL_COND(!d.has("faces")); - - setup(d["faces"]); -} - -Variant ConcavePolygonShapeBullet::get_data() const { - Dictionary d; - d["faces"] = faces; - - return d; -} - -PhysicsServer3D::ShapeType ConcavePolygonShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_CONCAVE_POLYGON; -} - -void ConcavePolygonShapeBullet::setup(Vector<Vector3> p_faces) { - faces = p_faces; - if (meshShape) { - /// Clear previous created shape - delete meshShape->getMeshInterface(); - delete meshShape->getTriangleInfoMap(); - bulletdelete(meshShape); - } - int src_face_count = faces.size(); - if (0 < src_face_count) { - // It counts the faces and assert the array contains the correct number of vertices. - ERR_FAIL_COND(src_face_count % 3); - - btTriangleMesh *shapeInterface = bulletnew(btTriangleMesh); - src_face_count /= 3; - const Vector3 *r = p_faces.ptr(); - const Vector3 *facesr = r; - - btVector3 supVec_0; - btVector3 supVec_1; - btVector3 supVec_2; - for (int i = 0; i < src_face_count; ++i) { - G_TO_B(facesr[i * 3 + 0], supVec_0); - G_TO_B(facesr[i * 3 + 1], supVec_1); - G_TO_B(facesr[i * 3 + 2], supVec_2); - - // Inverted from standard godot otherwise btGenerateInternalEdgeInfo generates wrong edge info - shapeInterface->addTriangle(supVec_2, supVec_1, supVec_0); - } - - const bool useQuantizedAabbCompression = true; - - meshShape = bulletnew(btBvhTriangleMeshShape(shapeInterface, useQuantizedAabbCompression)); - - if (GLOBAL_DEF("physics/3d/smooth_trimesh_collision", false)) { - btTriangleInfoMap *triangleInfoMap = new btTriangleInfoMap(); - btGenerateInternalEdgeInfo(meshShape, triangleInfoMap); - } - } else { - meshShape = nullptr; - ERR_PRINT("The faces count are 0, the mesh shape cannot be created"); - } - notifyShapeChanged(); -} - -btCollisionShape *ConcavePolygonShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - btCollisionShape *cs = ShapeBullet::create_shape_concave(meshShape); - if (!cs) { - // This is necessary since if 0 faces the creation of concave return null - cs = ShapeBullet::create_shape_empty(); - } - cs->setLocalScaling(p_implicit_scale); - prepare(cs); - cs->setMargin(0); - return cs; -} - -/* Height map shape */ - -HeightMapShapeBullet::HeightMapShapeBullet() : - ShapeBullet() {} - -void HeightMapShapeBullet::set_data(const Variant &p_data) { - ERR_FAIL_COND(p_data.get_type() != Variant::DICTIONARY); - Dictionary d = p_data; - ERR_FAIL_COND(!d.has("width")); - ERR_FAIL_COND(!d.has("depth")); - ERR_FAIL_COND(!d.has("heights")); - - real_t l_min_height = 0.0; - real_t l_max_height = 0.0; - - // If specified, min and max height will be used as precomputed values - if (d.has("min_height")) { - l_min_height = d["min_height"]; - } - if (d.has("max_height")) { - l_max_height = d["max_height"]; - } - - ERR_FAIL_COND(l_min_height > l_max_height); - - int l_width = d["width"]; - int l_depth = d["depth"]; - - ERR_FAIL_COND_MSG(l_width < 2, "Map width must be at least 2."); - ERR_FAIL_COND_MSG(l_depth < 2, "Map depth must be at least 2."); - - Vector<float> l_heights; - Variant l_heights_v = d["heights"]; - - if (l_heights_v.get_type() == Variant::PACKED_FLOAT32_ARRAY) { - // Ready-to-use heights can be passed - - l_heights = l_heights_v; - - } else if (l_heights_v.get_type() == Variant::OBJECT) { - // If an image is passed, we have to convert it to a format Bullet supports. - // this would be expensive to do with a script, so it's nice to have it here. - - Ref<Image> l_image = l_heights_v; - ERR_FAIL_COND(l_image.is_null()); - - // Float is the only common format between Godot and Bullet that can be used for decent collision. - // (Int16 would be nice too but we still don't have it) - // We could convert here automatically but it's better to not be intrusive and let the caller do it if necessary. - ERR_FAIL_COND(l_image->get_format() != Image::FORMAT_RF); - - PackedByteArray im_data = l_image->get_data(); - - l_heights.resize(l_image->get_width() * l_image->get_height()); - - float *w = l_heights.ptrw(); - const uint8_t *r = im_data.ptr(); - float *rp = (float *)r; - // At this point, `rp` could be used directly for Bullet, but I don't know how safe it would be. - - for (int i = 0; i < l_heights.size(); ++i) { - w[i] = rp[i]; - } - - } else { - ERR_FAIL_MSG("Expected PackedFloat32Array or float Image."); - } - - ERR_FAIL_COND(l_width <= 0); - ERR_FAIL_COND(l_depth <= 0); - ERR_FAIL_COND(l_heights.size() != (l_width * l_depth)); - - // Compute min and max heights if not specified. - if (!d.has("min_height") && !d.has("max_height")) { - const float *r = l_heights.ptr(); - int heights_size = l_heights.size(); - - for (int i = 0; i < heights_size; ++i) { - float h = r[i]; - - if (h < l_min_height) { - l_min_height = h; - } else if (h > l_max_height) { - l_max_height = h; - } - } - } - - setup(l_heights, l_width, l_depth, l_min_height, l_max_height); -} - -Variant HeightMapShapeBullet::get_data() const { - ERR_FAIL_V(Variant()); -} - -PhysicsServer3D::ShapeType HeightMapShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_HEIGHTMAP; -} - -void HeightMapShapeBullet::setup(Vector<float> &p_heights, int p_width, int p_depth, real_t p_min_height, real_t p_max_height) { - // TODO cell size must be tweaked using localScaling, which is a shared property for all Bullet shapes - - // If this array is resized outside of here, it should be preserved due to CoW - heights = p_heights; - - width = p_width; - depth = p_depth; - min_height = p_min_height; - max_height = p_max_height; - notifyShapeChanged(); -} - -btCollisionShape *HeightMapShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - btCollisionShape *cs(ShapeBullet::create_shape_height_field(heights, width, depth, min_height, max_height)); - cs->setLocalScaling(p_implicit_scale); - prepare(cs); - return cs; -} - -/* Ray shape */ -RayShapeBullet::RayShapeBullet() : - ShapeBullet() {} - -void RayShapeBullet::set_data(const Variant &p_data) { - Dictionary d = p_data; - setup(d["length"], d["slips_on_slope"]); -} - -Variant RayShapeBullet::get_data() const { - Dictionary d; - d["length"] = length; - d["slips_on_slope"] = slips_on_slope; - return d; -} - -PhysicsServer3D::ShapeType RayShapeBullet::get_type() const { - return PhysicsServer3D::SHAPE_RAY; -} - -void RayShapeBullet::setup(real_t p_length, bool p_slips_on_slope) { - length = p_length; - slips_on_slope = p_slips_on_slope; - notifyShapeChanged(); -} - -btCollisionShape *RayShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) { - return prepare(ShapeBullet::create_shape_ray(length * p_implicit_scale[1] + p_extra_edge, slips_on_slope)); -} diff --git a/modules/bullet/shape_bullet.h b/modules/bullet/shape_bullet.h deleted file mode 100644 index dffcadbcdc..0000000000 --- a/modules/bullet/shape_bullet.h +++ /dev/null @@ -1,244 +0,0 @@ -/*************************************************************************/ -/* shape_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 SHAPE_BULLET_H -#define SHAPE_BULLET_H - -#include "core/math/geometry_3d.h" -#include "core/variant/variant.h" -#include "rid_bullet.h" -#include "servers/physics_server_3d.h" - -#include <LinearMath/btAlignedObjectArray.h> -#include <LinearMath/btScalar.h> -#include <LinearMath/btVector3.h> - -class ShapeBullet; -class btCollisionShape; -class ShapeOwnerBullet; -class btBvhTriangleMeshShape; - -class ShapeBullet : public RIDBullet { - Map<ShapeOwnerBullet *, int> owners; - real_t margin = 0.04; - -protected: - /// return self - btCollisionShape *prepare(btCollisionShape *p_btShape) const; - void notifyShapeChanged(); - -public: - ShapeBullet(); - virtual ~ShapeBullet(); - - btCollisionShape *create_bt_shape(const Vector3 &p_implicit_scale, real_t p_extra_edge = 0); - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0) = 0; - - void add_owner(ShapeOwnerBullet *p_owner); - void remove_owner(ShapeOwnerBullet *p_owner, bool p_permanentlyFromThisBody = false); - bool is_owner(ShapeOwnerBullet *p_owner) const; - const Map<ShapeOwnerBullet *, int> &get_owners() const; - - void set_margin(real_t p_margin); - real_t get_margin() const; - - /// Setup the shape - virtual void set_data(const Variant &p_data) = 0; - virtual Variant get_data() const = 0; - - virtual PhysicsServer3D::ShapeType get_type() const = 0; - -public: - static class btEmptyShape *create_shape_empty(); - static class btStaticPlaneShape *create_shape_world_boundary(const btVector3 &planeNormal, btScalar planeConstant); - static class btSphereShape *create_shape_sphere(btScalar radius); - static class btBoxShape *create_shape_box(const btVector3 &boxHalfExtents); - static class btCapsuleShape *create_shape_capsule(btScalar radius, btScalar height); - static class btCylinderShape *create_shape_cylinder(btScalar radius, btScalar height); - /// IMPORTANT: Remember to delete the shape interface by calling: delete my_shape->getMeshInterface(); - static class btConvexPointCloudShape *create_shape_convex(btAlignedObjectArray<btVector3> &p_vertices, const btVector3 &p_local_scaling = btVector3(1, 1, 1)); - static class btScaledBvhTriangleMeshShape *create_shape_concave(btBvhTriangleMeshShape *p_mesh_shape, const btVector3 &p_local_scaling = btVector3(1, 1, 1)); - static class btHeightfieldTerrainShape *create_shape_height_field(Vector<float> &p_heights, int p_width, int p_depth, real_t p_min_height, real_t p_max_height); - static class btRayShape *create_shape_ray(real_t p_length, bool p_slips_on_slope); -}; - -class WorldBoundaryShapeBullet : public ShapeBullet { - Plane plane; - -public: - WorldBoundaryShapeBullet(); - - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(const Plane &p_plane); -}; - -class SphereShapeBullet : public ShapeBullet { - real_t radius = 0.0; - -public: - SphereShapeBullet(); - - _FORCE_INLINE_ real_t get_radius() { return radius; } - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(real_t p_radius); -}; - -class BoxShapeBullet : public ShapeBullet { - btVector3 half_extents; - -public: - BoxShapeBullet(); - - _FORCE_INLINE_ const btVector3 &get_half_extents() { return half_extents; } - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(const Vector3 &p_half_extents); -}; - -class CapsuleShapeBullet : public ShapeBullet { - real_t height = 0.0; - real_t radius = 0.0; - -public: - CapsuleShapeBullet(); - - _FORCE_INLINE_ real_t get_height() { return height; } - _FORCE_INLINE_ real_t get_radius() { return radius; } - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(real_t p_height, real_t p_radius); -}; - -class CylinderShapeBullet : public ShapeBullet { - real_t height = 0.0; - real_t radius = 0.0; - -public: - CylinderShapeBullet(); - - _FORCE_INLINE_ real_t get_height() { return height; } - _FORCE_INLINE_ real_t get_radius() { return radius; } - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_margin = 0); - -private: - void setup(real_t p_height, real_t p_radius); -}; - -class ConvexPolygonShapeBullet : public ShapeBullet { -public: - btAlignedObjectArray<btVector3> vertices; - - ConvexPolygonShapeBullet(); - - virtual void set_data(const Variant &p_data); - void get_vertices(Vector<Vector3> &out_vertices); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(const Vector<Vector3> &p_vertices); -}; - -class ConcavePolygonShapeBullet : public ShapeBullet { - class btBvhTriangleMeshShape *meshShape = nullptr; - -public: - Vector<Vector3> faces; - - ConcavePolygonShapeBullet(); - virtual ~ConcavePolygonShapeBullet(); - - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(Vector<Vector3> p_faces); -}; - -class HeightMapShapeBullet : public ShapeBullet { -public: - Vector<float> heights; - int width = 0; - int depth = 0; - real_t min_height = 0.0; - real_t max_height = 0.0; - - HeightMapShapeBullet(); - - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(Vector<float> &p_heights, int p_width, int p_depth, real_t p_min_height, real_t p_max_height); -}; - -class RayShapeBullet : public ShapeBullet { -public: - real_t length = 1.0; - bool slips_on_slope = false; - - RayShapeBullet(); - - virtual void set_data(const Variant &p_data); - virtual Variant get_data() const; - virtual PhysicsServer3D::ShapeType get_type() const; - virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge = 0); - -private: - void setup(real_t p_length, bool p_slips_on_slope); -}; - -#endif // SHAPE_BULLET_H diff --git a/modules/bullet/shape_owner_bullet.h b/modules/bullet/shape_owner_bullet.h deleted file mode 100644 index 11cf1bc2d5..0000000000 --- a/modules/bullet/shape_owner_bullet.h +++ /dev/null @@ -1,51 +0,0 @@ -/*************************************************************************/ -/* shape_owner_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 SHAPE_OWNER_BULLET_H -#define SHAPE_OWNER_BULLET_H - -#include "rid_bullet.h" - -class ShapeBullet; -class btCollisionShape; -class CollisionObjectBullet; - -/// Each class that want to use Shapes must inherit this class -/// E.G. BodyShape is a child of this -class ShapeOwnerBullet { -public: - virtual int find_shape(ShapeBullet *p_shape) const = 0; - virtual void shape_changed(int p_shape_index) = 0; - virtual void reload_shapes() = 0; - virtual void remove_shape_full(class ShapeBullet *p_shape) = 0; - virtual ~ShapeOwnerBullet() {} -}; - -#endif // SHAPE_OWNER_BULLET_H diff --git a/modules/bullet/slider_joint_bullet.cpp b/modules/bullet/slider_joint_bullet.cpp deleted file mode 100644 index 61c3b3b0a3..0000000000 --- a/modules/bullet/slider_joint_bullet.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/*************************************************************************/ -/* slider_joint_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "slider_joint_bullet.h" - -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "rigid_body_bullet.h" - -#include <BulletDynamics/ConstraintSolver/btSliderConstraint.h> - -SliderJointBullet::SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB) : - JointBullet() { - Transform3D scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); - scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); - - btTransform btFrameA; - G_TO_B(scaled_AFrame, btFrameA); - - if (rbB) { - Transform3D scaled_BFrame(frameInB.scaled(rbB->get_body_scale())); - scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); - - btTransform btFrameB; - G_TO_B(scaled_BFrame, btFrameB); - sliderConstraint = bulletnew(btSliderConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btFrameA, btFrameB, true)); - - } else { - sliderConstraint = bulletnew(btSliderConstraint(*rbA->get_bt_rigid_body(), btFrameA, true)); - } - setup(sliderConstraint); -} - -const RigidBodyBullet *SliderJointBullet::getRigidBodyA() const { - return static_cast<RigidBodyBullet *>(sliderConstraint->getRigidBodyA().getUserPointer()); -} - -const RigidBodyBullet *SliderJointBullet::getRigidBodyB() const { - return static_cast<RigidBodyBullet *>(sliderConstraint->getRigidBodyB().getUserPointer()); -} - -const Transform3D SliderJointBullet::getCalculatedTransformA() const { - btTransform btTransform = sliderConstraint->getCalculatedTransformA(); - Transform3D gTrans; - B_TO_G(btTransform, gTrans); - return gTrans; -} - -const Transform3D SliderJointBullet::getCalculatedTransformB() const { - btTransform btTransform = sliderConstraint->getCalculatedTransformB(); - Transform3D gTrans; - B_TO_G(btTransform, gTrans); - return gTrans; -} - -const Transform3D SliderJointBullet::getFrameOffsetA() const { - btTransform btTransform = sliderConstraint->getFrameOffsetA(); - Transform3D gTrans; - B_TO_G(btTransform, gTrans); - return gTrans; -} - -const Transform3D SliderJointBullet::getFrameOffsetB() const { - btTransform btTransform = sliderConstraint->getFrameOffsetB(); - Transform3D gTrans; - B_TO_G(btTransform, gTrans); - return gTrans; -} - -Transform3D SliderJointBullet::getFrameOffsetA() { - btTransform btTransform = sliderConstraint->getFrameOffsetA(); - Transform3D gTrans; - B_TO_G(btTransform, gTrans); - return gTrans; -} - -Transform3D SliderJointBullet::getFrameOffsetB() { - btTransform btTransform = sliderConstraint->getFrameOffsetB(); - Transform3D gTrans; - B_TO_G(btTransform, gTrans); - return gTrans; -} - -real_t SliderJointBullet::getLowerLinLimit() const { - return sliderConstraint->getLowerLinLimit(); -} - -void SliderJointBullet::setLowerLinLimit(real_t lowerLimit) { - sliderConstraint->setLowerLinLimit(lowerLimit); -} - -real_t SliderJointBullet::getUpperLinLimit() const { - return sliderConstraint->getUpperLinLimit(); -} - -void SliderJointBullet::setUpperLinLimit(real_t upperLimit) { - sliderConstraint->setUpperLinLimit(upperLimit); -} - -real_t SliderJointBullet::getLowerAngLimit() const { - return sliderConstraint->getLowerAngLimit(); -} - -void SliderJointBullet::setLowerAngLimit(real_t lowerLimit) { - sliderConstraint->setLowerAngLimit(lowerLimit); -} - -real_t SliderJointBullet::getUpperAngLimit() const { - return sliderConstraint->getUpperAngLimit(); -} - -void SliderJointBullet::setUpperAngLimit(real_t upperLimit) { - sliderConstraint->setUpperAngLimit(upperLimit); -} - -real_t SliderJointBullet::getSoftnessDirLin() const { - return sliderConstraint->getSoftnessDirLin(); -} - -real_t SliderJointBullet::getRestitutionDirLin() const { - return sliderConstraint->getRestitutionDirLin(); -} - -real_t SliderJointBullet::getDampingDirLin() const { - return sliderConstraint->getDampingDirLin(); -} - -real_t SliderJointBullet::getSoftnessDirAng() const { - return sliderConstraint->getSoftnessDirAng(); -} - -real_t SliderJointBullet::getRestitutionDirAng() const { - return sliderConstraint->getRestitutionDirAng(); -} - -real_t SliderJointBullet::getDampingDirAng() const { - return sliderConstraint->getDampingDirAng(); -} - -real_t SliderJointBullet::getSoftnessLimLin() const { - return sliderConstraint->getSoftnessLimLin(); -} - -real_t SliderJointBullet::getRestitutionLimLin() const { - return sliderConstraint->getRestitutionLimLin(); -} - -real_t SliderJointBullet::getDampingLimLin() const { - return sliderConstraint->getDampingLimLin(); -} - -real_t SliderJointBullet::getSoftnessLimAng() const { - return sliderConstraint->getSoftnessLimAng(); -} - -real_t SliderJointBullet::getRestitutionLimAng() const { - return sliderConstraint->getRestitutionLimAng(); -} - -real_t SliderJointBullet::getDampingLimAng() const { - return sliderConstraint->getDampingLimAng(); -} - -real_t SliderJointBullet::getSoftnessOrthoLin() const { - return sliderConstraint->getSoftnessOrthoLin(); -} - -real_t SliderJointBullet::getRestitutionOrthoLin() const { - return sliderConstraint->getRestitutionOrthoLin(); -} - -real_t SliderJointBullet::getDampingOrthoLin() const { - return sliderConstraint->getDampingOrthoLin(); -} - -real_t SliderJointBullet::getSoftnessOrthoAng() const { - return sliderConstraint->getSoftnessOrthoAng(); -} - -real_t SliderJointBullet::getRestitutionOrthoAng() const { - return sliderConstraint->getRestitutionOrthoAng(); -} - -real_t SliderJointBullet::getDampingOrthoAng() const { - return sliderConstraint->getDampingOrthoAng(); -} - -void SliderJointBullet::setSoftnessDirLin(real_t softnessDirLin) { - sliderConstraint->setSoftnessDirLin(softnessDirLin); -} - -void SliderJointBullet::setRestitutionDirLin(real_t restitutionDirLin) { - sliderConstraint->setRestitutionDirLin(restitutionDirLin); -} - -void SliderJointBullet::setDampingDirLin(real_t dampingDirLin) { - sliderConstraint->setDampingDirLin(dampingDirLin); -} - -void SliderJointBullet::setSoftnessDirAng(real_t softnessDirAng) { - sliderConstraint->setSoftnessDirAng(softnessDirAng); -} - -void SliderJointBullet::setRestitutionDirAng(real_t restitutionDirAng) { - sliderConstraint->setRestitutionDirAng(restitutionDirAng); -} - -void SliderJointBullet::setDampingDirAng(real_t dampingDirAng) { - sliderConstraint->setDampingDirAng(dampingDirAng); -} - -void SliderJointBullet::setSoftnessLimLin(real_t softnessLimLin) { - sliderConstraint->setSoftnessLimLin(softnessLimLin); -} - -void SliderJointBullet::setRestitutionLimLin(real_t restitutionLimLin) { - sliderConstraint->setRestitutionLimLin(restitutionLimLin); -} - -void SliderJointBullet::setDampingLimLin(real_t dampingLimLin) { - sliderConstraint->setDampingLimLin(dampingLimLin); -} - -void SliderJointBullet::setSoftnessLimAng(real_t softnessLimAng) { - sliderConstraint->setSoftnessLimAng(softnessLimAng); -} - -void SliderJointBullet::setRestitutionLimAng(real_t restitutionLimAng) { - sliderConstraint->setRestitutionLimAng(restitutionLimAng); -} - -void SliderJointBullet::setDampingLimAng(real_t dampingLimAng) { - sliderConstraint->setDampingLimAng(dampingLimAng); -} - -void SliderJointBullet::setSoftnessOrthoLin(real_t softnessOrthoLin) { - sliderConstraint->setSoftnessOrthoLin(softnessOrthoLin); -} - -void SliderJointBullet::setRestitutionOrthoLin(real_t restitutionOrthoLin) { - sliderConstraint->setRestitutionOrthoLin(restitutionOrthoLin); -} - -void SliderJointBullet::setDampingOrthoLin(real_t dampingOrthoLin) { - sliderConstraint->setDampingOrthoLin(dampingOrthoLin); -} - -void SliderJointBullet::setSoftnessOrthoAng(real_t softnessOrthoAng) { - sliderConstraint->setSoftnessOrthoAng(softnessOrthoAng); -} - -void SliderJointBullet::setRestitutionOrthoAng(real_t restitutionOrthoAng) { - sliderConstraint->setRestitutionOrthoAng(restitutionOrthoAng); -} - -void SliderJointBullet::setDampingOrthoAng(real_t dampingOrthoAng) { - sliderConstraint->setDampingOrthoAng(dampingOrthoAng); -} - -void SliderJointBullet::setPoweredLinMotor(bool onOff) { - sliderConstraint->setPoweredLinMotor(onOff); -} - -bool SliderJointBullet::getPoweredLinMotor() { - return sliderConstraint->getPoweredLinMotor(); -} - -void SliderJointBullet::setTargetLinMotorVelocity(real_t targetLinMotorVelocity) { - sliderConstraint->setTargetLinMotorVelocity(targetLinMotorVelocity); -} - -real_t SliderJointBullet::getTargetLinMotorVelocity() { - return sliderConstraint->getTargetLinMotorVelocity(); -} - -void SliderJointBullet::setMaxLinMotorForce(real_t maxLinMotorForce) { - sliderConstraint->setMaxLinMotorForce(maxLinMotorForce); -} - -real_t SliderJointBullet::getMaxLinMotorForce() { - return sliderConstraint->getMaxLinMotorForce(); -} - -void SliderJointBullet::setPoweredAngMotor(bool onOff) { - sliderConstraint->setPoweredAngMotor(onOff); -} - -bool SliderJointBullet::getPoweredAngMotor() { - return sliderConstraint->getPoweredAngMotor(); -} - -void SliderJointBullet::setTargetAngMotorVelocity(real_t targetAngMotorVelocity) { - sliderConstraint->setTargetAngMotorVelocity(targetAngMotorVelocity); -} - -real_t SliderJointBullet::getTargetAngMotorVelocity() { - return sliderConstraint->getTargetAngMotorVelocity(); -} - -void SliderJointBullet::setMaxAngMotorForce(real_t maxAngMotorForce) { - sliderConstraint->setMaxAngMotorForce(maxAngMotorForce); -} - -real_t SliderJointBullet::getMaxAngMotorForce() { - return sliderConstraint->getMaxAngMotorForce(); -} - -real_t SliderJointBullet::getLinearPos() { - return sliderConstraint->getLinearPos(); - ; -} - -void SliderJointBullet::set_param(PhysicsServer3D::SliderJointParam p_param, real_t p_value) { - switch (p_param) { - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: - setUpperLinLimit(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: - setLowerLinLimit(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: - setSoftnessLimLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: - setRestitutionLimLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: - setDampingLimLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: - setSoftnessDirLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: - setRestitutionDirLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: - setDampingDirLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: - setSoftnessOrthoLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: - setRestitutionOrthoLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: - setDampingOrthoLin(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: - setUpperAngLimit(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: - setLowerAngLimit(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: - setSoftnessLimAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: - setRestitutionLimAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: - setDampingLimAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: - setSoftnessDirAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: - setRestitutionDirAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: - setDampingDirAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: - setSoftnessOrthoAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: - setRestitutionOrthoAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: - setDampingOrthoAng(p_value); - break; - case PhysicsServer3D::SLIDER_JOINT_MAX: - break; // Can't happen, but silences warning - } -} - -real_t SliderJointBullet::get_param(PhysicsServer3D::SliderJointParam p_param) const { - switch (p_param) { - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: - return getUpperLinLimit(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: - return getLowerLinLimit(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: - return getSoftnessLimLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: - return getRestitutionLimLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: - return getDampingLimLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: - return getSoftnessDirLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: - return getRestitutionDirLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: - return getDampingDirLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: - return getSoftnessOrthoLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: - return getRestitutionOrthoLin(); - case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: - return getDampingOrthoLin(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: - return getUpperAngLimit(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: - return getLowerAngLimit(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: - return getSoftnessLimAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: - return getRestitutionLimAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: - return getDampingLimAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: - return getSoftnessDirAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: - return getRestitutionDirAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: - return getDampingDirAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: - return getSoftnessOrthoAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: - return getRestitutionOrthoAng(); - case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: - return getDampingOrthoAng(); - default: - return 0; - } -} diff --git a/modules/bullet/slider_joint_bullet.h b/modules/bullet/slider_joint_bullet.h deleted file mode 100644 index c355eb340b..0000000000 --- a/modules/bullet/slider_joint_bullet.h +++ /dev/null @@ -1,118 +0,0 @@ -/*************************************************************************/ -/* slider_joint_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 SLIDER_JOINT_BULLET_H -#define SLIDER_JOINT_BULLET_H - -#include "joint_bullet.h" - -class RigidBodyBullet; - -class SliderJointBullet : public JointBullet { - class btSliderConstraint *sliderConstraint; - -public: - /// Reference frame is A - SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB); - - virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_SLIDER; } - - const RigidBodyBullet *getRigidBodyA() const; - const RigidBodyBullet *getRigidBodyB() const; - const Transform3D getCalculatedTransformA() const; - const Transform3D getCalculatedTransformB() const; - const Transform3D getFrameOffsetA() const; - const Transform3D getFrameOffsetB() const; - Transform3D getFrameOffsetA(); - Transform3D getFrameOffsetB(); - real_t getLowerLinLimit() const; - void setLowerLinLimit(real_t lowerLimit); - real_t getUpperLinLimit() const; - void setUpperLinLimit(real_t upperLimit); - real_t getLowerAngLimit() const; - void setLowerAngLimit(real_t lowerLimit); - real_t getUpperAngLimit() const; - void setUpperAngLimit(real_t upperLimit); - - real_t getSoftnessDirLin() const; - real_t getRestitutionDirLin() const; - real_t getDampingDirLin() const; - real_t getSoftnessDirAng() const; - real_t getRestitutionDirAng() const; - real_t getDampingDirAng() const; - real_t getSoftnessLimLin() const; - real_t getRestitutionLimLin() const; - real_t getDampingLimLin() const; - real_t getSoftnessLimAng() const; - real_t getRestitutionLimAng() const; - real_t getDampingLimAng() const; - real_t getSoftnessOrthoLin() const; - real_t getRestitutionOrthoLin() const; - real_t getDampingOrthoLin() const; - real_t getSoftnessOrthoAng() const; - real_t getRestitutionOrthoAng() const; - real_t getDampingOrthoAng() const; - void setSoftnessDirLin(real_t softnessDirLin); - void setRestitutionDirLin(real_t restitutionDirLin); - void setDampingDirLin(real_t dampingDirLin); - void setSoftnessDirAng(real_t softnessDirAng); - void setRestitutionDirAng(real_t restitutionDirAng); - void setDampingDirAng(real_t dampingDirAng); - void setSoftnessLimLin(real_t softnessLimLin); - void setRestitutionLimLin(real_t restitutionLimLin); - void setDampingLimLin(real_t dampingLimLin); - void setSoftnessLimAng(real_t softnessLimAng); - void setRestitutionLimAng(real_t restitutionLimAng); - void setDampingLimAng(real_t dampingLimAng); - void setSoftnessOrthoLin(real_t softnessOrthoLin); - void setRestitutionOrthoLin(real_t restitutionOrthoLin); - void setDampingOrthoLin(real_t dampingOrthoLin); - void setSoftnessOrthoAng(real_t softnessOrthoAng); - void setRestitutionOrthoAng(real_t restitutionOrthoAng); - void setDampingOrthoAng(real_t dampingOrthoAng); - void setPoweredLinMotor(bool onOff); - bool getPoweredLinMotor(); - void setTargetLinMotorVelocity(real_t targetLinMotorVelocity); - real_t getTargetLinMotorVelocity(); - void setMaxLinMotorForce(real_t maxLinMotorForce); - real_t getMaxLinMotorForce(); - void setPoweredAngMotor(bool onOff); - bool getPoweredAngMotor(); - void setTargetAngMotorVelocity(real_t targetAngMotorVelocity); - real_t getTargetAngMotorVelocity(); - void setMaxAngMotorForce(real_t maxAngMotorForce); - real_t getMaxAngMotorForce(); - real_t getLinearPos(); - - void set_param(PhysicsServer3D::SliderJointParam p_param, real_t p_value); - real_t get_param(PhysicsServer3D::SliderJointParam p_param) const; -}; - -#endif // SLIDER_JOINT_BULLET_H diff --git a/modules/bullet/soft_body_bullet.cpp b/modules/bullet/soft_body_bullet.cpp deleted file mode 100644 index ea5a059b9e..0000000000 --- a/modules/bullet/soft_body_bullet.cpp +++ /dev/null @@ -1,456 +0,0 @@ -/*************************************************************************/ -/* soft_body_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "soft_body_bullet.h" - -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "space_bullet.h" - -#include "servers/rendering_server.h" - -SoftBodyBullet::SoftBodyBullet() : - CollisionObjectBullet(CollisionObjectBullet::TYPE_SOFT_BODY) {} - -SoftBodyBullet::~SoftBodyBullet() { -} - -void SoftBodyBullet::reload_body() { - if (space) { - space->remove_soft_body(this); - space->add_soft_body(this); - } -} - -void SoftBodyBullet::set_space(SpaceBullet *p_space) { - if (space) { - isScratched = false; - space->remove_soft_body(this); - } - - space = p_space; - - if (space) { - space->add_soft_body(this); - } -} - -void SoftBodyBullet::on_enter_area(AreaBullet *p_area) {} - -void SoftBodyBullet::on_exit_area(AreaBullet *p_area) {} - -void SoftBodyBullet::update_rendering_server(RenderingServerHandler *p_rendering_server_handler) { - if (!bt_soft_body) { - return; - } - - /// Update rendering server vertices - const btSoftBody::tNodeArray &nodes(bt_soft_body->m_nodes); - const int nodes_count = nodes.size(); - - const Vector<int> *vs_indices; - const void *vertex_position; - const void *vertex_normal; - - for (int vertex_index = 0; vertex_index < nodes_count; ++vertex_index) { - vertex_position = reinterpret_cast<const void *>(&nodes[vertex_index].m_x); - vertex_normal = reinterpret_cast<const void *>(&nodes[vertex_index].m_n); - - vs_indices = &indices_table[vertex_index]; - - const int vs_indices_size(vs_indices->size()); - for (int x = 0; x < vs_indices_size; ++x) { - p_rendering_server_handler->set_vertex((*vs_indices)[x], vertex_position); - p_rendering_server_handler->set_normal((*vs_indices)[x], vertex_normal); - } - } - - /// Generate AABB - btVector3 aabb_min; - btVector3 aabb_max; - bt_soft_body->getAabb(aabb_min, aabb_max); - - btVector3 size(aabb_max - aabb_min); - - AABB aabb; - B_TO_G(aabb_min, aabb.position); - B_TO_G(size, aabb.size); - - p_rendering_server_handler->set_aabb(aabb); -} - -void SoftBodyBullet::set_soft_mesh(RID p_mesh) { - destroy_soft_body(); - - soft_mesh = p_mesh; - - if (soft_mesh.is_null()) { - return; - } - - Array arrays = RenderingServer::get_singleton()->mesh_surface_get_arrays(soft_mesh, 0); - ERR_FAIL_COND(arrays.is_empty()); - - bool success = set_trimesh_body_shape(arrays[RS::ARRAY_INDEX], arrays[RS::ARRAY_VERTEX]); - if (!success) { - destroy_soft_body(); - } -} - -void SoftBodyBullet::destroy_soft_body() { - soft_mesh = RID(); - - if (!bt_soft_body) { - return; - } - - if (space) { - /// Remove from world before deletion - space->remove_soft_body(this); - } - - destroyBulletCollisionObject(); - bt_soft_body = nullptr; -} - -void SoftBodyBullet::set_soft_transform(const Transform3D &p_transform) { - reset_all_node_positions(); - move_all_nodes(p_transform); -} - -AABB SoftBodyBullet::get_bounds() const { - if (!bt_soft_body) { - return AABB(); - } - - btVector3 aabb_min; - btVector3 aabb_max; - bt_soft_body->getAabb(aabb_min, aabb_max); - - btVector3 size(aabb_max - aabb_min); - - AABB aabb; - B_TO_G(aabb_min, aabb.position); - B_TO_G(size, aabb.size); - - return aabb; -} - -void SoftBodyBullet::move_all_nodes(const Transform3D &p_transform) { - if (!bt_soft_body) { - return; - } - btTransform bt_transf; - G_TO_B(p_transform, bt_transf); - bt_soft_body->transform(bt_transf); -} - -void SoftBodyBullet::set_node_position(int p_node_index, const Vector3 &p_global_position) { - btVector3 bt_pos; - G_TO_B(p_global_position, bt_pos); - set_node_position(p_node_index, bt_pos); -} - -void SoftBodyBullet::set_node_position(int p_node_index, const btVector3 &p_global_position) { - if (bt_soft_body) { - bt_soft_body->m_nodes[p_node_index].m_q = bt_soft_body->m_nodes[p_node_index].m_x; - bt_soft_body->m_nodes[p_node_index].m_x = p_global_position; - } -} - -void SoftBodyBullet::get_node_position(int p_node_index, Vector3 &r_position) const { - if (bt_soft_body) { - B_TO_G(bt_soft_body->m_nodes[p_node_index].m_x, r_position); - } -} - -void SoftBodyBullet::set_node_mass(int p_node_index, btScalar p_mass) { - if (0 >= p_mass) { - pin_node(p_node_index); - } else { - unpin_node(p_node_index); - } - if (bt_soft_body) { - ERR_FAIL_INDEX(p_node_index, bt_soft_body->m_nodes.size()); - bt_soft_body->setMass(p_node_index, p_mass); - } -} - -btScalar SoftBodyBullet::get_node_mass(int p_node_index) const { - if (bt_soft_body) { - ERR_FAIL_INDEX_V(p_node_index, bt_soft_body->m_nodes.size(), 1); - return bt_soft_body->getMass(p_node_index); - } else { - return -1 == search_node_pinned(p_node_index) ? 1 : 0; - } -} - -void SoftBodyBullet::reset_all_node_mass() { - if (bt_soft_body) { - for (int i = pinned_nodes.size() - 1; 0 <= i; --i) { - bt_soft_body->setMass(pinned_nodes[i], 1); - } - } - pinned_nodes.resize(0); -} - -void SoftBodyBullet::reset_all_node_positions() { - if (soft_mesh.is_null()) { - return; - } - - Array arrays = soft_mesh->surface_get_arrays(0); - Vector<Vector3> vs_vertices(arrays[RS::ARRAY_VERTEX]); - const Vector3 *vs_vertices_read = vs_vertices.ptr(); - - for (int vertex_index = bt_soft_body->m_nodes.size() - 1; 0 <= vertex_index; --vertex_index) { - G_TO_B(vs_vertices_read[indices_table[vertex_index][0]], bt_soft_body->m_nodes[vertex_index].m_x); - - bt_soft_body->m_nodes[vertex_index].m_q = bt_soft_body->m_nodes[vertex_index].m_x; - bt_soft_body->m_nodes[vertex_index].m_v = btVector3(0, 0, 0); - bt_soft_body->m_nodes[vertex_index].m_f = btVector3(0, 0, 0); - } -} - -void SoftBodyBullet::set_activation_state(bool p_active) { - if (p_active) { - bt_soft_body->setActivationState(ACTIVE_TAG); - } else { - bt_soft_body->setActivationState(WANTS_DEACTIVATION); - } -} - -void SoftBodyBullet::set_total_mass(real_t p_val) { - if (0 >= p_val) { - p_val = 1; - } - total_mass = p_val; - if (bt_soft_body) { - bt_soft_body->setTotalMass(total_mass); - } -} - -void SoftBodyBullet::set_linear_stiffness(real_t p_val) { - linear_stiffness = p_val; - if (bt_soft_body) { - mat0->m_kLST = linear_stiffness; - } -} - -void SoftBodyBullet::set_simulation_precision(int p_val) { - simulation_precision = p_val; - if (bt_soft_body) { - bt_soft_body->m_cfg.piterations = simulation_precision; - bt_soft_body->m_cfg.viterations = simulation_precision; - bt_soft_body->m_cfg.diterations = simulation_precision; - bt_soft_body->m_cfg.citerations = simulation_precision; - } -} - -void SoftBodyBullet::set_pressure_coefficient(real_t p_val) { - pressure_coefficient = p_val; - if (bt_soft_body) { - bt_soft_body->m_cfg.kPR = pressure_coefficient; - } -} - -void SoftBodyBullet::set_damping_coefficient(real_t p_val) { - damping_coefficient = p_val; - if (bt_soft_body) { - bt_soft_body->m_cfg.kDP = damping_coefficient; - } -} - -void SoftBodyBullet::set_drag_coefficient(real_t p_val) { - drag_coefficient = p_val; - if (bt_soft_body) { - bt_soft_body->m_cfg.kDG = drag_coefficient; - } -} - -bool SoftBodyBullet::set_trimesh_body_shape(Vector<int> p_indices, Vector<Vector3> p_vertices) { - ERR_FAIL_COND_V(p_indices.is_empty(), false); - ERR_FAIL_COND_V(p_vertices.is_empty(), false); - - /// Parse rendering server indices to physical indices. - /// Merge all overlapping vertices and create a map of physical vertices to rendering server - - { - /// This is the map of rendering server indices to physics indices (So it's the inverse of idices_map), Thanks to it I don't need make a heavy search in the indices_map - Vector<int> vs_indices_to_physics_table; - - { // Map vertices - indices_table.resize(0); - - int index = 0; - Map<Vector3, int> unique_vertices; - - const int vs_vertices_size(p_vertices.size()); - - const Vector3 *p_vertices_read = p_vertices.ptr(); - - for (int vs_vertex_index = 0; vs_vertex_index < vs_vertices_size; ++vs_vertex_index) { - Map<Vector3, int>::Element *e = unique_vertices.find(p_vertices_read[vs_vertex_index]); - int vertex_id; - if (e) { - // Already existing - vertex_id = e->value(); - } else { - // Create new one - unique_vertices[p_vertices_read[vs_vertex_index]] = vertex_id = index++; - indices_table.push_back(Vector<int>()); - } - - indices_table.write[vertex_id].push_back(vs_vertex_index); - vs_indices_to_physics_table.push_back(vertex_id); - } - } - - const int indices_map_size(indices_table.size()); - - Vector<btScalar> bt_vertices; - - { // Parse vertices to bullet - - bt_vertices.resize(indices_map_size * 3); - const Vector3 *p_vertices_read = p_vertices.ptr(); - - for (int i = 0; i < indices_map_size; ++i) { - bt_vertices.write[3 * i + 0] = p_vertices_read[indices_table[i][0]].x; - bt_vertices.write[3 * i + 1] = p_vertices_read[indices_table[i][0]].y; - bt_vertices.write[3 * i + 2] = p_vertices_read[indices_table[i][0]].z; - } - } - - Vector<int> bt_triangles; - const int triangles_size(p_indices.size() / 3); - - { // Parse indices - - bt_triangles.resize(triangles_size * 3); - - const int *p_indices_read = p_indices.ptr(); - - for (int i = 0; i < triangles_size; ++i) { - bt_triangles.write[3 * i + 0] = vs_indices_to_physics_table[p_indices_read[3 * i + 2]]; - bt_triangles.write[3 * i + 1] = vs_indices_to_physics_table[p_indices_read[3 * i + 1]]; - bt_triangles.write[3 * i + 2] = vs_indices_to_physics_table[p_indices_read[3 * i + 0]]; - } - } - - btSoftBodyWorldInfo fake_world_info; - bt_soft_body = btSoftBodyHelpers::CreateFromTriMesh(fake_world_info, &bt_vertices[0], &bt_triangles[0], triangles_size, false); - setup_soft_body(); - } - - return true; -} - -void SoftBodyBullet::setup_soft_body() { - if (!bt_soft_body) { - return; - } - - // Soft body setup - setupBulletCollisionObject(bt_soft_body); - bt_soft_body->m_worldInfo = nullptr; // Remove fake world info - bt_soft_body->getCollisionShape()->setMargin(0.01); - bt_soft_body->setCollisionFlags(bt_soft_body->getCollisionFlags() & (~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT))); - - // Space setup - if (space) { - space->add_soft_body(this); - } - - mat0 = bt_soft_body->appendMaterial(); - - // Assign soft body data - bt_soft_body->generateBendingConstraints(2, mat0); - - mat0->m_kLST = linear_stiffness; - - // Clusters allow to have Soft vs Soft collision but doesn't work well right now - - //bt_soft_body->m_cfg.kSRHR_CL = 1;// Soft vs rigid hardness [0,1] (cluster only) - //bt_soft_body->m_cfg.kSKHR_CL = 1;// Soft vs kinematic hardness [0,1] (cluster only) - //bt_soft_body->m_cfg.kSSHR_CL = 1;// Soft vs soft hardness [0,1] (cluster only) - //bt_soft_body->m_cfg.kSR_SPLT_CL = 1; // Soft vs rigid impulse split [0,1] (cluster only) - //bt_soft_body->m_cfg.kSK_SPLT_CL = 1; // Soft vs kinematic impulse split [0,1] (cluster only) - //bt_soft_body->m_cfg.kSS_SPLT_CL = 1; // Soft vs Soft impulse split [0,1] (cluster only) - //bt_soft_body->m_cfg.collisions = btSoftBody::fCollision::CL_SS + btSoftBody::fCollision::CL_RS + btSoftBody::fCollision::VF_SS; - //bt_soft_body->generateClusters(64); - - bt_soft_body->m_cfg.piterations = simulation_precision; - bt_soft_body->m_cfg.viterations = simulation_precision; - bt_soft_body->m_cfg.diterations = simulation_precision; - bt_soft_body->m_cfg.citerations = simulation_precision; - bt_soft_body->m_cfg.kDP = damping_coefficient; - bt_soft_body->m_cfg.kDG = drag_coefficient; - bt_soft_body->m_cfg.kPR = pressure_coefficient; - bt_soft_body->setTotalMass(total_mass); - - btSoftBodyHelpers::ReoptimizeLinkOrder(bt_soft_body); - bt_soft_body->updateBounds(); - - // Set pinned nodes - for (int i = pinned_nodes.size() - 1; 0 <= i; --i) { - const int node_index = pinned_nodes[i]; - ERR_CONTINUE(0 > node_index || bt_soft_body->m_nodes.size() <= node_index); - bt_soft_body->setMass(node_index, 0); - } -} - -void SoftBodyBullet::pin_node(int p_node_index) { - if (bt_soft_body) { - ERR_FAIL_INDEX(p_node_index, bt_soft_body->m_nodes.size()); - } - if (-1 == search_node_pinned(p_node_index)) { - pinned_nodes.push_back(p_node_index); - } -} - -void SoftBodyBullet::unpin_node(int p_node_index) { - if (bt_soft_body) { - ERR_FAIL_INDEX(p_node_index, bt_soft_body->m_nodes.size()); - } - const int id = search_node_pinned(p_node_index); - if (-1 != id) { - pinned_nodes.remove_at(id); - } -} - -int SoftBodyBullet::search_node_pinned(int p_node_index) const { - for (int i = pinned_nodes.size() - 1; 0 <= i; --i) { - if (p_node_index == pinned_nodes[i]) { - return i; - } - } - return -1; -} diff --git a/modules/bullet/soft_body_bullet.h b/modules/bullet/soft_body_bullet.h deleted file mode 100644 index 82a7bb3b0c..0000000000 --- a/modules/bullet/soft_body_bullet.h +++ /dev/null @@ -1,144 +0,0 @@ -/*************************************************************************/ -/* soft_body_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef SOFT_BODY_BULLET_H -#define SOFT_BODY_BULLET_H - -#include "collision_object_bullet.h" - -#ifdef None -/// This is required to remove the macro None defined by x11 compiler because this word "None" is used internally by Bullet -#undef None -#define x11_None 0L -#endif - -#include "BulletSoftBody/btSoftBodyHelpers.h" -#include "collision_object_bullet.h" -#include "servers/physics_server_3d.h" - -#ifdef x11_None -/// This is required to re add the macro None defined by x11 compiler -#undef x11_None -#define None 0L -#endif - -class RenderingServerHandler; - -class SoftBodyBullet : public CollisionObjectBullet { -private: - btSoftBody *bt_soft_body = nullptr; - Vector<Vector<int>> indices_table; - btSoftBody::Material *mat0 = nullptr; // This is just a copy of pointer managed by btSoftBody - bool isScratched = false; - - RID soft_mesh; - - int simulation_precision = 5; - real_t total_mass = 1.; - real_t linear_stiffness = 0.5; // [0,1] - real_t pressure_coefficient = 0.; // [-inf,+inf] - real_t damping_coefficient = 0.01; // [0,1] - real_t drag_coefficient = 0.; // [0,1] - Vector<int> pinned_nodes; - - // Other property to add - //btScalar kVC; // Volume conversation coefficient [0,+inf] - //btScalar kDF; // Dynamic friction coefficient [0,1] - //btScalar kMT; // Pose matching coefficient [0,1] - //btScalar kCHR; // Rigid contacts hardness [0,1] - //btScalar kKHR; // Kinetic contacts hardness [0,1] - //btScalar kSHR; // Soft contacts hardness [0,1] - -public: - SoftBodyBullet(); - ~SoftBodyBullet(); - - virtual void reload_body(); - virtual void set_space(SpaceBullet *p_space); - - virtual void dispatch_callbacks() {} - virtual void on_collision_filters_change() {} - virtual void on_collision_checker_start() {} - virtual void on_collision_checker_end() {} - virtual void on_enter_area(AreaBullet *p_area); - virtual void on_exit_area(AreaBullet *p_area); - - _FORCE_INLINE_ btSoftBody *get_bt_soft_body() const { return bt_soft_body; } - - void update_rendering_server(RenderingServerHandler *p_rendering_server_handler); - - void set_soft_mesh(RID p_mesh); - void destroy_soft_body(); - - // Special function. This function has bad performance - void set_soft_transform(const Transform3D &p_transform); - - AABB get_bounds() const; - - void move_all_nodes(const Transform3D &p_transform); - void set_node_position(int node_index, const Vector3 &p_global_position); - void set_node_position(int node_index, const btVector3 &p_global_position); - void get_node_position(int node_index, Vector3 &r_position) const; - - void set_node_mass(int node_index, btScalar p_mass); - btScalar get_node_mass(int node_index) const; - void reset_all_node_mass(); - void reset_all_node_positions(); - - void set_activation_state(bool p_active); - - void set_total_mass(real_t p_val); - _FORCE_INLINE_ real_t get_total_mass() const { return total_mass; } - - void set_linear_stiffness(real_t p_val); - _FORCE_INLINE_ real_t get_linear_stiffness() const { return linear_stiffness; } - - void set_simulation_precision(int p_val); - _FORCE_INLINE_ int get_simulation_precision() const { return simulation_precision; } - - void set_pressure_coefficient(real_t p_val); - _FORCE_INLINE_ real_t get_pressure_coefficient() const { return pressure_coefficient; } - - void set_damping_coefficient(real_t p_val); - _FORCE_INLINE_ real_t get_damping_coefficient() const { return damping_coefficient; } - - void set_drag_coefficient(real_t p_val); - _FORCE_INLINE_ real_t get_drag_coefficient() const { return drag_coefficient; } - -private: - bool set_trimesh_body_shape(Vector<int> p_indices, Vector<Vector3> p_vertices); - void setup_soft_body(); - - void pin_node(int p_node_index); - void unpin_node(int p_node_index); - int search_node_pinned(int p_node_index) const; -}; - -#endif // SOFT_BODY_BULLET_H diff --git a/modules/bullet/space_bullet.cpp b/modules/bullet/space_bullet.cpp deleted file mode 100644 index 460b78d778..0000000000 --- a/modules/bullet/space_bullet.cpp +++ /dev/null @@ -1,1436 +0,0 @@ -/*************************************************************************/ -/* space_bullet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "space_bullet.h" - -#include "bullet_physics_server.h" -#include "bullet_types_converter.h" -#include "bullet_utilities.h" -#include "constraint_bullet.h" -#include "core/config/project_settings.h" -#include "core/string/ustring.h" -#include "godot_collision_configuration.h" -#include "godot_collision_dispatcher.h" -#include "rigid_body_bullet.h" -#include "servers/physics_server_3d.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> -#include <BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h> -#include <BulletCollision/NarrowPhaseCollision/btPointCollector.h> -#include <BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h> -#include <BulletSoftBody/btSoftRigidDynamicsWorld.h> -#include <btBulletDynamicsCommon.h> - -#include <assert.h> - -BulletPhysicsDirectSpaceState::BulletPhysicsDirectSpaceState(SpaceBullet *p_space) : - PhysicsDirectSpaceState3D(), - space(p_space) {} - -int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - if (p_result_max <= 0) { - return 0; - } - - btVector3 bt_point; - G_TO_B(p_point, bt_point); - - btSphereShape sphere_point(0.001f); - btCollisionObject collision_object_point; - collision_object_point.setCollisionShape(&sphere_point); - collision_object_point.setWorldTransform(btTransform(btQuaternion::getIdentity(), bt_point)); - - // Setup query - GodotAllContactResultCallback btResult(&collision_object_point, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas); - btResult.m_collisionFilterGroup = 0; - btResult.m_collisionFilterMask = p_collision_mask; - space->dynamicsWorld->contactTest(&collision_object_point, btResult); - - // The results are already populated by GodotAllConvexResultCallback - return btResult.m_count; -} - -bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_ray) { - btVector3 btVec_from; - btVector3 btVec_to; - - G_TO_B(p_from, btVec_from); - G_TO_B(p_to, btVec_to); - - // setup query - GodotClosestRayResultCallback btResult(btVec_from, btVec_to, &p_exclude, p_collide_with_bodies, p_collide_with_areas); - btResult.m_collisionFilterGroup = 0; - btResult.m_collisionFilterMask = p_collision_mask; - btResult.m_pickRay = p_pick_ray; - - space->dynamicsWorld->rayTest(btVec_from, btVec_to, btResult); - if (btResult.hasHit()) { - B_TO_G(btResult.m_hitPointWorld, r_result.position); - B_TO_G(btResult.m_hitNormalWorld.normalize(), r_result.normal); - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btResult.m_collisionObject->getUserPointer()); - if (gObj) { - r_result.shape = btResult.m_shapeId; - r_result.rid = gObj->get_self(); - r_result.collider_id = gObj->get_instance_id(); - r_result.collider = r_result.collider_id.is_null() ? nullptr : ObjectDB::get_instance(r_result.collider_id); - } else { - WARN_PRINT("The raycast performed has hit a collision object that is not part of Godot scene, please check it."); - } - return true; - } else { - return false; - } -} - -int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform3D &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - if (p_result_max <= 0) { - return 0; - } - - ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get_or_null(p_shape); - ERR_FAIL_COND_V(!shape, 0); - - btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale_abs(), p_margin); - if (!btShape->isConvex()) { - bulletdelete(btShape); - ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type())); - return 0; - } - btConvexShape *btConvex = static_cast<btConvexShape *>(btShape); - - btTransform bt_xform; - G_TO_B(p_xform, bt_xform); - UNSCALE_BT_BASIS(bt_xform); - - btCollisionObject collision_object; - collision_object.setCollisionShape(btConvex); - collision_object.setWorldTransform(bt_xform); - - GodotAllContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas); - btQuery.m_collisionFilterGroup = 0; - btQuery.m_collisionFilterMask = p_collision_mask; - btQuery.m_closestDistanceThreshold = 0; - space->dynamicsWorld->contactTest(&collision_object, btQuery); - - bulletdelete(btConvex); - - return btQuery.m_count; -} - -bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transform3D &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &r_closest_safe, real_t &r_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, ShapeRestInfo *r_info) { - r_closest_safe = 0.0f; - r_closest_unsafe = 0.0f; - btVector3 bt_motion; - G_TO_B(p_motion, bt_motion); - - ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get_or_null(p_shape); - ERR_FAIL_COND_V(!shape, false); - - btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale(), p_margin); - if (!btShape->isConvex()) { - bulletdelete(btShape); - ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type())); - return false; - } - btConvexShape *bt_convex_shape = static_cast<btConvexShape *>(btShape); - - btTransform bt_xform_from; - G_TO_B(p_xform, bt_xform_from); - UNSCALE_BT_BASIS(bt_xform_from); - - btTransform bt_xform_to(bt_xform_from); - bt_xform_to.getOrigin() += bt_motion; - - if ((bt_xform_to.getOrigin() - bt_xform_from.getOrigin()).fuzzyZero()) { - r_closest_safe = 1.0f; - r_closest_unsafe = 1.0f; - bulletdelete(btShape); - return true; - } - - GodotClosestConvexResultCallback btResult(bt_xform_from.getOrigin(), bt_xform_to.getOrigin(), &p_exclude, p_collide_with_bodies, p_collide_with_areas); - btResult.m_collisionFilterGroup = 0; - btResult.m_collisionFilterMask = p_collision_mask; - - space->dynamicsWorld->convexSweepTest(bt_convex_shape, bt_xform_from, bt_xform_to, btResult, space->dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration); - - if (btResult.hasHit()) { - const btScalar l = bt_motion.length(); - r_closest_unsafe = btResult.m_closestHitFraction; - r_closest_safe = MAX(r_closest_unsafe - (1 - ((l - 0.01) / l)), 0); - if (r_info) { - if (btCollisionObject::CO_RIGID_BODY == btResult.m_hitCollisionObject->getInternalType()) { - B_TO_G(static_cast<const btRigidBody *>(btResult.m_hitCollisionObject)->getVelocityInLocalPoint(btResult.m_hitPointWorld), r_info->linear_velocity); - } - CollisionObjectBullet *collision_object = static_cast<CollisionObjectBullet *>(btResult.m_hitCollisionObject->getUserPointer()); - B_TO_G(btResult.m_hitPointWorld, r_info->point); - B_TO_G(btResult.m_hitNormalWorld, r_info->normal); - r_info->rid = collision_object->get_self(); - r_info->collider_id = collision_object->get_instance_id(); - r_info->shape = btResult.m_shapeId; - } - } else { - r_closest_safe = 1.0f; - r_closest_unsafe = 1.0f; - } - - bulletdelete(bt_convex_shape); - return true; // Mean success -} - -/// Returns the list of contacts pairs in this order: Local contact, other body contact -bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - if (p_result_max <= 0) { - return false; - } - - ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get_or_null(p_shape); - ERR_FAIL_COND_V(!shape, false); - - btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin); - if (!btShape->isConvex()) { - bulletdelete(btShape); - ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type())); - return false; - } - btConvexShape *btConvex = static_cast<btConvexShape *>(btShape); - - btTransform bt_xform; - G_TO_B(p_shape_xform, bt_xform); - UNSCALE_BT_BASIS(bt_xform); - - btCollisionObject collision_object; - collision_object.setCollisionShape(btConvex); - collision_object.setWorldTransform(bt_xform); - - GodotContactPairContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas); - btQuery.m_collisionFilterGroup = 0; - btQuery.m_collisionFilterMask = p_collision_mask; - btQuery.m_closestDistanceThreshold = 0; - space->dynamicsWorld->contactTest(&collision_object, btQuery); - - r_result_count = btQuery.m_count; - bulletdelete(btConvex); - - return btQuery.m_count; -} - -bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { - ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get_or_null(p_shape); - ERR_FAIL_COND_V(!shape, false); - - btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin); - if (!btShape->isConvex()) { - bulletdelete(btShape); - ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type())); - return false; - } - btConvexShape *btConvex = static_cast<btConvexShape *>(btShape); - - btTransform bt_xform; - G_TO_B(p_shape_xform, bt_xform); - UNSCALE_BT_BASIS(bt_xform); - - btCollisionObject collision_object; - collision_object.setCollisionShape(btConvex); - collision_object.setWorldTransform(bt_xform); - - GodotRestInfoContactResultCallback btQuery(&collision_object, r_info, &p_exclude, p_collide_with_bodies, p_collide_with_areas); - btQuery.m_collisionFilterGroup = 0; - btQuery.m_collisionFilterMask = p_collision_mask; - btQuery.m_closestDistanceThreshold = 0; - space->dynamicsWorld->contactTest(&collision_object, btQuery); - - bulletdelete(btConvex); - - if (btQuery.m_collided) { - if (btCollisionObject::CO_RIGID_BODY == btQuery.m_rest_info_collision_object->getInternalType()) { - B_TO_G(static_cast<const btRigidBody *>(btQuery.m_rest_info_collision_object)->getVelocityInLocalPoint(btQuery.m_rest_info_bt_point), r_info->linear_velocity); - } - B_TO_G(btQuery.m_rest_info_bt_point, r_info->point); - } - - return btQuery.m_collided; -} - -Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const { - RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collision_object(p_object); - ERR_FAIL_COND_V(!rigid_object, Vector3()); - - btVector3 out_closest_point(0, 0, 0); - btScalar out_distance = 1e20; - - btVector3 bt_point; - G_TO_B(p_point, bt_point); - - btSphereShape point_shape(0.); - - btCollisionShape *shape; - btConvexShape *convex_shape; - btTransform child_transform; - btTransform body_transform(rigid_object->get_bt_collision_object()->getWorldTransform()); - - btGjkPairDetector::ClosestPointInput input; - input.m_transformA.getBasis().setIdentity(); - input.m_transformA.setOrigin(bt_point); - - bool shapes_found = false; - - for (int i = rigid_object->get_shape_count() - 1; 0 <= i; --i) { - shape = rigid_object->get_bt_shape(i); - if (shape->isConvex()) { - child_transform = rigid_object->get_bt_shape_transform(i); - convex_shape = static_cast<btConvexShape *>(shape); - - input.m_transformB = body_transform * child_transform; - - btPointCollector result; - btGjkPairDetector gjk_pair_detector(&point_shape, convex_shape, space->gjk_simplex_solver, space->gjk_epa_pen_solver); - gjk_pair_detector.getClosestPoints(input, result, nullptr); - - if (out_distance > result.m_distance) { - out_distance = result.m_distance; - out_closest_point = result.m_pointInWorld; - } - } - shapes_found = true; - } - - if (shapes_found) { - Vector3 out; - B_TO_G(out_closest_point, out); - return out; - } else { - // no shapes found, use distance to origin. - return rigid_object->get_transform().get_origin(); - } -} - -SpaceBullet::SpaceBullet() { - create_empty_world(GLOBAL_DEF("physics/3d/active_soft_world", true)); - direct_access = memnew(BulletPhysicsDirectSpaceState(this)); -} - -SpaceBullet::~SpaceBullet() { - memdelete(direct_access); - destroy_world(); -} - -void SpaceBullet::flush_queries() { - const btCollisionObjectArray &colObjArray = dynamicsWorld->getCollisionObjectArray(); - for (int i = colObjArray.size() - 1; 0 <= i; --i) { - static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->dispatch_callbacks(); - } -} - -void SpaceBullet::step(real_t p_delta_time) { - delta_time = p_delta_time; - dynamicsWorld->stepSimulation(p_delta_time, 0, 0); -} - -void SpaceBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) { - assert(dynamicsWorld); - - switch (p_param) { - case PhysicsServer3D::AREA_PARAM_GRAVITY: - gravityMagnitude = p_value; - update_gravity(); - break; - case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: - gravityDirection = p_value; - update_gravity(); - break; - case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: - linear_damp = p_value; - break; - case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: - angular_damp = p_value; - break; - case PhysicsServer3D::AREA_PARAM_PRIORITY: - // Priority is always 0, the lower - break; - case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: - case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: - case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: - break; - default: - WARN_PRINT("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it."); - break; - } -} - -Variant SpaceBullet::get_param(PhysicsServer3D::AreaParameter p_param) { - switch (p_param) { - case PhysicsServer3D::AREA_PARAM_GRAVITY: - return gravityMagnitude; - case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: - return gravityDirection; - case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: - return linear_damp; - case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: - return angular_damp; - case PhysicsServer3D::AREA_PARAM_PRIORITY: - return 0; // Priority is always 0, the lower - case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: - return false; - case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: - return 0; - case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: - return 0; - default: - WARN_PRINT("This get parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it."); - return Variant(); - } -} - -void SpaceBullet::set_param(PhysicsServer3D::SpaceParameter p_param, real_t p_value) { - switch (p_param) { - case PhysicsServer3D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: - case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_SEPARATION: - case PhysicsServer3D::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: - case PhysicsServer3D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: - case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: - case PhysicsServer3D::SPACE_PARAM_BODY_TIME_TO_SLEEP: - default: - WARN_PRINT("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it."); - break; - } -} - -real_t SpaceBullet::get_param(PhysicsServer3D::SpaceParameter p_param) { - switch (p_param) { - case PhysicsServer3D::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: - case PhysicsServer3D::SPACE_PARAM_CONTACT_MAX_SEPARATION: - case PhysicsServer3D::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: - case PhysicsServer3D::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: - case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: - case PhysicsServer3D::SPACE_PARAM_BODY_TIME_TO_SLEEP: - default: - WARN_PRINT("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned."); - return 0.f; - } -} - -void SpaceBullet::add_area(AreaBullet *p_area) { - areas.push_back(p_area); - dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask()); -} - -void SpaceBullet::remove_area(AreaBullet *p_area) { - areas.erase(p_area); - dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost()); -} - -void SpaceBullet::reload_collision_filters(AreaBullet *p_area) { - 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) { - if (p_body->is_static()) { - dynamicsWorld->addCollisionObject(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask()); - } else { - dynamicsWorld->addRigidBody(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask()); - p_body->scratch_space_override_modificator(); - } -} - -void SpaceBullet::remove_rigid_body_constraints(RigidBodyBullet *p_body) { - btRigidBody *btBody = p_body->get_bt_rigid_body(); - - int constraints = btBody->getNumConstraintRefs(); - if (constraints > 0) { - ERR_PRINT("A body connected to joints was removed."); - for (int i = 0; i < constraints; i++) { - dynamicsWorld->removeConstraint(btBody->getConstraintRef(i)); - } - } -} - -void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) { - btRigidBody *btBody = p_body->get_bt_rigid_body(); - - if (p_body->is_static()) { - dynamicsWorld->removeCollisionObject(btBody); - } else { - dynamicsWorld->removeRigidBody(btBody); - } -} - -void SpaceBullet::reload_collision_filters(RigidBodyBullet *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) { - if (is_using_soft_world()) { - if (p_body->get_bt_soft_body()) { - p_body->get_bt_soft_body()->m_worldInfo = get_soft_body_world_info(); - static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->addSoftBody(p_body->get_bt_soft_body(), p_body->get_collision_layer(), p_body->get_collision_mask()); - } - } else { - ERR_PRINT("This soft body can't be added to non soft world"); - } -} - -void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) { - if (is_using_soft_world()) { - if (p_body->get_bt_soft_body()) { - static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body()); - p_body->get_bt_soft_body()->m_worldInfo = nullptr; - } - } -} - -void SpaceBullet::reload_collision_filters(SoftBodyBullet *p_body) { - // This is necessary to change collision filter - remove_soft_body(p_body); - add_soft_body(p_body); -} - -void SpaceBullet::add_constraint(ConstraintBullet *p_constraint, bool disableCollisionsBetweenLinkedBodies) { - p_constraint->set_space(this); - dynamicsWorld->addConstraint(p_constraint->get_bt_constraint(), disableCollisionsBetweenLinkedBodies); -} - -void SpaceBullet::remove_constraint(ConstraintBullet *p_constraint) { - dynamicsWorld->removeConstraint(p_constraint->get_bt_constraint()); -} - -int SpaceBullet::get_num_collision_objects() const { - return dynamicsWorld->getNumCollisionObjects(); -} - -void SpaceBullet::remove_all_collision_objects() { - for (int i = dynamicsWorld->getNumCollisionObjects() - 1; 0 <= i; --i) { - btCollisionObject *btObj = dynamicsWorld->getCollisionObjectArray()[i]; - CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); - colObj->set_space(nullptr); - } -} - -void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) { - const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray(); - - // Notify all Collision objects the collision checker is started - for (int i = colObjArray.size() - 1; 0 <= i; --i) { - static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_start(); - } - - SpaceBullet *sb = static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo()); - sb->check_ghost_overlaps(); - sb->check_body_collision(); - - for (int i = colObjArray.size() - 1; 0 <= i; --i) { - static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_end(); - } -} - -BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() { - return direct_access; -} - -btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) { - return CLAMP(body0->getRestitution() + body1->getRestitution(), 0, 1); -} - -btScalar calculateGodotCombinedFriction(const btCollisionObject *body0, const btCollisionObject *body1) { - return ABS(MIN(body0->getFriction(), body1->getFriction())); -} - -void SpaceBullet::create_empty_world(bool p_create_soft_world) { - gjk_epa_pen_solver = bulletnew(btGjkEpaPenetrationDepthSolver); - gjk_simplex_solver = bulletnew(btVoronoiSimplexSolver); - - void *world_mem; - if (p_create_soft_world) { - world_mem = malloc(sizeof(btSoftRigidDynamicsWorld)); - } else { - 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 { - collisionConfiguration = bulletnew(GodotCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem))); - } - - dispatcher = bulletnew(GodotCollisionDispatcher(collisionConfiguration)); - broadphase = bulletnew(btDbvtBroadphase); - solver = bulletnew(btSequentialImpulseConstraintSolver); - - if (p_create_soft_world) { - dynamicsWorld = new (world_mem) btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); - soft_body_world_info = bulletnew(btSoftBodyWorldInfo); - } else { - dynamicsWorld = new (world_mem) btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); - } - - ghostPairCallback = bulletnew(btGhostPairCallback); - godotFilterCallback = bulletnew(GodotFilterCallback); - gCalculateCombinedRestitutionCallback = &calculateGodotCombinedRestitution; - gCalculateCombinedFrictionCallback = &calculateGodotCombinedFriction; - gContactAddedCallback = &godotContactAddedCallback; - - dynamicsWorld->setWorldUserInfo(this); - - dynamicsWorld->setInternalTickCallback(onBulletTickCallback, this, false); - dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback); // Setup ghost check - dynamicsWorld->getPairCache()->setOverlapFilterCallback(godotFilterCallback); - - if (soft_body_world_info) { - soft_body_world_info->m_broadphase = broadphase; - soft_body_world_info->m_dispatcher = dispatcher; - soft_body_world_info->m_sparsesdf.Initialize(); - } - - update_gravity(); -} - -void SpaceBullet::destroy_world() { - /// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot - - dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(nullptr); - dynamicsWorld->getPairCache()->setOverlapFilterCallback(nullptr); - - bulletdelete(ghostPairCallback); - bulletdelete(godotFilterCallback); - - // Deallocate world - dynamicsWorld->~btDiscreteDynamicsWorld(); - free(dynamicsWorld); - dynamicsWorld = nullptr; - - bulletdelete(solver); - bulletdelete(broadphase); - bulletdelete(dispatcher); - bulletdelete(collisionConfiguration); - bulletdelete(soft_body_world_info); - bulletdelete(gjk_simplex_solver); - bulletdelete(gjk_epa_pen_solver); -} - -void SpaceBullet::check_ghost_overlaps() { - // For each area - for (int area_idx = 0; area_idx < areas.size(); area_idx++) { - AreaBullet *area = areas[area_idx]; - if (!area->is_monitoring()) { - continue; - } - - btGhostObject *bt_ghost = area->get_bt_ghost(); - const btTransform &area_transform = area->get_transform__bullet(); - const btVector3 &area_scale(area->get_bt_body_scale()); - - // Mark all current overlapping shapes dirty. - area->mark_all_overlaps_dirty(); - - // Broadphase - const btAlignedObjectArray<btCollisionObject *> overlapping_pairs = bt_ghost->getOverlappingPairs(); - // Narrowphase - for (int pair_idx = 0; pair_idx < overlapping_pairs.size(); pair_idx++) { - btCollisionObject *other_bt_collision_object = overlapping_pairs[pair_idx]; - RigidCollisionObjectBullet *other_object = static_cast<RigidCollisionObjectBullet *>(other_bt_collision_object->getUserPointer()); - const btTransform &other_transform = other_object->get_transform__bullet(); - const btVector3 &other_scale(other_object->get_bt_body_scale()); - - if (!area->is_updated() && !other_object->is_updated()) { - area->mark_object_overlaps_inside(other_object); - continue; - } - - if (other_bt_collision_object->getUserIndex() == CollisionObjectBullet::TYPE_AREA) { - if (!static_cast<AreaBullet *>(other_bt_collision_object->getUserPointer())->is_monitorable()) { - continue; - } - } else if (other_bt_collision_object->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY) { - continue; - } - - // For each area shape - for (int our_shape_id = 0; our_shape_id < area->get_shape_count(); our_shape_id++) { - btCollisionShape *area_shape = area->get_bt_shape(our_shape_id); - if (!area_shape->isConvex()) { - continue; - } - btConvexShape *area_convex_shape = static_cast<btConvexShape *>(area_shape); - - btTransform area_shape_transform(area->get_bt_shape_transform(our_shape_id)); - area_shape_transform.getOrigin() *= area_scale; - btGjkPairDetector::ClosestPointInput gjk_input; - gjk_input.m_transformA = area_transform * area_shape_transform; - - // For each other object shape - for (int other_shape_id = 0; other_shape_id < other_object->get_shape_count(); other_shape_id++) { - btCollisionShape *other_shape = other_object->get_bt_shape(other_shape_id); - btTransform other_shape_transform(other_object->get_bt_shape_transform(other_shape_id)); - other_shape_transform.getOrigin() *= other_scale; - gjk_input.m_transformB = other_transform * other_shape_transform; - - if (other_shape->isConvex()) { - btPointCollector result; - btGjkPairDetector gjk_pair_detector( - area_convex_shape, - static_cast<btConvexShape *>(other_shape), - gjk_simplex_solver, - gjk_epa_pen_solver); - - gjk_pair_detector.getClosestPoints(gjk_input, result, nullptr); - if (result.m_distance <= 0) { - area->set_overlap(other_object, other_shape_id, our_shape_id); - } - } else { // Other shape is not convex. - btCollisionObjectWrapper obA(nullptr, area_convex_shape, bt_ghost, gjk_input.m_transformA, -1, our_shape_id); - btCollisionObjectWrapper obB(nullptr, other_shape, other_bt_collision_object, gjk_input.m_transformB, -1, other_shape_id); - btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS); - - if (!algorithm) { - continue; - } - - GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB); - algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult); - algorithm->~btCollisionAlgorithm(); - dispatcher->freeCollisionAlgorithm(algorithm); - - if (contactPointResult.hasHit()) { - area->set_overlap(other_object, our_shape_id, other_shape_id); - } - } - } // End for each other object shape - } // End for each area shape - } // End for each overlapping pair - - // All overlapping shapes still marked dirty must have exited. - area->mark_all_dirty_overlaps_as_exit(); - } // End for each area -} - -void SpaceBullet::check_body_collision() { -#ifdef DEBUG_ENABLED - reset_debug_contact_count(); -#endif - - const int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds(); - for (int i = 0; i < numManifolds; ++i) { - btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); - - // I know this static cast is a bit risky. But I'm checking its type just after it. - // This allow me to avoid a lot of other cast and checks - RigidBodyBullet *bodyA = static_cast<RigidBodyBullet *>(contactManifold->getBody0()->getUserPointer()); - RigidBodyBullet *bodyB = static_cast<RigidBodyBullet *>(contactManifold->getBody1()->getUserPointer()); - - if (CollisionObjectBullet::TYPE_RIGID_BODY == bodyA->getType() && CollisionObjectBullet::TYPE_RIGID_BODY == bodyB->getType()) { - if (!bodyA->can_add_collision() && !bodyB->can_add_collision()) { - continue; - } - - const int numContacts = contactManifold->getNumContacts(); - - /// Since I don't need report all contacts for these objects, - /// So report only the first -#define REPORT_ALL_CONTACTS 0 -#if REPORT_ALL_CONTACTS - for (int j = 0; j < numContacts; j++) { - btManifoldPoint &pt = contactManifold->getContactPoint(j); -#else - if (numContacts) { - btManifoldPoint &pt = contactManifold->getContactPoint(0); -#endif - if ( - pt.getDistance() < 0.0 || - bodyA->was_colliding(bodyB) || - bodyB->was_colliding(bodyA)) { - Vector3 collisionWorldPosition; - Vector3 collisionLocalPosition; - Vector3 normalOnB; - real_t appliedImpulse = pt.m_appliedImpulse; - B_TO_G(pt.m_normalWorldOnB, normalOnB); - - // The pt.m_index only contains the shape index when more than one collision shape is used - // and only if the collision shape is not a concave collision shape. - // A value of -1 in pt.m_partId indicates the pt.m_index is a shape index. - int shape_index_a = 0; - if (bodyA->get_shape_count() > 1 && pt.m_partId0 == -1) { - shape_index_a = pt.m_index0; - } - int shape_index_b = 0; - if (bodyB->get_shape_count() > 1 && pt.m_partId1 == -1) { - shape_index_b = pt.m_index1; - } - - if (bodyA->can_add_collision()) { - B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition); - /// pt.m_localPointB Doesn't report the exact point in local space - B_TO_G(pt.getPositionWorldOnB() - contactManifold->getBody1()->getWorldTransform().getOrigin(), collisionLocalPosition); - bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, appliedImpulse, shape_index_b, shape_index_a); - } - if (bodyB->can_add_collision()) { - B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition); - /// pt.m_localPointA Doesn't report the exact point in local space - B_TO_G(pt.getPositionWorldOnA() - contactManifold->getBody0()->getWorldTransform().getOrigin(), collisionLocalPosition); - bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, appliedImpulse * -1, shape_index_a, shape_index_b); - } - -#ifdef DEBUG_ENABLED - if (is_debugging_contacts()) { - add_debug_contact(collisionWorldPosition); - } -#endif - } - } - } - } -} - -void SpaceBullet::update_gravity() { - btVector3 btGravity; - G_TO_B(gravityDirection * gravityMagnitude, btGravity); - //dynamicsWorld->setGravity(btGravity); - dynamicsWorld->setGravity(btVector3(0, 0, 0)); - if (soft_body_world_info) { - soft_body_world_info->m_gravity = btGravity; - } -} - -/// IMPORTANT: Please don't turn it ON this is not managed correctly!! -/// I'm leaving this here just for future tests. -/// Debug motion and normal vector drawing -#define debug_test_motion 0 - -#define RECOVERING_MOVEMENT_SCALE 0.4 -#define RECOVERING_MOVEMENT_CYCLES 4 - -#if debug_test_motion - -#include "scene/3d/immediate_geometry.h" - -static ImmediateGeometry3D *motionVec(nullptr); -static ImmediateGeometry3D *normalLine(nullptr); -static Ref<StandardMaterial3D> red_mat; -static Ref<StandardMaterial3D> blue_mat; -#endif - -bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes, const Set<RID> &p_exclude) { -#if debug_test_motion - /// Yes I know this is not good, but I've used it as fast debugging hack. - /// I'm leaving it here just for speedup the other eventual debugs - if (!normalLine) { - motionVec = memnew(ImmediateGeometry3D); - normalLine = memnew(ImmediateGeometry3D); - SceneTree::get_singleton()->get_current_scene()->add_child(motionVec); - SceneTree::get_singleton()->get_current_scene()->add_child(normalLine); - - motionVec->set_as_top_level(true); - normalLine->set_as_top_level(true); - - red_mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D)); - red_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); - red_mat->set_line_width(20.0); - red_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); - red_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); - red_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); - red_mat->set_albedo(Color(1, 0, 0, 1)); - motionVec->set_material_override(red_mat); - - blue_mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D)); - blue_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); - blue_mat->set_line_width(20.0); - blue_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); - blue_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); - blue_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); - blue_mat->set_albedo(Color(0, 0, 1, 1)); - normalLine->set_material_override(blue_mat); - } -#endif - - btTransform body_transform; - G_TO_B(p_from, body_transform); - UNSCALE_BT_BASIS(body_transform); - - if (!p_body->get_kinematic_utilities()) { - p_body->init_kinematic_utilities(); - } - - btVector3 initial_recover_motion(0, 0, 0); - { /// Phase one - multi shapes depenetration using margin - for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) { - if (!recover_from_penetration(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, initial_recover_motion, nullptr, p_exclude)) { - break; - } - } - // Add recover movement in order to make it safe - body_transform.getOrigin() += initial_recover_motion; - } - - btVector3 motion; - G_TO_B(p_motion, motion); - real_t total_length = motion.length(); - real_t unsafe_fraction = 1.0; - real_t safe_fraction = 1.0; - { - // Phase two - sweep test, from a secure position without margin - - const int shape_count(p_body->get_shape_count()); - -#if debug_test_motion - Vector3 sup_line; - B_TO_G(body_safe_position.getOrigin(), sup_line); - motionVec->clear(); - motionVec->begin(Mesh::PRIMITIVE_LINES, nullptr); - motionVec->add_vertex(sup_line); - motionVec->add_vertex(sup_line + p_motion * 10); - motionVec->end(); -#endif - - for (int shIndex = 0; shIndex < shape_count; ++shIndex) { - if (p_body->is_shape_disabled(shIndex)) { - continue; - } - - if (!p_body->get_bt_shape(shIndex)->isConvex()) { - // Skip no convex shape - continue; - } - - if (p_exclude_raycast_shapes && p_body->get_bt_shape(shIndex)->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) { - // Skip rayshape in order to implement custom separation process - continue; - } - - btConvexShape *convex_shape_test(static_cast<btConvexShape *>(p_body->get_bt_shape(shIndex))); - - btTransform shape_world_from = body_transform * p_body->get_kinematic_utilities()->shapes[shIndex].transform; - - btTransform shape_world_to(shape_world_from); - shape_world_to.getOrigin() += motion; - - if ((shape_world_to.getOrigin() - shape_world_from.getOrigin()).fuzzyZero()) { - motion = btVector3(0, 0, 0); - break; - } - - GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia, &p_exclude); - btResult.m_collisionFilterGroup = p_body->get_collision_layer(); - btResult.m_collisionFilterMask = p_body->get_collision_mask(); - - dynamicsWorld->convexSweepTest(convex_shape_test, shape_world_from, shape_world_to, btResult, dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration); - - if (btResult.hasHit()) { - if (total_length > CMP_EPSILON) { - real_t hit_fraction = btResult.m_closestHitFraction * motion.length() / total_length; - if (hit_fraction < unsafe_fraction) { - unsafe_fraction = hit_fraction; - real_t margin = p_body->get_kinematic_utilities()->safe_margin; - safe_fraction = MAX(hit_fraction - (1 - ((total_length - margin) / total_length)), 0); - } - } - - /// Since for each sweep test I fix the motion of new shapes in base the recover result, - /// if another shape will hit something it means that has a deepest penetration respect the previous shape - motion *= btResult.m_closestHitFraction; - } - } - - body_transform.getOrigin() += motion; - } - - bool has_penetration = false; - - { /// Phase three - contact test with margin - - btVector3 __rec(0, 0, 0); - RecoverResult r_recover_result; - - has_penetration = recover_from_penetration(p_body, body_transform, 1, p_infinite_inertia, __rec, &r_recover_result, p_exclude); - - // Parse results - if (r_result) { - B_TO_G(motion + initial_recover_motion + __rec, r_result->motion); - - if (has_penetration) { - const btRigidBody *btRigid = static_cast<const btRigidBody *>(r_recover_result.other_collision_object); - CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer()); - - B_TO_G(motion, r_result->remainder); // is the remaining movements - r_result->remainder = p_motion - r_result->remainder; - - B_TO_G(r_recover_result.pointWorld, r_result->collision_point); - B_TO_G(r_recover_result.normal, r_result->collision_normal); - B_TO_G(btRigid->getVelocityInLocalPoint(r_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity); // It calculates velocity at point and assign it using special function Bullet_to_Godot - r_result->collider = collisionObject->get_self(); - r_result->collider_id = collisionObject->get_instance_id(); - r_result->collider_shape = r_recover_result.other_compound_shape_index; - r_result->collision_local_shape = r_recover_result.local_shape_most_recovered; - r_result->collision_depth = Math::abs(r_recover_result.penetration_distance); - r_result->collision_safe_fraction = safe_fraction; - r_result->collision_unsafe_fraction = unsafe_fraction; - -#if debug_test_motion - Vector3 sup_line2; - B_TO_G(motion, sup_line2); - normalLine->clear(); - normalLine->begin(Mesh::PRIMITIVE_LINES, nullptr); - normalLine->add_vertex(r_result->collision_point); - normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10); - normalLine->end(); -#endif - } else { - r_result->remainder = Vector3(); - } - } - } - - return has_penetration; -} - -int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, real_t p_margin) { - btTransform body_transform; - G_TO_B(p_transform, body_transform); - UNSCALE_BT_BASIS(body_transform); - - if (!p_body->get_kinematic_utilities()) { - p_body->init_kinematic_utilities(); - } - - 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) { - PhysicsServer3D::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 += rays_found_this_round; - if (rays_found_this_round == 0) { - body_transform.getOrigin() += recover_motion; - break; - } - } - - B_TO_G(recover_motion, r_recover_motion); - return rays_found; -} - -struct RecoverPenetrationBroadPhaseCallback : public btBroadphaseAabbCallback { -private: - btDbvtVolume bounds; - - const btCollisionObject *self_collision_object; - uint32_t collision_layer = 0; - - struct CompoundLeafCallback : btDbvt::ICollide { - private: - RecoverPenetrationBroadPhaseCallback *parent_callback = nullptr; - btCollisionObject *collision_object = nullptr; - - 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: - struct BroadphaseResult { - btCollisionObject *collision_object = nullptr; - int compound_child_index = 0; - }; - - Vector<BroadphaseResult> results; - -public: - RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, btVector3 p_aabb_min, btVector3 p_aabb_max) : - self_collision_object(p_self_collision_object), - collision_layer(p_collision_layer) { - bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max); - } - - virtual ~RecoverPenetrationBroadPhaseCallback() {} - - virtual bool process(const btBroadphaseProxy *proxy) { - btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject); - if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) { - if (self_collision_object != proxy->m_clientObject && (proxy->collision_layer & m_collisionFilterMask)) { - 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 == nullptr, 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; - } -}; - -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, const Set<RID> &p_exclude) { - // 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); - - 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; - } - - // Perform broadphase test - RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), aabb_min, aabb_max); - dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result); - - bool penetration = false; - - // Perform narrowphase per shape - 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; - } - - if (kin_shape.shape->getShapeType() == EMPTY_SHAPE_PROXYTYPE) { - continue; - } - - btTransform shape_transform = p_body_position * kin_shape.transform; - shape_transform.getOrigin() += r_delta_recover_movement; - - for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) { - btCollisionObject *otherObject = recover_broad_result.results[i].collision_object; - - CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(otherObject->getUserPointer()); - if (p_exclude.has(gObj->get_self())) { - continue; - } - - if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) { - otherObject->activate(); // Force activation of hitten rigid, soft body - continue; - } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) { - 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); - - 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)) { - 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; - } - } - } 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, 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, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - penetration = true; - } - } - } - } - - return penetration; -} - -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_transformB = p_transformB; - - // Perform GJK test - btPointCollector result; - btGjkPairDetector gjk_pair_detector(p_shapeA, p_shapeB, gjk_simplex_solver, gjk_epa_pen_solver); - gjk_pair_detector.getClosestPoints(gjk_input, result, nullptr); - if (0 > result.m_distance) { - // Has penetration - r_delta_recover_movement += result.m_normalOnBInWorld * (result.m_distance * -1 * p_recover_movement_scale); - - 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; - r_recover_result->pointWorld = result.m_pointInWorld; - r_recover_result->normal = result.m_normalOnBInWorld; - } - } - return true; - } - return false; -} - -bool SpaceBullet::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) { - /// Contact test - - btTransform tA(p_transformA); - - btCollisionObjectWrapper obA(nullptr, p_shapeA, p_objectA, tA, -1, p_shapeId_A); - btCollisionObjectWrapper obB(nullptr, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B); - - btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS); - if (algorithm) { - GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB); - //discrete collision detection query - algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult); - - algorithm->~btCollisionAlgorithm(); - dispatcher->freeCollisionAlgorithm(algorithm); - - if (contactPointResult.hasHit()) { - r_delta_recover_movement += contactPointResult.m_pointNormalWorld * (contactPointResult.m_penetration_distance * -1 * p_recover_movement_scale); - 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; - r_recover_result->pointWorld = contactPointResult.m_pointWorld; - r_recover_result->normal = contactPointResult.m_pointNormalWorld; - } - } - return true; - } - } - return false; -} - -int SpaceBullet::add_separation_result(PhysicsServer3D::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()); - - 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, PhysicsServer3D::SeparationResult *r_results) { - // 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) { - 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); - - 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 0; - } - - // Perform broadphase test - RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), 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_count >= p_result_max) { - break; - } - - 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; - } - - btTransform shape_transform = p_body_position * kin_shape.transform; - shape_transform.getOrigin() += r_delta_recover_movement; - - 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; - } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) { - 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); - - 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)) { - 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, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) { - ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject); - } - } - } - } - - return ray_count; -} diff --git a/modules/bullet/space_bullet.h b/modules/bullet/space_bullet.h deleted file mode 100644 index f858c5fcb5..0000000000 --- a/modules/bullet/space_bullet.h +++ /dev/null @@ -1,220 +0,0 @@ -/*************************************************************************/ -/* space_bullet.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 SPACE_BULLET_H -#define SPACE_BULLET_H - -#include "core/templates/vector.h" -#include "core/variant/variant.h" -#include "godot_result_callbacks.h" -#include "rid_bullet.h" -#include "servers/physics_server_3d.h" - -#include <BulletCollision/BroadphaseCollision/btBroadphaseProxy.h> -#include <BulletCollision/BroadphaseCollision/btOverlappingPairCache.h> -#include <LinearMath/btScalar.h> -#include <LinearMath/btTransform.h> -#include <LinearMath/btVector3.h> - -class AreaBullet; -class btBroadphaseInterface; -class btCollisionDispatcher; -class btConstraintSolver; -class btDefaultCollisionConfiguration; -class btDynamicsWorld; -class btDiscreteDynamicsWorld; -class btEmptyShape; -class btGhostPairCallback; -class btSoftRigidDynamicsWorld; -struct btSoftBodyWorldInfo; -class ConstraintBullet; -class CollisionObjectBullet; -class RigidBodyBullet; -class SpaceBullet; -class SoftBodyBullet; -class btGjkEpaPenetrationDepthSolver; - -extern ContactAddedCallback gContactAddedCallback; - -class BulletPhysicsDirectSpaceState : public PhysicsDirectSpaceState3D { - GDCLASS(BulletPhysicsDirectSpaceState, PhysicsDirectSpaceState3D); - -private: - SpaceBullet *space; - -public: - BulletPhysicsDirectSpaceState(SpaceBullet *p_space); - - virtual int intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = UINT32_MAX, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; - virtual bool intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = UINT32_MAX, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, bool p_pick_ray = false) override; - virtual int intersect_shape(const RID &p_shape, const Transform3D &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = UINT32_MAX, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; - virtual bool cast_motion(const RID &p_shape, const Transform3D &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &r_closest_safe, real_t &r_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = UINT32_MAX, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, ShapeRestInfo *r_info = nullptr) override; - /// Returns the list of contacts pairs in this order: Local contact, other body contact - virtual bool collide_shape(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = UINT32_MAX, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; - virtual bool rest_info(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = UINT32_MAX, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; - virtual Vector3 get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const override; -}; - -class SpaceBullet : public RIDBullet { - friend class AreaBullet; - friend void onBulletTickCallback(btDynamicsWorld *world, btScalar timeStep); - friend class BulletPhysicsDirectSpaceState; - - btBroadphaseInterface *broadphase = nullptr; - btDefaultCollisionConfiguration *collisionConfiguration = nullptr; - btCollisionDispatcher *dispatcher = nullptr; - btConstraintSolver *solver = nullptr; - btDiscreteDynamicsWorld *dynamicsWorld = nullptr; - btSoftBodyWorldInfo *soft_body_world_info = nullptr; - btGhostPairCallback *ghostPairCallback = nullptr; - GodotFilterCallback *godotFilterCallback = nullptr; - - btGjkEpaPenetrationDepthSolver *gjk_epa_pen_solver = nullptr; - btVoronoiSimplexSolver *gjk_simplex_solver = nullptr; - - BulletPhysicsDirectSpaceState *direct_access; - Vector3 gravityDirection = Vector3(0, -1, 0); - real_t gravityMagnitude = 10.0; - - real_t linear_damp = 0.0; - real_t angular_damp = 0.0; - - Vector<AreaBullet *> areas; - - Vector<Vector3> contactDebug; - int contactDebugCount = 0; - real_t delta_time = 0.; - -public: - SpaceBullet(); - virtual ~SpaceBullet(); - - void flush_queries(); - real_t get_delta_time() { return delta_time; } - void step(real_t p_delta_time); - - _FORCE_INLINE_ btBroadphaseInterface *get_broadphase() const { return broadphase; } - _FORCE_INLINE_ btDefaultCollisionConfiguration *get_collision_configuration() const { return collisionConfiguration; } - _FORCE_INLINE_ btCollisionDispatcher *get_dispatcher() const { return dispatcher; } - _FORCE_INLINE_ btConstraintSolver *get_solver() const { return solver; } - _FORCE_INLINE_ btDiscreteDynamicsWorld *get_dynamic_world() const { return dynamicsWorld; } - _FORCE_INLINE_ btSoftBodyWorldInfo *get_soft_body_world_info() const { return soft_body_world_info; } - _FORCE_INLINE_ bool is_using_soft_world() { return soft_body_world_info; } - - /// Used to set some parameters to Bullet world - /// @param p_param: - /// AREA_PARAM_GRAVITY to set the gravity magnitude of entire world - /// AREA_PARAM_GRAVITY_VECTOR to set the gravity direction of entire world - void set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value); - /// Used to get some parameters to Bullet world - /// @param p_param: - /// AREA_PARAM_GRAVITY to get the gravity magnitude of entire world - /// AREA_PARAM_GRAVITY_VECTOR to get the gravity direction of entire world - Variant get_param(PhysicsServer3D::AreaParameter p_param); - - void set_param(PhysicsServer3D::SpaceParameter p_param, real_t p_value); - real_t get_param(PhysicsServer3D::SpaceParameter p_param); - - void add_area(AreaBullet *p_area); - void remove_area(AreaBullet *p_area); - void reload_collision_filters(AreaBullet *p_area); - - void add_rigid_body(RigidBodyBullet *p_body); - void remove_rigid_body_constraints(RigidBodyBullet *p_body); - void remove_rigid_body(RigidBodyBullet *p_body); - void reload_collision_filters(RigidBodyBullet *p_body); - - void add_soft_body(SoftBodyBullet *p_body); - void remove_soft_body(SoftBodyBullet *p_body); - void reload_collision_filters(SoftBodyBullet *p_body); - - void add_constraint(ConstraintBullet *p_constraint, bool disableCollisionsBetweenLinkedBodies = false); - void remove_constraint(ConstraintBullet *p_constraint); - - int get_num_collision_objects() const; - void remove_all_collision_objects(); - - BulletPhysicsDirectSpaceState *get_direct_state(); - - void set_debug_contacts(int p_amount) { contactDebug.resize(p_amount); } - _FORCE_INLINE_ bool is_debugging_contacts() const { return !contactDebug.is_empty(); } - _FORCE_INLINE_ void reset_debug_contact_count() { - contactDebugCount = 0; - } - _FORCE_INLINE_ void add_debug_contact(const Vector3 &p_contact) { - if (contactDebugCount < contactDebug.size()) { - contactDebug.write[contactDebugCount++] = p_contact; - } - } - _FORCE_INLINE_ Vector<Vector3> get_debug_contacts() { return contactDebug; } - _FORCE_INLINE_ int get_debug_contact_count() { return contactDebugCount; } - - const Vector3 &get_gravity_direction() const { return gravityDirection; } - real_t get_gravity_magnitude() const { return gravityMagnitude; } - - void update_gravity(); - - real_t get_linear_damp() const { return linear_damp; } - real_t get_angular_damp() const { return angular_damp; } - - bool test_body_motion(RigidBodyBullet *p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes, const Set<RID> &p_exclude = Set<RID>()); - int test_ray_separation(RigidBodyBullet *p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, real_t p_margin); - -private: - void create_empty_world(bool p_create_soft_world); - void destroy_world(); - void check_ghost_overlaps(); - void check_body_collision(); - - struct RecoverResult { - bool hasPenetration = false; - btVector3 normal = btVector3(0, 0, 0); - btVector3 pointWorld = btVector3(0, 0, 0); - btScalar penetration_distance = 1e20; // Negative mean penetration - int other_compound_shape_index = 0; - const btCollisionObject *other_collision_object = nullptr; - int local_shape_most_recovered = 0; - - RecoverResult() {} - }; - - 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 = nullptr, const Set<RID> &p_exclude = Set<RID>()); - /// 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_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 = nullptr); - /// 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 = nullptr); - - int add_separation_result(PhysicsServer3D::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, PhysicsServer3D::SeparationResult *r_results); -}; - -#endif // SPACE_BULLET_H diff --git a/modules/csg/csg_gizmos.cpp b/modules/csg/csg_gizmos.cpp index 9a6a33fad3..95a0fc7ada 100644 --- a/modules/csg/csg_gizmos.cpp +++ b/modules/csg/csg_gizmos.cpp @@ -29,6 +29,8 @@ /*************************************************************************/ #include "csg_gizmos.h" + +#include "editor/editor_settings.h" #include "editor/plugins/node_3d_editor_plugin.h" #include "scene/3d/camera_3d.h" @@ -419,7 +421,7 @@ void CSGShape3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) { } } -EditorPluginCSG::EditorPluginCSG(EditorNode *p_editor) { +EditorPluginCSG::EditorPluginCSG() { Ref<CSGShape3DGizmoPlugin> gizmo_plugin = Ref<CSGShape3DGizmoPlugin>(memnew(CSGShape3DGizmoPlugin)); Node3DEditor::get_singleton()->add_gizmo_plugin(gizmo_plugin); } diff --git a/modules/csg/csg_gizmos.h b/modules/csg/csg_gizmos.h index 46761370dd..43efe57e64 100644 --- a/modules/csg/csg_gizmos.h +++ b/modules/csg/csg_gizmos.h @@ -57,7 +57,7 @@ class EditorPluginCSG : public EditorPlugin { GDCLASS(EditorPluginCSG, EditorPlugin); public: - EditorPluginCSG(EditorNode *p_editor); + EditorPluginCSG(); }; #endif // CSG_GIZMOS_H diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp index fbddedbe55..be9bf9538f 100644 --- a/modules/csg/csg_shape.cpp +++ b/modules/csg/csg_shape.cpp @@ -125,7 +125,7 @@ bool CSGShape3D::get_collision_mask_value(int p_layer_number) const { } bool CSGShape3D::is_root_shape() const { - return !parent; + return !parent_shape; } void CSGShape3D::set_snap(float p_snap) { @@ -136,13 +136,13 @@ float CSGShape3D::get_snap() const { return snap; } -void CSGShape3D::_make_dirty() { - if (!is_inside_tree()) { - return; +void CSGShape3D::_make_dirty(bool p_parent_removing) { + if ((p_parent_removing || is_root_shape()) && !dirty) { + call_deferred(SNAME("_update_shape")); // Must be deferred; otherwise, is_root_shape() will use the previous parent } - if (parent) { - parent->_make_dirty(); + if (!is_root_shape()) { + parent_shape->_make_dirty(); } else if (!dirty) { call_deferred(SNAME("_update_shape")); } @@ -164,7 +164,7 @@ CSGBrush *CSGShape3D::_get_brush() { if (!child) { continue; } - if (!child->is_visible_in_tree()) { + if (!child->is_visible()) { continue; } @@ -280,7 +280,7 @@ void CSGShape3D::mikktSetTSpaceDefault(const SMikkTSpaceContext *pContext, const } void CSGShape3D::_update_shape() { - if (parent || !is_inside_tree()) { + if (!is_root_shape()) { return; } @@ -303,17 +303,19 @@ void CSGShape3D::_update_shape() { ERR_CONTINUE(mat < -1 || mat >= face_count.size()); int idx = mat == -1 ? face_count.size() - 1 : mat; - Plane p(n->faces[i].vertices[0], n->faces[i].vertices[1], n->faces[i].vertices[2]); + if (n->faces[i].smooth) { + Plane p(n->faces[i].vertices[0], n->faces[i].vertices[1], n->faces[i].vertices[2]); - for (int j = 0; j < 3; j++) { - Vector3 v = n->faces[i].vertices[j]; - Vector3 add; - if (vec_map.lookup(v, add)) { - add += p.normal; - } else { - add = p.normal; + for (int j = 0; j < 3; j++) { + Vector3 v = n->faces[i].vertices[j]; + Vector3 add; + if (vec_map.lookup(v, add)) { + add += p.normal; + } else { + add = p.normal; + } + vec_map.set(v, add); } - vec_map.set(v, add); } face_count.write[idx]++; @@ -345,27 +347,6 @@ void CSGShape3D::_update_shape() { } } - // Update collision faces. - if (root_collision_shape.is_valid()) { - Vector<Vector3> physics_faces; - physics_faces.resize(n->faces.size() * 3); - Vector3 *physicsw = physics_faces.ptrw(); - - for (int i = 0; i < n->faces.size(); i++) { - int order[3] = { 0, 1, 2 }; - - if (n->faces[i].invert) { - SWAP(order[1], order[2]); - } - - physicsw[i * 3 + 0] = n->faces[i].vertices[order[0]]; - physicsw[i * 3 + 1] = n->faces[i].vertices[order[1]]; - physicsw[i * 3 + 2] = n->faces[i].vertices[order[2]]; - } - - root_collision_shape->set_faces(physics_faces); - } - //fill arrays { for (int i = 0; i < n->faces.size(); i++) { @@ -458,6 +439,32 @@ void CSGShape3D::_update_shape() { } set_base(root_mesh->get_rid()); + + _update_collision_faces(); +} + +void CSGShape3D::_update_collision_faces() { + if (use_collision && is_root_shape() && root_collision_shape.is_valid()) { + CSGBrush *n = _get_brush(); + ERR_FAIL_COND_MSG(!n, "Cannot get CSGBrush."); + Vector<Vector3> physics_faces; + physics_faces.resize(n->faces.size() * 3); + Vector3 *physicsw = physics_faces.ptrw(); + + for (int i = 0; i < n->faces.size(); i++) { + int order[3] = { 0, 1, 2 }; + + if (n->faces[i].invert) { + SWAP(order[1], order[2]); + } + + physicsw[i * 3 + 0] = n->faces[i].vertices[order[0]]; + physicsw[i * 3 + 1] = n->faces[i].vertices[order[1]]; + physicsw[i * 3 + 2] = n->faces[i].vertices[order[2]]; + } + + root_collision_shape->set_faces(physics_faces); + } } AABB CSGShape3D::get_aabb() const { @@ -486,66 +493,75 @@ Vector<Vector3> CSGShape3D::get_brush_faces() { return faces; } -Vector<Face3> CSGShape3D::get_faces(uint32_t p_usage_flags) const { - return Vector<Face3>(); -} - void CSGShape3D::_notification(int p_what) { - if (p_what == NOTIFICATION_ENTER_TREE) { - Node *parentn = get_parent(); - if (parentn) { - parent = Object::cast_to<CSGShape3D>(parentn); - if (parent) { - set_base(RID()); - root_mesh.unref(); + switch (p_what) { + case NOTIFICATION_PARENTED: { + Node *parentn = get_parent(); + if (parentn) { + parent_shape = Object::cast_to<CSGShape3D>(parentn); + if (parent_shape) { + set_base(RID()); + root_mesh.unref(); + } } - } - - if (use_collision && is_root_shape()) { - root_collision_shape.instantiate(); - root_collision_instance = PhysicsServer3D::get_singleton()->body_create(); - PhysicsServer3D::get_singleton()->body_set_mode(root_collision_instance, PhysicsServer3D::BODY_MODE_STATIC); - PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform()); - PhysicsServer3D::get_singleton()->body_add_shape(root_collision_instance, root_collision_shape->get_rid()); - PhysicsServer3D::get_singleton()->body_set_space(root_collision_instance, get_world_3d()->get_space()); - PhysicsServer3D::get_singleton()->body_attach_object_instance_id(root_collision_instance, get_instance_id()); - set_collision_layer(collision_layer); - set_collision_mask(collision_mask); - } + if (!brush || parent_shape) { + // Update this node if uninitialized, or both this node and its new parent if it gets added to another CSG shape + _make_dirty(); + } + last_visible = is_visible(); + } break; - _make_dirty(); - } + case NOTIFICATION_UNPARENTED: { + if (!is_root_shape()) { + // Update this node and its previous parent only if it's currently being removed from another CSG shape + _make_dirty(true); // Must be forced since is_root_shape() uses the previous parent + } + parent_shape = nullptr; + } break; - if (p_what == NOTIFICATION_TRANSFORM_CHANGED) { - if (use_collision && is_root_shape() && root_collision_instance.is_valid()) { - PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform()); - } - } + case NOTIFICATION_VISIBILITY_CHANGED: { + if (!is_root_shape() && last_visible != is_visible()) { + // Update this node's parent only if its own visibility has changed, not the visibility of parent nodes + parent_shape->_make_dirty(); + } + last_visible = is_visible(); + } break; - if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) { - if (parent) { - parent->_make_dirty(); - } - } + case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { + if (!is_root_shape()) { + // Update this node's parent only if its own transformation has changed, not the transformation of parent nodes + parent_shape->_make_dirty(); + } + } break; - if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { - if (parent) { - parent->_make_dirty(); - } - } + case NOTIFICATION_ENTER_TREE: { + if (use_collision && is_root_shape()) { + root_collision_shape.instantiate(); + root_collision_instance = PhysicsServer3D::get_singleton()->body_create(); + PhysicsServer3D::get_singleton()->body_set_mode(root_collision_instance, PhysicsServer3D::BODY_MODE_STATIC); + PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform()); + PhysicsServer3D::get_singleton()->body_add_shape(root_collision_instance, root_collision_shape->get_rid()); + PhysicsServer3D::get_singleton()->body_set_space(root_collision_instance, get_world_3d()->get_space()); + PhysicsServer3D::get_singleton()->body_attach_object_instance_id(root_collision_instance, get_instance_id()); + set_collision_layer(collision_layer); + set_collision_mask(collision_mask); + _update_collision_faces(); + } + } break; - if (p_what == NOTIFICATION_EXIT_TREE) { - if (parent) { - parent->_make_dirty(); - } - parent = nullptr; + case NOTIFICATION_EXIT_TREE: { + if (use_collision && is_root_shape() && root_collision_instance.is_valid()) { + PhysicsServer3D::get_singleton()->free(root_collision_instance); + root_collision_instance = RID(); + root_collision_shape.unref(); + } + } break; - if (use_collision && is_root_shape() && root_collision_instance.is_valid()) { - PhysicsServer3D::get_singleton()->free(root_collision_instance); - root_collision_instance = RID(); - root_collision_shape.unref(); - } - _make_dirty(); + case NOTIFICATION_TRANSFORM_CHANGED: { + if (use_collision && is_root_shape() && root_collision_instance.is_valid()) { + PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform()); + } + } break; } } @@ -953,6 +969,10 @@ CSGBrush *CSGSphere3D::_build_brush() { double u0 = double(j) / radial_segments; double longitude1 = longitude_step * (j + 1); + if (j == radial_segments - 1) { + longitude1 = 0; + } + double x1 = Math::sin(longitude1); double z1 = Math::cos(longitude1); double u1 = double(j + 1) / radial_segments; @@ -1269,6 +1289,9 @@ CSGBrush *CSGCylinder3D::_build_brush() { for (int i = 0; i < sides; i++) { float inc = float(i) / sides; float inc_n = float((i + 1)) / sides; + if (i == sides - 1) { + inc_n = 0; + } float ang = inc * Math_TAU; float ang_n = inc_n * Math_TAU; @@ -1509,6 +1532,9 @@ CSGBrush *CSGTorus3D::_build_brush() { for (int i = 0; i < sides; i++) { float inci = float(i) / sides; float inci_n = float((i + 1)) / sides; + if (i == sides - 1) { + inci_n = 0; + } float angi = inci * Math_TAU; float angi_n = inci_n * Math_TAU; @@ -1519,6 +1545,9 @@ CSGBrush *CSGTorus3D::_build_brush() { for (int j = 0; j < ring_sides; j++) { float incj = float(j) / ring_sides; float incj_n = float((j + 1)) / ring_sides; + if (j == ring_sides - 1) { + incj_n = 0; + } float angj = incj * Math_TAU; float angj_n = incj_n * Math_TAU; diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h index 6da9893368..4721d0c11c 100644 --- a/modules/csg/csg_shape.h +++ b/modules/csg/csg_shape.h @@ -52,13 +52,14 @@ public: private: Operation operation = OPERATION_UNION; - CSGShape3D *parent = nullptr; + CSGShape3D *parent_shape = nullptr; CSGBrush *brush = nullptr; AABB node_aabb; bool dirty = false; + bool last_visible = false; float snap = 0.001; bool use_collision = false; @@ -104,11 +105,12 @@ private: const tbool bIsOrientationPreserving, const int iFace, const int iVert); void _update_shape(); + void _update_collision_faces(); protected: void _notification(int p_what); virtual CSGBrush *_build_brush() = 0; - void _make_dirty(); + void _make_dirty(bool p_parent_removing = false); static void _bind_methods(); @@ -126,7 +128,6 @@ public: virtual Vector<Vector3> get_brush_faces(); virtual AABB get_aabb() const override; - virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override; void set_use_collision(bool p_enable); bool is_using_collision() const; diff --git a/modules/csg/doc_classes/CSGBox3D.xml b/modules/csg/doc_classes/CSGBox3D.xml index 64b07a6cbb..591110fa38 100644 --- a/modules/csg/doc_classes/CSGBox3D.xml +++ b/modules/csg/doc_classes/CSGBox3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGBox3D" inherits="CSGPrimitive3D" version="4.0"> +<class name="CSGBox3D" inherits="CSGPrimitive3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A CSG Box shape. </brief_description> diff --git a/modules/csg/doc_classes/CSGCombiner3D.xml b/modules/csg/doc_classes/CSGCombiner3D.xml index 16903141de..1601602601 100644 --- a/modules/csg/doc_classes/CSGCombiner3D.xml +++ b/modules/csg/doc_classes/CSGCombiner3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGCombiner3D" inherits="CSGShape3D" version="4.0"> +<class name="CSGCombiner3D" inherits="CSGShape3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A CSG node that allows you to combine other CSG modifiers. </brief_description> diff --git a/modules/csg/doc_classes/CSGCylinder3D.xml b/modules/csg/doc_classes/CSGCylinder3D.xml index fa61957c84..ea026c5ee9 100644 --- a/modules/csg/doc_classes/CSGCylinder3D.xml +++ b/modules/csg/doc_classes/CSGCylinder3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGCylinder3D" inherits="CSGPrimitive3D" version="4.0"> +<class name="CSGCylinder3D" inherits="CSGPrimitive3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A CSG Cylinder shape. </brief_description> diff --git a/modules/csg/doc_classes/CSGMesh3D.xml b/modules/csg/doc_classes/CSGMesh3D.xml index 660659a98b..3318fb21c8 100644 --- a/modules/csg/doc_classes/CSGMesh3D.xml +++ b/modules/csg/doc_classes/CSGMesh3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGMesh3D" inherits="CSGPrimitive3D" version="4.0"> +<class name="CSGMesh3D" inherits="CSGPrimitive3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A CSG Mesh shape that uses a mesh resource. </brief_description> diff --git a/modules/csg/doc_classes/CSGPolygon3D.xml b/modules/csg/doc_classes/CSGPolygon3D.xml index e8ef79a9e5..cacad21453 100644 --- a/modules/csg/doc_classes/CSGPolygon3D.xml +++ b/modules/csg/doc_classes/CSGPolygon3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGPolygon3D" inherits="CSGPrimitive3D" version="4.0"> +<class name="CSGPolygon3D" inherits="CSGPrimitive3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Extrudes a 2D polygon shape to create a 3D mesh. </brief_description> diff --git a/modules/csg/doc_classes/CSGPrimitive3D.xml b/modules/csg/doc_classes/CSGPrimitive3D.xml index 7eac85368e..39f4fa320d 100644 --- a/modules/csg/doc_classes/CSGPrimitive3D.xml +++ b/modules/csg/doc_classes/CSGPrimitive3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGPrimitive3D" inherits="CSGShape3D" version="4.0"> +<class name="CSGPrimitive3D" inherits="CSGShape3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Base class for CSG primitives. </brief_description> diff --git a/modules/csg/doc_classes/CSGShape3D.xml b/modules/csg/doc_classes/CSGShape3D.xml index b2513703c0..f1cd28e00f 100644 --- a/modules/csg/doc_classes/CSGShape3D.xml +++ b/modules/csg/doc_classes/CSGShape3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGShape3D" inherits="GeometryInstance3D" version="4.0"> +<class name="CSGShape3D" inherits="GeometryInstance3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> The CSG base class. </brief_description> diff --git a/modules/csg/doc_classes/CSGSphere3D.xml b/modules/csg/doc_classes/CSGSphere3D.xml index 1ef20bc7ca..227f620a4e 100644 --- a/modules/csg/doc_classes/CSGSphere3D.xml +++ b/modules/csg/doc_classes/CSGSphere3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGSphere3D" inherits="CSGPrimitive3D" version="4.0"> +<class name="CSGSphere3D" inherits="CSGPrimitive3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A CSG Sphere shape. </brief_description> diff --git a/modules/csg/doc_classes/CSGTorus3D.xml b/modules/csg/doc_classes/CSGTorus3D.xml index 09256af109..ea555a5449 100644 --- a/modules/csg/doc_classes/CSGTorus3D.xml +++ b/modules/csg/doc_classes/CSGTorus3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGTorus3D" inherits="CSGPrimitive3D" version="4.0"> +<class name="CSGTorus3D" inherits="CSGPrimitive3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A CSG Torus shape. </brief_description> diff --git a/modules/csg/register_types.cpp b/modules/csg/register_types.cpp index f01907bef3..f8db42b1a9 100644 --- a/modules/csg/register_types.cpp +++ b/modules/csg/register_types.cpp @@ -36,8 +36,8 @@ void register_csg_types() { #ifndef _3D_DISABLED - GDREGISTER_VIRTUAL_CLASS(CSGShape3D); - GDREGISTER_VIRTUAL_CLASS(CSGPrimitive3D); + GDREGISTER_ABSTRACT_CLASS(CSGShape3D); + GDREGISTER_ABSTRACT_CLASS(CSGPrimitive3D); GDREGISTER_CLASS(CSGMesh3D); GDREGISTER_CLASS(CSGSphere3D); GDREGISTER_CLASS(CSGBox3D); diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp index c422c3bd6b..7bfe849106 100644 --- a/modules/dds/texture_loader_dds.cpp +++ b/modules/dds/texture_loader_dds.cpp @@ -225,8 +225,8 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, ERR_FAIL_COND_V(!(flags & DDSD_LINEARSIZE), RES()); for (uint32_t i = 1; i < mipmaps; i++) { - w = MAX(1, w >> 1); - h = MAX(1, h >> 1); + w = MAX(1u, w >> 1); + h = MAX(1u, h >> 1); uint32_t bsize = MAX(info.divisor, w) / info.divisor * MAX(info.divisor, h) / info.divisor * info.block_size; //printf("%i x %i - block: %i\n",w,h,bsize); size += bsize; diff --git a/modules/enet/doc_classes/ENetConnection.xml b/modules/enet/doc_classes/ENetConnection.xml index d6b0553eba..14aad0cb39 100644 --- a/modules/enet/doc_classes/ENetConnection.xml +++ b/modules/enet/doc_classes/ENetConnection.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="ENetConnection" inherits="RefCounted" version="4.0"> +<class name="ENetConnection" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A wrapper class for an [url=http://enet.bespin.org/group__host.html]ENetHost[/url]. </brief_description> diff --git a/modules/enet/doc_classes/ENetMultiplayerPeer.xml b/modules/enet/doc_classes/ENetMultiplayerPeer.xml index 723149843a..2ecf6b4122 100644 --- a/modules/enet/doc_classes/ENetMultiplayerPeer.xml +++ b/modules/enet/doc_classes/ENetMultiplayerPeer.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="ENetMultiplayerPeer" inherits="MultiplayerPeer" version="4.0"> +<class name="ENetMultiplayerPeer" inherits="MultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A MultiplayerPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library. </brief_description> diff --git a/modules/enet/doc_classes/ENetPacketPeer.xml b/modules/enet/doc_classes/ENetPacketPeer.xml index 4116ba17f2..5de5a60853 100644 --- a/modules/enet/doc_classes/ENetPacketPeer.xml +++ b/modules/enet/doc_classes/ENetPacketPeer.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="ENetPacketPeer" inherits="PacketPeer" version="4.0"> +<class name="ENetPacketPeer" inherits="PacketPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A wrapper class for an [url=http://enet.bespin.org/group__peer.html]ENetPeer[/url]. </brief_description> diff --git a/modules/enet/register_types.cpp b/modules/enet/register_types.cpp index 36a4e6e6e7..ebc5d95348 100644 --- a/modules/enet/register_types.cpp +++ b/modules/enet/register_types.cpp @@ -44,7 +44,7 @@ void register_enet_types() { } GDREGISTER_CLASS(ENetMultiplayerPeer); - GDREGISTER_VIRTUAL_CLASS(ENetPacketPeer); + GDREGISTER_ABSTRACT_CLASS(ENetPacketPeer); GDREGISTER_CLASS(ENetConnection); } diff --git a/modules/fbx/data/fbx_material.cpp b/modules/fbx/data/fbx_material.cpp index bc638244d8..36e20df3a9 100644 --- a/modules/fbx/data/fbx_material.cpp +++ b/modules/fbx/data/fbx_material.cpp @@ -426,7 +426,7 @@ Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) { // meaning is that approx equal to zero is disabled not actually zero. ;) if (real_value && Math::is_zero_approx(real_value->Value())) { print_verbose("clearcoat real value: " + rtos(real_value->Value())); - spatial_material->set_clearcoat_gloss(1.0 - real_value->Value()); + spatial_material->set_clearcoat_roughness(real_value->Value()); } else { print_error("unsupported value type for clearcoat gloss"); } diff --git a/modules/fbx/fbx_parser/FBXMeshGeometry.cpp b/modules/fbx/fbx_parser/FBXMeshGeometry.cpp index b3956af762..591f2e5503 100644 --- a/modules/fbx/fbx_parser/FBXMeshGeometry.cpp +++ b/modules/fbx/fbx_parser/FBXMeshGeometry.cpp @@ -212,32 +212,6 @@ MeshGeometry::MeshGeometry(uint64_t id, const ElementPtr element, const std::str m_normals = resolve_vertex_data_array<Vector3>(layer_scope, MappingInformationType, ReferenceInformationType, "Normals"); } else if (layer_type_name == "LayerElementColor") { m_colors = resolve_vertex_data_array<Color>(layer_scope, MappingInformationType, ReferenceInformationType, "Colors", "ColorIndex"); - // NOTE: this is a useful sanity check to ensure you're getting any color data which is not default. - // const Color first_color_check = m_colors.data[0]; - // bool colors_are_all_the_same = true; - // size_t i = 1; - // for(i = 1; i < m_colors.data.size(); i++) - // { - // const Color current_color = m_colors.data[i]; - // if(current_color.is_equal_approx(first_color_check)) - // { - // continue; - // } - // else - // { - // colors_are_all_the_same = false; - // break; - // } - // } - // - // if(colors_are_all_the_same) - // { - // print_error("Color serialisation is not working for vertex colors some should be different in the test asset."); - // } - // else - // { - // print_verbose("Color array has unique colors at index: " + itos(i)); - // } } } } diff --git a/modules/fbx/register_types.cpp b/modules/fbx/register_types.cpp index 3eafb4af45..73e15e38b4 100644 --- a/modules/fbx/register_types.cpp +++ b/modules/fbx/register_types.cpp @@ -31,7 +31,7 @@ #include "register_types.h" #include "editor/editor_node.h" -#include "editor_scene_importer_fbx.h" +#include "modules/fbx/editor_scene_importer_fbx.h" #ifdef TOOLS_ENABLED static void _editor_init() { diff --git a/modules/gdnative/SCsub b/modules/gdnative/SCsub deleted file mode 100644 index f7f21a433e..0000000000 --- a/modules/gdnative/SCsub +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - -Import("env") -Import("env_modules") - -env_gdnative = env_modules.Clone() -env_gdnative.add_source_files(env.modules_sources, "gdnative.cpp") -env_gdnative.add_source_files(env.modules_sources, "register_types.cpp") -env_gdnative.add_source_files(env.modules_sources, "android/*.cpp") -env_gdnative.add_source_files(env.modules_sources, "gdnative/*.cpp") -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.Prepend(CPPPATH=["#modules/gdnative/include/"]) - -Export("env_gdnative") - -SConscript("pluginscript/SCsub") -SConscript("videodecoder/SCsub") - - -import gdnative_builders - -_, gensource = env_gdnative.CommandNoCache( - ["include/gdnative_api_struct.gen.h", "gdnative_api_struct.gen.cpp"], - "gdnative_api.json", - env.Run(gdnative_builders.build_gdnative_api_struct, "Generating GDNative API."), -) -env_gdnative.add_source_files(env.modules_sources, [gensource]) diff --git a/modules/gdnative/android/android_gdn.cpp b/modules/gdnative/android/android_gdn.cpp deleted file mode 100644 index 7411fc4031..0000000000 --- a/modules/gdnative/android/android_gdn.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/*************************************************************************/ -/* android_gdn.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "modules/gdnative/gdnative.h" - -// Code by Paritosh97 with minor tweaks by Mux213 -// 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 -#define jobject void * -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEnv *GDAPI godot_android_get_env() { -#ifdef __ANDROID__ - return get_jni_env(); -#else - return nullptr; -#endif -} - -jobject GDAPI godot_android_get_activity() { -#ifdef __ANDROID__ - OS_Android *os_android = (OS_Android *)OS::get_singleton(); - return os_android->get_godot_java()->get_activity(); -#else - return nullptr; -#endif -} - -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 nullptr; -#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 diff --git a/modules/gdnative/config.py b/modules/gdnative/config.py deleted file mode 100644 index 026a84a70f..0000000000 --- a/modules/gdnative/config.py +++ /dev/null @@ -1,20 +0,0 @@ -def can_build(env, platform): - return True - - -def configure(env): - pass - - -def get_doc_classes(): - return [ - "GDNative", - "GDNativeLibrary", - "NativeScript", - "PluginScript", - "VideoStreamGDNative", - ] - - -def get_doc_path(): - return "doc_classes" diff --git a/modules/gdnative/doc_classes/GDNative.xml b/modules/gdnative/doc_classes/GDNative.xml deleted file mode 100644 index 4bc149b119..0000000000 --- a/modules/gdnative/doc_classes/GDNative.xml +++ /dev/null @@ -1,33 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="GDNative" inherits="RefCounted" version="4.0"> - <brief_description> - </brief_description> - <description> - </description> - <tutorials> - </tutorials> - <methods> - <method name="call_native"> - <return type="Variant" /> - <argument index="0" name="calling_type" type="StringName" /> - <argument index="1" name="procedure_name" type="StringName" /> - <argument index="2" name="arguments" type="Array" /> - <description> - </description> - </method> - <method name="initialize"> - <return type="bool" /> - <description> - </description> - </method> - <method name="terminate"> - <return type="bool" /> - <description> - </description> - </method> - </methods> - <members> - <member name="library" type="GDNativeLibrary" setter="set_library" getter="get_library"> - </member> - </members> -</class> diff --git a/modules/gdnative/doc_classes/GDNativeLibrary.xml b/modules/gdnative/doc_classes/GDNativeLibrary.xml deleted file mode 100644 index 21df640ebc..0000000000 --- a/modules/gdnative/doc_classes/GDNativeLibrary.xml +++ /dev/null @@ -1,48 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="GDNativeLibrary" inherits="Resource" version="4.0"> - <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 XRInterfaceGDNative. The library must be compiled for each platform and architecture that the project will run on. - </description> - <tutorials> - <link title="GDNative C example">$DOCS_URL/tutorials/scripting/gdnative/gdnative_c_example.html</link> - <link title="GDNative C++ example">$DOCS_URL/tutorials/scripting/gdnative/gdnative_cpp_example.html</link> - </tutorials> - <methods> - <method name="get_current_dependencies" qualifiers="const"> - <return type="PackedStringArray" /> - <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" /> - <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" 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" 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" 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" 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> -</class> diff --git a/modules/gdnative/doc_classes/NativeScript.xml b/modules/gdnative/doc_classes/NativeScript.xml deleted file mode 100644 index 221374a7a4..0000000000 --- a/modules/gdnative/doc_classes/NativeScript.xml +++ /dev/null @@ -1,55 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="NativeScript" inherits="Script" version="4.0"> - <brief_description> - </brief_description> - <description> - </description> - <tutorials> - </tutorials> - <methods> - <method name="get_class_documentation" qualifiers="const"> - <return type="String" /> - <description> - Returns the documentation string that was previously set with [code]godot_nativescript_set_class_documentation[/code]. - </description> - </method> - <method name="get_method_documentation" qualifiers="const"> - <return type="String" /> - <argument index="0" name="method" type="StringName" /> - <description> - Returns the documentation string that was previously set with [code]godot_nativescript_set_method_documentation[/code]. - </description> - </method> - <method name="get_property_documentation" qualifiers="const"> - <return type="String" /> - <argument index="0" name="path" type="StringName" /> - <description> - Returns the documentation string that was previously set with [code]godot_nativescript_set_property_documentation[/code]. - </description> - </method> - <method name="get_signal_documentation" qualifiers="const"> - <return type="String" /> - <argument index="0" name="signal_name" type="StringName" /> - <description> - Returns the documentation string that was previously set with [code]godot_nativescript_set_signal_documentation[/code]. - </description> - </method> - <method name="new" qualifiers="vararg"> - <return type="Variant" /> - <description> - Constructs a new object of the base type with a script of this type already attached. - [b]Note:[/b] Any arguments passed to this function will be ignored and not passed to the native constructor function. This will change with in a future API extension. - </description> - </method> - </methods> - <members> - <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" default=""""> - </member> - <member name="script_class_name" type="String" setter="set_script_class_name" getter="get_script_class_name" default=""""> - </member> - </members> -</class> diff --git a/modules/gdnative/doc_classes/PluginScript.xml b/modules/gdnative/doc_classes/PluginScript.xml deleted file mode 100644 index ec80ade394..0000000000 --- a/modules/gdnative/doc_classes/PluginScript.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="PluginScript" inherits="Script" version="4.0"> - <brief_description> - </brief_description> - <description> - </description> - <tutorials> - </tutorials> - <methods> - <method name="new" qualifiers="vararg"> - <return type="Variant" /> - <description> - Returns a new instance of the script. - </description> - </method> - </methods> -</class> diff --git a/modules/gdnative/doc_classes/VideoStreamGDNative.xml b/modules/gdnative/doc_classes/VideoStreamGDNative.xml deleted file mode 100644 index dc64e8fc18..0000000000 --- a/modules/gdnative/doc_classes/VideoStreamGDNative.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="VideoStreamGDNative" inherits="VideoStream" version="4.0"> - <brief_description> - [VideoStream] resource for for video formats implemented via GDNative. - </brief_description> - <description> - [VideoStream] resource for for video formats implemented via GDNative. - It can be used via [url=https://github.com/KidRigger/godot-videodecoder]godot-videodecoder[/url] which uses the [url=https://ffmpeg.org]FFmpeg[/url] library. - </description> - <tutorials> - </tutorials> - <methods> - <method name="get_file"> - <return type="String" /> - <description> - Returns the video file handled by this [VideoStreamGDNative]. - </description> - </method> - <method name="set_file"> - <return type="void" /> - <argument index="0" name="file" type="String" /> - <description> - Sets the video file that this [VideoStreamGDNative] resource handles. The supported extensions depend on the GDNative plugins used to expose video formats. - </description> - </method> - </methods> -</class> diff --git a/modules/gdnative/gdnative.cpp b/modules/gdnative/gdnative.cpp deleted file mode 100644 index 3950ce1ade..0000000000 --- a/modules/gdnative/gdnative.cpp +++ /dev/null @@ -1,583 +0,0 @@ -/*************************************************************************/ -/* gdnative.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative.h" - -#include "core/config/project_settings.h" -#include "core/core_constants.h" -#include "core/io/dir_access.h" -#include "core/io/file_access.h" -#include "core/io/file_access_encrypted.h" -#include "core/os/os.h" - -#include "scene/main/scene_tree.h" - -static const String init_symbol = "gdnative_init"; -static const String terminate_symbol = "gdnative_terminate"; -static const String default_symbol_prefix = "godot_"; -static const bool default_singleton = false; -static const bool default_load_once = true; -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; - -GDNativeLibrary::GDNativeLibrary() { - config_file.instantiate(); - - symbol_prefix = default_symbol_prefix; - load_once = default_load_once; - singleton = default_singleton; - reloadable = default_reloadable; -} - -GDNativeLibrary::~GDNativeLibrary() { -} - -bool GDNativeLibrary::_set(const StringName &p_name, const Variant &p_property) { - String name = p_name; - - if (name.begins_with("entry/")) { - String key = name.substr(6, name.length() - 6); - - config_file->set_value("entry", key, p_property); - - set_config_file(config_file); - - return true; - } - - if (name.begins_with("dependency/")) { - String key = name.substr(11, name.length() - 11); - - config_file->set_value("dependencies", key, p_property); - - set_config_file(config_file); - - return true; - } - - return false; -} - -bool GDNativeLibrary::_get(const StringName &p_name, Variant &r_property) const { - String name = p_name; - - if (name.begins_with("entry/")) { - String key = name.substr(6, name.length() - 6); - - r_property = config_file->get_value("entry", key); - - return true; - } - - if (name.begins_with("dependency/")) { - String key = name.substr(11, name.length() - 11); - - r_property = config_file->get_value("dependencies", key); - - return true; - } - - return false; -} - -void GDNativeLibrary::reset_state() { - config_file.instantiate(); - current_library_path = ""; - current_dependencies.clear(); - symbol_prefix = default_symbol_prefix; - load_once = default_load_once; - singleton = default_singleton; - reloadable = default_reloadable; -} - -void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const { - // set entries - List<String> entry_key_list; - - if (config_file->has_section("entry")) { - config_file->get_section_keys("entry", &entry_key_list); - } - - for (const String &key : entry_key_list) { - PropertyInfo prop; - - prop.type = Variant::STRING; - prop.name = "entry/" + key; - - p_list->push_back(prop); - } - - // set dependencies - List<String> dependency_key_list; - - if (config_file->has_section("dependencies")) { - config_file->get_section_keys("dependencies", &dependency_key_list); - } - - for (const String &key : dependency_key_list) { - PropertyInfo prop; - - prop.type = Variant::STRING; - prop.name = "dependency/" + key; - - p_list->push_back(prop); - } -} - -void GDNativeLibrary::set_config_file(Ref<ConfigFile> p_config_file) { - ERR_FAIL_COND(p_config_file.is_null()); - - set_singleton(p_config_file->get_value("general", "singleton", default_singleton)); - set_load_once(p_config_file->get_value("general", "load_once", default_load_once)); - set_symbol_prefix(p_config_file->get_value("general", "symbol_prefix", default_symbol_prefix)); - set_reloadable(p_config_file->get_value("general", "reloadable", default_reloadable)); - - String entry_lib_path; - { - List<String> entry_keys; - - if (p_config_file->has_section("entry")) { - p_config_file->get_section_keys("entry", &entry_keys); - } - - for (const String &key : entry_keys) { - Vector<String> tags = key.split("."); - - bool skip = false; - for (int i = 0; i < tags.size(); i++) { - bool has_feature = OS::get_singleton()->has_feature(tags[i]); - - if (!has_feature) { - skip = true; - break; - } - } - - if (skip) { - continue; - } - - entry_lib_path = p_config_file->get_value("entry", key); - break; - } - } - - Vector<String> dependency_paths; - { - List<String> dependency_keys; - - if (p_config_file->has_section("dependencies")) { - p_config_file->get_section_keys("dependencies", &dependency_keys); - } - - for (const String &key : dependency_keys) { - Vector<String> tags = key.split("."); - - bool skip = false; - for (int i = 0; i < tags.size(); i++) { - bool has_feature = OS::get_singleton()->has_feature(tags[i]); - - if (!has_feature) { - skip = true; - break; - } - } - - if (skip) { - continue; - } - - dependency_paths = p_config_file->get_value("dependencies", key); - break; - } - } - - current_library_path = entry_lib_path; - current_dependencies = dependency_paths; -} - -void GDNativeLibrary::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_config_file"), &GDNativeLibrary::get_config_file); - ClassDB::bind_method(D_METHOD("set_config_file", "config_file"), &GDNativeLibrary::set_config_file); - - ClassDB::bind_method(D_METHOD("get_current_library_path"), &GDNativeLibrary::get_current_library_path); - ClassDB::bind_method(D_METHOD("get_current_dependencies"), &GDNativeLibrary::get_current_dependencies); - - ClassDB::bind_method(D_METHOD("should_load_once"), &GDNativeLibrary::should_load_once); - ClassDB::bind_method(D_METHOD("is_singleton"), &GDNativeLibrary::is_singleton); - ClassDB::bind_method(D_METHOD("get_symbol_prefix"), &GDNativeLibrary::get_symbol_prefix); - ClassDB::bind_method(D_METHOD("is_reloadable"), &GDNativeLibrary::is_reloadable); - - ClassDB::bind_method(D_METHOD("set_load_once", "load_once"), &GDNativeLibrary::set_load_once); - ClassDB::bind_method(D_METHOD("set_singleton", "singleton"), &GDNativeLibrary::set_singleton); - 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", PROPERTY_USAGE_NONE), "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"); - ADD_PROPERTY(PropertyInfo(Variant::STRING, "symbol_prefix"), "set_symbol_prefix", "get_symbol_prefix"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reloadable"), "set_reloadable", "is_reloadable"); -} - -GDNative::GDNative() { - native_handle = nullptr; - initialized = false; -} - -GDNative::~GDNative() { -} - -void GDNative::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_library", "library"), &GDNative::set_library); - ClassDB::bind_method(D_METHOD("get_library"), &GDNative::get_library); - - ClassDB::bind_method(D_METHOD("initialize"), &GDNative::initialize); - ClassDB::bind_method(D_METHOD("terminate"), &GDNative::terminate); - - ClassDB::bind_method(D_METHOD("call_native", "calling_type", "procedure_name", "arguments"), &GDNative::call_native); - - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "library", PROPERTY_HINT_RESOURCE_TYPE, "GDNativeLibrary"), "set_library", "get_library"); -} - -void GDNative::set_library(Ref<GDNativeLibrary> p_library) { - ERR_FAIL_COND_MSG(library.is_valid(), "Tried to change library of GDNative when it is already set."); - library = p_library; -} - -Ref<GDNativeLibrary> GDNative::get_library() const { - return library; -} - -extern "C" void _gdnative_report_version_mismatch(const godot_object *p_library, const char *p_ext, godot_gdnative_api_version p_want, godot_gdnative_api_version p_have); -extern "C" void _gdnative_report_loading_error(const godot_object *p_library, const char *p_what); - -bool GDNative::initialize() { - if (library.is_null()) { - ERR_PRINT("No library set, can't initialize GDNative object"); - return false; - } - - String lib_path = library->get_current_library_path(); - if (lib_path.is_empty()) { - ERR_PRINT("No library set for this platform"); - return false; - } -#ifdef IPHONE_ENABLED - // On iOS we use static linking by default. - String path = ""; - - // On iOS dylibs is not allowed, but can be replaced with .framework or .xcframework. - // If they are used, we can run dlopen on them. - // They should be located under Frameworks directory, so we need to replace library path. - if (!lib_path.ends_with(".a")) { - path = ProjectSettings::get_singleton()->globalize_path(lib_path); - - if (!FileAccess::exists(path)) { - String lib_name = lib_path.get_basename().get_file(); - String framework_path_format = "Frameworks/$name.framework/$name"; - - Dictionary format_dict; - format_dict["name"] = lib_name; - String framework_path = framework_path_format.format(format_dict, "$_"); - - path = OS::get_singleton()->get_executable_path().get_base_dir().plus_file(framework_path); - } - } -#elif defined(ANDROID_ENABLED) - // On Android dynamic libraries are located separately from resource assets, - // we should pass library name to dlopen(). The library name is flattened - // during export. - String path = lib_path.get_file(); -#elif defined(UWP_ENABLED) - // On UWP we use a relative path from the app - String path = lib_path.replace("res://", ""); -#elif defined(OSX_ENABLED) - // On OSX the exported libraries are located under the Frameworks directory. - // So we need to replace the library path. - String path = ProjectSettings::get_singleton()->globalize_path(lib_path); - DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - - if (!da->file_exists(path) && !da->dir_exists(path)) { - path = OS::get_singleton()->get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(lib_path.get_file()); - } - - if (da->dir_exists(path)) { // Target library is a ".framework", add library base name to the path. - path = path.plus_file(path.get_file().get_basename()); - } - - memdelete(da); - -#else - String path = ProjectSettings::get_singleton()->globalize_path(lib_path); -#endif - - if (library->should_load_once()) { - 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; - initialized = true; - return true; - } - } - - Error err = OS::get_singleton()->open_dynamic_library(path, native_handle, true); - if (err != OK) { - return false; - } - - void *library_init; - - // we cheat here a little bit. you saw nothing - initialized = true; - - err = get_symbol(library->get_symbol_prefix() + init_symbol, library_init, false); - - initialized = false; - - if (err || !library_init) { - OS::get_singleton()->close_dynamic_library(native_handle); - native_handle = nullptr; - ERR_PRINT("Failed to obtain " + library->get_symbol_prefix() + "gdnative_init symbol"); - return false; - } - - godot_gdnative_init_fn library_init_fpointer; - library_init_fpointer = (godot_gdnative_init_fn)library_init; - - static uint64_t core_api_hash = 0; - static uint64_t editor_api_hash = 0; - static uint64_t no_api_hash = 0; - - if (!(core_api_hash || editor_api_hash || no_api_hash)) { - core_api_hash = ClassDB::get_api_hash(ClassDB::API_CORE); - editor_api_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR); - no_api_hash = ClassDB::get_api_hash(ClassDB::API_NONE); - } - - godot_gdnative_init_options options; - - options.api_struct = &api_struct; - options.in_editor = Engine::get_singleton()->is_editor_hint(); - options.core_api_hash = core_api_hash; - options.editor_api_hash = editor_api_hash; - options.no_api_hash = no_api_hash; - options.report_version_mismatch = &_gdnative_report_version_mismatch; - options.report_loading_error = &_gdnative_report_loading_error; - options.gd_native_library = (godot_object *)(get_library().ptr()); - options.active_library_path = (godot_string *)&path; - - library_init_fpointer(&options); - - initialized = true; - - 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); - } - - return true; -} - -bool GDNative::terminate() { - if (!initialized) { - ERR_PRINT("No valid library handle, can't terminate GDNative object"); - return false; - } - - if (library->should_load_once()) { - 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)); - initialized = false; - return true; - } else if (gdnatives->size() == 1) { - // we're the last one, terminate! - gdnatives->clear(); - // 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())); - } - } - - void *library_terminate; - Error error = get_symbol(library->get_symbol_prefix() + terminate_symbol, library_terminate); - if (error || !library_terminate) { - OS::get_singleton()->close_dynamic_library(native_handle); - native_handle = nullptr; - initialized = false; - return true; - } - - godot_gdnative_terminate_fn library_terminate_pointer; - library_terminate_pointer = (godot_gdnative_terminate_fn)library_terminate; - - godot_gdnative_terminate_options options; - options.in_editor = Engine::get_singleton()->is_editor_hint(); - - library_terminate_pointer(&options); - - initialized = false; - - // GDNativeScriptLanguage::get_singleton()->initialized_libraries.erase(p_native_lib->path); - - OS::get_singleton()->close_dynamic_library(native_handle); - native_handle = nullptr; - - return true; -} - -bool GDNative::is_initialized() const { - return initialized; -} - -void GDNativeCallRegistry::register_native_call_type(StringName p_call_type, native_call_cb p_callback) { - native_calls.insert(p_call_type, p_callback); -} - -Vector<StringName> GDNativeCallRegistry::get_native_call_types() { - Vector<StringName> call_types; - call_types.resize(native_calls.size()); - - size_t idx = 0; - for (Map<StringName, native_call_cb>::Element *E = native_calls.front(); E; E = E->next(), idx++) { - call_types.write[idx] = E->key(); - } - - return call_types; -} - -Variant GDNative::call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments) { - Map<StringName, native_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_calls.find(p_native_call_type); - if (!E) { - ERR_PRINT((String("No handler for native call type \"" + p_native_call_type) + "\" found").utf8().get_data()); - return Variant(); - } - - void *procedure_handle; - - Error err = OS::get_singleton()->get_dynamic_library_symbol_handle( - native_handle, - p_procedure_name, - procedure_handle); - - if (err != OK || procedure_handle == nullptr) { - return Variant(); - } - - godot_variant result = E->get()(procedure_handle, (godot_array *)&p_arguments); - - Variant res = *(Variant *)&result; - godot_variant_destroy(&result); - return res; -} - -Error GDNative::get_symbol(StringName p_procedure_name, void *&r_handle, bool p_optional) const { - if (!initialized) { - ERR_PRINT("No valid library handle, can't get symbol from GDNative object"); - return ERR_CANT_OPEN; - } - - Error result = OS::get_singleton()->get_dynamic_library_symbol_handle( - native_handle, - p_procedure_name, - r_handle, - p_optional); - - return result; -} - -RES GDNativeLibraryResourceLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) { - Ref<GDNativeLibrary> lib; - lib.instantiate(); - - Ref<ConfigFile> config = lib->get_config_file(); - - Error err = config->load(p_path); - - if (r_error) { - *r_error = err; - } - - lib->set_config_file(config); - - return lib; -} - -void GDNativeLibraryResourceLoader::get_recognized_extensions(List<String> *p_extensions) const { - p_extensions->push_back("gdnlib"); -} - -bool GDNativeLibraryResourceLoader::handles_type(const String &p_type) const { - return p_type == "GDNativeLibrary"; -} - -String GDNativeLibraryResourceLoader::get_resource_type(const String &p_path) const { - String el = p_path.get_extension().to_lower(); - if (el == "gdnlib") { - return "GDNativeLibrary"; - } - return ""; -} - -Error GDNativeLibraryResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { - Ref<GDNativeLibrary> lib = p_resource; - - if (lib.is_null()) { - return ERR_INVALID_DATA; - } - - Ref<ConfigFile> config = lib->get_config_file(); - - config->set_value("general", "singleton", lib->is_singleton()); - config->set_value("general", "load_once", lib->should_load_once()); - config->set_value("general", "symbol_prefix", lib->get_symbol_prefix()); - config->set_value("general", "reloadable", lib->is_reloadable()); - - return config->save(p_path); -} - -bool GDNativeLibraryResourceSaver::recognize(const RES &p_resource) const { - return Object::cast_to<GDNativeLibrary>(*p_resource) != nullptr; -} - -void GDNativeLibraryResourceSaver::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { - if (Object::cast_to<GDNativeLibrary>(*p_resource) != nullptr) { - p_extensions->push_back("gdnlib"); - } -} diff --git a/modules/gdnative/gdnative.h b/modules/gdnative/gdnative.h deleted file mode 100644 index 8facd43743..0000000000 --- a/modules/gdnative/gdnative.h +++ /dev/null @@ -1,184 +0,0 @@ -/*************************************************************************/ -/* gdnative.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 GDNATIVE_H -#define GDNATIVE_H - -#include "core/io/resource.h" -#include "core/io/resource_loader.h" -#include "core/io/resource_saver.h" -#include "core/os/thread_safe.h" - -#include "gdnative/gdnative.h" -#include "gdnative_api_struct.gen.h" - -#include "core/io/config_file.h" - -class GDNativeLibraryResourceLoader; -class GDNative; - -class GDNativeLibrary : public Resource { - GDCLASS(GDNativeLibrary, Resource); - - static Map<String, Vector<Ref<GDNative>>> loaded_libraries; - - friend class GDNativeLibraryResourceLoader; - friend class GDNative; - - Ref<ConfigFile> config_file; - - String current_library_path; - Vector<String> current_dependencies; - - bool singleton; - bool load_once; - String symbol_prefix; - bool reloadable; - -public: - virtual void reset_state() override; - - GDNativeLibrary(); - ~GDNativeLibrary(); - - virtual bool _set(const StringName &p_name, const Variant &p_property); - virtual bool _get(const StringName &p_name, Variant &r_property) const; - virtual void _get_property_list(List<PropertyInfo> *p_list) const; - - _FORCE_INLINE_ Ref<ConfigFile> get_config_file() { return config_file; } - - void set_config_file(Ref<ConfigFile> p_config_file); - - // things that change per-platform - // so there are no setters for this - _FORCE_INLINE_ String get_current_library_path() const { - return current_library_path; - } - _FORCE_INLINE_ Vector<String> get_current_dependencies() const { - return current_dependencies; - } - - // things that are a property of the library itself, not platform specific - _FORCE_INLINE_ bool should_load_once() const { - return load_once; - } - _FORCE_INLINE_ bool is_singleton() const { - return singleton; - } - _FORCE_INLINE_ String get_symbol_prefix() const { - return symbol_prefix; - } - - _FORCE_INLINE_ bool is_reloadable() const { - return reloadable; - } - - _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; - } - - static void _bind_methods(); -}; - -struct GDNativeCallRegistry { - static GDNativeCallRegistry *singleton; - - inline static GDNativeCallRegistry *get_singleton() { - return singleton; - } - - inline GDNativeCallRegistry() : - native_calls() {} - - Map<StringName, native_call_cb> native_calls; - - void register_native_call_type(StringName p_call_type, native_call_cb p_callback); - - Vector<StringName> get_native_call_types(); -}; - -class GDNative : public RefCounted { - GDCLASS(GDNative, RefCounted); - - Ref<GDNativeLibrary> library; - - void *native_handle; - - bool initialized; - -public: - GDNative(); - ~GDNative(); - - static void _bind_methods(); - - void set_library(Ref<GDNativeLibrary> p_library); - Ref<GDNativeLibrary> get_library() const; - - bool is_initialized() const; - - bool initialize(); - bool terminate(); - - Variant call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments = Array()); - - Error get_symbol(StringName p_procedure_name, void *&r_handle, bool p_optional = true) const; -}; - -class GDNativeLibraryResourceLoader : public ResourceFormatLoader { -public: - virtual RES load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE); - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String &p_type) const; - virtual String get_resource_type(const String &p_path) const; -}; - -class GDNativeLibraryResourceSaver : public 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; - virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; -}; - -#endif // GDNATIVE_H diff --git a/modules/gdnative/gdnative/aabb.cpp b/modules/gdnative/gdnative/aabb.cpp deleted file mode 100644 index 82aa7215b2..0000000000 --- a/modules/gdnative/gdnative/aabb.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/*************************************************************************/ -/* aabb.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/aabb.h" - -#include "core/math/aabb.h" - -static_assert(sizeof(godot_aabb) == sizeof(AABB), "AABB size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_aabb_new(godot_aabb *p_self) { - memnew_placement(p_self, AABB); -} - -void GDAPI godot_aabb_new_copy(godot_aabb *r_dest, const godot_aabb *p_src) { - memnew_placement(r_dest, AABB(*(AABB *)p_src)); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/array.cpp b/modules/gdnative/gdnative/array.cpp deleted file mode 100644 index 31063e43c1..0000000000 --- a/modules/gdnative/gdnative/array.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/*************************************************************************/ -/* array.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/array.h" - -#include "core/os/memory.h" -#include "core/variant/array.h" - -static_assert(sizeof(godot_array) == sizeof(Array), "Array size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_array_new(godot_array *p_self) { - memnew_placement(p_self, Array); -} - -void GDAPI godot_array_new_copy(godot_array *r_dest, const godot_array *p_src) { - memnew_placement(r_dest, Array(*(Array *)p_src)); -} - -void GDAPI godot_array_destroy(godot_array *p_self) { - ((Array *)p_self)->~Array(); -} - -godot_variant GDAPI *godot_array_operator_index(godot_array *p_self, godot_int p_index) { - Array *self = (Array *)p_self; - return (godot_variant *)&self->operator[](p_index); -} - -const godot_variant GDAPI *godot_array_operator_index_const(const godot_array *p_self, godot_int p_index) { - const Array *self = (const Array *)p_self; - return (const godot_variant *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/basis.cpp b/modules/gdnative/gdnative/basis.cpp deleted file mode 100644 index af7f9a2399..0000000000 --- a/modules/gdnative/gdnative/basis.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/*************************************************************************/ -/* basis.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/basis.h" - -#include "core/math/basis.h" - -static_assert(sizeof(godot_basis) == sizeof(Basis), "Basis size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_basis_new(godot_basis *p_self) { - memnew_placement(p_self, Basis); -} - -void GDAPI godot_basis_new_copy(godot_basis *r_dest, const godot_basis *p_src) { - memnew_placement(r_dest, Basis(*(Basis *)p_src)); -} - -godot_vector3 GDAPI *godot_basis_operator_index(godot_basis *p_self, godot_int p_index) { - Basis *self = (Basis *)p_self; - return (godot_vector3 *)&self->operator[](p_index); -} - -const godot_vector3 GDAPI *godot_basis_operator_index_const(const godot_basis *p_self, godot_int p_index) { - const Basis *self = (const Basis *)p_self; - return (const godot_vector3 *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/callable.cpp b/modules/gdnative/gdnative/callable.cpp deleted file mode 100644 index 7ae1038a13..0000000000 --- a/modules/gdnative/gdnative/callable.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/*************************************************************************/ -/* callable.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/callable.h" - -#include "core/variant/callable.h" -#include "core/variant/variant.h" - -static_assert(sizeof(godot_callable) == sizeof(Callable), "Callable size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_callable_new(godot_callable *p_self) { - memnew_placement(p_self, Callable); -} - -void GDAPI godot_callable_new_copy(godot_callable *r_dest, const godot_callable *p_src) { - memnew_placement(r_dest, Callable(*(Callable *)p_src)); -} - -void GDAPI godot_callable_destroy(godot_callable *p_self) { - Callable *self = (Callable *)p_self; - self->~Callable(); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/color.cpp b/modules/gdnative/gdnative/color.cpp deleted file mode 100644 index 8f13610b2c..0000000000 --- a/modules/gdnative/gdnative/color.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/*************************************************************************/ -/* color.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/color.h" - -#include "core/math/color.h" - -static_assert(sizeof(godot_color) == sizeof(Color), "Color size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_color_new(godot_color *p_self) { - memnew_placement(p_self, Color); -} - -void GDAPI godot_color_new_copy(godot_color *r_dest, const godot_color *p_src) { - memnew_placement(r_dest, Color(*(Color *)p_src)); -} - -float GDAPI *godot_color_operator_index(godot_color *p_self, godot_int p_index) { - Color *self = (Color *)p_self; - return (float *)&self->operator[](p_index); -} - -const float GDAPI *godot_color_operator_index_const(const godot_color *p_self, godot_int p_index) { - const Color *self = (const Color *)p_self; - return (const float *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/dictionary.cpp b/modules/gdnative/gdnative/dictionary.cpp deleted file mode 100644 index dea01dad43..0000000000 --- a/modules/gdnative/gdnative/dictionary.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/*************************************************************************/ -/* dictionary.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/dictionary.h" - -#include "core/variant/dictionary.h" -#include "core/variant/variant.h" - -static_assert(sizeof(godot_dictionary) == sizeof(Dictionary), "Dictionary size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_dictionary_new(godot_dictionary *p_self) { - memnew_placement(p_self, Dictionary); -} - -void GDAPI godot_dictionary_new_copy(godot_dictionary *r_dest, const godot_dictionary *p_src) { - memnew_placement(r_dest, Dictionary(*(Dictionary *)p_src)); -} - -void GDAPI godot_dictionary_destroy(godot_dictionary *p_self) { - Dictionary *self = (Dictionary *)p_self; - self->~Dictionary(); -} - -godot_variant GDAPI *godot_dictionary_operator_index(godot_dictionary *p_self, const godot_variant *p_key) { - Dictionary *self = (Dictionary *)p_self; - return (godot_variant *)&self->operator[](*((const Variant *)p_key)); -} - -const godot_variant GDAPI *godot_dictionary_operator_index_const(const godot_dictionary *p_self, const godot_variant *p_key) { - const Dictionary *self = (const Dictionary *)p_self; - return (const godot_variant *)&self->operator[](*((const Variant *)p_key)); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/gdnative.cpp b/modules/gdnative/gdnative/gdnative.cpp deleted file mode 100644 index 8ba41b3224..0000000000 --- a/modules/gdnative/gdnative/gdnative.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/*************************************************************************/ -/* gdnative.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/gdnative.h" - -#include "core/config/engine.h" -#include "core/core_constants.h" -#include "core/error/error_macros.h" -#include "core/object/class_db.h" -#include "core/os/os.h" -#include "core/variant/variant.h" - -#include "modules/gdnative/gdnative.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_object_destroy(godot_object *p_o) { - memdelete((Object *)p_o); -} - -// Singleton API - -godot_object GDAPI *godot_global_get_singleton(char *p_name) { - return (godot_object *)Engine::get_singleton()->get_singleton_object(String(p_name)); -} // result shouldn't be freed - -// MethodBind API - -godot_method_bind GDAPI *godot_method_bind_get_method(const char *p_classname, const char *p_methodname) { - MethodBind *mb = ClassDB::get_method(StringName(p_classname), StringName(p_methodname)); - // MethodBind *mb = ClassDB::get_method("Node", "get_name"); - return (godot_method_bind *)mb; -} - -void GDAPI godot_method_bind_ptrcall(godot_method_bind *p_method_bind, godot_object *p_instance, const void **p_args, void *p_ret) { - MethodBind *mb = (MethodBind *)p_method_bind; - Object *o = (Object *)p_instance; - mb->ptrcall(o, p_args, p_ret); -} - -godot_variant GDAPI godot_method_bind_call(godot_method_bind *p_method_bind, godot_object *p_instance, const godot_variant **p_args, const int p_arg_count, godot_variant_call_error *p_call_error) { - MethodBind *mb = (MethodBind *)p_method_bind; - Object *o = (Object *)p_instance; - const Variant **args = (const Variant **)p_args; - - godot_variant ret; - godot_variant_new_nil(&ret); - - Variant *ret_val = (Variant *)&ret; - - Callable::CallError r_error; - *ret_val = mb->call(o, args, p_arg_count, r_error); - - if (p_call_error) { - p_call_error->error = (godot_variant_call_error_error)r_error.error; - p_call_error->argument = r_error.argument; - p_call_error->expected = (godot_variant_type)r_error.expected; - } - - return ret; -} - -godot_class_constructor GDAPI godot_get_class_constructor(const char *p_classname) { - ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(StringName(p_classname)); - if (class_info) { - return (godot_class_constructor)class_info->creation_func; - } - return nullptr; -} - -godot_dictionary GDAPI godot_get_global_constants() { - godot_dictionary constants; - memnew_placement(&constants, Dictionary); - Dictionary *p_constants = (Dictionary *)&constants; - const int constants_count = CoreConstants::get_global_constant_count(); - for (int i = 0; i < constants_count; ++i) { - const char *name = CoreConstants::get_global_constant_name(i); - int value = CoreConstants::get_global_constant_value(i); - (*p_constants)[name] = value; - } - return constants; -} - -// System functions -void GDAPI godot_register_native_call_type(const char *p_call_type, native_call_cb p_callback) { - GDNativeCallRegistry::get_singleton()->register_native_call_type(StringName(p_call_type), p_callback); -} - -void GDAPI *godot_alloc(int p_bytes) { - return memalloc(p_bytes); -} - -void GDAPI *godot_realloc(void *p_ptr, int p_bytes) { - return memrealloc(p_ptr, p_bytes); -} - -void GDAPI godot_free(void *p_ptr) { - memfree(p_ptr); -} - -// Helper print functions. -void GDAPI godot_print_error(const char *p_description, const char *p_function, const char *p_file, int p_line) { - _err_print_error(p_function, p_file, p_line, p_description, false, ERR_HANDLER_ERROR); -} -void GDAPI godot_print_warning(const char *p_description, const char *p_function, const char *p_file, int p_line) { - _err_print_error(p_function, p_file, p_line, p_description, false, ERR_HANDLER_WARNING); -} -void GDAPI godot_print_script_error(const char *p_description, const char *p_function, const char *p_file, int p_line) { - _err_print_error(p_function, p_file, p_line, p_description, false, ERR_HANDLER_SCRIPT); -} - -void _gdnative_report_version_mismatch(const godot_object *p_library, const char *p_ext, godot_gdnative_api_version p_want, godot_gdnative_api_version p_have) { - String message = "Error loading GDNative file "; - GDNativeLibrary *library = (GDNativeLibrary *)p_library; - - message += library->get_current_library_path() + ": Extension \"" + p_ext + "\" can't be loaded.\n"; - - Dictionary versions; - versions["have_major"] = p_have.major; - versions["have_minor"] = p_have.minor; - versions["want_major"] = p_want.major; - versions["want_minor"] = p_want.minor; - - message += String("Got version {have_major}.{have_minor} but needs {want_major}.{want_minor}!").format(versions); - - _err_print_error("gdnative_init", library->get_current_library_path().utf8().ptr(), 0, message.utf8().ptr()); -} - -void _gdnative_report_loading_error(const godot_object *p_library, const char *p_what) { - String message = "Error loading GDNative file "; - GDNativeLibrary *library = (GDNativeLibrary *)p_library; - - message += library->get_current_library_path() + ": " + p_what; - - _err_print_error("gdnative_init", library->get_current_library_path().utf8().ptr(), 0, message.utf8().ptr()); -} - -godot_object GDAPI *godot_instance_from_id(uint64_t p_instance_id) { - return (godot_object *)ObjectDB::get_instance(ObjectID(p_instance_id)); -} - -void *godot_get_class_tag(const godot_string_name *p_class) { - StringName class_name = *(StringName *)p_class; - ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(class_name); - return class_info ? class_info->class_ptr : nullptr; -} - -godot_object *godot_object_cast_to(const godot_object *p_object, void *p_class_tag) { - if (!p_object) { - return nullptr; - } - Object *o = (Object *)p_object; - - return o->is_class_ptr(p_class_tag) ? (godot_object *)o : nullptr; -} - -uint64_t GDAPI godot_object_get_instance_id(const godot_object *p_object) { - const Object *o = (const Object *)p_object; - return (uint64_t)o->get_instance_id(); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/node_path.cpp b/modules/gdnative/gdnative/node_path.cpp deleted file mode 100644 index 3db705f550..0000000000 --- a/modules/gdnative/gdnative/node_path.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/*************************************************************************/ -/* node_path.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/node_path.h" - -#include "core/string/node_path.h" - -static_assert(sizeof(godot_node_path) == sizeof(NodePath), "NodePath size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_node_path_new(godot_node_path *p_self) { - memnew_placement(p_self, NodePath); -} - -void GDAPI godot_node_path_new_copy(godot_node_path *r_dest, const godot_node_path *p_src) { - memnew_placement(r_dest, NodePath(*(NodePath *)p_src)); -} - -void GDAPI godot_node_path_destroy(godot_node_path *p_self) { - NodePath *self = (NodePath *)p_self; - self->~NodePath(); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/packed_arrays.cpp b/modules/gdnative/gdnative/packed_arrays.cpp deleted file mode 100644 index 0c49694e0b..0000000000 --- a/modules/gdnative/gdnative/packed_arrays.cpp +++ /dev/null @@ -1,320 +0,0 @@ -/*************************************************************************/ -/* packed_arrays.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/packed_arrays.h" - -#include "core/variant/variant.h" - -#include "core/math/vector2i.h" -#include "core/math/vector3i.h" - -static_assert(sizeof(godot_packed_byte_array) == sizeof(PackedByteArray), "PackedByteArray size mismatch"); -static_assert(sizeof(godot_packed_int32_array) == sizeof(PackedInt32Array), "PackedInt32Array size mismatch"); -static_assert(sizeof(godot_packed_int64_array) == sizeof(PackedInt64Array), "PackedInt64Array size mismatch"); -static_assert(sizeof(godot_packed_float32_array) == sizeof(PackedFloat32Array), "PackedFloat32Array size mismatch"); -static_assert(sizeof(godot_packed_float64_array) == sizeof(PackedFloat64Array), "PackedFloat64Array size mismatch"); -static_assert(sizeof(godot_packed_string_array) == sizeof(PackedStringArray), "PackedStringArray size mismatch"); -static_assert(sizeof(godot_packed_vector2_array) == sizeof(PackedVector2Array), "PackedVector2Array size mismatch"); -static_assert(sizeof(godot_packed_vector2i_array) == sizeof(Vector<Vector2i>), "Vector<Vector2i> size mismatch"); -static_assert(sizeof(godot_packed_vector3_array) == sizeof(PackedVector3Array), "PackedVector3Array size mismatch"); -static_assert(sizeof(godot_packed_vector3i_array) == sizeof(Vector<Vector3i>), "Vector<Vector3i> size mismatch"); -static_assert(sizeof(godot_packed_color_array) == sizeof(PackedColorArray), "PackedColorArray size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -// byte - -void GDAPI godot_packed_byte_array_new(godot_packed_byte_array *p_self) { - memnew_placement(p_self, PackedByteArray); -} - -void GDAPI godot_packed_byte_array_new_copy(godot_packed_byte_array *r_dest, const godot_packed_byte_array *p_src) { - memnew_placement(r_dest, PackedByteArray(*(PackedByteArray *)p_src)); -} - -void GDAPI godot_packed_byte_array_destroy(godot_packed_byte_array *p_self) { - ((PackedByteArray *)p_self)->~PackedByteArray(); -} - -uint8_t GDAPI *godot_packed_byte_array_operator_index(godot_packed_byte_array *p_self, godot_int p_index) { - PackedByteArray *self = (PackedByteArray *)p_self; - return (uint8_t *)&self->operator[](p_index); -} - -const uint8_t GDAPI *godot_packed_byte_array_operator_index_const(const godot_packed_byte_array *p_self, godot_int p_index) { - const PackedByteArray *self = (const PackedByteArray *)p_self; - return (const uint8_t *)&self->operator[](p_index); -} - -// int32 - -void GDAPI godot_packed_int32_array_new(godot_packed_int32_array *p_self) { - memnew_placement(p_self, PackedInt32Array); -} - -void GDAPI godot_packed_int32_array_new_copy(godot_packed_int32_array *r_dest, const godot_packed_int32_array *p_src) { - memnew_placement(r_dest, PackedInt32Array(*(PackedInt32Array *)p_src)); -} - -void GDAPI godot_packed_int32_array_destroy(godot_packed_int32_array *p_self) { - ((PackedInt32Array *)p_self)->~PackedInt32Array(); -} - -int32_t GDAPI *godot_packed_int32_array_operator_index(godot_packed_int32_array *p_self, godot_int p_index) { - PackedInt32Array *self = (PackedInt32Array *)p_self; - return (int32_t *)&self->operator[](p_index); -} - -const int32_t GDAPI *godot_packed_int32_array_operator_index_const(const godot_packed_int32_array *p_self, godot_int p_index) { - const PackedInt32Array *self = (const PackedInt32Array *)p_self; - return (const int32_t *)&self->operator[](p_index); -} - -// int64 - -void GDAPI godot_packed_int64_array_new(godot_packed_int64_array *p_self) { - memnew_placement(p_self, PackedInt64Array); -} - -void GDAPI godot_packed_int64_array_new_copy(godot_packed_int64_array *r_dest, const godot_packed_int64_array *p_src) { - memnew_placement(r_dest, PackedInt64Array(*(PackedInt64Array *)p_src)); -} - -void GDAPI godot_packed_int64_array_destroy(godot_packed_int64_array *p_self) { - ((PackedInt64Array *)p_self)->~PackedInt64Array(); -} - -int64_t GDAPI *godot_packed_int64_array_operator_index(godot_packed_int64_array *p_self, godot_int p_index) { - PackedInt64Array *self = (PackedInt64Array *)p_self; - return (int64_t *)&self->operator[](p_index); -} - -const int64_t GDAPI *godot_packed_int64_array_operator_index_const(const godot_packed_int64_array *p_self, godot_int p_index) { - const PackedInt64Array *self = (const PackedInt64Array *)p_self; - return (const int64_t *)&self->operator[](p_index); -} - -// float32 - -void GDAPI godot_packed_float32_array_new(godot_packed_float32_array *p_self) { - memnew_placement(p_self, PackedFloat32Array); -} - -void GDAPI godot_packed_float32_array_new_copy(godot_packed_float32_array *r_dest, const godot_packed_float32_array *p_src) { - memnew_placement(r_dest, PackedFloat32Array(*(PackedFloat32Array *)p_src)); -} - -void GDAPI godot_packed_float32_array_destroy(godot_packed_float32_array *p_self) { - ((PackedFloat32Array *)p_self)->~PackedFloat32Array(); -} - -float GDAPI *godot_packed_float32_array_operator_index(godot_packed_float32_array *p_self, godot_int p_index) { - PackedFloat32Array *self = (PackedFloat32Array *)p_self; - return (float *)&self->operator[](p_index); -} - -const float GDAPI *godot_packed_float32_array_operator_index_const(const godot_packed_float32_array *p_self, godot_int p_index) { - const PackedFloat32Array *self = (const PackedFloat32Array *)p_self; - return (const float *)&self->operator[](p_index); -} - -// float64 - -void GDAPI godot_packed_float64_array_new(godot_packed_float64_array *p_self) { - memnew_placement(p_self, PackedFloat64Array); -} - -void GDAPI godot_packed_float64_array_new_copy(godot_packed_float64_array *r_dest, const godot_packed_float64_array *p_src) { - memnew_placement(r_dest, PackedFloat64Array(*(PackedFloat64Array *)p_src)); -} - -void GDAPI godot_packed_float64_array_destroy(godot_packed_float64_array *p_self) { - ((PackedFloat64Array *)p_self)->~PackedFloat64Array(); -} - -double GDAPI *godot_packed_float64_array_operator_index(godot_packed_float64_array *p_self, godot_int p_index) { - PackedFloat64Array *self = (PackedFloat64Array *)p_self; - return (double *)&self->operator[](p_index); -} - -const double GDAPI *godot_packed_float64_array_operator_index_const(const godot_packed_float64_array *p_self, godot_int p_index) { - const PackedFloat64Array *self = (const PackedFloat64Array *)p_self; - return (const double *)&self->operator[](p_index); -} - -// string - -void GDAPI godot_packed_string_array_new(godot_packed_string_array *p_self) { - memnew_placement(p_self, PackedStringArray); -} - -void GDAPI godot_packed_string_array_new_copy(godot_packed_string_array *r_dest, const godot_packed_string_array *p_src) { - memnew_placement(r_dest, PackedStringArray(*(PackedStringArray *)p_src)); -} - -void GDAPI godot_packed_string_array_destroy(godot_packed_string_array *p_self) { - ((PackedStringArray *)p_self)->~PackedStringArray(); -} - -godot_string GDAPI *godot_packed_string_array_operator_index(godot_packed_string_array *p_self, godot_int p_index) { - PackedStringArray *self = (PackedStringArray *)p_self; - return (godot_string *)&self->operator[](p_index); -} - -const godot_string GDAPI *godot_packed_string_array_operator_index_const(const godot_packed_string_array *p_self, godot_int p_index) { - const PackedStringArray *self = (const PackedStringArray *)p_self; - return (const godot_string *)&self->operator[](p_index); -} - -// vector2 - -void GDAPI godot_packed_vector2_array_new(godot_packed_vector2_array *p_self) { - memnew_placement(p_self, PackedVector2Array); -} - -void GDAPI godot_packed_vector2_array_new_copy(godot_packed_vector2_array *r_dest, const godot_packed_vector2_array *p_src) { - memnew_placement(r_dest, PackedVector2Array(*(PackedVector2Array *)p_src)); -} - -void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self) { - ((PackedVector2Array *)p_self)->~PackedVector2Array(); -} - -godot_vector2 GDAPI *godot_packed_vector2_array_operator_index(godot_packed_vector2_array *p_self, godot_int p_index) { - PackedVector2Array *self = (PackedVector2Array *)p_self; - return (godot_vector2 *)&self->operator[](p_index); -} - -const godot_vector2 GDAPI *godot_packed_vector2_array_operator_index_const(const godot_packed_vector2_array *p_self, godot_int p_index) { - const PackedVector2Array *self = (const PackedVector2Array *)p_self; - return (const godot_vector2 *)&self->operator[](p_index); -} - -// vector2i - -void GDAPI godot_packed_vector2i_array_new(godot_packed_vector2i_array *p_self) { - memnew_placement(p_self, Vector<Vector2i>); -} - -void GDAPI godot_packed_vector2i_array_new_copy(godot_packed_vector2i_array *r_dest, const godot_packed_vector2i_array *p_src) { - memnew_placement(r_dest, Vector<Vector2i>(*(Vector<Vector2i> *)p_src)); -} - -void GDAPI godot_packed_vector2i_array_destroy(godot_packed_vector2i_array *p_self) { - ((Vector<Vector2i> *)p_self)->~Vector(); -} - -godot_vector2i GDAPI *godot_packed_vector2i_array_operator_index(godot_packed_vector2i_array *p_self, godot_int p_index) { - Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; - return (godot_vector2i *)&self->operator[](p_index); -} - -const godot_vector2i GDAPI *godot_packed_vector2i_array_operator_index_const(const godot_packed_vector2i_array *p_self, godot_int p_index) { - const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self; - return (const godot_vector2i *)&self->operator[](p_index); -} - -// vector3 - -void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *p_self) { - memnew_placement(p_self, PackedVector3Array); -} - -void GDAPI godot_packed_vector3_array_new_copy(godot_packed_vector3_array *r_dest, const godot_packed_vector3_array *p_src) { - memnew_placement(r_dest, PackedVector3Array(*(PackedVector3Array *)p_src)); -} - -void GDAPI godot_packed_vector3_array_destroy(godot_packed_vector3_array *p_self) { - ((PackedVector3Array *)p_self)->~PackedVector3Array(); -} - -godot_vector3 GDAPI *godot_packed_vector3_array_operator_index(godot_packed_vector3_array *p_self, godot_int p_index) { - PackedVector3Array *self = (PackedVector3Array *)p_self; - return (godot_vector3 *)&self->operator[](p_index); -} - -const godot_vector3 GDAPI *godot_packed_vector3_array_operator_index_const(const godot_packed_vector3_array *p_self, godot_int p_index) { - const PackedVector3Array *self = (const PackedVector3Array *)p_self; - return (const godot_vector3 *)&self->operator[](p_index); -} - -// vector3i - -void GDAPI godot_packed_vector3i_array_new(godot_packed_vector3i_array *p_self) { - memnew_placement(p_self, Vector<Vector3i>); -} - -void GDAPI godot_packed_vector3i_array_new_copy(godot_packed_vector3i_array *r_dest, const godot_packed_vector3i_array *p_src) { - memnew_placement(r_dest, Vector<Vector3i>(*(Vector<Vector3i> *)p_src)); -} - -void GDAPI godot_packed_vector3i_array_destroy(godot_packed_vector3i_array *p_self) { - ((Vector<Vector3i> *)p_self)->~Vector(); -} - -godot_vector3i GDAPI *godot_packed_vector3i_array_operator_index(godot_packed_vector3i_array *p_self, godot_int p_index) { - Vector<Vector3i> *self = (Vector<Vector3i> *)p_self; - return (godot_vector3i *)&self->operator[](p_index); -} - -const godot_vector3i GDAPI *godot_packed_vector3i_array_operator_index_const(const godot_packed_vector3i_array *p_self, godot_int p_index) { - const Vector<Vector3i> *self = (const Vector<Vector3i> *)p_self; - return (const godot_vector3i *)&self->operator[](p_index); -} - -// color - -void GDAPI godot_packed_color_array_new(godot_packed_color_array *p_self) { - memnew_placement(p_self, PackedColorArray); -} - -void GDAPI godot_packed_color_array_new_copy(godot_packed_color_array *r_dest, const godot_packed_color_array *p_src) { - memnew_placement(r_dest, PackedColorArray(*(PackedColorArray *)p_src)); -} - -void GDAPI godot_packed_color_array_destroy(godot_packed_color_array *p_self) { - ((PackedColorArray *)p_self)->~PackedColorArray(); -} - -godot_color GDAPI *godot_packed_color_array_operator_index(godot_packed_color_array *p_self, godot_int p_index) { - PackedColorArray *self = (PackedColorArray *)p_self; - return (godot_color *)&self->operator[](p_index); -} - -const godot_color GDAPI *godot_packed_color_array_operator_index_const(const godot_packed_color_array *p_self, godot_int p_index) { - const PackedColorArray *self = (const PackedColorArray *)p_self; - return (const godot_color *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/plane.cpp b/modules/gdnative/gdnative/plane.cpp deleted file mode 100644 index 9ac5cfb3b7..0000000000 --- a/modules/gdnative/gdnative/plane.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/*************************************************************************/ -/* plane.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/plane.h" - -#include "core/math/plane.h" - -static_assert(sizeof(godot_plane) == sizeof(Plane), "Plane size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_plane_new(godot_plane *p_self) { - memnew_placement(p_self, Plane); -} - -void GDAPI godot_plane_new_copy(godot_plane *r_dest, const godot_plane *p_src) { - memnew_placement(r_dest, Plane(*(Plane *)p_src)); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/quaternion.cpp b/modules/gdnative/gdnative/quaternion.cpp deleted file mode 100644 index b91e47e77e..0000000000 --- a/modules/gdnative/gdnative/quaternion.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/*************************************************************************/ -/* quaternion.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/quaternion.h" - -#include "core/math/quaternion.h" - -static_assert(sizeof(godot_quaternion) == sizeof(Quaternion), "Quaternion size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_quaternion_new(godot_quaternion *p_self) { - memnew_placement(p_self, Quaternion); -} - -void GDAPI godot_quaternion_new_copy(godot_quaternion *r_dest, const godot_quaternion *p_src) { - memnew_placement(r_dest, Quaternion(*(Quaternion *)p_src)); -} - -godot_real_t GDAPI *godot_quaternion_operator_index(godot_quaternion *p_self, godot_int p_index) { - Quaternion *self = (Quaternion *)p_self; - return (godot_real_t *)&self->operator[](p_index); -} - -const godot_real_t GDAPI *godot_quaternion_operator_index_const(const godot_quaternion *p_self, godot_int p_index) { - const Quaternion *self = (const Quaternion *)p_self; - return (const godot_real_t *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/rid.cpp b/modules/gdnative/gdnative/rid.cpp deleted file mode 100644 index b40fa7c2c6..0000000000 --- a/modules/gdnative/gdnative/rid.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/*************************************************************************/ -/* rid.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/rid.h" - -#include "core/os/memory.h" -#include "core/templates/rid.h" - -static_assert(sizeof(godot_rid) == sizeof(RID), "RID size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_rid_new(godot_rid *p_self) { - memnew_placement(p_self, RID); -} - -void GDAPI godot_rid_new_copy(godot_rid *r_dest, const godot_rid *p_src) { - memnew_placement(r_dest, RID(*(RID *)p_src)); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/signal.cpp b/modules/gdnative/gdnative/signal.cpp deleted file mode 100644 index 8293aed439..0000000000 --- a/modules/gdnative/gdnative/signal.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/*************************************************************************/ -/* signal.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/signal.h" - -#include "core/variant/callable.h" -#include "core/variant/variant.h" - -static_assert(sizeof(godot_signal) == sizeof(Signal), "Signal size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_signal_new(godot_signal *p_self) { - memnew_placement(p_self, Signal); -} - -void GDAPI godot_signal_new_copy(godot_signal *r_dest, const godot_signal *p_src) { - memnew_placement(r_dest, Signal(*(Signal *)p_src)); -} - -void GDAPI godot_signal_destroy(godot_signal *p_self) { - Signal *self = (Signal *)p_self; - self->~Signal(); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/string.cpp b/modules/gdnative/gdnative/string.cpp deleted file mode 100644 index 7a5d8c6703..0000000000 --- a/modules/gdnative/gdnative/string.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/*************************************************************************/ -/* string.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/string.h" - -#include "core/string/ustring.h" - -static_assert(sizeof(godot_string) == sizeof(String), "String size mismatch"); -static_assert(sizeof(godot_char_type) == sizeof(char32_t), "char32_t size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_string_new(godot_string *r_dest) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); -} - -void GDAPI godot_string_new_copy(godot_string *r_dest, const godot_string *p_src) { - memnew_placement(r_dest, String(*(String *)p_src)); -} - -void GDAPI godot_string_new_with_latin1_chars(godot_string *r_dest, const char *p_contents) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - *dest = String(p_contents); -} - -void GDAPI godot_string_new_with_utf8_chars(godot_string *r_dest, const char *p_contents) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - dest->parse_utf8(p_contents); -} - -void GDAPI godot_string_new_with_utf16_chars(godot_string *r_dest, const char16_t *p_contents) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - dest->parse_utf16(p_contents); -} - -void GDAPI godot_string_new_with_utf32_chars(godot_string *r_dest, const char32_t *p_contents) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - *dest = String((const char32_t *)p_contents); -} - -void GDAPI godot_string_new_with_wide_chars(godot_string *r_dest, const wchar_t *p_contents) { - String *dest = (String *)r_dest; - if (sizeof(wchar_t) == 2) { - // wchar_t is 16 bit, parse. - memnew_placement(dest, String); - dest->parse_utf16((const char16_t *)p_contents); - } else { - // wchar_t is 32 bit, copy. - memnew_placement(dest, String); - *dest = String((const char32_t *)p_contents); - } -} - -void GDAPI godot_string_new_with_latin1_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - *dest = String(p_contents, p_size); -} - -void GDAPI godot_string_new_with_utf8_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - dest->parse_utf8(p_contents, p_size); -} - -void GDAPI godot_string_new_with_utf16_chars_and_len(godot_string *r_dest, const char16_t *p_contents, const int p_size) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - dest->parse_utf16(p_contents, p_size); -} - -void GDAPI godot_string_new_with_utf32_chars_and_len(godot_string *r_dest, const char32_t *p_contents, const int p_size) { - String *dest = (String *)r_dest; - memnew_placement(dest, String); - *dest = String((const char32_t *)p_contents, p_size); -} - -void GDAPI godot_string_new_with_wide_chars_and_len(godot_string *r_dest, const wchar_t *p_contents, const int p_size) { - String *dest = (String *)r_dest; - if (sizeof(wchar_t) == 2) { - // wchar_t is 16 bit, parse. - memnew_placement(dest, String); - dest->parse_utf16((const char16_t *)p_contents, p_size); - } else { - // wchar_t is 32 bit, copy. - memnew_placement(dest, String); - *dest = String((const char32_t *)p_contents, p_size); - } -} - -const char GDAPI *godot_string_to_latin1_chars(const godot_string *p_self) { - String *self = (String *)p_self; - return self->ascii(true).get_data(); -} - -const char GDAPI *godot_string_to_utf8_chars(const godot_string *p_self) { - String *self = (String *)p_self; - return self->utf8().get_data(); -} - -const char16_t GDAPI *godot_string_to_utf16_chars(const godot_string *p_self) { - String *self = (String *)p_self; - return self->utf16().get_data(); -} - -const char32_t GDAPI *godot_string_to_utf32_chars(const godot_string *p_self) { - String *self = (String *)p_self; - return self->get_data(); -} - -const wchar_t GDAPI *godot_string_to_wide_chars(const godot_string *p_self) { - String *self = (String *)p_self; - if (sizeof(wchar_t) == 2) { - return (const wchar_t *)self->utf16().get_data(); - } else { - return (const wchar_t *)self->get_data(); - } -} - -char32_t GDAPI *godot_string_operator_index(godot_string *p_self, godot_int p_index) { - String *self = (String *)p_self; - return self->ptrw(); -} - -const char32_t GDAPI *godot_string_operator_index_const(const godot_string *p_self, godot_int p_index) { - const String *self = (const String *)p_self; - return self->ptr(); -} - -void GDAPI godot_string_destroy(godot_string *p_self) { - String *self = (String *)p_self; - self->~String(); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/transform2d.cpp b/modules/gdnative/gdnative/transform2d.cpp deleted file mode 100644 index 7dc07024e5..0000000000 --- a/modules/gdnative/gdnative/transform2d.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/*************************************************************************/ -/* transform2d.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/transform2d.h" - -#include "core/math/transform_2d.h" -#include "core/os/memory.h" - -static_assert(sizeof(godot_transform2d) == sizeof(Transform2D), "Transform2D size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_transform2d_new(godot_transform2d *p_self) { - memnew_placement(p_self, Transform2D); -} - -void GDAPI godot_transform2d_new_copy(godot_transform2d *r_dest, const godot_transform2d *p_src) { - memnew_placement(r_dest, Transform2D(*(Transform2D *)p_src)); -} - -godot_vector2 GDAPI *godot_transform2d_operator_index(godot_transform2d *p_self, godot_int p_index) { - Transform2D *self = (Transform2D *)p_self; - return (godot_vector2 *)&self->operator[](p_index); -} - -const godot_vector2 GDAPI *godot_transform2d_operator_index_const(const godot_transform2d *p_self, godot_int p_index) { - const Transform2D *self = (const Transform2D *)p_self; - return (const godot_vector2 *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/transform_3d.cpp b/modules/gdnative/gdnative/transform_3d.cpp deleted file mode 100644 index b47e8e69de..0000000000 --- a/modules/gdnative/gdnative/transform_3d.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/*************************************************************************/ -/* transform_3d.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/transform_3d.h" - -#include "core/math/transform_3d.h" - -static_assert(sizeof(godot_transform3d) == sizeof(Transform3D), "Transform3D size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_transform3d_new(godot_transform3d *p_self) { - memnew_placement(p_self, Transform3D); -} - -void GDAPI godot_transform3d_new_copy(godot_transform3d *r_dest, const godot_transform3d *p_src) { - memnew_placement(r_dest, Transform3D(*(Transform3D *)p_src)); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/variant.cpp b/modules/gdnative/gdnative/variant.cpp deleted file mode 100644 index 42fa77a174..0000000000 --- a/modules/gdnative/gdnative/variant.cpp +++ /dev/null @@ -1,1273 +0,0 @@ -/*************************************************************************/ -/* variant.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/variant.h" - -#include "core/object/ref_counted.h" -#include "core/variant/variant.h" - -#ifdef __cplusplus -extern "C" { -#endif - -static_assert(sizeof(godot_variant) == sizeof(Variant), "Variant size mismatch"); - -// Workaround GCC ICE on armv7hl which was affected GCC 6.0 up to 8.0 (GH-16100). -// It was fixed upstream in 8.1, and a fix was backported to 7.4. -// This can be removed once no supported distro ships with versions older than 7.4. -#if defined(__arm__) && defined(__GNUC__) && !defined(__clang__) && \ - (__GNUC__ == 6 || (__GNUC__ == 7 && __GNUC_MINOR__ < 4) || (__GNUC__ == 8 && __GNUC_MINOR__ < 1)) -#pragma GCC push_options -#pragma GCC optimize("-O0") -#endif - -#if defined(__arm__) && defined(__GNUC__) && !defined(__clang__) && \ - (__GNUC__ == 6 || (__GNUC__ == 7 && __GNUC_MINOR__ < 4) || (__GNUC__ == 8 && __GNUC_MINOR__ < 1)) -#pragma GCC pop_options -#endif - -// Memory - -void GDAPI godot_variant_new_copy(godot_variant *p_dest, const godot_variant *p_src) { - Variant *dest = (Variant *)p_dest; - const Variant *src = (const Variant *)p_src; - memnew_placement(dest, Variant(*src)); -} - -void GDAPI godot_variant_new_nil(godot_variant *r_dest) { - Variant *dest = (Variant *)r_dest; - memnew_placement(dest, Variant); -} - -void GDAPI godot_variant_new_bool(godot_variant *r_dest, const godot_bool p_b) { - Variant *dest = (Variant *)r_dest; - memnew_placement(dest, Variant(p_b)); -} - -void GDAPI godot_variant_new_int(godot_variant *r_dest, const godot_int p_i) { - Variant *dest = (Variant *)r_dest; - memnew_placement(dest, Variant(p_i)); -} - -void GDAPI godot_variant_new_float(godot_variant *r_dest, const godot_float p_r) { - Variant *dest = (Variant *)r_dest; - memnew_placement(dest, Variant(p_r)); -} - -void GDAPI godot_variant_new_string(godot_variant *r_dest, const godot_string *p_s) { - Variant *dest = (Variant *)r_dest; - const String *s = (const String *)p_s; - memnew_placement(dest, Variant(*s)); -} - -void GDAPI godot_variant_new_string_name(godot_variant *r_dest, const godot_string_name *p_s) { - Variant *dest = (Variant *)r_dest; - const StringName *s = (const StringName *)p_s; - memnew_placement(dest, Variant(*s)); -} - -void GDAPI godot_variant_new_vector2(godot_variant *r_dest, const godot_vector2 *p_v2) { - Variant *dest = (Variant *)r_dest; - const Vector2 *v2 = (const Vector2 *)p_v2; - memnew_placement(dest, Variant(*v2)); -} - -void GDAPI godot_variant_new_vector2i(godot_variant *r_dest, const godot_vector2i *p_v2) { - Variant *dest = (Variant *)r_dest; - const Vector2i *v2 = (const Vector2i *)p_v2; - memnew_placement(dest, Variant(*v2)); -} - -void GDAPI godot_variant_new_rect2(godot_variant *r_dest, const godot_rect2 *p_rect2) { - Variant *dest = (Variant *)r_dest; - const Rect2 *rect2 = (const Rect2 *)p_rect2; - memnew_placement(dest, Variant(*rect2)); -} - -void GDAPI godot_variant_new_rect2i(godot_variant *r_dest, const godot_rect2i *p_rect2) { - Variant *dest = (Variant *)r_dest; - const Rect2i *rect2 = (const Rect2i *)p_rect2; - memnew_placement(dest, Variant(*rect2)); -} - -void GDAPI godot_variant_new_vector3(godot_variant *r_dest, const godot_vector3 *p_v3) { - Variant *dest = (Variant *)r_dest; - const Vector3 *v3 = (const Vector3 *)p_v3; - memnew_placement(dest, Variant(*v3)); -} - -void GDAPI godot_variant_new_vector3i(godot_variant *r_dest, const godot_vector3i *p_v3) { - Variant *dest = (Variant *)r_dest; - const Vector3i *v3 = (const Vector3i *)p_v3; - memnew_placement(dest, Variant(*v3)); -} - -void GDAPI godot_variant_new_transform2d(godot_variant *r_dest, const godot_transform2d *p_t2d) { - Variant *dest = (Variant *)r_dest; - const Transform2D *t2d = (const Transform2D *)p_t2d; - memnew_placement(dest, Variant(*t2d)); -} - -void GDAPI godot_variant_new_plane(godot_variant *r_dest, const godot_plane *p_plane) { - Variant *dest = (Variant *)r_dest; - const Plane *plane = (const Plane *)p_plane; - memnew_placement(dest, Variant(*plane)); -} - -void GDAPI godot_variant_new_quaternion(godot_variant *r_dest, const godot_quaternion *p_quaternion) { - Variant *dest = (Variant *)r_dest; - const Quaternion *quaternion = (const Quaternion *)p_quaternion; - memnew_placement(dest, Variant(*quaternion)); -} - -void GDAPI godot_variant_new_aabb(godot_variant *r_dest, const godot_aabb *p_aabb) { - Variant *dest = (Variant *)r_dest; - const AABB *aabb = (const AABB *)p_aabb; - memnew_placement(dest, Variant(*aabb)); -} - -void GDAPI godot_variant_new_basis(godot_variant *r_dest, const godot_basis *p_basis) { - Variant *dest = (Variant *)r_dest; - const Basis *basis = (const Basis *)p_basis; - memnew_placement(dest, Variant(*basis)); -} - -void GDAPI godot_variant_new_transform3d(godot_variant *r_dest, const godot_transform3d *p_trans) { - Variant *dest = (Variant *)r_dest; - const Transform3D *trans = (const Transform3D *)p_trans; - memnew_placement(dest, Variant(*trans)); -} - -void GDAPI godot_variant_new_color(godot_variant *r_dest, const godot_color *p_color) { - Variant *dest = (Variant *)r_dest; - const Color *color = (const Color *)p_color; - memnew_placement(dest, Variant(*color)); -} - -void GDAPI godot_variant_new_node_path(godot_variant *r_dest, const godot_node_path *p_np) { - Variant *dest = (Variant *)r_dest; - const NodePath *np = (const NodePath *)p_np; - memnew_placement(dest, Variant(*np)); -} - -void GDAPI godot_variant_new_rid(godot_variant *r_dest, const godot_rid *p_rid) { - Variant *dest = (Variant *)r_dest; - const RID *rid = (const RID *)p_rid; - memnew_placement(dest, Variant(*rid)); -} - -void GDAPI godot_variant_new_callable(godot_variant *r_dest, const godot_callable *p_cb) { - Variant *dest = (Variant *)r_dest; - const Callable *cb = (const Callable *)p_cb; - memnew_placement(dest, Variant(*cb)); -} - -void GDAPI godot_variant_new_signal(godot_variant *r_dest, const godot_signal *p_signal) { - Variant *dest = (Variant *)r_dest; - const Signal *signal = (const Signal *)p_signal; - memnew_placement(dest, Variant(*signal)); -} - -void GDAPI godot_variant_new_object(godot_variant *r_dest, const godot_object *p_obj) { - Variant *dest = (Variant *)r_dest; - const Object *obj = (const Object *)p_obj; - const RefCounted *ref_counted = Object::cast_to<RefCounted>(obj); - REF ref; - if (ref_counted) { - ref = REF(ref_counted); - } - if (!ref.is_null()) { - memnew_placement(dest, Variant(ref)); - } else { -#if defined(DEBUG_METHODS_ENABLED) - if (ref_counted) { - ERR_PRINT("RefCounted object has 0 refcount in godot_variant_new_object - you lost it somewhere."); - } -#endif - memnew_placement(dest, Variant(obj)); - } -} - -void GDAPI godot_variant_new_dictionary(godot_variant *r_dest, const godot_dictionary *p_dict) { - Variant *dest = (Variant *)r_dest; - const Dictionary *dict = (const Dictionary *)p_dict; - memnew_placement(dest, Variant(*dict)); -} - -void GDAPI godot_variant_new_array(godot_variant *r_dest, const godot_array *p_arr) { - Variant *dest = (Variant *)r_dest; - const Array *arr = (const Array *)p_arr; - memnew_placement(dest, Variant(*arr)); -} - -void GDAPI godot_variant_new_packed_byte_array(godot_variant *r_dest, const godot_packed_byte_array *p_pba) { - Variant *dest = (Variant *)r_dest; - const PackedByteArray *pba = (const PackedByteArray *)p_pba; - memnew_placement(dest, Variant(*pba)); -} - -void GDAPI godot_variant_new_packed_int32_array(godot_variant *r_dest, const godot_packed_int32_array *p_pia) { - Variant *dest = (Variant *)r_dest; - const PackedInt32Array *pia = (const PackedInt32Array *)p_pia; - memnew_placement(dest, Variant(*pia)); -} - -void GDAPI godot_variant_new_packed_int64_array(godot_variant *r_dest, const godot_packed_int64_array *p_pia) { - Variant *dest = (Variant *)r_dest; - const PackedInt64Array *pia = (const PackedInt64Array *)p_pia; - memnew_placement(dest, Variant(*pia)); -} - -void GDAPI godot_variant_new_packed_float32_array(godot_variant *r_dest, const godot_packed_float32_array *p_pra) { - Variant *dest = (Variant *)r_dest; - const PackedFloat32Array *pra = (const PackedFloat32Array *)p_pra; - memnew_placement(dest, Variant(*pra)); -} - -void GDAPI godot_variant_new_packed_float64_array(godot_variant *r_dest, const godot_packed_float64_array *p_pra) { - Variant *dest = (Variant *)r_dest; - const PackedFloat64Array *pra = (const PackedFloat64Array *)p_pra; - memnew_placement(dest, Variant(*pra)); -} - -void GDAPI godot_variant_new_packed_string_array(godot_variant *r_dest, const godot_packed_string_array *p_psa) { - Variant *dest = (Variant *)r_dest; - const PackedStringArray *psa = (const PackedStringArray *)p_psa; - memnew_placement(dest, Variant(*psa)); -} - -void GDAPI godot_variant_new_packed_vector2_array(godot_variant *r_dest, const godot_packed_vector2_array *p_pv2a) { - Variant *dest = (Variant *)r_dest; - const PackedVector2Array *pv2a = (const PackedVector2Array *)p_pv2a; - memnew_placement(dest, Variant(*pv2a)); -} - -void GDAPI godot_variant_new_packed_vector3_array(godot_variant *r_dest, const godot_packed_vector3_array *p_pv3a) { - Variant *dest = (Variant *)r_dest; - const PackedVector3Array *pv3a = (const PackedVector3Array *)p_pv3a; - memnew_placement(dest, Variant(*pv3a)); -} - -void GDAPI godot_variant_new_packed_color_array(godot_variant *r_dest, const godot_packed_color_array *p_pca) { - Variant *dest = (Variant *)r_dest; - const PackedColorArray *pca = (const PackedColorArray *)p_pca; - memnew_placement(dest, Variant(*pca)); -} - -godot_bool GDAPI godot_variant_as_bool(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - return self->operator bool(); -} - -godot_int GDAPI godot_variant_as_int(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - return self->operator int64_t(); -} - -godot_float GDAPI godot_variant_as_float(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - return self->operator double(); -} - -godot_string GDAPI godot_variant_as_string(const godot_variant *p_self) { - godot_string raw_dest; - const Variant *self = (const Variant *)p_self; - String *dest = (String *)&raw_dest; - memnew_placement(dest, String(self->operator String())); // operator = is overloaded by String - return raw_dest; -} - -godot_string_name GDAPI godot_variant_as_string_name(const godot_variant *p_self) { - godot_string_name raw_dest; - const Variant *self = (const Variant *)p_self; - StringName *dest = (StringName *)&raw_dest; - memnew_placement(dest, StringName(self->operator StringName())); // operator = is overloaded by StringName - return raw_dest; -} - -godot_vector2 GDAPI godot_variant_as_vector2(const godot_variant *p_self) { - godot_vector2 raw_dest; - const Variant *self = (const Variant *)p_self; - Vector2 *dest = (Vector2 *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_vector2i GDAPI godot_variant_as_vector2i(const godot_variant *p_self) { - godot_vector2i raw_dest; - const Variant *self = (const Variant *)p_self; - Vector2i *dest = (Vector2i *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_rect2 GDAPI godot_variant_as_rect2(const godot_variant *p_self) { - godot_rect2 raw_dest; - const Variant *self = (const Variant *)p_self; - Rect2 *dest = (Rect2 *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_rect2i GDAPI godot_variant_as_rect2i(const godot_variant *p_self) { - godot_rect2i raw_dest; - const Variant *self = (const Variant *)p_self; - Rect2i *dest = (Rect2i *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_vector3 GDAPI godot_variant_as_vector3(const godot_variant *p_self) { - godot_vector3 raw_dest; - const Variant *self = (const Variant *)p_self; - Vector3 *dest = (Vector3 *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_vector3i GDAPI godot_variant_as_vector3i(const godot_variant *p_self) { - godot_vector3i raw_dest; - const Variant *self = (const Variant *)p_self; - Vector3i *dest = (Vector3i *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_transform2d GDAPI godot_variant_as_transform2d(const godot_variant *p_self) { - godot_transform2d raw_dest; - const Variant *self = (const Variant *)p_self; - Transform2D *dest = (Transform2D *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_plane GDAPI godot_variant_as_plane(const godot_variant *p_self) { - godot_plane raw_dest; - const Variant *self = (const Variant *)p_self; - Plane *dest = (Plane *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_quaternion GDAPI godot_variant_as_quaternion(const godot_variant *p_self) { - godot_quaternion raw_dest; - const Variant *self = (const Variant *)p_self; - Quaternion *dest = (Quaternion *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_aabb GDAPI godot_variant_as_aabb(const godot_variant *p_self) { - godot_aabb raw_dest; - const Variant *self = (const Variant *)p_self; - AABB *dest = (AABB *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_basis GDAPI godot_variant_as_basis(const godot_variant *p_self) { - godot_basis raw_dest; - const Variant *self = (const Variant *)p_self; - Basis *dest = (Basis *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_transform3d GDAPI godot_variant_as_transform3d(const godot_variant *p_self) { - godot_transform3d raw_dest; - const Variant *self = (const Variant *)p_self; - Transform3D *dest = (Transform3D *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_color GDAPI godot_variant_as_color(const godot_variant *p_self) { - godot_color raw_dest; - const Variant *self = (const Variant *)p_self; - Color *dest = (Color *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_node_path GDAPI godot_variant_as_node_path(const godot_variant *p_self) { - godot_node_path raw_dest; - const Variant *self = (const Variant *)p_self; - NodePath *dest = (NodePath *)&raw_dest; - memnew_placement(dest, NodePath(self->operator NodePath())); // operator = is overloaded by NodePath - return raw_dest; -} - -godot_rid GDAPI godot_variant_as_rid(const godot_variant *p_self) { - godot_rid raw_dest; - const Variant *self = (const Variant *)p_self; - RID *dest = (RID *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_callable GDAPI godot_variant_as_callable(const godot_variant *p_self) { - godot_callable raw_dest; - const Variant *self = (const Variant *)p_self; - Callable *dest = (Callable *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_signal GDAPI godot_variant_as_signal(const godot_variant *p_self) { - godot_signal raw_dest; - const Variant *self = (const Variant *)p_self; - Signal *dest = (Signal *)&raw_dest; - *dest = *self; - return raw_dest; -} - -godot_object GDAPI *godot_variant_as_object(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - Object *dest; - dest = *self; - return (godot_object *)dest; -} - -godot_dictionary GDAPI godot_variant_as_dictionary(const godot_variant *p_self) { - godot_dictionary raw_dest; - const Variant *self = (const Variant *)p_self; - Dictionary *dest = (Dictionary *)&raw_dest; - memnew_placement(dest, Dictionary(self->operator Dictionary())); // operator = is overloaded by Dictionary - return raw_dest; -} - -godot_array GDAPI godot_variant_as_array(const godot_variant *p_self) { - godot_array raw_dest; - const Variant *self = (const Variant *)p_self; - Array *dest = (Array *)&raw_dest; - memnew_placement(dest, Array(self->operator Array())); // operator = is overloaded by Array - return raw_dest; -} - -godot_packed_byte_array GDAPI godot_variant_as_packed_byte_array(const godot_variant *p_self) { - godot_packed_byte_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedByteArray *dest = (PackedByteArray *)&raw_dest; - memnew_placement(dest, PackedByteArray(self->operator PackedByteArray())); // operator = is overloaded by PackedByteArray - *dest = *self; - return raw_dest; -} - -godot_packed_int32_array GDAPI godot_variant_as_packed_int32_array(const godot_variant *p_self) { - godot_packed_int32_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedInt32Array *dest = (PackedInt32Array *)&raw_dest; - memnew_placement(dest, PackedInt32Array(self->operator PackedInt32Array())); // operator = is overloaded by PackedInt32Array - *dest = *self; - return raw_dest; -} - -godot_packed_int64_array GDAPI godot_variant_as_packed_int64_array(const godot_variant *p_self) { - godot_packed_int64_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedInt64Array *dest = (PackedInt64Array *)&raw_dest; - memnew_placement(dest, PackedInt64Array(self->operator PackedInt64Array())); // operator = is overloaded by PackedInt64Array - *dest = *self; - return raw_dest; -} - -godot_packed_float32_array GDAPI godot_variant_as_packed_float32_array(const godot_variant *p_self) { - godot_packed_float32_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedFloat32Array *dest = (PackedFloat32Array *)&raw_dest; - memnew_placement(dest, PackedFloat32Array(self->operator PackedFloat32Array())); // operator = is overloaded by PackedFloat32Array - *dest = *self; - return raw_dest; -} - -godot_packed_float64_array GDAPI godot_variant_as_packed_float64_array(const godot_variant *p_self) { - godot_packed_float64_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedFloat64Array *dest = (PackedFloat64Array *)&raw_dest; - memnew_placement(dest, PackedFloat64Array(self->operator PackedFloat64Array())); // operator = is overloaded by PackedFloat64Array - *dest = *self; - return raw_dest; -} - -godot_packed_string_array GDAPI godot_variant_as_packed_string_array(const godot_variant *p_self) { - godot_packed_string_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedStringArray *dest = (PackedStringArray *)&raw_dest; - memnew_placement(dest, PackedStringArray(self->operator PackedStringArray())); // operator = is overloaded by PackedStringArray - *dest = *self; - return raw_dest; -} - -godot_packed_vector2_array GDAPI godot_variant_as_packed_vector2_array(const godot_variant *p_self) { - godot_packed_vector2_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedVector2Array *dest = (PackedVector2Array *)&raw_dest; - memnew_placement(dest, PackedVector2Array(self->operator PackedVector2Array())); // operator = is overloaded by PackedVector2Array - *dest = *self; - return raw_dest; -} - -godot_packed_vector3_array GDAPI godot_variant_as_packed_vector3_array(const godot_variant *p_self) { - godot_packed_vector3_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedVector3Array *dest = (PackedVector3Array *)&raw_dest; - memnew_placement(dest, PackedVector3Array(self->operator PackedVector3Array())); // operator = is overloaded by PackedVector3Array - *dest = *self; - return raw_dest; -} - -godot_packed_color_array GDAPI godot_variant_as_packed_color_array(const godot_variant *p_self) { - godot_packed_color_array raw_dest; - const Variant *self = (const Variant *)p_self; - PackedColorArray *dest = (PackedColorArray *)&raw_dest; - memnew_placement(dest, PackedColorArray(self->operator PackedColorArray())); // operator = is overloaded by PackedColorArray - *dest = *self; - return raw_dest; -} - -void GDAPI godot_variant_destroy(godot_variant *p_self) { - Variant *self = (Variant *)p_self; - self->~Variant(); -} - -// Dynamic interaction. - -void GDAPI godot_variant_call(godot_variant *p_self, const godot_string_name *p_method, const godot_variant **p_args, const godot_int p_argcount, godot_variant *r_return, godot_variant_call_error *r_error) { - Variant *self = (Variant *)p_self; - const StringName *method = (const StringName *)p_method; - const Variant **args = (const Variant **)p_args; - Variant ret; - Callable::CallError error; - self->call(*method, args, p_argcount, ret, error); - memnew_placement(r_return, Variant(ret)); - - if (r_error) { - r_error->error = (godot_variant_call_error_error)error.error; - r_error->argument = error.argument; - r_error->expected = (godot_variant_type)error.expected; - } -} - -void GDAPI godot_variant_call_with_cstring(godot_variant *p_self, const char *p_method, const godot_variant **p_args, const godot_int p_argcount, godot_variant *r_return, godot_variant_call_error *r_error) { - Variant *self = (Variant *)p_self; - const StringName method(p_method); - const Variant **args = (const Variant **)p_args; - Variant ret; - Callable::CallError error; - self->call(method, args, p_argcount, ret, error); - memnew_placement(r_return, Variant(ret)); - - if (r_error) { - r_error->error = (godot_variant_call_error_error)error.error; - r_error->argument = error.argument; - r_error->expected = (godot_variant_type)error.expected; - } -} - -void GDAPI godot_variant_call_static(godot_variant_type p_type, const godot_string_name *p_method, const godot_variant **p_args, const godot_int p_argcount, godot_variant *r_return, godot_variant_call_error *r_error) { - Variant::Type type = (Variant::Type)p_type; - const StringName *method = (const StringName *)p_method; - const Variant **args = (const Variant **)p_args; - Variant ret; - Callable::CallError error; - Variant::call_static(type, *method, args, p_argcount, ret, error); - memnew_placement(r_return, Variant(ret)); - - if (r_error) { - r_error->error = (godot_variant_call_error_error)error.error; - r_error->argument = error.argument; - r_error->expected = (godot_variant_type)error.expected; - } -} - -void GDAPI godot_variant_call_static_with_cstring(godot_variant_type p_type, const char *p_method, const godot_variant **p_args, const godot_int p_argcount, godot_variant *r_return, godot_variant_call_error *r_error) { - Variant::Type type = (Variant::Type)p_type; - const StringName method(p_method); - const Variant **args = (const Variant **)p_args; - Variant ret; - Callable::CallError error; - Variant::call_static(type, method, args, p_argcount, ret, error); - memnew_placement(r_return, Variant(ret)); - - if (r_error) { - r_error->error = (godot_variant_call_error_error)error.error; - r_error->argument = error.argument; - r_error->expected = (godot_variant_type)error.expected; - } -} - -void GDAPI godot_variant_evaluate(godot_variant_operator p_op, const godot_variant *p_a, const godot_variant *p_b, godot_variant *r_return, bool *r_valid) { - Variant::Operator op = (Variant::Operator)p_op; - const Variant *a = (const Variant *)p_a; - const Variant *b = (const Variant *)p_b; - Variant *ret = (Variant *)r_return; - Variant::evaluate(op, *a, *b, *ret, *r_valid); -} - -void GDAPI godot_variant_set(godot_variant *p_self, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid) { - Variant *self = (Variant *)p_self; - const Variant *key = (const Variant *)p_key; - const Variant *value = (const Variant *)p_value; - - self->set(*key, *value, r_valid); -} - -void GDAPI godot_variant_set_named(godot_variant *p_self, const godot_string_name *p_key, const godot_variant *p_value, bool *r_valid) { - Variant *self = (Variant *)p_self; - const StringName *key = (const StringName *)p_key; - const Variant *value = (const Variant *)p_value; - - self->set_named(*key, *value, *r_valid); -} - -void GDAPI godot_variant_set_named_with_cstring(godot_variant *p_self, const char *p_key, const godot_variant *p_value, bool *r_valid) { - Variant *self = (Variant *)p_self; - const StringName key(p_key); - const Variant *value = (const Variant *)p_value; - - self->set_named(key, *value, *r_valid); -} - -void GDAPI godot_variant_set_keyed(godot_variant *p_self, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid) { - Variant *self = (Variant *)p_self; - const Variant *key = (const Variant *)p_key; - const Variant *value = (const Variant *)p_value; - - self->set_keyed(*key, *value, *r_valid); -} - -void GDAPI godot_variant_set_indexed(godot_variant *p_self, godot_int p_index, const godot_variant *p_value, bool *r_valid, bool *r_oob) { - Variant *self = (Variant *)p_self; - const Variant *value = (const Variant *)p_value; - - self->set_indexed(p_index, value, *r_valid, *r_oob); -} - -godot_variant GDAPI godot_variant_get(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - const Variant *key = (const Variant *)p_key; - Variant ret; - - ret = self->get(*key, r_valid); - godot_variant result; - memnew_placement(&result, Variant(ret)); - return result; -} - -godot_variant GDAPI godot_variant_get_named(const godot_variant *p_self, const godot_string_name *p_key, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - const StringName *key = (const StringName *)p_key; - Variant ret; - - ret = self->get_named(*key, *r_valid); - godot_variant result; - memnew_placement(&result, Variant(ret)); - return result; -} - -godot_variant GDAPI godot_variant_get_named_with_cstring(const godot_variant *p_self, const char *p_key, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - const StringName *key = (const StringName *)p_key; - Variant ret; - - ret = self->get_named(*key, *r_valid); - godot_variant result; - memnew_placement(&result, Variant(ret)); - return result; -} - -godot_variant GDAPI godot_variant_get_keyed(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - const Variant *key = (const Variant *)p_key; - Variant ret; - - ret = self->get_keyed(*key, *r_valid); - godot_variant result; - memnew_placement(&result, Variant(ret)); - return result; -} - -godot_variant GDAPI godot_variant_get_indexed(const godot_variant *p_self, godot_int p_index, bool *r_valid, bool *r_oob) { - const Variant *self = (const Variant *)p_self; - Variant ret; - - ret = self->get_indexed(p_index, *r_valid, *r_oob); - godot_variant result; - memnew_placement(&result, Variant(ret)); - return result; -} - -/// Iteration. -bool GDAPI godot_variant_iter_init(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - Variant *iter = (Variant *)r_iter; - - return self->iter_init(*iter, *r_valid); -} - -bool GDAPI godot_variant_iter_next(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - Variant *iter = (Variant *)r_iter; - - return self->iter_next(*iter, *r_valid); -} - -godot_variant GDAPI godot_variant_iter_get(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - Variant *iter = (Variant *)r_iter; - - Variant result = self->iter_next(*iter, *r_valid); - godot_variant ret; - memnew_placement(&ret, Variant(result)); - return ret; -} - -/// Variant functions. -godot_bool GDAPI godot_variant_hash_compare(const godot_variant *p_self, const godot_variant *p_other) { - const Variant *self = (const Variant *)p_self; - const Variant *other = (const Variant *)p_other; - return self->hash_compare(*other); -} - -godot_bool GDAPI godot_variant_booleanize(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - return self->booleanize(); -} - -void GDAPI godot_variant_blend(const godot_variant *p_a, const godot_variant *p_b, float p_c, godot_variant *r_dst) { - const Variant *a = (const Variant *)p_a; - const Variant *b = (const Variant *)p_b; - Variant *dst = (Variant *)r_dst; - Variant::blend(*a, *b, p_c, *dst); -} - -void GDAPI godot_variant_interpolate(const godot_variant *p_a, const godot_variant *p_b, float p_c, godot_variant *r_dst) { - const Variant *a = (const Variant *)p_a; - const Variant *b = (const Variant *)p_b; - Variant *dst = (Variant *)r_dst; - Variant::interpolate(*a, *b, p_c, *dst); -} - -godot_variant GDAPI godot_variant_duplicate(const godot_variant *p_self, godot_bool p_deep) { - const Variant *self = (const Variant *)p_self; - Variant result = self->duplicate(p_deep); - godot_variant ret; - memnew_placement(&ret, Variant(result)); - return ret; -} - -godot_string GDAPI godot_variant_stringify(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - String result = *self; - godot_string ret; - memnew_placement(&ret, String(result)); - return ret; -} - -// Discovery API - -/// Operators -godot_validated_operator_evaluator GDAPI godot_variant_get_validated_operator_evaluator(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b) { - return (godot_validated_operator_evaluator)Variant::get_validated_operator_evaluator((Variant::Operator)p_operator, (Variant::Type)p_type_a, (Variant::Type)p_type_b); -} - -godot_ptr_operator_evaluator GDAPI godot_variant_get_ptr_operator_evaluator(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b) { - return (godot_ptr_operator_evaluator)Variant::get_ptr_operator_evaluator((Variant::Operator)p_operator, (Variant::Type)p_type_a, (Variant::Type)p_type_b); -} - -godot_variant_type GDAPI godot_variant_get_operator_return_type(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b) { - return (godot_variant_type)Variant::get_operator_return_type((Variant::Operator)p_operator, (Variant::Type)p_type_a, (Variant::Type)p_type_b); -} - -godot_string GDAPI godot_variant_get_operator_name(godot_variant_operator p_operator) { - String op_name = Variant::get_operator_name((Variant::Operator)p_operator); - godot_string ret; - memnew_placement(&ret, String(op_name)); - return ret; -} - -/// Built-in Methods - -bool GDAPI godot_variant_has_builtin_method(godot_variant_type p_type, const godot_string_name *p_method) { - return Variant::has_builtin_method((Variant::Type)p_type, *((const StringName *)p_method)); -} - -bool GDAPI godot_variant_has_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method) { - return Variant::has_builtin_method((Variant::Type)p_type, StringName(p_method)); -} - -godot_validated_builtin_method GDAPI godot_variant_get_validated_builtin_method(godot_variant_type p_type, const godot_string_name *p_method) { - return (godot_validated_builtin_method)Variant::get_validated_builtin_method((Variant::Type)p_type, *((const StringName *)p_method)); -} - -godot_validated_builtin_method GDAPI godot_variant_get_validated_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method) { - return (godot_validated_builtin_method)Variant::get_validated_builtin_method((Variant::Type)p_type, StringName(p_method)); -} - -godot_ptr_builtin_method GDAPI godot_variant_get_ptr_builtin_method(godot_variant_type p_type, const godot_string_name *p_method) { - return (godot_ptr_builtin_method)Variant::get_ptr_builtin_method((Variant::Type)p_type, *((const StringName *)p_method)); -} - -godot_ptr_builtin_method GDAPI godot_variant_get_ptr_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method) { - return (godot_ptr_builtin_method)Variant::get_ptr_builtin_method((Variant::Type)p_type, StringName(p_method)); -} - -int GDAPI godot_variant_get_builtin_method_argument_count(godot_variant_type p_type, const godot_string_name *p_method) { - return Variant::get_builtin_method_argument_count((Variant::Type)p_type, *((const StringName *)p_method)); -} - -int GDAPI godot_variant_get_builtin_method_argument_count_with_cstring(godot_variant_type p_type, const char *p_method) { - return Variant::get_builtin_method_argument_count((Variant::Type)p_type, StringName(p_method)); -} - -godot_variant_type GDAPI godot_variant_get_builtin_method_argument_type(godot_variant_type p_type, const godot_string_name *p_method, int p_argument) { - return (godot_variant_type)Variant::get_builtin_method_argument_type((Variant::Type)p_type, *((const StringName *)p_method), p_argument); -} - -godot_variant_type GDAPI godot_variant_get_builtin_method_argument_type_with_cstring(godot_variant_type p_type, const char *p_method, int p_argument) { - return (godot_variant_type)Variant::get_builtin_method_argument_type((Variant::Type)p_type, StringName(p_method), p_argument); -} - -godot_string GDAPI godot_variant_get_builtin_method_argument_name(godot_variant_type p_type, const godot_string_name *p_method, int p_argument) { - String name = Variant::get_builtin_method_argument_name((Variant::Type)p_type, *((const StringName *)p_method), p_argument); - return *(godot_string *)&name; -} - -godot_string GDAPI godot_variant_get_builtin_method_argument_name_with_cstring(godot_variant_type p_type, const char *p_method, int p_argument) { - String name = Variant::get_builtin_method_argument_name((Variant::Type)p_type, StringName(p_method), p_argument); - return *(godot_string *)&name; -} - -bool GDAPI godot_variant_has_builtin_method_return_value(godot_variant_type p_type, const godot_string_name *p_method) { - return Variant::has_builtin_method_return_value((Variant::Type)p_type, *((const StringName *)p_method)); -} - -bool GDAPI godot_variant_has_builtin_method_return_value_with_cstring(godot_variant_type p_type, const char *p_method) { - return Variant::has_builtin_method_return_value((Variant::Type)p_type, StringName(p_method)); -} - -godot_variant_type GDAPI godot_variant_get_builtin_method_return_type(godot_variant_type p_type, const godot_string_name *p_method) { - return (godot_variant_type)Variant::get_builtin_method_return_type((Variant::Type)p_type, *((const StringName *)p_method)); -} - -godot_variant_type GDAPI godot_variant_get_builtin_method_return_type_with_cstring(godot_variant_type p_type, const char *p_method) { - return (godot_variant_type)Variant::get_builtin_method_return_type((Variant::Type)p_type, StringName(p_method)); -} - -bool GDAPI godot_variant_is_builtin_method_const(godot_variant_type p_type, const godot_string_name *p_method) { - return Variant::is_builtin_method_const((Variant::Type)p_type, *((const StringName *)p_method)); -} - -bool GDAPI godot_variant_is_builtin_method_const_with_cstring(godot_variant_type p_type, const char *p_method) { - return Variant::is_builtin_method_const((Variant::Type)p_type, StringName(p_method)); -} - -bool GDAPI godot_variant_is_builtin_method_static(godot_variant_type p_type, const godot_string_name *p_method) { - return Variant::is_builtin_method_static((Variant::Type)p_type, *((const StringName *)p_method)); -} - -bool GDAPI godot_variant_is_builtin_method_static_with_cstring(godot_variant_type p_type, const char *p_method) { - return Variant::is_builtin_method_static((Variant::Type)p_type, StringName(p_method)); -} - -bool GDAPI godot_variant_is_builtin_method_vararg(godot_variant_type p_type, const godot_string_name *p_method) { - return Variant::is_builtin_method_vararg((Variant::Type)p_type, *((const StringName *)p_method)); -} - -bool GDAPI godot_variant_is_builtin_method_vararg_with_cstring(godot_variant_type p_type, const char *p_method) { - return Variant::is_builtin_method_vararg((Variant::Type)p_type, StringName(p_method)); -} - -int GDAPI godot_variant_get_builtin_method_count(godot_variant_type p_type) { - return Variant::get_builtin_method_count((Variant::Type)p_type); -} - -void GDAPI godot_variant_get_builtin_method_list(godot_variant_type p_type, godot_string_name *r_list) { - List<StringName> list; - Variant::get_builtin_method_list((Variant::Type)p_type, &list); - int i = 0; - for (const StringName &E : list) { - memnew_placement(&r_list[i], StringName(E)); - } -} - -/// Constructors - -int GDAPI godot_variant_get_constructor_count(godot_variant_type p_type) { - return Variant::get_constructor_count((Variant::Type)p_type); -} - -godot_validated_constructor GDAPI godot_variant_get_validated_constructor(godot_variant_type p_type, int p_constructor) { - return (godot_validated_constructor)Variant::get_validated_constructor((Variant::Type)p_type, p_constructor); -} - -godot_ptr_constructor GDAPI godot_variant_get_ptr_constructor(godot_variant_type p_type, int p_constructor) { - return (godot_ptr_constructor)Variant::get_ptr_constructor((Variant::Type)p_type, p_constructor); -} - -int GDAPI godot_variant_get_constructor_argument_count(godot_variant_type p_type, int p_constructor) { - return Variant::get_constructor_argument_count((Variant::Type)p_type, p_constructor); -} - -godot_variant_type GDAPI godot_variant_get_constructor_argument_type(godot_variant_type p_type, int p_constructor, int p_argument) { - return (godot_variant_type)Variant::get_constructor_argument_type((Variant::Type)p_type, p_constructor, p_argument); -} - -godot_string GDAPI godot_variant_get_constructor_argument_name(godot_variant_type p_type, int p_constructor, int p_argument) { - String name = Variant::get_constructor_argument_name((Variant::Type)p_type, p_constructor, p_argument); - godot_string ret; - memnew_placement(&ret, String(name)); - return ret; -} - -void GDAPI godot_variant_construct(godot_variant_type p_type, godot_variant *p_base, const godot_variant **p_args, int p_argcount, godot_variant_call_error *r_error) { - Variant::construct((Variant::Type)p_type, *((Variant *)p_base), (const Variant **)p_args, p_argcount, *((Callable::CallError *)r_error)); -} - -/// Properties. -godot_variant_type GDAPI godot_variant_get_member_type(godot_variant_type p_type, const godot_string_name *p_member) { - return (godot_variant_type)Variant::get_member_type((Variant::Type)p_type, *((const StringName *)p_member)); -} - -godot_variant_type GDAPI godot_variant_get_member_type_with_cstring(godot_variant_type p_type, const char *p_member) { - return (godot_variant_type)Variant::get_member_type((Variant::Type)p_type, StringName(p_member)); -} - -int GDAPI godot_variant_get_member_count(godot_variant_type p_type) { - return Variant::get_member_count((Variant::Type)p_type); -} - -void GDAPI godot_variant_get_member_list(godot_variant_type p_type, godot_string_name *r_list) { - List<StringName> members; - Variant::get_member_list((Variant::Type)p_type, &members); - int i = 0; - for (const StringName &E : members) { - memnew_placement(&r_list[i++], StringName(E)); - } -} - -godot_validated_setter GDAPI godot_variant_get_validated_setter(godot_variant_type p_type, const godot_string_name *p_member) { - return (godot_validated_setter)Variant::get_member_validated_setter((Variant::Type)p_type, *((const StringName *)p_member)); -} - -godot_validated_setter GDAPI godot_variant_get_validated_setter_with_cstring(godot_variant_type p_type, const char *p_member) { - return (godot_validated_setter)Variant::get_member_validated_setter((Variant::Type)p_type, StringName(p_member)); -} - -godot_validated_getter GDAPI godot_variant_get_validated_getter(godot_variant_type p_type, const godot_string_name *p_member) { - return (godot_validated_getter)Variant::get_member_validated_getter((Variant::Type)p_type, *((const StringName *)p_member)); -} - -godot_validated_getter GDAPI godot_variant_get_validated_getter_with_cstring(godot_variant_type p_type, const char *p_member) { - return (godot_validated_getter)Variant::get_member_validated_getter((Variant::Type)p_type, StringName(p_member)); -} - -godot_ptr_setter GDAPI godot_variant_get_ptr_setter(godot_variant_type p_type, const godot_string_name *p_member) { - return (godot_ptr_setter)Variant::get_member_ptr_setter((Variant::Type)p_type, *((const StringName *)p_member)); -} - -godot_ptr_setter GDAPI godot_variant_get_ptr_setter_with_cstring(godot_variant_type p_type, const char *p_member) { - return (godot_ptr_setter)Variant::get_member_ptr_setter((Variant::Type)p_type, StringName(p_member)); -} - -godot_ptr_getter GDAPI godot_variant_get_ptr_getter(godot_variant_type p_type, const godot_string_name *p_member) { - return (godot_ptr_getter)Variant::get_member_ptr_getter((Variant::Type)p_type, *((const StringName *)p_member)); -} - -godot_ptr_getter GDAPI godot_variant_get_ptr_getter_with_cstring(godot_variant_type p_type, const char *p_member) { - return (godot_ptr_getter)Variant::get_member_ptr_getter((Variant::Type)p_type, StringName(p_member)); -} - -/// Indexing. -bool GDAPI godot_variant_has_indexing(godot_variant_type p_type) { - return Variant::has_indexing((Variant::Type)p_type); -} - -godot_variant_type GDAPI godot_variant_get_indexed_element_type(godot_variant_type p_type) { - return (godot_variant_type)Variant::get_indexed_element_type((Variant::Type)p_type); -} - -godot_validated_indexed_setter GDAPI godot_variant_get_validated_indexed_setter(godot_variant_type p_type) { - return (godot_validated_indexed_setter)Variant::get_member_validated_indexed_setter((Variant::Type)p_type); -} - -godot_validated_indexed_getter GDAPI godot_variant_get_validated_indexed_getter(godot_variant_type p_type) { - return (godot_validated_indexed_getter)Variant::get_member_validated_indexed_getter((Variant::Type)p_type); -} - -godot_ptr_indexed_setter GDAPI godot_variant_get_ptr_indexed_setter(godot_variant_type p_type) { - return (godot_ptr_indexed_setter)Variant::get_member_ptr_indexed_setter((Variant::Type)p_type); -} - -godot_ptr_indexed_getter GDAPI godot_variant_get_ptr_indexed_getter(godot_variant_type p_type) { - return (godot_ptr_indexed_getter)Variant::get_member_ptr_indexed_getter((Variant::Type)p_type); -} - -uint64_t GDAPI godot_variant_get_indexed_size(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - return self->get_indexed_size(); -} - -/// Keying. -bool GDAPI godot_variant_is_keyed(godot_variant_type p_type) { - return Variant::is_keyed((Variant::Type)p_type); -} - -godot_validated_keyed_setter GDAPI godot_variant_get_validated_keyed_setter(godot_variant_type p_type) { - return (godot_validated_keyed_setter)Variant::get_member_validated_keyed_setter((Variant::Type)p_type); -} - -godot_validated_keyed_getter GDAPI godot_variant_get_validated_keyed_getter(godot_variant_type p_type) { - return (godot_validated_keyed_getter)Variant::get_member_validated_keyed_getter((Variant::Type)p_type); -} - -godot_validated_keyed_checker GDAPI godot_variant_get_validated_keyed_checker(godot_variant_type p_type) { - return (godot_validated_keyed_checker)Variant::get_member_validated_keyed_checker((Variant::Type)p_type); -} - -godot_ptr_keyed_setter GDAPI godot_variant_get_ptr_keyed_setter(godot_variant_type p_type) { - return (godot_ptr_keyed_setter)Variant::get_member_ptr_keyed_setter((Variant::Type)p_type); -} - -godot_ptr_keyed_getter GDAPI godot_variant_get_ptr_keyed_getter(godot_variant_type p_type) { - return (godot_ptr_keyed_getter)Variant::get_member_ptr_keyed_getter((Variant::Type)p_type); -} - -godot_ptr_keyed_checker GDAPI godot_variant_get_ptr_keyed_checker(godot_variant_type p_type) { - return (godot_ptr_keyed_checker)Variant::get_member_ptr_keyed_checker((Variant::Type)p_type); -} - -/// Constants. -int GDAPI godot_variant_get_constants_count(godot_variant_type p_type) { - return Variant::get_constants_count_for_type((Variant::Type)p_type); -} - -void GDAPI godot_variant_get_constants_list(godot_variant_type p_type, godot_string_name *r_list) { - List<StringName> constants; - int i = 0; - Variant::get_constants_for_type((Variant::Type)p_type, &constants); - for (const StringName &E : constants) { - memnew_placement(&r_list[i++], StringName(E)); - } -} - -bool GDAPI godot_variant_has_constant(godot_variant_type p_type, const godot_string_name *p_constant) { - return Variant::has_constant((Variant::Type)p_type, *((const StringName *)p_constant)); -} - -bool GDAPI godot_variant_has_constant_with_cstring(godot_variant_type p_type, const char *p_constant) { - return Variant::has_constant((Variant::Type)p_type, StringName(p_constant)); -} - -godot_variant GDAPI godot_variant_get_constant_value(godot_variant_type p_type, const godot_string_name *p_constant) { - Variant constant = Variant::get_constant_value((Variant::Type)p_type, *((const StringName *)p_constant)); - godot_variant ret; - memnew_placement(&ret, Variant(constant)); - return ret; -} - -godot_variant GDAPI godot_variant_get_constant_value_with_cstring(godot_variant_type p_type, const char *p_constant) { - Variant constant = Variant::get_constant_value((Variant::Type)p_type, StringName(p_constant)); - godot_variant ret; - memnew_placement(&ret, Variant(constant)); - return ret; -} - -/// Utilities. -bool GDAPI godot_variant_has_utility_function(const godot_string_name *p_function) { - return Variant::has_utility_function(*((const StringName *)p_function)); -} - -bool GDAPI godot_variant_has_utility_function_with_cstring(const char *p_function) { - return Variant::has_utility_function(StringName(p_function)); -} - -void GDAPI godot_variant_call_utility_function(const godot_string_name *p_function, godot_variant *r_ret, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error) { - const StringName *function = (const StringName *)p_function; - Variant *ret = (Variant *)r_ret; - const Variant **args = (const Variant **)p_args; - Callable::CallError error; - - Variant::call_utility_function(*function, ret, args, p_argument_count, error); - - if (r_error) { - r_error->error = (godot_variant_call_error_error)error.error; - r_error->argument = error.argument; - r_error->expected = (godot_variant_type)error.expected; - } -} - -void GDAPI godot_variant_call_utility_function_with_cstring(const char *p_function, godot_variant *r_ret, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error) { - Variant *ret = (Variant *)r_ret; - const Variant **args = (const Variant **)p_args; - Callable::CallError error; - - Variant::call_utility_function(StringName(p_function), ret, args, p_argument_count, error); - - if (r_error) { - r_error->error = (godot_variant_call_error_error)error.error; - r_error->argument = error.argument; - r_error->expected = (godot_variant_type)error.expected; - } -} - -godot_ptr_utility_function GDAPI godot_variant_get_ptr_utility_function(const godot_string_name *p_function) { - return (godot_ptr_utility_function)Variant::get_ptr_utility_function(*((const StringName *)p_function)); -} - -godot_ptr_utility_function GDAPI godot_variant_get_ptr_utility_function_with_cstring(const char *p_function) { - return (godot_ptr_utility_function)Variant::get_ptr_utility_function(StringName(p_function)); -} - -godot_validated_utility_function GDAPI godot_variant_get_validated_utility_function(const godot_string_name *p_function) { - return (godot_validated_utility_function)Variant::get_validated_utility_function(*((const StringName *)p_function)); -} - -godot_validated_utility_function GDAPI godot_variant_get_validated_utility_function_with_cstring(const char *p_function) { - return (godot_validated_utility_function)Variant::get_validated_utility_function(StringName(p_function)); -} - -godot_variant_utility_function_type GDAPI godot_variant_get_utility_function_type(const godot_string_name *p_function) { - return (godot_variant_utility_function_type)Variant::get_utility_function_type(*((const StringName *)p_function)); -} - -godot_variant_utility_function_type GDAPI godot_variant_get_utility_function_type_with_cstring(const char *p_function) { - return (godot_variant_utility_function_type)Variant::get_utility_function_type(StringName(p_function)); -} - -int GDAPI godot_variant_get_utility_function_argument_count(const godot_string_name *p_function) { - return Variant::get_utility_function_argument_count(*((const StringName *)p_function)); -} - -int GDAPI godot_variant_get_utility_function_argument_count_with_cstring(const char *p_function) { - return Variant::get_utility_function_argument_count(StringName(p_function)); -} - -godot_variant_type GDAPI godot_variant_get_utility_function_argument_type(const godot_string_name *p_function, int p_argument) { - return (godot_variant_type)Variant::get_utility_function_argument_type(*((const StringName *)p_function), p_argument); -} - -godot_variant_type GDAPI godot_variant_get_utility_function_argument_type_with_cstring(const char *p_function, int p_argument) { - return (godot_variant_type)Variant::get_utility_function_argument_type(StringName(p_function), p_argument); -} - -godot_string GDAPI godot_variant_get_utility_function_argument_name(const godot_string_name *p_function, int p_argument) { - String argument_name = Variant::get_utility_function_argument_name(*((const StringName *)p_function), p_argument); - godot_string ret; - memnew_placement(&ret, String(argument_name)); - return ret; -} - -godot_string GDAPI godot_variant_get_utility_function_argument_name_with_cstring(const char *p_function, int p_argument) { - String argument_name = Variant::get_utility_function_argument_name(StringName(p_function), p_argument); - godot_string ret; - memnew_placement(&ret, String(argument_name)); - return ret; -} - -bool GDAPI godot_variant_has_utility_function_return_value(const godot_string_name *p_function) { - return Variant::has_utility_function_return_value(*((const StringName *)p_function)); -} - -bool GDAPI godot_variant_has_utility_function_return_value_with_cstring(const char *p_function) { - return Variant::has_utility_function_return_value(StringName(p_function)); -} - -godot_variant_type GDAPI godot_variant_get_utility_function_return_type(const godot_string_name *p_function) { - return (godot_variant_type)Variant::get_utility_function_return_type(*((const StringName *)p_function)); -} - -godot_variant_type GDAPI godot_variant_get_utility_function_return_type_with_cstring(const char *p_function) { - return (godot_variant_type)Variant::get_utility_function_return_type(StringName(p_function)); -} - -bool GDAPI godot_variant_is_utility_function_vararg(const godot_string_name *p_function) { - return Variant::is_utility_function_vararg(*((const StringName *)p_function)); -} - -bool GDAPI godot_variant_is_utility_function_vararg_with_cstring(const char *p_function) { - return Variant::is_utility_function_vararg(StringName(p_function)); -} - -int GDAPI godot_variant_get_utility_function_count() { - return Variant::get_utility_function_count(); -} - -void GDAPI godot_variant_get_utility_function_list(godot_string_name *r_functions) { - List<StringName> functions; - godot_string_name *func = r_functions; - Variant::get_utility_function_list(&functions); - - for (const StringName &E : functions) { - memnew_placement(func++, StringName(E)); - } -} - -// Introspection. - -godot_variant_type GDAPI godot_variant_get_type(const godot_variant *p_self) { - const Variant *self = (const Variant *)p_self; - return (godot_variant_type)self->get_type(); -} - -bool GDAPI godot_variant_has_method(const godot_variant *p_self, const godot_string_name *p_method) { - const Variant *self = (const Variant *)p_self; - const StringName *method = (const StringName *)p_method; - return self->has_method(*method); -} - -bool GDAPI godot_variant_has_member(godot_variant_type p_type, const godot_string_name *p_member) { - return Variant::has_member((Variant::Type)p_type, *((const StringName *)p_member)); -} - -bool GDAPI godot_variant_has_key(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid) { - const Variant *self = (const Variant *)p_self; - const Variant *key = (const Variant *)p_key; - return self->has_key(*key, *r_valid); -} - -godot_string GDAPI godot_variant_get_type_name(godot_variant_type p_type) { - String name = Variant::get_type_name((Variant::Type)p_type); - godot_string ret; - memnew_placement(&ret, String(name)); - return ret; -} - -bool GDAPI godot_variant_can_convert(godot_variant_type p_from, godot_variant_type p_to) { - return Variant::can_convert((Variant::Type)p_from, (Variant::Type)p_to); -} - -bool GDAPI godot_variant_can_convert_strict(godot_variant_type p_from, godot_variant_type p_to) { - return Variant::can_convert_strict((Variant::Type)p_from, (Variant::Type)p_to); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/vector2.cpp b/modules/gdnative/gdnative/vector2.cpp deleted file mode 100644 index a8d4281d25..0000000000 --- a/modules/gdnative/gdnative/vector2.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/*************************************************************************/ -/* vector2.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/vector2.h" - -#include "core/math/vector2.h" -#include "core/math/vector2i.h" -#include "core/os/memory.h" - -static_assert(sizeof(godot_vector2) == sizeof(Vector2), "Vector2 size mismatch"); -static_assert(sizeof(godot_vector2i) == sizeof(Vector2i), "Vector2i size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_vector2_new(godot_vector2 *p_self) { - memnew_placement(p_self, Vector2); -} - -void GDAPI godot_vector2_new_copy(godot_vector2 *r_dest, const godot_vector2 *p_src) { - memnew_placement(r_dest, Vector2(*(Vector2 *)p_src)); -} - -void GDAPI godot_vector2i_new(godot_vector2i *p_self) { - memnew_placement(p_self, Vector2i); -} - -void GDAPI godot_vector2i_new_copy(godot_vector2i *r_dest, const godot_vector2i *p_src) { - memnew_placement(r_dest, Vector2i(*(Vector2i *)p_src)); -} - -godot_real_t GDAPI *godot_vector2_operator_index(godot_vector2 *p_self, godot_int p_index) { - Vector2 *self = (Vector2 *)p_self; - return (godot_real_t *)&self->operator[](p_index); -} - -const godot_real_t GDAPI *godot_vector2_operator_index_const(const godot_vector2 *p_self, godot_int p_index) { - const Vector2 *self = (const Vector2 *)p_self; - return (const godot_real_t *)&self->operator[](p_index); -} - -int32_t GDAPI *godot_vector2i_operator_index(godot_vector2i *p_self, godot_int p_index) { - Vector2i *self = (Vector2i *)p_self; - return (int32_t *)&self->operator[](p_index); -} - -const int32_t GDAPI *godot_vector2i_operator_index_const(const godot_vector2i *p_self, godot_int p_index) { - const Vector2i *self = (const Vector2i *)p_self; - return (const int32_t *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative/vector3.cpp b/modules/gdnative/gdnative/vector3.cpp deleted file mode 100644 index 26e94d7e5c..0000000000 --- a/modules/gdnative/gdnative/vector3.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/*************************************************************************/ -/* vector3.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/vector3.h" - -#include "core/math/vector3.h" - -static_assert(sizeof(godot_vector3) == sizeof(Vector3), "Vector3 size mismatch"); -static_assert(sizeof(godot_vector3i) == sizeof(Vector3i), "Vector3i size mismatch"); - -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_vector3_new(godot_vector3 *p_self) { - memnew_placement(p_self, Vector3); -} - -void GDAPI godot_vector3_new_copy(godot_vector3 *r_dest, const godot_vector3 *p_src) { - memnew_placement(r_dest, Vector3(*(Vector3 *)p_src)); -} - -void GDAPI godot_vector3i_new(godot_vector3i *p_self) { - memnew_placement(p_self, Vector3i); -} - -void GDAPI godot_vector3i_new_copy(godot_vector3i *r_dest, const godot_vector3i *p_src) { - memnew_placement(r_dest, Vector3i(*(Vector3i *)p_src)); -} - -godot_real_t GDAPI *godot_vector3_operator_index(godot_vector3 *p_self, godot_int p_index) { - Vector3 *self = (Vector3 *)p_self; - return (godot_real_t *)&self->operator[](p_index); -} - -const godot_real_t GDAPI *godot_vector3_operator_index_const(const godot_vector3 *p_self, godot_int p_index) { - const Vector3 *self = (const Vector3 *)p_self; - return (const godot_real_t *)&self->operator[](p_index); -} - -int32_t GDAPI *godot_vector3i_operator_index(godot_vector3i *p_self, godot_int p_index) { - Vector3i *self = (Vector3i *)p_self; - return (int32_t *)&self->operator[](p_index); -} - -const int32_t GDAPI *godot_vector3i_operator_index_const(const godot_vector3i *p_self, godot_int p_index) { - const Vector3i *self = (const Vector3i *)p_self; - return (const int32_t *)&self->operator[](p_index); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json deleted file mode 100644 index cf1c7dc01f..0000000000 --- a/modules/gdnative/gdnative_api.json +++ /dev/null @@ -1,5108 +0,0 @@ -{ - "core": { - "type": "CORE", - "version": { - "major": 4, - "minor": 0 - }, - "next": null, - "api": [ - { - "name": "godot_object_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_object *", - "p_o" - ] - ] - }, - { - "name": "godot_global_get_singleton", - "return_type": "godot_object *", - "arguments": [ - [ - "char *", - "p_name" - ] - ] - }, - { - "name": "godot_method_bind_get_method", - "return_type": "godot_method_bind *", - "arguments": [ - [ - "const char *", - "p_classname" - ], - [ - "const char *", - "p_methodname" - ] - ] - }, - { - "name": "godot_method_bind_ptrcall", - "return_type": "void", - "arguments": [ - [ - "godot_method_bind *", - "p_method_bind" - ], - [ - "godot_object *", - "p_instance" - ], - [ - "const void **", - "p_args" - ], - [ - "void *", - "p_ret" - ] - ] - }, - { - "name": "godot_method_bind_call", - "return_type": "godot_variant", - "arguments": [ - [ - "godot_method_bind *", - "p_method_bind" - ], - [ - "godot_object *", - "p_instance" - ], - [ - "const godot_variant **", - "p_args" - ], - [ - "const int", - "p_arg_count" - ], - [ - "godot_variant_call_error *", - "p_call_error" - ] - ] - }, - { - "name": "godot_get_class_constructor", - "return_type": "godot_class_constructor", - "arguments": [ - [ - "const char *", - "p_classname" - ] - ] - }, - { - "name": "godot_get_global_constants", - "return_type": "godot_dictionary", - "arguments": [] - }, - { - "name": "godot_register_native_call_type", - "return_type": "void", - "arguments": [ - [ - "const char *", - "call_type" - ], - [ - "native_call_cb", - "p_callback" - ] - ] - }, - { - "name": "godot_alloc", - "return_type": "void *", - "arguments": [ - [ - "int", - "p_bytes" - ] - ] - }, - { - "name": "godot_realloc", - "return_type": "void *", - "arguments": [ - [ - "void *", - "p_ptr" - ], - [ - "int", - "p_bytes" - ] - ] - }, - { - "name": "godot_free", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_ptr" - ] - ] - }, - { - "name": "godot_print_error", - "return_type": "void", - "arguments": [ - [ - "const char *", - "p_description" - ], - [ - "const char *", - "p_function" - ], - [ - "const char *", - "p_file" - ], - [ - "int", - "p_line" - ] - ] - }, - { - "name": "godot_print_warning", - "return_type": "void", - "arguments": [ - [ - "const char *", - "p_description" - ], - [ - "const char *", - "p_function" - ], - [ - "const char *", - "p_file" - ], - [ - "int", - "p_line" - ] - ] - }, - { - "name": "godot_print_script_error", - "return_type": "void", - "arguments": [ - [ - "const char *", - "p_description" - ], - [ - "const char *", - "p_function" - ], - [ - "const char *", - "p_file" - ], - [ - "int", - "p_line" - ] - ] - }, - { - "name": "godot_get_class_tag", - "return_type": "void *", - "arguments": [ - [ - "const godot_string_name *", - "p_class" - ] - ] - }, - { - "name": "godot_object_cast_to", - "return_type": "godot_object *", - "arguments": [ - [ - "const godot_object *", - "p_object" - ], - [ - "void *", - "p_class_tag" - ] - ] - }, - { - "name": "godot_instance_from_id", - "return_type": "godot_object *", - "arguments": [ - [ - "uint64_t", - "p_instance_id" - ] - ] - }, - { - "name": "godot_object_get_instance_id", - "return_type": "uint64_t", - "arguments": [ - [ - "const godot_object *", - "p_object" - ] - ] - }, - { - "name": "godot_variant_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_variant *", - "p_src" - ] - ] - }, - { - "name": "godot_variant_new_nil", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ] - ] - }, - { - "name": "godot_variant_new_bool", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_bool", - "p_b" - ] - ] - }, - { - "name": "godot_variant_new_int", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const int64_t", - "p_i" - ] - ] - }, - { - "name": "godot_variant_new_float", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const double", - "p_f" - ] - ] - }, - { - "name": "godot_variant_new_string", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_string *", - "p_s" - ] - ] - }, - { - "name": "godot_variant_new_string_name", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_string_name *", - "p_s" - ] - ] - }, - { - "name": "godot_variant_new_vector2", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_vector2 *", - "p_v2" - ] - ] - }, - { - "name": "godot_variant_new_vector2i", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_vector2i *", - "p_v2" - ] - ] - }, - { - "name": "godot_variant_new_rect2", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_rect2 *", - "p_rect2" - ] - ] - }, - { - "name": "godot_variant_new_rect2i", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_rect2i *", - "p_rect2" - ] - ] - }, - { - "name": "godot_variant_new_vector3", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_vector3 *", - "p_v3" - ] - ] - }, - { - "name": "godot_variant_new_vector3i", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_vector3i *", - "p_v3" - ] - ] - }, - { - "name": "godot_variant_new_transform2d", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_transform2d *", - "p_t2d" - ] - ] - }, - { - "name": "godot_variant_new_plane", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_plane *", - "p_plane" - ] - ] - }, - { - "name": "godot_variant_new_quaternion", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_quaternion *", - "p_quaternion" - ] - ] - }, - { - "name": "godot_variant_new_aabb", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_aabb *", - "p_aabb" - ] - ] - }, - { - "name": "godot_variant_new_basis", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_basis *", - "p_basis" - ] - ] - }, - { - "name": "godot_variant_new_transform3d", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_transform3d *", - "p_trans" - ] - ] - }, - { - "name": "godot_variant_new_color", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_color *", - "p_color" - ] - ] - }, - { - "name": "godot_variant_new_node_path", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_node_path *", - "p_np" - ] - ] - }, - { - "name": "godot_variant_new_rid", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_rid *", - "p_rid" - ] - ] - }, - { - "name": "godot_variant_new_object", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_object *", - "p_obj" - ] - ] - }, - { - "name": "godot_variant_new_callable", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_callable *", - "p_cb" - ] - ] - }, - { - "name": "godot_variant_new_signal", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_signal *", - "p_signal" - ] - ] - }, - { - "name": "godot_variant_new_dictionary", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_dictionary *", - "p_dict" - ] - ] - }, - { - "name": "godot_variant_new_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_array *", - "p_arr" - ] - ] - }, - { - "name": "godot_variant_new_packed_byte_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_byte_array *", - "p_pba" - ] - ] - }, - { - "name": "godot_variant_new_packed_int32_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_int32_array *", - "p_pia" - ] - ] - }, - { - "name": "godot_variant_new_packed_int64_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_int64_array *", - "p_pia" - ] - ] - }, - { - "name": "godot_variant_new_packed_float32_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_float32_array *", - "p_pra" - ] - ] - }, - { - "name": "godot_variant_new_packed_float64_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_float64_array *", - "p_pra" - ] - ] - }, - { - "name": "godot_variant_new_packed_string_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_string_array *", - "p_psa" - ] - ] - }, - { - "name": "godot_variant_new_packed_vector2_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_vector2_array *", - "p_pv2a" - ] - ] - }, - { - "name": "godot_variant_new_packed_vector3_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_vector3_array *", - "p_pv3a" - ] - ] - }, - { - "name": "godot_variant_new_packed_color_array", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "r_dest" - ], - [ - "const godot_packed_color_array *", - "p_pca" - ] - ] - }, - { - "name": "godot_variant_as_bool", - "return_type": "godot_bool", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_int", - "return_type": "int64_t", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_float", - "return_type": "double", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_string", - "return_type": "godot_string", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_string_name", - "return_type": "godot_string_name", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_vector2", - "return_type": "godot_vector2", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_vector2i", - "return_type": "godot_vector2i", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_rect2", - "return_type": "godot_rect2", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_rect2i", - "return_type": "godot_rect2i", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_vector3", - "return_type": "godot_vector3", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_vector3i", - "return_type": "godot_vector3i", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_transform2d", - "return_type": "godot_transform2d", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_plane", - "return_type": "godot_plane", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_quaternion", - "return_type": "godot_quaternion", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_aabb", - "return_type": "godot_aabb", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_basis", - "return_type": "godot_basis", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_transform3d", - "return_type": "godot_transform3d", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_color", - "return_type": "godot_color", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_node_path", - "return_type": "godot_node_path", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_rid", - "return_type": "godot_rid", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_object", - "return_type": "godot_object *", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_callable", - "return_type": "godot_callable", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_signal", - "return_type": "godot_signal", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_dictionary", - "return_type": "godot_dictionary", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_array", - "return_type": "godot_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_byte_array", - "return_type": "godot_packed_byte_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_int32_array", - "return_type": "godot_packed_int32_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_int64_array", - "return_type": "godot_packed_int64_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_float32_array", - "return_type": "godot_packed_float32_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_float64_array", - "return_type": "godot_packed_float64_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_string_array", - "return_type": "godot_packed_string_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_vector2_array", - "return_type": "godot_packed_vector2_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_vector3_array", - "return_type": "godot_packed_vector3_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_as_packed_color_array", - "return_type": "godot_packed_color_array", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_call", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ], - [ - "const godot_string_name *", - "p_method" - ], - [ - "const godot_variant **", - "p_args" - ], - [ - "const godot_int", - "p_argument_count" - ], - [ - "godot_variant *", - "r_return" - ], - [ - "godot_variant_call_error *", - "r_error" - ] - ] - }, - { - "name": "godot_variant_call_with_cstring", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ], - [ - "const char *", - "p_method" - ], - [ - "const godot_variant **", - "p_args" - ], - [ - "const godot_int", - "p_argument_count" - ], - [ - "godot_variant *", - "r_return" - ], - [ - "godot_variant_call_error *", - "r_error" - ] - ] - }, - { - "name": "godot_variant_evaluate", - "return_type": "void", - "arguments": [ - [ - "godot_variant_operator", - "p_op" - ], - [ - "const godot_variant *", - "p_a" - ], - [ - "const godot_variant *", - "p_b" - ], - [ - "godot_variant *", - "r_return" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_set", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ], - [ - "const godot_variant *", - "p_key" - ], - [ - "const godot_variant *", - "p_value" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_set_named", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ], - [ - "const godot_string_name *", - "p_key" - ], - [ - "const godot_variant *", - "p_value" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_set_named_with_cstring", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ], - [ - "const char *", - "p_key" - ], - [ - "const godot_variant *", - "p_value" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_set_keyed", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ], - [ - "const godot_variant *", - "p_key" - ], - [ - "const godot_variant *", - "p_value" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_set_indexed", - "return_type": "void", - "arguments": [ - [ - "godot_variant *", - "p_self" - ], - [ - "godot_int", - "p_index" - ], - [ - "const godot_variant *", - "p_value" - ], - [ - "bool *", - "r_valid" - ], - [ - "bool *", - "r_oob" - ] - ] - }, - { - "name": "godot_variant_get", - "return_type": "godot_variant", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "const godot_variant *", - "p_key" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_get_named", - "return_type": "godot_variant", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "const godot_string_name *", - "p_key" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_get_named_with_cstring", - "return_type": "godot_variant", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "const char *", - "p_key" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_get_keyed", - "return_type": "godot_variant", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "const godot_variant *", - "p_key" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_get_indexed", - "return_type": "godot_variant", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "godot_int", - "p_index" - ], - [ - "bool *", - "r_valid" - ], - [ - "bool *", - "r_oob" - ] - ] - }, - { - "name": "godot_variant_iter_init", - "return_type": "bool", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "godot_variant *", - "r_iter" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_iter_next", - "return_type": "bool", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "godot_variant *", - "r_iter" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_iter_get", - "return_type": "godot_variant", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "godot_variant *", - "r_iter" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_hash_compare", - "return_type": "godot_bool", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "const godot_variant *", - "p_other" - ] - ] - }, - { - "name": "godot_variant_booleanize", - "return_type": "godot_bool", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_blend", - "return_type": "void", - "arguments": [ - [ - "const godot_variant *", - "p_a" - ], - [ - "const godot_variant *", - "p_b" - ], - [ - "float", - "p_c" - ], - [ - "godot_variant *", - "r_dst" - ] - ] - }, - { - "name": "godot_variant_interpolate", - "return_type": "void", - "arguments": [ - [ - "const godot_variant *", - "p_a" - ], - [ - "const godot_variant *", - "p_b" - ], - [ - "float", - "p_c" - ], - [ - "godot_variant *", - "r_dst" - ] - ] - }, - { - "name": "godot_variant_duplicate", - "return_type": "godot_variant", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "godot_bool", - "p_deep" - ] - ] - }, - { - "name": "godot_variant_stringify", - "return_type": "godot_string", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_get_validated_operator_evaluator", - "return_type": "godot_validated_operator_evaluator", - "arguments": [ - [ - "godot_variant_operator", - "p_operator" - ], - [ - "godot_variant_type", - "p_type_a" - ], - [ - "godot_variant_type", - "p_type_b" - ] - ] - }, - { - "name": "godot_variant_get_ptr_operator_evaluator", - "return_type": "godot_ptr_operator_evaluator", - "arguments": [ - [ - "godot_variant_operator", - "p_operator" - ], - [ - "godot_variant_type", - "p_type_a" - ], - [ - "godot_variant_type", - "p_type_b" - ] - ] - }, - { - "name": "godot_variant_get_operator_return_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_operator", - "p_operator" - ], - [ - "godot_variant_type", - "p_type_a" - ], - [ - "godot_variant_type", - "p_type_b" - ] - ] - }, - { - "name": "godot_variant_get_operator_name", - "return_type": "godot_string", - "arguments": [ - [ - "godot_variant_operator", - "p_operator" - ] - ] - }, - { - "name": "godot_variant_has_builtin_method", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_has_builtin_method_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_validated_builtin_method", - "return_type": "godot_validated_builtin_method", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_validated_builtin_method_with_cstring", - "return_type": "godot_validated_builtin_method", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_ptr_builtin_method", - "return_type": "godot_ptr_builtin_method", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_ptr_builtin_method_with_cstring", - "return_type": "godot_ptr_builtin_method", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_argument_count", - "return_type": "int", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_argument_count_with_cstring", - "return_type": "int", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_argument_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_argument_type_with_cstring", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_argument_name", - "return_type": "godot_string", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_argument_name_with_cstring", - "return_type": "godot_string", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_has_builtin_method_return_value", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_has_builtin_method_return_value_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_return_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_return_type_with_cstring", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_is_builtin_method_const", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_is_builtin_method_const_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_is_builtin_method_static", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_is_builtin_method_static_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_is_builtin_method_vararg", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_is_builtin_method_vararg_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_count", - "return_type": "int", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_builtin_method_list", - "return_type": "void", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "godot_string_name *", - "r_list" - ] - ] - }, - { - "name": "godot_variant_get_constructor_count", - "return_type": "int", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_validated_constructor", - "return_type": "godot_validated_constructor", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "int", - "p_constructor" - ] - ] - }, - { - "name": "godot_variant_get_ptr_constructor", - "return_type": "godot_ptr_constructor", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "int", - "p_constructor" - ] - ] - }, - { - "name": "godot_variant_get_constructor_argument_count", - "return_type": "int", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "int", - "p_constructor" - ] - ] - }, - { - "name": "godot_variant_get_constructor_argument_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "int", - "p_constructor" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_get_constructor_argument_name", - "return_type": "godot_string", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "int", - "p_constructor" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_construct", - "return_type": "void", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "godot_variant *", - "p_base" - ], - [ - "const godot_variant **", - "p_args" - ], - [ - "int", - "p_argument_count" - ], - [ - "godot_variant_call_error *", - "r_error" - ] - ] - }, - { - "name": "godot_variant_get_member_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_member_type_with_cstring", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_member_count", - "return_type": "int", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_member_list", - "return_type": "void", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "godot_string_name *", - "r_list" - ] - ] - }, - { - "name": "godot_variant_get_validated_setter", - "return_type": "godot_validated_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_validated_setter_with_cstring", - "return_type": "godot_validated_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_validated_getter", - "return_type": "godot_validated_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_validated_getter_with_cstring", - "return_type": "godot_validated_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_ptr_setter", - "return_type": "godot_ptr_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_ptr_setter_with_cstring", - "return_type": "godot_ptr_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_ptr_getter", - "return_type": "godot_ptr_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_get_ptr_getter_with_cstring", - "return_type": "godot_ptr_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_has_indexing", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_indexed_element_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_validated_indexed_setter", - "return_type": "godot_validated_indexed_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_validated_indexed_getter", - "return_type": "godot_validated_indexed_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_ptr_indexed_setter", - "return_type": "godot_ptr_indexed_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_ptr_indexed_getter", - "return_type": "godot_ptr_indexed_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_indexed_size", - "return_type": "uint64_t", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_is_keyed", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_validated_keyed_setter", - "return_type": "godot_validated_keyed_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_validated_keyed_getter", - "return_type": "godot_validated_keyed_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_validated_keyed_checker", - "return_type": "godot_validated_keyed_checker", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_ptr_keyed_setter", - "return_type": "godot_ptr_keyed_setter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_ptr_keyed_getter", - "return_type": "godot_ptr_keyed_getter", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_ptr_keyed_checker", - "return_type": "godot_ptr_keyed_checker", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_constants_count", - "return_type": "int", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_get_constants_list", - "return_type": "void", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "godot_string_name *", - "r_list" - ] - ] - }, - { - "name": "godot_variant_has_constant", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_constant" - ] - ] - }, - { - "name": "godot_variant_has_constant_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_constant" - ] - ] - }, - { - "name": "godot_variant_get_constant_value", - "return_type": "godot_variant", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_constant" - ] - ] - }, - { - "name": "godot_variant_get_constant_value_with_cstring", - "return_type": "godot_variant", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const char *", - "p_constant" - ] - ] - }, - { - "name": "godot_variant_has_utility_function", - "return_type": "bool", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_has_utility_function_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_call_utility_function", - "return_type": "void", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ], - [ - "godot_variant *", - "r_ret" - ], - [ - "const godot_variant **", - "p_args" - ], - [ - "int", - "p_argument_count" - ], - [ - "godot_variant_call_error *", - "r_error" - ] - ] - }, - { - "name": "godot_variant_call_utility_function_with_cstring", - "return_type": "void", - "arguments": [ - [ - "const char *", - "p_function" - ], - [ - "godot_variant *", - "r_ret" - ], - [ - "const godot_variant **", - "p_args" - ], - [ - "int", - "p_argument_count" - ], - [ - "godot_variant_call_error *", - "r_error" - ] - ] - }, - { - "name": "godot_variant_get_ptr_utility_function", - "return_type": "godot_ptr_utility_function", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_ptr_utility_function_with_cstring", - "return_type": "godot_ptr_utility_function", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_validated_utility_function", - "return_type": "godot_validated_utility_function", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_validated_utility_function_with_cstring", - "return_type": "godot_validated_utility_function", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_type", - "return_type": "godot_variant_utility_function_type", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_type_with_cstring", - "return_type": "godot_variant_utility_function_type", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_argument_count", - "return_type": "int", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_argument_count_with_cstring", - "return_type": "int", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_argument_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_argument_type_with_cstring", - "return_type": "godot_variant_type", - "arguments": [ - [ - "const char *", - "p_function" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_argument_name", - "return_type": "godot_string", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_argument_name_with_cstring", - "return_type": "godot_string", - "arguments": [ - [ - "const char *", - "p_function" - ], - [ - "int", - "p_argument" - ] - ] - }, - { - "name": "godot_variant_has_utility_function_return_value", - "return_type": "bool", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_has_utility_function_return_value_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_return_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_return_type_with_cstring", - "return_type": "godot_variant_type", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_is_utility_function_vararg", - "return_type": "bool", - "arguments": [ - [ - "const godot_string_name *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_is_utility_function_vararg_with_cstring", - "return_type": "bool", - "arguments": [ - [ - "const char *", - "p_function" - ] - ] - }, - { - "name": "godot_variant_get_utility_function_count", - "return_type": "int", - "arguments": [] - }, - { - "name": "godot_variant_get_utility_function_list", - "return_type": "void", - "arguments": [ - [ - "godot_string_name *", - "r_functions" - ] - ] - }, - { - "name": "godot_variant_get_type", - "return_type": "godot_variant_type", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ] - ] - }, - { - "name": "godot_variant_has_method", - "return_type": "bool", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "const godot_string_name *", - "p_method" - ] - ] - }, - { - "name": "godot_variant_has_member", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ], - [ - "const godot_string_name *", - "p_member" - ] - ] - }, - { - "name": "godot_variant_has_key", - "return_type": "bool", - "arguments": [ - [ - "const godot_variant *", - "p_self" - ], - [ - "const godot_variant *", - "p_key" - ], - [ - "bool *", - "r_valid" - ] - ] - }, - { - "name": "godot_variant_get_type_name", - "return_type": "godot_string", - "arguments": [ - [ - "godot_variant_type", - "p_type" - ] - ] - }, - { - "name": "godot_variant_can_convert", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_from" - ], - [ - "godot_variant_type", - "p_to" - ] - ] - }, - { - "name": "godot_variant_can_convert_strict", - "return_type": "bool", - "arguments": [ - [ - "godot_variant_type", - "p_from" - ], - [ - "godot_variant_type", - "p_to" - ] - ] - }, - { - "name": "godot_aabb_new", - "return_type": "void", - "arguments": [ - [ - "godot_aabb *", - "p_self" - ] - ] - }, - { - "name": "godot_aabb_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_aabb *", - "r_dest" - ], - [ - "const godot_aabb *", - "p_src" - ] - ] - }, - { - "name": "godot_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_array *", - "p_self" - ] - ] - }, - { - "name": "godot_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_array *", - "r_dest" - ], - [ - "const godot_array *", - "p_src" - ] - ] - }, - { - "name": "godot_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_array *", - "p_self" - ] - ] - }, - { - "name": "godot_array_operator_index", - "return_type": "godot_variant *", - "arguments": [ - [ - "godot_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_array_operator_index_const", - "return_type": "const godot_variant *", - "arguments": [ - [ - "const godot_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_basis_new", - "return_type": "void", - "arguments": [ - [ - "godot_basis *", - "p_self" - ] - ] - }, - { - "name": "godot_basis_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_basis *", - "r_dest" - ], - [ - "const godot_basis *", - "p_src" - ] - ] - }, - { - "name": "godot_basis_operator_index", - "return_type": "godot_vector3 *", - "arguments": [ - [ - "godot_basis *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_basis_operator_index_const", - "return_type": "const godot_vector3 *", - "arguments": [ - [ - "const godot_basis *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_callable_new", - "return_type": "void", - "arguments": [ - [ - "godot_callable *", - "p_self" - ] - ] - }, - { - "name": "godot_callable_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_callable *", - "r_dest" - ], - [ - "const godot_callable *", - "p_src" - ] - ] - }, - { - "name": "godot_callable_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_callable *", - "p_self" - ] - ] - }, - { - "name": "godot_color_new", - "return_type": "void", - "arguments": [ - [ - "godot_color *", - "p_self" - ] - ] - }, - { - "name": "godot_color_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_color *", - "r_dest" - ], - [ - "const godot_color *", - "p_src" - ] - ] - }, - { - "name": "godot_color_operator_index", - "return_type": "float *", - "arguments": [ - [ - "godot_color *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_color_operator_index_const", - "return_type": "const float *", - "arguments": [ - [ - "const godot_color *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_dictionary_new", - "return_type": "void", - "arguments": [ - [ - "godot_dictionary *", - "p_self" - ] - ] - }, - { - "name": "godot_dictionary_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_dictionary *", - "r_dest" - ], - [ - "const godot_dictionary *", - "p_src" - ] - ] - }, - { - "name": "godot_dictionary_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_dictionary *", - "p_self" - ] - ] - }, - { - "name": "godot_dictionary_operator_index", - "return_type": "godot_variant *", - "arguments": [ - [ - "godot_dictionary *", - "p_self" - ], - [ - "const godot_variant *", - "p_key" - ] - ] - }, - { - "name": "godot_dictionary_operator_index_const", - "return_type": "const godot_variant *", - "arguments": [ - [ - "const godot_dictionary *", - "p_self" - ], - [ - "const godot_variant *", - "p_key" - ] - ] - }, - { - "name": "godot_node_path_new", - "return_type": "void", - "arguments": [ - [ - "godot_node_path *", - "p_self" - ] - ] - }, - { - "name": "godot_node_path_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_node_path *", - "r_dest" - ], - [ - "const godot_node_path *", - "p_src" - ] - ] - }, - { - "name": "godot_node_path_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_node_path *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_byte_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_byte_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_byte_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_byte_array *", - "r_dest" - ], - [ - "const godot_packed_byte_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_byte_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_byte_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_byte_array_operator_index", - "return_type": "uint8_t *", - "arguments": [ - [ - "godot_packed_byte_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_byte_array_operator_index_const", - "return_type": "const uint8_t *", - "arguments": [ - [ - "const godot_packed_byte_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_int32_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_int32_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_int32_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_int32_array *", - "r_dest" - ], - [ - "const godot_packed_int32_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_int32_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_int32_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_int32_array_operator_index", - "return_type": "int32_t *", - "arguments": [ - [ - "godot_packed_int32_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_int32_array_operator_index_const", - "return_type": "const int32_t *", - "arguments": [ - [ - "const godot_packed_int32_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_int64_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_int64_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_int64_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_int64_array *", - "r_dest" - ], - [ - "const godot_packed_int64_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_int64_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_int64_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_int64_array_operator_index", - "return_type": "int64_t *", - "arguments": [ - [ - "godot_packed_int64_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_int64_array_operator_index_const", - "return_type": "const int64_t *", - "arguments": [ - [ - "const godot_packed_int64_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_float32_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_float32_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_float32_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_float32_array *", - "r_dest" - ], - [ - "const godot_packed_float32_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_float32_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_float32_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_float32_array_operator_index", - "return_type": "float *", - "arguments": [ - [ - "godot_packed_float32_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_float32_array_operator_index_const", - "return_type": "const float *", - "arguments": [ - [ - "const godot_packed_float32_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_float64_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_float64_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_float64_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_float64_array *", - "r_dest" - ], - [ - "const godot_packed_float64_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_float64_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_float64_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_float64_array_operator_index", - "return_type": "double *", - "arguments": [ - [ - "godot_packed_float64_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_float64_array_operator_index_const", - "return_type": "const double *", - "arguments": [ - [ - "const godot_packed_float64_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_string_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_string_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_string_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_string_array *", - "r_dest" - ], - [ - "const godot_packed_string_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_string_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_string_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_string_array_operator_index", - "return_type": "godot_string *", - "arguments": [ - [ - "godot_packed_string_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_string_array_operator_index_const", - "return_type": "const godot_string *", - "arguments": [ - [ - "const godot_packed_string_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector2_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector2_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector2_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector2_array *", - "r_dest" - ], - [ - "const godot_packed_vector2_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_vector2_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector2_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector2_array_operator_index", - "return_type": "godot_vector2 *", - "arguments": [ - [ - "godot_packed_vector2_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector2_array_operator_index_const", - "return_type": "const godot_vector2 *", - "arguments": [ - [ - "const godot_packed_vector2_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector2i_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector2i_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector2i_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector2i_array *", - "r_dest" - ], - [ - "const godot_packed_vector2i_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_vector2i_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector2i_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector2i_array_operator_index", - "return_type": "godot_vector2i *", - "arguments": [ - [ - "godot_packed_vector2i_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector2i_array_operator_index_const", - "return_type": "const godot_vector2i *", - "arguments": [ - [ - "const godot_packed_vector2i_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector3_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector3_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector3_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector3_array *", - "r_dest" - ], - [ - "const godot_packed_vector3_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_vector3_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector3_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector3_array_operator_index", - "return_type": "godot_vector3 *", - "arguments": [ - [ - "godot_packed_vector3_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector3_array_operator_index_const", - "return_type": "const godot_vector3 *", - "arguments": [ - [ - "const godot_packed_vector3_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector3i_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector3i_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector3i_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector3i_array *", - "r_dest" - ], - [ - "const godot_packed_vector3i_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_vector3i_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_vector3i_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_vector3i_array_operator_index", - "return_type": "godot_vector3i *", - "arguments": [ - [ - "godot_packed_vector3i_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_vector3i_array_operator_index_const", - "return_type": "const godot_vector3i *", - "arguments": [ - [ - "const godot_packed_vector3i_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_color_array_new", - "return_type": "void", - "arguments": [ - [ - "godot_packed_color_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_color_array_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_color_array *", - "r_dest" - ], - [ - "const godot_packed_color_array *", - "p_src" - ] - ] - }, - { - "name": "godot_packed_color_array_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_packed_color_array *", - "p_self" - ] - ] - }, - { - "name": "godot_packed_color_array_operator_index", - "return_type": "godot_color *", - "arguments": [ - [ - "godot_packed_color_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_packed_color_array_operator_index_const", - "return_type": "const godot_color *", - "arguments": [ - [ - "const godot_packed_color_array *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_plane_new", - "return_type": "void", - "arguments": [ - [ - "godot_plane *", - "p_self" - ] - ] - }, - { - "name": "godot_plane_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_plane *", - "r_dest" - ], - [ - "const godot_plane *", - "p_src" - ] - ] - }, - { - "name": "godot_quaternion_new", - "return_type": "void", - "arguments": [ - [ - "godot_quaternion *", - "p_self" - ] - ] - }, - { - "name": "godot_quaternion_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_quaternion *", - "r_dest" - ], - [ - "const godot_quaternion *", - "p_src" - ] - ] - }, - { - "name": "godot_quaternion_operator_index", - "return_type": "godot_real_t *", - "arguments": [ - [ - "godot_quaternion *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_quaternion_operator_index_const", - "return_type": "const godot_real_t *", - "arguments": [ - [ - "const godot_quaternion *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_rect2_new", - "return_type": "void", - "arguments": [ - [ - "godot_rect2 *", - "p_self" - ] - ] - }, - { - "name": "godot_rect2_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_rect2 *", - "r_dest" - ], - [ - "const godot_rect2 *", - "p_src" - ] - ] - }, - { - "name": "godot_rect2i_new", - "return_type": "void", - "arguments": [ - [ - "godot_rect2i *", - "p_self" - ] - ] - }, - { - "name": "godot_rect2i_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_rect2i *", - "r_dest" - ], - [ - "const godot_rect2i *", - "p_src" - ] - ] - }, - { - "name": "godot_rid_new", - "return_type": "void", - "arguments": [ - [ - "godot_rid *", - "p_self" - ] - ] - }, - { - "name": "godot_rid_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_rid *", - "r_dest" - ], - [ - "const godot_rid *", - "p_src" - ] - ] - }, - { - "name": "godot_signal_new", - "return_type": "void", - "arguments": [ - [ - "godot_signal *", - "p_self" - ] - ] - }, - { - "name": "godot_signal_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_signal *", - "r_dest" - ], - [ - "const godot_signal *", - "p_src" - ] - ] - }, - { - "name": "godot_signal_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_signal *", - "p_self" - ] - ] - }, - { - "name": "godot_string_new", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ] - ] - }, - { - "name": "godot_string_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const godot_string *", - "p_src" - ] - ] - }, - { - "name": "godot_string_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "p_self" - ] - ] - }, - { - "name": "godot_string_new_with_latin1_chars", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char *", - "p_contents" - ] - ] - }, - { - "name": "godot_string_new_with_utf8_chars", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char *", - "p_contents" - ] - ] - }, - { - "name": "godot_string_new_with_utf16_chars", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char16_t *", - "p_contents" - ] - ] - }, - { - "name": "godot_string_new_with_utf32_chars", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char32_t *", - "p_contents" - ] - ] - }, - { - "name": "godot_string_new_with_wide_chars", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const wchar_t *", - "p_contents" - ] - ] - }, - { - "name": "godot_string_new_with_latin1_chars_and_len", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char *", - "p_contents" - ], - [ - "const int", - "p_size" - ] - ] - }, - { - "name": "godot_string_new_with_utf8_chars_and_len", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char *", - "p_contents" - ], - [ - "const int", - "p_size" - ] - ] - }, - { - "name": "godot_string_new_with_utf16_chars_and_len", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char16_t *", - "p_contents" - ], - [ - "const int", - "p_size" - ] - ] - }, - { - "name": "godot_string_new_with_utf32_chars_and_len", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const char32_t *", - "p_contents" - ], - [ - "const int", - "p_size" - ] - ] - }, - { - "name": "godot_string_new_with_wide_chars_and_len", - "return_type": "void", - "arguments": [ - [ - "godot_string *", - "r_dest" - ], - [ - "const wchar_t *", - "p_contents" - ], - [ - "const int", - "p_size" - ] - ] - }, - { - "name": "godot_string_to_latin1_chars", - "return_type": "const char *", - "arguments": [ - [ - "const godot_string *", - "p_self" - ] - ] - }, - { - "name": "godot_string_to_utf8_chars", - "return_type": "const char *", - "arguments": [ - [ - "const godot_string *", - "p_self" - ] - ] - }, - { - "name": "godot_string_to_utf16_chars", - "return_type": "const char16_t *", - "arguments": [ - [ - "const godot_string *", - "p_self" - ] - ] - }, - { - "name": "godot_string_to_utf32_chars", - "return_type": "const char32_t *", - "arguments": [ - [ - "const godot_string *", - "p_self" - ] - ] - }, - { - "name": "godot_string_to_wide_chars", - "return_type": "const wchar_t *", - "arguments": [ - [ - "const godot_string *", - "p_self" - ] - ] - }, - { - "name": "godot_string_operator_index", - "return_type": "char32_t *", - "arguments": [ - [ - "godot_string *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_string_operator_index_const", - "return_type": "const char32_t *", - "arguments": [ - [ - "const godot_string *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_string_name_new", - "return_type": "void", - "arguments": [ - [ - "godot_string_name *", - "r_dest" - ] - ] - }, - { - "name": "godot_string_name_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_string_name *", - "r_dest" - ], - [ - "const godot_string_name *", - "p_src" - ] - ] - }, - { - "name": "godot_string_name_destroy", - "return_type": "void", - "arguments": [ - [ - "godot_string_name *", - "p_self" - ] - ] - }, - { - "name": "godot_string_name_new_with_latin1_chars", - "return_type": "void", - "arguments": [ - [ - "godot_string_name *", - "r_dest" - ], - [ - "const char *", - "p_contents" - ] - ] - }, - { - "name": "godot_transform3d_new", - "return_type": "void", - "arguments": [ - [ - "godot_transform3d *", - "r_dest" - ] - ] - }, - { - "name": "godot_transform3d_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_transform3d *", - "r_dest" - ], - [ - "const godot_transform3d *", - "p_src" - ] - ] - }, - { - "name": "godot_transform2d_new", - "return_type": "void", - "arguments": [ - [ - "godot_transform2d *", - "r_dest" - ] - ] - }, - { - "name": "godot_transform2d_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_transform2d *", - "r_dest" - ], - [ - "const godot_transform2d *", - "p_src" - ] - ] - }, - { - "name": "godot_transform2d_operator_index", - "return_type": "godot_vector2 *", - "arguments": [ - [ - "godot_transform2d *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_transform2d_operator_index_const", - "return_type": "const godot_vector2 *", - "arguments": [ - [ - "const godot_transform2d *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector2_new", - "return_type": "void", - "arguments": [ - [ - "godot_vector2 *", - "r_dest" - ] - ] - }, - { - "name": "godot_vector2_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_vector2 *", - "r_dest" - ], - [ - "const godot_vector2 *", - "p_src" - ] - ] - }, - { - "name": "godot_vector2_operator_index", - "return_type": "godot_real_t *", - "arguments": [ - [ - "godot_vector2 *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector2_operator_index_const", - "return_type": "const godot_real_t *", - "arguments": [ - [ - "const godot_vector2 *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector2i_new", - "return_type": "void", - "arguments": [ - [ - "godot_vector2i *", - "r_dest" - ] - ] - }, - { - "name": "godot_vector2i_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_vector2i *", - "r_dest" - ], - [ - "const godot_vector2i *", - "p_src" - ] - ] - }, - { - "name": "godot_vector2i_operator_index", - "return_type": "int32_t *", - "arguments": [ - [ - "godot_vector2i *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector2i_operator_index_const", - "return_type": "const int32_t *", - "arguments": [ - [ - "const godot_vector2i *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector3_new", - "return_type": "void", - "arguments": [ - [ - "godot_vector3 *", - "r_dest" - ] - ] - }, - { - "name": "godot_vector3_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_vector3 *", - "r_dest" - ], - [ - "const godot_vector3 *", - "p_src" - ] - ] - }, - { - "name": "godot_vector3_operator_index", - "return_type": "godot_real_t *", - "arguments": [ - [ - "godot_vector3 *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector3_operator_index_const", - "return_type": "const godot_real_t *", - "arguments": [ - [ - "const godot_vector3 *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector3i_new", - "return_type": "void", - "arguments": [ - [ - "godot_vector3i *", - "r_dest" - ] - ] - }, - { - "name": "godot_vector3i_new_copy", - "return_type": "void", - "arguments": [ - [ - "godot_vector3i *", - "r_dest" - ], - [ - "const godot_vector3i *", - "p_src" - ] - ] - }, - { - "name": "godot_vector3i_operator_index", - "return_type": "int32_t *", - "arguments": [ - [ - "godot_vector3i *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - }, - { - "name": "godot_vector3i_operator_index_const", - "return_type": "const int32_t *", - "arguments": [ - [ - "const godot_vector3i *", - "p_self" - ], - [ - "godot_int", - "p_index" - ] - ] - } - ] - }, - "extensions": [ - { - "name": "nativescript", - "type": "NATIVESCRIPT", - "version": { - "major": 4, - "minor": 0 - }, - "next": null, - "api": [ - { - "name": "godot_nativescript_register_class", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_base" - ], - [ - "godot_nativescript_instance_create_func", - "p_create_func" - ], - [ - "godot_nativescript_instance_destroy_func", - "p_destroy_func" - ] - ] - }, - { - "name": "godot_nativescript_register_tool_class", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_base" - ], - [ - "godot_nativescript_instance_create_func", - "p_create_func" - ], - [ - "godot_nativescript_instance_destroy_func", - "p_destroy_func" - ] - ] - }, - { - "name": "godot_nativescript_register_method", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_function_name" - ], - [ - "godot_nativescript_method_attributes", - "p_attr" - ], - [ - "godot_nativescript_instance_method", - "p_method" - ] - ] - }, - { - "name": "godot_nativescript_set_method_argument_information", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_function_name" - ], - [ - "int", - "p_num_args" - ], - [ - "const godot_nativescript_method_argument *", - "p_args" - ] - ] - }, - { - "name": "godot_nativescript_register_property", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_path" - ], - [ - "godot_nativescript_property_attributes *", - "p_attr" - ], - [ - "godot_nativescript_property_set_func", - "p_set_func" - ], - [ - "godot_nativescript_property_get_func", - "p_get_func" - ] - ] - }, - { - "name": "godot_nativescript_register_signal", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const godot_nativescript_signal *", - "p_signal" - ] - ] - }, - { - "name": "godot_nativescript_get_userdata", - "return_type": "void *", - "arguments": [ - [ - "godot_object *", - "p_instance" - ] - ] - }, - { - "name": "godot_nativescript_set_class_documentation", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "godot_string", - "p_documentation" - ] - ] - }, - { - "name": "godot_nativescript_set_method_documentation", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_function_name" - ], - [ - "godot_string", - "p_documentation" - ] - ] - }, - { - "name": "godot_nativescript_set_property_documentation", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_path" - ], - [ - "godot_string", - "p_documentation" - ] - ] - }, - { - "name": "godot_nativescript_set_signal_documentation", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const char *", - "p_signal_name" - ], - [ - "godot_string", - "p_documentation" - ] - ] - }, - { - "name": "godot_nativescript_set_global_type_tag", - "return_type": "void", - "arguments": [ - [ - "int", - "p_idx" - ], - [ - "const char *", - "p_name" - ], - [ - "const void *", - "p_type_tag" - ] - ] - }, - { - "name": "godot_nativescript_get_global_type_tag", - "return_type": "const void *", - "arguments": [ - [ - "int", - "p_idx" - ], - [ - "const char *", - "p_name" - ] - ] - }, - { - "name": "godot_nativescript_set_type_tag", - "return_type": "void", - "arguments": [ - [ - "void *", - "p_gdnative_handle" - ], - [ - "const char *", - "p_name" - ], - [ - "const void *", - "p_type_tag" - ] - ] - }, - { - "name": "godot_nativescript_get_type_tag", - "return_type": "const void *", - "arguments": [ - [ - "const godot_object *", - "p_object" - ] - ] - }, - { - "name": "godot_nativescript_register_instance_binding_data_functions", - "return_type": "int", - "arguments": [ - [ - "godot_nativescript_instance_binding_functions", - "p_binding_functions" - ] - ] - }, - { - "name": "godot_nativescript_unregister_instance_binding_data_functions", - "return_type": "void", - "arguments": [ - [ - "int", - "p_idx" - ] - ] - }, - { - "name": "godot_nativescript_get_instance_binding_data", - "return_type": "void *", - "arguments": [ - [ - "int", - "p_idx" - ], - [ - "godot_object *", - "p_object" - ] - ] - }, - { - "name": "godot_nativescript_profiling_add_data", - "return_type": "void", - "arguments": [ - [ - "const char *", - "p_signature" - ], - [ - "uint64_t", - "p_line" - ] - ] - } - ] - }, - { - "name": "pluginscript", - "type": "PLUGINSCRIPT", - "version": { - "major": 1, - "minor": 0 - }, - "next": null, - "api": [ - { - "name": "godot_pluginscript_register_language", - "return_type": "void", - "arguments": [ - [ - "const godot_pluginscript_language_desc *", - "language_desc" - ] - ] - } - ] - }, - { - "name": "android", - "type": "ANDROID", - "version": { - "major": 1, - "minor": 1 - }, - "next": null, - "api": [ - { - "name": "godot_android_get_env", - "return_type": "JNIEnv*", - "arguments": [] - }, - { - "name": "godot_android_get_activity", - "return_type": "jobject", - "arguments": [] - }, - { - "name": "godot_android_get_surface", - "return_type": "jobject", - "arguments": [] - }, - { - "name": "godot_android_is_activity_resumed", - "return_type": "bool", - "arguments": [] - } - ] - }, - { - "name": "videodecoder", - "type": "VIDEODECODER", - "version": { - "major": 0, - "minor": 1 - }, - "next": null, - "api": [ - { - "name": "godot_videodecoder_file_read", - "return_type": "godot_int", - "arguments": [ - [ - "void *", - "file_ptr" - ], - [ - "uint8_t *", - "buf" - ], - [ - "int", - "buf_size" - ] - ] - }, - { - "name": "godot_videodecoder_file_seek", - "return_type": "int64_t", - "arguments": [ - [ - "void *", - "file_ptr" - ], - [ - "int64_t", - "pos" - ], - [ - "int", - "whence" - ] - ] - }, - { - "name": "godot_videodecoder_register_decoder", - "return_type": "void", - "arguments": [ - [ - "const godot_videodecoder_interface_gdnative *", - "p_interface" - ] - ] - } - ] - } - ] -} diff --git a/modules/gdnative/gdnative_builders.py b/modules/gdnative/gdnative_builders.py deleted file mode 100644 index 6c96e23426..0000000000 --- a/modules/gdnative/gdnative_builders.py +++ /dev/null @@ -1,263 +0,0 @@ -"""Functions used to generate source files during build time - -All such functions are invoked in a subprocess on Windows to prevent build flakiness. - -""" -import json -from platform_methods import subprocess_main - - -def _spaced(e): - return e if e[-1] == "*" else e + " " - - -def _build_gdnative_api_struct_header(api): - out = [ - "/* THIS FILE IS GENERATED DO NOT EDIT */", - "#ifndef GODOT_GDNATIVE_API_STRUCT_H", - "#define GODOT_GDNATIVE_API_STRUCT_H", - "", - "#include <gdnative/gdnative.h>", - "#include <android/godot_android.h>", - "#include <nativescript/godot_nativescript.h>", - "#include <pluginscript/godot_pluginscript.h>", - "#include <videodecoder/godot_videodecoder.h>", - "", - "#ifdef __cplusplus", - 'extern "C" {', - "#endif", - "", - "enum GDNATIVE_API_TYPES {", - "\tGDNATIVE_" + api["core"]["type"] + ",", - ] - - for ext in api["extensions"]: - out += ["\tGDNATIVE_EXT_" + ext["type"] + ","] - - out += ["};", ""] - - def generate_extension_struct(name, ext, include_version=True): - ret_val = [] - if ext["next"]: - ret_val += generate_extension_struct(name, ext["next"]) - - ret_val += [ - "typedef struct godot_gdnative_ext_" - + name - + ("" if not include_version else ("_{0}_{1}".format(ext["version"]["major"], ext["version"]["minor"]))) - + "_api_struct {", - "\tunsigned int type;", - "\tgodot_gdnative_api_version version;", - "\tconst godot_gdnative_api_struct *next;", - ] - - for funcdef in ext["api"]: - args = ", ".join(["%s%s" % (_spaced(t), n) for t, n in funcdef["arguments"]]) - ret_val.append("\t%s(*%s)(%s);" % (_spaced(funcdef["return_type"]), funcdef["name"], args)) - - ret_val += [ - "} godot_gdnative_ext_" - + name - + ("" if not include_version else ("_{0}_{1}".format(ext["version"]["major"], ext["version"]["minor"]))) - + "_api_struct;", - "", - ] - - return ret_val - - def generate_core_extension_struct(core): - ret_val = [] - if core["next"]: - ret_val += generate_core_extension_struct(core["next"]) - - ret_val += [ - "typedef struct godot_gdnative_core_" - + "{0}_{1}".format(core["version"]["major"], core["version"]["minor"]) - + "_api_struct {", - "\tunsigned int type;", - "\tgodot_gdnative_api_version version;", - "\tconst godot_gdnative_api_struct *next;", - ] - - for funcdef in core["api"]: - args = ", ".join(["%s%s" % (_spaced(t), n) for t, n in funcdef["arguments"]]) - ret_val.append("\t%s(*%s)(%s);" % (_spaced(funcdef["return_type"]), funcdef["name"], args)) - - ret_val += [ - "} godot_gdnative_core_" - + "{0}_{1}".format(core["version"]["major"], core["version"]["minor"]) - + "_api_struct;", - "", - ] - - return ret_val - - for ext in api["extensions"]: - name = ext["name"] - out += generate_extension_struct(name, ext, False) - - if api["core"]["next"]: - out += generate_core_extension_struct(api["core"]["next"]) - - out += [ - "typedef struct godot_gdnative_core_api_struct {", - "\tunsigned int type;", - "\tgodot_gdnative_api_version version;", - "\tconst godot_gdnative_api_struct *next;", - "\tunsigned int num_extensions;", - "\tconst godot_gdnative_api_struct **extensions;", - ] - - for funcdef in api["core"]["api"]: - args = ", ".join(["%s%s" % (_spaced(t), n) for t, n in funcdef["arguments"]]) - out.append("\t%s(*%s)(%s);" % (_spaced(funcdef["return_type"]), funcdef["name"], args)) - - out += [ - "} godot_gdnative_core_api_struct;", - "", - "#ifdef __cplusplus", - "}", - "#endif", - "", - "#endif // GODOT_GDNATIVE_API_STRUCT_H", - "", - ] - return "\n".join(out) - - -def _build_gdnative_api_struct_source(api): - out = ["/* THIS FILE IS GENERATED DO NOT EDIT */", "", "#include <gdnative_api_struct.gen.h>", ""] - - def get_extension_struct_name(name, ext, include_version=True): - return ( - "godot_gdnative_ext_" - + name - + ("" if not include_version else ("_{0}_{1}".format(ext["version"]["major"], ext["version"]["minor"]))) - + "_api_struct" - ) - - def get_extension_struct_instance_name(name, ext, include_version=True): - return ( - "api_extension_" - + name - + ("" if not include_version else ("_{0}_{1}".format(ext["version"]["major"], ext["version"]["minor"]))) - + "_struct" - ) - - def get_extension_struct_definition(name, ext, include_version=True): - - ret_val = [] - - if ext["next"]: - ret_val += get_extension_struct_definition(name, ext["next"]) - - ret_val += [ - "extern const " - + get_extension_struct_name(name, ext, include_version) - + " " - + get_extension_struct_instance_name(name, ext, include_version) - + " = {", - "\tGDNATIVE_EXT_" + ext["type"] + ",", - "\t{" + str(ext["version"]["major"]) + ", " + str(ext["version"]["minor"]) + "},", - "\t" - + ( - "nullptr" - if not ext["next"] - else ("(const godot_gdnative_api_struct *)&" + get_extension_struct_instance_name(name, ext["next"])) - ) - + ",", - ] - - for funcdef in ext["api"]: - ret_val.append("\t%s," % funcdef["name"]) - - ret_val += ["};\n"] - - return ret_val - - def get_core_struct_definition(core): - ret_val = [] - - if core["next"]: - ret_val += get_core_struct_definition(core["next"]) - - ret_val += [ - "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" - + ( - "nullptr" - 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"]: - ret_val.append("\t%s," % funcdef["name"]) - - ret_val += ["};\n"] - - return ret_val - - for ext in api["extensions"]: - name = ext["name"] - out += get_extension_struct_definition(name, ext, False) - - out += ["", "const godot_gdnative_api_struct *gdnative_extensions_pointers[] = {"] - - for ext in api["extensions"]: - name = ext["name"] - out += ["\t(godot_gdnative_api_struct *)&api_extension_" + name + "_struct,"] - - out += ["};\n"] - - if api["core"]["next"]: - out += get_core_struct_definition(api["core"]["next"]) - - out += [ - "extern const godot_gdnative_core_api_struct api_struct = {", - "\tGDNATIVE_" + api["core"]["type"] + ",", - "\t{" + str(api["core"]["version"]["major"]) + ", " + str(api["core"]["version"]["minor"]) + "},", - "\t" - + ( - "nullptr, " - if not api["core"]["next"] - else ( - "(const godot_gdnative_api_struct *)& api_{0}_{1},".format( - api["core"]["next"]["version"]["major"], api["core"]["next"]["version"]["minor"] - ) - ) - ), - "\t" + str(len(api["extensions"])) + ",", - "\tgdnative_extensions_pointers,", - ] - - for funcdef in api["core"]["api"]: - out.append("\t%s," % funcdef["name"]) - out.append("};\n") - - return "\n".join(out) - - -def build_gdnative_api_struct(target, source, env): - - with open(source[0], "r") as fd: - api = json.load(fd) - - header, source = target - with open(header, "w") as fd: - fd.write(_build_gdnative_api_struct_header(api)) - with open(source, "w") as fd: - fd.write(_build_gdnative_api_struct_source(api)) - - -if __name__ == "__main__": - subprocess_main(globals()) diff --git a/modules/gdnative/gdnative_library_editor_plugin.cpp b/modules/gdnative/gdnative_library_editor_plugin.cpp deleted file mode 100644 index 33ea078696..0000000000 --- a/modules/gdnative/gdnative_library_editor_plugin.cpp +++ /dev/null @@ -1,417 +0,0 @@ -/*************************************************************************/ -/* gdnative_library_editor_plugin.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 TOOLS_ENABLED -#include "gdnative_library_editor_plugin.h" -#include "gdnative.h" - -#include "editor/editor_scale.h" - -void GDNativeLibraryEditor::edit(Ref<GDNativeLibrary> p_library) { - library = p_library; - Ref<ConfigFile> config = p_library->get_config_file(); - - for (KeyValue<String, NativePlatformConfig> &E : platforms) { - for (List<String>::Element *it = E.value.entries.front(); it; it = it->next()) { - String target = E.key + "." + it->get(); - TargetConfig ecfg; - ecfg.library = config->get_value("entry", target, ""); - ecfg.dependencies = config->get_value("dependencies", target, Array()); - entry_configs[target] = ecfg; - } - } - - _update_tree(); -} - -void GDNativeLibraryEditor::_bind_methods() { -} - -void GDNativeLibraryEditor::_update_tree() { - tree->clear(); - TreeItem *root = tree->create_item(); - - PopupMenu *filter_list = filter->get_popup(); - String text = ""; - for (int i = 0; i < filter_list->get_item_count(); i++) { - if (!filter_list->is_item_checked(i)) { - continue; - } - Map<String, NativePlatformConfig>::Element *E = platforms.find(filter_list->get_item_metadata(i)); - if (!text.is_empty()) { - text += ", "; - } - text += E->get().name; - - TreeItem *platform = tree->create_item(root); - platform->set_text(0, E->get().name); - platform->set_metadata(0, E->get().library_extension); - - platform->set_custom_bg_color(0, get_theme_color(SNAME("prop_category"), SNAME("Editor"))); - platform->set_custom_bg_color(1, get_theme_color(SNAME("prop_category"), SNAME("Editor"))); - platform->set_custom_bg_color(2, get_theme_color(SNAME("prop_category"), SNAME("Editor"))); - platform->set_selectable(0, false); - platform->set_expand_right(0, true); - - for (List<String>::Element *it = E->value().entries.front(); it; it = it->next()) { - String target = E->key() + "." + it->get(); - TreeItem *bit = tree->create_item(platform); - - bit->set_text(0, it->get()); - bit->set_metadata(0, target); - bit->set_selectable(0, false); - bit->set_custom_bg_color(0, get_theme_color(SNAME("prop_subsection"), SNAME("Editor"))); - - bit->add_button(1, get_theme_icon(SNAME("Folder"), SNAME("EditorIcons")), BUTTON_SELECT_LIBRARY, false, TTR("Select the dynamic library for this entry")); - String file = entry_configs[target].library; - if (!file.is_empty()) { - bit->add_button(1, get_theme_icon(SNAME("Clear"), SNAME("EditorIcons")), BUTTON_CLEAR_LIBRARY, false, TTR("Clear")); - } - bit->set_text(1, file); - - bit->add_button(2, get_theme_icon(SNAME("Folder"), SNAME("EditorIcons")), BUTTON_SELECT_DEPENDENCES, false, TTR("Select dependencies of the library for this entry")); - Array files = entry_configs[target].dependencies; - if (files.size()) { - bit->add_button(2, get_theme_icon(SNAME("Clear"), SNAME("EditorIcons")), BUTTON_CLEAR_DEPENDENCES, false, TTR("Clear")); - } - bit->set_text(2, Variant(files)); - - bit->add_button(3, get_theme_icon(SNAME("MoveUp"), SNAME("EditorIcons")), BUTTON_MOVE_UP, false, TTR("Move Up")); - bit->add_button(3, get_theme_icon(SNAME("MoveDown"), SNAME("EditorIcons")), BUTTON_MOVE_DOWN, false, TTR("Move Down")); - bit->add_button(3, get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_ERASE_ENTRY, false, TTR("Remove current entry")); - } - - TreeItem *new_arch = tree->create_item(platform); - new_arch->set_text(0, TTR("Double click to create a new entry")); - new_arch->set_text_alignment(0, HORIZONTAL_ALIGNMENT_CENTER); - new_arch->set_custom_color(0, get_theme_color(SNAME("accent_color"), SNAME("Editor"))); - new_arch->set_expand_right(0, true); - new_arch->set_metadata(1, E->key()); - - platform->set_collapsed(collapsed_items.find(E->get().name) != nullptr); - } - filter->set_text(text); -} - -void GDNativeLibraryEditor::_on_item_button(Object *item, int column, int id) { - String target = Object::cast_to<TreeItem>(item)->get_metadata(0); - String platform = target.substr(0, target.find(".")); - String entry = target.substr(platform.length() + 1, target.length()); - String section = (id == BUTTON_SELECT_DEPENDENCES || id == BUTTON_CLEAR_DEPENDENCES) ? "dependencies" : "entry"; - - if (id == BUTTON_SELECT_LIBRARY || id == BUTTON_SELECT_DEPENDENCES) { - TreeItem *treeItem = Object::cast_to<TreeItem>(item)->get_parent(); - EditorFileDialog::FileMode mode = EditorFileDialog::FILE_MODE_OPEN_FILE; - if (id == BUTTON_SELECT_DEPENDENCES) { - mode = EditorFileDialog::FILE_MODE_OPEN_FILES; - } else if (treeItem->get_text(0) == "iOS" || treeItem->get_text(0) == "macOS") { - mode = EditorFileDialog::FILE_MODE_OPEN_ANY; - } - - file_dialog->set_meta("target", target); - file_dialog->set_meta("section", section); - file_dialog->clear_filters(); - - String filter_string = treeItem->get_metadata(0); - Vector<String> filters = filter_string.split(",", false, 0); - for (int i = 0; i < filters.size(); i++) { - file_dialog->add_filter(filters[i]); - } - - file_dialog->set_file_mode(mode); - file_dialog->popup_file_dialog(); - - } else if (id == BUTTON_CLEAR_LIBRARY) { - _set_target_value(section, target, ""); - } else if (id == BUTTON_CLEAR_DEPENDENCES) { - _set_target_value(section, target, Array()); - } else if (id == BUTTON_ERASE_ENTRY) { - _erase_entry(platform, entry); - } else if (id == BUTTON_MOVE_UP || id == BUTTON_MOVE_DOWN) { - _move_entry(platform, entry, id); - } -} - -void GDNativeLibraryEditor::_on_library_selected(const String &file) { - _set_target_value(file_dialog->get_meta("section"), file_dialog->get_meta("target"), file); -} - -void GDNativeLibraryEditor::_on_dependencies_selected(const PackedStringArray &files) { - _set_target_value(file_dialog->get_meta("section"), file_dialog->get_meta("target"), files); -} - -void GDNativeLibraryEditor::_on_filter_selected(int index) { - PopupMenu *filter_list = filter->get_popup(); - filter_list->set_item_checked(index, !filter_list->is_item_checked(index)); - _update_tree(); -} - -void GDNativeLibraryEditor::_on_item_collapsed(Object *p_item) { - TreeItem *item = Object::cast_to<TreeItem>(p_item); - String name = item->get_text(0); - - if (item->is_collapsed()) { - collapsed_items.insert(name); - } else if (Set<String>::Element *e = collapsed_items.find(name)) { - collapsed_items.erase(e); - } -} - -void GDNativeLibraryEditor::_on_item_activated() { - TreeItem *item = tree->get_selected(); - if (item && tree->get_selected_column() == 0 && item->get_metadata(0).get_type() == Variant::NIL) { - new_architecture_dialog->set_meta("platform", item->get_metadata(1)); - new_architecture_dialog->popup_centered(); - } -} - -void GDNativeLibraryEditor::_on_create_new_entry() { - String platform = new_architecture_dialog->get_meta("platform"); - String entry = new_architecture_input->get_text().strip_edges(); - if (!entry.is_empty()) { - platforms[platform].entries.push_back(entry); - _update_tree(); - } -} - -void GDNativeLibraryEditor::_set_target_value(const String §ion, const String &target, Variant file) { - if (section == "entry") { - entry_configs[target].library = file; - } else if (section == "dependencies") { - entry_configs[target].dependencies = file; - } - _translate_to_config_file(); - _update_tree(); -} - -void GDNativeLibraryEditor::_erase_entry(const String &platform, const String &entry) { - if (platforms.has(platform)) { - if (List<String>::Element *E = platforms[platform].entries.find(entry)) { - String target = platform + "." + entry; - - platforms[platform].entries.erase(E); - _set_target_value("entry", target, ""); - _set_target_value("dependencies", target, Array()); - _translate_to_config_file(); - _update_tree(); - } - } -} - -void GDNativeLibraryEditor::_move_entry(const String &platform, const String &entry, int dir) { - if (List<String>::Element *E = platforms[platform].entries.find(entry)) { - if (E->prev() && dir == BUTTON_MOVE_UP) { - platforms[platform].entries.insert_before(E->prev(), E->get()); - platforms[platform].entries.erase(E); - } else if (E->next() && dir == BUTTON_MOVE_DOWN) { - platforms[platform].entries.insert_after(E->next(), E->get()); - platforms[platform].entries.erase(E); - } - _translate_to_config_file(); - _update_tree(); - } -} - -void GDNativeLibraryEditor::_translate_to_config_file() { - if (!library.is_null()) { - Ref<ConfigFile> config = library->get_config_file(); - config->erase_section("entry"); - config->erase_section("dependencies"); - - for (KeyValue<String, NativePlatformConfig> &E : platforms) { - for (List<String>::Element *it = E.value.entries.front(); it; it = it->next()) { - String target = E.key + "." + it->get(); - if (entry_configs[target].library.is_empty() && entry_configs[target].dependencies.is_empty()) { - continue; - } - - config->set_value("entry", target, entry_configs[target].library); - config->set_value("dependencies", target, entry_configs[target].dependencies); - } - } - - library->notify_property_list_changed(); - } -} - -GDNativeLibraryEditor::GDNativeLibraryEditor() { - { // Define platforms - NativePlatformConfig platform_windows; - platform_windows.name = "Windows"; - platform_windows.entries.push_back("64"); - platform_windows.entries.push_back("32"); - platform_windows.library_extension = "*.dll"; - platforms["Windows"] = platform_windows; - - NativePlatformConfig platform_linux; - platform_linux.name = "Linux/X11"; - platform_linux.entries.push_back("64"); - platform_linux.entries.push_back("32"); - platform_linux.library_extension = "*.so"; - platforms["X11"] = platform_linux; - - NativePlatformConfig platform_osx; - platform_osx.name = "macOS"; - platform_osx.entries.push_back("64"); - platform_osx.library_extension = "*.framework; Framework, *.dylib; Dynamic Library"; - platforms["macOS"] = platform_osx; - - NativePlatformConfig platform_haiku; - platform_haiku.name = "Haiku"; - platform_haiku.entries.push_back("64"); - platform_haiku.entries.push_back("32"); - platform_haiku.library_extension = "*.so"; - platforms["Haiku"] = platform_haiku; - - NativePlatformConfig platform_uwp; - platform_uwp.name = "UWP"; - platform_uwp.entries.push_back("arm"); - platform_uwp.entries.push_back("32"); - platform_uwp.entries.push_back("64"); - platform_uwp.library_extension = "*.dll"; - platforms["UWP"] = platform_uwp; - - NativePlatformConfig platform_android; - platform_android.name = "Android"; - platform_android.entries.push_back("armeabi-v7a"); - platform_android.entries.push_back("arm64-v8a"); - platform_android.entries.push_back("x86"); - platform_android.entries.push_back("x86_64"); - platform_android.library_extension = "*.so"; - platforms["Android"] = platform_android; - - NativePlatformConfig platform_html5; - platform_html5.name = "HTML5"; - platform_html5.entries.push_back("wasm32"); - platform_html5.library_extension = "*.wasm"; - platforms["HTML5"] = platform_html5; - - NativePlatformConfig platform_ios; - platform_ios.name = "iOS"; - platform_ios.entries.push_back("arm64"); - platform_ios.entries.push_back("x86_64"); - // iOS can use both Static and Dynamic libraries. - // Frameworks is actually a folder with files. - platform_ios.library_extension = "*.framework; Framework, *.xcframework; Binary Framework, *.a; Static Library, *.dylib; Dynamic Library"; - platforms["iOS"] = platform_ios; - } - - VBoxContainer *container = memnew(VBoxContainer); - add_child(container); - container->set_anchors_and_offsets_preset(PRESET_WIDE); - - HBoxContainer *hbox = memnew(HBoxContainer); - container->add_child(hbox); - Label *label = memnew(Label); - label->set_text(TTR("Platform:")); - hbox->add_child(label); - filter = memnew(MenuButton); - filter->set_h_size_flags(SIZE_EXPAND_FILL); - filter->set_text_alignment(HORIZONTAL_ALIGNMENT_LEFT); - hbox->add_child(filter); - PopupMenu *filter_list = filter->get_popup(); - filter_list->set_hide_on_checkable_item_selection(false); - - int idx = 0; - for (const KeyValue<String, NativePlatformConfig> &E : platforms) { - filter_list->add_check_item(E.value.name, idx); - filter_list->set_item_metadata(idx, E.key); - filter_list->set_item_checked(idx, true); - idx += 1; - } - filter_list->connect("index_pressed", callable_mp(this, &GDNativeLibraryEditor::_on_filter_selected)); - - tree = memnew(Tree); - container->add_child(tree); - tree->set_v_size_flags(SIZE_EXPAND_FILL); - tree->set_hide_root(true); - tree->set_column_titles_visible(true); - tree->set_columns(4); - tree->set_column_expand(0, false); - tree->set_column_custom_minimum_width(0, int(200 * EDSCALE)); - tree->set_column_title(0, TTR("Platform")); - tree->set_column_title(1, TTR("Dynamic Library")); - tree->set_column_title(2, TTR("Dependencies")); - tree->set_column_expand(3, false); - tree->set_column_custom_minimum_width(3, int(110 * EDSCALE)); - tree->connect("button_pressed", callable_mp(this, &GDNativeLibraryEditor::_on_item_button)); - tree->connect("item_collapsed", callable_mp(this, &GDNativeLibraryEditor::_on_item_collapsed)); - tree->connect("item_activated", callable_mp(this, &GDNativeLibraryEditor::_on_item_activated)); - - file_dialog = memnew(EditorFileDialog); - file_dialog->set_access(EditorFileDialog::ACCESS_RESOURCES); - //file_dialog->set_resizable(true); - add_child(file_dialog); - file_dialog->connect("file_selected", callable_mp(this, &GDNativeLibraryEditor::_on_library_selected)); - file_dialog->connect("dir_selected", callable_mp(this, &GDNativeLibraryEditor::_on_library_selected)); - file_dialog->connect("files_selected", callable_mp(this, &GDNativeLibraryEditor::_on_dependencies_selected)); - - new_architecture_dialog = memnew(ConfirmationDialog); - add_child(new_architecture_dialog); - new_architecture_dialog->set_title(TTR("Add an architecture entry")); - new_architecture_input = memnew(LineEdit); - new_architecture_dialog->add_child(new_architecture_input); - // new_architecture_dialog->set_custom_minimum_size(Vector2(300, 80) * EDSCALE); - new_architecture_input->set_anchors_and_offsets_preset(PRESET_HCENTER_WIDE, PRESET_MODE_MINSIZE, 5 * EDSCALE); - new_architecture_dialog->get_ok_button()->connect("pressed", callable_mp(this, &GDNativeLibraryEditor::_on_create_new_entry)); -} - -void GDNativeLibraryEditorPlugin::edit(Object *p_node) { - 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 { - return p_node->is_class("GDNativeLibrary"); -} - -void GDNativeLibraryEditorPlugin::make_visible(bool p_visible) { - if (p_visible) { - button->show(); - EditorNode::get_singleton()->make_bottom_panel_item_visible(library_editor); - - } else { - if (library_editor->is_visible_in_tree()) { - EditorNode::get_singleton()->hide_bottom_panel(); - } - button->hide(); - } -} - -GDNativeLibraryEditorPlugin::GDNativeLibraryEditorPlugin(EditorNode *p_node) { - library_editor = memnew(GDNativeLibraryEditor); - library_editor->set_custom_minimum_size(Size2(0, 250 * EDSCALE)); - button = p_node->add_bottom_panel_item(TTR("GDNativeLibrary"), library_editor); - button->hide(); -} - -#endif diff --git a/modules/gdnative/gdnative_library_editor_plugin.h b/modules/gdnative/gdnative_library_editor_plugin.h deleted file mode 100644 index 27848893fa..0000000000 --- a/modules/gdnative/gdnative_library_editor_plugin.h +++ /dev/null @@ -1,112 +0,0 @@ -/*************************************************************************/ -/* gdnative_library_editor_plugin.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 GDNATIVE_LIBRARY_EDITOR_PLUGIN_H -#define GDNATIVE_LIBRARY_EDITOR_PLUGIN_H - -#ifdef TOOLS_ENABLED -#include "editor/editor_node.h" -#include "gdnative.h" - -class GDNativeLibraryEditor : public Control { - GDCLASS(GDNativeLibraryEditor, Control); - - struct NativePlatformConfig { - String name; - String library_extension; - List<String> entries; - }; - - struct TargetConfig { - String library; - Array dependencies; - }; - - enum ItemButton { - BUTTON_SELECT_LIBRARY, - BUTTON_CLEAR_LIBRARY, - BUTTON_SELECT_DEPENDENCES, - BUTTON_CLEAR_DEPENDENCES, - BUTTON_ERASE_ENTRY, - BUTTON_MOVE_UP, - BUTTON_MOVE_DOWN, - }; - - Tree *tree; - MenuButton *filter; - EditorFileDialog *file_dialog; - ConfirmationDialog *new_architecture_dialog; - LineEdit *new_architecture_input; - Set<String> collapsed_items; - - String showing_platform; - Ref<GDNativeLibrary> library; - Map<String, NativePlatformConfig> platforms; - Map<String, TargetConfig> entry_configs; - -protected: - static void _bind_methods(); - void _update_tree(); - void _on_item_button(Object *item, int column, int id); - void _on_library_selected(const String &file); - void _on_dependencies_selected(const PackedStringArray &files); - void _on_filter_selected(int id); - void _on_item_collapsed(Object *p_item); - void _on_item_activated(); - void _on_create_new_entry(); - void _set_target_value(const String §ion, const String &target, Variant file); - void _erase_entry(const String &platform, const String &entry); - void _move_entry(const String &platform, const String &entry, int dir); - void _translate_to_config_file(); - -public: - void edit(Ref<GDNativeLibrary> p_library); - - GDNativeLibraryEditor(); -}; - -class GDNativeLibraryEditorPlugin : public EditorPlugin { - GDCLASS(GDNativeLibraryEditorPlugin, EditorPlugin); - - GDNativeLibraryEditor *library_editor = nullptr; - EditorNode *editor = nullptr; - Button *button = nullptr; - -public: - virtual String get_name() const override { return "GDNativeLibrary"; } - bool has_main_screen() const override { return false; } - virtual void edit(Object *p_node) override; - virtual bool handles(Object *p_node) const override; - virtual void make_visible(bool p_visible) override; - - GDNativeLibraryEditorPlugin(EditorNode *p_node); -}; -#endif -#endif // GDNATIVE_LIBRARY_EDITOR_PLUGIN_H diff --git a/modules/gdnative/gdnative_library_singleton_editor.cpp b/modules/gdnative/gdnative_library_singleton_editor.cpp deleted file mode 100644 index 6eb412eccb..0000000000 --- a/modules/gdnative/gdnative_library_singleton_editor.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/*************************************************************************/ -/* gdnative_library_singleton_editor.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 TOOLS_ENABLED -#include "gdnative_library_singleton_editor.h" -#include "gdnative.h" - -#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") { - 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 = _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(); - } -} - -void GDNativeLibrarySingletonEditor::_update_libraries() { - updating = true; - libraries->clear(); - libraries->create_item(); // root item - - Array singletons; - if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { - singletons = ProjectSettings::get_singleton()->get("gdnative/singletons"); - } - Array singletons_disabled; - if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons_disabled")) { - singletons_disabled = ProjectSettings::get_singleton()->get("gdnative/singletons_disabled"); - } - - 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; -} - -void GDNativeLibrarySingletonEditor::_item_edited() { - if (updating) { - return; - } - - TreeItem *item = libraries->get_edited(); - if (!item) { - return; - } - - bool enabled = item->get_range(1); - String path = item->get_metadata(0); - - 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) { - disabled_paths.erase(path); - } else { - if (disabled_paths.find(path) == -1) { - disabled_paths.push_back(path); - } - } - - 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) { - if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { - if (is_visible_in_tree()) { - _update_libraries(); - } - } -} - -void GDNativeLibrarySingletonEditor::_bind_methods() { - 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); - libraries->set_column_title(0, TTR("Library")); - libraries->set_column_title(1, TTR("Status")); - libraries->set_hide_root(true); - add_margin_child(TTR("Libraries: "), libraries, true); - updating = false; - libraries->connect("item_edited", callable_mp(this, &GDNativeLibrarySingletonEditor::_item_edited)); - EditorFileSystem::get_singleton()->connect("filesystem_changed", callable_mp(this, &GDNativeLibrarySingletonEditor::_discover_singletons)); -} - -#endif // TOOLS_ENABLED diff --git a/modules/gdnative/icons/GDNativeLibrary.svg b/modules/gdnative/icons/GDNativeLibrary.svg deleted file mode 100644 index 0ddfd4e6f2..0000000000 --- a/modules/gdnative/icons/GDNativeLibrary.svg +++ /dev/null @@ -1 +0,0 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7 1-.56445 2.2578a5 5 0 0 0 -.68945.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -.28516.68555l-2.2539.5625v2l2.2578.56445a5 5 0 0 0 .2793.6875l-1.1934 1.9902 1.4141 1.4141 1.9941-1.1953a5 5 0 0 0 .68555.28516l.5625 2.2539v-5.2695a2 2 0 0 1 -1-1.7305 2 2 0 0 1 1-1.7285v-.27148h1 4.5762a5 5 0 0 0 -.11328-.25195l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -.68555-.28516l-.5625-2.2539h-2zm2 7v1 5 1h5c.55228 0 1-.4477 1-1v-5c0-.5523-.44772-1-1-1v4l-1-1-1 1v-4z" fill="#e0e0e0"/></svg> diff --git a/modules/gdnative/icons/NativeScript.svg b/modules/gdnative/icons/NativeScript.svg deleted file mode 100644 index 2224b36b29..0000000000 --- a/modules/gdnative/icons/NativeScript.svg +++ /dev/null @@ -1 +0,0 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7 1-.56445 2.2578a5 5 0 0 0 -.68945.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -.28516.68555l-2.2539.5625h3v1 1h2v-.95117a2 2 0 0 1 0-.048828 2 2 0 0 1 2-2 2 2 0 0 1 2 2v1h5v-2l-2.2578-.56445a5 5 0 0 0 -.2793-.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -.68555-.28516l-.5625-2.2539h-2zm-6 7v4 4h2a3 3 0 0 0 3-3 3 3 0 0 0 -3-3v-2zm6 0v2h2v-2zm3 2v6h2v-4a1 1 0 0 1 1 1v3h2v-3a3 3 0 0 0 -3-3zm-7 2a1 1 0 0 1 1 1 1 1 0 0 1 -1 1zm4 0v4h2v-4z" fill="#e0e0e0"/></svg> diff --git a/modules/gdnative/include/android/godot_android.h b/modules/gdnative/include/android/godot_android.h deleted file mode 100644 index 859a85ae1e..0000000000 --- a/modules/gdnative/include/android/godot_android.h +++ /dev/null @@ -1,56 +0,0 @@ -/*************************************************************************/ -/* godot_android.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_ANDROID_GDN_H -#define GODOT_ANDROID_GDN_H - -#include <gdnative/gdnative.h> - -#ifdef __ANDROID__ -#include <jni.h> -#else -#define JNIEnv void -#define jobject void * -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -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 -} -#endif - -#endif /* !GODOT_ANDROID_GDN_H */ diff --git a/modules/gdnative/include/gdnative/aabb.h b/modules/gdnative/include/gdnative/aabb.h deleted file mode 100644 index 67818f61c8..0000000000 --- a/modules/gdnative/include/gdnative/aabb.h +++ /dev/null @@ -1,58 +0,0 @@ -/*************************************************************************/ -/* aabb.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_AABB_H -#define GODOT_AABB_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_AABB_SIZE (sizeof(godot_real_t) * 6) - -#ifndef GODOT_CORE_API_GODOT_AABB_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_AABB_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_AABB_SIZE]; -} godot_aabb; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_aabb_new(godot_aabb *p_self); -void GDAPI godot_aabb_new_copy(godot_aabb *r_dest, const godot_aabb *p_src); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_AABB_H diff --git a/modules/gdnative/include/gdnative/array.h b/modules/gdnative/include/gdnative/array.h deleted file mode 100644 index cee641a7c5..0000000000 --- a/modules/gdnative/include/gdnative/array.h +++ /dev/null @@ -1,62 +0,0 @@ -/*************************************************************************/ -/* array.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_ARRAY_H -#define GODOT_ARRAY_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> - -#define GODOT_ARRAY_SIZE sizeof(void *) - -#ifndef GODOT_CORE_API_GODOT_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_ARRAY_SIZE]; -} godot_array; -#endif - -#include <gdnative/gdnative.h> -#include <gdnative/variant_struct.h> - -void GDAPI godot_array_new(godot_array *p_self); -void GDAPI godot_array_new_copy(godot_array *r_dest, const godot_array *p_src); -void GDAPI godot_array_destroy(godot_array *p_self); -godot_variant GDAPI *godot_array_operator_index(godot_array *p_self, godot_int p_index); -const godot_variant GDAPI *godot_array_operator_index_const(const godot_array *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_ARRAY_H diff --git a/modules/gdnative/include/gdnative/basis.h b/modules/gdnative/include/gdnative/basis.h deleted file mode 100644 index 50c9aa6408..0000000000 --- a/modules/gdnative/include/gdnative/basis.h +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************/ -/* basis.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_BASIS_H -#define GODOT_BASIS_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_BASIS_SIZE (sizeof(godot_real_t) * 9) - -#ifndef GODOT_CORE_API_GODOT_BASIS_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_BASIS_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_BASIS_SIZE]; -} godot_basis; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_basis_new(godot_basis *p_self); -void GDAPI godot_basis_new_copy(godot_basis *r_dest, const godot_basis *p_src); -godot_vector3 GDAPI *godot_basis_operator_index(godot_basis *p_self, godot_int p_index); -const godot_vector3 GDAPI *godot_basis_operator_index_const(const godot_basis *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_BASIS_H diff --git a/modules/gdnative/include/gdnative/callable.h b/modules/gdnative/include/gdnative/callable.h deleted file mode 100644 index db068d2ac7..0000000000 --- a/modules/gdnative/include/gdnative/callable.h +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************/ -/* callable.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_CALLABLE_H -#define GODOT_CALLABLE_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> - -// Alignment hardcoded in `core/variant/callable.h`. -#define GODOT_CALLABLE_SIZE (16) - -#ifndef GODOT_CORE_API_GODOT_CALLABLE_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_CALLABLE_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_CALLABLE_SIZE]; -} godot_callable; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_callable_new(godot_callable *p_self); -void GDAPI godot_callable_new_copy(godot_callable *r_dest, const godot_callable *p_src); -void GDAPI godot_callable_destroy(godot_callable *p_self); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/modules/gdnative/include/gdnative/color.h b/modules/gdnative/include/gdnative/color.h deleted file mode 100644 index 2d64a323f9..0000000000 --- a/modules/gdnative/include/gdnative/color.h +++ /dev/null @@ -1,61 +0,0 @@ -/*************************************************************************/ -/* color.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_COLOR_H -#define GODOT_COLOR_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -// Colors should always use 32-bit floats, so don't use real_t here. -#define GODOT_COLOR_SIZE (sizeof(float) * 4) - -#ifndef GODOT_CORE_API_GODOT_COLOR_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_COLOR_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_COLOR_SIZE]; -} godot_color; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_color_new(godot_color *p_self); -void GDAPI godot_color_new_copy(godot_color *r_dest, const godot_color *p_src); -float GDAPI *godot_color_operator_index(godot_color *p_self, godot_int p_index); -const float GDAPI *godot_color_operator_index_const(const godot_color *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_COLOR_H diff --git a/modules/gdnative/include/gdnative/dictionary.h b/modules/gdnative/include/gdnative/dictionary.h deleted file mode 100644 index 4219753f71..0000000000 --- a/modules/gdnative/include/gdnative/dictionary.h +++ /dev/null @@ -1,62 +0,0 @@ -/*************************************************************************/ -/* dictionary.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_DICTIONARY_H -#define GODOT_DICTIONARY_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> - -#define GODOT_DICTIONARY_SIZE sizeof(void *) - -#ifndef GODOT_CORE_API_GODOT_DICTIONARY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_DICTIONARY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_DICTIONARY_SIZE]; -} godot_dictionary; -#endif - -#include <gdnative/gdnative.h> -#include <gdnative/variant_struct.h> - -void GDAPI godot_dictionary_new(godot_dictionary *p_self); -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_variant GDAPI *godot_dictionary_operator_index(godot_dictionary *p_self, const godot_variant *p_key); -const godot_variant GDAPI *godot_dictionary_operator_index_const(const godot_dictionary *p_self, const godot_variant *p_key); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_DICTIONARY_H diff --git a/modules/gdnative/include/gdnative/gdnative.h b/modules/gdnative/include/gdnative/gdnative.h deleted file mode 100644 index b46a00c185..0000000000 --- a/modules/gdnative/include/gdnative/gdnative.h +++ /dev/null @@ -1,287 +0,0 @@ -/*************************************************************************/ -/* gdnative.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_GDNATIVE_H -#define GODOT_GDNATIVE_H - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_WIN32) || defined(__ANDROID__) -#define GDCALLINGCONV -#define GDAPI GDCALLINGCONV -#elif defined(__APPLE__) -#include "TargetConditionals.h" -#if TARGET_OS_IPHONE -#define GDCALLINGCONV __attribute__((visibility("default"))) -#define GDAPI GDCALLINGCONV -#elif TARGET_OS_MAC -#define GDCALLINGCONV __attribute__((sysv_abi)) -#define GDAPI GDCALLINGCONV -#endif -#else // !_WIN32 && !__APPLE__ -#define GDCALLINGCONV __attribute__((sysv_abi)) -#define GDAPI GDCALLINGCONV -#endif - -// This is for libraries *using* the header, NOT GODOT EXPOSING STUFF!! -#ifdef __GNUC__ -#define GDN_EXPORT __attribute__((visibility("default"))) -#elif defined(_WIN32) -#define GDN_EXPORT __declspec(dllexport) -#else -#define GDN_EXPORT -#endif - -#include <stdbool.h> -#include <stdint.h> - -////// Error - -typedef enum { - 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 - GODOT_ERR_UNAUTHORIZED, ///< Missing credentials for requested resource - GODOT_ERR_PARAMETER_RANGE_ERROR, ///< Parameter given out of range (5) - GODOT_ERR_OUT_OF_MEMORY, ///< Out of memory - GODOT_ERR_FILE_NOT_FOUND, - GODOT_ERR_FILE_BAD_DRIVE, - GODOT_ERR_FILE_BAD_PATH, - GODOT_ERR_FILE_NO_PERMISSION, // (10) - GODOT_ERR_FILE_ALREADY_IN_USE, - GODOT_ERR_FILE_CANT_OPEN, - GODOT_ERR_FILE_CANT_WRITE, - GODOT_ERR_FILE_CANT_READ, - GODOT_ERR_FILE_UNRECOGNIZED, // (15) - GODOT_ERR_FILE_CORRUPT, - GODOT_ERR_FILE_MISSING_DEPENDENCIES, - GODOT_ERR_FILE_EOF, - GODOT_ERR_CANT_OPEN, ///< Can't open a resource/socket/file - GODOT_ERR_CANT_CREATE, // (20) - GODOT_ERR_QUERY_FAILED, - GODOT_ERR_ALREADY_IN_USE, - GODOT_ERR_LOCKED, ///< resource is locked - GODOT_ERR_TIMEOUT, - GODOT_ERR_CANT_CONNECT, // (25) - GODOT_ERR_CANT_RESOLVE, - 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_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_COMPILATION_FAILED, - GODOT_ERR_METHOD_NOT_FOUND, - GODOT_ERR_LINK_FAILED, - GODOT_ERR_SCRIPT_FAILED, - GODOT_ERR_CYCLIC_LINK, // (40) - GODOT_ERR_INVALID_DECLARATION, - GODOT_ERR_DUPLICATE_SYMBOL, - GODOT_ERR_PARSE_ERROR, - GODOT_ERR_BUSY, - GODOT_ERR_SKIP, // (45) - GODOT_ERR_HELP, ///< user requested help!! - GODOT_ERR_BUG, ///< a bug in the software certainly happened, due to a double check failing or unexpected behavior. - GODOT_ERR_PRINTER_ON_FIRE, /// the parallel port printer is engulfed in flames -} godot_error; - -/////// Object (forward declared) -typedef void godot_object; - -/////// String - -#include <gdnative/string.h> - -/////// String name - -#include <gdnative/string_name.h> - -////// Vector2 & Vector2i - -#include <gdnative/vector2.h> - -////// Rect2 & Rect2i - -#include <gdnative/rect2.h> - -////// Vector3 & Vector3i - -#include <gdnative/vector3.h> - -////// Transform2D - -#include <gdnative/transform2d.h> - -/////// Plane - -#include <gdnative/plane.h> - -/////// Quaternion - -#include <gdnative/quaternion.h> - -/////// AABB - -#include <gdnative/aabb.h> - -/////// Basis - -#include <gdnative/basis.h> - -/////// Transform3D - -#include <gdnative/transform_3d.h> - -/////// Color - -#include <gdnative/color.h> - -/////// NodePath - -#include <gdnative/node_path.h> - -/////// RID - -#include <gdnative/rid.h> - -/////// Callable & Signal - -#include <gdnative/callable.h> - -/////// Dictionary - -#include <gdnative/dictionary.h> - -/////// Array - -#include <gdnative/array.h> - -// single API file for Packed*Array -#include <gdnative/packed_arrays.h> - -void GDAPI godot_object_destroy(godot_object *p_o); - -////// Variant - -#include <gdnative/variant.h> - -////// Singleton API - -godot_object GDAPI *godot_global_get_singleton(char *p_name); // Result shouldn't be freed. - -////// MethodBind API - -typedef struct { - uint8_t _dont_touch_that[1]; // TODO -} godot_method_bind; - -godot_method_bind GDAPI *godot_method_bind_get_method(const char *p_classname, const char *p_methodname); -void GDAPI godot_method_bind_ptrcall(godot_method_bind *p_method_bind, godot_object *p_instance, const void **p_args, void *p_ret); -godot_variant GDAPI godot_method_bind_call(godot_method_bind *p_method_bind, godot_object *p_instance, const godot_variant **p_args, const int p_arg_count, godot_variant_call_error *p_call_error); -////// Script API - -typedef struct godot_gdnative_api_version { - unsigned int major; - unsigned int minor; -} godot_gdnative_api_version; - -typedef struct godot_gdnative_api_struct godot_gdnative_api_struct; - -struct godot_gdnative_api_struct { - unsigned int type; - godot_gdnative_api_version version; - const godot_gdnative_api_struct *next; -}; - -#define GDNATIVE_VERSION_COMPATIBLE(want, have) (want.major == have.major && want.minor <= have.minor) - -typedef struct { - godot_bool in_editor; - uint64_t core_api_hash; - uint64_t editor_api_hash; - uint64_t no_api_hash; - void (*report_version_mismatch)(const godot_object *p_library, const char *p_what, godot_gdnative_api_version p_want, godot_gdnative_api_version p_have); - void (*report_loading_error)(const godot_object *p_library, const char *p_what); - godot_object *gd_native_library; // pointer to GDNativeLibrary that is being initialized - const struct godot_gdnative_core_api_struct *api_struct; - const godot_string *active_library_path; -} godot_gdnative_init_options; - -typedef struct { - godot_bool in_editor; -} godot_gdnative_terminate_options; - -// Calling convention? -typedef godot_object *(*godot_class_constructor)(); - -godot_class_constructor GDAPI godot_get_class_constructor(const char *p_classname); - -godot_dictionary GDAPI godot_get_global_constants(); - -////// GDNative procedure types -typedef void (*godot_gdnative_init_fn)(godot_gdnative_init_options *); -typedef void (*godot_gdnative_terminate_fn)(godot_gdnative_terminate_options *); -typedef godot_variant (*godot_gdnative_procedure_fn)(godot_array *); - -////// System Functions - -typedef godot_variant (*native_call_cb)(void *, godot_array *); -void GDAPI godot_register_native_call_type(const char *p_call_type, native_call_cb p_callback); - -//using these will help Godot track how much memory is in use in debug mode -void GDAPI *godot_alloc(int p_bytes); -void GDAPI *godot_realloc(void *p_ptr, int p_bytes); -void GDAPI godot_free(void *p_ptr); - -// Helper print functions. -void GDAPI godot_print_error(const char *p_description, const char *p_function, const char *p_file, int p_line); -void GDAPI godot_print_warning(const char *p_description, const char *p_function, const char *p_file, int p_line); -void GDAPI godot_print_script_error(const char *p_description, const char *p_function, const char *p_file, int p_line); - -//tags used for safe dynamic casting -void GDAPI *godot_get_class_tag(const godot_string_name *p_class); -godot_object GDAPI *godot_object_cast_to(const godot_object *p_object, void *p_class_tag); - -// equivalent of GDScript's instance_from_id -godot_object GDAPI *godot_instance_from_id(uint64_t p_instance_id); - -uint64_t GDAPI godot_object_get_instance_id(const godot_object *p_object); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_GDNATIVE_H diff --git a/modules/gdnative/include/gdnative/math_defs.h b/modules/gdnative/include/gdnative/math_defs.h deleted file mode 100644 index dee027527e..0000000000 --- a/modules/gdnative/include/gdnative/math_defs.h +++ /dev/null @@ -1,66 +0,0 @@ -/*************************************************************************/ -/* math_defs.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_GDNATIVE_MATH_DEFS_H -#define GODOT_GDNATIVE_MATH_DEFS_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdbool.h> -#include <stdint.h> - -////// bool - -typedef bool godot_bool; - -#define GODOT_TRUE 1 -#define GODOT_FALSE 0 - -/////// int - -typedef int64_t godot_int; - -/////// float - -typedef double godot_float; - -#ifdef REAL_T_IS_DOUBLE -typedef double godot_real_t; -#else -typedef float godot_real_t; -#endif - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_C_H diff --git a/modules/gdnative/include/gdnative/node_path.h b/modules/gdnative/include/gdnative/node_path.h deleted file mode 100644 index 46b693dcf6..0000000000 --- a/modules/gdnative/include/gdnative/node_path.h +++ /dev/null @@ -1,59 +0,0 @@ -/*************************************************************************/ -/* node_path.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_NODE_PATH_H -#define GODOT_NODE_PATH_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> - -#define GODOT_NODE_PATH_SIZE sizeof(void *) - -#ifndef GODOT_CORE_API_GODOT_NODE_PATH_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_NODE_PATH_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_NODE_PATH_SIZE]; -} godot_node_path; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_node_path_new(godot_node_path *p_self); -void GDAPI godot_node_path_new_copy(godot_node_path *r_dest, const godot_node_path *p_src); -void GDAPI godot_node_path_destroy(godot_node_path *p_self); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_NODE_PATH_H diff --git a/modules/gdnative/include/gdnative/packed_arrays.h b/modules/gdnative/include/gdnative/packed_arrays.h deleted file mode 100644 index f4935ee0dc..0000000000 --- a/modules/gdnative/include/gdnative/packed_arrays.h +++ /dev/null @@ -1,255 +0,0 @@ -/*************************************************************************/ -/* packed_arrays.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_PACKED_ARRAYS_H -#define GODOT_PACKED_ARRAYS_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> - -/////// PackedByteArray - -#define GODOT_PACKED_BYTE_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_BYTE_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_BYTE_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_BYTE_ARRAY_SIZE]; -} godot_packed_byte_array; -#endif - -/////// PackedInt32Array - -#define GODOT_PACKED_INT32_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_INT32_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_INT32_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_INT32_ARRAY_SIZE]; -} godot_packed_int32_array; -#endif - -/////// PackedInt64Array - -#define GODOT_PACKED_INT64_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_INT64_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_INT64_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_INT64_ARRAY_SIZE]; -} godot_packed_int64_array; -#endif - -/////// PackedFloat32Array - -#define GODOT_PACKED_FLOAT32_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_FLOAT32_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_FLOAT32_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_FLOAT32_ARRAY_SIZE]; -} godot_packed_float32_array; -#endif - -/////// PackedFloat64Array - -#define GODOT_PACKED_FLOAT64_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_FLOAT64_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_FLOAT64_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_FLOAT64_ARRAY_SIZE]; -} godot_packed_float64_array; -#endif - -/////// PackedStringArray - -#define GODOT_PACKED_STRING_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_STRING_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_STRING_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_STRING_ARRAY_SIZE]; -} godot_packed_string_array; -#endif - -/////// PackedVector2Array - -#define GODOT_PACKED_VECTOR2_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR2_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_VECTOR2_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_VECTOR2_ARRAY_SIZE]; -} godot_packed_vector2_array; -#endif - -/////// PackedVector2iArray - -#define GODOT_PACKED_VECTOR2I_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR2I_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_VECTOR2I_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_VECTOR2I_ARRAY_SIZE]; -} godot_packed_vector2i_array; -#endif - -/////// PackedVector3Array - -#define GODOT_PACKED_VECTOR3_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR3_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_VECTOR3_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_VECTOR3_ARRAY_SIZE]; -} godot_packed_vector3_array; -#endif - -/////// PackedVector3iArray - -#define GODOT_PACKED_VECTOR3I_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR3I_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_VECTOR3I_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_VECTOR3I_ARRAY_SIZE]; -} godot_packed_vector3i_array; -#endif - -/////// PackedColorArray - -#define GODOT_PACKED_COLOR_ARRAY_SIZE (2 * sizeof(void *)) - -#ifndef GODOT_CORE_API_GODOT_PACKED_COLOR_ARRAY_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PACKED_COLOR_ARRAY_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PACKED_COLOR_ARRAY_SIZE]; -} godot_packed_color_array; -#endif - -#include <gdnative/gdnative.h> - -// Byte. - -void GDAPI godot_packed_byte_array_new(godot_packed_byte_array *p_self); -void GDAPI godot_packed_byte_array_new_copy(godot_packed_byte_array *r_dest, const godot_packed_byte_array *p_src); -void GDAPI godot_packed_byte_array_destroy(godot_packed_byte_array *p_self); -uint8_t GDAPI *godot_packed_byte_array_operator_index(godot_packed_byte_array *p_self, godot_int p_index); -const uint8_t GDAPI *godot_packed_byte_array_operator_index_const(const godot_packed_byte_array *p_self, godot_int p_index); - -// Int32. - -void GDAPI godot_packed_int32_array_new(godot_packed_int32_array *p_self); -void GDAPI godot_packed_int32_array_new_copy(godot_packed_int32_array *r_dest, const godot_packed_int32_array *p_src); -void GDAPI godot_packed_int32_array_destroy(godot_packed_int32_array *p_self); -int32_t GDAPI *godot_packed_int32_array_operator_index(godot_packed_int32_array *p_self, godot_int p_index); -const int32_t GDAPI *godot_packed_int32_array_operator_index_const(const godot_packed_int32_array *p_self, godot_int p_index); - -// Int64. - -void GDAPI godot_packed_int64_array_new(godot_packed_int64_array *p_self); -void GDAPI godot_packed_int64_array_new_copy(godot_packed_int64_array *r_dest, const godot_packed_int64_array *p_src); -void GDAPI godot_packed_int64_array_destroy(godot_packed_int64_array *p_self); -int64_t GDAPI *godot_packed_int64_array_operator_index(godot_packed_int64_array *p_self, godot_int p_index); -const int64_t GDAPI *godot_packed_int64_array_operator_index_const(const godot_packed_int64_array *p_self, godot_int p_index); - -// Float32. - -void GDAPI godot_packed_float32_array_new(godot_packed_float32_array *p_self); -void GDAPI godot_packed_float32_array_new_copy(godot_packed_float32_array *r_dest, const godot_packed_float32_array *p_src); -void GDAPI godot_packed_float32_array_destroy(godot_packed_float32_array *p_self); -float GDAPI *godot_packed_float32_array_operator_index(godot_packed_float32_array *p_self, godot_int p_index); -const float GDAPI *godot_packed_float32_array_operator_index_const(const godot_packed_float32_array *p_self, godot_int p_index); - -// Float64. - -void GDAPI godot_packed_float64_array_new(godot_packed_float64_array *p_self); -void GDAPI godot_packed_float64_array_new_copy(godot_packed_float64_array *r_dest, const godot_packed_float64_array *p_src); -void GDAPI godot_packed_float64_array_destroy(godot_packed_float64_array *p_self); -double GDAPI *godot_packed_float64_array_operator_index(godot_packed_float64_array *p_self, godot_int p_index); -const double GDAPI *godot_packed_float64_array_operator_index_const(const godot_packed_float64_array *p_self, godot_int p_index); - -// String. - -void GDAPI godot_packed_string_array_new(godot_packed_string_array *p_self); -void GDAPI godot_packed_string_array_new_copy(godot_packed_string_array *r_dest, const godot_packed_string_array *p_src); -void GDAPI godot_packed_string_array_destroy(godot_packed_string_array *p_self); -godot_string GDAPI *godot_packed_string_array_operator_index(godot_packed_string_array *p_self, godot_int p_index); -const godot_string GDAPI *godot_packed_string_array_operator_index_const(const godot_packed_string_array *p_self, godot_int p_index); - -// Vector2. - -void GDAPI godot_packed_vector2_array_new(godot_packed_vector2_array *p_self); -void GDAPI godot_packed_vector2_array_new_copy(godot_packed_vector2_array *r_dest, const godot_packed_vector2_array *p_src); -void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self); -godot_vector2 GDAPI *godot_packed_vector2_array_operator_index(godot_packed_vector2_array *p_self, godot_int p_index); -const godot_vector2 GDAPI *godot_packed_vector2_array_operator_index_const(const godot_packed_vector2_array *p_self, godot_int p_index); - -// Vector2i. - -void GDAPI godot_packed_vector2i_array_new(godot_packed_vector2i_array *p_self); -void GDAPI godot_packed_vector2i_array_new_copy(godot_packed_vector2i_array *r_dest, const godot_packed_vector2i_array *p_src); -void GDAPI godot_packed_vector2i_array_destroy(godot_packed_vector2i_array *p_self); -godot_vector2i GDAPI *godot_packed_vector2i_array_operator_index(godot_packed_vector2i_array *p_self, godot_int p_index); -const godot_vector2i GDAPI *godot_packed_vector2i_array_operator_index_const(const godot_packed_vector2i_array *p_self, godot_int p_index); - -// Vector3. - -void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *p_self); -void GDAPI godot_packed_vector3_array_new_copy(godot_packed_vector3_array *r_dest, const godot_packed_vector3_array *p_src); -void GDAPI godot_packed_vector3_array_destroy(godot_packed_vector3_array *p_self); -godot_vector3 GDAPI *godot_packed_vector3_array_operator_index(godot_packed_vector3_array *p_self, godot_int p_index); -const godot_vector3 GDAPI *godot_packed_vector3_array_operator_index_const(const godot_packed_vector3_array *p_self, godot_int p_index); - -// Vector3i. - -void GDAPI godot_packed_vector3i_array_new(godot_packed_vector3i_array *p_self); -void GDAPI godot_packed_vector3i_array_new_copy(godot_packed_vector3i_array *r_dest, const godot_packed_vector3i_array *p_src); -void GDAPI godot_packed_vector3i_array_destroy(godot_packed_vector3i_array *p_self); -godot_vector3i GDAPI *godot_packed_vector3i_array_operator_index(godot_packed_vector3i_array *p_self, godot_int p_index); -const godot_vector3i GDAPI *godot_packed_vector3i_array_operator_index_const(const godot_packed_vector3i_array *p_self, godot_int p_index); - -// Color. - -void GDAPI godot_packed_color_array_new(godot_packed_color_array *p_self); -void GDAPI godot_packed_color_array_new_copy(godot_packed_color_array *r_dest, const godot_packed_color_array *p_src); -void GDAPI godot_packed_color_array_destroy(godot_packed_color_array *p_self); -godot_color GDAPI *godot_packed_color_array_operator_index(godot_packed_color_array *p_self, godot_int p_index); -const godot_color GDAPI *godot_packed_color_array_operator_index_const(const godot_packed_color_array *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_PACKED_ARRAYS_H diff --git a/modules/gdnative/include/gdnative/plane.h b/modules/gdnative/include/gdnative/plane.h deleted file mode 100644 index e8f4f13b99..0000000000 --- a/modules/gdnative/include/gdnative/plane.h +++ /dev/null @@ -1,58 +0,0 @@ -/*************************************************************************/ -/* plane.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_PLANE_H -#define GODOT_PLANE_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_PLANE_SIZE (sizeof(godot_real_t) * 4) - -#ifndef GODOT_CORE_API_GODOT_PLANE_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_PLANE_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_PLANE_SIZE]; -} godot_plane; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_plane_new(godot_plane *p_self); -void GDAPI godot_plane_new_copy(godot_plane *r_dest, const godot_plane *p_src); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_PLANE_H diff --git a/modules/gdnative/include/gdnative/quaternion.h b/modules/gdnative/include/gdnative/quaternion.h deleted file mode 100644 index 80e99c3a7c..0000000000 --- a/modules/gdnative/include/gdnative/quaternion.h +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************/ -/* quaternion.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_QUATERNION_H -#define GODOT_QUATERNION_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_QUATERNION_SIZE (sizeof(godot_real_t) * 4) - -#ifndef GODOT_CORE_API_GODOT_QUATERNION_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_QUATERNION_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_QUATERNION_SIZE]; -} godot_quaternion; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_quaternion_new(godot_quaternion *p_self); -void GDAPI godot_quaternion_new_copy(godot_quaternion *r_dest, const godot_quaternion *p_src); -godot_real_t GDAPI *godot_quaternion_operator_index(godot_quaternion *p_self, godot_int p_index); -const godot_real_t GDAPI *godot_quaternion_operator_index_const(const godot_quaternion *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_QUATERNION_H diff --git a/modules/gdnative/include/gdnative/rect2.h b/modules/gdnative/include/gdnative/rect2.h deleted file mode 100644 index a901537fc4..0000000000 --- a/modules/gdnative/include/gdnative/rect2.h +++ /dev/null @@ -1,69 +0,0 @@ -/*************************************************************************/ -/* rect2.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_RECT2_H -#define GODOT_RECT2_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_RECT2_SIZE (sizeof(godot_real_t) * 4) - -#ifndef GODOT_CORE_API_GODOT_RECT2_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_RECT2_TYPE_DEFINED -typedef struct godot_rect2 { - uint8_t _dont_touch_that[GODOT_RECT2_SIZE]; -} godot_rect2; -#endif - -#define GODOT_RECT2I_SIZE (sizeof(int32_t) * 4) - -#ifndef GODOT_CORE_API_GODOT_RECT2I_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_RECT2I_TYPE_DEFINED -typedef struct godot_rect2i { - uint8_t _dont_touch_that[GODOT_RECT2I_SIZE]; -} godot_rect2i; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_rect2_new(godot_rect2 *p_self); -void GDAPI godot_rect2_new_copy(godot_rect2 *r_dest, const godot_rect2 *p_src); -void GDAPI godot_rect2i_new(godot_rect2i *p_self); -void GDAPI godot_rect2i_new_copy(godot_rect2i *r_dest, const godot_rect2i *p_src); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_RECT2_H diff --git a/modules/gdnative/include/gdnative/rid.h b/modules/gdnative/include/gdnative/rid.h deleted file mode 100644 index f3013f36f0..0000000000 --- a/modules/gdnative/include/gdnative/rid.h +++ /dev/null @@ -1,58 +0,0 @@ -/*************************************************************************/ -/* rid.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_RID_H -#define GODOT_RID_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> - -#define GODOT_RID_SIZE sizeof(uint64_t) - -#ifndef GODOT_CORE_API_GODOT_RID_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_RID_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_RID_SIZE]; -} godot_rid; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_rid_new(godot_rid *p_self); -void GDAPI godot_rid_new_copy(godot_rid *r_dest, const godot_rid *p_src); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_RID_H diff --git a/modules/gdnative/include/gdnative/signal.h b/modules/gdnative/include/gdnative/signal.h deleted file mode 100644 index 64aef1c918..0000000000 --- a/modules/gdnative/include/gdnative/signal.h +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************/ -/* signal.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_SIGNAL_H -#define GODOT_SIGNAL_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> - -// Alignment hardcoded in `core/variant/callable.h`. -#define GODOT_SIGNAL_SIZE (16) - -#ifndef GODOT_CORE_API_GODOT_SIGNAL_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_SIGNAL_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_SIGNAL_SIZE]; -} godot_signal; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_signal_new(godot_signal *p_self); -void GDAPI godot_signal_new_copy(godot_signal *r_dest, const godot_signal *p_src); -void GDAPI godot_signal_destroy(godot_signal *p_self); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/modules/gdnative/include/gdnative/string.h b/modules/gdnative/include/gdnative/string.h deleted file mode 100644 index 375e8f94c3..0000000000 --- a/modules/gdnative/include/gdnative/string.h +++ /dev/null @@ -1,89 +0,0 @@ -/*************************************************************************/ -/* string.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_STRING_H -#define GODOT_STRING_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stddef.h> -#include <stdint.h> - -#ifndef __cplusplus -typedef uint16_t char16_t; -typedef uint32_t char32_t; -#endif - -typedef char32_t godot_char_type; - -#define GODOT_STRING_SIZE sizeof(void *) - -#ifndef GODOT_CORE_API_GODOT_STRING_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_STRING_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_STRING_SIZE]; -} godot_string; -#endif - -#include <gdnative/gdnative.h> -#include <gdnative/math_defs.h> - -void GDAPI godot_string_new(godot_string *r_dest); -void GDAPI godot_string_new_copy(godot_string *r_dest, const godot_string *p_src); -void GDAPI godot_string_destroy(godot_string *p_self); - -void GDAPI godot_string_new_with_latin1_chars(godot_string *r_dest, const char *p_contents); -void GDAPI godot_string_new_with_utf8_chars(godot_string *r_dest, const char *p_contents); -void GDAPI godot_string_new_with_utf16_chars(godot_string *r_dest, const char16_t *p_contents); -void GDAPI godot_string_new_with_utf32_chars(godot_string *r_dest, const char32_t *p_contents); -void GDAPI godot_string_new_with_wide_chars(godot_string *r_dest, const wchar_t *p_contents); - -void GDAPI godot_string_new_with_latin1_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size); -void GDAPI godot_string_new_with_utf8_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size); -void GDAPI godot_string_new_with_utf16_chars_and_len(godot_string *r_dest, const char16_t *p_contents, const int p_size); -void GDAPI godot_string_new_with_utf32_chars_and_len(godot_string *r_dest, const char32_t *p_contents, const int p_size); -void GDAPI godot_string_new_with_wide_chars_and_len(godot_string *r_dest, const wchar_t *p_contents, const int p_size); - -const char GDAPI *godot_string_to_latin1_chars(const godot_string *p_self); -const char GDAPI *godot_string_to_utf8_chars(const godot_string *p_self); -const char16_t GDAPI *godot_string_to_utf16_chars(const godot_string *p_self); -const char32_t GDAPI *godot_string_to_utf32_chars(const godot_string *p_self); -const wchar_t GDAPI *godot_string_to_wide_chars(const godot_string *p_self); - -char32_t GDAPI *godot_string_operator_index(godot_string *p_self, godot_int p_index); -const char32_t GDAPI *godot_string_operator_index_const(const godot_string *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_STRING_H diff --git a/modules/gdnative/include/gdnative/string_name.h b/modules/gdnative/include/gdnative/string_name.h deleted file mode 100644 index 6f4d9c64fe..0000000000 --- a/modules/gdnative/include/gdnative/string_name.h +++ /dev/null @@ -1,62 +0,0 @@ -/*************************************************************************/ -/* string_name.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_STRING_NAME_H -#define GODOT_STRING_NAME_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdint.h> -#include <wchar.h> - -#define GODOT_STRING_NAME_SIZE sizeof(void *) - -#ifndef GODOT_CORE_API_GODOT_STRING_NAME_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_STRING_NAME_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_STRING_NAME_SIZE]; -} godot_string_name; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_string_name_new(godot_string_name *r_dest); -void GDAPI godot_string_name_new_copy(godot_string_name *r_dest, const godot_string_name *p_src); -void GDAPI godot_string_name_destroy(godot_string_name *p_self); - -void GDAPI godot_string_name_new_with_latin1_chars(godot_string_name *r_dest, const char *p_contents); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_STRING_NAME_H diff --git a/modules/gdnative/include/gdnative/transform2d.h b/modules/gdnative/include/gdnative/transform2d.h deleted file mode 100644 index a083e61a2c..0000000000 --- a/modules/gdnative/include/gdnative/transform2d.h +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************/ -/* transform2d.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_TRANSFORM2D_H -#define GODOT_TRANSFORM2D_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_TRANSFORM2D_SIZE (sizeof(godot_real_t) * 6) - -#ifndef GODOT_CORE_API_GODOT_TRANSFORM2D_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_TRANSFORM2D_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_TRANSFORM2D_SIZE]; -} godot_transform2d; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_transform2d_new(godot_transform2d *p_self); -void GDAPI godot_transform2d_new_copy(godot_transform2d *r_dest, const godot_transform2d *p_src); -godot_vector2 GDAPI *godot_transform2d_operator_index(godot_transform2d *p_self, godot_int p_index); -const godot_vector2 GDAPI *godot_transform2d_operator_index_const(const godot_transform2d *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_TRANSFORM2D_H diff --git a/modules/gdnative/include/gdnative/transform_3d.h b/modules/gdnative/include/gdnative/transform_3d.h deleted file mode 100644 index abd64a4d1d..0000000000 --- a/modules/gdnative/include/gdnative/transform_3d.h +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************/ -/* transform_3d.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_TRANSFORM3D_H -#define GODOT_TRANSFORM3D_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_TRANSFORM3D_SIZE (sizeof(godot_real_t) * 12) - -#ifndef GODOT_CORE_API_GODOT_TRANSFORM3D_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_TRANSFORM3D_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_TRANSFORM3D_SIZE]; -} godot_transform3d; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_transform3d_new(godot_transform3d *p_self); -void GDAPI godot_transform3d_new_copy(godot_transform3d *r_dest, const godot_transform3d *p_src); -godot_vector3 GDAPI *godot_transform3d_operator_index(godot_transform3d *p_self, godot_int p_index); -const godot_vector3 GDAPI *godot_transform3d_operator_index_const(const godot_transform3d *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_TRANSFORM3D_H diff --git a/modules/gdnative/include/gdnative/variant.h b/modules/gdnative/include/gdnative/variant.h deleted file mode 100644 index b716fdaca1..0000000000 --- a/modules/gdnative/include/gdnative/variant.h +++ /dev/null @@ -1,425 +0,0 @@ -/*************************************************************************/ -/* variant.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_VARIANT_H -#define GODOT_VARIANT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> -#include <gdnative/variant_struct.h> - -typedef enum godot_variant_type { - GODOT_VARIANT_TYPE_NIL, - - // atomic types - GODOT_VARIANT_TYPE_BOOL, - GODOT_VARIANT_TYPE_INT, - GODOT_VARIANT_TYPE_FLOAT, - GODOT_VARIANT_TYPE_STRING, - - // math types - GODOT_VARIANT_TYPE_VECTOR2, - GODOT_VARIANT_TYPE_VECTOR2I, - GODOT_VARIANT_TYPE_RECT2, - GODOT_VARIANT_TYPE_RECT2I, - GODOT_VARIANT_TYPE_VECTOR3, - GODOT_VARIANT_TYPE_VECTOR3I, - GODOT_VARIANT_TYPE_TRANSFORM2D, - GODOT_VARIANT_TYPE_PLANE, - GODOT_VARIANT_TYPE_QUATERNION, - GODOT_VARIANT_TYPE_AABB, - GODOT_VARIANT_TYPE_BASIS, - GODOT_VARIANT_TYPE_TRANSFORM3D, - - // misc types - GODOT_VARIANT_TYPE_COLOR, - GODOT_VARIANT_TYPE_STRING_NAME, - GODOT_VARIANT_TYPE_NODE_PATH, - GODOT_VARIANT_TYPE_RID, - GODOT_VARIANT_TYPE_OBJECT, - GODOT_VARIANT_TYPE_CALLABLE, - GODOT_VARIANT_TYPE_SIGNAL, - GODOT_VARIANT_TYPE_DICTIONARY, - GODOT_VARIANT_TYPE_ARRAY, - - // arrays - GODOT_VARIANT_TYPE_PACKED_BYTE_ARRAY, - GODOT_VARIANT_TYPE_PACKED_INT32_ARRAY, - GODOT_VARIANT_TYPE_PACKED_INT64_ARRAY, - GODOT_VARIANT_TYPE_PACKED_FLOAT32_ARRAY, - GODOT_VARIANT_TYPE_PACKED_FLOAT64_ARRAY, - GODOT_VARIANT_TYPE_PACKED_STRING_ARRAY, - GODOT_VARIANT_TYPE_PACKED_VECTOR2_ARRAY, - GODOT_VARIANT_TYPE_PACKED_VECTOR3_ARRAY, - GODOT_VARIANT_TYPE_PACKED_COLOR_ARRAY, -} godot_variant_type; - -typedef enum godot_variant_call_error_error { - GODOT_CALL_ERROR_CALL_OK, - GODOT_CALL_ERROR_CALL_ERROR_INVALID_METHOD, - GODOT_CALL_ERROR_CALL_ERROR_INVALID_ARGUMENT, - GODOT_CALL_ERROR_CALL_ERROR_TOO_MANY_ARGUMENTS, - GODOT_CALL_ERROR_CALL_ERROR_TOO_FEW_ARGUMENTS, - GODOT_CALL_ERROR_CALL_ERROR_INSTANCE_IS_NULL, -} godot_variant_call_error_error; - -typedef struct godot_variant_call_error { - godot_variant_call_error_error error; - int argument; - godot_variant_type expected; -} godot_variant_call_error; - -typedef enum godot_variant_operator { - // comparison - GODOT_VARIANT_OP_EQUAL, - GODOT_VARIANT_OP_NOT_EQUAL, - GODOT_VARIANT_OP_LESS, - GODOT_VARIANT_OP_LESS_EQUAL, - GODOT_VARIANT_OP_GREATER, - GODOT_VARIANT_OP_GREATER_EQUAL, - - // mathematic - GODOT_VARIANT_OP_ADD, - GODOT_VARIANT_OP_SUBTRACT, - GODOT_VARIANT_OP_MULTIPLY, - GODOT_VARIANT_OP_DIVIDE, - GODOT_VARIANT_OP_NEGATE, - GODOT_VARIANT_OP_POSITIVE, - GODOT_VARIANT_OP_MODULE, - GODOT_VARIANT_OP_STRING_CONCAT, - - // bitwise - GODOT_VARIANT_OP_SHIFT_LEFT, - GODOT_VARIANT_OP_SHIFT_RIGHT, - GODOT_VARIANT_OP_BIT_AND, - GODOT_VARIANT_OP_BIT_OR, - GODOT_VARIANT_OP_BIT_XOR, - GODOT_VARIANT_OP_BIT_NEGATE, - - // logic - GODOT_VARIANT_OP_AND, - GODOT_VARIANT_OP_OR, - GODOT_VARIANT_OP_XOR, - GODOT_VARIANT_OP_NOT, - - // containment - GODOT_VARIANT_OP_IN, - - GODOT_VARIANT_OP_MAX, -} godot_variant_operator; - -typedef enum godot_variant_utility_function_type { - GODOT_UTILITY_FUNC_TYPE_MATH, - GODOT_UTILITY_FUNC_TYPE_RANDOM, - GODOT_UTILITY_FUNC_TYPE_GENERAL, -} godot_variant_utility_function_type; - -// Types for function pointers. -typedef void (*godot_validated_operator_evaluator)(const godot_variant *p_left, const godot_variant *p_right, godot_variant *r_result); -typedef void (*godot_ptr_operator_evaluator)(const void *p_left, const void *p_right, void *r_result); -typedef void (*godot_validated_builtin_method)(godot_variant *p_base, const godot_variant **p_args, int p_argument_count, godot_variant *r_return); -typedef void (*godot_ptr_builtin_method)(void *p_base, const void **p_args, void *r_return, int p_argument_count); -typedef void (*godot_validated_constructor)(godot_variant *p_base, const godot_variant **p_args); -typedef void (*godot_ptr_constructor)(void *p_base, const void **p_args); -typedef void (*godot_validated_setter)(godot_variant *p_base, const godot_variant *p_value); -typedef void (*godot_validated_getter)(const godot_variant *p_base, godot_variant *r_value); -typedef void (*godot_ptr_setter)(void *p_base, const void *p_value); -typedef void (*godot_ptr_getter)(const void *p_base, void *r_value); -typedef void (*godot_validated_indexed_setter)(godot_variant *p_base, godot_int p_index, const godot_variant *p_value, bool *r_oob); -typedef void (*godot_validated_indexed_getter)(const godot_variant *p_base, godot_int p_index, godot_variant *r_value, bool *r_oob); -typedef void (*godot_ptr_indexed_setter)(void *p_base, godot_int p_index, const void *p_value); -typedef void (*godot_ptr_indexed_getter)(const void *p_base, godot_int p_index, void *r_value); -typedef void (*godot_validated_keyed_setter)(godot_variant *p_base, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid); -typedef void (*godot_validated_keyed_getter)(const godot_variant *p_base, const godot_variant *p_key, godot_variant *r_value, bool *r_valid); -typedef bool (*godot_validated_keyed_checker)(const godot_variant *p_base, const godot_variant *p_key, bool *r_valid); -typedef void (*godot_ptr_keyed_setter)(void *p_base, const void *p_key, const void *p_value); -typedef void (*godot_ptr_keyed_getter)(const void *p_base, const void *p_key, void *r_value); -typedef uint32_t (*godot_ptr_keyed_checker)(const godot_variant *p_base, const godot_variant *p_key); -typedef void (*godot_validated_utility_function)(godot_variant *r_return, const godot_variant **p_arguments, int p_argument_count); -typedef void (*godot_ptr_utility_function)(void *r_return, const void **p_arguments, int p_argument_count); - -#include <gdnative/aabb.h> -#include <gdnative/array.h> -#include <gdnative/basis.h> -#include <gdnative/callable.h> -#include <gdnative/color.h> -#include <gdnative/dictionary.h> -#include <gdnative/node_path.h> -#include <gdnative/packed_arrays.h> -#include <gdnative/plane.h> -#include <gdnative/quaternion.h> -#include <gdnative/rect2.h> -#include <gdnative/rid.h> -#include <gdnative/signal.h> -#include <gdnative/string.h> -#include <gdnative/string_name.h> -#include <gdnative/transform2d.h> -#include <gdnative/transform_3d.h> -#include <gdnative/variant.h> -#include <gdnative/vector2.h> -#include <gdnative/vector3.h> - -#include <gdnative/gdnative.h> - -// Memory. - -void GDAPI godot_variant_new_copy(godot_variant *r_dest, const godot_variant *p_src); - -void GDAPI godot_variant_new_nil(godot_variant *r_dest); -void GDAPI godot_variant_new_bool(godot_variant *r_dest, const godot_bool p_b); -void GDAPI godot_variant_new_int(godot_variant *r_dest, const godot_int p_i); -void GDAPI godot_variant_new_float(godot_variant *r_dest, const godot_float p_f); -void GDAPI godot_variant_new_string(godot_variant *r_dest, const godot_string *p_s); -void GDAPI godot_variant_new_vector2(godot_variant *r_dest, const godot_vector2 *p_v2); -void GDAPI godot_variant_new_vector2i(godot_variant *r_dest, const godot_vector2i *p_v2); -void GDAPI godot_variant_new_rect2(godot_variant *r_dest, const godot_rect2 *p_rect2); -void GDAPI godot_variant_new_rect2i(godot_variant *r_dest, const godot_rect2i *p_rect2); -void GDAPI godot_variant_new_vector3(godot_variant *r_dest, const godot_vector3 *p_v3); -void GDAPI godot_variant_new_vector3i(godot_variant *r_dest, const godot_vector3i *p_v3); -void GDAPI godot_variant_new_transform2d(godot_variant *r_dest, const godot_transform2d *p_t2d); -void GDAPI godot_variant_new_plane(godot_variant *r_dest, const godot_plane *p_plane); -void GDAPI godot_variant_new_quaternion(godot_variant *r_dest, const godot_quaternion *p_quaternion); -void GDAPI godot_variant_new_aabb(godot_variant *r_dest, const godot_aabb *p_aabb); -void GDAPI godot_variant_new_basis(godot_variant *r_dest, const godot_basis *p_basis); -void GDAPI godot_variant_new_transform3d(godot_variant *r_dest, const godot_transform3d *p_trans); -void GDAPI godot_variant_new_color(godot_variant *r_dest, const godot_color *p_color); -void GDAPI godot_variant_new_string_name(godot_variant *r_dest, const godot_string_name *p_s); -void GDAPI godot_variant_new_node_path(godot_variant *r_dest, const godot_node_path *p_np); -void GDAPI godot_variant_new_rid(godot_variant *r_dest, const godot_rid *p_rid); -void GDAPI godot_variant_new_object(godot_variant *r_dest, const godot_object *p_obj); -void GDAPI godot_variant_new_callable(godot_variant *r_dest, const godot_callable *p_callable); -void GDAPI godot_variant_new_signal(godot_variant *r_dest, const godot_signal *p_signal); -void GDAPI godot_variant_new_dictionary(godot_variant *r_dest, const godot_dictionary *p_dict); -void GDAPI godot_variant_new_array(godot_variant *r_dest, const godot_array *p_arr); -void GDAPI godot_variant_new_packed_byte_array(godot_variant *r_dest, const godot_packed_byte_array *p_pba); -void GDAPI godot_variant_new_packed_int32_array(godot_variant *r_dest, const godot_packed_int32_array *p_pia); -void GDAPI godot_variant_new_packed_int64_array(godot_variant *r_dest, const godot_packed_int64_array *p_pia); -void GDAPI godot_variant_new_packed_float32_array(godot_variant *r_dest, const godot_packed_float32_array *p_pra); -void GDAPI godot_variant_new_packed_float64_array(godot_variant *r_dest, const godot_packed_float64_array *p_pra); -void GDAPI godot_variant_new_packed_string_array(godot_variant *r_dest, const godot_packed_string_array *p_psa); -void GDAPI godot_variant_new_packed_vector2_array(godot_variant *r_dest, const godot_packed_vector2_array *p_pv2a); -void GDAPI godot_variant_new_packed_vector3_array(godot_variant *r_dest, const godot_packed_vector3_array *p_pv3a); -void GDAPI godot_variant_new_packed_color_array(godot_variant *r_dest, const godot_packed_color_array *p_pca); - -godot_bool GDAPI godot_variant_as_bool(const godot_variant *p_self); -godot_int GDAPI godot_variant_as_int(const godot_variant *p_self); -godot_float GDAPI godot_variant_as_float(const godot_variant *p_self); -godot_string GDAPI godot_variant_as_string(const godot_variant *p_self); -godot_vector2 GDAPI godot_variant_as_vector2(const godot_variant *p_self); -godot_vector2i GDAPI godot_variant_as_vector2i(const godot_variant *p_self); -godot_rect2 GDAPI godot_variant_as_rect2(const godot_variant *p_self); -godot_rect2i GDAPI godot_variant_as_rect2i(const godot_variant *p_self); -godot_vector3 GDAPI godot_variant_as_vector3(const godot_variant *p_self); -godot_vector3i GDAPI godot_variant_as_vector3i(const godot_variant *p_self); -godot_transform2d GDAPI godot_variant_as_transform2d(const godot_variant *p_self); -godot_plane GDAPI godot_variant_as_plane(const godot_variant *p_self); -godot_quaternion GDAPI godot_variant_as_quaternion(const godot_variant *p_self); -godot_aabb GDAPI godot_variant_as_aabb(const godot_variant *p_self); -godot_basis GDAPI godot_variant_as_basis(const godot_variant *p_self); -godot_transform3d GDAPI godot_variant_as_transform3d(const godot_variant *p_self); -godot_color GDAPI godot_variant_as_color(const godot_variant *p_self); -godot_string_name GDAPI godot_variant_as_string_name(const godot_variant *p_self); -godot_node_path GDAPI godot_variant_as_node_path(const godot_variant *p_self); -godot_rid GDAPI godot_variant_as_rid(const godot_variant *p_self); -godot_object GDAPI *godot_variant_as_object(const godot_variant *p_self); -godot_callable GDAPI godot_variant_as_callable(const godot_variant *p_self); -godot_signal GDAPI godot_variant_as_signal(const godot_variant *p_self); -godot_dictionary GDAPI godot_variant_as_dictionary(const godot_variant *p_self); -godot_array GDAPI godot_variant_as_array(const godot_variant *p_self); -godot_packed_byte_array GDAPI godot_variant_as_packed_byte_array(const godot_variant *p_self); -godot_packed_int32_array GDAPI godot_variant_as_packed_int32_array(const godot_variant *p_self); -godot_packed_int64_array GDAPI godot_variant_as_packed_int64_array(const godot_variant *p_self); -godot_packed_float32_array GDAPI godot_variant_as_packed_float32_array(const godot_variant *p_self); -godot_packed_float64_array GDAPI godot_variant_as_packed_float64_array(const godot_variant *p_self); -godot_packed_string_array GDAPI godot_variant_as_packed_string_array(const godot_variant *p_self); -godot_packed_vector2_array GDAPI godot_variant_as_packed_vector2_array(const godot_variant *p_self); -godot_packed_vector3_array GDAPI godot_variant_as_packed_vector3_array(const godot_variant *p_self); -godot_packed_color_array GDAPI godot_variant_as_packed_color_array(const godot_variant *p_self); - -void GDAPI godot_variant_destroy(godot_variant *p_self); - -// Dynamic interaction. - -void GDAPI godot_variant_call(godot_variant *p_self, const godot_string_name *p_method, const godot_variant **p_args, const godot_int p_argument_count, godot_variant *r_return, godot_variant_call_error *r_error); -void GDAPI godot_variant_call_with_cstring(godot_variant *p_self, const char *p_method, const godot_variant **p_args, const godot_int p_argument_count, godot_variant *r_return, godot_variant_call_error *r_error); -void GDAPI godot_variant_call_static(godot_variant_type p_type, const godot_string_name *p_method, const godot_variant **p_args, const godot_int p_argument_count, godot_variant *r_return, godot_variant_call_error *r_error); -void GDAPI godot_variant_call_static_with_cstring(godot_variant_type p_type, const char *p_method, const godot_variant **p_args, const godot_int p_argument_count, godot_variant *r_return, godot_variant_call_error *r_error); -void GDAPI godot_variant_evaluate(godot_variant_operator p_op, const godot_variant *p_a, const godot_variant *p_b, godot_variant *r_return, bool *r_valid); -void GDAPI godot_variant_set(godot_variant *p_self, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid); -void GDAPI godot_variant_set_named(godot_variant *p_self, const godot_string_name *p_name, const godot_variant *p_value, bool *r_valid); -void GDAPI godot_variant_set_named_with_cstring(godot_variant *p_self, const char *p_name, const godot_variant *p_value, bool *r_valid); -void GDAPI godot_variant_set_keyed(godot_variant *p_self, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid); -void GDAPI godot_variant_set_indexed(godot_variant *p_self, godot_int p_index, const godot_variant *p_value, bool *r_valid, bool *r_oob); -godot_variant GDAPI godot_variant_get(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid); -godot_variant GDAPI godot_variant_get_named(const godot_variant *p_self, const godot_string_name *p_key, bool *r_valid); -godot_variant GDAPI godot_variant_get_named_with_cstring(const godot_variant *p_self, const char *p_key, bool *r_valid); -godot_variant GDAPI godot_variant_get_keyed(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid); -godot_variant GDAPI godot_variant_get_indexed(const godot_variant *p_self, godot_int p_index, bool *r_valid, bool *r_oob); -/// Iteration. -bool GDAPI godot_variant_iter_init(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid); -bool GDAPI godot_variant_iter_next(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid); -godot_variant GDAPI godot_variant_iter_get(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid); - -/// Variant functions. -godot_bool GDAPI godot_variant_hash_compare(const godot_variant *p_self, const godot_variant *p_other); -godot_bool GDAPI godot_variant_booleanize(const godot_variant *p_self); -void GDAPI godot_variant_blend(const godot_variant *p_a, const godot_variant *p_b, float p_c, godot_variant *r_dst); -void GDAPI godot_variant_interpolate(const godot_variant *p_a, const godot_variant *p_b, float p_c, godot_variant *r_dst); -godot_variant GDAPI godot_variant_duplicate(const godot_variant *p_self, godot_bool p_deep); -godot_string GDAPI godot_variant_stringify(const godot_variant *p_self); - -// Discovery API. - -/// Operators. -godot_validated_operator_evaluator GDAPI godot_variant_get_validated_operator_evaluator(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b); -godot_ptr_operator_evaluator GDAPI godot_variant_get_ptr_operator_evaluator(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b); -godot_variant_type GDAPI godot_variant_get_operator_return_type(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b); -godot_string GDAPI godot_variant_get_operator_name(godot_variant_operator p_operator); - -/// Built-in methods. -bool GDAPI godot_variant_has_builtin_method(godot_variant_type p_type, const godot_string_name *p_method); -bool GDAPI godot_variant_has_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method); -godot_validated_builtin_method GDAPI godot_variant_get_validated_builtin_method(godot_variant_type p_type, const godot_string_name *p_method); -godot_validated_builtin_method GDAPI godot_variant_get_validated_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method); -godot_ptr_builtin_method GDAPI godot_variant_get_ptr_builtin_method(godot_variant_type p_type, const godot_string_name *p_method); -godot_ptr_builtin_method GDAPI godot_variant_get_ptr_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method); -int GDAPI godot_variant_get_builtin_method_argument_count(godot_variant_type p_type, const godot_string_name *p_method); -int GDAPI godot_variant_get_builtin_method_argument_count_with_cstring(godot_variant_type p_type, const char *p_method); -godot_variant_type GDAPI godot_variant_get_builtin_method_argument_type(godot_variant_type p_type, const godot_string_name *p_method, int p_argument); -godot_variant_type GDAPI godot_variant_get_builtin_method_argument_type_with_cstring(godot_variant_type p_type, const char *p_method, int p_argument); -godot_string GDAPI godot_variant_get_builtin_method_argument_name(godot_variant_type p_type, const godot_string_name *p_method, int p_argument); -godot_string GDAPI godot_variant_get_builtin_method_argument_name_with_cstring(godot_variant_type p_type, const char *p_method, int p_argument); -bool GDAPI godot_variant_has_builtin_method_return_value(godot_variant_type p_type, const godot_string_name *p_method); -bool GDAPI godot_variant_has_builtin_method_return_value_with_cstring(godot_variant_type p_type, const char *p_method); -godot_variant_type GDAPI godot_variant_get_builtin_method_return_type(godot_variant_type p_type, const godot_string_name *p_method); -godot_variant_type GDAPI godot_variant_get_builtin_method_return_type_with_cstring(godot_variant_type p_type, const char *p_method); -bool GDAPI godot_variant_is_builtin_method_const(godot_variant_type p_type, const godot_string_name *p_method); -bool GDAPI godot_variant_is_builtin_method_const_with_cstring(godot_variant_type p_type, const char *p_method); -bool GDAPI godot_variant_is_builtin_method_static(godot_variant_type p_type, const godot_string_name *p_method); -bool GDAPI godot_variant_is_builtin_method_static_with_cstring(godot_variant_type p_type, const char *p_method); -bool GDAPI godot_variant_is_builtin_method_vararg(godot_variant_type p_type, const godot_string_name *p_method); -bool GDAPI godot_variant_is_builtin_method_vararg_with_cstring(godot_variant_type p_type, const char *p_method); -int GDAPI godot_variant_get_builtin_method_count(godot_variant_type p_type); -void GDAPI godot_variant_get_builtin_method_list(godot_variant_type p_type, godot_string_name *r_list); - -/// Constructors. -int GDAPI godot_variant_get_constructor_count(godot_variant_type p_type); -godot_validated_constructor GDAPI godot_variant_get_validated_constructor(godot_variant_type p_type, int p_constructor); -godot_ptr_constructor GDAPI godot_variant_get_ptr_constructor(godot_variant_type p_type, int p_constructor); -int GDAPI godot_variant_get_constructor_argument_count(godot_variant_type p_type, int p_constructor); -godot_variant_type GDAPI godot_variant_get_constructor_argument_type(godot_variant_type p_type, int p_constructor, int p_argument); -godot_string GDAPI godot_variant_get_constructor_argument_name(godot_variant_type p_type, int p_constructor, int p_argument); -void GDAPI godot_variant_construct(godot_variant_type p_type, godot_variant *p_base, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error); - -/// Properties. -godot_variant_type GDAPI godot_variant_get_member_type(godot_variant_type p_type, const godot_string_name *p_member); -godot_variant_type GDAPI godot_variant_get_member_type_with_cstring(godot_variant_type p_type, const char *p_member); -int GDAPI godot_variant_get_member_count(godot_variant_type p_type); -void GDAPI godot_variant_get_member_list(godot_variant_type p_type, godot_string_name *r_list); -godot_validated_setter GDAPI godot_variant_get_validated_setter(godot_variant_type p_type, const godot_string_name *p_member); -godot_validated_setter GDAPI godot_variant_get_validated_setter_with_cstring(godot_variant_type p_type, const char *p_member); -godot_validated_getter GDAPI godot_variant_get_validated_getter(godot_variant_type p_type, const godot_string_name *p_member); -godot_validated_getter GDAPI godot_variant_get_validated_getter_with_cstring(godot_variant_type p_type, const char *p_member); -godot_ptr_setter GDAPI godot_variant_get_ptr_setter(godot_variant_type p_type, const godot_string_name *p_member); -godot_ptr_setter GDAPI godot_variant_get_ptr_setter_with_cstring(godot_variant_type p_type, const char *p_member); -godot_ptr_getter GDAPI godot_variant_get_ptr_getter(godot_variant_type p_type, const godot_string_name *p_member); -godot_ptr_getter GDAPI godot_variant_get_ptr_getter_with_cstring(godot_variant_type p_type, const char *p_member); - -/// Indexing. -bool GDAPI godot_variant_has_indexing(godot_variant_type p_type); -godot_variant_type GDAPI godot_variant_get_indexed_element_type(godot_variant_type p_type); -godot_validated_indexed_setter GDAPI godot_variant_get_validated_indexed_setter(godot_variant_type p_type); -godot_validated_indexed_getter GDAPI godot_variant_get_validated_indexed_getter(godot_variant_type p_type); -godot_ptr_indexed_setter GDAPI godot_variant_get_ptr_indexed_setter(godot_variant_type p_type); -godot_ptr_indexed_getter GDAPI godot_variant_get_ptr_indexed_getter(godot_variant_type p_type); -uint64_t GDAPI godot_variant_get_indexed_size(const godot_variant *p_self); - -/// Keying. -bool GDAPI godot_variant_is_keyed(godot_variant_type p_type); -godot_validated_keyed_setter GDAPI godot_variant_get_validated_keyed_setter(godot_variant_type p_type); -godot_validated_keyed_getter GDAPI godot_variant_get_validated_keyed_getter(godot_variant_type p_type); -godot_validated_keyed_checker GDAPI godot_variant_get_validated_keyed_checker(godot_variant_type p_type); -godot_ptr_keyed_setter GDAPI godot_variant_get_ptr_keyed_setter(godot_variant_type p_type); -godot_ptr_keyed_getter GDAPI godot_variant_get_ptr_keyed_getter(godot_variant_type p_type); -godot_ptr_keyed_checker GDAPI godot_variant_get_ptr_keyed_checker(godot_variant_type p_type); - -/// Constants. -int GDAPI godot_variant_get_constants_count(godot_variant_type p_type); -void GDAPI godot_variant_get_constants_list(godot_variant_type p_type, godot_string_name *r_list); -bool GDAPI godot_variant_has_constant(godot_variant_type p_type, const godot_string_name *p_constant); -bool GDAPI godot_variant_has_constant_with_cstring(godot_variant_type p_type, const char *p_constant); -godot_variant GDAPI godot_variant_get_constant_value(godot_variant_type p_type, const godot_string_name *p_constant); -godot_variant GDAPI godot_variant_get_constant_value_with_cstring(godot_variant_type p_type, const char *p_constant); - -/// Utilities. -bool GDAPI godot_variant_has_utility_function(const godot_string_name *p_function); -bool GDAPI godot_variant_has_utility_function_with_cstring(const char *p_function); -void GDAPI godot_variant_call_utility_function(const godot_string_name *p_function, godot_variant *r_ret, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error); -void GDAPI godot_variant_call_utility_function_with_cstring(const char *p_function, godot_variant *r_ret, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error); -godot_ptr_utility_function GDAPI godot_variant_get_ptr_utility_function(const godot_string_name *p_function); -godot_ptr_utility_function GDAPI godot_variant_get_ptr_utility_function_with_cstring(const char *p_function); -godot_validated_utility_function GDAPI godot_variant_get_validated_utility_function(const godot_string_name *p_function); -godot_validated_utility_function GDAPI godot_variant_get_validated_utility_function_with_cstring(const char *p_function); -godot_variant_utility_function_type GDAPI godot_variant_get_utility_function_type(const godot_string_name *p_function); -godot_variant_utility_function_type GDAPI godot_variant_get_utility_function_type_with_cstring(const char *p_function); -int GDAPI godot_variant_get_utility_function_argument_count(const godot_string_name *p_function); -int GDAPI godot_variant_get_utility_function_argument_count_with_cstring(const char *p_function); -godot_variant_type GDAPI godot_variant_get_utility_function_argument_type(const godot_string_name *p_function, int p_argument); -godot_variant_type GDAPI godot_variant_get_utility_function_argument_type_with_cstring(const char *p_function, int p_argument); -godot_string GDAPI godot_variant_get_utility_function_argument_name(const godot_string_name *p_function, int p_argument); -godot_string GDAPI godot_variant_get_utility_function_argument_name_with_cstring(const char *p_function, int p_argument); -bool GDAPI godot_variant_has_utility_function_return_value(const godot_string_name *p_function); -bool GDAPI godot_variant_has_utility_function_return_value_with_cstring(const char *p_function); -godot_variant_type GDAPI godot_variant_get_utility_function_return_type(const godot_string_name *p_function); -godot_variant_type GDAPI godot_variant_get_utility_function_return_type_with_cstring(const char *p_function); -bool GDAPI godot_variant_is_utility_function_vararg(const godot_string_name *p_function); -bool GDAPI godot_variant_is_utility_function_vararg_with_cstring(const char *p_function); -int GDAPI godot_variant_get_utility_function_count(); -void GDAPI godot_variant_get_utility_function_list(godot_string_name *r_functions); - -// Introspection. - -godot_variant_type GDAPI godot_variant_get_type(const godot_variant *p_self); -bool GDAPI godot_variant_has_method(const godot_variant *p_self, const godot_string_name *p_method); -bool GDAPI godot_variant_has_member(godot_variant_type p_type, const godot_string_name *p_member); -bool GDAPI godot_variant_has_key(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid); - -godot_string GDAPI godot_variant_get_type_name(godot_variant_type p_type); -bool GDAPI godot_variant_can_convert(godot_variant_type p_from, godot_variant_type p_to); -bool GDAPI godot_variant_can_convert_strict(godot_variant_type p_from, godot_variant_type p_to); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/modules/gdnative/include/gdnative/variant_struct.h b/modules/gdnative/include/gdnative/variant_struct.h deleted file mode 100644 index cc75a8c498..0000000000 --- a/modules/gdnative/include/gdnative/variant_struct.h +++ /dev/null @@ -1,53 +0,0 @@ -/*************************************************************************/ -/* variant_struct.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_VARIANT_STRUCT_H -#define GODOT_VARIANT_STRUCT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_VARIANT_SIZE (sizeof(godot_real_t) * 4 + sizeof(int64_t)) - -#ifndef GODOT_CORE_API_GODOT_VARIANT_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_VARIANT_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_VARIANT_SIZE]; -} godot_variant; -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/modules/gdnative/include/gdnative/vector2.h b/modules/gdnative/include/gdnative/vector2.h deleted file mode 100644 index f5b55fd4ce..0000000000 --- a/modules/gdnative/include/gdnative/vector2.h +++ /dev/null @@ -1,73 +0,0 @@ -/*************************************************************************/ -/* vector2.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_VECTOR2_H -#define GODOT_VECTOR2_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_VECTOR2_SIZE (sizeof(godot_real_t) * 2) - -#ifndef GODOT_CORE_API_GODOT_VECTOR2_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_VECTOR2_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_VECTOR2_SIZE]; -} godot_vector2; -#endif - -#define GODOT_VECTOR2I_SIZE (sizeof(int32_t) * 2) - -#ifndef GODOT_CORE_API_GODOT_VECTOR2I_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_VECTOR2I_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_VECTOR2I_SIZE]; -} godot_vector2i; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_vector2_new(godot_vector2 *p_self); -void GDAPI godot_vector2_new_copy(godot_vector2 *r_dest, const godot_vector2 *p_src); -void GDAPI godot_vector2i_new(godot_vector2i *p_self); -void GDAPI godot_vector2i_new_copy(godot_vector2i *r_dest, const godot_vector2i *p_src); -godot_real_t GDAPI *godot_vector2_operator_index(godot_vector2 *p_self, godot_int p_index); -const godot_real_t GDAPI *godot_vector2_operator_index_const(const godot_vector2 *p_self, godot_int p_index); -int32_t GDAPI *godot_vector2i_operator_index(godot_vector2i *p_self, godot_int p_index); -const int32_t GDAPI *godot_vector2i_operator_index_const(const godot_vector2i *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_VECTOR2_H diff --git a/modules/gdnative/include/gdnative/vector3.h b/modules/gdnative/include/gdnative/vector3.h deleted file mode 100644 index d52cd38a72..0000000000 --- a/modules/gdnative/include/gdnative/vector3.h +++ /dev/null @@ -1,73 +0,0 @@ -/*************************************************************************/ -/* vector3.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_VECTOR3_H -#define GODOT_VECTOR3_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include <gdnative/math_defs.h> - -#define GODOT_VECTOR3_SIZE (sizeof(godot_real_t) * 3) - -#ifndef GODOT_CORE_API_GODOT_VECTOR3_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_VECTOR3_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_VECTOR3_SIZE]; -} godot_vector3; -#endif - -#define GODOT_VECTOR3I_SIZE (sizeof(int32_t) * 3) - -#ifndef GODOT_CORE_API_GODOT_VECTOR3I_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_VECTOR3I_TYPE_DEFINED -typedef struct { - uint8_t _dont_touch_that[GODOT_VECTOR3I_SIZE]; -} godot_vector3i; -#endif - -#include <gdnative/gdnative.h> - -void GDAPI godot_vector3_new(godot_vector3 *p_self); -void GDAPI godot_vector3_new_copy(godot_vector3 *r_dest, const godot_vector3 *p_src); -void GDAPI godot_vector3i_new(godot_vector3i *p_self); -void GDAPI godot_vector3i_new_copy(godot_vector3i *r_dest, const godot_vector3i *p_src); -godot_real_t GDAPI *godot_vector3_operator_index(godot_vector3 *p_self, godot_int p_index); -const godot_real_t GDAPI *godot_vector3_operator_index_const(const godot_vector3 *p_self, godot_int p_index); -int32_t GDAPI *godot_vector3i_operator_index(godot_vector3i *p_self, godot_int p_index); -const int32_t GDAPI *godot_vector3i_operator_index_const(const godot_vector3i *p_self, godot_int p_index); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_VECTOR3_H diff --git a/modules/gdnative/include/nativescript/godot_nativescript.h b/modules/gdnative/include/nativescript/godot_nativescript.h deleted file mode 100644 index 879291c2e0..0000000000 --- a/modules/gdnative/include/nativescript/godot_nativescript.h +++ /dev/null @@ -1,233 +0,0 @@ -/*************************************************************************/ -/* godot_nativescript.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_NATIVESCRIPT_H -#define GODOT_NATIVESCRIPT_H - -#include <gdnative/gdnative.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - GODOT_METHOD_RPC_MODE_DISABLED, - GODOT_METHOD_RPC_MODE_ANY_PEER, - GODOT_METHOD_RPC_MODE_AUTHORITY, -} godot_nativescript_method_rpc_mode; - -typedef enum { - GODOT_PROPERTY_HINT_NONE, ///< no hint provided. - GODOT_PROPERTY_HINT_RANGE, ///< hint_text = "min,max,step,slider; //slider is optional" - GODOT_PROPERTY_HINT_EXP_RANGE, ///< hint_text = "min,max,step", exponential edit - 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_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, - GODOT_PROPERTY_HINT_LAYERS_2D_PHYSICS, - GODOT_PROPERTY_HINT_LAYERS_2D_NAVIGATION, - GODOT_PROPERTY_HINT_LAYERS_3D_RENDER, - GODOT_PROPERTY_HINT_LAYERS_3D_PHYSICS, - GODOT_PROPERTY_HINT_LAYERS_3D_NAVIGATION, - GODOT_PROPERTY_HINT_FILE, ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," - 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 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 - GODOT_PROPERTY_HINT_COLOR_NO_ALPHA, ///< used for ignoring alpha component when editing a color - GODOT_PROPERTY_HINT_IMAGE_COMPRESS_LOSSY, - GODOT_PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS, - GODOT_PROPERTY_HINT_OBJECT_ID, - GODOT_PROPERTY_HINT_TYPE_STRING, ///< a type string, the hint is the base type to choose - GODOT_PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE, ///< so something else can provide this (used in scripts) - GODOT_PROPERTY_HINT_METHOD_OF_VARIANT_TYPE, ///< a method of a type - GODOT_PROPERTY_HINT_METHOD_OF_BASE_TYPE, ///< a method of a base type - GODOT_PROPERTY_HINT_METHOD_OF_INSTANCE, ///< a method of an instance - GODOT_PROPERTY_HINT_METHOD_OF_SCRIPT, ///< a method of a script & base - GODOT_PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE, ///< a property of a type - GODOT_PROPERTY_HINT_PROPERTY_OF_BASE_TYPE, ///< a property of a base type - GODOT_PROPERTY_HINT_PROPERTY_OF_INSTANCE, ///< a property of an instance - GODOT_PROPERTY_HINT_PROPERTY_OF_SCRIPT, ///< a property of a script & base - GODOT_PROPERTY_HINT_LOCALE_ID, - GODOT_PROPERTY_HINT_MAX, -} godot_nativescript_property_hint; - -typedef enum { - GODOT_PROPERTY_USAGE_STORAGE = 1, - GODOT_PROPERTY_USAGE_EDITOR = 2, - GODOT_PROPERTY_USAGE_NETWORK = 4, - GODOT_PROPERTY_USAGE_EDITOR_HELPER = 8, - GODOT_PROPERTY_USAGE_CHECKABLE = 16, //used for editing global variables - GODOT_PROPERTY_USAGE_CHECKED = 32, //used for editing global variables - 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_SUBGROUP = 512, - GODOT_PROPERTY_USAGE_NO_INSTANCE_STATE = 2048, - GODOT_PROPERTY_USAGE_RESTART_IF_CHANGED = 4096, - GODOT_PROPERTY_USAGE_SCRIPT_VARIABLE = 8192, - GODOT_PROPERTY_USAGE_STORE_IF_NULL = 16384, - GODOT_PROPERTY_USAGE_ANIMATE_AS_TRIGGER = 32768, - GODOT_PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED = 65536, - - GODOT_PROPERTY_USAGE_DEFAULT = GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK, - GODOT_PROPERTY_USAGE_DEFAULT_INTL = GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK | GODOT_PROPERTY_USAGE_INTERNATIONALIZED, - GODOT_PROPERTY_USAGE_NO_EDITOR = GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_NETWORK, -} godot_nativescript_property_usage_flags; - -typedef struct { - godot_nativescript_method_rpc_mode rset_type; - - godot_int type; - godot_nativescript_property_hint hint; - godot_string hint_string; - godot_nativescript_property_usage_flags usage; - godot_variant default_value; -} godot_nativescript_property_attributes; - -typedef struct { - // instance pointer, method_data - return user data - GDCALLINGCONV void *(*create_func)(godot_object *, void *); - void *method_data; - GDCALLINGCONV void (*free_func)(void *); -} godot_nativescript_instance_create_func; - -typedef struct { - // instance pointer, method data, user data - GDCALLINGCONV void (*destroy_func)(godot_object *, void *, void *); - void *method_data; - GDCALLINGCONV void (*free_func)(void *); -} godot_nativescript_instance_destroy_func; - -void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func); - -void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func); - -typedef struct { - godot_nativescript_method_rpc_mode rpc_type; -} godot_nativescript_method_attributes; - -typedef struct { - godot_string name; - - godot_variant_type type; - godot_nativescript_property_hint hint; - godot_string hint_string; -} godot_nativescript_method_argument; - -typedef struct { - // instance pointer, method data, user data, num args, args - return result as variant - GDCALLINGCONV godot_variant (*method)(godot_object *, void *, void *, int, godot_variant **); - void *method_data; - GDCALLINGCONV void (*free_func)(void *); -} godot_nativescript_instance_method; - -void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_nativescript_method_attributes p_attr, godot_nativescript_instance_method p_method); -void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_handle, const char *p_name, const char *p_function_name, int p_num_args, const godot_nativescript_method_argument *p_args); - -typedef struct { - // instance pointer, method data, user data, value - GDCALLINGCONV void (*set_func)(godot_object *, void *, void *, godot_variant *); - void *method_data; - GDCALLINGCONV void (*free_func)(void *); -} godot_nativescript_property_set_func; - -typedef struct { - // instance pointer, method data, user data, value - GDCALLINGCONV godot_variant (*get_func)(godot_object *, void *, void *); - void *method_data; - GDCALLINGCONV void (*free_func)(void *); -} godot_nativescript_property_get_func; - -void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_nativescript_property_attributes *p_attr, godot_nativescript_property_set_func p_set_func, godot_nativescript_property_get_func p_get_func); - -typedef struct { - godot_string name; - godot_int type; - godot_nativescript_property_hint hint; - godot_string hint_string; - godot_nativescript_property_usage_flags usage; - godot_variant default_value; -} godot_nativescript_signal_argument; - -typedef struct { - godot_string name; - int num_args; - godot_nativescript_signal_argument *args; - int num_default_args; - godot_variant *default_args; -} godot_nativescript_signal; - -void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const char *p_name, const godot_nativescript_signal *p_signal); - -void GDAPI *godot_nativescript_get_userdata(godot_object *p_instance); - -// documentation - -void GDAPI godot_nativescript_set_class_documentation(void *p_gdnative_handle, const char *p_name, godot_string p_documentation); -void GDAPI godot_nativescript_set_method_documentation(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_string p_documentation); -void GDAPI godot_nativescript_set_property_documentation(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_string p_documentation); -void GDAPI godot_nativescript_set_signal_documentation(void *p_gdnative_handle, const char *p_name, const char *p_signal_name, godot_string p_documentation); - -// type tag API - -void GDAPI godot_nativescript_set_global_type_tag(int p_idx, const char *p_name, const void *p_type_tag); -const void GDAPI *godot_nativescript_get_global_type_tag(int p_idx, const char *p_name); - -void GDAPI godot_nativescript_set_type_tag(void *p_gdnative_handle, const char *p_name, const void *p_type_tag); -const void GDAPI *godot_nativescript_get_type_tag(const godot_object *p_object); - -// instance binding API - -typedef struct { - GDCALLINGCONV void *(*alloc_instance_binding_data)(void *, const void *, godot_object *); - GDCALLINGCONV void (*free_instance_binding_data)(void *, void *); - GDCALLINGCONV void (*refcount_incremented_instance_binding)(void *, godot_object *); - GDCALLINGCONV bool (*refcount_decremented_instance_binding)(void *, godot_object *); - void *data; - GDCALLINGCONV void (*free_func)(void *); -} godot_nativescript_instance_binding_functions; - -int GDAPI godot_nativescript_register_instance_binding_data_functions(godot_nativescript_instance_binding_functions p_binding_functions); -void GDAPI godot_nativescript_unregister_instance_binding_data_functions(int p_idx); - -void GDAPI *godot_nativescript_get_instance_binding_data(int p_idx, godot_object *p_object); - -void GDAPI godot_nativescript_profiling_add_data(const char *p_signature, uint64_t p_time); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/modules/gdnative/include/pluginscript/godot_pluginscript.h b/modules/gdnative/include/pluginscript/godot_pluginscript.h deleted file mode 100644 index 0042d79966..0000000000 --- a/modules/gdnative/include/pluginscript/godot_pluginscript.h +++ /dev/null @@ -1,171 +0,0 @@ -/*************************************************************************/ -/* godot_pluginscript.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_PLUGINSCRIPT_H -#define GODOT_PLUGINSCRIPT_H - -#include <gdnative/gdnative.h> -#include <nativescript/godot_nativescript.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void godot_pluginscript_instance_data; -typedef void godot_pluginscript_script_data; -typedef void godot_pluginscript_language_data; - -// --- Instance --- - -typedef struct { - godot_pluginscript_instance_data *(*init)(godot_pluginscript_script_data *p_data, godot_object *p_owner); - void (*finish)(godot_pluginscript_instance_data *p_data); - - godot_bool (*set_prop)(godot_pluginscript_instance_data *p_data, const godot_string_name *p_name, const godot_variant *p_value); - godot_bool (*get_prop)(godot_pluginscript_instance_data *p_data, const godot_string_name *p_name, godot_variant *r_ret); - - godot_variant (*call_method)(godot_pluginscript_instance_data *p_data, - const godot_string_name *p_method, const godot_variant **p_args, - int p_argcount, godot_variant_call_error *r_error); - - void (*notification)(godot_pluginscript_instance_data *p_data, int p_notification); - godot_string (*to_string)(godot_pluginscript_instance_data *p_data, godot_bool *r_valid); - - //this is used by script languages that keep a reference counter of their own - //you can make make Ref<> not die when it reaches zero, so deleting the reference - //depends entirely from the script. - // Note: You can set those function pointer to nullptr if not needed. - void (*refcount_incremented)(godot_pluginscript_instance_data *p_data); - bool (*refcount_decremented)(godot_pluginscript_instance_data *p_data); // return true if it can die -} godot_pluginscript_instance_desc; - -// --- Script --- - -typedef struct { - godot_pluginscript_script_data *data; - godot_string_name name; - godot_bool is_tool; - godot_string_name base; - godot_string icon_path; - - // Member lines format: {<string>: <int>} - godot_dictionary member_lines; - // Method info dictionary format - // { - // name: <string> - // args: [<dict:property>] - // default_args: [<variant>] - // return: <dict:property> - // flags: <int> - // rpc_mode: <int:godot_method_rpc_mode> - // } - godot_array methods; - // Same format than for methods - godot_array signals; - // Property info dictionary format - // { - // name: <string> - // type: <int:godot_variant_type> - // hint: <int:godot_property_hint> - // hint_string: <string> - // usage: <int:godot_property_usage_flags> - // default_value: <variant> - // rset_mode: <int:godot_method_rpc_mode> - // } - godot_array properties; -} godot_pluginscript_script_manifest; - -typedef struct { - godot_pluginscript_script_manifest (*init)(godot_pluginscript_language_data *p_data, const godot_string *p_path, const godot_string *p_source, godot_error *r_error); - void (*finish)(godot_pluginscript_script_data *p_data); - godot_pluginscript_instance_desc instance_desc; -} godot_pluginscript_script_desc; - -// --- Language --- - -typedef struct { - godot_string_name signature; - godot_int call_count; - godot_int total_time; // In microseconds - godot_int self_time; // In microseconds -} godot_pluginscript_profiling_data; - -typedef struct { - const char *name; - const char *type; - const char *extension; - const char **recognized_extensions; // nullptr terminated array - godot_pluginscript_language_data *(*init)(); - void (*finish)(godot_pluginscript_language_data *p_data); - const char **reserved_words; // nullptr terminated array - const char **comment_delimiters; // nullptr terminated array - const char **string_delimiters; // nullptr terminated array - godot_bool has_named_classes; - godot_bool supports_builtin_mode; - godot_bool can_inherit_from_file; - - godot_string (*get_template_source_code)(godot_pluginscript_language_data *p_data, const godot_string *p_class_name, const godot_string *p_base_class_name); - godot_bool (*validate)(godot_pluginscript_language_data *p_data, const godot_string *p_script, const godot_string *p_path, godot_packed_string_array *r_functions, godot_array *r_errors); // errors = Array of Dictionary with "line", "column", "message" keys - int (*find_function)(godot_pluginscript_language_data *p_data, const godot_string *p_function, const godot_string *p_code); // Can be nullptr - godot_string (*make_function)(godot_pluginscript_language_data *p_data, const godot_string *p_class, const godot_string *p_name, const godot_packed_string_array *p_args); - 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_name *p_variable, const godot_variant *p_value); - godot_string (*debug_get_error)(godot_pluginscript_language_data *p_data); - int (*debug_get_stack_level_count)(godot_pluginscript_language_data *p_data); - int (*debug_get_stack_level_line)(godot_pluginscript_language_data *p_data, int p_level); - godot_string (*debug_get_stack_level_function)(godot_pluginscript_language_data *p_data, int p_level); - godot_string (*debug_get_stack_level_source)(godot_pluginscript_language_data *p_data, int p_level); - void (*debug_get_stack_level_locals)(godot_pluginscript_language_data *p_data, int p_level, godot_packed_string_array *p_locals, godot_array *p_values, int p_max_subitems, int p_max_depth); - void (*debug_get_stack_level_members)(godot_pluginscript_language_data *p_data, int p_level, godot_packed_string_array *p_members, godot_array *p_values, int p_max_subitems, int p_max_depth); - void (*debug_get_globals)(godot_pluginscript_language_data *p_data, godot_packed_string_array *p_locals, godot_array *p_values, int p_max_subitems, int p_max_depth); - godot_string (*debug_parse_stack_level_expression)(godot_pluginscript_language_data *p_data, int p_level, const godot_string *p_expression, int p_max_subitems, int p_max_depth); - - // TODO: could this stuff be moved to the godot_pluginscript_language_desc ? - void (*get_public_functions)(godot_pluginscript_language_data *p_data, godot_array *r_functions); - void (*get_public_constants)(godot_pluginscript_language_data *p_data, godot_dictionary *r_constants); - - void (*profiling_start)(godot_pluginscript_language_data *p_data); - void (*profiling_stop)(godot_pluginscript_language_data *p_data); - int (*profiling_get_accumulated_data)(godot_pluginscript_language_data *p_data, godot_pluginscript_profiling_data *r_info, int p_info_max); - int (*profiling_get_frame_data)(godot_pluginscript_language_data *p_data, godot_pluginscript_profiling_data *r_info, int p_info_max); - void (*profiling_frame)(godot_pluginscript_language_data *p_data); - - godot_pluginscript_script_desc script_desc; -} godot_pluginscript_language_desc; - -void GDAPI godot_pluginscript_register_language(const godot_pluginscript_language_desc *language_desc); - -#ifdef __cplusplus -} -#endif - -#endif // GODOT_PLUGINSCRIPT_H diff --git a/modules/gdnative/include/videodecoder/godot_videodecoder.h b/modules/gdnative/include/videodecoder/godot_videodecoder.h deleted file mode 100644 index 16daba0a67..0000000000 --- a/modules/gdnative/include/videodecoder/godot_videodecoder.h +++ /dev/null @@ -1,75 +0,0 @@ -/*************************************************************************/ -/* godot_videodecoder.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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_NATIVEVIDEODECODER_H -#define GODOT_NATIVEVIDEODECODER_H - -#include <gdnative/gdnative.h> - -#ifdef __cplusplus -extern "C" { -#endif - -#define GODOTAV_API_MAJOR 0 -#define GODOTAV_API_MINOR 1 - -typedef struct -{ - godot_gdnative_api_version version; - void *next; - void *(*constructor)(godot_object *); - void (*destructor)(void *); - const char *(*get_plugin_name)(); - const char **(*get_supported_extensions)(int *count); - godot_bool (*open_file)(void *, void *); // data struct, and a FileAccess pointer - godot_float (*get_length)(const void *); - godot_float (*get_playback_position)(const void *); - void (*seek)(void *, godot_float); - void (*set_audio_track)(void *, godot_int); - void (*update)(void *, godot_float); - godot_packed_byte_array *(*get_videoframe)(void *); - godot_int (*get_audioframe)(void *, float *, int); - godot_int (*get_channels)(const void *); - godot_int (*get_mix_rate)(const void *); - godot_vector2 (*get_texture_size)(const void *); -} godot_videodecoder_interface_gdnative; - -typedef int (*GDNativeAudioMixCallback)(void *, const float *, int); - -// FileAccess wrappers for custom FFmpeg IO -godot_int GDAPI godot_videodecoder_file_read(void *file_ptr, uint8_t *buf, int buf_size); -int64_t GDAPI godot_videodecoder_file_seek(void *file_ptr, int64_t pos, int whence); -void GDAPI godot_videodecoder_register_decoder(const godot_videodecoder_interface_gdnative *p_interface); - -#ifdef __cplusplus -} -#endif - -#endif /* GODOT_NATIVEVIDEODECODER_H */ diff --git a/modules/gdnative/nativescript/SCsub b/modules/gdnative/nativescript/SCsub deleted file mode 100644 index 4212e87a87..0000000000 --- a/modules/gdnative/nativescript/SCsub +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python - -Import("env") -Import("env_gdnative") - -env_gdnative.add_source_files(env.modules_sources, "*.cpp") - -if "platform" in env and env["platform"] in ["linuxbsd", "iphone"]: - env.Append(LINKFLAGS=["-rdynamic"]) diff --git a/modules/gdnative/nativescript/api_generator.cpp b/modules/gdnative/nativescript/api_generator.cpp deleted file mode 100644 index 0309d1d9c7..0000000000 --- a/modules/gdnative/nativescript/api_generator.cpp +++ /dev/null @@ -1,948 +0,0 @@ -/*************************************************************************/ -/* api_generator.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "api_generator.h" - -#ifdef TOOLS_ENABLED - -#include "core/config/engine.h" -#include "core/core_constants.h" -#include "core/io/file_access.h" -#include "core/object/class_db.h" -#include "core/string/string_builder.h" -#include "core/templates/pair.h" -#include "core/variant/variant_parser.h" - -// helper stuff - -static Error save_file(const String &p_path, const List<String> &p_content) { - FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE); - - ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE); - - for (const List<String>::Element *e = p_content.front(); e != nullptr; e = e->next()) { - file->store_string(e->get()); - } - - file->close(); - - return OK; -} - -// helper stuff end - -struct MethodAPI { - String method_name; - String return_type; - - List<String> argument_types; - List<String> argument_names; - - Map<int, Variant> default_arguments; - - int argument_count = 0; - bool has_varargs = false; - bool is_editor = false; - bool is_noscript = false; - bool is_const = false; - bool is_static = false; // For builtin types. - bool is_reverse = false; - bool is_virtual = false; - bool is_from_script = false; -}; - -struct PropertyAPI { - String name; - String getter; - String setter; - String type; - int index = 0; -}; - -struct ConstantAPI { - String constant_name; - int constant_value = 0; - Variant builtin_constant_value; // For builtin types; - String builtin_constant_type; // For builtin types; -}; - -struct SignalAPI { - String name; - List<String> argument_types; - List<String> argument_names; - Map<int, Variant> default_arguments; -}; - -struct EnumAPI { - String name; - List<Pair<int, String>> values; -}; - -struct OperatorAPI { // For builtin types; - String name; - int oper = Variant::OP_MAX; - String other_type; - String return_type; -}; - -struct ClassAPI { - String class_name; - String super_class_name; - - ClassDB::APIType api_type = ClassDB::API_NONE; - - bool is_singleton = false; - String singleton_name; - bool is_instantiable = false; - // @Unclear - bool is_ref_counted = false; - bool has_indexing = false; // For builtin types. - String indexed_type; // For builtin types. - bool is_keyed = false; // For builtin types. - - List<MethodAPI> methods; - List<MethodAPI> constructors; // For builtin types. - List<PropertyAPI> properties; - List<ConstantAPI> constants; - List<SignalAPI> signals_; - List<EnumAPI> enums; - List<OperatorAPI> operators; // For builtin types. -}; - -static String get_type_name(const PropertyInfo &info) { - if (info.type == Variant::INT && (info.usage & PROPERTY_USAGE_CLASS_IS_ENUM)) { - return String("enum.") + String(info.class_name).replace(".", "::"); - } - if (info.class_name != StringName()) { - return info.class_name; - } - if (info.hint == PROPERTY_HINT_RESOURCE_TYPE) { - return info.class_name; - } - if (info.type == Variant::NIL && (info.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) { - return "Variant"; - } - if (info.type == Variant::NIL) { - return "void"; - } - return Variant::get_type_name(info.type); -} - -/* - * 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() { - List<ClassAPI> api; - - List<StringName> classes; - ClassDB::get_class_list(&classes); - classes.sort_custom<StringName::AlphCompare>(); - - // Register global constants as a fake CoreConstants singleton class - { - ClassAPI global_constants_api; - global_constants_api.class_name = "CoreConstants"; - global_constants_api.api_type = ClassDB::API_CORE; - global_constants_api.is_singleton = true; - global_constants_api.singleton_name = "CoreConstants"; - global_constants_api.is_instantiable = false; - const int constants_count = CoreConstants::get_global_constant_count(); - - Map<StringName, EnumAPI> enum_api_map; - for (int i = 0; i < constants_count; ++i) { - StringName enum_name = CoreConstants::get_global_constant_enum(i); - String name = String(CoreConstants::get_global_constant_name(i)); - int value = CoreConstants::get_global_constant_value(i); - - if (enum_name == StringName()) { - ConstantAPI constant_api; - constant_api.constant_name = name; - constant_api.constant_value = value; - global_constants_api.constants.push_back(constant_api); - } else { - EnumAPI enum_api; - if (enum_api_map.has(enum_name)) { - enum_api = enum_api_map[enum_name]; - } else { - enum_api.name = String(enum_name); - } - enum_api.values.push_back(Pair(value, name)); - - enum_api_map[enum_name] = enum_api; - } - } - for (const KeyValue<StringName, EnumAPI> &E : enum_api_map) { - global_constants_api.enums.push_back(E.value); - } - global_constants_api.constants.sort_custom<ConstantAPIComparator>(); - api.push_back(global_constants_api); - } - - for (List<StringName>::Element *e = classes.front(); e != nullptr; e = e->next()) { - StringName class_name = e->get(); - - if (!ClassDB::is_class_exposed(class_name)) { - continue; - } - - ClassAPI class_api; - class_api.api_type = ClassDB::get_api_type(e->get()); - class_api.class_name = class_name; - class_api.super_class_name = ClassDB::get_parent_class(class_name); - { - class_api.is_singleton = Engine::get_singleton()->has_singleton(class_name); - if (class_api.is_singleton) { - class_api.singleton_name = class_name; - } - } - class_api.is_instantiable = !class_api.is_singleton && ClassDB::can_instantiate(class_name); - - { - List<StringName> inheriters; - ClassDB::get_inheriters_from_class("RefCounted", &inheriters); - bool is_ref_counted = !!inheriters.find(class_name) || class_name == "RefCounted"; - // @Unclear - class_api.is_ref_counted = !class_api.is_singleton && is_ref_counted; - } - - // constants - { - List<String> constant; - ClassDB::get_integer_constant_list(class_name, &constant, true); - constant.sort_custom<NoCaseComparator>(); - for (List<String>::Element *c = constant.front(); c != nullptr; c = c->next()) { - ConstantAPI constant_api; - constant_api.constant_name = c->get(); - constant_api.constant_value = ClassDB::get_integer_constant(class_name, c->get()); - - class_api.constants.push_back(constant_api); - } - } - - // signals - { - 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; - - MethodInfo method_info = signals_[i]; - signal.name = method_info.name; - - for (int j = 0; j < method_info.arguments.size(); j++) { - PropertyInfo argument = method_info.arguments[j]; - String type; - String name = argument.name; - - if (argument.name.contains(":")) { - type = argument.name.get_slice(":", 1); - name = argument.name.get_slice(":", 0); - } else { - type = get_type_name(argument); - } - - signal.argument_names.push_back(name); - signal.argument_types.push_back(type); - } - - Vector<Variant> default_arguments = method_info.default_arguments; - - int default_start = signal.argument_names.size() - default_arguments.size(); - - for (int j = 0; j < default_arguments.size(); j++) { - signal.default_arguments[default_start + j] = default_arguments[j]; - } - - class_api.signals_.push_back(signal); - } - } - - //properties - { - List<PropertyInfo> properties; - ClassDB::get_property_list(class_name, &properties, true); - properties.sort_custom<PropertyInfoComparator>(); - - for (List<PropertyInfo>::Element *p = properties.front(); p != nullptr; p = p->next()) { - PropertyAPI property_api; - - property_api.name = p->get().name; - property_api.getter = ClassDB::get_property_getter(class_name, p->get().name); - property_api.setter = ClassDB::get_property_setter(class_name, p->get().name); - - if (p->get().name.contains(":")) { - property_api.type = p->get().name.get_slice(":", 1); - property_api.name = p->get().name.get_slice(":", 0); - } else { - MethodInfo minfo; - ClassDB::get_method_info(class_name, property_api.getter, &minfo, true, false); - property_api.type = get_type_name(minfo.return_val); - } - - property_api.index = ClassDB::get_property_index(class_name, p->get().name); - - if (!property_api.setter.is_empty() || !property_api.getter.is_empty()) { - class_api.properties.push_back(property_api); - } - } - } - - //methods - { - List<MethodInfo> methods; - ClassDB::get_method_list(class_name, &methods, true); - methods.sort_custom<MethodInfoComparator>(); - - for (List<MethodInfo>::Element *m = methods.front(); m != nullptr; m = m->next()) { - MethodAPI method_api; - MethodBind *method_bind = ClassDB::get_method(class_name, m->get().name); - MethodInfo &method_info = m->get(); - - //method name - method_api.method_name = method_info.name; - //method return type - if (method_api.method_name.contains(":")) { - method_api.return_type = method_api.method_name.get_slice(":", 1); - method_api.method_name = method_api.method_name.get_slice(":", 0); - } else { - method_api.return_type = get_type_name(m->get().return_val); - } - - method_api.argument_count = method_info.arguments.size(); - method_api.has_varargs = method_bind && method_bind->is_vararg(); - - // Method flags - method_api.is_virtual = false; - if (method_info.flags) { - const uint32_t flags = method_info.flags; - method_api.is_editor = flags & METHOD_FLAG_EDITOR; - method_api.is_noscript = flags & METHOD_FLAG_NOSCRIPT; - method_api.is_const = flags & METHOD_FLAG_CONST; - method_api.is_reverse = flags & METHOD_FLAG_REVERSE; - method_api.is_virtual = flags & METHOD_FLAG_VIRTUAL; - method_api.is_from_script = flags & METHOD_FLAG_FROM_SCRIPT; - } - - method_api.is_virtual = method_api.is_virtual || method_api.method_name[0] == '_'; - - // method argument name and type - - for (int i = 0; i < method_api.argument_count; i++) { - String arg_name; - String arg_type; - PropertyInfo arg_info = method_info.arguments[i]; - - arg_name = arg_info.name; - - if (arg_info.name.contains(":")) { - arg_type = arg_info.name.get_slice(":", 1); - arg_name = arg_info.name.get_slice(":", 0); - } else if (arg_info.hint == PROPERTY_HINT_RESOURCE_TYPE) { - arg_type = arg_info.class_name; - } else if (arg_info.type == Variant::NIL) { - arg_type = "Variant"; - } else if (arg_info.type == Variant::OBJECT) { - arg_type = arg_info.class_name; - if (arg_type.is_empty()) { - arg_type = Variant::get_type_name(arg_info.type); - } - } else { - arg_type = get_type_name(arg_info); - } - - method_api.argument_names.push_back(arg_name); - method_api.argument_types.push_back(arg_type); - - if (method_bind && method_bind->has_default_argument(i)) { - method_api.default_arguments[i] = method_bind->get_default_argument(i); - } - } - - class_api.methods.push_back(method_api); - } - } - - // enums - { - List<EnumAPI> enums; - List<StringName> enum_names; - ClassDB::get_enum_list(class_name, &enum_names, true); - for (const StringName &E : enum_names) { - List<StringName> value_names; - EnumAPI enum_api; - enum_api.name = E; - ClassDB::get_enum_constants(class_name, E, &value_names, true); - for (List<StringName>::Element *val_e = value_names.front(); val_e; val_e = val_e->next()) { - int int_val = ClassDB::get_integer_constant(class_name, val_e->get(), nullptr); - enum_api.values.push_back(Pair<int, String>(int_val, val_e->get())); - } - enum_api.values.sort_custom<PairSort<int, String>>(); - class_api.enums.push_back(enum_api); - } - } - - api.push_back(class_api); - } - - return api; -} - -/* - * Reads the builtin Variant API to a list - */ -List<ClassAPI> generate_c_builtin_api_types() { - List<ClassAPI> api; - - // Special class for the utility methods. - { - ClassAPI utility_api; - utility_api.class_name = "Utilities"; - utility_api.is_instantiable = false; - - List<StringName> utility_functions; - Variant::get_utility_function_list(&utility_functions); - for (const StringName &E : utility_functions) { - const StringName &function_name = E; - - MethodAPI function_api; - function_api.method_name = function_name; - function_api.has_varargs = Variant::is_utility_function_vararg(function_name); - function_api.argument_count = function_api.has_varargs ? 0 : Variant::get_utility_function_argument_count(function_name); - function_api.is_const = Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH; - - for (int i = 0; i < function_api.argument_count; i++) { - function_api.argument_names.push_back(Variant::get_utility_function_argument_name(function_name, i)); - Variant::Type arg_type = Variant::get_utility_function_argument_type(function_name, i); - function_api.argument_types.push_back(arg_type == Variant::NIL ? "Variant" : Variant::get_type_name(arg_type)); - } - - if (Variant::has_utility_function_return_value(function_name)) { - Variant::Type ret_type = Variant::get_utility_function_return_type(function_name); - function_api.return_type = ret_type == Variant::NIL ? "Variant" : Variant::get_type_name(ret_type); - } else { - function_api.return_type = "void"; - } - - utility_api.methods.push_back(function_api); - } - - api.push_back(utility_api); - } - - for (int t = 0; t < Variant::VARIANT_MAX; t++) { - Variant::Type type = (Variant::Type)t; - - ClassAPI class_api; - class_api.class_name = Variant::get_type_name(type); - class_api.is_instantiable = true; - class_api.has_indexing = Variant::has_indexing(type); - class_api.indexed_type = Variant::get_type_name(Variant::get_indexed_element_type(type)); - class_api.is_keyed = Variant::is_keyed(type); - // Types that are passed by reference. - switch (type) { - case Variant::OBJECT: - case Variant::DICTIONARY: - case Variant::ARRAY: - case Variant::PACKED_BYTE_ARRAY: - case Variant::PACKED_INT32_ARRAY: - case Variant::PACKED_INT64_ARRAY: - case Variant::PACKED_FLOAT32_ARRAY: - case Variant::PACKED_FLOAT64_ARRAY: - case Variant::PACKED_STRING_ARRAY: - case Variant::PACKED_VECTOR2_ARRAY: - case Variant::PACKED_VECTOR3_ARRAY: - case Variant::PACKED_COLOR_ARRAY: - class_api.is_ref_counted = true; - break; - default: - class_api.is_ref_counted = false; - break; - } - - // Methods. - - List<StringName> methods; - Variant::get_builtin_method_list(type, &methods); - for (const StringName &E : methods) { - const StringName &method_name = E; - - MethodAPI method_api; - - method_api.method_name = method_name; - method_api.argument_count = Variant::get_builtin_method_argument_count(type, method_name); - method_api.has_varargs = Variant::is_builtin_method_vararg(type, method_name); - method_api.is_const = Variant::is_builtin_method_const(type, method_name); - method_api.is_static = Variant::is_builtin_method_static(type, method_name); - - for (int i = 0; i < method_api.argument_count; i++) { - method_api.argument_names.push_back(Variant::get_builtin_method_argument_name(type, method_name, i)); - Variant::Type arg_type = Variant::get_builtin_method_argument_type(type, method_name, i); - method_api.argument_types.push_back(arg_type == Variant::NIL ? "Variant" : Variant::get_type_name(arg_type)); - } - - Vector<Variant> default_arguments = Variant::get_builtin_method_default_arguments(type, method_name); - - int default_start = method_api.argument_names.size() - default_arguments.size(); - - for (int i = 0; i < default_arguments.size(); i++) { - method_api.default_arguments[default_start + i] = default_arguments[i]; - } - - if (Variant::has_builtin_method_return_value(type, method_name)) { - Variant::Type ret_type = Variant::get_builtin_method_return_type(type, method_name); - method_api.return_type = ret_type == Variant::NIL ? "Variant" : Variant::get_type_name(ret_type); - } else { - method_api.return_type = "void"; - } - - class_api.methods.push_back(method_api); - } - - // Constructors. - - for (int c = 0; c < Variant::get_constructor_count(type); c++) { - MethodAPI constructor_api; - - constructor_api.method_name = Variant::get_type_name(type); - constructor_api.argument_count = Variant::get_constructor_argument_count(type, c); - constructor_api.return_type = Variant::get_type_name(type); - - for (int i = 0; i < constructor_api.argument_count; i++) { - constructor_api.argument_names.push_back(Variant::get_constructor_argument_name(type, c, i)); - Variant::Type arg_type = Variant::get_constructor_argument_type(type, c, i); - constructor_api.argument_types.push_back(arg_type == Variant::NIL ? "Variant" : Variant::get_type_name(arg_type)); - } - - class_api.constructors.push_back(constructor_api); - } - - // Constants. - - List<StringName> constants; - Variant::get_constants_for_type(type, &constants); - for (const StringName &E : constants) { - const StringName &constant_name = E; - ConstantAPI constant_api; - - constant_api.constant_name = constant_name; - constant_api.builtin_constant_value = Variant::get_constant_value(type, constant_name); - constant_api.builtin_constant_type = Variant::get_type_name(constant_api.builtin_constant_value.get_type()); - - class_api.constants.push_back(constant_api); - } - - // Members. - - List<StringName> members; - Variant::get_member_list(type, &members); - for (const StringName &E : members) { - const StringName &member_name = E; - - PropertyAPI member_api; - member_api.name = member_name; - Variant::Type member_type = Variant::get_member_type(type, member_name); - member_api.type = member_type == Variant::NIL ? "Variant" : Variant::get_type_name(member_type); - - class_api.properties.push_back(member_api); - } - - // Operators. - - for (int op = 0; op < Variant::OP_MAX; op++) { - Variant::Operator oper = (Variant::Operator)op; - - for (int ot = 0; ot < Variant::VARIANT_MAX; ot++) { - Variant::Type other_type = (Variant::Type)ot; - - if (!Variant::get_validated_operator_evaluator(oper, type, other_type)) { - continue; - } - - OperatorAPI oper_api; - oper_api.name = Variant::get_operator_name(oper); - oper_api.oper = oper; - oper_api.other_type = Variant::get_type_name(other_type); - oper_api.return_type = Variant::get_type_name(Variant::get_operator_return_type(oper, type, other_type)); - - class_api.operators.push_back(oper_api); - } - } - - api.push_back(class_api); - } - - return api; -} - -/* - * Generates the JSON source from the API in p_api - */ -static List<String> generate_c_api_json(const List<ClassAPI> &p_api) { - // I'm sorry for the \t mess - - List<String> source; - VariantWriter writer; - - source.push_back("[\n"); - - for (const List<ClassAPI>::Element *c = p_api.front(); c != nullptr; c = c->next()) { - ClassAPI api = c->get(); - - source.push_back("\t{\n"); - - source.push_back("\t\t\"name\": \"" + api.class_name + "\",\n"); - 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\"instantiable\": ") + (api.is_instantiable ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\"is_ref_counted\": ") + (api.is_ref_counted ? "true" : "false") + ",\n"); - - source.push_back("\t\t\"constants\": {\n"); - for (List<ConstantAPI>::Element *e = api.constants.front(); e; e = e->next()) { - source.push_back("\t\t\t\"" + e->get().constant_name + "\": " + String::num_int64(e->get().constant_value) + (e->next() ? "," : "") + "\n"); - } - source.push_back("\t\t},\n"); - - source.push_back("\t\t\"properties\": [\n"); - for (List<PropertyAPI>::Element *e = api.properties.front(); e; e = e->next()) { - source.push_back("\t\t\t{\n"); - source.push_back("\t\t\t\t\"name\": \"" + e->get().name + "\",\n"); - source.push_back("\t\t\t\t\"type\": \"" + e->get().type + "\",\n"); - source.push_back("\t\t\t\t\"getter\": \"" + e->get().getter + "\",\n"); - source.push_back("\t\t\t\t\"setter\": \"" + e->get().setter + "\",\n"); - source.push_back(String("\t\t\t\t\"index\": ") + itos(e->get().index) + "\n"); - source.push_back(String("\t\t\t}") + (e->next() ? "," : "") + "\n"); - } - source.push_back("\t\t],\n"); - - source.push_back("\t\t\"signals\": [\n"); - for (List<SignalAPI>::Element *e = api.signals_.front(); e; e = e->next()) { - source.push_back("\t\t\t{\n"); - source.push_back("\t\t\t\t\"name\": \"" + e->get().name + "\",\n"); - source.push_back("\t\t\t\t\"arguments\": [\n"); - for (int i = 0; i < e->get().argument_names.size(); i++) { - source.push_back("\t\t\t\t\t{\n"); - source.push_back("\t\t\t\t\t\t\"name\": \"" + e->get().argument_names[i] + "\",\n"); - source.push_back("\t\t\t\t\t\t\"type\": \"" + e->get().argument_types[i] + "\",\n"); - source.push_back(String("\t\t\t\t\t\t\"has_default_value\": ") + (e->get().default_arguments.has(i) ? "true" : "false") + ",\n"); - String default_value; - if (e->get().default_arguments.has(i)) { - writer.write_to_string(e->get().default_arguments[i], default_value); - default_value = default_value.replace("\n", "").json_escape(); - } - source.push_back("\t\t\t\t\t\t\"default_value\": \"" + default_value + "\"\n"); - source.push_back(String("\t\t\t\t\t}") + ((i < e->get().argument_names.size() - 1) ? "," : "") + "\n"); - } - source.push_back("\t\t\t\t]\n"); - source.push_back(String("\t\t\t}") + (e->next() ? "," : "") + "\n"); - } - source.push_back("\t\t],\n"); - - source.push_back("\t\t\"methods\": [\n"); - for (List<MethodAPI>::Element *e = api.methods.front(); e; e = e->next()) { - source.push_back("\t\t\t{\n"); - source.push_back("\t\t\t\t\"name\": \"" + e->get().method_name + "\",\n"); - source.push_back("\t\t\t\t\"return_type\": \"" + e->get().return_type + "\",\n"); - source.push_back(String("\t\t\t\t\"is_editor\": ") + (e->get().is_editor ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\t\t\"is_noscript\": ") + (e->get().is_noscript ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\t\t\"is_const\": ") + (e->get().is_const ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\t\t\"is_reverse\": ") + (e->get().is_reverse ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\t\t\"is_virtual\": ") + (e->get().is_virtual ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\t\t\"has_varargs\": ") + (e->get().has_varargs ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\t\t\"is_from_script\": ") + (e->get().is_from_script ? "true" : "false") + ",\n"); - source.push_back("\t\t\t\t\"arguments\": [\n"); - for (int i = 0; i < e->get().argument_names.size(); i++) { - source.push_back("\t\t\t\t\t{\n"); - source.push_back("\t\t\t\t\t\t\"name\": \"" + e->get().argument_names[i] + "\",\n"); - source.push_back("\t\t\t\t\t\t\"type\": \"" + e->get().argument_types[i] + "\",\n"); - source.push_back(String("\t\t\t\t\t\t\"has_default_value\": ") + (e->get().default_arguments.has(i) ? "true" : "false") + ",\n"); - String default_value; - if (e->get().default_arguments.has(i)) { - writer.write_to_string(e->get().default_arguments[i], default_value); - default_value = default_value.replace("\n", "").json_escape(); - } - source.push_back("\t\t\t\t\t\t\"default_value\": \"" + default_value + "\"\n"); - source.push_back(String("\t\t\t\t\t}") + ((i < e->get().argument_names.size() - 1) ? "," : "") + "\n"); - } - source.push_back("\t\t\t\t]\n"); - source.push_back(String("\t\t\t}") + (e->next() ? "," : "") + "\n"); - } - source.push_back("\t\t],\n"); - - source.push_back("\t\t\"enums\": [\n"); - for (List<EnumAPI>::Element *e = api.enums.front(); e; e = e->next()) { - source.push_back("\t\t\t{\n"); - source.push_back("\t\t\t\t\"name\": \"" + e->get().name + "\",\n"); - source.push_back("\t\t\t\t\"values\": {\n"); - for (List<Pair<int, String>>::Element *val_e = e->get().values.front(); val_e; val_e = val_e->next()) { - source.push_back("\t\t\t\t\t\"" + val_e->get().second + "\": " + itos(val_e->get().first)); - source.push_back(String((val_e->next() ? "," : "")) + "\n"); - } - source.push_back("\t\t\t\t}\n"); - source.push_back(String("\t\t\t}") + (e->next() ? "," : "") + "\n"); - } - source.push_back("\t\t]\n"); - - source.push_back(String("\t}") + (c->next() ? "," : "") + "\n"); - } - source.push_back("]"); - - return source; -} - -static int indent_level = 0; - -static void append_indented(StringBuilder &p_source, const String &p_text) { - for (int i = 0; i < indent_level; i++) { - p_source.append("\t"); - } - p_source.append(p_text); - p_source.append("\n"); -} - -static void append_indented(StringBuilder &p_source, const char *p_text) { - for (int i = 0; i < indent_level; i++) { - p_source.append("\t"); - } - p_source.append(p_text); - p_source.append("\n"); -} - -static void write_builtin_method(StringBuilder &p_source, const MethodAPI &p_method) { - VariantWriter writer; - - append_indented(p_source, vformat(R"("name": "%s",)", p_method.method_name)); - append_indented(p_source, vformat(R"("return_type": "%s",)", p_method.return_type)); - append_indented(p_source, vformat(R"("is_const": %s,)", p_method.is_const ? "true" : "false")); - append_indented(p_source, vformat(R"("is_static": %s,)", p_method.is_static ? "true" : "false")); - append_indented(p_source, vformat(R"("has_varargs": %s,)", p_method.has_varargs ? "true" : "false")); - - append_indented(p_source, R"("arguments": [)"); - indent_level++; - for (int i = 0; i < p_method.argument_count; i++) { - append_indented(p_source, "{"); - indent_level++; - - append_indented(p_source, vformat(R"("name": "%s",)", p_method.argument_names[i])); - append_indented(p_source, vformat(R"("type": "%s",)", p_method.argument_types[i])); - append_indented(p_source, vformat(R"("has_default_value": %s,)", p_method.default_arguments.has(i) ? "true" : "false")); - String default_value; - if (p_method.default_arguments.has(i)) { - writer.write_to_string(p_method.default_arguments[i], default_value); - default_value = default_value.replace("\n", "").json_escape(); - } - append_indented(p_source, vformat(R"("default_value": "%s")", default_value)); - - indent_level--; - append_indented(p_source, i < p_method.argument_count - 1 ? "}," : "}"); - } - indent_level--; - append_indented(p_source, "]"); -} - -static List<String> generate_c_builtin_api_json(const List<ClassAPI> &p_api) { - StringBuilder source; - - source.append("[\n"); - - indent_level = 1; - - for (const List<ClassAPI>::Element *C = p_api.front(); C; C = C->next()) { - const ClassAPI &class_api = C->get(); - append_indented(source, "{"); - indent_level++; - - append_indented(source, vformat(R"("name": "%s",)", class_api.class_name)); - append_indented(source, vformat(R"("is_instantiable": %s,)", class_api.is_instantiable ? "true" : "false")); - append_indented(source, vformat(R"("is_ref_counted": %s,)", class_api.is_ref_counted ? "true" : "false")); - append_indented(source, vformat(R"("has_indexing": %s,)", class_api.has_indexing ? "true" : "false")); - append_indented(source, vformat(R"("indexed_type": "%s",)", class_api.has_indexing && class_api.indexed_type == "Nil" ? "Variant" : class_api.indexed_type)); - append_indented(source, vformat(R"("is_keyed": %s,)", class_api.is_keyed ? "true" : "false")); - - // Constructors. - append_indented(source, R"("constructors": [)"); - indent_level++; - for (const List<MethodAPI>::Element *E = class_api.constructors.front(); E; E = E->next()) { - const MethodAPI &constructor = E->get(); - append_indented(source, "{"); - indent_level++; - - write_builtin_method(source, constructor); - - indent_level--; - append_indented(source, E->next() ? "}," : "}"); - } - indent_level--; - append_indented(source, "],"); - - // Constants. - append_indented(source, R"("constants": [)"); - indent_level++; - for (const List<ConstantAPI>::Element *E = class_api.constants.front(); E; E = E->next()) { - const ConstantAPI &constant = E->get(); - append_indented(source, "{"); - indent_level++; - - append_indented(source, vformat(R"("name": "%s",)", constant.constant_name)); - append_indented(source, vformat(R"("type": "%s",)", constant.builtin_constant_type)); - append_indented(source, vformat(R"("value": "%s")", constant.builtin_constant_value.operator String())); - - indent_level--; - append_indented(source, E->next() ? "}," : "}"); - } - indent_level--; - append_indented(source, "],"); - - // Methods. - append_indented(source, R"("methods": [)"); - indent_level++; - for (const List<MethodAPI>::Element *E = class_api.methods.front(); E; E = E->next()) { - const MethodAPI &method = E->get(); - append_indented(source, "{"); - indent_level++; - - write_builtin_method(source, method); - - indent_level--; - append_indented(source, E->next() ? "}," : "}"); - } - indent_level--; - append_indented(source, "],"); - - // Members. - append_indented(source, R"("members": [)"); - indent_level++; - for (const List<PropertyAPI>::Element *E = class_api.properties.front(); E; E = E->next()) { - const PropertyAPI &member = E->get(); - append_indented(source, "{"); - indent_level++; - - append_indented(source, vformat(R"("name": "%s",)", member.name)); - append_indented(source, vformat(R"("type": "%s")", member.type)); - - indent_level--; - append_indented(source, E->next() ? "}," : "}"); - } - indent_level--; - append_indented(source, "],"); - - // Operators. - append_indented(source, R"("operators": [)"); - indent_level++; - for (const List<OperatorAPI>::Element *E = class_api.operators.front(); E; E = E->next()) { - const OperatorAPI &oper = E->get(); - append_indented(source, "{"); - indent_level++; - - append_indented(source, vformat(R"("name": "%s",)", oper.name)); - append_indented(source, vformat(R"("operator": %d,)", oper.oper)); - append_indented(source, vformat(R"("other_type": "%s",)", oper.other_type)); - append_indented(source, vformat(R"("return_type": "%s")", oper.return_type)); - - indent_level--; - append_indented(source, E->next() ? "}," : "}"); - } - indent_level--; - append_indented(source, "]"); - - indent_level--; - append_indented(source, C->next() ? "}," : "}"); - } - - indent_level--; - source.append("]\n"); - - List<String> result; - result.push_back(source.as_string()); - return result; -} - -#endif - -/* - * Saves the whole Godot API to a JSON file located at - * p_path - */ -Error generate_c_api(const String &p_path) { -#ifndef TOOLS_ENABLED - return ERR_BUG; -#else - - List<ClassAPI> api = generate_c_api_classes(); - - List<String> json_source = generate_c_api_json(api); - - return save_file(p_path, json_source); -#endif -} -/* - * Saves the builtin Godot API to a JSON file located at - * p_path - */ -Error generate_c_builtin_api(const String &p_path) { -#ifndef TOOLS_ENABLED - return ERR_BUG; -#else - - List<ClassAPI> api = generate_c_builtin_api_types(); - - List<String> json_source = generate_c_builtin_api_json(api); - - return save_file(p_path, json_source); -#endif -} diff --git a/modules/gdnative/nativescript/godot_nativescript.cpp b/modules/gdnative/nativescript/godot_nativescript.cpp deleted file mode 100644 index 992eeba8f4..0000000000 --- a/modules/gdnative/nativescript/godot_nativescript.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*************************************************************************/ -/* godot_nativescript.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "nativescript/godot_nativescript.h" - -#include "core/config/project_settings.h" -#include "core/core_constants.h" -#include "core/error/error_macros.h" -#include "core/object/class_db.h" -#include "core/variant/variant.h" -#include "gdnative/gdnative.h" -#include <stdint.h> - -#include "nativescript.h" - -#ifdef __cplusplus -extern "C" { -#endif - -extern "C" void _native_script_hook() { -} - -#define NSL NativeScriptLanguage::get_singleton() - -// Script API - -void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc> *classes = &NSL->library_classes[*s]; - - NativeScriptDesc desc; - - desc.create_func = p_create_func; - desc.destroy_func = p_destroy_func; - desc.is_tool = false; - - desc.base = p_base; - - if (classes->has(p_base)) { - desc.base_data = &(*classes)[p_base]; - desc.base_native_type = desc.base_data->base_native_type; - - const NativeScriptDesc *b = desc.base_data; - while (b) { - desc.rpc_methods.append_array(b->rpc_methods); - b = b->base_data; - } - - } else { - desc.base_data = nullptr; - desc.base_native_type = p_base; - } - - classes->insert(p_name, desc); -} - -void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc> *classes = &NSL->library_classes[*s]; - - NativeScriptDesc desc; - - desc.create_func = p_create_func; - desc.destroy_func = p_destroy_func; - desc.is_tool = true; - desc.base = p_base; - - if (classes->has(p_base)) { - desc.base_data = &(*classes)[p_base]; - desc.base_native_type = desc.base_data->base_native_type; - - const NativeScriptDesc *b = desc.base_data; - while (b) { - desc.rpc_methods.append_array(b->rpc_methods); - b = b->base_data; - } - - } else { - desc.base_data = nullptr; - desc.base_native_type = p_base; - } - - classes->insert(p_name, desc); -} - -void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_nativescript_method_attributes p_attr, godot_nativescript_instance_method p_method) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - ERR_FAIL_COND_MSG(!E, "Attempted to register method on non-existent class."); - - NativeScriptDesc::Method method; - method.method = p_method; - method.rpc_mode = p_attr.rpc_type; - method.rpc_method_id = UINT16_MAX; - method.info = MethodInfo(p_function_name); - - E->get().methods.insert(p_function_name, method); - - if (p_attr.rpc_type != GODOT_METHOD_RPC_MODE_DISABLED) { - Multiplayer::RPCConfig nd; - nd.name = String(p_name); - nd.rpc_mode = Multiplayer::RPCMode(p_attr.rpc_type); - E->get().rpc_methods.push_back(nd); - } -} - -void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_nativescript_property_attributes *p_attr, godot_nativescript_property_set_func p_set_func, godot_nativescript_property_get_func p_get_func) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - ERR_FAIL_COND_MSG(!E, "Attempted to register method on non-existent class."); - - NativeScriptDesc::Property property; - property.default_value = *(Variant *)&p_attr->default_value; - property.getter = p_get_func; - property.setter = p_set_func; - property.info = PropertyInfo((Variant::Type)p_attr->type, - p_path, - (PropertyHint)p_attr->hint, - *(String *)&p_attr->hint_string, - (PropertyUsageFlags)p_attr->usage); - - E->get().properties.insert(p_path, property); -} - -void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const char *p_name, const godot_nativescript_signal *p_signal) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - ERR_FAIL_COND_MSG(!E, "Attempted to register method on non-existent class."); - - List<PropertyInfo> args; - Vector<Variant> default_args; - - for (int i = 0; i < p_signal->num_args; i++) { - PropertyInfo info; - - godot_nativescript_signal_argument arg = p_signal->args[i]; - - info.hint = (PropertyHint)arg.hint; - info.hint_string = *(String *)&arg.hint_string; - info.name = *(String *)&arg.name; - info.type = (Variant::Type)arg.type; - info.usage = (PropertyUsageFlags)arg.usage; - - args.push_back(info); - } - - for (int i = 0; i < p_signal->num_default_args; i++) { - Variant *v; - godot_nativescript_signal_argument attrib = p_signal->args[i]; - - v = (Variant *)&attrib.default_value; - - default_args.push_back(*v); - } - - MethodInfo method_info; - method_info.name = *(String *)&p_signal->name; - method_info.arguments = args; - method_info.default_arguments = default_args; - - NativeScriptDesc::Signal signal; - signal.signal = method_info; - - E->get().signals_.insert(*(String *)&p_signal->name, signal); -} - -void GDAPI *godot_nativescript_get_userdata(godot_object *p_instance) { - Object *instance = (Object *)p_instance; - if (!instance) { - return nullptr; - } - if (instance->get_script_instance() && instance->get_script_instance()->get_language() == NativeScriptLanguage::get_singleton()) { - return ((NativeScriptInstance *)instance->get_script_instance())->userdata; - } - return nullptr; -} - -/* - * - * - * NativeScript 1.1 - * - * - */ - -void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_handle, const char *p_name, const char *p_function_name, int p_num_args, const godot_nativescript_method_argument *p_args) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - 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); - ERR_FAIL_COND_MSG(!method, "Attempted to add argument information to non-existent method."); - - MethodInfo *method_information = &method->get().info; - - List<PropertyInfo> args; - - for (int i = 0; i < p_num_args; i++) { - godot_nativescript_method_argument arg = p_args[i]; - String name = *(String *)&arg.name; - String hint_string = *(String *)&arg.hint_string; - - Variant::Type type = (Variant::Type)arg.type; - PropertyHint hint = (PropertyHint)arg.hint; - - args.push_back(PropertyInfo(type, p_name, hint, hint_string)); - } - - method_information->arguments = args; -} - -void GDAPI godot_nativescript_set_class_documentation(void *p_gdnative_handle, const char *p_name, godot_string p_documentation) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - ERR_FAIL_COND_MSG(!E, "Attempted to add documentation to a non-existent class."); - - E->get().documentation = *(String *)&p_documentation; -} - -void GDAPI godot_nativescript_set_method_documentation(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_string p_documentation) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - 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); - ERR_FAIL_COND_MSG(!method, "Attempted to add documentation to non-existent method."); - - method->get().documentation = *(String *)&p_documentation; -} - -void GDAPI godot_nativescript_set_property_documentation(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_string p_documentation) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - 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); - ERR_FAIL_COND_MSG(!property, "Attempted to add documentation to non-existent property."); - - property.get().documentation = *(String *)&p_documentation; -} - -void GDAPI godot_nativescript_set_signal_documentation(void *p_gdnative_handle, const char *p_name, const char *p_signal_name, godot_string p_documentation) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - 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); - ERR_FAIL_COND_MSG(!signal, "Attempted to add documentation to non-existent signal."); - - signal->get().documentation = *(String *)&p_documentation; -} - -void GDAPI godot_nativescript_set_global_type_tag(int p_idx, const char *p_name, const void *p_type_tag) { - NativeScriptLanguage::get_singleton()->set_global_type_tag(p_idx, StringName(p_name), p_type_tag); -} - -const void GDAPI *godot_nativescript_get_global_type_tag(int p_idx, const char *p_name) { - return NativeScriptLanguage::get_singleton()->get_global_type_tag(p_idx, StringName(p_name)); -} - -void GDAPI godot_nativescript_set_type_tag(void *p_gdnative_handle, const char *p_name, const void *p_type_tag) { - String *s = (String *)p_gdnative_handle; - - Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - ERR_FAIL_COND_MSG(!E, "Attempted to set type tag on a non-existent class."); - - E->get().type_tag = p_type_tag; -} - -const void GDAPI *godot_nativescript_get_type_tag(const godot_object *p_object) { - const Object *o = (Object *)p_object; - - if (!o->get_script_instance()) { - return nullptr; - } else { - NativeScript *script = Object::cast_to<NativeScript>(o->get_script_instance()->get_script().ptr()); - if (!script) { - return nullptr; - } - - if (script->get_script_desc()) { - return script->get_script_desc()->type_tag; - } - } - - return nullptr; -} - -int GDAPI godot_nativescript_register_instance_binding_data_functions(godot_nativescript_instance_binding_functions p_binding_functions) { - return NativeScriptLanguage::get_singleton()->register_binding_functions(p_binding_functions); -} - -void GDAPI godot_nativescript_unregister_instance_binding_data_functions(int p_idx) { - NativeScriptLanguage::get_singleton()->unregister_binding_functions(p_idx); -} - -void GDAPI *godot_nativescript_get_instance_binding_data(int p_idx, godot_object *p_object) { - return nullptr; -} - -void GDAPI godot_nativescript_profiling_add_data(const char *p_signature, uint64_t p_time) { - NativeScriptLanguage::get_singleton()->profiling_add_data(StringName(p_signature), p_time); -} - -#ifdef __cplusplus -} -#endif diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp deleted file mode 100644 index 5d5414c694..0000000000 --- a/modules/gdnative/nativescript/nativescript.cpp +++ /dev/null @@ -1,1780 +0,0 @@ -/*************************************************************************/ -/* nativescript.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "nativescript.h" - -#include <stdint.h> - -#include "gdnative/gdnative.h" - -#include "core/config/project_settings.h" -#include "core/core_constants.h" -#include "core/core_string_names.h" -#include "core/io/file_access.h" -#include "core/io/file_access_encrypted.h" -#include "core/os/os.h" - -#include "main/main.h" - -#include "scene/main/scene_tree.h" -#include "scene/resources/resource_format_text.h" - -#include <stdlib.h> - -#ifndef NO_THREADS -#include "core/os/thread.h" -#endif - -#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED) -#include "api_generator.h" -#endif - -#ifdef TOOLS_ENABLED -#include "editor/editor_node.h" -#endif - -void NativeScript::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_class_name", "class_name"), &NativeScript::set_class_name); - ClassDB::bind_method(D_METHOD("get_class_name"), &NativeScript::get_class_name); - - ClassDB::bind_method(D_METHOD("set_library", "library"), &NativeScript::set_library); - ClassDB::bind_method(D_METHOD("get_library"), &NativeScript::get_library); - - ClassDB::bind_method(D_METHOD("set_script_class_name", "class_name"), &NativeScript::set_script_class_name); - ClassDB::bind_method(D_METHOD("get_script_class_name"), &NativeScript::get_script_class_name); - ClassDB::bind_method(D_METHOD("set_script_class_icon_path", "icon_path"), &NativeScript::set_script_class_icon_path); - ClassDB::bind_method(D_METHOD("get_script_class_icon_path"), &NativeScript::get_script_class_icon_path); - - ClassDB::bind_method(D_METHOD("get_class_documentation"), &NativeScript::get_class_documentation); - ClassDB::bind_method(D_METHOD("get_method_documentation", "method"), &NativeScript::get_method_documentation); - ClassDB::bind_method(D_METHOD("get_signal_documentation", "signal_name"), &NativeScript::get_signal_documentation); - ClassDB::bind_method(D_METHOD("get_property_documentation", "path"), &NativeScript::get_property_documentation); - - ADD_PROPERTY(PropertyInfo(Variant::STRING, "class_name"), "set_class_name", "get_class_name"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "library", PROPERTY_HINT_RESOURCE_TYPE, "GDNativeLibrary"), "set_library", "get_library"); - ADD_GROUP("Script Class", "script_class_"); - 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("new")); -} - -#define NSL NativeScriptLanguage::get_singleton() - -#ifdef TOOLS_ENABLED - -void NativeScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) { - NativeScriptDesc *script_data = get_script_desc(); - - ERR_FAIL_COND(!script_data); - - List<PropertyInfo> info; - get_script_property_list(&info); - Map<StringName, Variant> values; - for (const PropertyInfo &E : info) { - Variant value; - get_property_default_value(E.name, value); - values[E.name] = value; - } - - p_placeholder->update(info, values); -} - -void NativeScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) { - placeholders.erase(p_placeholder); -} - -#endif - -bool NativeScript::inherits_script(const Ref<Script> &p_script) const { - Ref<NativeScript> ns = p_script; - if (ns.is_null()) { - return false; - } - - const NativeScriptDesc *other_s = ns->get_script_desc(); - if (!other_s) { - return false; - } - - const NativeScriptDesc *s = get_script_desc(); - - while (s) { - if (s == other_s) { - return true; - } - s = s->base_data; - } - - return false; -} - -void NativeScript::set_class_name(String p_class_name) { - class_name = p_class_name; -} - -String NativeScript::get_class_name() const { - return class_name; -} - -void NativeScript::set_library(Ref<GDNativeLibrary> p_library) { - if (!library.is_null()) { - WARN_PRINT("Library in NativeScript already set. Do nothing."); - return; - } - if (p_library.is_null()) { - return; - } - library = p_library; - lib_path = library->get_current_library_path(); - -#ifndef NO_THREADS - if (Thread::get_caller_id() != Thread::get_main_id()) { - NSL->defer_init_library(p_library, this); - } else -#endif - { - NSL->init_library(p_library); - NSL->register_script(this); - } -} - -Ref<GDNativeLibrary> NativeScript::get_library() const { - return library; -} - -void NativeScript::set_script_class_name(String p_type) { - script_class_name = p_type; -} - -String NativeScript::get_script_class_name() const { - return script_class_name; -} - -void NativeScript::set_script_class_icon_path(String p_icon_path) { - script_class_icon_path = p_icon_path; -} - -String NativeScript::get_script_class_icon_path() const { - return script_class_icon_path; -} - -bool NativeScript::can_instantiate() const { - NativeScriptDesc *script_data = get_script_desc(); - -#ifdef TOOLS_ENABLED - // Only valid if this is either a tool script or a "regular" script. - // (so, an environment where scripting is disabled (and not the editor) would not - // create objects). - return script_data && (is_tool() || ScriptServer::is_scripting_enabled()); -#else - return script_data; -#endif -} - -Ref<Script> NativeScript::get_base_script() const { - NativeScriptDesc *script_data = get_script_desc(); - - if (!script_data) { - return Ref<Script>(); - } - - NativeScript *script = (NativeScript *)NSL->create_script(); - Ref<NativeScript> ns = Ref<NativeScript>(script); - ERR_FAIL_COND_V(!ns.is_valid(), Ref<Script>()); - - ns->set_class_name(script_data->base); - ns->set_library(get_library()); - return ns; -} - -StringName NativeScript::get_instance_base_type() const { - NativeScriptDesc *script_data = get_script_desc(); - - if (!script_data) { - return ""; - } - - return script_data->base_native_type; -} - -ScriptInstance *NativeScript::instance_create(Object *p_this) { - NativeScriptDesc *script_data = get_script_desc(); - - if (!script_data) { - return nullptr; - } - - NativeScriptInstance *nsi = memnew(NativeScriptInstance); - - nsi->owner = p_this; - nsi->script = Ref<NativeScript>(this); - -#ifndef TOOLS_ENABLED - if (!ScriptServer::is_scripting_enabled()) { - nsi->userdata = nullptr; - } else { - nsi->userdata = script_data->create_func.create_func((godot_object *)p_this, script_data->create_func.method_data); - } -#else - nsi->userdata = script_data->create_func.create_func((godot_object *)p_this, script_data->create_func.method_data); -#endif - - { - MutexLock lock(owners_lock); - - instance_owners.insert(p_this); - } - - return nsi; -} - -PlaceHolderScriptInstance *NativeScript::placeholder_instance_create(Object *p_this) { -#ifdef TOOLS_ENABLED - PlaceHolderScriptInstance *sins = memnew(PlaceHolderScriptInstance(NSL, Ref<Script>(this), p_this)); - placeholders.insert(sins); - - _update_placeholder(sins); - - return sins; -#else - return nullptr; -#endif -} - -bool NativeScript::instance_has(const Object *p_this) const { - return instance_owners.has((Object *)p_this); -} - -bool NativeScript::has_source_code() const { - return false; -} - -String NativeScript::get_source_code() const { - return ""; -} - -void NativeScript::set_source_code(const String &p_code) { -} - -Error NativeScript::reload(bool p_keep_state) { - return FAILED; -} - -bool NativeScript::has_method(const StringName &p_method) const { - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - if (script_data->methods.has(p_method)) { - return true; - } - - script_data = script_data->base_data; - } - return false; -} - -MethodInfo NativeScript::get_method_info(const StringName &p_method) const { - NativeScriptDesc *script_data = get_script_desc(); - - if (!script_data) { - return MethodInfo(); - } - - while (script_data) { - Map<StringName, NativeScriptDesc::Method>::Element *M = script_data->methods.find(p_method); - - if (M) { - return M->get().info; - } - - script_data = script_data->base_data; - } - return MethodInfo(); -} - -bool NativeScript::is_valid() const { - return true; -} - -bool NativeScript::is_tool() const { - NativeScriptDesc *script_data = get_script_desc(); - - if (script_data) { - return script_data->is_tool; - } - - return false; -} - -ScriptLanguage *NativeScript::get_language() const { - return NativeScriptLanguage::get_singleton(); -} - -bool NativeScript::has_script_signal(const StringName &p_signal) const { - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - if (script_data->signals_.has(p_signal)) { - return true; - } - script_data = script_data->base_data; - } - return false; -} - -void NativeScript::get_script_signal_list(List<MethodInfo> *r_signals) const { - NativeScriptDesc *script_data = get_script_desc(); - - if (!script_data) { - return; - } - - Set<MethodInfo> signals_; - - while (script_data) { - for (const KeyValue<StringName, NativeScriptDesc::Signal> &S : script_data->signals_) { - signals_.insert(S.value.signal); - } - - script_data = script_data->base_data; - } - - for (Set<MethodInfo>::Element *E = signals_.front(); E; E = E->next()) { - r_signals->push_back(E->get()); - } -} - -bool NativeScript::get_property_default_value(const StringName &p_property, Variant &r_value) const { - NativeScriptDesc *script_data = get_script_desc(); - - OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P; - while (!P && script_data) { - P = script_data->properties.find(p_property); - script_data = script_data->base_data; - } - if (!P) { - return false; - } - - r_value = P.get().default_value; - return true; -} - -void NativeScript::update_exports() { -} - -void NativeScript::get_script_method_list(List<MethodInfo> *p_list) const { - NativeScriptDesc *script_data = get_script_desc(); - - if (!script_data) { - return; - } - - Set<MethodInfo> methods; - - while (script_data) { - for (const KeyValue<StringName, NativeScriptDesc::Method> &E : script_data->methods) { - methods.insert(E.value.info); - } - - script_data = script_data->base_data; - } - - for (Set<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - p_list->push_back(E->get()); - } -} - -void NativeScript::get_script_property_list(List<PropertyInfo> *p_list) const { - NativeScriptDesc *script_data = get_script_desc(); - - Set<StringName> existing_properties; - List<PropertyInfo>::Element *original_back = p_list->back(); - while (script_data) { - List<PropertyInfo>::Element *insert_position = original_back; - - for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.front(); E; E = E.next()) { - if (!existing_properties.has(E.key())) { - insert_position = p_list->insert_after(insert_position, E.get().info); - existing_properties.insert(E.key()); - } - } - script_data = script_data->base_data; - } -} - -const Vector<Multiplayer::RPCConfig> NativeScript::get_rpc_methods() const { - NativeScriptDesc *script_data = get_script_desc(); - ERR_FAIL_COND_V(!script_data, Vector<Multiplayer::RPCConfig>()); - - return script_data->rpc_methods; -} - -String NativeScript::get_class_documentation() const { - NativeScriptDesc *script_data = get_script_desc(); - - ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get class documentation on invalid NativeScript."); - - return script_data->documentation; -} - -String NativeScript::get_method_documentation(const StringName &p_method) const { - NativeScriptDesc *script_data = get_script_desc(); - - ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get method documentation on invalid NativeScript."); - - while (script_data) { - Map<StringName, NativeScriptDesc::Method>::Element *method = script_data->methods.find(p_method); - - if (method) { - return method->get().documentation; - } - - script_data = script_data->base_data; - } - - 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(); - - ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get signal documentation on invalid NativeScript."); - - while (script_data) { - Map<StringName, NativeScriptDesc::Signal>::Element *signal = script_data->signals_.find(p_signal_name); - - if (signal) { - return signal->get().documentation; - } - - script_data = script_data->base_data; - } - - 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(); - - ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get property documentation on invalid NativeScript."); - - while (script_data) { - OrderedHashMap<StringName, NativeScriptDesc::Property>::Element property = script_data->properties.find(p_path); - - if (property) { - return property.get().documentation; - } - - script_data = script_data->base_data; - } - - ERR_FAIL_V_MSG("", "Attempt to get property documentation for non-existent signal."); -} - -Variant NativeScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { - if (lib_path.is_empty() || class_name.is_empty() || library.is_null()) { - r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; - return Variant(); - } - - NativeScriptDesc *script_data = get_script_desc(); - - if (!script_data) { - r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; - return Variant(); - } - - r_error.error = Callable::CallError::CALL_OK; - - REF ref; - Object *owner = nullptr; - - if (!(script_data->base_native_type == "")) { - owner = ClassDB::instantiate(script_data->base_native_type); - } else { - owner = memnew(RefCounted); - } - - if (!owner) { - r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; - return Variant(); - } - - RefCounted *r = Object::cast_to<RefCounted>(owner); - if (r) { - ref = REF(r); - } - - NativeScriptInstance *instance = (NativeScriptInstance *)instance_create(owner); - - owner->set_script_instance(instance); - - if (!instance) { - if (ref.is_null()) { - memdelete(owner); //no owner, sorry - } - return Variant(); - } - - if (ref.is_valid()) { - return ref; - } else { - return owner; - } -} - -NativeScript::NativeScript() { - library = Ref<GDNative>(); - lib_path = ""; - class_name = ""; -} - -NativeScript::~NativeScript() { - NSL->unregister_script(this); -} - -#define GET_SCRIPT_DESC() script->get_script_desc() - -void NativeScriptInstance::_ml_call_reversed(NativeScriptDesc *script_data, const StringName &p_method, const Variant **p_args, int p_argcount) { - if (script_data->base_data) { - _ml_call_reversed(script_data->base_data, p_method, p_args, p_argcount); - } - - Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find(p_method); - if (E) { - godot_variant res = E->get().method.method((godot_object *)owner, E->get().method.method_data, userdata, p_argcount, (godot_variant **)p_args); - godot_variant_destroy(&res); - } -} - -bool NativeScriptInstance::set(const StringName &p_name, const Variant &p_value) { - NativeScriptDesc *script_data = GET_SCRIPT_DESC(); - - while (script_data) { - OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = script_data->properties.find(p_name); - if (P) { - P.get().setter.set_func((godot_object *)owner, - P.get().setter.method_data, - userdata, - (godot_variant *)&p_value); - return true; - } - - Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find("_set"); - if (E) { - Variant name = p_name; - const Variant *args[2] = { &name, &p_value }; - - godot_variant result; - result = E->get().method.method((godot_object *)owner, - E->get().method.method_data, - userdata, - 2, - (godot_variant **)args); - bool handled = *(Variant *)&result; - godot_variant_destroy(&result); - if (handled) { - return true; - } - } - - script_data = script_data->base_data; - } - return false; -} - -bool NativeScriptInstance::get(const StringName &p_name, Variant &r_ret) const { - NativeScriptDesc *script_data = GET_SCRIPT_DESC(); - - while (script_data) { - OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = script_data->properties.find(p_name); - if (P) { - godot_variant value; - value = P.get().getter.get_func((godot_object *)owner, - P.get().getter.method_data, - userdata); - r_ret = *(Variant *)&value; - godot_variant_destroy(&value); - return true; - } - - Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find("_get"); - if (E) { - Variant name = p_name; - const Variant *args[1] = { &name }; - - godot_variant result; - result = E->get().method.method((godot_object *)owner, - E->get().method.method_data, - userdata, - 1, - (godot_variant **)args); - r_ret = *(Variant *)&result; - godot_variant_destroy(&result); - if (r_ret.get_type() != Variant::NIL) { - return true; - } - } - - script_data = script_data->base_data; - } - return false; -} - -void NativeScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { - script->get_script_property_list(p_properties); - - NativeScriptDesc *script_data = GET_SCRIPT_DESC(); - - while (script_data) { - Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find("_get_property_list"); - if (E) { - godot_variant result; - result = E->get().method.method((godot_object *)owner, - E->get().method.method_data, - userdata, - 0, - nullptr); - Variant res = *(Variant *)&result; - godot_variant_destroy(&result); - - 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++) { - Dictionary d = arr[i]; - - ERR_CONTINUE(!d.has("name")); - ERR_CONTINUE(!d.has("type")); - - PropertyInfo info; - - info.type = Variant::Type(d["type"].operator int64_t()); - ERR_CONTINUE(info.type < 0 || info.type >= Variant::VARIANT_MAX); - - info.name = d["name"]; - ERR_CONTINUE(info.name.is_empty()); - - if (d.has("hint")) { - info.hint = PropertyHint(d["hint"].operator int64_t()); - } - - if (d.has("hint_string")) { - info.hint_string = d["hint_string"]; - } - - if (d.has("usage")) { - info.usage = d["usage"]; - } - - p_properties->push_back(info); - } - } - - script_data = script_data->base_data; - } - return; -} - -Variant::Type NativeScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { - NativeScriptDesc *script_data = GET_SCRIPT_DESC(); - - while (script_data) { - OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = script_data->properties.find(p_name); - if (P) { - *r_is_valid = true; - return P.get().info.type; - } - - script_data = script_data->base_data; - } - return Variant::NIL; -} - -void NativeScriptInstance::get_method_list(List<MethodInfo> *p_list) const { - script->get_script_method_list(p_list); -} - -bool NativeScriptInstance::has_method(const StringName &p_method) const { - return script->has_method(p_method); -} - -Variant NativeScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { - NativeScriptDesc *script_data = GET_SCRIPT_DESC(); - - while (script_data) { - Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find(p_method); - if (E) { - godot_variant result; - -#ifdef DEBUG_ENABLED - current_method_call = p_method; -#endif - - result = E->get().method.method((godot_object *)owner, - E->get().method.method_data, - userdata, - p_argcount, - (godot_variant **)p_args); - -#ifdef DEBUG_ENABLED - current_method_call = ""; -#endif - - Variant res = *(Variant *)&result; - godot_variant_destroy(&result); - r_error.error = Callable::CallError::CALL_OK; - return res; - } - - script_data = script_data->base_data; - } - - r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; - return Variant(); -} - -void NativeScriptInstance::notification(int p_notification) { -#ifdef DEBUG_ENABLED - if (p_notification == MainLoop::NOTIFICATION_CRASH) { - if (current_method_call != StringName()) { - ERR_PRINT("NativeScriptInstance detected crash on method: " + current_method_call); - current_method_call = ""; - } - } -#endif - - Variant value = p_notification; - const Variant *args[1] = { &value }; - Callable::CallError error; - call("_notification", args, 1, error); -} - -String NativeScriptInstance::to_string(bool *r_valid) { - if (has_method(CoreStringNames::get_singleton()->_to_string)) { - Callable::CallError ce; - Variant ret = call(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce); - if (ce.error == Callable::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() { - Callable::CallError err; - call("_refcount_incremented", nullptr, 0, err); - if (err.error != Callable::CallError::CALL_OK && err.error != Callable::CallError::CALL_ERROR_INVALID_METHOD) { - ERR_PRINT("Failed to invoke _refcount_incremented - should not happen"); - } -} - -bool NativeScriptInstance::refcount_decremented() { - Callable::CallError err; - Variant ret = call("_refcount_decremented", nullptr, 0, err); - if (err.error != Callable::CallError::CALL_OK && err.error != Callable::CallError::CALL_ERROR_INVALID_METHOD) { - ERR_PRINT("Failed to invoke _refcount_decremented - should not happen"); - return true; // assume we can destroy the object - } - if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) { - // the method does not exist, default is true - return true; - } - return ret; -} - -Ref<Script> NativeScriptInstance::get_script() const { - return script; -} - -const Vector<Multiplayer::RPCConfig> NativeScriptInstance::get_rpc_methods() const { - return script->get_rpc_methods(); -} - -ScriptLanguage *NativeScriptInstance::get_language() { - return NativeScriptLanguage::get_singleton(); -} - -NativeScriptInstance::~NativeScriptInstance() { - NativeScriptDesc *script_data = GET_SCRIPT_DESC(); - - if (!script_data) { - return; - } - - script_data->destroy_func.destroy_func((godot_object *)owner, script_data->destroy_func.method_data, userdata); - - if (owner) { - MutexLock lock(script->owners_lock); - - script->instance_owners.erase(owner); - } -} - -NativeScriptLanguage *NativeScriptLanguage::singleton; - -void NativeScriptLanguage::_unload_stuff(bool p_reload) { - Map<String, Ref<GDNative>> erase_and_unload; - - for (KeyValue<String, Map<StringName, NativeScriptDesc>> &L : library_classes) { - String lib_path = L.key; - Map<StringName, NativeScriptDesc> classes = L.value; - - if (p_reload) { - Map<String, Ref<GDNative>>::Element *E = library_gdnatives.find(lib_path); - Ref<GDNative> gdn; - - if (E) { - gdn = E->get(); - } - - bool should_reload = false; - - if (gdn.is_valid()) { - Ref<GDNativeLibrary> lib = gdn->get_library(); - if (lib.is_valid()) { - should_reload = lib->is_reloadable(); - } - } - - if (!should_reload) { - continue; - } - } - - Map<String, Ref<GDNative>>::Element *E = library_gdnatives.find(lib_path); - Ref<GDNative> gdn; - - if (E) { - gdn = E->get(); - } - - for (KeyValue<StringName, NativeScriptDesc> &C : classes) { - // free property stuff first - for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = C.value.properties.front(); P; P = P.next()) { - if (P.get().getter.free_func) { - P.get().getter.free_func(P.get().getter.method_data); - } - - if (P.get().setter.free_func) { - P.get().setter.free_func(P.get().setter.method_data); - } - } - - // free method stuff - for (const KeyValue<StringName, NativeScriptDesc::Method> &M : C.value.methods) { - if (M.value.method.free_func) { - M.value.method.free_func(M.value.method.method_data); - } - } - - // free constructor/destructor - if (C.value.create_func.free_func) { - C.value.create_func.free_func(C.value.create_func.method_data); - } - - if (C.value.destroy_func.free_func) { - C.value.destroy_func.free_func(C.value.destroy_func.method_data); - } - } - - erase_and_unload.insert(lib_path, gdn); - } - - for (KeyValue<String, Ref<GDNative>> &E : erase_and_unload) { - String lib_path = E.key; - Ref<GDNative> gdn = E.value; - - library_classes.erase(lib_path); - - if (gdn.is_valid() && gdn->get_library().is_valid()) { - Ref<GDNativeLibrary> lib = gdn->get_library(); - void *terminate_fn; - Error err = gdn->get_symbol(lib->get_symbol_prefix() + _terminate_call_name, terminate_fn, true); - - if (err == OK) { - void (*terminate)(void *) = (void (*)(void *))terminate_fn; - - terminate((void *)&lib_path); - } - } - } -} - -NativeScriptLanguage::NativeScriptLanguage() { - NativeScriptLanguage::singleton = this; - - _init_call_type = "nativescript_init"; - _init_call_name = "nativescript_init"; - _terminate_call_name = "nativescript_terminate"; - _noarg_call_type = "nativescript_no_arg"; - _frame_call_name = "nativescript_frame"; -#ifndef NO_THREADS - _thread_enter_call_name = "nativescript_thread_enter"; - _thread_exit_call_name = "nativescript_thread_exit"; -#endif -} - -NativeScriptLanguage::~NativeScriptLanguage() { - for (KeyValue<String, Ref<GDNative>> &L : NSL->library_gdnatives) { - Ref<GDNative> lib = L.value; - // only shut down valid libs, duh! - if (lib.is_valid()) { - // If it's a singleton-library then the gdnative module - // manages the destruction at engine shutdown, not NativeScript. - if (!lib->get_library()->is_singleton()) { - lib->terminate(); - } - } - } - - NSL->library_classes.clear(); - NSL->library_gdnatives.clear(); - NSL->library_script_users.clear(); -} - -String NativeScriptLanguage::get_name() const { - return "NativeScript"; -} - -void _add_reload_node() { -#ifdef TOOLS_ENABLED - NativeReloadNode *rn = memnew(NativeReloadNode); - EditorNode::get_singleton()->add_child(rn); -#endif -} - -void NativeScriptLanguage::init() { -#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED) - - List<String> args = OS::get_singleton()->get_cmdline_args(); - - List<String>::Element *E = args.find("--gdnative-generate-json-api"); - - if (E && E->next()) { - if (generate_c_api(E->next()->get()) != OK) { - ERR_PRINT("Failed to generate C API\n"); - } - Main::cleanup(true); - exit(0); - } - - E = args.find("--gdnative-generate-json-builtin-api"); - - if (E && E->next()) { - if (generate_c_builtin_api(E->next()->get()) != OK) { - ERR_PRINT("Failed to generate C builtin API\n"); - } - Main::cleanup(true); - exit(0); - } -#endif - -#ifdef TOOLS_ENABLED - EditorNode::add_init_callback(&_add_reload_node); -#endif -} - -String NativeScriptLanguage::get_type() const { - return "NativeScript"; -} - -String NativeScriptLanguage::get_extension() const { - return "gdns"; -} - -Error NativeScriptLanguage::execute_file(const String &p_path) { - return OK; // Qué? -} - -void NativeScriptLanguage::finish() { - _unload_stuff(); -} - -void NativeScriptLanguage::get_reserved_words(List<String> *p_words) const { -} - -bool NativeScriptLanguage::is_control_flow_keyword(String p_keyword) const { - return false; -} - -void NativeScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const { -} - -void NativeScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const { -} - -Ref<Script> NativeScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { - NativeScript *s = memnew(NativeScript); - s->set_class_name(p_class_name); - return Ref<NativeScript>(s); -} - -bool NativeScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { - return true; -} - -Script *NativeScriptLanguage::create_script() const { - NativeScript *script = memnew(NativeScript); - return script; -} - -bool NativeScriptLanguage::has_named_classes() const { - return true; -} - -bool NativeScriptLanguage::supports_builtin_mode() const { - return true; -} - -int NativeScriptLanguage::find_function(const String &p_function, const String &p_code) const { - return -1; -} - -String NativeScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const { - return ""; -} - -void NativeScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const { -} - -void NativeScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) { -} - -// Debugging stuff here. Not used for now. -String NativeScriptLanguage::debug_get_error() const { - return ""; -} - -int NativeScriptLanguage::debug_get_stack_level_count() const { - return -1; -} - -int NativeScriptLanguage::debug_get_stack_level_line(int p_level) const { - return -1; -} - -String NativeScriptLanguage::debug_get_stack_level_function(int p_level) const { - return ""; -} - -String NativeScriptLanguage::debug_get_stack_level_source(int p_level) const { - return ""; -} - -void NativeScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { -} - -void NativeScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { -} - -void NativeScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { -} - -String NativeScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { - return ""; -} - -// Debugging stuff end. - -void NativeScriptLanguage::reload_all_scripts() { -} - -void NativeScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) { -} - -void NativeScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const { - p_extensions->push_back("gdns"); -} - -void NativeScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const { -} - -void NativeScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_constants) const { -} - -void NativeScriptLanguage::profiling_start() { -#ifdef DEBUG_ENABLED - MutexLock lock(mutex); - - profile_data.clear(); -#endif -} - -void NativeScriptLanguage::profiling_stop() { -#ifdef DEBUG_ENABLED - MutexLock lock(mutex); -#endif -} - -int NativeScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) { -#ifdef DEBUG_ENABLED - MutexLock lock(mutex); - - int current = 0; - - for (const KeyValue<StringName, ProfileData> &d : profile_data) { - if (current >= p_info_max) { - break; - } - - p_info_arr[current].call_count = d.value.call_count; - p_info_arr[current].self_time = d.value.self_time; - p_info_arr[current].total_time = d.value.total_time; - p_info_arr[current].signature = d.value.signature; - current++; - } - - return current; -#else - return 0; -#endif -} - -int NativeScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) { -#ifdef DEBUG_ENABLED - MutexLock lock(mutex); - - int current = 0; - - for (const KeyValue<StringName, ProfileData> &d : profile_data) { - if (current >= p_info_max) { - break; - } - - if (d.value.last_frame_call_count) { - p_info_arr[current].call_count = d.value.last_frame_call_count; - p_info_arr[current].self_time = d.value.last_frame_self_time; - p_info_arr[current].total_time = d.value.last_frame_total_time; - p_info_arr[current].signature = d.value.signature; - current++; - } - } - - return current; -#else - return 0; -#endif -} - -void NativeScriptLanguage::profiling_add_data(StringName p_signature, uint64_t p_time) { -#ifdef DEBUG_ENABLED - MutexLock lock(mutex); - - Map<StringName, ProfileData>::Element *d = profile_data.find(p_signature); - if (d) { - d->get().call_count += 1; - d->get().total_time += p_time; - d->get().frame_call_count += 1; - d->get().frame_total_time += p_time; - } else { - ProfileData data; - - data.signature = p_signature; - data.call_count = 1; - data.self_time = 0; - data.total_time = p_time; - data.frame_call_count = 1; - data.frame_self_time = 0; - data.frame_total_time = p_time; - data.last_frame_call_count = 0; - data.last_frame_self_time = 0; - data.last_frame_total_time = 0; - - profile_data.insert(p_signature, data); - } -#endif -} - -int NativeScriptLanguage::register_binding_functions(godot_nativescript_instance_binding_functions p_binding_functions) { - // find index - - int idx = -1; - - for (int i = 0; i < binding_functions.size(); i++) { - if (!binding_functions[i].first) { - // free, we'll take it - idx = i; - break; - } - } - - if (idx == -1) { - idx = binding_functions.size(); - binding_functions.resize(idx + 1); - } - - // set the functions - binding_functions.write[idx].first = true; - binding_functions.write[idx].second = p_binding_functions; - - return idx; -} - -void NativeScriptLanguage::unregister_binding_functions(int p_idx) { - ERR_FAIL_INDEX(p_idx, binding_functions.size()); - - for (Set<Vector<void *> *>::Element *E = binding_instances.front(); E; E = E->next()) { - Vector<void *> &binding_data = *E->get(); - - 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]); - } - } - - binding_functions.write[p_idx].first = false; - - if (binding_functions[p_idx].second.free_func) { - binding_functions[p_idx].second.free_func(binding_functions[p_idx].second.data); - } -} - -void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_object) { - return nullptr; -#if 0 - ERR_FAIL_INDEX_V(p_idx, binding_functions.size(), nullptr); - - ERR_FAIL_COND_V_MSG(!binding_functions[p_idx].first, nullptr, "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); - - if (!binding_data) { - return nullptr; // should never happen. - } - - if (binding_data->size() <= p_idx) { - // okay, add new elements here. - int old_size = binding_data->size(); - - binding_data->resize(p_idx + 1); - - for (int i = old_size; i <= p_idx; i++) { - (*binding_data).write[i] = nullptr; - } - } - - if (!(*binding_data)[p_idx]) { - 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); - } - - return (*binding_data)[p_idx]; -#endif -} - -void *NativeScriptLanguage::alloc_instance_binding_data(Object *p_object) { - return nullptr; -#if 0 - Vector<void *> *binding_data = new Vector<void *>; - - binding_data->resize(binding_functions.size()); - - for (int i = 0; i < binding_functions.size(); i++) { - (*binding_data).write[i] = nullptr; - } - - binding_instances.insert(binding_data); - - return (void *)binding_data; -#endif -} - -void NativeScriptLanguage::free_instance_binding_data(void *p_data) { -#if 0 - if (!p_data) { - return; - } - - Vector<void *> &binding_data = *(Vector<void *> *)p_data; - - for (int i = 0; i < binding_data.size(); i++) { - if (!binding_data[i]) { - continue; - } - - if (binding_functions[i].first && binding_functions[i].second.free_instance_binding_data) { - binding_functions[i].second.free_instance_binding_data(binding_functions[i].second.data, binding_data[i]); - } - } - - binding_instances.erase(&binding_data); - - delete &binding_data; -#endif -} - -void NativeScriptLanguage::refcount_incremented_instance_binding(Object *p_object) { -#if 0 - void *data = p_object->get_script_instance_binding(lang_idx); - - if (!data) { - return; - } - - Vector<void *> &binding_data = *(Vector<void *> *)data; - - for (int i = 0; i < binding_data.size(); i++) { - if (!binding_data[i]) { - continue; - } - - if (!binding_functions[i].first) { - continue; - } - - if (binding_functions[i].second.refcount_incremented_instance_binding) { - binding_functions[i].second.refcount_incremented_instance_binding(binding_data[i], p_object); - } - } -#endif -} - -bool NativeScriptLanguage::refcount_decremented_instance_binding(Object *p_object) { -#if 0 - void *data = p_object->get_script_instance_binding(lang_idx); - - if (!data) { - return true; - } - - Vector<void *> &binding_data = *(Vector<void *> *)data; - - bool can_die = true; - - for (int i = 0; i < binding_data.size(); i++) { - if (!binding_data[i]) { - continue; - } - - if (!binding_functions[i].first) { - continue; - } - - if (binding_functions[i].second.refcount_decremented_instance_binding) { - can_die = can_die && binding_functions[i].second.refcount_decremented_instance_binding(binding_data[i], p_object); - } - } - - return can_die; -#endif - return false; -} - -void NativeScriptLanguage::set_global_type_tag(int p_idx, StringName p_class_name, const void *p_type_tag) { - if (!global_type_tags.has(p_idx)) { - global_type_tags.insert(p_idx, HashMap<StringName, const void *>()); - } - - HashMap<StringName, const void *> &tags = global_type_tags[p_idx]; - - tags.set(p_class_name, p_type_tag); -} - -const void *NativeScriptLanguage::get_global_type_tag(int p_idx, StringName p_class_name) const { - if (!global_type_tags.has(p_idx)) { - return nullptr; - } - - const HashMap<StringName, const void *> &tags = global_type_tags[p_idx]; - - if (!tags.has(p_class_name)) { - return nullptr; - } - - const void *tag = tags.get(p_class_name); - - return tag; -} - -#ifndef NO_THREADS -void NativeScriptLanguage::defer_init_library(Ref<GDNativeLibrary> lib, NativeScript *script) { - MutexLock lock(mutex); - libs_to_init.insert(lib); - scripts_to_register.insert(script); - has_objects_to_register.set(); -} -#endif - -void NativeScriptLanguage::init_library(const Ref<GDNativeLibrary> &lib) { - MutexLock lock(mutex); - - // See if this library was "registered" already. - const String &lib_path = lib->get_current_library_path(); - 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) { - Ref<GDNative> gdn; - gdn.instantiate(); - gdn->set_library(lib); - - // TODO check the return value? - gdn->initialize(); - - library_gdnatives.insert(lib_path, gdn); - - library_classes.insert(lib_path, Map<StringName, NativeScriptDesc>()); - - if (!library_script_users.has(lib_path)) { - library_script_users.insert(lib_path, Set<NativeScript *>()); - } - - void *proc_ptr; - - Error err = gdn->get_symbol(lib->get_symbol_prefix() + _init_call_name, proc_ptr); - - if (err != OK) { - ERR_PRINT(String("No " + _init_call_name + " in \"" + lib_path + "\" found").utf8().get_data()); - } else { - ((void (*)(godot_string *))proc_ptr)((godot_string *)&lib_path); - } - } else { - // already initialized. Nice. - } -} - -void NativeScriptLanguage::register_script(NativeScript *script) { - MutexLock lock(mutex); - - library_script_users[script->lib_path].insert(script); -} - -void NativeScriptLanguage::unregister_script(NativeScript *script) { - MutexLock lock(mutex); - - Map<String, Set<NativeScript *>>::Element *S = library_script_users.find(script->lib_path); - if (S) { - S->get().erase(script); - if (S->get().size() == 0) { - library_script_users.erase(S); - - Map<String, Ref<GDNative>>::Element *G = library_gdnatives.find(script->lib_path); - if (G && G->get()->get_library()->is_reloadable()) { - // ONLY if the library is marked as reloadable, and no more instances of its scripts exist do we unload the library - - // First remove meta data related to the library - Map<String, Map<StringName, NativeScriptDesc>>::Element *L = library_classes.find(script->lib_path); - if (L) { - Map<StringName, NativeScriptDesc> classes = L->get(); - - for (KeyValue<StringName, NativeScriptDesc> &C : classes) { - // free property stuff first - for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = C.value.properties.front(); P; P = P.next()) { - if (P.get().getter.free_func) { - P.get().getter.free_func(P.get().getter.method_data); - } - - if (P.get().setter.free_func) { - P.get().setter.free_func(P.get().setter.method_data); - } - } - - // free method stuff - for (const KeyValue<StringName, NativeScriptDesc::Method> &M : C.value.methods) { - if (M.value.method.free_func) { - M.value.method.free_func(M.value.method.method_data); - } - } - - // free constructor/destructor - if (C.value.create_func.free_func) { - C.value.create_func.free_func(C.value.create_func.method_data); - } - - if (C.value.destroy_func.free_func) { - C.value.destroy_func.free_func(C.value.destroy_func.method_data); - } - } - - library_classes.erase(script->lib_path); - } - - // now unload the library - G->get()->terminate(); - library_gdnatives.erase(G); - } - } - } -#ifndef NO_THREADS - scripts_to_register.erase(script); -#endif -} - -void NativeScriptLanguage::call_libraries_cb(const StringName &name) { - // library_gdnatives is modified only from the main thread, so it's safe not to use mutex here - for (KeyValue<String, Ref<GDNative>> &L : library_gdnatives) { - if (L.value.is_null()) { - continue; - } - - if (L.value->is_initialized()) { - void *proc_ptr; - Error err = L.value->get_symbol(L.value->get_library()->get_symbol_prefix() + name, proc_ptr); - - if (!err) { - ((void (*)())proc_ptr)(); - } - } - } -} - -void NativeScriptLanguage::frame() { -#ifndef NO_THREADS - if (has_objects_to_register.is_set()) { - MutexLock lock(mutex); - for (Set<Ref<GDNativeLibrary>>::Element *L = libs_to_init.front(); L; L = L->next()) { - init_library(L->get()); - } - libs_to_init.clear(); - for (Set<NativeScript *>::Element *S = scripts_to_register.front(); S; S = S->next()) { - register_script(S->get()); - } - scripts_to_register.clear(); - has_objects_to_register.clear(); - } -#endif - -#ifdef DEBUG_ENABLED - { - MutexLock lock(mutex); - - for (KeyValue<StringName, ProfileData> &d : profile_data) { - d.value.last_frame_call_count = d.value.frame_call_count; - d.value.last_frame_self_time = d.value.frame_self_time; - d.value.last_frame_total_time = d.value.frame_total_time; - d.value.frame_call_count = 0; - d.value.frame_self_time = 0; - d.value.frame_total_time = 0; - } - } -#endif - - call_libraries_cb(_frame_call_name); -} - -#ifndef NO_THREADS - -void NativeScriptLanguage::thread_enter() { - call_libraries_cb(_thread_enter_call_name); -} - -void NativeScriptLanguage::thread_exit() { - call_libraries_cb(_thread_exit_call_name); -} - -#endif // NO_THREADS - -bool NativeScriptLanguage::handles_global_class_type(const String &p_type) const { - return p_type == "NativeScript"; -} - -String NativeScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const { - if (!p_path.is_empty()) { - Ref<NativeScript> script = ResourceLoader::load(p_path, "NativeScript"); - if (script.is_valid()) { - if (r_base_type) { - *r_base_type = script->get_instance_base_type(); - } - if (r_icon_path) { - *r_icon_path = script->get_script_class_icon_path(); - } - return script->get_script_class_name(); - } - if (r_base_type) { - *r_base_type = String(); - } - if (r_icon_path) { - *r_icon_path = String(); - } - } - return String(); -} - -void NativeReloadNode::_bind_methods() { - ClassDB::bind_method(D_METHOD("_notification"), &NativeReloadNode::_notification); -} - -void NativeReloadNode::_notification(int p_what) { -#ifdef TOOLS_ENABLED - - switch (p_what) { - case NOTIFICATION_APPLICATION_FOCUS_OUT: { - if (unloaded) { - break; - } - MutexLock lock(NSL->mutex); - NSL->_unload_stuff(true); - - for (KeyValue<String, Ref<GDNative>> &L : NSL->library_gdnatives) { - Ref<GDNative> gdn = L.value; - - if (gdn.is_null()) { - continue; - } - - // Don't unload what should not be reloaded! - if (!gdn->get_library()->is_reloadable()) { - continue; - } - - // singleton libraries might have alive pointers living inside the - // editor. Also reloading a singleton library would mean that - // the singleton entry will not be called again, as this only - // happens at engine startup. - if (gdn->get_library()->is_singleton()) { - continue; - } - - gdn->terminate(); - } - - unloaded = true; - - } break; - - case NOTIFICATION_APPLICATION_FOCUS_IN: { - if (!unloaded) { - break; - } - MutexLock lock(NSL->mutex); - - Set<StringName> libs_to_remove; - for (KeyValue<String, Ref<GDNative>> &L : NSL->library_gdnatives) { - Ref<GDNative> gdn = L.value; - - if (gdn.is_null()) { - continue; - } - - if (!gdn->get_library()->is_reloadable()) { - continue; - } - - // since singleton libraries are not unloaded there is no point - // in loading them again. - if (gdn->get_library()->is_singleton()) { - continue; - } - - if (!gdn->initialize()) { - libs_to_remove.insert(L.key); - continue; - } - - NSL->library_classes.insert(L.key, Map<StringName, NativeScriptDesc>()); - - // here the library registers all the classes and stuff. - - void *proc_ptr; - Error err = gdn->get_symbol(gdn->get_library()->get_symbol_prefix() + "nativescript_init", proc_ptr); - if (err != OK) { - ERR_PRINT(String("No godot_nativescript_init in \"" + L.key + "\" found").utf8().get_data()); - } else { - ((void (*)(void *))proc_ptr)((void *)&L.key); - } - - for (KeyValue<String, Set<NativeScript *>> &U : NSL->library_script_users) { - for (Set<NativeScript *>::Element *S = U.value.front(); S; S = S->next()) { - NativeScript *script = S->get(); - - if (script->placeholders.size() == 0) { - continue; - } - - for (Set<PlaceHolderScriptInstance *>::Element *P = script->placeholders.front(); P; P = P->next()) { - script->_update_placeholder(P->get()); - } - } - } - } - - unloaded = false; - - for (Set<StringName>::Element *R = libs_to_remove.front(); R; R = R->next()) { - NSL->library_gdnatives.erase(R->get()); - } - - } break; - default: { - }; - } -#endif -} - -RES ResourceFormatLoaderNativeScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_no_cache) { - return ResourceFormatLoaderText::singleton->load(p_path, p_original_path, r_error); -} - -void ResourceFormatLoaderNativeScript::get_recognized_extensions(List<String> *p_extensions) const { - p_extensions->push_back("gdns"); -} - -bool ResourceFormatLoaderNativeScript::handles_type(const String &p_type) const { - return (p_type == "Script" || p_type == "NativeScript"); -} - -String ResourceFormatLoaderNativeScript::get_resource_type(const String &p_path) const { - String el = p_path.get_extension().to_lower(); - if (el == "gdns") { - return "NativeScript"; - } - return ""; -} - -Error ResourceFormatSaverNativeScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { - ResourceFormatSaverText rfst; - return rfst.save(p_path, p_resource, p_flags); -} - -bool ResourceFormatSaverNativeScript::recognize(const RES &p_resource) const { - return Object::cast_to<NativeScript>(*p_resource) != nullptr; -} - -void ResourceFormatSaverNativeScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { - if (Object::cast_to<NativeScript>(*p_resource)) { - p_extensions->push_back("gdns"); - } -} diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h deleted file mode 100644 index 6c47d35abc..0000000000 --- a/modules/gdnative/nativescript/nativescript.h +++ /dev/null @@ -1,393 +0,0 @@ -/*************************************************************************/ -/* nativescript.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 NATIVE_SCRIPT_H -#define NATIVE_SCRIPT_H - -#include "core/doc_data.h" -#include "core/io/resource.h" -#include "core/io/resource_loader.h" -#include "core/io/resource_saver.h" -#include "core/object/script_language.h" -#include "core/os/mutex.h" -#include "core/os/thread_safe.h" -#include "core/templates/oa_hash_map.h" -#include "core/templates/ordered_hash_map.h" -#include "core/templates/safe_refcount.h" -#include "core/templates/self_list.h" -#include "scene/main/node.h" - -#include "modules/gdnative/gdnative.h" - -#include <nativescript/godot_nativescript.h> - -struct NativeScriptDesc { - struct Method { - godot_nativescript_instance_method method; - MethodInfo info; - int rpc_mode = 0; - uint16_t rpc_method_id = 0; - String documentation; - }; - - struct Property { - godot_nativescript_property_set_func setter; - godot_nativescript_property_get_func getter; - PropertyInfo info; - Variant default_value; - String documentation; - }; - - struct Signal { - MethodInfo signal; - String documentation; - }; - - Map<StringName, Method> methods; - Vector<Multiplayer::RPCConfig> rpc_methods; - OrderedHashMap<StringName, Property> properties; - Map<StringName, Signal> signals_; // QtCreator doesn't like the name signals - StringName base; - StringName base_native_type; - NativeScriptDesc *base_data = nullptr; - godot_nativescript_instance_create_func create_func; - godot_nativescript_instance_destroy_func destroy_func; - - String documentation; - - const void *type_tag = nullptr; - - bool is_tool = false; - - inline NativeScriptDesc() { - memset(&create_func, 0, sizeof(godot_nativescript_instance_create_func)); - memset(&destroy_func, 0, sizeof(godot_nativescript_instance_destroy_func)); - } -}; - -class NativeScript : public Script { - GDCLASS(NativeScript, Script); - -#ifdef TOOLS_ENABLED - Set<PlaceHolderScriptInstance *> placeholders; - void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); - virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override; -#endif - - friend class NativeScriptInstance; - friend class NativeScriptLanguage; - friend class NativeReloadNode; - friend class GDNativeLibrary; - - Ref<GDNativeLibrary> library; - - String lib_path; - - String class_name; - - String script_class_name; - String script_class_icon_path; - - Mutex owners_lock; - Set<Object *> instance_owners; - -protected: - static void _bind_methods(); - -public: - inline NativeScriptDesc *get_script_desc() const; - - bool inherits_script(const Ref<Script> &p_script) const override; - - void set_class_name(String p_class_name); - String get_class_name() const; - - void set_library(Ref<GDNativeLibrary> p_library); - Ref<GDNativeLibrary> get_library() const; - - void set_script_class_name(String p_type); - String get_script_class_name() const; - void set_script_class_icon_path(String p_icon_path); - String get_script_class_icon_path() const; - - virtual bool can_instantiate() const override; - - virtual Ref<Script> get_base_script() const override; //for script inheritance - - virtual StringName get_instance_base_type() const override; // this may not work in all scripts, will return empty if so - virtual ScriptInstance *instance_create(Object *p_this) override; - virtual PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this) override; - virtual bool instance_has(const Object *p_this) const override; - - virtual bool has_source_code() const override; - virtual String get_source_code() const override; - virtual void set_source_code(const String &p_code) override; - virtual Error reload(bool p_keep_state = false) override; - -#ifdef TOOLS_ENABLED - virtual const Vector<DocData::ClassDoc> &get_documentation() const override { - static Vector<DocData::ClassDoc> docs; - return docs; - } -#endif // TOOLS_ENABLED - - virtual bool has_method(const StringName &p_method) const override; - virtual MethodInfo get_method_info(const StringName &p_method) const override; - - virtual bool is_tool() const override; - virtual bool is_valid() const override; - - virtual ScriptLanguage *get_language() const override; - - virtual bool has_script_signal(const StringName &p_signal) const override; - virtual void get_script_signal_list(List<MethodInfo> *r_signals) const override; - - virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const override; - - virtual void update_exports() override; //editor tool - virtual void get_script_method_list(List<MethodInfo> *p_list) const override; - virtual void get_script_property_list(List<PropertyInfo> *p_list) const override; - - virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const override; - - String get_class_documentation() const; - String get_method_documentation(const StringName &p_method) const; - String get_signal_documentation(const StringName &p_signal_name) const; - String get_property_documentation(const StringName &p_path) const; - - Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error); - - NativeScript(); - ~NativeScript(); -}; - -class NativeScriptInstance : public ScriptInstance { - friend class NativeScript; - - Object *owner; - Ref<NativeScript> script; -#ifdef DEBUG_ENABLED - StringName current_method_call; -#endif - - void _ml_call_reversed(NativeScriptDesc *script_data, const StringName &p_method, const Variant **p_args, int p_argcount); - -public: - void *userdata; - - virtual bool set(const StringName &p_name, const Variant &p_value); - virtual bool get(const StringName &p_name, Variant &r_ret) const; - virtual void get_property_list(List<PropertyInfo> *p_properties) const; - virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const; - virtual void get_method_list(List<MethodInfo> *p_list) const; - virtual bool has_method(const StringName &p_method) const; - virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error); - virtual void notification(int p_notification); - String to_string(bool *r_valid); - virtual Ref<Script> get_script() const; - - virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const; - - virtual ScriptLanguage *get_language(); - - virtual void refcount_incremented(); - virtual bool refcount_decremented(); - - ~NativeScriptInstance(); -}; - -class NativeReloadNode; - -class NativeScriptLanguage : public ScriptLanguage { - friend class NativeScript; - friend class NativeScriptInstance; - friend class NativeReloadNode; - -private: - static NativeScriptLanguage *singleton; - int lang_idx = 0; - - void _unload_stuff(bool p_reload = false); - - Mutex mutex; -#ifndef NO_THREADS - Set<Ref<GDNativeLibrary>> libs_to_init; - Set<NativeScript *> scripts_to_register; - SafeFlag has_objects_to_register; // so that we don't lock mutex every frame - it's rarely needed - void defer_init_library(Ref<GDNativeLibrary> lib, NativeScript *script); -#endif - - void init_library(const Ref<GDNativeLibrary> &lib); - void register_script(NativeScript *script); - void unregister_script(NativeScript *script); - - void call_libraries_cb(const StringName &name); - - Vector<Pair<bool, godot_nativescript_instance_binding_functions>> binding_functions; - Set<Vector<void *> *> binding_instances; - - Map<int, HashMap<StringName, const void *>> global_type_tags; - - struct ProfileData { - StringName signature; - uint64_t call_count = 0; - uint64_t self_time = 0; - uint64_t total_time = 0; - uint64_t frame_call_count = 0; - uint64_t frame_self_time = 0; - uint64_t frame_total_time = 0; - uint64_t last_frame_call_count = 0; - uint64_t last_frame_self_time = 0; - uint64_t last_frame_total_time = 0; - }; - - Map<StringName, ProfileData> profile_data; - -public: - // These two maps must only be touched on the main thread - Map<String, Map<StringName, NativeScriptDesc>> library_classes; - Map<String, Ref<GDNative>> library_gdnatives; - - Map<String, Set<NativeScript *>> library_script_users; - - StringName _init_call_type; - StringName _init_call_name; - StringName _terminate_call_name; - StringName _noarg_call_type; - StringName _frame_call_name; -#ifndef NO_THREADS - StringName _thread_enter_call_name; - StringName _thread_exit_call_name; -#endif - - NativeScriptLanguage(); - ~NativeScriptLanguage(); - - inline static NativeScriptLanguage *get_singleton() { - return singleton; - } - - _FORCE_INLINE_ void set_language_index(int p_idx) { lang_idx = p_idx; } - -#ifndef NO_THREADS - virtual void thread_enter(); - virtual void thread_exit(); -#endif - - virtual void frame(); - - virtual String get_name() const; - virtual void init(); - virtual String get_type() const; - virtual String get_extension() const; - virtual Error execute_file(const String &p_path); - virtual void finish(); - virtual void get_reserved_words(List<String> *p_words) const; - virtual bool is_control_flow_keyword(String p_keyword) const; - virtual void get_comment_delimiters(List<String> *p_delimiters) const; - virtual void get_string_delimiters(List<String> *p_delimiters) const; - virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; - virtual bool validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; - virtual Script *create_script() const; - virtual bool has_named_classes() const; - virtual bool supports_builtin_mode() const; - 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 PackedStringArray &p_args) const; - 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); - virtual String debug_get_error() const; - virtual int debug_get_stack_level_count() const; - virtual int debug_get_stack_level_line(int p_level) const; - virtual String debug_get_stack_level_function(int p_level) const; - virtual String debug_get_stack_level_source(int p_level) const; - virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth); - virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth); - virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth); - virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth); - virtual void reload_all_scripts(); - virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload); - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual void get_public_functions(List<MethodInfo> *p_functions) const; - virtual void get_public_constants(List<Pair<String, Variant>> *p_constants) const; - virtual void profiling_start(); - virtual void profiling_stop(); - virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max); - virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max); - - int register_binding_functions(godot_nativescript_instance_binding_functions p_binding_functions); - void unregister_binding_functions(int p_idx); - - void *get_instance_binding_data(int p_idx, Object *p_object); - - virtual void *alloc_instance_binding_data(Object *p_object); - virtual void free_instance_binding_data(void *p_data); - virtual void refcount_incremented_instance_binding(Object *p_object); - virtual bool refcount_decremented_instance_binding(Object *p_object); - - void set_global_type_tag(int p_idx, StringName p_class_name, const void *p_type_tag); - const void *get_global_type_tag(int p_idx, StringName p_class_name) const; - - virtual bool handles_global_class_type(const String &p_type) const; - virtual String get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const; - - void profiling_add_data(StringName p_signature, uint64_t p_time); -}; - -inline NativeScriptDesc *NativeScript::get_script_desc() const { - Map<StringName, NativeScriptDesc>::Element *E = NativeScriptLanguage::singleton->library_classes[lib_path].find(class_name); - return E ? &E->get() : nullptr; -} - -class NativeReloadNode : public Node { - GDCLASS(NativeReloadNode, Node); - bool unloaded = false; - -public: - static void _bind_methods(); - void _notification(int p_what); - - NativeReloadNode() {} -}; - -class ResourceFormatLoaderNativeScript : public ResourceFormatLoader { -public: - virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE); - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String &p_type) const; - virtual String get_resource_type(const String &p_path) const; -}; - -class ResourceFormatSaverNativeScript : public 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; -}; - -#endif // GDNATIVE_H diff --git a/modules/gdnative/nativescript/register_types.h b/modules/gdnative/nativescript/register_types.h deleted file mode 100644 index ce6085f62a..0000000000 --- a/modules/gdnative/nativescript/register_types.h +++ /dev/null @@ -1,37 +0,0 @@ -/*************************************************************************/ -/* register_types.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 NATIVESCRIPT_REGISTER_TYPES_H -#define NATIVESCRIPT_REGISTER_TYPES_H - -void register_nativescript_types(); -void unregister_nativescript_types(); - -#endif // NATIVESCRIPT_REGISTER_TYPES_H diff --git a/modules/gdnative/pluginscript/SCsub b/modules/gdnative/pluginscript/SCsub deleted file mode 100644 index 0b2db3b504..0000000000 --- a/modules/gdnative/pluginscript/SCsub +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env python - -Import("env") -Import("env_gdnative") - -env_gdnative.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/gdnative/pluginscript/pluginscript_instance.cpp b/modules/gdnative/pluginscript/pluginscript_instance.cpp deleted file mode 100644 index 9236aceb3e..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_instance.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/*************************************************************************/ -/* pluginscript_instance.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "pluginscript_instance.h" - -// Godot imports -#include "core/os/os.h" -#include "core/variant/variant.h" - -// PluginScript imports -#include "pluginscript_language.h" -#include "pluginscript_script.h" - -bool PluginScriptInstance::set(const StringName &p_name, const Variant &p_value) { - return _desc->set_prop(_data, (const godot_string_name *)&p_name, (const godot_variant *)&p_value); -} - -bool PluginScriptInstance::get(const StringName &p_name, Variant &r_ret) const { - return _desc->get_prop(_data, (const godot_string_name *)&p_name, (godot_variant *)&r_ret); -} - -Ref<Script> PluginScriptInstance::get_script() const { - return _script; -} - -ScriptLanguage *PluginScriptInstance::get_language() { - return _script->get_language(); -} - -Variant::Type PluginScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { - if (!_script->has_property(p_name)) { - if (r_is_valid) { - *r_is_valid = false; - } - return Variant::NIL; - } - if (r_is_valid) { - *r_is_valid = true; - } - return _script->get_property_info(p_name).type; -} - -void PluginScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { - _script->get_script_property_list(p_properties); -} - -void PluginScriptInstance::get_method_list(List<MethodInfo> *p_list) const { - _script->get_script_method_list(p_list); -} - -bool PluginScriptInstance::has_method(const StringName &p_method) const { - return _script->has_method(p_method); -} - -Variant PluginScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { - // TODO: optimize when calling a Godot method from Godot to avoid param conversion ? - godot_variant ret = _desc->call_method( - _data, (godot_string_name *)&p_method, (const godot_variant **)p_args, - p_argcount, (godot_variant_call_error *)&r_error); - Variant var_ret = *(Variant *)&ret; - godot_variant_destroy(&ret); - return var_ret; -} - -void PluginScriptInstance::notification(int p_notification) { - _desc->notification(_data, p_notification); -} - -String PluginScriptInstance::to_string(bool *r_valid) { - godot_string ret = _desc->to_string(_data, r_valid); - String str_ret = *(String *)&ret; - godot_string_destroy(&ret); - return str_ret; -} - -const Vector<Multiplayer::RPCConfig> PluginScriptInstance::get_rpc_methods() const { - return _script->get_rpc_methods(); -} - -void PluginScriptInstance::refcount_incremented() { - if (_desc->refcount_decremented) { - _desc->refcount_incremented(_data); - } -} - -bool PluginScriptInstance::refcount_decremented() { - // Return true if it can die - if (_desc->refcount_decremented) { - return _desc->refcount_decremented(_data); - } - return true; -} - -PluginScriptInstance::PluginScriptInstance() { -} - -bool PluginScriptInstance::init(PluginScript *p_script, Object *p_owner) { - _owner = p_owner; - _owner_variant = Variant(p_owner); - _script = Ref<PluginScript>(p_script); - _desc = &p_script->_desc->instance_desc; - _data = _desc->init(p_script->_data, (godot_object *)p_owner); - ERR_FAIL_COND_V(_data == nullptr, false); - p_owner->set_script_instance(this); - return true; -} - -PluginScriptInstance::~PluginScriptInstance() { - _desc->finish(_data); - _script->_language->lock(); - _script->_instances.erase(_owner); - _script->_language->unlock(); -} diff --git a/modules/gdnative/pluginscript/pluginscript_instance.h b/modules/gdnative/pluginscript/pluginscript_instance.h deleted file mode 100644 index 09b051c008..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_instance.h +++ /dev/null @@ -1,82 +0,0 @@ -/*************************************************************************/ -/* pluginscript_instance.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 PLUGINSCRIPT_INSTANCE_H -#define PLUGINSCRIPT_INSTANCE_H - -// Godot imports -#include "core/object/script_language.h" - -// PluginScript imports -#include <pluginscript/godot_pluginscript.h> - -class PluginScript; - -class PluginScriptInstance : public ScriptInstance { - friend class PluginScript; - -private: - Ref<PluginScript> _script; - Object *_owner = nullptr; - Variant _owner_variant; - godot_pluginscript_instance_data *_data = nullptr; - const godot_pluginscript_instance_desc *_desc = nullptr; - -public: - _FORCE_INLINE_ Object *get_owner() { return _owner; } - - virtual bool set(const StringName &p_name, const Variant &p_value); - virtual bool get(const StringName &p_name, Variant &r_ret) const; - virtual void get_property_list(List<PropertyInfo> *p_properties) const; - virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = nullptr) const; - - virtual void get_method_list(List<MethodInfo> *p_list) const; - virtual bool has_method(const StringName &p_method) const; - - virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error); - - virtual void notification(int p_notification); - virtual String to_string(bool *r_valid); - - virtual Ref<Script> get_script() const; - - virtual ScriptLanguage *get_language(); - - virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const; - - virtual void refcount_incremented(); - virtual bool refcount_decremented(); - - PluginScriptInstance(); - bool init(PluginScript *p_script, Object *p_owner); - virtual ~PluginScriptInstance(); -}; - -#endif // PLUGINSCRIPT_INSTANCE_H diff --git a/modules/gdnative/pluginscript/pluginscript_language.cpp b/modules/gdnative/pluginscript/pluginscript_language.cpp deleted file mode 100644 index 0e068dec3a..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_language.cpp +++ /dev/null @@ -1,459 +0,0 @@ -/*************************************************************************/ -/* pluginscript_language.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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. */ -/*************************************************************************/ - -// Godot imports -#include "core/config/project_settings.h" -#include "core/io/file_access.h" -#include "core/os/os.h" -// PluginScript imports -#include "pluginscript_language.h" -#include "pluginscript_script.h" - -String PluginScriptLanguage::get_name() const { - return String(_desc.name); -} - -void PluginScriptLanguage::init() { - _data = _desc.init(); -} - -String PluginScriptLanguage::get_type() const { - // We should use _desc.type here, however the returned type is used to - // query ClassDB which would complain given the type is not registered - // from his point of view... - // To solve this we just use a more generic (but present in ClassDB) type. - return String("PluginScript"); -} - -String PluginScriptLanguage::get_extension() const { - return String(_desc.extension); -} - -Error PluginScriptLanguage::execute_file(const String &p_path) { - // TODO: pretty sure this method is totally deprecated and should be removed... - return OK; -} - -void PluginScriptLanguage::finish() { - _desc.finish(_data); -} - -/* EDITOR FUNCTIONS */ - -void PluginScriptLanguage::get_reserved_words(List<String> *p_words) const { - if (_desc.reserved_words) { - const char **w = _desc.reserved_words; - while (*w) { - p_words->push_back(*w); - w++; - } - } -} - -bool PluginScriptLanguage::is_control_flow_keyword(String p_keyword) const { - return false; -} - -void PluginScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const { - if (_desc.comment_delimiters) { - const char **w = _desc.comment_delimiters; - while (*w) { - p_delimiters->push_back(*w); - w++; - } - } -} - -void PluginScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const { - if (_desc.string_delimiters) { - const char **w = _desc.string_delimiters; - while (*w) { - p_delimiters->push_back(*w); - w++; - } - } -} - -Ref<Script> PluginScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { - Script *ns = create_script(); - Ref<Script> script = Ref<Script>(ns); - if (_desc.get_template_source_code) { - godot_string src = _desc.get_template_source_code(_data, (godot_string *)&p_class_name, (godot_string *)&p_base_class_name); - script->set_source_code(*(String *)&src); - godot_string_destroy(&src); - } - return script; -} - -bool PluginScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { - PackedStringArray functions; - Array errors; - if (_desc.validate) { - bool ret = _desc.validate( - _data, - (godot_string *)&p_script, - (godot_string *)&p_path, - (godot_packed_string_array *)&functions, - (godot_array *)&errors); - for (int i = 0; i < functions.size(); i++) { - r_functions->push_back(functions[i]); - } - if (r_errors) { - for (int i = 0; i < errors.size(); i++) { - Dictionary error = errors[i]; - ScriptLanguage::ScriptError e; - e.line = error["line"]; - e.column = error["column"]; - e.message = error["message"]; - r_errors->push_back(e); - } - } - return ret; - } - return true; -} - -Script *PluginScriptLanguage::create_script() const { - PluginScript *script = memnew(PluginScript()); - // I'm hurting kittens doing this I guess... - script->init(const_cast<PluginScriptLanguage *>(this)); - return script; -} - -bool PluginScriptLanguage::has_named_classes() const { - return _desc.has_named_classes; -} - -bool PluginScriptLanguage::supports_builtin_mode() const { - return _desc.supports_builtin_mode; -} - -bool PluginScriptLanguage::can_inherit_from_file() const { - return _desc.can_inherit_from_file; -} - -int PluginScriptLanguage::find_function(const String &p_function, const String &p_code) const { - if (_desc.find_function) { - return _desc.find_function(_data, (godot_string *)&p_function, (godot_string *)&p_code); - } - return -1; -} - -String PluginScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const { - if (_desc.make_function) { - godot_string tmp = _desc.make_function(_data, (godot_string *)&p_class, (godot_string *)&p_name, (godot_packed_string_array *)&p_args); - String ret = *(String *)&tmp; - godot_string_destroy(&tmp); - return ret; - } - return String(); -} - -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_path, - (godot_object *)p_owner, - (godot_array *)&options, - &r_force, - (godot_string *)&r_call_hint); - for (int i = 0; i < options.size(); i++) { - ScriptCodeCompletionOption option(options[i], ScriptCodeCompletionOption::KIND_PLAIN_TEXT); - r_options->push_back(option); - } - return (Error)tmp; - } - return ERR_UNAVAILABLE; -} - -void PluginScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const { - if (_desc.auto_indent_code) { - _desc.auto_indent_code(_data, (godot_string *)&p_code, p_from_line, p_to_line); - } - return; -} - -void PluginScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) { - _desc.add_global_constant(_data, (godot_string_name *)&p_variable, (godot_variant *)&p_value); -} - -/* LOADER FUNCTIONS */ - -void PluginScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const { - for (int i = 0; _desc.recognized_extensions[i]; ++i) { - p_extensions->push_back(String(_desc.recognized_extensions[i])); - } -} - -void PluginScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const { - // TODO: provide this statically in `godot_pluginscript_language_desc` ? - if (_desc.get_public_functions) { - Array functions; - _desc.get_public_functions(_data, (godot_array *)&functions); - for (int i = 0; i < functions.size(); i++) { - MethodInfo mi = MethodInfo::from_dict(functions[i]); - p_functions->push_back(mi); - } - } -} - -void PluginScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_constants) const { - // 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]; - p_constants->push_back(Pair<String, Variant>(*key, value)); - } - } -} - -void PluginScriptLanguage::profiling_start() { -#ifdef DEBUG_ENABLED - if (_desc.profiling_start) { - lock(); - _desc.profiling_start(_data); - unlock(); - } -#endif -} - -void PluginScriptLanguage::profiling_stop() { -#ifdef DEBUG_ENABLED - if (_desc.profiling_stop) { - lock(); - _desc.profiling_stop(_data); - unlock(); - } -#endif -} - -int PluginScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) { - int info_count = 0; -#ifdef DEBUG_ENABLED - if (_desc.profiling_get_accumulated_data) { - godot_pluginscript_profiling_data *info = (godot_pluginscript_profiling_data *)memalloc( - sizeof(godot_pluginscript_profiling_data) * p_info_max); - info_count = _desc.profiling_get_accumulated_data(_data, info, p_info_max); - for (int i = 0; i < info_count; ++i) { - p_info_arr[i].signature = *(StringName *)&info[i].signature; - p_info_arr[i].call_count = info[i].call_count; - p_info_arr[i].total_time = info[i].total_time; - p_info_arr[i].self_time = info[i].self_time; - godot_string_name_destroy(&info[i].signature); - } - } -#endif - return info_count; -} - -int PluginScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) { - int info_count = 0; -#ifdef DEBUG_ENABLED - if (_desc.profiling_get_frame_data) { - godot_pluginscript_profiling_data *info = (godot_pluginscript_profiling_data *)memalloc( - sizeof(godot_pluginscript_profiling_data) * p_info_max); - info_count = _desc.profiling_get_frame_data(_data, info, p_info_max); - for (int i = 0; i < info_count; ++i) { - p_info_arr[i].signature = *(StringName *)&info[i].signature; - p_info_arr[i].call_count = info[i].call_count; - p_info_arr[i].total_time = info[i].total_time; - p_info_arr[i].self_time = info[i].self_time; - godot_string_name_destroy(&info[i].signature); - } - } -#endif - return info_count; -} - -void PluginScriptLanguage::frame() { -#ifdef DEBUG_ENABLED - if (_desc.profiling_frame) { - _desc.profiling_frame(_data); - } -#endif -} - -/* DEBUGGER FUNCTIONS */ - -String PluginScriptLanguage::debug_get_error() const { - if (_desc.debug_get_error) { - godot_string tmp = _desc.debug_get_error(_data); - String ret = *(String *)&tmp; - godot_string_destroy(&tmp); - return ret; - } - return String("Nothing"); -} - -int PluginScriptLanguage::debug_get_stack_level_count() const { - if (_desc.debug_get_stack_level_count) { - return _desc.debug_get_stack_level_count(_data); - } - return 1; -} - -int PluginScriptLanguage::debug_get_stack_level_line(int p_level) const { - if (_desc.debug_get_stack_level_line) { - return _desc.debug_get_stack_level_line(_data, p_level); - } - return 1; -} - -String PluginScriptLanguage::debug_get_stack_level_function(int p_level) const { - if (_desc.debug_get_stack_level_function) { - godot_string tmp = _desc.debug_get_stack_level_function(_data, p_level); - String ret = *(String *)&tmp; - godot_string_destroy(&tmp); - return ret; - } - return String("Nothing"); -} - -String PluginScriptLanguage::debug_get_stack_level_source(int p_level) const { - if (_desc.debug_get_stack_level_source) { - godot_string tmp = _desc.debug_get_stack_level_source(_data, p_level); - String ret = *(String *)&tmp; - godot_string_destroy(&tmp); - return ret; - } - return String("Nothing"); -} - -void PluginScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - if (_desc.debug_get_stack_level_locals) { - PackedStringArray locals; - Array values; - _desc.debug_get_stack_level_locals(_data, p_level, (godot_packed_string_array *)&locals, (godot_array *)&values, p_max_subitems, p_max_depth); - for (int i = 0; i < locals.size(); i++) { - p_locals->push_back(locals[i]); - } - for (int i = 0; i < values.size(); i++) { - p_values->push_back(values[i]); - } - } -} - -void PluginScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - if (_desc.debug_get_stack_level_members) { - PackedStringArray members; - Array values; - _desc.debug_get_stack_level_members(_data, p_level, (godot_packed_string_array *)&members, (godot_array *)&values, p_max_subitems, p_max_depth); - for (int i = 0; i < members.size(); i++) { - p_members->push_back(members[i]); - } - for (int i = 0; i < values.size(); i++) { - p_values->push_back(values[i]); - } - } -} - -void PluginScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - if (_desc.debug_get_globals) { - PackedStringArray locals; - Array values; - _desc.debug_get_globals(_data, (godot_packed_string_array *)&locals, (godot_array *)&values, p_max_subitems, p_max_depth); - for (int i = 0; i < locals.size(); i++) { - p_locals->push_back(locals[i]); - } - for (int i = 0; i < values.size(); i++) { - p_values->push_back(values[i]); - } - } -} - -String PluginScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { - if (_desc.debug_parse_stack_level_expression) { - godot_string tmp = _desc.debug_parse_stack_level_expression(_data, p_level, (godot_string *)&p_expression, p_max_subitems, p_max_depth); - String ret = *(String *)&tmp; - godot_string_destroy(&tmp); - return ret; - } - return String("Nothing"); -} - -void PluginScriptLanguage::reload_all_scripts() { - // TODO -} - -void PluginScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) { -#ifdef DEBUG_ENABLED - lock(); - // TODO - unlock(); -#endif -} - -bool PluginScriptLanguage::handles_global_class_type(const String &p_type) const { - return p_type == "PluginScript"; -} - -String PluginScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const { - if (!p_path.is_empty()) { - Ref<PluginScript> script = ResourceLoader::load(p_path, "PluginScript"); - if (script.is_valid()) { - if (r_base_type) { - *r_base_type = script->get_instance_base_type(); - } - if (r_icon_path) { - *r_icon_path = script->get_script_class_icon_path(); - } - return script->get_script_class_name(); - } - if (r_base_type) { - *r_base_type = String(); - } - if (r_icon_path) { - *r_icon_path = String(); - } - } - return String(); -} - -void PluginScriptLanguage::lock() { - _lock.lock(); -} - -void PluginScriptLanguage::unlock() { - _lock.unlock(); -} - -PluginScriptLanguage::PluginScriptLanguage(const godot_pluginscript_language_desc *desc) : - _desc(*desc) { - _resource_loader = Ref<ResourceFormatLoaderPluginScript>(memnew(ResourceFormatLoaderPluginScript(this))); - _resource_saver = Ref<ResourceFormatSaverPluginScript>(memnew(ResourceFormatSaverPluginScript(this))); -} - -PluginScriptLanguage::~PluginScriptLanguage() { -} diff --git a/modules/gdnative/pluginscript/pluginscript_language.h b/modules/gdnative/pluginscript/pluginscript_language.h deleted file mode 100644 index 6039f807a8..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_language.h +++ /dev/null @@ -1,138 +0,0 @@ -/*************************************************************************/ -/* pluginscript_language.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 PLUGINSCRIPT_LANGUAGE_H -#define PLUGINSCRIPT_LANGUAGE_H - -// Godot imports -#include "core/io/resource_loader.h" -#include "core/io/resource_saver.h" -#include "core/object/script_language.h" -#include "core/templates/map.h" -#include "core/templates/self_list.h" -// PluginScript imports -#include "pluginscript_loader.h" -#include <pluginscript/godot_pluginscript.h> - -class PluginScript; -class PluginScriptInstance; - -class PluginScriptLanguage : public ScriptLanguage { - friend class PluginScript; - friend class PluginScriptInstance; - - Ref<ResourceFormatLoaderPluginScript> _resource_loader; - Ref<ResourceFormatSaverPluginScript> _resource_saver; - const godot_pluginscript_language_desc _desc; - godot_pluginscript_language_data *_data; - - Mutex _lock; - SelfList<PluginScript>::List _script_list; - -public: - virtual String get_name() const; - - _FORCE_INLINE_ Ref<ResourceFormatLoaderPluginScript> get_resource_loader() { return _resource_loader; } - _FORCE_INLINE_ Ref<ResourceFormatSaverPluginScript> get_resource_saver() { return _resource_saver; } - - /* LANGUAGE FUNCTIONS */ - virtual void init(); - virtual String get_type() const; - virtual String get_extension() const; - virtual Error execute_file(const String &p_path); - virtual void finish(); - - /* EDITOR FUNCTIONS */ - virtual void get_reserved_words(List<String> *p_words) const; - virtual bool is_control_flow_keyword(String p_keyword) const; - virtual void get_comment_delimiters(List<String> *p_delimiters) const; - virtual void get_string_delimiters(List<String> *p_delimiters) const; - virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; - virtual bool validate(const String &p_script, const String &p_path = "", List<String> *r_functions = nullptr, List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; - virtual Script *create_script() const; - virtual bool has_named_classes() const; - virtual bool supports_builtin_mode() const; - virtual bool can_inherit_from_file() const; - 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 PackedStringArray &p_args) const; - 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); - - /* MULTITHREAD FUNCTIONS */ - - //some VMs need to be notified of thread creation/exiting to allocate a stack - // void thread_enter() {} - // void thread_exit() {} - - /* DEBUGGER FUNCTIONS */ - - virtual String debug_get_error() const; - virtual int debug_get_stack_level_count() const; - virtual int debug_get_stack_level_line(int p_level) const; - virtual String debug_get_stack_level_function(int p_level) const; - virtual String debug_get_stack_level_source(int p_level) const; - virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); - virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); - virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); - virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1); - - // virtual Vector<StackInfo> debug_get_current_stack_info() { return Vector<StackInfo>(); } - - virtual void reload_all_scripts(); - virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload); - - /* LOADER FUNCTIONS */ - - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual void get_public_functions(List<MethodInfo> *p_functions) const; - virtual void get_public_constants(List<Pair<String, Variant>> *p_constants) const; - - virtual void profiling_start(); - virtual void profiling_stop(); - - virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max); - virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max); - - virtual void frame(); - - /* GLOBAL CLASSES */ - - virtual bool handles_global_class_type(const String &p_type) const; - virtual String get_global_class_name(const String &p_path, String *r_base_type = nullptr, String *r_icon_path = nullptr) const; - - void lock(); - void unlock(); - - PluginScriptLanguage(const godot_pluginscript_language_desc *desc); - virtual ~PluginScriptLanguage(); -}; - -#endif // PLUGINSCRIPT_LANGUAGE_H diff --git a/modules/gdnative/pluginscript/pluginscript_loader.cpp b/modules/gdnative/pluginscript/pluginscript_loader.cpp deleted file mode 100644 index a151d551dc..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_loader.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/*************************************************************************/ -/* pluginscript_loader.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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. */ -/*************************************************************************/ - -// Godot imports -#include "core/io/file_access.h" -// Pythonscript imports -#include "pluginscript_language.h" -#include "pluginscript_loader.h" -#include "pluginscript_script.h" - -ResourceFormatLoaderPluginScript::ResourceFormatLoaderPluginScript(PluginScriptLanguage *language) { - _language = language; -} - -RES ResourceFormatLoaderPluginScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) { - if (r_error) { - *r_error = ERR_FILE_CANT_OPEN; - } - - PluginScript *script = memnew(PluginScript); - script->init(_language); - - Ref<PluginScript> scriptres(script); - - Error err = script->load_source_code(p_path); - ERR_FAIL_COND_V(err != OK, RES()); - - script->set_path(p_original_path); - - script->reload(); - - if (r_error) { - *r_error = OK; - } - - return scriptres; -} - -void ResourceFormatLoaderPluginScript::get_recognized_extensions(List<String> *p_extensions) const { - p_extensions->push_back(_language->get_extension()); -} - -bool ResourceFormatLoaderPluginScript::handles_type(const String &p_type) const { - return p_type == "Script" || p_type == _language->get_type(); -} - -String ResourceFormatLoaderPluginScript::get_resource_type(const String &p_path) const { - String el = p_path.get_extension().to_lower(); - if (el == _language->get_extension()) { - return _language->get_type(); - } - return ""; -} - -ResourceFormatSaverPluginScript::ResourceFormatSaverPluginScript(PluginScriptLanguage *language) { - _language = language; -} - -Error ResourceFormatSaverPluginScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { - Ref<PluginScript> sqscr = p_resource; - ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER); - - String source = sqscr->get_source_code(); - - Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V(err, err); - - file->store_string(source); - if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { - memdelete(file); - return ERR_CANT_CREATE; - } - file->close(); - memdelete(file); - return OK; -} - -void ResourceFormatSaverPluginScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { - if (Object::cast_to<PluginScript>(*p_resource)) { - p_extensions->push_back(_language->get_extension()); - } -} - -bool ResourceFormatSaverPluginScript::recognize(const RES &p_resource) const { - return Object::cast_to<PluginScript>(*p_resource) != nullptr; -} diff --git a/modules/gdnative/pluginscript/pluginscript_loader.h b/modules/gdnative/pluginscript/pluginscript_loader.h deleted file mode 100644 index bcce742aea..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_loader.h +++ /dev/null @@ -1,62 +0,0 @@ -/*************************************************************************/ -/* pluginscript_loader.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 PYTHONSCRIPT_PY_LOADER_H -#define PYTHONSCRIPT_PY_LOADER_H - -// Godot imports -#include "core/io/resource_loader.h" -#include "core/io/resource_saver.h" -#include "core/object/script_language.h" - -class PluginScriptLanguage; - -class ResourceFormatLoaderPluginScript : public ResourceFormatLoader { - PluginScriptLanguage *_language; - -public: - ResourceFormatLoaderPluginScript(PluginScriptLanguage *language); - virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE); - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String &p_type) const; - virtual String get_resource_type(const String &p_path) const; -}; - -class ResourceFormatSaverPluginScript : public ResourceFormatSaver { - PluginScriptLanguage *_language; - -public: - ResourceFormatSaverPluginScript(PluginScriptLanguage *language); - 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; - virtual bool recognize(const RES &p_resource) const; -}; - -#endif // PYTHONSCRIPT_PY_LOADER_H diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp deleted file mode 100644 index ec3c9eb4ff..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_script.cpp +++ /dev/null @@ -1,510 +0,0 @@ -/*************************************************************************/ -/* pluginscript_script.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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. */ -/*************************************************************************/ - -// Godot imports -#include "core/io/file_access.h" -// PluginScript imports -#include "pluginscript_instance.h" -#include "pluginscript_script.h" - -#include <stdint.h> - -#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_instantiate(), __ASSERT_SCRIPT_REASON); \ - } -#define ASSERT_SCRIPT_VALID_V(ret) \ - { \ - ERR_FAIL_COND_V_MSG(!can_instantiate(), ret, __ASSERT_SCRIPT_REASON); \ - } -#else -#define ASSERT_SCRIPT_VALID() -#define ASSERT_SCRIPT_VALID_V(ret) -#endif - -void PluginScript::_bind_methods() { - 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, Callable::CallError &r_error) { - r_error.error = Callable::CallError::CALL_OK; - - // Create instance - PluginScriptInstance *instance = memnew(PluginScriptInstance()); - - if (instance->init(this, p_owner)) { - _language->lock(); - _instances.insert(instance->get_owner()); - _language->unlock(); - } else { - r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; - memdelete(instance); - ERR_FAIL_V(nullptr); - } - - // Construct - // TODO: Support arguments in the constructor? - // 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"); - } - - return instance; -} - -Variant PluginScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { - r_error.error = Callable::CallError::CALL_OK; - - if (!_valid) { - r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; - return Variant(); - } - - REF ref; - Object *owner = nullptr; - - if (get_instance_base_type() == StringName()) { - owner = memnew(RefCounted); - } else { - owner = ClassDB::instantiate(get_instance_base_type()); - } - - if (!owner) { - r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; - return Variant(); - } - - RefCounted *r = Object::cast_to<RefCounted>(owner); - if (r) { - ref = REF(r); - } - - PluginScriptInstance *instance = _create_instance(p_args, p_argcount, owner, r_error); - - if (!instance) { - if (ref.is_null()) { - memdelete(owner); //no owner, sorry - } - return Variant(); - } - - if (ref.is_valid()) { - return ref; - } else { - return owner; - } -} - -#ifdef TOOLS_ENABLED - -void PluginScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) { - placeholders.erase(p_placeholder); -} - -#endif - -bool PluginScript::can_instantiate() const { - bool can = _valid || (!_tool && !ScriptServer::is_scripting_enabled()); - return can; -} - -bool PluginScript::inherits_script(const Ref<Script> &p_script) const { - Ref<PluginScript> ps = p_script; - if (ps.is_null()) { - return false; - } - - const PluginScript *s = this; - - while (s) { - if (s == p_script.ptr()) { - return true; - } - s = Object::cast_to<PluginScript>(s->_ref_base_parent.ptr()); - } - - return false; -} - -Ref<Script> PluginScript::get_base_script() const { - if (_ref_base_parent.is_valid()) { - return Ref<PluginScript>(_ref_base_parent); - } else { - return Ref<Script>(); - } -} - -StringName PluginScript::get_instance_base_type() const { - if (_native_parent) { - return _native_parent; - } - if (_ref_base_parent.is_valid()) { - return _ref_base_parent->get_instance_base_type(); - } - return StringName(); -} - -void PluginScript::update_exports() { -#ifdef TOOLS_ENABLED - ASSERT_SCRIPT_VALID(); - if (placeholders.size()) { - //update placeholders if any - Map<StringName, Variant> propdefvalues; - List<PropertyInfo> propinfos; - - get_script_property_list(&propinfos); - for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { - E->get()->update(propinfos, _properties_default_values); - } - } -#endif -} - -// TODO: rename p_this "p_owner" ? -ScriptInstance *PluginScript::instance_create(Object *p_this) { - ASSERT_SCRIPT_VALID_V(nullptr); - // TODO check script validity ? - if (!_tool && !ScriptServer::is_scripting_enabled()) { -#ifdef TOOLS_ENABLED - // Instance a fake script for editing the values - PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(get_language(), Ref<Script>(this), p_this)); - placeholders.insert(si); - update_exports(); - return si; -#else - return nullptr; -#endif - } - - StringName base_type = get_instance_base_type(); - if (base_type) { - if (!ClassDB::is_parent_class(p_this->get_class_name(), base_type)) { - String msg = "Script inherits from native type '" + String(base_type) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'"; - // TODO: implement PluginscriptLanguage::debug_break_parse - // if (EngineDebugger::is_active()) { - // _language->debug_break_parse(get_path(), 0, msg); - // } - ERR_FAIL_V_MSG(nullptr, msg); - } - } - - Callable::CallError unchecked_error; - return _create_instance(nullptr, 0, p_this, unchecked_error); -} - -bool PluginScript::instance_has(const Object *p_this) const { - ERR_FAIL_COND_V(!_language, false); - - _language->lock(); - bool hasit = _instances.has((Object *)p_this); - _language->unlock(); - return hasit; -} - -bool PluginScript::has_source_code() const { - return !_source.is_empty(); -} - -String PluginScript::get_source_code() const { - return _source; -} - -void PluginScript::set_source_code(const String &p_code) { - if (_source == p_code) { - return; - } - _source = 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(); - - _valid = false; - String basedir = _path; - - if (basedir.is_empty()) { - basedir = get_path(); - } - - if (!basedir.is_empty()) { - basedir = basedir.get_base_dir(); - } - - if (_data) { - _desc->finish(_data); - } - - Error err; - godot_pluginscript_script_manifest manifest = _desc->init( - _language->_data, - (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; - } - - // Script's parent is passed as base_name which can make reference to a - // ClassDB name (i.e. `Node2D`) or a resource path (i.e. `res://foo/bar.gd`) - StringName *base_name = (StringName *)&manifest.base; - if (*base_name) { - if (ClassDB::class_exists(*base_name)) { - _native_parent = *base_name; - } else { - Ref<Script> res = ResourceLoader::load(*base_name); - if (res.is_valid()) { - _ref_base_parent = res; - } else { - String name = *(StringName *)&manifest.name; - FREE_SCRIPT_MANIFEST(manifest); - ERR_FAIL_V_MSG(ERR_PARSE_ERROR, _path + ": Script '" + name + "' has an invalid parent '" + *base_name + "'."); - } - } - } - - _valid = true; - // Use the manifest to configure this script object - _data = manifest.data; - _name = *(StringName *)&manifest.name; - _tool = manifest.is_tool; - _icon_path = *(String *)&manifest.icon_path; - - Dictionary *members = (Dictionary *)&manifest.member_lines; - for (const Variant *key = members->next(); key != nullptr; key = members->next(key)) { - _member_lines[*key] = (*members)[*key]; - } - Array *methods = (Array *)&manifest.methods; - _rpc_methods.clear(); - if (_ref_base_parent.is_valid()) { - /// XXX TODO Should this be _rpc_methods.append_array(...) - _rpc_methods = _ref_base_parent->get_rpc_methods(); - } - for (int i = 0; i < methods->size(); ++i) { - Dictionary v = (*methods)[i]; - MethodInfo mi = MethodInfo::from_dict(v); - _methods_info[mi.name] = mi; - // rpc_mode is passed as an optional field and is not part of MethodInfo - Variant var = v["rpc_mode"]; - if (var != Variant()) { - Multiplayer::RPCConfig nd; - nd.name = mi.name; - nd.rpc_mode = Multiplayer::RPCMode(int(var)); - // TODO Transfer Channel - if (_rpc_methods.find(nd) == -1) { - _rpc_methods.push_back(nd); - } - } - } - - // Sort so we are 100% that they are always the same. - _rpc_methods.sort_custom<Multiplayer::SortRPCConfig>(); - - Array *signals = (Array *)&manifest.signals; - for (int i = 0; i < signals->size(); ++i) { - Variant v = (*signals)[i]; - MethodInfo mi = MethodInfo::from_dict(v); - _signals_info[mi.name] = mi; - } - Array *properties = (Array *)&manifest.properties; - for (int i = 0; i < properties->size(); ++i) { - Dictionary v = (*properties)[i]; - PropertyInfo pi = PropertyInfo::from_dict(v); - _properties_info[pi.name] = pi; - _properties_default_values[pi.name] = v["default_value"]; - } - - FREE_SCRIPT_MANIFEST(manifest); - return OK; -#undef FREE_SCRIPT_MANIFEST -} - -void PluginScript::get_script_method_list(List<MethodInfo> *r_methods) const { - ASSERT_SCRIPT_VALID(); - for (Map<StringName, MethodInfo>::Element *e = _methods_info.front(); e != nullptr; e = e->next()) { - r_methods->push_back(e->get()); - } -} - -void PluginScript::get_script_property_list(List<PropertyInfo> *r_properties) const { - ASSERT_SCRIPT_VALID(); - for (Map<StringName, PropertyInfo>::Element *e = _properties_info.front(); e != nullptr; e = e->next()) { - r_properties->push_back(e->get()); - } -} - -bool PluginScript::has_method(const StringName &p_method) const { - ASSERT_SCRIPT_VALID_V(false); - return _methods_info.has(p_method); -} - -MethodInfo PluginScript::get_method_info(const StringName &p_method) const { - ASSERT_SCRIPT_VALID_V(MethodInfo()); - const Map<StringName, MethodInfo>::Element *e = _methods_info.find(p_method); - if (e != nullptr) { - return e->get(); - } else { - return MethodInfo(); - } -} - -bool PluginScript::has_property(const StringName &p_method) const { - ASSERT_SCRIPT_VALID_V(false); - return _properties_info.has(p_method); -} - -PropertyInfo PluginScript::get_property_info(const StringName &p_property) const { - ASSERT_SCRIPT_VALID_V(PropertyInfo()); - const Map<StringName, PropertyInfo>::Element *e = _properties_info.find(p_property); - if (e != nullptr) { - return e->get(); - } else { - return PropertyInfo(); - } -} - -bool PluginScript::get_property_default_value(const StringName &p_property, Variant &r_value) const { - ASSERT_SCRIPT_VALID_V(false); -#ifdef TOOLS_ENABLED - const Map<StringName, Variant>::Element *e = _properties_default_values.find(p_property); - if (e != nullptr) { - r_value = e->get(); - return true; - } else { - return false; - } -#endif - return false; -} - -ScriptLanguage *PluginScript::get_language() const { - return _language; -} - -Error PluginScript::load_source_code(const String &p_path) { - Vector<uint8_t> sourcef; - Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + p_path + "'."); - - uint64_t len = f->get_length(); - sourcef.resize(len + 1); - uint8_t *w = sourcef.ptrw(); - uint64_t r = f->get_buffer(w, len); - f->close(); - memdelete(f); - ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); - w[len] = 0; - - String s; - if (s.parse_utf8((const char *)w)) { - 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; -#ifdef TOOLS_ENABLED -// source_changed_cache=true; -#endif - _path = p_path; - return OK; -} - -bool PluginScript::has_script_signal(const StringName &p_signal) const { - ASSERT_SCRIPT_VALID_V(false); - return _signals_info.has(p_signal); -} - -void PluginScript::get_script_signal_list(List<MethodInfo> *r_signals) const { - ASSERT_SCRIPT_VALID(); - for (Map<StringName, MethodInfo>::Element *e = _signals_info.front(); e != nullptr; e = e->next()) { - r_signals->push_back(e->get()); - } -} - -int PluginScript::get_member_line(const StringName &p_member) const { -#ifdef TOOLS_ENABLED - if (_member_lines.has(p_member)) { - return _member_lines[p_member]; - } -#endif - return -1; -} - -const Vector<Multiplayer::RPCConfig> PluginScript::get_rpc_methods() const { - return _rpc_methods; -} - -PluginScript::PluginScript() : - _script_list(this) { -} - -void PluginScript::init(PluginScriptLanguage *language) { - _desc = &language->_desc.script_desc; - _language = language; - -#ifdef DEBUG_ENABLED - _language->lock(); - _language->_script_list.add(&_script_list); - _language->unlock(); -#endif -} - -PluginScript::~PluginScript() { - if (_desc && _data) { - _desc->finish(_data); - } - -#ifdef DEBUG_ENABLED - if (_language) { - _language->lock(); - _language->_script_list.remove(&_script_list); - _language->unlock(); - } -#endif -} diff --git a/modules/gdnative/pluginscript/pluginscript_script.h b/modules/gdnative/pluginscript/pluginscript_script.h deleted file mode 100644 index 73c486f6d9..0000000000 --- a/modules/gdnative/pluginscript/pluginscript_script.h +++ /dev/null @@ -1,146 +0,0 @@ -/*************************************************************************/ -/* pluginscript_script.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 PLUGINSCRIPT_SCRIPT_H -#define PLUGINSCRIPT_SCRIPT_H - -// Godot imports - -#include "core/doc_data.h" -#include "core/object/script_language.h" -// PluginScript imports -#include "pluginscript_language.h" -#include <pluginscript/godot_pluginscript.h> - -class PluginScript : public Script { - GDCLASS(PluginScript, Script); - - friend class PluginScriptInstance; - friend class PluginScriptLanguage; - -private: - godot_pluginscript_script_data *_data = nullptr; - const godot_pluginscript_script_desc *_desc = nullptr; - PluginScriptLanguage *_language = nullptr; - bool _tool = false; - bool _valid = false; - - Ref<Script> _ref_base_parent; - StringName _native_parent; - SelfList<PluginScript> _script_list; - - Map<StringName, int> _member_lines; - Map<StringName, Variant> _properties_default_values; - Map<StringName, PropertyInfo> _properties_info; - Map<StringName, MethodInfo> _signals_info; - Map<StringName, MethodInfo> _methods_info; - Vector<Multiplayer::RPCConfig> _rpc_methods; - - Set<Object *> _instances; - //exported members - String _source; - String _path; - StringName _name; - String _icon_path; - -protected: - static void _bind_methods(); - - bool inherits_script(const Ref<Script> &p_script) const override; - - PluginScriptInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, Callable::CallError &r_error); - Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error); - -#ifdef TOOLS_ENABLED - Set<PlaceHolderScriptInstance *> placeholders; - //void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); - virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override; -#endif -public: - String get_script_class_name() const { - return _name; - } - - String get_script_class_icon_path() const { - return _icon_path; - } - - virtual bool can_instantiate() const override; - - virtual Ref<Script> get_base_script() const override; //for script inheritance - - virtual StringName get_instance_base_type() const override; // this may not work in all scripts, will return empty if so - virtual ScriptInstance *instance_create(Object *p_this) override; - virtual bool instance_has(const Object *p_this) const override; - - virtual bool has_source_code() const override; - virtual String get_source_code() const override; - virtual void set_source_code(const String &p_code) override; - virtual Error reload(bool p_keep_state = false) override; - // TODO: load_source_code only allow utf-8 file, should handle bytecode as well ? - virtual Error load_source_code(const String &p_path); - -#ifdef TOOLS_ENABLED - virtual const Vector<DocData::ClassDoc> &get_documentation() const override { - static Vector<DocData::ClassDoc> docs; - return docs; - } -#endif // TOOLS_ENABLED - - virtual bool has_method(const StringName &p_method) const override; - virtual MethodInfo get_method_info(const StringName &p_method) const override; - - bool has_property(const StringName &p_method) const; - PropertyInfo get_property_info(const StringName &p_property) const; - - bool is_tool() const override { return _tool; } - bool is_valid() const override { return true; } - - virtual ScriptLanguage *get_language() const override; - - virtual bool has_script_signal(const StringName &p_signal) const override; - virtual void get_script_signal_list(List<MethodInfo> *r_signals) const override; - - virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const override; - - virtual void update_exports() override; - virtual void get_script_method_list(List<MethodInfo> *r_methods) const override; - virtual void get_script_property_list(List<PropertyInfo> *r_properties) const override; - - virtual int get_member_line(const StringName &p_member) const override; - - virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const override; - - PluginScript(); - void init(PluginScriptLanguage *language); - virtual ~PluginScript(); -}; - -#endif // PLUGINSCRIPT_SCRIPT_H diff --git a/modules/gdnative/pluginscript/register_types.cpp b/modules/gdnative/pluginscript/register_types.cpp deleted file mode 100644 index 39c8124c17..0000000000 --- a/modules/gdnative/pluginscript/register_types.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/*************************************************************************/ -/* register_types.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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/config/project_settings.h" -#include "core/io/dir_access.h" -#include "core/io/resource_loader.h" -#include "core/io/resource_saver.h" -#include "core/os/os.h" -#include "scene/main/scene_tree.h" - -#include "pluginscript_language.h" -#include "pluginscript_script.h" -#include <pluginscript/godot_pluginscript.h> - -static List<PluginScriptLanguage *> pluginscript_languages; - -static Error _check_language_desc(const godot_pluginscript_language_desc *desc) { - ERR_FAIL_COND_V(!desc->name, ERR_BUG); - ERR_FAIL_COND_V(!desc->type, ERR_BUG); - ERR_FAIL_COND_V(!desc->extension, ERR_BUG); - ERR_FAIL_COND_V(!desc->recognized_extensions || !desc->recognized_extensions[0], ERR_BUG); - ERR_FAIL_COND_V(!desc->init, ERR_BUG); - ERR_FAIL_COND_V(!desc->finish, ERR_BUG); - - // desc->reserved_words is not mandatory - // desc->comment_delimiters is not mandatory - // desc->string_delimiters is not mandatory - - // desc->get_template_source_code is not mandatory - // desc->validate is not mandatory - - // desc->get_template_source_code is not mandatory - // desc->validate is not mandatory - // desc->find_function is not mandatory - // desc->make_function is not mandatory - // desc->complete_code is not mandatory - // desc->auto_indent_code is not mandatory - ERR_FAIL_COND_V(!desc->add_global_constant, ERR_BUG); - // desc->debug_get_error is not mandatory - // desc->debug_get_stack_level_count is not mandatory - // desc->debug_get_stack_level_line is not mandatory - // desc->debug_get_stack_level_function is not mandatory - // desc->debug_get_stack_level_source is not mandatory - // desc->debug_get_stack_level_locals is not mandatory - // desc->debug_get_stack_level_members is not mandatory - // desc->debug_get_globals is not mandatory - // desc->debug_parse_stack_level_expression is not mandatory - // desc->profiling_start is not mandatory - // desc->profiling_stop is not mandatory - // desc->profiling_get_accumulated_data is not mandatory - // desc->profiling_get_frame_data is not mandatory - // desc->profiling_frame is not mandatory - - ERR_FAIL_COND_V(!desc->script_desc.init, ERR_BUG); - ERR_FAIL_COND_V(!desc->script_desc.finish, ERR_BUG); - - ERR_FAIL_COND_V(!desc->script_desc.instance_desc.init, ERR_BUG); - ERR_FAIL_COND_V(!desc->script_desc.instance_desc.finish, ERR_BUG); - ERR_FAIL_COND_V(!desc->script_desc.instance_desc.set_prop, ERR_BUG); - ERR_FAIL_COND_V(!desc->script_desc.instance_desc.get_prop, ERR_BUG); - ERR_FAIL_COND_V(!desc->script_desc.instance_desc.call_method, ERR_BUG); - ERR_FAIL_COND_V(!desc->script_desc.instance_desc.notification, ERR_BUG); - // desc->script_desc.instance_desc.refcount_incremented is not mandatory - // desc->script_desc.instance_desc.refcount_decremented is not mandatory - return OK; -} - -void GDAPI godot_pluginscript_register_language(const godot_pluginscript_language_desc *language_desc) { - Error ret = _check_language_desc(language_desc); - if (ret) { - ERR_FAIL(); - } - PluginScriptLanguage *language = memnew(PluginScriptLanguage(language_desc)); - ScriptServer::register_language(language); - ResourceLoader::add_resource_format_loader(language->get_resource_loader()); - ResourceSaver::add_resource_format_saver(language->get_resource_saver()); - pluginscript_languages.push_back(language); -} - -void register_pluginscript_types() { - GDREGISTER_CLASS(PluginScript); -} - -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/pluginscript/register_types.h b/modules/gdnative/pluginscript/register_types.h deleted file mode 100644 index 49e7357a98..0000000000 --- a/modules/gdnative/pluginscript/register_types.h +++ /dev/null @@ -1,37 +0,0 @@ -/*************************************************************************/ -/* register_types.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 PLUGINSCRIPT_REGISTER_TYPES_H -#define PLUGINSCRIPT_REGISTER_TYPES_H - -void register_pluginscript_types(); -void unregister_pluginscript_types(); - -#endif // PLUGINSCRIPT_REGISTER_TYPES_H diff --git a/modules/gdnative/register_types.cpp b/modules/gdnative/register_types.cpp deleted file mode 100644 index fb682beccc..0000000000 --- a/modules/gdnative/register_types.cpp +++ /dev/null @@ -1,360 +0,0 @@ -/*************************************************************************/ -/* register_types.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "gdnative/gdnative.h" - -#include "gdnative.h" - -#include "nativescript/register_types.h" -#include "pluginscript/register_types.h" -#include "videodecoder/register_types.h" - -#include "core/config/engine.h" -#include "core/config/project_settings.h" -#include "core/io/resource_loader.h" -#include "core/io/resource_saver.h" -#include "core/os/os.h" - -#ifdef TOOLS_ENABLED -#include "editor/editor_export.h" -#include "editor/editor_node.h" -#include "gdnative_library_editor_plugin.h" -#include "gdnative_library_singleton_editor.h" - -class GDNativeExportPlugin : public EditorExportPlugin { -protected: - virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features); -}; - -struct LibrarySymbol { - const char *name; - bool is_required; -}; - -void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_type, const Set<String> &p_features) { - if (p_type != "GDNativeLibrary") { - return; - } - - Ref<GDNativeLibrary> lib = ResourceLoader::load(p_path); - - if (lib.is_null()) { - return; - } - - Ref<ConfigFile> config = lib->get_config_file(); - - { - List<String> entry_keys; - config->get_section_keys("entry", &entry_keys); - - for (const String &key : entry_keys) { - Vector<String> tags = key.split("."); - - bool skip = false; - for (int i = 0; i < tags.size(); i++) { - bool has_feature = p_features.has(tags[i]); - - if (!has_feature) { - skip = true; - break; - } - } - - if (skip) { - continue; - } - - 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); - } - } - - { - List<String> dependency_keys; - config->get_section_keys("dependencies", &dependency_keys); - - for (const String &key : dependency_keys) { - Vector<String> tags = key.split("."); - - bool skip = false; - for (int i = 0; i < tags.size(); i++) { - bool has_feature = p_features.has(tags[i]); - - if (!has_feature) { - skip = true; - break; - } - } - - if (skip) { - continue; - } - - 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); - } - } - } - - // Add symbols for statically linked libraries on iOS - if (p_features.has("iOS")) { - bool should_fake_dynamic = false; - - List<String> entry_keys; - config->get_section_keys("entry", &entry_keys); - - for (const String &key : entry_keys) { - Vector<String> tags = key.split("."); - - bool skip = false; - for (int i = 0; i < tags.size(); i++) { - bool has_feature = p_features.has(tags[i]); - - if (!has_feature) { - skip = true; - break; - } - } - - if (skip) { - continue; - } - - String entry_lib_path = config->get_value("entry", key); - if (entry_lib_path.begins_with("res://") && entry_lib_path.ends_with(".a")) { - // If we find static library that was used for export - // we should add a fake lookup table. - // In case of dynamic library being used, - // this symbols will not cause any issues with library loading. - should_fake_dynamic = true; - break; - } - } - - if (should_fake_dynamic) { - // Register symbols in the "fake" dynamic lookup table, because dlsym does not work well on iOS. - LibrarySymbol expected_symbols[] = { - { "gdnative_init", true }, - { "gdnative_terminate", false }, - { "nativescript_init", false }, - { "nativescript_frame", false }, - { "nativescript_thread_enter", false }, - { "nativescript_thread_exit", false }, - { "gdnative_singleton", false } - }; - String declare_pattern = "extern \"C\" void $name(void)$weak;\n"; - 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 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))"); - additional_code += code; - - if (!expected_symbols[i].is_required) { - if (linker_flags.length() > 0) { - linker_flags += " "; - } - linker_flags += "-Wl,-U,_" + full_name; - } - } - - 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 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); - } - additional_code += "}\n"; - additional_code += String("struct $prefixstruct {$prefixstruct() {add_ios_init_callback($prefixinit);}};\n").replace("$prefix", lib->get_symbol_prefix()); - additional_code += String("$prefixstruct $prefixstruct_instance;\n").replace("$prefix", lib->get_symbol_prefix()); - - add_ios_cpp_code(additional_code); - add_ios_linker_flags(linker_flags); - } - } -} - -static void editor_init_callback() { - GDNativeLibrarySingletonEditor *library_editor = memnew(GDNativeLibrarySingletonEditor); - library_editor->set_name(TTR("GDNative")); - ProjectSettingsEditor::get_singleton()->get_tabs()->add_child(library_editor); - - Ref<GDNativeExportPlugin> export_plugin; - export_plugin.instantiate(); - - EditorExport::get_singleton()->add_export_plugin(export_plugin); - - EditorNode::get_singleton()->add_editor_plugin(memnew(GDNativeLibraryEditorPlugin(EditorNode::get_singleton()))); -} - -#endif - -static godot_variant cb_standard_varcall(void *p_procedure_handle, godot_array *p_args) { - godot_gdnative_procedure_fn proc; - proc = (godot_gdnative_procedure_fn)p_procedure_handle; - - return proc(p_args); -} - -GDNativeCallRegistry *GDNativeCallRegistry::singleton; - -Vector<Ref<GDNative>> singleton_gdnatives; - -Ref<GDNativeLibraryResourceLoader> resource_loader_gdnlib; -Ref<GDNativeLibraryResourceSaver> resource_saver_gdnlib; - -void register_gdnative_types() { -#ifdef TOOLS_ENABLED - - EditorNode::add_init_callback(editor_init_callback); -#endif - - GDREGISTER_CLASS(GDNativeLibrary); - GDREGISTER_CLASS(GDNative); - - resource_loader_gdnlib.instantiate(); - ResourceLoader::add_resource_format_loader(resource_loader_gdnlib); - - resource_saver_gdnlib.instantiate(); - ResourceSaver::add_resource_format_saver(resource_saver_gdnlib); - - GDNativeCallRegistry::singleton = memnew(GDNativeCallRegistry); - - GDNativeCallRegistry::singleton->register_native_call_type("standard_varcall", cb_standard_varcall); - - register_nativescript_types(); - register_pluginscript_types(); - register_videodecoder_types(); - - // run singletons - - Array singletons = Array(); - if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { - singletons = ProjectSettings::get_singleton()->get("gdnative/singletons"); - } - 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]; - - if (excluded.has(path)) { - continue; - } - - Ref<GDNativeLibrary> lib = ResourceLoader::load(path); - Ref<GDNative> singleton; - singleton.instantiate(); - singleton->set_library(lib); - - if (!singleton->initialize()) { - // Can't initialize. Don't make a native_call then - continue; - } - - void *proc_ptr; - Error err = singleton->get_symbol( - lib->get_symbol_prefix() + "gdnative_singleton", - proc_ptr); - - if (err != OK) { - ERR_PRINT("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)(); - } - } -} - -void unregister_gdnative_types() { - for (int i = 0; i < singleton_gdnatives.size(); i++) { - if (singleton_gdnatives[i].is_null()) { - continue; - } - - if (!singleton_gdnatives[i]->is_initialized()) { - continue; - } - - singleton_gdnatives.write[i]->terminate(); - } - singleton_gdnatives.clear(); - - unregister_videodecoder_types(); - unregister_pluginscript_types(); - unregister_nativescript_types(); - - memdelete(GDNativeCallRegistry::singleton); - - ResourceLoader::remove_resource_format_loader(resource_loader_gdnlib); - resource_loader_gdnlib.unref(); - - ResourceSaver::remove_resource_format_saver(resource_saver_gdnlib); - resource_saver_gdnlib.unref(); - - // This is for printing out the sizes of the core types - - /* - print_line(String("array:\t") + itos(sizeof(Array))); - print_line(String("basis:\t") + itos(sizeof(Basis))); - print_line(String("color:\t") + itos(sizeof(Color))); - print_line(String("dict:\t" ) + itos(sizeof(Dictionary))); - print_line(String("node_path:\t") + itos(sizeof(NodePath))); - print_line(String("plane:\t") + itos(sizeof(Plane))); - print_line(String("poolarray:\t") + itos(sizeof(PackedByteArray))); - print_line(String("quat:\t") + itos(sizeof(Quat))); - print_line(String("rect2:\t") + itos(sizeof(Rect2))); - print_line(String("aabb:\t") + itos(sizeof(AABB))); - print_line(String("rid:\t") + itos(sizeof(RID))); - print_line(String("string:\t") + itos(sizeof(String))); - print_line(String("transform:\t") + itos(sizeof(Transform3D))); - print_line(String("transfo2D:\t") + itos(sizeof(Transform2D))); - print_line(String("variant:\t") + itos(sizeof(Variant))); - print_line(String("vector2:\t") + itos(sizeof(Vector2))); - print_line(String("vector3:\t") + itos(sizeof(Vector3))); - */ -} diff --git a/modules/gdnative/register_types.h b/modules/gdnative/register_types.h deleted file mode 100644 index 0e1cb46a55..0000000000 --- a/modules/gdnative/register_types.h +++ /dev/null @@ -1,37 +0,0 @@ -/*************************************************************************/ -/* register_types.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 GDNATIVE_REGISTER_TYPES_H -#define GDNATIVE_REGISTER_TYPES_H - -void register_gdnative_types(); -void unregister_gdnative_types(); - -#endif // GDNATIVE_REGISTER_TYPES_H diff --git a/modules/gdnative/tests/test_variant.h b/modules/gdnative/tests/test_variant.h deleted file mode 100644 index fb6537cf42..0000000000 --- a/modules/gdnative/tests/test_variant.h +++ /dev/null @@ -1,205 +0,0 @@ -/*************************************************************************/ -/* test_variant.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 TEST_GDNATIVE_VARIANT_H -#define TEST_GDNATIVE_VARIANT_H - -#include <gdnative/gdnative.h> -#include <gdnative/variant.h> - -#include "tests/test_macros.h" - -namespace TestGDNativeVariant { - -TEST_CASE("[GDNative Variant] New Variant with copy") { - godot_variant src; - godot_variant_new_int(&src, 42); - - godot_variant copy; - godot_variant_new_copy(©, &src); - - CHECK(godot_variant_as_int(©) == 42); - CHECK(godot_variant_get_type(©) == GODOT_VARIANT_TYPE_INT); - - godot_variant_destroy(&src); - godot_variant_destroy(©); -} - -TEST_CASE("[GDNative Variant] New Variant with Nil") { - godot_variant val; - godot_variant_new_nil(&val); - - CHECK(godot_variant_get_type(&val) == GODOT_VARIANT_TYPE_NIL); - - godot_variant_destroy(&val); -} - -TEST_CASE("[GDNative Variant] New Variant with bool") { - godot_variant val; - godot_variant_new_bool(&val, true); - - CHECK(godot_variant_as_bool(&val)); - CHECK(godot_variant_get_type(&val) == GODOT_VARIANT_TYPE_BOOL); - - godot_variant_destroy(&val); -} - -TEST_CASE("[GDNative Variant] New Variant with float") { - godot_variant val; - godot_variant_new_float(&val, 4.2); - - CHECK(godot_variant_as_float(&val) == 4.2); - CHECK(godot_variant_get_type(&val) == GODOT_VARIANT_TYPE_FLOAT); - - godot_variant_destroy(&val); -} - -TEST_CASE("[GDNative Variant] New Variant with String") { - String str = "something"; - - godot_variant val; - godot_variant_new_string(&val, (godot_string *)&str); - godot_string gd_str = godot_variant_as_string(&val); - String *result = (String *)&gd_str; - - CHECK(*result == String("something")); - CHECK(godot_variant_get_type(&val) == GODOT_VARIANT_TYPE_STRING); - - godot_variant_destroy(&val); - godot_string_destroy(&gd_str); -} - -TEST_CASE("[GDNative Variant] Variant call") { - String str("something"); - godot_variant self; - godot_variant_new_string(&self, (godot_string *)&str); - - godot_variant ret; - - godot_string_name method; - godot_string_name_new_with_latin1_chars(&method, "is_valid_identifier"); - - godot_variant_call_error error; - godot_variant_call(&self, &method, nullptr, 0, &ret, &error); - - CHECK(godot_variant_get_type(&ret) == GODOT_VARIANT_TYPE_BOOL); - CHECK(godot_variant_as_bool(&ret)); - - godot_variant_destroy(&ret); - godot_variant_destroy(&self); - godot_string_name_destroy(&method); -} - -TEST_CASE("[GDNative Variant] Variant evaluate") { - godot_variant one; - godot_variant_new_int(&one, 1); - godot_variant two; - godot_variant_new_int(&two, 2); - - godot_variant three; - godot_variant_new_nil(&three); - bool valid = false; - - godot_variant_evaluate(GODOT_VARIANT_OP_ADD, &one, &two, &three, &valid); - - CHECK(godot_variant_get_type(&three) == GODOT_VARIANT_TYPE_INT); - CHECK(godot_variant_as_int(&three) == 3); - CHECK(valid); - - godot_variant_destroy(&one); - godot_variant_destroy(&two); - godot_variant_destroy(&three); -} - -TEST_CASE("[GDNative Variant] Variant set/get named") { - godot_string_name x; - godot_string_name_new_with_latin1_chars(&x, "x"); - - Vector2 vec(0, 0); - godot_variant self; - godot_variant_new_vector2(&self, (godot_vector2 *)&vec); - - godot_variant set; - godot_variant_new_float(&set, 1.0); - - bool set_valid = false; - godot_variant_set_named(&self, &x, &set, &set_valid); - - bool get_valid = false; - godot_variant get = godot_variant_get_named(&self, &x, &get_valid); - - CHECK(get_valid); - CHECK(set_valid); - CHECK(godot_variant_get_type(&get) == GODOT_VARIANT_TYPE_FLOAT); - CHECK(godot_variant_as_float(&get) == 1.0); - - godot_string_name_destroy(&x); - godot_variant_destroy(&self); - godot_variant_destroy(&set); - godot_variant_destroy(&get); -} - -TEST_CASE("[GDNative Variant] Get utility function argument name") { - godot_string_name function; - godot_string_name_new_with_latin1_chars(&function, "pow"); - - godot_string arg_name = godot_variant_get_utility_function_argument_name(&function, 0); - - String *arg_name_str = (String *)&arg_name; - - CHECK(*arg_name_str == "base"); - - godot_string_destroy(&arg_name); - godot_string_name_destroy(&function); -} - -TEST_CASE("[GDNative Variant] Get utility function list") { - int count = godot_variant_get_utility_function_count(); - - godot_string_name *c_list = (godot_string_name *)godot_alloc(count * sizeof(godot_string_name)); - godot_variant_get_utility_function_list(c_list); - - List<StringName> cpp_list; - Variant::get_utility_function_list(&cpp_list); - - godot_string_name *cur = c_list; - - for (const StringName &E : cpp_list) { - const StringName &cpp_name = E; - StringName *c_name = (StringName *)cur++; - - CHECK(*c_name == cpp_name); - } - - godot_free(c_list); -} -} // namespace TestGDNativeVariant - -#endif // TEST_GDNATIVE_VARIANT_H diff --git a/modules/gdnative/videodecoder/SCsub b/modules/gdnative/videodecoder/SCsub deleted file mode 100644 index 5948b9a3dd..0000000000 --- a/modules/gdnative/videodecoder/SCsub +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python - -Import("env") -Import("env_modules") - -env_vsdecoder_gdnative = env_modules.Clone() - -env_vsdecoder_gdnative.Prepend(CPPPATH=["#modules/gdnative/include/"]) -env_vsdecoder_gdnative.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/gdnative/videodecoder/register_types.cpp b/modules/gdnative/videodecoder/register_types.cpp deleted file mode 100644 index b28ff99bb8..0000000000 --- a/modules/gdnative/videodecoder/register_types.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/*************************************************************************/ -/* register_types.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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/object/class_db.h" -#include "video_stream_gdnative.h" - -static Ref<ResourceFormatLoaderVideoStreamGDNative> resource_loader_vsgdnative; - -void register_videodecoder_types() { - resource_loader_vsgdnative.instantiate(); - ResourceLoader::add_resource_format_loader(resource_loader_vsgdnative, true); - - GDREGISTER_CLASS(VideoStreamGDNative); -} - -void unregister_videodecoder_types() { - ResourceLoader::remove_resource_format_loader(resource_loader_vsgdnative); - resource_loader_vsgdnative.unref(); -} diff --git a/modules/gdnative/videodecoder/register_types.h b/modules/gdnative/videodecoder/register_types.h deleted file mode 100644 index b261c36503..0000000000 --- a/modules/gdnative/videodecoder/register_types.h +++ /dev/null @@ -1,37 +0,0 @@ -/*************************************************************************/ -/* register_types.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 VIDEODECODER_REGISTER_TYPES_H -#define VIDEODECODER_REGISTER_TYPES_H - -void register_videodecoder_types(); -void unregister_videodecoder_types(); - -#endif // VIDEODECODER_REGISTER_TYPES_H diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.cpp b/modules/gdnative/videodecoder/video_stream_gdnative.cpp deleted file mode 100644 index d3d295c494..0000000000 --- a/modules/gdnative/videodecoder/video_stream_gdnative.cpp +++ /dev/null @@ -1,389 +0,0 @@ -/*************************************************************************/ -/* video_stream_gdnative.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "video_stream_gdnative.h" - -#include "core/config/project_settings.h" -#include "servers/audio_server.h" - -VideoDecoderServer *VideoDecoderServer::instance = nullptr; - -static VideoDecoderServer decoder_server; - -const int AUX_BUFFER_SIZE = 1024; // Buffer 1024 samples. - -// NOTE: Callbacks for the GDNative libraries. -extern "C" { -godot_int GDAPI godot_videodecoder_file_read(void *ptr, uint8_t *buf, int buf_size) { - // ptr is a FileAccess - FileAccess *file = reinterpret_cast<FileAccess *>(ptr); - - // if file exists - if (file) { - int64_t bytes_read = file->get_buffer(buf, buf_size); - return bytes_read; - } - return -1; -} - -int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) { - // file - FileAccess *file = reinterpret_cast<FileAccess *>(ptr); - - if (file) { - int64_t len = file->get_length(); - switch (whence) { - case SEEK_SET: { - if (pos > len) { - return -1; - } - file->seek(pos); - return file->get_position(); - } break; - case SEEK_CUR: { - // Just in case it doesn't exist - if (pos < 0 && -pos > (int64_t)file->get_position()) { - return -1; - } - file->seek(file->get_position() + pos); - return file->get_position(); - } break; - case SEEK_END: { - // Just in case something goes wrong - if (-pos > len) { - return -1; - } - file->seek_end(pos); - return file->get_position(); - } break; - default: { - // Only 4 possible options, hence default = AVSEEK_SIZE - // Asks to return the length of file - return len; - } break; - } - } - // In case nothing works out. - return -1; -} - -void GDAPI godot_videodecoder_register_decoder(const godot_videodecoder_interface_gdnative *p_interface) { - decoder_server.register_decoder_interface(p_interface); -} -} - -// VideoStreamPlaybackGDNative starts here. - -bool VideoStreamPlaybackGDNative::open_file(const String &p_file) { - ERR_FAIL_COND_V(interface == nullptr, false); - file = FileAccess::open(p_file, FileAccess::READ); - bool file_opened = interface->open_file(data_struct, file); - - if (file_opened) { - num_channels = interface->get_channels(data_struct); - mix_rate = interface->get_mix_rate(data_struct); - - 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_write_idx = -1; - samples_decoded = 0; - - Ref<Image> img; - img.instantiate(); - img->create((int)texture_size.width, false, (int)texture_size.height, Image::FORMAT_RGBA8); - - texture->create_from_image(img); - } - - return file_opened; -} - -void VideoStreamPlaybackGDNative::update(float p_delta) { - if (!playing || paused) { - return; - } - if (!file) { - return; - } - time += p_delta; - ERR_FAIL_COND(interface == nullptr); - interface->update(data_struct, p_delta); - - // 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 (seek_backward) { - update_texture(); - seek_backward = false; - } - - while (interface->get_playback_position(data_struct) < time && playing) { - update_texture(); - } -} - -void VideoStreamPlaybackGDNative::update_texture() { - PackedByteArray *pba = (PackedByteArray *)interface->get_videoframe(data_struct); - - if (pba == nullptr) { - playing = false; - return; - } - - Ref<Image> img = memnew(Image(texture_size.width, texture_size.height, 0, Image::FORMAT_RGBA8, *pba)); - - texture->update(img); -} - -// ctor and dtor - -VideoStreamPlaybackGDNative::VideoStreamPlaybackGDNative() : - texture(Ref<ImageTexture>(memnew(ImageTexture))) {} - -VideoStreamPlaybackGDNative::~VideoStreamPlaybackGDNative() { - cleanup(); -} - -void VideoStreamPlaybackGDNative::cleanup() { - if (data_struct) { - interface->destructor(data_struct); - } - if (pcm) { - memfree(pcm); - } - if (file) { - file->close(); - memdelete(file); - file = nullptr; - } - pcm = nullptr; - time = 0; - num_channels = -1; - interface = nullptr; - data_struct = nullptr; -} - -void VideoStreamPlaybackGDNative::set_interface(const godot_videodecoder_interface_gdnative *p_interface) { - ERR_FAIL_COND(p_interface == nullptr); - if (interface != nullptr) { - cleanup(); - } - interface = p_interface; - data_struct = interface->constructor((godot_object *)this); -} - -// controls - -bool VideoStreamPlaybackGDNative::is_playing() const { - return playing; -} - -bool VideoStreamPlaybackGDNative::is_paused() const { - return paused; -} - -void VideoStreamPlaybackGDNative::play() { - stop(); - - playing = true; - - delay_compensation = ProjectSettings::get_singleton()->get("audio/video/video_delay_compensation_ms"); - delay_compensation /= 1000.0; -} - -void VideoStreamPlaybackGDNative::stop() { - if (playing) { - seek(0); - } - playing = false; -} - -void VideoStreamPlaybackGDNative::seek(float p_time) { - ERR_FAIL_COND(interface == nullptr); - 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<Texture2D> VideoStreamPlaybackGDNative::get_texture() const { - return texture; -} - -float VideoStreamPlaybackGDNative::get_length() const { - ERR_FAIL_COND_V(interface == nullptr, 0); - return interface->get_length(data_struct); -} - -float VideoStreamPlaybackGDNative::get_playback_position() const { - ERR_FAIL_COND_V(interface == nullptr, 0); - return interface->get_playback_position(data_struct); -} - -bool VideoStreamPlaybackGDNative::has_loop() const { - // TODO: Implement looping? - return false; -} - -void VideoStreamPlaybackGDNative::set_loop(bool p_enable) { - // Do nothing -} - -void VideoStreamPlaybackGDNative::set_audio_track(int p_idx) { - ERR_FAIL_COND(interface == nullptr); - interface->set_audio_track(data_struct, p_idx); -} - -void VideoStreamPlaybackGDNative::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) { - mix_udata = p_userdata; - mix_callback = p_callback; -} - -int VideoStreamPlaybackGDNative::get_channels() const { - ERR_FAIL_COND_V(interface == nullptr, 0); - - return (num_channels > 0) ? num_channels : 0; -} - -int VideoStreamPlaybackGDNative::get_mix_rate() const { - ERR_FAIL_COND_V(interface == nullptr, 0); - - return mix_rate; -} - -/* --- NOTE VideoStreamGDNative starts here. ----- */ - -Ref<VideoStreamPlayback> VideoStreamGDNative::instance_playback() { - Ref<VideoStreamPlaybackGDNative> pb = memnew(VideoStreamPlaybackGDNative); - VideoDecoderGDNative *decoder = decoder_server.get_decoder(file.get_extension().to_lower()); - if (decoder == nullptr) { - return nullptr; - } - pb->set_interface(decoder->interface); - pb->set_audio_track(audio_track); - if (pb->open_file(file)) { - return pb; - } - return nullptr; -} - -void VideoStreamGDNative::set_file(const String &p_file) { - file = p_file; -} - -String VideoStreamGDNative::get_file() { - return file; -} - -void VideoStreamGDNative::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamGDNative::set_file); - ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamGDNative::get_file); - - ADD_PROPERTY(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_file", "get_file"); -} - -void VideoStreamGDNative::set_audio_track(int p_track) { - audio_track = p_track; -} - -/* --- NOTE ResourceFormatLoaderVideoStreamGDNative starts here. ----- */ - -RES ResourceFormatLoaderVideoStreamGDNative::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { - if (r_error) { - *r_error = ERR_CANT_OPEN; - } - return RES(); - } - memdelete(f); - VideoStreamGDNative *stream = memnew(VideoStreamGDNative); - stream->set_file(p_path); - Ref<VideoStreamGDNative> ogv_stream = Ref<VideoStreamGDNative>(stream); - if (r_error) { - *r_error = OK; - } - return ogv_stream; -} - -void ResourceFormatLoaderVideoStreamGDNative::get_recognized_extensions(List<String> *p_extensions) const { - Map<String, int>::Element *el = VideoDecoderServer::get_instance()->get_extensions().front(); - while (el) { - p_extensions->push_back(el->key()); - el = el->next(); - } -} - -bool ResourceFormatLoaderVideoStreamGDNative::handles_type(const String &p_type) const { - return ClassDB::is_parent_class(p_type, "VideoStream"); -} - -String ResourceFormatLoaderVideoStreamGDNative::get_resource_type(const String &p_path) const { - String el = p_path.get_extension().to_lower(); - if (VideoDecoderServer::get_instance()->get_extensions().has(el)) { - return "VideoStreamGDNative"; - } - return ""; -} diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.h b/modules/gdnative/videodecoder/video_stream_gdnative.h deleted file mode 100644 index b0a10242be..0000000000 --- a/modules/gdnative/videodecoder/video_stream_gdnative.h +++ /dev/null @@ -1,205 +0,0 @@ -/*************************************************************************/ -/* video_stream_gdnative.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 VIDEO_STREAM_GDNATIVE_H -#define VIDEO_STREAM_GDNATIVE_H - -#include "../gdnative.h" -#include "core/io/file_access.h" -#include "scene/resources/texture.h" -#include "scene/resources/video_stream.h" - -struct VideoDecoderGDNative { - const godot_videodecoder_interface_gdnative *interface = nullptr; - String plugin_name = "none"; - Vector<String> supported_extensions; - - VideoDecoderGDNative() {} - - VideoDecoderGDNative(const godot_videodecoder_interface_gdnative *p_interface) : - interface(p_interface), - plugin_name(p_interface->get_plugin_name()) { - _get_supported_extensions(); - } - -private: - void _get_supported_extensions() { - supported_extensions.clear(); - int num_ext; - const char **supported_ext = interface->get_supported_extensions(&num_ext); - for (int i = 0; i < num_ext; i++) { - supported_extensions.push_back(supported_ext[i]); - } - } -}; - -class VideoDecoderServer { -private: - Vector<VideoDecoderGDNative *> decoders; - Map<String, int> extensions; - - static VideoDecoderServer *instance; - -public: - static VideoDecoderServer *get_instance() { - return instance; - } - - const Map<String, int> &get_extensions() { - return extensions; - } - - void register_decoder_interface(const godot_videodecoder_interface_gdnative *p_interface) { - VideoDecoderGDNative *decoder = memnew(VideoDecoderGDNative(p_interface)); - int index = decoders.size(); - for (int i = 0; i < decoder->supported_extensions.size(); i++) { - extensions[decoder->supported_extensions[i]] = index; - } - decoders.push_back(decoder); - } - - VideoDecoderGDNative *get_decoder(const String &extension) { - if (extensions.size() == 0 || !extensions.has(extension)) { - return nullptr; - } - return decoders[extensions[extension]]; - } - - VideoDecoderServer() { - instance = this; - } - - ~VideoDecoderServer() { - for (int i = 0; i < decoders.size(); i++) { - memdelete(decoders[i]); - } - decoders.clear(); - instance = nullptr; - } -}; - -class VideoStreamPlaybackGDNative : public VideoStreamPlayback { - GDCLASS(VideoStreamPlaybackGDNative, VideoStreamPlayback); - - Ref<ImageTexture> texture; - bool playing = false; - bool paused = false; - - Vector2 texture_size; - - void *mix_udata = nullptr; - AudioMixCallback mix_callback = nullptr; - - int num_channels = -1; - float time = 0.0; - bool seek_backward = false; - int mix_rate = 0; - double delay_compensation = 0; - - float *pcm = nullptr; - int pcm_write_idx = 0; - int samples_decoded = 0; - - void cleanup(); - void update_texture(); - -protected: - String file_name; - - FileAccess *file = nullptr; - - const godot_videodecoder_interface_gdnative *interface = nullptr; - void *data_struct = nullptr; - -public: - VideoStreamPlaybackGDNative(); - ~VideoStreamPlaybackGDNative(); - - void set_interface(const godot_videodecoder_interface_gdnative *p_interface); - - bool open_file(const String &p_file); - - virtual void stop() override; - virtual void play() override; - - virtual bool is_playing() const override; - - virtual void set_paused(bool p_paused) override; - virtual bool is_paused() const override; - - virtual void set_loop(bool p_enable) override; - virtual bool has_loop() const override; - - virtual float get_length() const override; - - virtual float get_playback_position() const override; - virtual void seek(float p_time) override; - - virtual void set_audio_track(int p_idx) override; - - //virtual int mix(int16_t* p_buffer,int p_frames)=0; - - virtual Ref<Texture2D> get_texture() const override; - virtual void update(float p_delta) override; - - virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) override; - virtual int get_channels() const override; - virtual int get_mix_rate() const override; -}; - -class VideoStreamGDNative : public VideoStream { - GDCLASS(VideoStreamGDNative, VideoStream); - - String file; - int audio_track = 0; - -protected: - static void - _bind_methods(); - -public: - void set_file(const String &p_file); - String get_file(); - - virtual void set_audio_track(int p_track) override; - virtual Ref<VideoStreamPlayback> instance_playback() override; - - VideoStreamGDNative() {} -}; - -class ResourceFormatLoaderVideoStreamGDNative : public ResourceFormatLoader { -public: - virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE); - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String &p_type) const; - virtual String get_resource_type(const String &p_path) const; -}; - -#endif diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml index 33f4198ac1..d9fab01dce 100644 --- a/modules/gdscript/doc_classes/@GDScript.xml +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="@GDScript" version="4.0"> +<class name="@GDScript" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Built-in GDScript functions. </brief_description> @@ -186,6 +186,7 @@ <description> Returns an array with the given range. Range can be 1 argument [code]N[/code] (0 to [code]N[/code] - 1), two arguments ([code]initial[/code], [code]final - 1[/code]) or three arguments ([code]initial[/code], [code]final - 1[/code], [code]increment[/code]). Returns an empty array if the range isn't valid (e.g. [code]range(2, 5, -1)[/code] or [code]range(5, 5, 1)[/code]). Returns an array with the given range. [code]range()[/code] can have 1 argument N ([code]0[/code] to [code]N - 1[/code]), two arguments ([code]initial[/code], [code]final - 1[/code]) or three arguments ([code]initial[/code], [code]final - 1[/code], [code]increment[/code]). [code]increment[/code] can be negative. If [code]increment[/code] is negative, [code]final - 1[/code] will become [code]final + 1[/code]. Also, the initial value must be greater than the final value for the loop to run. + [code]range()(/code] converts all arguments to [int] before processing. [codeblock] print(range(4)) print(range(2, 5)) @@ -211,6 +212,17 @@ 6 3 [/codeblock] + To iterate over [float], convert them in the loop. + [codeblock] + for i in range (3, 0, -1): + print(i / 10.0) + [/codeblock] + Output: + [codeblock] + 0.3 + 0.2 + 0.1 + [/codeblock] </description> </method> <method name="str" qualifiers="vararg"> diff --git a/modules/gdscript/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml index 5acb29e748..578e7a34f3 100644 --- a/modules/gdscript/doc_classes/GDScript.xml +++ b/modules/gdscript/doc_classes/GDScript.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GDScript" inherits="Script" version="4.0"> +<class name="GDScript" inherits="Script" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A script implemented in the GDScript programming language. </brief_description> diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp index ac6684a29c..e3f0ddfc35 100644 --- a/modules/gdscript/editor/gdscript_highlighter.cpp +++ b/modules/gdscript/editor/gdscript_highlighter.cpp @@ -31,6 +31,7 @@ #include "gdscript_highlighter.h" #include "../gdscript.h" #include "../gdscript_tokenizer.h" +#include "core/config/project_settings.h" #include "editor/editor_settings.h" Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_line) { diff --git a/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd b/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd index edaccae018..34b5ba45b7 100644 --- a/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd +++ b/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd @@ -12,18 +12,18 @@ var gravity: int = ProjectSettings.get_setting("physics/2d/default_gravity") func _physics_process(delta: float) -> void: # Add the gravity. if not is_on_floor(): - motion_velocity.y += gravity * delta + velocity.y += gravity * delta # Handle Jump. if Input.is_action_just_pressed("ui_accept") and is_on_floor(): - motion_velocity.y = JUMP_VELOCITY + velocity.y = JUMP_VELOCITY # Get the input direction and handle the movement/deceleration. # As good practice, you should replace UI actions with custom gameplay actions. var direction := Input.get_axis("ui_left", "ui_right") if direction: - motion_velocity.x = direction * SPEED + velocity.x = direction * SPEED else: - motion_velocity.x = move_toward(motion_velocity.x, 0, SPEED) + velocity.x = move_toward(velocity.x, 0, SPEED) move_and_slide() diff --git a/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd b/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd index e191e5451a..cbc9cf1064 100644 --- a/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd +++ b/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd @@ -12,21 +12,21 @@ var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity") func _physics_process(delta: float) -> void: # Add the gravity. if not is_on_floor(): - motion_velocity.y -= gravity * delta + velocity.y -= gravity * delta # Handle Jump. if Input.is_action_just_pressed("ui_accept") and is_on_floor(): - motion_velocity.y = JUMP_VELOCITY + velocity.y = JUMP_VELOCITY # Get the input direction and handle the movement/deceleration. # As good practice, you should replace UI actions with custom gameplay actions. var input_dir := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down") var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized() if direction: - motion_velocity.x = direction.x * SPEED - motion_velocity.z = direction.z * SPEED + velocity.x = direction.x * SPEED + velocity.z = direction.z * SPEED else: - motion_velocity.x = move_toward(motion_velocity.x, 0, SPEED) - motion_velocity.z = move_toward(motion_velocity.z, 0, SPEED) + velocity.x = move_toward(velocity.x, 0, SPEED) + velocity.z = move_toward(velocity.z, 0, SPEED) move_and_slide() diff --git a/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd b/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd index d71f2592fe..cf6d68333d 100644 --- a/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd +++ b/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd @@ -34,5 +34,5 @@ func _get_output_port_name(port: int) -> String: func _get_output_port_type(port: int) -> int: return PORT_TYPE_SCALAR -func _get_code(input_vars: Array[String], output_vars: Array[String], mode: Shader.Mode, type: VisualShader.Type) -> String: +func _get_code(input_vars: Array[String], output_vars: Array[String], mode: int, type: int) -> String: return output_vars[0] + " = 0.0;" diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 58a788e255..c12c1a43a3 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -796,7 +796,7 @@ void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) { String GDScript::_get_debug_path() const { if (is_built_in() && !get_name().is_empty()) { - return get_name() + " (" + get_path().get_slice("::", 0) + ")"; + return get_name() + " (" + get_path() + ")"; } else { return get_path(); } @@ -938,7 +938,7 @@ const Vector<Multiplayer::RPCConfig> GDScript::get_rpc_methods() const { return rpc_functions; } -Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { +Variant GDScript::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { GDScript *top = this; while (top) { Map<StringName, GDScriptFunction *>::Element *E = top->member_functions.find(p_method); @@ -952,7 +952,7 @@ Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p //none found, regular - return Script::call(p_method, p_args, p_argcount, r_error); + return Script::callp(p_method, p_args, p_argcount, r_error); } bool GDScript::_get(const StringName &p_name, Variant &r_ret) const { @@ -1273,7 +1273,7 @@ bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) { if (member->setter) { const Variant *val = &p_value; Callable::CallError err; - call(member->setter, &val, 1, err); + callp(member->setter, &val, 1, err); if (err.error == Callable::CallError::CALL_OK) { return true; //function exists, call was successful } else { @@ -1335,7 +1335,7 @@ bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const { if (E) { if (E->get().getter) { Callable::CallError err; - r_ret = const_cast<GDScriptInstance *>(this)->call(E->get().getter, nullptr, 0, err); + r_ret = const_cast<GDScriptInstance *>(this)->callp(E->get().getter, nullptr, 0, err); if (err.error == Callable::CallError::CALL_OK) { return true; } @@ -1520,7 +1520,7 @@ bool GDScriptInstance::has_method(const StringName &p_method) const { return false; } -Variant GDScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { +Variant GDScriptInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { GDScript *sptr = script.ptr(); while (sptr) { Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method); @@ -1555,7 +1555,7 @@ void GDScriptInstance::notification(int p_notification) { String GDScriptInstance::to_string(bool *r_valid) { if (has_method(CoreStringNames::get_singleton()->_to_string)) { Callable::CallError ce; - Variant ret = call(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce); + Variant ret = callp(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce); if (ce.error == Callable::CallError::CALL_OK) { if (ret.get_type() != Variant::STRING) { if (r_valid) { diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index 2b43e6d21b..30e60e2b91 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -166,7 +166,7 @@ protected: bool _set(const StringName &p_name, const Variant &p_value); void _get_property_list(List<PropertyInfo> *p_properties) const; - Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override; + Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override; static void _bind_methods(); @@ -285,7 +285,7 @@ public: virtual void get_method_list(List<MethodInfo> *p_list) const; virtual bool has_method(const StringName &p_method) const; - virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error); + virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error); Variant debug_get_member_by_index(int p_idx) const { return members[p_idx]; } diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 94daba4bf6..326720ce86 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -646,41 +646,51 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas } } - if (member.variable->datatype_specifier != nullptr) { - datatype = specified_type; + // Check if initalizer is an unset identifier (ie: a variable within scope, but declared below) + if (member.variable->initializer && !member.variable->initializer->get_datatype().is_set()) { + if (member.variable->initializer->type == GDScriptParser::Node::IDENTIFIER) { + GDScriptParser::IdentifierNode *initializer_identifier = static_cast<GDScriptParser::IdentifierNode *>(member.variable->initializer); + push_error(vformat(R"(Identifier "%s" must be declared above current variable.)", initializer_identifier->name), member.variable->initializer); + } else { + ERR_PRINT("Parser bug (please report): tried to assign unset node without an identifier."); + } + } else { + if (member.variable->datatype_specifier != nullptr) { + datatype = specified_type; - if (member.variable->initializer != nullptr) { - if (!is_type_compatible(datatype, member.variable->initializer->get_datatype(), true, member.variable->initializer)) { - // Try reverse test since it can be a masked subtype. - if (!is_type_compatible(member.variable->initializer->get_datatype(), datatype, true, member.variable->initializer)) { - push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer); - } else { - // TODO: Add warning. + if (member.variable->initializer != nullptr) { + if (!is_type_compatible(datatype, member.variable->initializer->get_datatype(), true, member.variable->initializer)) { + // Try reverse test since it can be a masked subtype. + if (!is_type_compatible(member.variable->initializer->get_datatype(), datatype, true, member.variable->initializer)) { + push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer); + } else { + // TODO: Add warning. + mark_node_unsafe(member.variable->initializer); + member.variable->use_conversion_assign = true; + } + } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) { +#ifdef DEBUG_ENABLED + parser->push_warning(member.variable->initializer, GDScriptWarning::NARROWING_CONVERSION); +#endif + } + if (member.variable->initializer->get_datatype().is_variant()) { + // TODO: Warn unsafe assign. mark_node_unsafe(member.variable->initializer); member.variable->use_conversion_assign = true; } - } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) { -#ifdef DEBUG_ENABLED - parser->push_warning(member.variable->initializer, GDScriptWarning::NARROWING_CONVERSION); -#endif } - if (member.variable->initializer->get_datatype().is_variant()) { - // TODO: Warn unsafe assign. - mark_node_unsafe(member.variable->initializer); - member.variable->use_conversion_assign = true; + } else if (member.variable->infer_datatype) { + if (member.variable->initializer == nullptr) { + push_error(vformat(R"(Cannot infer the type of "%s" variable because there's no default value.)", member.variable->identifier->name), member.variable->identifier); + } else if (!datatype.is_set() || datatype.has_no_type()) { + push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value doesn't have a set type.)", member.variable->identifier->name), member.variable->initializer); + } else if (datatype.is_variant()) { + push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is Variant. Use explicit "Variant" type if this is intended.)", member.variable->identifier->name), member.variable->initializer); + } else if (datatype.builtin_type == Variant::NIL) { + push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is "null".)", member.variable->identifier->name), member.variable->initializer); } + datatype.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; } - } else if (member.variable->infer_datatype) { - if (member.variable->initializer == nullptr) { - push_error(vformat(R"(Cannot infer the type of "%s" variable because there's no default value.)", member.variable->identifier->name), member.variable->identifier); - } else if (!datatype.is_set() || datatype.has_no_type()) { - push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value doesn't have a set type.)", member.variable->identifier->name), member.variable->initializer); - } else if (datatype.is_variant()) { - push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is Variant. Use explicit "Variant" type if this is intended.)", member.variable->identifier->name), member.variable->initializer); - } else if (datatype.builtin_type == Variant::NIL) { - push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is "null".)", member.variable->identifier->name), member.variable->initializer); - } - datatype.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; } datatype.is_constant = false; @@ -1129,7 +1139,7 @@ void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode * #endif // TOOLS_ENABLED } - if (p_function->identifier->name == "_init") { + if (p_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init) { // Constructor. GDScriptParser::DataType return_type = parser->current_class->get_datatype(); return_type.is_meta_type = false; @@ -1143,6 +1153,57 @@ void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode * } else { GDScriptParser::DataType return_type = resolve_datatype(p_function->return_type); p_function->set_datatype(return_type); + +#ifdef TOOLS_ENABLED + // Check if the function signature matches the parent. If not it's an error since it breaks polymorphism. + // Not for the constructor which can vary in signature. + GDScriptParser::DataType base_type = parser->current_class->base_type; + GDScriptParser::DataType parent_return_type; + List<GDScriptParser::DataType> parameters_types; + int default_par_count = 0; + bool is_static = false; + bool is_vararg = false; + if (get_function_signature(p_function, false, base_type, p_function->identifier->name, parent_return_type, parameters_types, default_par_count, is_static, is_vararg)) { + bool valid = p_function->is_static == is_static; + valid = valid && parent_return_type == p_function->get_datatype(); + + int par_count_diff = p_function->parameters.size() - parameters_types.size(); + valid = valid && par_count_diff >= 0; + valid = valid && p_function->default_arg_values.size() >= default_par_count + par_count_diff; + + int i = 0; + for (const GDScriptParser::DataType &par_type : parameters_types) { + valid = valid && par_type == p_function->parameters[i++]->get_datatype(); + } + + if (!valid) { + // Compute parent signature as a string to show in the error message. + String parent_signature = parent_return_type.is_hard_type() ? parent_return_type.to_string() : "Variant"; + if (parent_signature == "null") { + parent_signature = "void"; + } + parent_signature += " " + p_function->identifier->name.operator String() + "("; + int j = 0; + for (const GDScriptParser::DataType &par_type : parameters_types) { + if (j > 0) { + parent_signature += ", "; + } + String parameter = par_type.to_string(); + if (parameter == "null") { + parameter = "Variant"; + } + parent_signature += parameter; + if (j == parameters_types.size() - default_par_count) { + parent_signature += " = default"; + } + + j++; + } + parent_signature += ")"; + push_error(vformat(R"(The function signature doesn't match the parent. Parent signature is "%s".)", parent_signature), p_function); + } + } +#endif } parser->current_function = previous_function; @@ -1241,7 +1302,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { bool list_resolved = false; // Optimize constant range() call to not allocate an array. - // Use int, Vector2, Vector3 instead, which also can be used as range iterators. + // Use int, Vector2i, Vector3i instead, which also can be used as range iterators. if (p_for->list && p_for->list->type == GDScriptParser::Node::CALL) { GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list); GDScriptParser::Node::Type callee_type = call->get_callee_type(); @@ -1414,7 +1475,7 @@ void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable parser->push_warning(p_variable->initializer, GDScriptWarning::NARROWING_CONVERSION); #endif } - if (p_variable->initializer->get_datatype().is_variant()) { + if (p_variable->initializer->get_datatype().is_variant() && !type.is_variant()) { // TODO: Warn unsafe assign. mark_node_unsafe(p_variable->initializer); p_variable->use_conversion_assign = true; @@ -2406,7 +2467,9 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a GDScriptParser::DataType return_type; List<GDScriptParser::DataType> par_types; - if (get_function_signature(p_call, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) { + bool is_constructor = (base_type.is_meta_type || (p_call->callee && p_call->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_call->function_name == SNAME("new"); + + if (get_function_signature(p_call, is_constructor, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) { // If the function require typed arrays we must make literals be typed. for (const KeyValue<int, GDScriptParser::ArrayNode *> &E : arrays) { int index = E.key; @@ -2565,18 +2628,24 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) } GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) { + GDScriptParser::DataType type; + Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name)); - Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + if (ref.is_null()) { + push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source); + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } + Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err) { push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source); - GDScriptParser::DataType type; type.type_source = GDScriptParser::DataType::UNDETECTED; type.kind = GDScriptParser::DataType::VARIANT; return type; } - GDScriptParser::DataType type; type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; type.kind = GDScriptParser::DataType::CLASS; type.builtin_type = Variant::OBJECT; @@ -3560,7 +3629,7 @@ GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo return result; } -bool GDScriptAnalyzer::get_function_signature(GDScriptParser::CallNode *p_source, GDScriptParser::DataType p_base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) { +bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bool p_is_constructor, GDScriptParser::DataType p_base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) { r_static = false; r_vararg = false; r_default_arg_count = 0; @@ -3600,8 +3669,7 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::CallNode *p_source return false; } - bool is_constructor = (p_base_type.is_meta_type || (p_source->callee && p_source->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_function == StaticCString::create("new"); - if (is_constructor) { + if (p_is_constructor) { function_name = "_init"; r_static = true; } @@ -3622,7 +3690,7 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::CallNode *p_source } if (found_function != nullptr) { - r_static = is_constructor || found_function->is_static; + r_static = p_is_constructor || found_function->is_static; for (int i = 0; i < found_function->parameters.size(); i++) { r_par_types.push_back(found_function->parameters[i]->get_datatype()); if (found_function->parameters[i]->default_value != nullptr) { @@ -3648,7 +3716,7 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::CallNode *p_source } // If the base is a script, it might be trying to access members of the Script class itself. - if (p_base_type.is_meta_type && !is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) { + if (p_base_type.is_meta_type && !p_is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) { MethodInfo info; StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static()); @@ -3668,7 +3736,7 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::CallNode *p_source } #endif - if (is_constructor) { + if (p_is_constructor) { // Native types always have a default constructor. r_return_type = p_base_type; r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index 2697a6ec2b..7b8883e1d3 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -105,7 +105,7 @@ class GDScriptAnalyzer { GDScriptParser::DataType type_from_metatype(const GDScriptParser::DataType &p_meta_type) const; GDScriptParser::DataType type_from_property(const PropertyInfo &p_property) const; GDScriptParser::DataType make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source); - bool get_function_signature(GDScriptParser::CallNode *p_source, GDScriptParser::DataType base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg); + bool get_function_signature(GDScriptParser::Node *p_source, bool p_is_constructor, GDScriptParser::DataType base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg); bool function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg); bool validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call); bool validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call); diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 108c988add..8190eecbc7 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -98,6 +98,7 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D case GDScriptParser::DataType::NATIVE: { result.kind = GDScriptDataType::NATIVE; result.native_type = p_datatype.native_type; + result.builtin_type = p_datatype.builtin_type; } break; case GDScriptParser::DataType::SCRIPT: { result.kind = GDScriptDataType::SCRIPT; @@ -132,11 +133,13 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D result.kind = GDScriptDataType::GDSCRIPT; result.script_type = script.ptr(); result.native_type = script->get_instance_base_type(); + result.builtin_type = p_datatype.builtin_type; } else { result.kind = GDScriptDataType::GDSCRIPT; result.script_type_ref = GDScriptCache::get_shallow_script(p_datatype.script_path, main_script->path); result.script_type = result.script_type_ref.ptr(); result.native_type = p_datatype.native_type; + result.builtin_type = p_datatype.builtin_type; } } } break; @@ -291,16 +294,21 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // Try signals and methods (can be made callables). { - if (codegen.class_node->members_indices.has(identifier)) { - const GDScriptParser::ClassNode::Member &member = codegen.class_node->members[codegen.class_node->members_indices[identifier]]; - if (member.type == GDScriptParser::ClassNode::Member::FUNCTION || member.type == GDScriptParser::ClassNode::Member::SIGNAL) { - // Get like it was a property. - GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Get type here. - GDScriptCodeGenerator::Address self(GDScriptCodeGenerator::Address::SELF); - - gen->write_get_named(temp, identifier, self); - return temp; + // Search upwards through parent classes: + const GDScriptParser::ClassNode *base_class = codegen.class_node; + while (base_class != nullptr) { + if (base_class->has_member(identifier)) { + const GDScriptParser::ClassNode::Member &member = base_class->get_member(identifier); + if (member.type == GDScriptParser::ClassNode::Member::FUNCTION || member.type == GDScriptParser::ClassNode::Member::SIGNAL) { + // Get like it was a property. + GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Get type here. + GDScriptCodeGenerator::Address self(GDScriptCodeGenerator::Address::SELF); + + gen->write_get_named(temp, identifier, self); + return temp; + } } + base_class = base_class->base_type.class_type; } // Try in native base. diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index f0dc830ed8..350962ba1b 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -65,7 +65,7 @@ Ref<Script> GDScriptLanguage::make_template(const String &p_template, const Stri script.instantiate(); String processed_template = p_template; #ifdef TOOLS_ENABLED - if (!EDITOR_DEF("text_editor/completion/add_type_hints", false)) { + if (!EDITOR_GET("text_editor/completion/add_type_hints")) { processed_template = processed_template.replace(": int", "") .replace(": String", "") .replace(": float", "") @@ -1198,6 +1198,27 @@ static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, static bool _guess_identifier_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type); static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type); +static bool _is_expression_named_identifier(const GDScriptParser::ExpressionNode *p_expression, const StringName &p_name) { + if (p_expression) { + switch (p_expression->type) { + case GDScriptParser::Node::IDENTIFIER: { + const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(p_expression); + if (id->name == p_name) { + return true; + } + } break; + case GDScriptParser::Node::CAST: { + const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression); + return _is_expression_named_identifier(cn->operand, p_name); + } break; + default: + break; + } + } + + return false; +} + static bool _guess_expression_type(GDScriptParser::CompletionContext &p_context, const GDScriptParser::ExpressionNode *p_expression, GDScriptCompletionIdentifier &r_type) { bool found = false; @@ -1904,6 +1925,14 @@ static bool _guess_identifier_type_from_base(GDScriptParser::CompletionContext & return true; } else if (init->start_line == p_context.current_line) { return false; + // Detects if variable is assigned to itself + } else if (_is_expression_named_identifier(init, member.variable->identifier->name)) { + if (member.variable->initializer->get_datatype().is_set()) { + r_type.type = member.variable->initializer->get_datatype(); + } else if (member.variable->get_datatype().is_set() && !member.variable->get_datatype().is_variant()) { + r_type.type = member.variable->get_datatype(); + } + return true; } else if (_guess_expression_type(p_context, init, r_type)) { return true; } else if (init->get_datatype().is_set() && !init->get_datatype().is_variant()) { @@ -2742,10 +2771,10 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path String GDScriptLanguage::_get_indentation() const { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { - bool use_space_indentation = EDITOR_DEF("text_editor/behavior/indent/type", false); + bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type"); if (use_space_indentation) { - int indent_size = EDITOR_DEF("text_editor/behavior/indent/size", 4); + int indent_size = EDITOR_GET("text_editor/behavior/indent/size"); String space_indent = ""; for (int i = 0; i < indent_size; i++) { diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index 9424de9d22..3d708955ed 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -95,7 +95,7 @@ void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<String int oc = 0; Map<StringName, _GDFKC> sdmap; for (const StackDebug &sd : stack_debug) { - if (sd.line > p_line) { + if (sd.line >= p_line) { break; } diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h index db663ca48f..3ee664c76d 100644 --- a/modules/gdscript/gdscript_function.h +++ b/modules/gdscript/gdscript_function.h @@ -502,6 +502,8 @@ private: List<StackDebug> stack_debug; + Variant _get_default_variant_for_data_type(const GDScriptDataType &p_data_type); + _FORCE_INLINE_ Variant *_get_variant(int p_address, GDScriptInstance *p_instance, Variant *p_stack, String &r_error) const; _FORCE_INLINE_ String _get_call_error(const Callable::CallError &p_err, const String &p_where, const Variant **argptrs) const; diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 8e4e457ec1..725b62f6d6 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -2692,12 +2692,13 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode * } } - attribute->is_attribute = true; attribute->base = p_previous_operand; if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) { return attribute; } + + attribute->is_attribute = true; attribute->attribute = parse_identifier(); return attribute; diff --git a/modules/gdscript/gdscript_rpc_callable.cpp b/modules/gdscript/gdscript_rpc_callable.cpp index 07e5ed4171..07ef5aefcb 100644 --- a/modules/gdscript/gdscript_rpc_callable.cpp +++ b/modules/gdscript/gdscript_rpc_callable.cpp @@ -64,7 +64,7 @@ ObjectID GDScriptRPCCallable::get_object() const { } void GDScriptRPCCallable::call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const { - r_return_value = object->call(method, p_arguments, p_argcount, r_call_error); + r_return_value = object->callp(method, p_arguments, p_argcount, r_call_error); } GDScriptRPCCallable::GDScriptRPCCallable(Object *p_object, const StringName &p_method) { diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp index 95122714f9..41c59c7703 100644 --- a/modules/gdscript/gdscript_vm.cpp +++ b/modules/gdscript/gdscript_vm.cpp @@ -123,6 +123,34 @@ static String _get_var_type(const Variant *p_var) { } #endif // DEBUG_ENABLED +Variant GDScriptFunction::_get_default_variant_for_data_type(const GDScriptDataType &p_data_type) { + if (p_data_type.kind == GDScriptDataType::BUILTIN) { + if (p_data_type.builtin_type == Variant::ARRAY) { + Array array; + // Typed array. + if (p_data_type.has_container_element_type()) { + const GDScriptDataType &element_type = p_data_type.get_container_element_type(); + array.set_typed( + element_type.kind == GDScriptDataType::BUILTIN ? element_type.builtin_type : Variant::OBJECT, + element_type.native_type, + element_type.script_type); + } + + return array; + } else { + Callable::CallError ce; + Variant variant; + Variant::construct(p_data_type.builtin_type, variant, nullptr, 0, ce); + + ERR_FAIL_COND_V(ce.error != Callable::CallError::CALL_OK, Variant()); + + return variant; + } + } + + return Variant(); +} + String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const String &p_where, const Variant **argptrs) const { String err_text; @@ -428,7 +456,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a OPCODES_TABLE; if (!_code_ptr) { - return Variant(); + return _get_default_variant_for_data_type(return_type); } r_err.error = Callable::CallError::CALL_OK; @@ -467,11 +495,11 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a r_err.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; r_err.argument = _argument_count; - return Variant(); + return _get_default_variant_for_data_type(return_type); } else if (p_argcount < _argument_count - _default_arg_count) { r_err.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_err.argument = _argument_count - _default_arg_count; - return Variant(); + return _get_default_variant_for_data_type(return_type); } else { defarg = _argument_count - p_argcount; } @@ -498,7 +526,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a r_err.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_err.argument = i; r_err.expected = argument_types[i].kind == GDScriptDataType::BUILTIN ? argument_types[i].builtin_type : Variant::OBJECT; - return Variant(); + return _get_default_variant_for_data_type(return_type); } if (argument_types[i].kind == GDScriptDataType::BUILTIN) { Variant arg; @@ -1419,7 +1447,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a const StringName native_type = _global_names_ptr[native_type_idx]; Array array; - array.set_typed(builtin_type, native_type, script_type); + array.set_typed(builtin_type, native_type, *script_type); array.resize(argc); for (int i = 0; i < argc; i++) { @@ -1489,7 +1517,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a Callable::CallError err; if (call_ret) { GET_INSTRUCTION_ARG(ret, argc + 1); - base->call(*methodname, (const Variant **)argptrs, argc, *ret, err); + base->callp(*methodname, (const Variant **)argptrs, argc, *ret, err); #ifdef DEBUG_ENABLED if (!call_async && ret->get_type() == Variant::OBJECT) { // Check if getting a function state without await. @@ -1508,7 +1536,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a #endif } else { Variant ret; - base->call(*methodname, (const Variant **)argptrs, argc, ret, err); + base->callp(*methodname, (const Variant **)argptrs, argc, ret, err); } #ifdef DEBUG_ENABLED if (GDScriptLanguage::get_singleton()->profiling) { @@ -2312,7 +2340,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } Array array; - array.set_typed(builtin_type, native_type, script_type); + array.set_typed(builtin_type, native_type, *script_type); #ifdef DEBUG_ENABLED bool valid = array.typed_assign(*VariantInternal::get_array(r)); @@ -2782,7 +2810,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a args[0] = &vref; Callable::CallError ce; - Variant has_next = obj->call(CoreStringNames::get_singleton()->_iter_init, (const Variant **)args, 1, ce); + Variant has_next = obj->callp(CoreStringNames::get_singleton()->_iter_init, (const Variant **)args, 1, ce); #ifdef DEBUG_ENABLED if (ce.error != Callable::CallError::CALL_OK) { @@ -2796,7 +2824,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a ip = jumpto; } else { GET_INSTRUCTION_ARG(iterator, 2); - *iterator = obj->call(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce); + *iterator = obj->callp(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce); #ifdef DEBUG_ENABLED if (ce.error != Callable::CallError::CALL_OK) { err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container); @@ -3113,7 +3141,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a args[0] = &vref; Callable::CallError ce; - Variant has_next = obj->call(CoreStringNames::get_singleton()->_iter_next, (const Variant **)args, 1, ce); + Variant has_next = obj->callp(CoreStringNames::get_singleton()->_iter_next, (const Variant **)args, 1, ce); #ifdef DEBUG_ENABLED if (ce.error != Callable::CallError::CALL_OK) { @@ -3127,7 +3155,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a ip = jumpto; } else { GET_INSTRUCTION_ARG(iterator, 2); - *iterator = obj->call(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce); + *iterator = obj->callp(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce); #ifdef DEBUG_ENABLED if (ce.error != Callable::CallError::CALL_OK) { err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container); @@ -3324,6 +3352,9 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } #endif + // Get a default return type in case of failure + retvalue = _get_default_variant_for_data_type(return_type); + OPCODE_OUT; } diff --git a/modules/gdscript/language_server/gdscript_language_server.cpp b/modules/gdscript/language_server/gdscript_language_server.cpp index 33c1c834f1..14337e87da 100644 --- a/modules/gdscript/language_server/gdscript_language_server.cpp +++ b/modules/gdscript/language_server/gdscript_language_server.cpp @@ -45,17 +45,20 @@ GDScriptLanguageServer::GDScriptLanguageServer() { void GDScriptLanguageServer::_notification(int p_what) { switch (p_what) { - case NOTIFICATION_ENTER_TREE: + case NOTIFICATION_ENTER_TREE: { start(); - break; - case NOTIFICATION_EXIT_TREE: + } break; + + case NOTIFICATION_EXIT_TREE: { stop(); - break; + } break; + case NOTIFICATION_INTERNAL_PROCESS: { if (started && !use_thread) { protocol.poll(); } } break; + case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { String host = String(_EDITOR_GET("network/language_server/remote_host")); int port = (int)_EDITOR_GET("network/language_server/remote_port"); diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp index c2bb2caa29..e8ddf90836 100644 --- a/modules/gdscript/tests/gdscript_test_runner.cpp +++ b/modules/gdscript/tests/gdscript_test_runner.cpp @@ -573,7 +573,7 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { // Call test function. Callable::CallError call_err; - instance->call(GDScriptTestRunner::test_function_name, nullptr, 0, call_err); + instance->callp(GDScriptTestRunner::test_function_name, nullptr, 0, call_err); // Tear down output handlers. remove_print_handler(&_print_handler); diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_less.gd b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_less.gd new file mode 100644 index 0000000000..435711fcaf --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_less.gd @@ -0,0 +1,10 @@ +func test(): + print("Shouldn't reach this") + +class Parent: + func my_function(_par1: int) -> int: + return 0 + +class Child extends Parent: + func my_function() -> int: + return 0 diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_less.out b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_less.out new file mode 100644 index 0000000000..3baeb17066 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_less.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +The function signature doesn't match the parent. Parent signature is "int my_function(int)". diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_more.gd b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_more.gd new file mode 100644 index 0000000000..2bd392e8f8 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_more.gd @@ -0,0 +1,10 @@ +func test(): + print("Shouldn't reach this") + +class Parent: + func my_function(_par1: int) -> int: + return 0 + +class Child extends Parent: + func my_function(_pary1: int, _par2: int) -> int: + return 0 diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_more.out b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_more.out new file mode 100644 index 0000000000..3baeb17066 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_count_more.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +The function signature doesn't match the parent. Parent signature is "int my_function(int)". diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_default_values.gd b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_default_values.gd new file mode 100644 index 0000000000..49ec82ce2d --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_default_values.gd @@ -0,0 +1,10 @@ +func test(): + print("Shouldn't reach this") + +class Parent: + func my_function(_par1: int = 0) -> int: + return 0 + +class Child extends Parent: + func my_function(_par1: int) -> int: + return 0 diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_default_values.out b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_default_values.out new file mode 100644 index 0000000000..665c229339 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_default_values.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +The function signature doesn't match the parent. Parent signature is "int my_function(int = default)". diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_type.gd b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_type.gd new file mode 100644 index 0000000000..4a17a7831f --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_type.gd @@ -0,0 +1,10 @@ +func test(): + print("Shouldn't reach this") + +class Parent: + func my_function(_par1: int) -> int: + return 0 + +class Child extends Parent: + func my_function(_par1: Vector2) -> int: + return 0 diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_type.out b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_type.out new file mode 100644 index 0000000000..3baeb17066 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_parameter_type.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +The function signature doesn't match the parent. Parent signature is "int my_function(int)". diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_return_type.gd b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_return_type.gd new file mode 100644 index 0000000000..b205ec96ef --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_return_type.gd @@ -0,0 +1,10 @@ +func test(): + print("Shouldn't reach this") + +class Parent: + func my_function() -> int: + return 0 + +class Child extends Parent: + func my_function() -> Vector2: + return Vector2() diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_return_type.out b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_return_type.out new file mode 100644 index 0000000000..5b22739a93 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/function_dont_match_parent_signature_return_type.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +The function signature doesn't match the parent. Parent signature is "int my_function()". diff --git a/modules/gdscript/tests/scripts/analyzer/features/function_match_parent_signature_with_extra_parameters.gd b/modules/gdscript/tests/scripts/analyzer/features/function_match_parent_signature_with_extra_parameters.gd new file mode 100644 index 0000000000..d678f3acfc --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/function_match_parent_signature_with_extra_parameters.gd @@ -0,0 +1,17 @@ +func test(): + var instance := Parent.new() + var result := instance.my_function(1) + print(result) + assert(result == 1) + instance = Child.new() + result = instance.my_function(2) + print(result) + assert(result == 0) + +class Parent: + func my_function(par1: int) -> int: + return par1 + +class Child extends Parent: + func my_function(_par1: int, par2: int = 0) -> int: + return par2 diff --git a/modules/gdscript/tests/scripts/analyzer/features/function_match_parent_signature_with_extra_parameters.out b/modules/gdscript/tests/scripts/analyzer/features/function_match_parent_signature_with_extra_parameters.out new file mode 100644 index 0000000000..fc5315a501 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/function_match_parent_signature_with_extra_parameters.out @@ -0,0 +1,3 @@ +GDTEST_OK +1 +0 diff --git a/modules/gdscript/tests/scripts/parser/features/class_inheritance_access.gd b/modules/gdscript/tests/scripts/parser/features/class_inheritance_access.gd new file mode 100644 index 0000000000..eb392672eb --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/features/class_inheritance_access.gd @@ -0,0 +1,40 @@ +# Test access visibility of parent elements in nested class architectures. +class Parent: + const parent_const := 1 + + var parent_variable := 2 + + signal parent_signal + + var parent_attribute: int: + get: + return 3 + + func parent_func(): + return 4 + + class Nested: + const nested_const := 5 + + +class Child extends Parent: + func child_test(): + print(parent_const) + print(self.parent_const) + print(parent_variable) + print(self.parent_variable) + print(parent_signal.get_name()) + print(self.parent_signal.get_name()) + print(parent_attribute) + print(self.parent_attribute) + print(parent_func.get_method()) + print(self.parent_func.get_method()) + print(parent_func()) + print(self.parent_func()) + print(Nested.nested_const) + print(self.Nested.nested_const) + print(Parent.Nested.nested_const) + + +func test(): + Child.new().child_test() diff --git a/modules/gdscript/tests/scripts/parser/features/class_inheritance_access.out b/modules/gdscript/tests/scripts/parser/features/class_inheritance_access.out new file mode 100644 index 0000000000..09e87bccfa --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/features/class_inheritance_access.out @@ -0,0 +1,16 @@ +GDTEST_OK +1 +1 +2 +2 +parent_signal +parent_signal +3 +3 +parent_func +parent_func +4 +4 +5 +5 +5 diff --git a/modules/gltf/doc_classes/GLTFAccessor.xml b/modules/gltf/doc_classes/GLTFAccessor.xml index ae81cae81a..b73a4f8c5f 100644 --- a/modules/gltf/doc_classes/GLTFAccessor.xml +++ b/modules/gltf/doc_classes/GLTFAccessor.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFAccessor" inherits="Resource" version="4.0"> +<class name="GLTFAccessor" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFAnimation.xml b/modules/gltf/doc_classes/GLTFAnimation.xml index 70480c2b38..e2991170a4 100644 --- a/modules/gltf/doc_classes/GLTFAnimation.xml +++ b/modules/gltf/doc_classes/GLTFAnimation.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFAnimation" inherits="Resource" version="4.0"> +<class name="GLTFAnimation" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFBufferView.xml b/modules/gltf/doc_classes/GLTFBufferView.xml index f58aa46508..00b6ccbe7d 100644 --- a/modules/gltf/doc_classes/GLTFBufferView.xml +++ b/modules/gltf/doc_classes/GLTFBufferView.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFBufferView" inherits="Resource" version="4.0"> +<class name="GLTFBufferView" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFCamera.xml b/modules/gltf/doc_classes/GLTFCamera.xml index 3682df5951..9b9eff6141 100644 --- a/modules/gltf/doc_classes/GLTFCamera.xml +++ b/modules/gltf/doc_classes/GLTFCamera.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFCamera" inherits="Resource" version="4.0"> +<class name="GLTFCamera" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFDocument.xml b/modules/gltf/doc_classes/GLTFDocument.xml index ed7c018cb9..7adabdc605 100644 --- a/modules/gltf/doc_classes/GLTFDocument.xml +++ b/modules/gltf/doc_classes/GLTFDocument.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFDocument" inherits="Resource" version="4.0"> +<class name="GLTFDocument" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFDocumentExtension.xml b/modules/gltf/doc_classes/GLTFDocumentExtension.xml index 390bd3b30b..03b4380ff4 100644 --- a/modules/gltf/doc_classes/GLTFDocumentExtension.xml +++ b/modules/gltf/doc_classes/GLTFDocumentExtension.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFDocumentExtension" inherits="Resource" version="4.0"> +<class name="GLTFDocumentExtension" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFDocumentExtensionConvertImporterMesh.xml b/modules/gltf/doc_classes/GLTFDocumentExtensionConvertImporterMesh.xml index 452eec5f4f..70268fc0c9 100644 --- a/modules/gltf/doc_classes/GLTFDocumentExtensionConvertImporterMesh.xml +++ b/modules/gltf/doc_classes/GLTFDocumentExtensionConvertImporterMesh.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFDocumentExtensionConvertImporterMesh" inherits="GLTFDocumentExtension" version="4.0"> +<class name="GLTFDocumentExtensionConvertImporterMesh" inherits="GLTFDocumentExtension" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFLight.xml b/modules/gltf/doc_classes/GLTFLight.xml index b4f03cd1ed..354cd48a06 100644 --- a/modules/gltf/doc_classes/GLTFLight.xml +++ b/modules/gltf/doc_classes/GLTFLight.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFLight" inherits="Resource" version="4.0"> +<class name="GLTFLight" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFMesh.xml b/modules/gltf/doc_classes/GLTFMesh.xml index 58853217e2..bac351cc20 100644 --- a/modules/gltf/doc_classes/GLTFMesh.xml +++ b/modules/gltf/doc_classes/GLTFMesh.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFMesh" inherits="Resource" version="4.0"> +<class name="GLTFMesh" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml index f27965ea07..e933e6046a 100644 --- a/modules/gltf/doc_classes/GLTFNode.xml +++ b/modules/gltf/doc_classes/GLTFNode.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFNode" inherits="Resource" version="4.0"> +<class name="GLTFNode" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFSkeleton.xml b/modules/gltf/doc_classes/GLTFSkeleton.xml index 037c3545a6..dad985e886 100644 --- a/modules/gltf/doc_classes/GLTFSkeleton.xml +++ b/modules/gltf/doc_classes/GLTFSkeleton.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFSkeleton" inherits="Resource" version="4.0"> +<class name="GLTFSkeleton" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFSkin.xml b/modules/gltf/doc_classes/GLTFSkin.xml index ad4f017584..b6a2bdb957 100644 --- a/modules/gltf/doc_classes/GLTFSkin.xml +++ b/modules/gltf/doc_classes/GLTFSkin.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFSkin" inherits="Resource" version="4.0"> +<class name="GLTFSkin" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFSpecGloss.xml b/modules/gltf/doc_classes/GLTFSpecGloss.xml index 6b8f86ed1c..8433cf8dd7 100644 --- a/modules/gltf/doc_classes/GLTFSpecGloss.xml +++ b/modules/gltf/doc_classes/GLTFSpecGloss.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFSpecGloss" inherits="Resource" version="4.0"> +<class name="GLTFSpecGloss" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFState.xml b/modules/gltf/doc_classes/GLTFState.xml index 6d03d0ecf8..a59fa900bc 100644 --- a/modules/gltf/doc_classes/GLTFState.xml +++ b/modules/gltf/doc_classes/GLTFState.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFState" inherits="Resource" version="4.0"> +<class name="GLTFState" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/doc_classes/GLTFTexture.xml b/modules/gltf/doc_classes/GLTFTexture.xml index 7c88d2318e..c0bc424168 100644 --- a/modules/gltf/doc_classes/GLTFTexture.xml +++ b/modules/gltf/doc_classes/GLTFTexture.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GLTFTexture" inherits="Resource" version="4.0"> +<class name="GLTFTexture" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp index fd5741605c..601c70791c 100644 --- a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp +++ b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp @@ -30,10 +30,12 @@ #if TOOLS_ENABLED #include "editor_scene_exporter_gltf_plugin.h" + #include "core/config/project_settings.h" #include "core/error/error_list.h" #include "core/object/object.h" #include "core/templates/vector.h" +#include "editor/editor_file_dialog.h" #include "editor/editor_file_system.h" #include "gltf_document.h" #include "gltf_state.h" @@ -51,10 +53,9 @@ bool SceneExporterGLTFPlugin::has_main_screen() const { return false; } -SceneExporterGLTFPlugin::SceneExporterGLTFPlugin(EditorNode *p_node) { - editor = p_node; +SceneExporterGLTFPlugin::SceneExporterGLTFPlugin() { file_export_lib = memnew(EditorFileDialog); - editor->get_gui_base()->add_child(file_export_lib); + EditorNode::get_singleton()->get_gui_base()->add_child(file_export_lib); file_export_lib->connect("file_selected", callable_mp(this, &SceneExporterGLTFPlugin::_gltf2_dialog_action)); file_export_lib->set_title(TTR("Export Library")); file_export_lib->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE); @@ -68,9 +69,9 @@ SceneExporterGLTFPlugin::SceneExporterGLTFPlugin(EditorNode *p_node) { } void SceneExporterGLTFPlugin::_gltf2_dialog_action(String p_file) { - Node *root = editor->get_tree()->get_edited_scene_root(); + Node *root = EditorNode::get_singleton()->get_tree()->get_edited_scene_root(); if (!root) { - editor->show_accept(TTR("This operation can't be done without a scene."), TTR("OK")); + EditorNode::get_singleton()->show_accept(TTR("This operation can't be done without a scene."), TTR("OK")); return; } List<String> deps; @@ -91,9 +92,9 @@ void SceneExporterGLTFPlugin::_gltf2_dialog_action(String p_file) { } void SceneExporterGLTFPlugin::convert_scene_to_gltf2() { - Node *root = editor->get_tree()->get_edited_scene_root(); + Node *root = EditorNode::get_singleton()->get_tree()->get_edited_scene_root(); if (!root) { - editor->show_accept(TTR("This operation can't be done without a scene."), TTR("OK")); + EditorNode::get_singleton()->show_accept(TTR("This operation can't be done without a scene."), TTR("OK")); return; } String filename = String(root->get_scene_file_path().get_file().get_basename()); diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.h b/modules/gltf/editor_scene_exporter_gltf_plugin.h index e6b15e73c4..c2c3f5710c 100644 --- a/modules/gltf/editor_scene_exporter_gltf_plugin.h +++ b/modules/gltf/editor_scene_exporter_gltf_plugin.h @@ -33,13 +33,11 @@ #if TOOLS_ENABLED #include "editor/editor_plugin.h" - #include "editor_scene_importer_gltf.h" class SceneExporterGLTFPlugin : public EditorPlugin { GDCLASS(SceneExporterGLTFPlugin, EditorPlugin); - EditorNode *editor = nullptr; EditorFileDialog *file_export_lib = nullptr; void _gltf2_dialog_action(String p_file); void convert_scene_to_gltf2(); @@ -47,7 +45,7 @@ class SceneExporterGLTFPlugin : public EditorPlugin { public: virtual String get_name() const override; bool has_main_screen() const override; - SceneExporterGLTFPlugin(class EditorNode *p_node); + SceneExporterGLTFPlugin(); }; #endif // TOOLS_ENABLED #endif // EDITOR_SCENE_EXPORTER_GLTF_PLUGIN_H diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index 0056fee7a4..c70081a620 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -84,6 +84,41 @@ #include <cstdint> #include <limits> +static Ref<ImporterMesh> _mesh_to_importer_mesh(Ref<Mesh> p_mesh) { + Ref<ImporterMesh> importer_mesh; + importer_mesh.instantiate(); + if (p_mesh.is_null()) { + return importer_mesh; + } + + Ref<ArrayMesh> array_mesh = p_mesh; + if (p_mesh->get_blend_shape_count()) { + ArrayMesh::BlendShapeMode shape_mode = ArrayMesh::BLEND_SHAPE_MODE_NORMALIZED; + if (array_mesh.is_valid()) { + shape_mode = array_mesh->get_blend_shape_mode(); + } + importer_mesh->set_blend_shape_mode(shape_mode); + for (int morph_i = 0; morph_i < p_mesh->get_blend_shape_count(); morph_i++) { + importer_mesh->add_blend_shape(p_mesh->get_blend_shape_name(morph_i)); + } + } + for (int32_t surface_i = 0; surface_i < p_mesh->get_surface_count(); surface_i++) { + Array array = p_mesh->surface_get_arrays(surface_i); + Ref<Material> mat = p_mesh->surface_get_material(surface_i); + String mat_name; + if (mat.is_valid()) { + mat_name = mat->get_name(); + } else { + // Assign default material when no material is assigned. + mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D)); + } + importer_mesh->add_surface(p_mesh->surface_get_primitive_type(surface_i), + array, p_mesh->surface_get_blend_shape_arrays(surface_i), p_mesh->surface_get_lods(surface_i), mat, + mat_name, p_mesh->surface_get_format(surface_i)); + } + return importer_mesh; +} + Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { if (!state->buffers.size()) { state->buffers.push_back(Vector<uint8_t>()); @@ -3373,9 +3408,9 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { orm_texture_index = _set_texture(state, orm_texture); } if (has_ao) { - Dictionary ot; - ot["index"] = orm_texture_index; - d["occlusionTexture"] = ot; + Dictionary occt; + occt["index"] = orm_texture_index; + d["occlusionTexture"] = occt; } if (has_roughness || has_metalness) { mrt["index"] = orm_texture_index; @@ -5038,39 +5073,16 @@ GLTFMeshIndex GLTFDocument::_convert_mesh_to_gltf(Ref<GLTFState> state, MeshInst if (p_mesh_instance->get_mesh().is_null()) { return -1; } - Ref<ImporterMesh> current_mesh; - current_mesh.instantiate(); + + Ref<Mesh> import_mesh = p_mesh_instance->get_mesh(); + Ref<ImporterMesh> current_mesh = _mesh_to_importer_mesh(import_mesh); Vector<float> blend_weights; - { - Ref<Mesh> import_mesh = p_mesh_instance->get_mesh(); - Ref<ArrayMesh> import_array_mesh = p_mesh_instance->get_mesh(); - if (import_mesh->get_blend_shape_count()) { - ArrayMesh::BlendShapeMode shape_mode = ArrayMesh::BLEND_SHAPE_MODE_NORMALIZED; - if (import_array_mesh.is_valid()) { - shape_mode = import_array_mesh->get_blend_shape_mode(); - } - current_mesh->set_blend_shape_mode(shape_mode); - for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) { - current_mesh->add_blend_shape(import_mesh->get_blend_shape_name(morph_i)); - } - } - for (int32_t surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) { - Array array = import_mesh->surface_get_arrays(surface_i); - Ref<Material> mat = import_mesh->surface_get_material(surface_i); - String mat_name; - if (mat.is_valid()) { - mat_name = mat->get_name(); - } - current_mesh->add_surface(import_mesh->surface_get_primitive_type(surface_i), - array, import_mesh->surface_get_blend_shape_arrays(surface_i), import_mesh->surface_get_lods(surface_i), mat, - mat_name, import_mesh->surface_get_format(surface_i)); - } - int32_t blend_count = import_mesh->get_blend_shape_count(); - blend_weights.resize(blend_count); - for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) { - blend_weights.write[blend_i] = 0.0f; - } + int32_t blend_count = import_mesh->get_blend_shape_count(); + blend_weights.resize(blend_count); + for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) { + blend_weights.write[blend_i] = 0.0f; } + Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); Array instance_materials; @@ -5322,14 +5334,31 @@ void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeInd if (meshes.size() != 2) { return; } - Ref<Material> mat; - if (csg->get_material_override().is_valid()) { - mat = csg->get_material_override(); + + Ref<ImporterMesh> mesh; + mesh.instantiate(); + { + Ref<Mesh> csg_mesh = csg->get_meshes()[1]; + + for (int32_t surface_i = 0; surface_i < csg_mesh->get_surface_count(); surface_i++) { + Array array = csg_mesh->surface_get_arrays(surface_i); + Ref<Material> mat = csg_mesh->surface_get_material(surface_i); + String mat_name; + if (mat.is_valid()) { + mat_name = mat->get_name(); + } else { + // Assign default material when no material is assigned. + mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D)); + } + mesh->add_surface(csg_mesh->surface_get_primitive_type(surface_i), + array, csg_mesh->surface_get_blend_shape_arrays(surface_i), csg_mesh->surface_get_lods(surface_i), mat, + mat_name, csg_mesh->surface_get_format(surface_i)); + } } + Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); - Ref<ImporterMesh> array_mesh = csg->get_meshes()[1]; - gltf_mesh->set_mesh(array_mesh); + gltf_mesh->set_mesh(mesh); GLTFMeshIndex mesh_i = state->meshes.size(); state->meshes.push_back(gltf_mesh); gltf_node->mesh = mesh_i; @@ -5395,8 +5424,6 @@ void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex Vector3 cell_location = cells[k]; int32_t cell = p_grid_map->get_cell_item( Vector3(cell_location.x, cell_location.y, cell_location.z)); - ImporterMeshInstance3D *import_mesh_node = memnew(ImporterMeshInstance3D); - import_mesh_node->set_mesh(p_grid_map->get_mesh_library()->get_item_mesh(cell)); Transform3D cell_xform; cell_xform.basis.set_orthogonal_index( p_grid_map->get_cell_item_orientation( @@ -5408,7 +5435,7 @@ void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex Vector3(cell_location.x, cell_location.y, cell_location.z))); Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); - gltf_mesh = import_mesh_node; + gltf_mesh->set_mesh(_mesh_to_importer_mesh(p_grid_map->get_mesh_library()->get_item_mesh(cell))); new_gltf_node->mesh = state->meshes.size(); state->meshes.push_back(gltf_mesh); new_gltf_node->xform = cell_xform * p_grid_map->get_transform(); @@ -6443,8 +6470,8 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, gltf_animation->get_tracks().insert(transform_track_i.key, track); } } - } else if (String(orig_track_path).contains(":blend_shapes/")) { - const Vector<String> node_suffix = String(orig_track_path).split(":blend_shapes/"); + } else if (String(orig_track_path).contains(":") && animation->track_get_type(track_i) == Animation::TYPE_BLEND_SHAPE) { + const Vector<String> node_suffix = String(orig_track_path).split(":"); const NodePath path = node_suffix[0]; const String suffix = node_suffix[1]; Node *node = ap->get_parent()->get_node_or_null(path); diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml index 9c28421a46..407ce961c8 100644 --- a/modules/gridmap/doc_classes/GridMap.xml +++ b/modules/gridmap/doc_classes/GridMap.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GridMap" inherits="Node3D" version="4.0"> +<class name="GridMap" inherits="Node3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Node for 3D tile-based maps. </brief_description> @@ -79,6 +79,13 @@ Returns an array of [Vector3] with the non-empty cell coordinates in the grid map. </description> </method> + <method name="get_used_cells_by_item" qualifiers="const"> + <return type="Array" /> + <argument index="0" name="item" type="int" /> + <description> + Returns an array of all cells with the given item index specified in [code]item[/code]. + </description> + </method> <method name="make_baked_meshes"> <return type="void" /> <argument index="0" name="gen_lightmap_uv" type="bool" default="false" /> @@ -110,15 +117,6 @@ Optionally, the item's orientation can be passed. For valid orientation values, see [method Basis.get_orthogonal_index]. </description> </method> - <method name="set_clip"> - <return type="void" /> - <argument index="0" name="enabled" type="bool" /> - <argument index="1" name="clipabove" type="bool" default="true" /> - <argument index="2" name="floor" type="int" default="0" /> - <argument index="3" name="axis" type="int" enum="Vector3.Axis" default="0" /> - <description> - </description> - </method> <method name="set_collision_layer_value"> <return type="void" /> <argument index="0" name="layer_number" type="int" /> diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index 6df7835855..02fe4d93de 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -703,8 +703,8 @@ void GridMap::_notification(int p_what) { RS::get_singleton()->instance_set_scenario(baked_meshes[i].instance, get_world_3d()->get_scenario()); RS::get_singleton()->instance_set_transform(baked_meshes[i].instance, get_global_transform()); } - } break; + case NOTIFICATION_TRANSFORM_CHANGED: { Transform3D new_xform = get_global_transform(); if (new_xform == last_transform) { @@ -721,6 +721,7 @@ void GridMap::_notification(int p_what) { RS::get_singleton()->instance_set_transform(baked_meshes[i].instance, get_global_transform()); } } break; + case NOTIFICATION_EXIT_WORLD: { for (const KeyValue<OctantKey, Octant *> &E : octant_map) { _octant_exit_world(E.key); @@ -732,8 +733,8 @@ void GridMap::_notification(int p_what) { for (int i = 0; i < baked_meshes.size(); i++) { RS::get_singleton()->instance_set_scenario(baked_meshes[i].instance, RID()); } - } break; + case NOTIFICATION_VISIBILITY_CHANGED: { _update_visibility(); } break; @@ -873,11 +874,10 @@ void GridMap::_bind_methods() { ClassDB::bind_method(D_METHOD("set_center_z", "enable"), &GridMap::set_center_z); ClassDB::bind_method(D_METHOD("get_center_z"), &GridMap::get_center_z); - ClassDB::bind_method(D_METHOD("set_clip", "enabled", "clipabove", "floor", "axis"), &GridMap::set_clip, DEFVAL(true), DEFVAL(0), DEFVAL(Vector3::AXIS_X)); - ClassDB::bind_method(D_METHOD("clear"), &GridMap::clear); ClassDB::bind_method(D_METHOD("get_used_cells"), &GridMap::get_used_cells); + ClassDB::bind_method(D_METHOD("get_used_cells_by_item", "item"), &GridMap::get_used_cells_by_item); ClassDB::bind_method(D_METHOD("get_meshes"), &GridMap::get_meshes); ClassDB::bind_method(D_METHOD("get_bake_meshes"), &GridMap::get_bake_meshes); @@ -907,28 +907,6 @@ void GridMap::_bind_methods() { 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) { - if (!p_enabled && !clip) { - return; - } - if (clip && p_enabled && clip_floor == p_floor && p_clip_above == clip_above && p_axis == clip_axis) { - return; - } - - clip = p_enabled; - clip_floor = p_floor; - clip_axis = p_axis; - clip_above = p_clip_above; - - //make it all update - for (KeyValue<OctantKey, Octant *> &E : octant_map) { - Octant *g = E.value; - g->dirty = true; - } - awaiting_update = true; - _update_octants_callback(); -} - void GridMap::set_cell_scale(float p_scale) { cell_scale = p_scale; _recreate_octant_data(); @@ -950,6 +928,18 @@ Array GridMap::get_used_cells() const { return a; } +Array GridMap::get_used_cells_by_item(int p_item) const { + Array a; + for (const KeyValue<IndexKey, Cell> &E : cell_map) { + if (E.value.item == p_item) { + Vector3 p(E.key.x, E.key.y, E.key.z); + a.push_back(p); + } + } + + return a; +} + Array GridMap::get_meshes() const { if (mesh_library.is_null()) { return Array(); diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h index 6cdc3b178d..b09cabfe25 100644 --- a/modules/gridmap/grid_map.h +++ b/modules/gridmap/grid_map.h @@ -150,14 +150,8 @@ class GridMap : public Node3D { bool center_z = true; float cell_scale = 1.0; - bool clip = false; - bool clip_above = true; - int clip_floor = 0; - bool recreating_octants = false; - Vector3::Axis clip_axis = Vector3::AXIS_Z; - Ref<MeshLibrary> mesh_library; Map<OctantKey, Octant *> octant_map; @@ -260,12 +254,11 @@ public: Vector3i world_to_map(const Vector3 &p_world_position) const; Vector3 map_to_world(const Vector3i &p_map_position) const; - void set_clip(bool p_enabled, bool p_clip_above = true, int p_floor = 0, Vector3::Axis p_axis = Vector3::AXIS_X); - void set_cell_scale(float p_scale); float get_cell_scale() const; Array get_used_cells() const; + Array get_used_cells_by_item(int p_item) const; Array get_meshes() const; diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp index 84510fc71e..e8e096d52b 100644 --- a/modules/gridmap/grid_map_editor_plugin.cpp +++ b/modules/gridmap/grid_map_editor_plugin.cpp @@ -30,6 +30,7 @@ #include "grid_map_editor_plugin.h" #include "core/input/input.h" +#include "editor/editor_node.h" #include "editor/editor_scale.h" #include "editor/editor_settings.h" #include "editor/plugins/node_3d_editor_plugin.h" @@ -62,17 +63,6 @@ void GridMapEditor::_menu_option(int p_option) { floor->set_value(floor->get_value() + 1); } break; - case MENU_OPTION_CLIP_DISABLED: - case MENU_OPTION_CLIP_ABOVE: - case MENU_OPTION_CLIP_BELOW: { - clip_mode = ClipMode(p_option - MENU_OPTION_CLIP_DISABLED); - for (int i = 0; i < 3; i++) { - int index = options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED + i); - options->get_popup()->set_item_checked(index, i == clip_mode); - } - - _update_clip(); - } break; case MENU_OPTION_X_AXIS: case MENU_OPTION_Y_AXIS: case MENU_OPTION_Z_AXIS: { @@ -97,7 +87,6 @@ void GridMapEditor::_menu_option(int p_option) { } edit_axis = Vector3::Axis(new_axis); update_grid(); - _update_clip(); } break; case MENU_OPTION_CURSOR_ROTATE_Y: { @@ -834,7 +823,7 @@ 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); + float min_size = EDITOR_GET("editors/grid_map/preview_size"); min_size *= EDSCALE; mesh_library_palette->clear(); @@ -923,7 +912,7 @@ void GridMapEditor::edit(GridMap *p_gridmap) { _update_selection_transform(); _update_paste_indicator(); - spatial_editor = Object::cast_to<Node3DEditorPlugin>(editor->get_editor_plugin_screen()); + spatial_editor = Object::cast_to<Node3DEditorPlugin>(EditorNode::get_singleton()->get_editor_plugin_screen()); if (!node) { set_process(false); @@ -942,24 +931,12 @@ void GridMapEditor::edit(GridMap *p_gridmap) { set_process(true); - clip_mode = p_gridmap->has_meta("_editor_clip_") ? ClipMode(p_gridmap->get_meta("_editor_clip_").operator int()) : CLIP_DISABLED; - _draw_grids(node->get_cell_size()); update_grid(); - _update_clip(); node->connect("cell_size_changed", callable_mp(this, &GridMapEditor::_draw_grids)); } -void GridMapEditor::_update_clip() { - node->set_meta("_editor_clip_", clip_mode); - if (clip_mode == CLIP_DISABLED) { - node->set_clip(false); - } else { - node->set_clip(true, clip_mode == CLIP_ABOVE, edit_floor[edit_axis], edit_axis); - } -} - void GridMapEditor::update_grid() { grid_xform.origin.x -= 1; // Force update in hackish way. @@ -1146,7 +1123,6 @@ void GridMapEditor::_floor_changed(float p_value) { edit_floor[edit_axis] = p_value; node->set_meta("_editor_floor_", Vector3(edit_floor[0], edit_floor[1], edit_floor[2])); update_grid(); - _update_clip(); _update_selection_transform(); } @@ -1159,9 +1135,8 @@ void GridMapEditor::_bind_methods() { ClassDB::bind_method("_set_selection", &GridMapEditor::_set_selection); } -GridMapEditor::GridMapEditor(EditorNode *p_editor) { - editor = p_editor; - undo_redo = p_editor->get_undo_redo(); +GridMapEditor::GridMapEditor() { + undo_redo = EditorNode::get_singleton()->get_undo_redo(); int mw = EDITOR_DEF("editors/grid_map/palette_min_width", 230); Control *ec = memnew(Control); @@ -1198,11 +1173,6 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { options->get_popup()->add_item(TTR("Previous Floor"), MENU_OPTION_PREV_LEVEL, Key::Q); options->get_popup()->add_item(TTR("Next Floor"), MENU_OPTION_NEXT_LEVEL, Key::E); options->get_popup()->add_separator(); - options->get_popup()->add_radio_check_item(TTR("Clip Disabled"), MENU_OPTION_CLIP_DISABLED); - options->get_popup()->set_item_checked(options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED), true); - options->get_popup()->add_radio_check_item(TTR("Clip Above"), MENU_OPTION_CLIP_ABOVE); - options->get_popup()->add_radio_check_item(TTR("Clip Below"), MENU_OPTION_CLIP_BELOW); - options->get_popup()->add_separator(); options->get_popup()->add_radio_check_item(TTR("Edit X Axis"), MENU_OPTION_X_AXIS, Key::Z); options->get_popup()->add_radio_check_item(TTR("Edit Y Axis"), MENU_OPTION_Y_AXIS, Key::X); options->get_popup()->add_radio_check_item(TTR("Edit Z Axis"), MENU_OPTION_Z_AXIS, Key::C); @@ -1237,7 +1207,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { settings_pick_distance->set_max(10000.0f); settings_pick_distance->set_min(500.0f); settings_pick_distance->set_step(1.0f); - settings_pick_distance->set_value(EDITOR_DEF("editors/grid_map/pick_distance", 5000.0)); + settings_pick_distance->set_value(EDITOR_GET("editors/grid_map/pick_distance")); settings_vbc->add_margin_child(TTR("Pick Distance:"), settings_pick_distance); options->get_popup()->connect("id_pressed", callable_mp(this, &GridMapEditor::_menu_option)); @@ -1456,15 +1426,17 @@ GridMapEditor::~GridMapEditor() { } void GridMapEditorPlugin::_notification(int p_what) { - if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) { - switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) { - case 0: { // Left. - Node3DEditor::get_singleton()->move_control_to_left_panel(grid_map_editor); - } break; - case 1: { // Right. - Node3DEditor::get_singleton()->move_control_to_right_panel(grid_map_editor); - } break; - } + switch (p_what) { + case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { + switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) { + case 0: { // Left. + Node3DEditor::get_singleton()->move_control_to_left_panel(grid_map_editor); + } break; + case 1: { // Right. + Node3DEditor::get_singleton()->move_control_to_right_panel(grid_map_editor); + } break; + } + } break; } } @@ -1489,13 +1461,11 @@ void GridMapEditorPlugin::make_visible(bool p_visible) { } } -GridMapEditorPlugin::GridMapEditorPlugin(EditorNode *p_node) { - editor = p_node; - +GridMapEditorPlugin::GridMapEditorPlugin() { EDITOR_DEF("editors/grid_map/editor_side", 1); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/grid_map/editor_side", PROPERTY_HINT_ENUM, "Left,Right")); - grid_map_editor = memnew(GridMapEditor(editor)); + grid_map_editor = memnew(GridMapEditor); switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) { case 0: { // Left. Node3DEditor::get_singleton()->add_control_to_left_panel(grid_map_editor); diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h index 37298a1d80..c44c4ca7e0 100644 --- a/modules/gridmap/grid_map_editor_plugin.h +++ b/modules/gridmap/grid_map_editor_plugin.h @@ -31,9 +31,11 @@ #ifndef GRID_MAP_EDITOR_PLUGIN_H #define GRID_MAP_EDITOR_PLUGIN_H -#include "editor/editor_node.h" #include "editor/editor_plugin.h" #include "grid_map.h" +#include "scene/gui/item_list.h" +#include "scene/gui/slider.h" +#include "scene/gui/spin_box.h" class Node3DEditorPlugin; @@ -53,12 +55,6 @@ class GridMapEditor : public VBoxContainer { INPUT_PASTE, }; - enum ClipMode { - CLIP_DISABLED, - CLIP_ABOVE, - CLIP_BELOW - }; - enum DisplayMode { DISPLAY_THUMBNAIL, DISPLAY_LIST @@ -92,7 +88,6 @@ class GridMapEditor : public VBoxContainer { GridMap *node = nullptr; MeshLibrary *last_mesh_library; - ClipMode clip_mode = CLIP_DISABLED; Transform3D grid_xform; Transform3D edit_grid_xform; @@ -157,9 +152,6 @@ class GridMapEditor : public VBoxContainer { MENU_OPTION_NEXT_LEVEL, MENU_OPTION_PREV_LEVEL, MENU_OPTION_LOCK_VIEW, - MENU_OPTION_CLIP_DISABLED, - MENU_OPTION_CLIP_ABOVE, - MENU_OPTION_CLIP_BELOW, MENU_OPTION_X_AXIS, MENU_OPTION_Y_AXIS, MENU_OPTION_Z_AXIS, @@ -189,8 +181,6 @@ class GridMapEditor : public VBoxContainer { 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(); @@ -200,7 +190,6 @@ class GridMapEditor : public VBoxContainer { void _item_selected_cbk(int idx); void _update_cursor_transform(); void _update_cursor_instance(); - void _update_clip(); void _update_theme(); void _text_changed(const String &p_text); @@ -236,8 +225,7 @@ public: EditorPlugin::AfterGUIInput forward_spatial_input_event(Camera3D *p_camera, const Ref<InputEvent> &p_event); void edit(GridMap *p_gridmap); - GridMapEditor() {} - GridMapEditor(EditorNode *p_editor); + GridMapEditor(); ~GridMapEditor(); }; @@ -245,7 +233,6 @@ class GridMapEditorPlugin : public EditorPlugin { GDCLASS(GridMapEditorPlugin, EditorPlugin); GridMapEditor *grid_map_editor; - EditorNode *editor; protected: void _notification(int p_what); @@ -258,7 +245,7 @@ public: virtual bool handles(Object *p_object) const override; virtual void make_visible(bool p_visible) override; - GridMapEditorPlugin(EditorNode *p_node); + GridMapEditorPlugin(); ~GridMapEditorPlugin(); }; diff --git a/modules/lightmapper_rd/lightmapper_rd.cpp b/modules/lightmapper_rd/lightmapper_rd.cpp index 11715040c2..68b3a41b9a 100644 --- a/modules/lightmapper_rd/lightmapper_rd.cpp +++ b/modules/lightmapper_rd/lightmapper_rd.cpp @@ -618,14 +618,14 @@ LightmapperRD::BakeError LightmapperRD::_dilate(RenderingDevice *rd, Ref<RDShade RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 0; - u.ids.push_back(dest_light_tex); + u.append_id(dest_light_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 1; - u.ids.push_back(source_light_tex); + u.append_id(source_light_tex); uniforms.push_back(u); } } @@ -856,70 +856,70 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 1; - u.ids.push_back(vertex_buffer); + u.append_id(vertex_buffer); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 2; - u.ids.push_back(triangle_buffer); + u.append_id(triangle_buffer); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 3; - u.ids.push_back(triangle_cell_indices_buffer); + u.append_id(triangle_cell_indices_buffer); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 4; - u.ids.push_back(lights_buffer); + u.append_id(lights_buffer); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 5; - u.ids.push_back(seams_buffer); + u.append_id(seams_buffer); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 6; - u.ids.push_back(probe_positions_buffer); + u.append_id(probe_positions_buffer); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 7; - u.ids.push_back(grid_texture); + u.append_id(grid_texture); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 8; - u.ids.push_back(albedo_array_tex); + u.append_id(albedo_array_tex); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 9; - u.ids.push_back(emission_array_tex); + u.append_id(emission_array_tex); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_SAMPLER; u.binding = 10; - u.ids.push_back(sampler); + u.append_id(sampler); base_uniforms.push_back(u); } } @@ -1057,14 +1057,14 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 0; - u.ids.push_back(position_tex); + u.append_id(position_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 1; - u.ids.push_back(unocclude_tex); //will be unused + u.append_id(unocclude_tex); //will be unused uniforms.push_back(u); } } @@ -1097,42 +1097,42 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 0; - u.ids.push_back(light_source_tex); + u.append_id(light_source_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 1; - u.ids.push_back(light_dest_tex); //will be unused + u.append_id(light_dest_tex); //will be unused uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 2; - u.ids.push_back(position_tex); + u.append_id(position_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 3; - u.ids.push_back(normal_tex); + u.append_id(normal_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 4; - u.ids.push_back(light_accum_tex); + u.append_id(light_accum_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 5; - u.ids.push_back(light_primary_dynamic_tex); + u.append_id(light_primary_dynamic_tex); uniforms.push_back(u); } } @@ -1176,57 +1176,57 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 0; - u.ids.push_back(light_dest_tex); + u.append_id(light_dest_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 1; - u.ids.push_back(light_source_tex); + u.append_id(light_source_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 2; - u.ids.push_back(position_tex); + u.append_id(position_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 3; - u.ids.push_back(normal_tex); + u.append_id(normal_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 4; - u.ids.push_back(light_accum_tex); + u.append_id(light_accum_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 5; - u.ids.push_back(unocclude_tex); //reuse unocclude tex + u.append_id(unocclude_tex); //reuse unocclude tex uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 6; - u.ids.push_back(light_environment_tex); + u.append_id(light_environment_tex); uniforms.push_back(u); } } RID secondary_uniform_set[2]; secondary_uniform_set[0] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1); - uniforms.write[0].ids.write[0] = light_source_tex; - uniforms.write[1].ids.write[0] = light_dest_tex; + uniforms.write[0].set_id(0, light_source_tex); + uniforms.write[1].set_id(0, light_dest_tex); secondary_uniform_set[1] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1); switch (p_quality) { @@ -1244,7 +1244,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d } break; } - push_constant.ray_count = CLAMP(push_constant.ray_count, 16, 8192); + push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u); int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size"))); int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass"); @@ -1332,28 +1332,28 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 0; - u.ids.push_back(light_probe_buffer); + u.append_id(light_probe_buffer); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 1; - u.ids.push_back(light_dest_tex); + u.append_id(light_dest_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 2; - u.ids.push_back(light_primary_dynamic_tex); + u.append_id(light_primary_dynamic_tex); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 3; - u.ids.push_back(light_environment_tex); + u.append_id(light_environment_tex); uniforms.push_back(u); } } @@ -1375,7 +1375,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d } push_constant.atlas_size[0] = probe_positions.size(); - push_constant.ray_count = CLAMP(push_constant.ray_count, 16, 8192); + push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u); int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass"); int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1; @@ -1531,7 +1531,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 0; - u.ids.push_back(light_accum_tex2); + u.append_id(light_accum_tex2); uniforms.push_back(u); } } diff --git a/modules/lightmapper_rd/lm_blendseams.glsl b/modules/lightmapper_rd/lm_blendseams.glsl index 374c48082e..70164e27c4 100644 --- a/modules/lightmapper_rd/lm_blendseams.glsl +++ b/modules/lightmapper_rd/lm_blendseams.glsl @@ -11,7 +11,7 @@ triangles = "#define MODE_TRIANGLES"; #include "lm_common_inc.glsl" -layout(push_constant, binding = 0, std430) uniform Params { +layout(push_constant, std430) uniform Params { uint base_index; uint slice; vec2 uv_offset; @@ -78,7 +78,7 @@ void main() { #include "lm_common_inc.glsl" -layout(push_constant, binding = 0, std430) uniform Params { +layout(push_constant, std430) uniform Params { uint base_index; uint slice; vec2 uv_offset; diff --git a/modules/lightmapper_rd/lm_compute.glsl b/modules/lightmapper_rd/lm_compute.glsl index 7bb8346c47..0b6b72a310 100644 --- a/modules/lightmapper_rd/lm_compute.glsl +++ b/modules/lightmapper_rd/lm_compute.glsl @@ -70,7 +70,7 @@ layout(rgba16f, set = 1, binding = 0) uniform restrict writeonly image2DArray de layout(set = 1, binding = 1) uniform texture2DArray source_light; #endif -layout(push_constant, binding = 0, std430) uniform Params { +layout(push_constant, std430) uniform Params { ivec2 atlas_size; // x used for light probe mode total probes uint ray_count; uint ray_to; diff --git a/modules/lightmapper_rd/lm_raster.glsl b/modules/lightmapper_rd/lm_raster.glsl index a86968a4f3..875c3e967a 100644 --- a/modules/lightmapper_rd/lm_raster.glsl +++ b/modules/lightmapper_rd/lm_raster.glsl @@ -14,7 +14,7 @@ layout(location = 4) flat out uvec3 vertex_indices; layout(location = 5) flat out vec3 face_normal; layout(location = 6) flat out uint fragment_action; -layout(push_constant, binding = 0, std430) uniform Params { +layout(push_constant, std430) uniform Params { vec2 atlas_size; vec2 uv_offset; vec3 to_cell_size; @@ -69,7 +69,7 @@ void main() { #include "lm_common_inc.glsl" -layout(push_constant, binding = 0, std430) uniform Params { +layout(push_constant, std430) uniform Params { vec2 atlas_size; vec2 uv_offset; vec3 to_cell_size; diff --git a/modules/minimp3/audio_stream_mp3.cpp b/modules/minimp3/audio_stream_mp3.cpp index 63fec6db8c..b5b51403f7 100644 --- a/modules/minimp3/audio_stream_mp3.cpp +++ b/modules/minimp3/audio_stream_mp3.cpp @@ -83,7 +83,7 @@ void AudioStreamPlaybackMP3::start(float p_from_pos) { active = true; seek(p_from_pos); loops = 0; - _begin_resample(); + begin_resample(); } void AudioStreamPlaybackMP3::stop() { diff --git a/modules/minimp3/doc_classes/AudioStreamMP3.xml b/modules/minimp3/doc_classes/AudioStreamMP3.xml index e4f56614ee..f5f7d3ef17 100644 --- a/modules/minimp3/doc_classes/AudioStreamMP3.xml +++ b/modules/minimp3/doc_classes/AudioStreamMP3.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="AudioStreamMP3" inherits="AudioStream" version="4.0"> +<class name="AudioStreamMP3" inherits="AudioStream" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> MP3 audio stream driver. </brief_description> diff --git a/modules/mobile_vr/doc_classes/MobileVRInterface.xml b/modules/mobile_vr/doc_classes/MobileVRInterface.xml index df099f2c98..db186079b0 100644 --- a/modules/mobile_vr/doc_classes/MobileVRInterface.xml +++ b/modules/mobile_vr/doc_classes/MobileVRInterface.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="MobileVRInterface" inherits="XRInterface" version="4.0"> +<class name="MobileVRInterface" inherits="XRInterface" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Generic mobile VR implementation. </brief_description> diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 085ab9a467..7ed0422236 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -527,10 +527,10 @@ String CSharpLanguage::make_function(const String &, const String &, const Packe String CSharpLanguage::_get_indentation() const { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { - bool use_space_indentation = EDITOR_DEF("text_editor/behavior/indent/type", 0); + bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type"); if (use_space_indentation) { - int indent_size = EDITOR_DEF("text_editor/behavior/indent/size", 4); + int indent_size = EDITOR_GET("text_editor/behavior/indent/size"); String space_indent = ""; for (int i = 0; i < indent_size; i++) { @@ -1893,7 +1893,7 @@ bool CSharpInstance::has_method(const StringName &p_method) const { return false; } -Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { +Variant CSharpInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { ERR_FAIL_COND_V(!script.is_valid(), Variant()); GD_MONO_SCOPE_THREAD_ATTACH; @@ -2908,7 +2908,7 @@ int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, Manage } #endif -Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { +Variant CSharpScript::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { if (unlikely(GDMono::get_singleton() == nullptr)) { // Probably not the best error but eh. r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; @@ -2936,7 +2936,7 @@ Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, i } // No static method found. Try regular instance calls - return Script::call(p_method, p_args, p_argcount, r_error); + return Script::callp(p_method, p_args, p_argcount, r_error); } void CSharpScript::_resource_path_changed() { diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index 2de923c125..3b97d2acc4 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -53,8 +53,9 @@ class CSharpLanguage; #ifdef NO_SAFE_CAST template <typename TScriptInstance, typename TScriptLanguage> TScriptInstance *cast_script_instance(ScriptInstance *p_inst) { - if (!p_inst) + if (!p_inst) { return nullptr; + } return p_inst->get_language() == TScriptLanguage::get_singleton() ? static_cast<TScriptInstance *>(p_inst) : nullptr; } #else @@ -183,7 +184,7 @@ private: protected: static void _bind_methods(); - Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override; + Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override; void _resource_path_changed() override; bool _get(const StringName &p_name, Variant &r_ret) const; bool _set(const StringName &p_name, const Variant &p_value); @@ -294,7 +295,7 @@ public: void get_method_list(List<MethodInfo> *p_list) const override; bool has_method(const StringName &p_method) const override; - Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override; + Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override; void mono_object_disposed(MonoObject *p_obj); diff --git a/modules/mono/doc_classes/CSharpScript.xml b/modules/mono/doc_classes/CSharpScript.xml index 14c62b4bb0..f8293fb107 100644 --- a/modules/mono/doc_classes/CSharpScript.xml +++ b/modules/mono/doc_classes/CSharpScript.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSharpScript" inherits="Script" version="4.0"> +<class name="CSharpScript" inherits="Script" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A script implemented in the C# programming language (Mono-enabled builds only). </brief_description> diff --git a/modules/mono/doc_classes/GodotSharp.xml b/modules/mono/doc_classes/GodotSharp.xml index a148072245..9de6b48e9e 100644 --- a/modules/mono/doc_classes/GodotSharp.xml +++ b/modules/mono/doc_classes/GodotSharp.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GodotSharp" inherits="Object" version="4.0"> +<class name="GodotSharp" inherits="Object" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Bridge between Godot and the Mono runtime (Mono-enabled builds only). </brief_description> diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs index 56fca6b5cb..bfc807c01a 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs @@ -350,7 +350,7 @@ namespace GodotTools.Build if (_issuesListContextMenu.ItemCount > 0) { - _issuesListContextMenu.Position = (Vector2i)(_issuesList.RectGlobalPosition + atPosition); + _issuesListContextMenu.Position = (Vector2i)(_issuesList.GlobalPosition + atPosition); _issuesListContextMenu.Popup(); } } diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs index 2dbc78ab77..9e8f7ef1b1 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs @@ -126,7 +126,7 @@ namespace GodotTools.Build { base._Ready(); - RectMinSize = new Vector2(0, 228) * EditorScale; + MinimumSize = new Vector2(0, 228) * EditorScale; SizeFlagsVertical = (int)SizeFlags.ExpandFill; var toolBarHBox = new HBoxContainer { SizeFlagsHorizontal = (int)SizeFlags.ExpandFill }; diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs index ed758cc137..e2f4d2f5fd 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs @@ -107,7 +107,7 @@ namespace GodotTools.Export ExecuteCompiler(FindCrossCompiler(compilerDirPath), compilerArgs, bclDir); // The Godot exporter expects us to pass the abi in the tags parameter - exporter.AddSharedObject(soFilePath, tags: new[] { abi }); + exporter.AddSharedObject(soFilePath, tags: new[] { abi }, ""); } } } @@ -134,7 +134,7 @@ namespace GodotTools.Export if (platform == OS.Platforms.MacOS) { - exporter.AddSharedObject(tempOutputFilePath, tags: null); + exporter.AddSharedObject(tempOutputFilePath, tags: null, ""); } else { diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index 1de41821f9..272283432d 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -278,11 +278,12 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf } else if (code_tag) { xml_output.append("["); pos = brk_pos + 1; - } else if (tag.begins_with("method ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ")) { - String link_target = tag.substr(tag.find(" ") + 1, tag.length()); - String link_tag = tag.substr(0, tag.find(" ")); + } else if (tag.begins_with("method ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ") || tag.begins_with("theme_item ")) { + const int tag_end = tag.find(" "); + const String link_tag = tag.substr(0, tag_end); + const String link_target = tag.substr(tag_end + 1, tag.length()).lstrip(" "); - Vector<String> link_target_parts = link_target.split("."); + const Vector<String> link_target_parts = link_target.split("."); if (link_target_parts.size() <= 0 || link_target_parts.size() > 2) { ERR_PRINT("Invalid reference format: '" + tag + "'."); @@ -310,175 +311,18 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf } if (link_tag == "method") { - if (!target_itype || !target_itype->is_object_type) { - if (OS::get_singleton()->is_stdout_verbose()) { - if (target_itype) { - OS::get_singleton()->print("Cannot resolve method reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data()); - } else { - OS::get_singleton()->print("Cannot resolve type from method reference in documentation: %s\n", link_target.utf8().get_data()); - } - } - - // TODO Map what we can - xml_output.append("<c>"); - xml_output.append(link_target); - xml_output.append("</c>"); - } else { - const MethodInterface *target_imethod = target_itype->find_method_by_name(target_cname); - - if (target_imethod) { - xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); - xml_output.append(target_itype->proxy_name); - xml_output.append("."); - xml_output.append(target_imethod->proxy_name); - xml_output.append("\"/>"); - } - } + _append_xml_method(xml_output, target_itype, target_cname, link_target, link_target_parts); } else if (link_tag == "member") { - if (!target_itype || !target_itype->is_object_type) { - if (OS::get_singleton()->is_stdout_verbose()) { - if (target_itype) { - OS::get_singleton()->print("Cannot resolve member reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data()); - } else { - OS::get_singleton()->print("Cannot resolve type from member reference in documentation: %s\n", link_target.utf8().get_data()); - } - } - - // TODO Map what we can - xml_output.append("<c>"); - xml_output.append(link_target); - xml_output.append("</c>"); - } else { - const PropertyInterface *target_iprop = target_itype->find_property_by_name(target_cname); - - if (target_iprop) { - xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); - xml_output.append(target_itype->proxy_name); - xml_output.append("."); - xml_output.append(target_iprop->proxy_name); - xml_output.append("\"/>"); - } - } + _append_xml_member(xml_output, target_itype, target_cname, link_target, link_target_parts); } else if (link_tag == "signal") { - // We do not declare signals in any way in C#, so there is nothing to reference - xml_output.append("<c>"); - xml_output.append(link_target); - xml_output.append("</c>"); + _append_xml_signal(xml_output, target_itype, target_cname, link_target, link_target_parts); } else if (link_tag == "enum") { - StringName search_cname = !target_itype ? target_cname : StringName(target_itype->name + "." + (String)target_cname); - - const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(search_cname); - - if (!enum_match && search_cname != target_cname) { - enum_match = enum_types.find(target_cname); - } - - if (enum_match) { - const TypeInterface &target_enum_itype = enum_match->value(); - - xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); - xml_output.append(target_enum_itype.proxy_name); // Includes nesting class if any - xml_output.append("\"/>"); - } else { - ERR_PRINT("Cannot resolve enum reference in documentation: '" + link_target + "'."); - - xml_output.append("<c>"); - xml_output.append(link_target); - xml_output.append("</c>"); - } + _append_xml_enum(xml_output, target_itype, target_cname, link_target, link_target_parts); } else if (link_tag == "constant") { - if (!target_itype || !target_itype->is_object_type) { - if (OS::get_singleton()->is_stdout_verbose()) { - if (target_itype) { - OS::get_singleton()->print("Cannot resolve constant reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data()); - } else { - OS::get_singleton()->print("Cannot resolve type from constant reference in documentation: %s\n", link_target.utf8().get_data()); - } - } - - // TODO Map what we can - xml_output.append("<c>"); - xml_output.append(link_target); - xml_output.append("</c>"); - } else if (!target_itype && target_cname == name_cache.type_at_GlobalScope) { - String target_name = (String)target_cname; - - // Try to find as a global constant - const ConstantInterface *target_iconst = find_constant_by_name(target_name, global_constants); - - if (target_iconst) { - // Found global constant - xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "." BINDINGS_GLOBAL_SCOPE_CLASS "."); - xml_output.append(target_iconst->proxy_name); - xml_output.append("\"/>"); - } else { - // Try to find as global enum constant - const EnumInterface *target_ienum = nullptr; - - for (const EnumInterface &ienum : global_enums) { - target_ienum = &ienum; - target_iconst = find_constant_by_name(target_name, target_ienum->constants); - if (target_iconst) { - break; - } - } - - if (target_iconst) { - xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); - xml_output.append(target_ienum->cname); - xml_output.append("."); - xml_output.append(target_iconst->proxy_name); - xml_output.append("\"/>"); - } else { - ERR_PRINT("Cannot resolve global constant reference in documentation: '" + link_target + "'."); - - xml_output.append("<c>"); - xml_output.append(link_target); - xml_output.append("</c>"); - } - } - } else { - String target_name = (String)target_cname; - - // Try to find the constant in the current class - const ConstantInterface *target_iconst = find_constant_by_name(target_name, target_itype->constants); - - if (target_iconst) { - // Found constant in current class - xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); - xml_output.append(target_itype->proxy_name); - xml_output.append("."); - xml_output.append(target_iconst->proxy_name); - xml_output.append("\"/>"); - } else { - // Try to find as enum constant in the current class - const EnumInterface *target_ienum = nullptr; - - for (const EnumInterface &ienum : target_itype->enums) { - target_ienum = &ienum; - target_iconst = find_constant_by_name(target_name, target_ienum->constants); - if (target_iconst) { - break; - } - } - - if (target_iconst) { - xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); - xml_output.append(target_itype->proxy_name); - xml_output.append("."); - xml_output.append(target_ienum->cname); - xml_output.append("."); - xml_output.append(target_iconst->proxy_name); - xml_output.append("\"/>"); - } else { - ERR_PRINT("Cannot resolve constant reference in documentation: '" + link_target + "'."); - - xml_output.append("<c>"); - xml_output.append(link_target); - xml_output.append("</c>"); - } - } - } + _append_xml_constant(xml_output, target_itype, target_cname, link_target, link_target_parts); + } else if (link_tag == "theme_item") { + // We do not declare theme_items in any way in C#, so there is nothing to reference + _append_xml_undeclared(xml_output, link_target); } pos = brk_end + 1; @@ -643,6 +487,240 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf return xml_output.as_string(); } +void BindingsGenerator::_append_xml_method(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) { + if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) { + if (OS::get_singleton()->is_stdout_verbose()) { + OS::get_singleton()->print("Cannot resolve @GlobalScope method reference in documentation: %s\n", p_link_target.utf8().get_data()); + } + + // TODO Map what we can + _append_xml_undeclared(p_xml_output, p_link_target); + } else if (!p_target_itype || !p_target_itype->is_object_type) { + if (OS::get_singleton()->is_stdout_verbose()) { + if (p_target_itype) { + OS::get_singleton()->print("Cannot resolve method reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data()); + } else { + OS::get_singleton()->print("Cannot resolve type from method reference in documentation: %s\n", p_link_target.utf8().get_data()); + } + } + + // TODO Map what we can + _append_xml_undeclared(p_xml_output, p_link_target); + } else { + if (p_target_cname == "_init") { + // The _init method is not declared in C#, reference the constructor instead + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(p_target_itype->proxy_name); + p_xml_output.append("."); + p_xml_output.append(p_target_itype->proxy_name); + p_xml_output.append("()\"/>"); + } else { + const MethodInterface *target_imethod = p_target_itype->find_method_by_name(p_target_cname); + + if (target_imethod) { + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(p_target_itype->proxy_name); + p_xml_output.append("."); + p_xml_output.append(target_imethod->proxy_name); + p_xml_output.append("\"/>"); + } else { + ERR_PRINT("Cannot resolve method reference in documentation: '" + p_link_target + "'."); + _append_xml_undeclared(p_xml_output, p_link_target); + } + } + } +} + +void BindingsGenerator::_append_xml_member(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) { + if (p_link_target.find("/") >= 0) { + // Properties with '/' (slash) in the name are not declared in C#, so there is nothing to reference. + _append_xml_undeclared(p_xml_output, p_link_target); + } else if (!p_target_itype || !p_target_itype->is_object_type) { + if (OS::get_singleton()->is_stdout_verbose()) { + if (p_target_itype) { + OS::get_singleton()->print("Cannot resolve member reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data()); + } else { + OS::get_singleton()->print("Cannot resolve type from member reference in documentation: %s\n", p_link_target.utf8().get_data()); + } + } + + // TODO Map what we can + _append_xml_undeclared(p_xml_output, p_link_target); + } else { + const TypeInterface *current_itype = p_target_itype; + const PropertyInterface *target_iprop = nullptr; + + while (target_iprop == nullptr && current_itype != nullptr) { + target_iprop = current_itype->find_property_by_name(p_target_cname); + if (target_iprop == nullptr) { + current_itype = _get_type_or_null(TypeReference(current_itype->base_name)); + } + } + + if (target_iprop) { + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(current_itype->proxy_name); + p_xml_output.append("."); + p_xml_output.append(target_iprop->proxy_name); + p_xml_output.append("\"/>"); + } else { + ERR_PRINT("Cannot resolve member reference in documentation: '" + p_link_target + "'."); + _append_xml_undeclared(p_xml_output, p_link_target); + } + } +} + +void BindingsGenerator::_append_xml_signal(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) { + if (!p_target_itype || !p_target_itype->is_object_type) { + if (OS::get_singleton()->is_stdout_verbose()) { + if (p_target_itype) { + OS::get_singleton()->print("Cannot resolve signal reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data()); + } else { + OS::get_singleton()->print("Cannot resolve type from signal reference in documentation: %s\n", p_link_target.utf8().get_data()); + } + } + + // TODO Map what we can + _append_xml_undeclared(p_xml_output, p_link_target); + } else { + const SignalInterface *target_isignal = p_target_itype->find_signal_by_name(p_target_cname); + + if (target_isignal) { + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(p_target_itype->proxy_name); + p_xml_output.append("."); + p_xml_output.append(target_isignal->proxy_name); + p_xml_output.append("\"/>"); + } else { + ERR_PRINT("Cannot resolve signal reference in documentation: '" + p_link_target + "'."); + _append_xml_undeclared(p_xml_output, p_link_target); + } + } +} + +void BindingsGenerator::_append_xml_enum(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) { + const StringName search_cname = !p_target_itype ? p_target_cname : StringName(p_target_itype->name + "." + (String)p_target_cname); + + const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(search_cname); + + if (!enum_match && search_cname != p_target_cname) { + enum_match = enum_types.find(p_target_cname); + } + + if (enum_match) { + const TypeInterface &target_enum_itype = enum_match->value(); + + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(target_enum_itype.proxy_name); // Includes nesting class if any + p_xml_output.append("\"/>"); + } else { + ERR_PRINT("Cannot resolve enum reference in documentation: '" + p_link_target + "'."); + _append_xml_undeclared(p_xml_output, p_link_target); + } +} + +void BindingsGenerator::_append_xml_constant(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) { + if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) { + _append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target); + } else if (!p_target_itype || !p_target_itype->is_object_type) { + // Search in @GlobalScope as a last resort if no class was specified + if (p_link_target_parts.size() == 1) { + _append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target); + return; + } + + if (OS::get_singleton()->is_stdout_verbose()) { + if (p_target_itype) { + OS::get_singleton()->print("Cannot resolve constant reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data()); + } else { + OS::get_singleton()->print("Cannot resolve type from constant reference in documentation: %s\n", p_link_target.utf8().get_data()); + } + } + + // TODO Map what we can + _append_xml_undeclared(p_xml_output, p_link_target); + } else { + // Try to find the constant in the current class + const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, p_target_itype->constants); + + if (target_iconst) { + // Found constant in current class + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(p_target_itype->proxy_name); + p_xml_output.append("."); + p_xml_output.append(target_iconst->proxy_name); + p_xml_output.append("\"/>"); + } else { + // Try to find as enum constant in the current class + const EnumInterface *target_ienum = nullptr; + + for (const EnumInterface &ienum : p_target_itype->enums) { + target_ienum = &ienum; + target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants); + if (target_iconst) { + break; + } + } + + if (target_iconst) { + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(p_target_itype->proxy_name); + p_xml_output.append("."); + p_xml_output.append(target_ienum->cname); + p_xml_output.append("."); + p_xml_output.append(target_iconst->proxy_name); + p_xml_output.append("\"/>"); + } else if (p_link_target_parts.size() == 1) { + // Also search in @GlobalScope as a last resort if no class was specified + _append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target); + } else { + ERR_PRINT("Cannot resolve constant reference in documentation: '" + p_link_target + "'."); + _append_xml_undeclared(p_xml_output, p_link_target); + } + } + } +} + +void BindingsGenerator::_append_xml_constant_in_global_scope(StringBuilder &p_xml_output, const String &p_target_cname, const String &p_link_target) { + // Try to find as a global constant + const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, global_constants); + + if (target_iconst) { + // Found global constant + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "." BINDINGS_GLOBAL_SCOPE_CLASS "."); + p_xml_output.append(target_iconst->proxy_name); + p_xml_output.append("\"/>"); + } else { + // Try to find as global enum constant + const EnumInterface *target_ienum = nullptr; + + for (const EnumInterface &ienum : global_enums) { + target_ienum = &ienum; + target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants); + if (target_iconst) { + break; + } + } + + if (target_iconst) { + p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "."); + p_xml_output.append(target_ienum->cname); + p_xml_output.append("."); + p_xml_output.append(target_iconst->proxy_name); + p_xml_output.append("\"/>"); + } else { + ERR_PRINT("Cannot resolve global constant reference in documentation: '" + p_link_target + "'."); + _append_xml_undeclared(p_xml_output, p_link_target); + } + } +} + +void BindingsGenerator::_append_xml_undeclared(StringBuilder &p_xml_output, const String &p_link_target) { + p_xml_output.append("<c>"); + p_xml_output.append(p_link_target); + p_xml_output.append("</c>"); +} + int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) { CRASH_COND(p_ienum.constants.is_empty()); @@ -2122,8 +2200,9 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { } output.append("#ifdef TOOLS_ENABLED\n"); - for (const InternalCall &internal_call : editor_custom_icalls) + for (const InternalCall &internal_call : editor_custom_icalls) { ADD_INTERNAL_CALL_REGISTRATION(internal_call); + } output.append("#endif // TOOLS_ENABLED\n"); for (const InternalCall &internal_call : method_icalls) { diff --git a/modules/mono/editor/bindings_generator.h b/modules/mono/editor/bindings_generator.h index 2e6ce3a952..f601ffde2b 100644 --- a/modules/mono/editor/bindings_generator.h +++ b/modules/mono/editor/bindings_generator.h @@ -366,6 +366,16 @@ class BindingsGenerator { return nullptr; } + const MethodInterface *find_method_by_proxy_name(const String &p_proxy_name) const { + for (const MethodInterface &E : methods) { + if (E.proxy_name == p_proxy_name) { + return &E; + } + } + + return nullptr; + } + const PropertyInterface *find_property_by_name(const StringName &p_cname) const { for (const PropertyInterface &E : properties) { if (E.cname == p_cname) { @@ -386,8 +396,18 @@ class BindingsGenerator { return nullptr; } - const MethodInterface *find_method_by_proxy_name(const String &p_proxy_name) const { - for (const MethodInterface &E : methods) { + const SignalInterface *find_signal_by_name(const StringName &p_cname) const { + for (const SignalInterface &E : signals_) { + if (E.cname == p_cname) { + return &E; + } + } + + return nullptr; + } + + const SignalInterface *find_signal_by_proxy_name(const String &p_proxy_name) const { + for (const SignalInterface &E : signals_) { if (E.proxy_name == p_proxy_name) { return &E; } @@ -638,6 +658,14 @@ class BindingsGenerator { String bbcode_to_xml(const String &p_bbcode, const TypeInterface *p_itype); + void _append_xml_method(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts); + void _append_xml_member(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts); + void _append_xml_signal(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts); + void _append_xml_enum(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts); + void _append_xml_constant(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts); + void _append_xml_constant_in_global_scope(StringBuilder &p_xml_output, const String &p_target_cname, const String &p_link_target); + void _append_xml_undeclared(StringBuilder &p_xml_output, const String &p_link_target); + int _determine_enum_prefix(const EnumInterface &p_ienum); void _apply_prefix_to_enum_constants(EnumInterface &p_ienum, int p_prefix_length); diff --git a/modules/mono/editor/code_completion.cpp b/modules/mono/editor/code_completion.cpp index 095fd831a3..3a41b3f6f5 100644 --- a/modules/mono/editor/code_completion.cpp +++ b/modules/mono/editor/code_completion.cpp @@ -120,7 +120,7 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr } break; case CompletionKind::NODE_PATHS: { { - // AutoLoads + // Autoloads. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list(); for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) { diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp index 3c02ea0e8e..f7f710f3f1 100644 --- a/modules/mono/editor/editor_internal_calls.cpp +++ b/modules/mono/editor/editor_internal_calls.cpp @@ -34,6 +34,7 @@ #include <unistd.h> // access #endif +#include "core/config/project_settings.h" #include "core/os/os.h" #include "core/version.h" #include "editor/debugger/editor_debugger_node.h" diff --git a/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs b/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs index b0ded3133f..2ca81ab7cd 100644 --- a/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs +++ b/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs @@ -13,29 +13,29 @@ public partial class _CLASS_ : _BASE_ public override void _PhysicsProcess(float delta) { - Vector2 motionVelocity = MotionVelocity; + Vector2 velocity = Velocity; // Add the gravity. if (!IsOnFloor()) - motionVelocity.y += gravity * delta; + velocity.y += gravity * delta; // Handle Jump. if (Input.IsActionJustPressed("ui_accept") && IsOnFloor()) - motionVelocity.y = JumpVelocity; + velocity.y = JumpVelocity; // Get the input direction and handle the movement/deceleration. // As good practice, you should replace UI actions with custom gameplay actions. Vector2 direction = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down"); if (direction != Vector2.Zero) { - motionVelocity.x = direction.x * Speed; + velocity.x = direction.x * Speed; } else { - motionVelocity.x = Mathf.MoveToward(MotionVelocity.x, 0, Speed); + velocity.x = Mathf.MoveToward(Velocity.x, 0, Speed); } - MotionVelocity = motionVelocity; + Velocity = velocity; MoveAndSlide(); } } diff --git a/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs b/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs index d8c2f67ac8..a6935fe497 100644 --- a/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs +++ b/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs @@ -13,15 +13,15 @@ public partial class _CLASS_ : _BASE_ public override void _PhysicsProcess(float delta) { - Vector3 motionVelocity = MotionVelocity; + Vector3 velocity = Velocity; // Add the gravity. if (!IsOnFloor()) - motionVelocity.y -= gravity * delta; + velocity.y -= gravity * delta; // Handle Jump. if (Input.IsActionJustPressed("ui_accept") && IsOnFloor()) - motionVelocity.y = JumpVelocity; + velocity.y = JumpVelocity; // Get the input direction and handle the movement/deceleration. // As good practice, you should replace UI actions with custom gameplay actions. @@ -29,16 +29,16 @@ public partial class _CLASS_ : _BASE_ Vector3 direction = Transform.basis.Xform(new Vector3(inputDir.x, 0, inputDir.y)).Normalized(); if (direction != Vector3.Zero) { - motionVelocity.x = direction.x * Speed; - motionVelocity.z = direction.z * Speed; + velocity.x = direction.x * Speed; + velocity.z = direction.z * Speed; } else { - motionVelocity.x = Mathf.MoveToward(MotionVelocity.x, 0, Speed); - motionVelocity.z = Mathf.MoveToward(MotionVelocity.z, 0, Speed); + velocity.x = Mathf.MoveToward(Velocity.x, 0, Speed); + velocity.z = Mathf.MoveToward(Velocity.z, 0, Speed); } - MotionVelocity = motionVelocity; + Velocity = velocity; MoveAndSlide(); } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs index bfe9600084..ce213da6a7 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs @@ -180,6 +180,24 @@ namespace Godot } /// <summary> + /// Cubic interpolates between two values by a normalized value with pre and post values. + /// </summary> + /// <param name="from">The start value for interpolation.</param> + /// <param name="to">The destination value for interpolation.</param> + /// <param name="pre">The value which before "from" value for interpolation.</param> + /// <param name="post">The value which after "to" value for interpolation.</param> + /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> + /// <returns>The resulting value of the interpolation.</returns> + public static real_t CubicInterpolate(real_t from, real_t to, real_t pre, real_t post, real_t weight) + { + return 0.5f * + ((from * 2.0f) + + (-pre + to) * weight + + (2.0f * pre - 5.0f * from + 4.0f * to - post) * (weight * weight) + + (-pre + 3.0f * from - 3.0f * to + post) * (weight * weight * weight)); + } + + /// <summary> /// Converts an angle expressed in degrees to radians. /// </summary> /// <param name="deg">An angle expressed in degrees.</param> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs index fa7838633c..d4b623b2ea 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs @@ -81,6 +81,15 @@ namespace Godot } } + /// <summary> + /// Helper method for deconstruction into a tuple. + /// </summary> + public void Deconstruct(out real_t x, out real_t y) + { + x = this.x; + y = this.y; + } + internal void Normalize() { real_t lengthsq = LengthSquared(); @@ -204,20 +213,10 @@ namespace Godot /// <returns>The interpolated vector.</returns> public Vector2 CubicInterpolate(Vector2 b, Vector2 preA, Vector2 postB, real_t weight) { - Vector2 p0 = preA; - Vector2 p1 = this; - Vector2 p2 = b; - Vector2 p3 = postB; - - real_t t = weight; - real_t t2 = t * t; - real_t t3 = t2 * t; - - return 0.5f * ( - (p1 * 2.0f) + - ((-p0 + p2) * t) + - (((2.0f * p0) - (5.0f * p1) + (4 * p2) - p3) * t2) + - ((-p0 + (3.0f * p1) - (3.0f * p2) + p3) * t3) + return new Vector2 + ( + Mathf.CubicInterpolate(x, b.x, preA.x, postB.x, weight), + Mathf.CubicInterpolate(y, b.y, preA.y, postB.y, weight) ); } @@ -512,8 +511,9 @@ namespace Godot /// Returns the result of the spherical linear interpolation between /// this vector and <paramref name="to"/> by amount <paramref name="weight"/>. /// - /// This method also handles interpolating the lengths if the input vectors have different lengths. - /// For the special case of one or both input vectors having zero length, this method behaves like [method lerp]. + /// This method also handles interpolating the lengths if the input vectors + /// have different lengths. For the special case of one or both input vectors + /// having zero length, this method behaves like <see cref="Lerp"/>. /// </summary> /// <param name="to">The destination vector for interpolation.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs index 9b51de5c8c..412a885daa 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs @@ -82,6 +82,15 @@ namespace Godot } /// <summary> + /// Helper method for deconstruction into a tuple. + /// </summary> + public void Deconstruct(out int x, out int y) + { + x = this.x; + y = this.y; + } + + /// <summary> /// Returns a new vector with all components in absolute values (i.e. positive). /// </summary> /// <returns>A vector with <see cref="Mathf.Abs(int)"/> called on each component.</returns> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs index 0faf13f8b7..eddfa76f10 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs @@ -96,6 +96,16 @@ namespace Godot } } + /// <summary> + /// Helper method for deconstruction into a tuple. + /// </summary> + public void Deconstruct(out real_t x, out real_t y, out real_t z) + { + x = this.x; + y = this.y; + z = this.z; + } + internal void Normalize() { real_t lengthsq = LengthSquared(); @@ -195,19 +205,11 @@ namespace Godot /// <returns>The interpolated vector.</returns> public Vector3 CubicInterpolate(Vector3 b, Vector3 preA, Vector3 postB, real_t weight) { - Vector3 p0 = preA; - Vector3 p1 = this; - Vector3 p2 = b; - Vector3 p3 = postB; - - real_t t = weight; - real_t t2 = t * t; - real_t t3 = t2 * t; - - return 0.5f * ( - (p1 * 2.0f) + ((-p0 + p2) * t) + - (((2.0f * p0) - (5.0f * p1) + (4f * p2) - p3) * t2) + - ((-p0 + (3.0f * p1) - (3.0f * p2) + p3) * t3) + return new Vector3 + ( + Mathf.CubicInterpolate(x, b.x, preA.x, postB.x, weight), + Mathf.CubicInterpolate(y, b.y, preA.y, postB.y, weight), + Mathf.CubicInterpolate(z, b.z, preA.z, postB.z, weight) ); } @@ -549,8 +551,9 @@ namespace Godot /// Returns the result of the spherical linear interpolation between /// this vector and <paramref name="to"/> by amount <paramref name="weight"/>. /// - /// This method also handles interpolating the lengths if the input vectors have different lengths. - /// For the special case of one or both input vectors having zero length, this method behaves like [method lerp]. + /// This method also handles interpolating the lengths if the input vectors + /// have different lengths. For the special case of one or both input vectors + /// having zero length, this method behaves like <see cref="Lerp"/>. /// </summary> /// <param name="to">The destination vector for interpolation.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs index eb06d2b87e..abfd2ae720 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs @@ -97,6 +97,16 @@ namespace Godot } /// <summary> + /// Helper method for deconstruction into a tuple. + /// </summary> + public void Deconstruct(out int x, out int y, out int z) + { + x = this.x; + y = this.y; + z = this.z; + } + + /// <summary> /// Returns a new vector with all components in absolute values (i.e. positive). /// </summary> /// <returns>A vector with <see cref="Mathf.Abs(int)"/> called on each component.</returns> diff --git a/modules/mono/glue/base_object_glue.cpp b/modules/mono/glue/base_object_glue.cpp index 8e7b125ed5..b5f2c98af5 100644 --- a/modules/mono/glue/base_object_glue.cpp +++ b/modules/mono/glue/base_object_glue.cpp @@ -199,7 +199,7 @@ MonoBoolean godot_icall_DynamicGodotObject_InvokeMember(Object *p_ptr, MonoStrin } Callable::CallError error; - Variant result = p_ptr->call(StringName(name), args.ptr(), argc, error); + Variant result = p_ptr->callp(StringName(name), args.ptr(), argc, error); *r_result = GDMonoMarshal::variant_to_mono_object(result); diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index c0cd18e29d..7c2cb2e260 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -36,7 +36,7 @@ #ifdef TOOLS_ENABLED #include "core/version.h" -#include "editor/editor_settings.h" +#include "editor/editor_paths.h" #endif #ifdef ANDROID_ENABLED diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index 6f542a67e7..424b74906f 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -52,10 +52,6 @@ #include "gd_mono_marshal.h" #include "gd_mono_utils.h" -#ifdef TOOLS_ENABLED -#include "main/main.h" -#endif - #ifdef ANDROID_ENABLED #include "android_mono_config.h" #include "support/android_support.h" @@ -143,7 +139,7 @@ void gd_mono_debug_init() { if (Engine::get_singleton()->is_editor_hint() || ProjectSettings::get_singleton()->get_resource_path().is_empty() || - Main::is_project_manager()) { + Engine::get_singleton()->is_project_manager_hint()) { if (da_args.size() == 0) { return; } @@ -155,8 +151,9 @@ void gd_mono_debug_init() { .utf8(); } #else - if (da_args.length() == 0) + if (da_args.length() == 0) { return; // Exported games don't use the project settings to setup the debugger agent + } #endif // Debugging enabled @@ -230,8 +227,9 @@ void GDMono::add_mono_shared_libs_dir_to_path() { path_value += mono_reg_info.bin_dir; } #else - if (DirAccess::exists(bundled_bin_dir)) + if (DirAccess::exists(bundled_bin_dir)) { path_value += bundled_bin_dir; + } #endif // TOOLS_ENABLED #else @@ -423,7 +421,7 @@ void GDMono::initialize_load_assemblies() { bool tool_assemblies_loaded = _load_tools_assemblies(); CRASH_COND_MSG(!tool_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies."); - if (Main::is_project_manager()) { + if (Engine::get_singleton()->is_project_manager_hint()) { return; } #endif @@ -645,9 +643,8 @@ bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const // Create destination directory if needed if (!DirAccess::exists(dst_dir)) { - DirAccess *da = DirAccess::create_for_path(dst_dir); + DirAccessRef da = DirAccess::create_for_path(dst_dir); Error err = da->make_dir_recursive(dst_dir); - memdelete(da); if (err != OK) { ERR_PRINT("Failed to create destination directory for the API assemblies. Error: " + itos(err) + "."); @@ -815,7 +812,7 @@ bool GDMono::_load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, c // 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() + String assembly_dir = !Engine::get_singleton()->is_project_manager_hint() ? GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) : GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); @@ -848,7 +845,7 @@ bool GDMono::_load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, // 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() + String assembly_dir = !Engine::get_singleton()->is_project_manager_hint() ? GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) : GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); @@ -932,7 +929,7 @@ void GDMono::_load_api_assemblies() { // this time update them from the prebuilt assemblies directory before trying to load them again. // 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."); + CRASH_COND_MSG(Engine::get_singleton()->is_project_manager_hint(), "Failed to load one of the prebuilt API assemblies."); // 1. Unload the scripts domain Error domain_unload_err = _unload_scripts_domain(); @@ -1273,8 +1270,9 @@ GDMono::~GDMono() { print_verbose("Mono: Finalizing scripts domain..."); - if (mono_domain_get() != root_domain) + if (mono_domain_get() != root_domain) { mono_domain_set(root_domain, true); + } finalizing_scripts_domain = true; diff --git a/modules/mono/mono_gd/support/android_support.cpp b/modules/mono/mono_gd/support/android_support.cpp index eb8bbab948..4797d5dae1 100644 --- a/modules/mono/mono_gd/support/android_support.cpp +++ b/modules/mono/mono_gd/support/android_support.cpp @@ -134,8 +134,9 @@ String determine_app_native_lib_dir() { } String get_app_native_lib_dir() { - if (app_native_lib_dir_cache.is_empty()) + if (app_native_lib_dir_cache.is_empty()) { app_native_lib_dir_cache = determine_app_native_lib_dir(); + } return app_native_lib_dir_cache; } @@ -144,10 +145,11 @@ int gd_mono_convert_dl_flags(int flags) { int lflags = flags & MONO_DL_LOCAL ? 0 : RTLD_GLOBAL; - if (flags & MONO_DL_LAZY) + if (flags & MONO_DL_LAZY) { lflags |= RTLD_LAZY; - else + } else { lflags |= RTLD_NOW; + } return lflags; } @@ -164,8 +166,9 @@ void *godot_dl_handle = nullptr; void *try_dlopen(const String &p_so_path, int p_flags) { if (!FileAccess::exists(p_so_path)) { - if (OS::get_singleton()->is_stdout_verbose()) + if (OS::get_singleton()->is_stdout_verbose()) { OS::get_singleton()->print("Cannot find shared library: '%s'\n", p_so_path.utf8().get_data()); + } return nullptr; } @@ -174,13 +177,15 @@ void *try_dlopen(const String &p_so_path, int p_flags) { void *handle = dlopen(p_so_path.utf8().get_data(), lflags); if (!handle) { - if (OS::get_singleton()->is_stdout_verbose()) + 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 nullptr; } - if (OS::get_singleton()->is_stdout_verbose()) + 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; } @@ -217,20 +222,23 @@ void *gd_mono_android_dlopen(const char *p_name, int p_flags, char **r_err, void 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) + 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) + if (sym_addr) { return sym_addr; + } } - if (r_err) + if (r_err) { *r_err = str_format_new("%s\n", dlerror()); + } return nullptr; } @@ -239,8 +247,9 @@ 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) + if (p_handle == mono_dl_handle) { mono_dl_handle = nullptr; + } return nullptr; } @@ -292,13 +301,15 @@ MonoBoolean _gd_mono_init_cert_store() { ScopedLocalRef<jobject> certStoreLocal(env, env->CallStaticObjectMethod(keyStoreClass, getInstance, androidCAStoreString.get())); - if (jni_exception_check(env)) + if (jni_exception_check(env)) { return 0; + } env->CallVoidMethod(certStoreLocal, load, nullptr); - if (jni_exception_check(env)) + if (jni_exception_check(env)) { return 0; + } certStore = env->NewGlobalRef(certStoreLocal); @@ -309,8 +320,9 @@ 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) + // if (certificate == null) { // return null; + // } // return certificate.getEncoded(); MonoError mono_error; @@ -340,8 +352,9 @@ MonoArray *_gd_mono_android_cert_store_lookup(MonoString *p_alias) { ScopedLocalRef<jobject> certificate(env, env->CallObjectMethod(certStore, getCertificate, js_alias.get())); - if (!certificate) + if (!certificate) { return nullptr; + } ScopedLocalRef<jbyteArray> encoded(env, (jbyteArray)env->CallObjectMethod(certificate, getEncoded)); jsize encodedLength = env->GetArrayLength(encoded); @@ -374,11 +387,13 @@ void initialize() { void cleanup() { // This is called after shutting down the Mono runtime - if (mono_dl_handle) + if (mono_dl_handle) { gd_mono_android_dlclose(mono_dl_handle, nullptr); + } - if (godot_dl_handle) + if (godot_dl_handle) { gd_mono_android_dlclose(godot_dl_handle, nullptr); + } JNIEnv *env = get_jni_env(); @@ -431,8 +446,9 @@ GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_up_state(const char // // NetworkInterface.getByName(p_ifname).isUp() - if (!r_is_up || !p_ifname || strlen(p_ifname) == 0) + if (!r_is_up || !p_ifname || strlen(p_ifname) == 0) { return 0; + } *r_is_up = 0; @@ -450,8 +466,9 @@ GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_up_state(const char ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname)); ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get())); - if (!networkInterface) + if (!networkInterface) { return 0; + } *r_is_up = (mono_bool)env->CallBooleanMethod(networkInterface, isUp); @@ -463,8 +480,9 @@ GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_supports_multicast( // // NetworkInterface.getByName(p_ifname).supportsMulticast() - if (!r_supports_multicast || !p_ifname || strlen(p_ifname) == 0) + if (!r_supports_multicast || !p_ifname || strlen(p_ifname) == 0) { return 0; + } *r_supports_multicast = 0; @@ -482,8 +500,9 @@ GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_supports_multicast( ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname)); ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get())); - if (!networkInterface) + if (!networkInterface) { return 0; + } *r_supports_multicast = (mono_bool)env->CallBooleanMethod(networkInterface, supportsMulticast); @@ -528,8 +547,9 @@ static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dn ScopedLocalRef<jobject> connectivityManager(env, env->CallObjectMethod(applicationContext, getSystemService, connectivityServiceString.get())); - if (!connectivityManager) + if (!connectivityManager) { return; + } ScopedLocalRef<jclass> connectivityManagerClass(env, env->FindClass("android/net/ConnectivityManager")); ERR_FAIL_NULL(connectivityManagerClass); @@ -539,8 +559,9 @@ static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dn ScopedLocalRef<jobject> activeNetwork(env, env->CallObjectMethod(connectivityManager, getActiveNetwork)); - if (!activeNetwork) + if (!activeNetwork) { return; + } jmethodID getLinkProperties = env->GetMethodID(connectivityManagerClass, "getLinkProperties", "(Landroid/net/Network;)Landroid/net/LinkProperties;"); @@ -548,8 +569,9 @@ static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dn ScopedLocalRef<jobject> linkProperties(env, env->CallObjectMethod(connectivityManager, getLinkProperties, activeNetwork.get())); - if (!linkProperties) + if (!linkProperties) { return; + } ScopedLocalRef<jclass> linkPropertiesClass(env, env->FindClass("android/net/LinkProperties")); ERR_FAIL_NULL(linkPropertiesClass); @@ -559,8 +581,9 @@ static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dn ScopedLocalRef<jobject> dnsServers(env, env->CallObjectMethod(linkProperties, getDnsServers)); - if (!dnsServers) + if (!dnsServers) { return; + } ScopedLocalRef<jclass> listClass(env, env->FindClass("java/util/List")); ERR_FAIL_NULL(listClass); @@ -570,11 +593,13 @@ static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dn int dnsServersCount = env->CallIntMethod(dnsServers, listSize); - if (dnsServersCount > dns_servers_len) + if (dnsServersCount > dns_servers_len) { dnsServersCount = dns_servers_len; + } - if (dnsServersCount <= 0) + if (dnsServersCount <= 0) { return; + } jmethodID listGet = env->GetMethodID(listClass, "get", "(I)Ljava/lang/Object;"); ERR_FAIL_NULL(listGet); @@ -587,8 +612,9 @@ static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dn for (int i = 0; i < dnsServersCount; i++) { ScopedLocalRef<jobject> dnsServer(env, env->CallObjectMethod(dnsServers, listGet, (jint)i)); - if (!dnsServer) + if (!dnsServer) { continue; + } ScopedLocalRef<jstring> hostAddress(env, (jstring)env->CallObjectMethod(dnsServer, getHostAddress)); const char *host_address = env->GetStringUTFChars(hostAddress, 0); @@ -603,8 +629,9 @@ static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dn } GD_PINVOKE_EXPORT int32_t _monodroid_get_dns_servers(void **r_dns_servers_array) { - if (!r_dns_servers_array) + if (!r_dns_servers_array) { return -1; + } *r_dns_servers_array = nullptr; @@ -661,13 +688,15 @@ GD_PINVOKE_EXPORT const char *_monodroid_timezone_get_default_id() { ScopedLocalRef<jobject> defaultTimeZone(env, env->CallStaticObjectMethod(timeZoneClass, getDefault)); - if (!defaultTimeZone) + if (!defaultTimeZone) { return nullptr; + } ScopedLocalRef<jstring> defaultTimeZoneID(env, (jstring)env->CallObjectMethod(defaultTimeZone, getID)); - if (!defaultTimeZoneID) + if (!defaultTimeZoneID) { return nullptr; + } const char *default_time_zone_id = env->GetStringUTFChars(defaultTimeZoneID, 0); diff --git a/modules/mono/mono_gd/support/ios_support.mm b/modules/mono/mono_gd/support/ios_support.mm index e66b88db32..df97dfba49 100644 --- a/modules/mono/mono_gd/support/ios_support.mm +++ b/modules/mono/mono_gd/support/ios_support.mm @@ -94,8 +94,9 @@ GD_PINVOKE_EXPORT const char *xamarin_get_locale_country_code() { GD_PINVOKE_EXPORT void xamarin_log(const uint16_t *p_unicode_message) { int length = 0; const uint16_t *ptr = p_unicode_message; - while (*ptr++) + while (*ptr++) { length += sizeof(uint16_t); + } NSString *msg = [[NSString alloc] initWithBytes:p_unicode_message length:length encoding:NSUTF16LittleEndianStringEncoding]; os_log_info(OS_LOG_DEFAULT, "%{public}@", msg); diff --git a/modules/mono/utils/mono_reg_utils.cpp b/modules/mono/utils/mono_reg_utils.cpp index f388661207..8e37e6943c 100644 --- a/modules/mono/utils/mono_reg_utils.cpp +++ b/modules/mono/utils/mono_reg_utils.cpp @@ -60,8 +60,9 @@ REGSAM _get_bitness_sam() { LONG _RegOpenKey(HKEY hKey, LPCWSTR lpSubKey, PHKEY phkResult) { LONG res = RegOpenKeyExW(hKey, lpSubKey, 0, KEY_READ, phkResult); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { res = RegOpenKeyExW(hKey, lpSubKey, 0, KEY_READ | _get_bitness_sam(), phkResult); + } return res; } @@ -92,31 +93,37 @@ LONG _find_mono_in_reg(const String &p_subkey, MonoRegInfo &r_info, bool p_old_r HKEY hKey; LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, (LPCWSTR)(p_subkey.utf16().get_data()), &hKey); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } if (!p_old_reg) { res = _RegKeyQueryString(hKey, "Version", r_info.version); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } } res = _RegKeyQueryString(hKey, "SdkInstallRoot", r_info.install_root_dir); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } res = _RegKeyQueryString(hKey, "FrameworkAssemblyDirectory", r_info.assembly_dir); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } res = _RegKeyQueryString(hKey, "MonoConfigDir", r_info.config_dir); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } - if (r_info.install_root_dir.ends_with("\\")) + if (r_info.install_root_dir.ends_with("\\")) { r_info.bin_dir = r_info.install_root_dir + "bin"; - else + } else { r_info.bin_dir = r_info.install_root_dir + "\\bin"; + } cleanup: RegCloseKey(hKey); @@ -129,8 +136,9 @@ LONG _find_mono_in_reg_old(const String &p_subkey, MonoRegInfo &r_info) { HKEY hKey; LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, (LPCWSTR)(p_subkey.utf16().get_data()), &hKey); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } res = _RegKeyQueryString(hKey, "DefaultCLR", default_clr); @@ -147,11 +155,13 @@ cleanup: MonoRegInfo find_mono() { MonoRegInfo info; - if (_find_mono_in_reg("Software\\Mono", info) == ERROR_SUCCESS) + if (_find_mono_in_reg("Software\\Mono", info) == ERROR_SUCCESS) { return info; + } - if (_find_mono_in_reg_old("Software\\Novell\\Mono", info) == ERROR_SUCCESS) + if (_find_mono_in_reg_old("Software\\Novell\\Mono", info) == ERROR_SUCCESS) { return info; + } return MonoRegInfo(); } @@ -212,13 +222,15 @@ String find_msbuild_tools_path() { HKEY hKey; LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\14.0", &hKey); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } res = _RegKeyQueryString(hKey, "MSBuildToolsPath", msbuild_tools_path); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { goto cleanup; + } cleanup: RegCloseKey(hKey); diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp index 89851fc4d3..15a0b28181 100644 --- a/modules/mono/utils/path_utils.cpp +++ b/modules/mono/utils/path_utils.cpp @@ -57,8 +57,9 @@ String cwd() { Char16String buffer; buffer.resize((int)expected_size); - if (::GetCurrentDirectoryW(expected_size, (wchar_t *)buffer.ptrw()) == 0) + if (::GetCurrentDirectoryW(expected_size, (wchar_t *)buffer.ptrw()) == 0) { return "."; + } String result; if (result.parse_utf16(buffer.ptr())) { @@ -95,8 +96,9 @@ String realpath(const String &p_path) { FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (hFile == INVALID_HANDLE_VALUE) + if (hFile == INVALID_HANDLE_VALUE) { return p_path; + } const DWORD expected_size = ::GetFinalPathNameByHandleW(hFile, nullptr, 0, FILE_NAME_NORMALIZED); @@ -177,8 +179,9 @@ String relative_to_impl(const String &p_path, const String &p_relative_to) { #ifdef WINDOWS_ENABLED String get_drive_letter(const String &p_norm_path) { int idx = p_norm_path.find(":/"); - if (idx != -1 && idx < p_norm_path.find("/")) + if (idx != -1 && idx < p_norm_path.find("/")) { return p_norm_path.substr(0, idx + 1); + } return String(); } #endif diff --git a/modules/navigation/nav_map.cpp b/modules/navigation/nav_map.cpp index 76c31a5f42..1151df6390 100644 --- a/modules/navigation/nav_map.cpp +++ b/modules/navigation/nav_map.cpp @@ -83,12 +83,9 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p continue; } - // For each point cast a face and check the distance between the origin/destination - for (size_t point_id = 0; point_id < p.points.size(); point_id++) { - const Vector3 p1 = p.points[point_id].pos; - const Vector3 p2 = p.points[(point_id + 1) % p.points.size()].pos; - const Vector3 p3 = p.points[(point_id + 2) % p.points.size()].pos; - const Face3 face(p1, p2, p3); + // For each face check the distance between the origin/destination + for (size_t point_id = 2; point_id < p.points.size(); point_id++) { + const Face3 face(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos); Vector3 point = face.get_closest_point_to(p_origin); float distance_to_point = point.distance_to(p_origin); @@ -214,7 +211,7 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p end_poly = reachable_end; end_d = 1e20; for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) { - Face3 f(end_poly->points[point_id - 2].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos); + Face3 f(end_poly->points[0].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos); Vector3 spoint = f.get_closest_point_to(p_destination); float dpoint = spoint.distance_to(p_destination); if (dpoint < end_d) { @@ -370,13 +367,12 @@ Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector Vector3 closest_point; real_t closest_point_d = 1e20; - // Find the initial poly and the end poly on this map. for (size_t i(0); i < polygons.size(); i++) { const gd::Polygon &p = polygons[i]; - // For each point cast a face and check the distance to the segment + // For each face check the distance to the segment for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) { - const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos); + const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos); Vector3 inters; if (f.intersects_segment(p_from, p_to, &inters)) { const real_t d = closest_point_d = p_from.distance_to(inters); @@ -416,82 +412,42 @@ Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector } Vector3 NavMap::get_closest_point(const Vector3 &p_point) const { - // TODO this is really not optimal, please redesign the API to directly return all this data - - Vector3 closest_point; - real_t closest_point_d = 1e20; - - // Find the initial poly and the end poly on this map. - for (size_t i(0); i < polygons.size(); i++) { - const gd::Polygon &p = polygons[i]; - - // For each point cast a face and check the distance to the point - for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) { - const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos); - const Vector3 inters = f.get_closest_point_to(p_point); - const real_t d = inters.distance_to(p_point); - if (d < closest_point_d) { - closest_point = inters; - closest_point_d = d; - } - } - } - - return closest_point; + gd::ClosestPointQueryResult cp = get_closest_point_info(p_point); + return cp.point; } Vector3 NavMap::get_closest_point_normal(const Vector3 &p_point) const { - // TODO this is really not optimal, please redesign the API to directly return all this data - - Vector3 closest_point; - Vector3 closest_point_normal; - real_t closest_point_d = 1e20; - - // Find the initial poly and the end poly on this map. - for (size_t i(0); i < polygons.size(); i++) { - const gd::Polygon &p = polygons[i]; - - // For each point cast a face and check the distance to the point - for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) { - const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos); - const Vector3 inters = f.get_closest_point_to(p_point); - const real_t d = inters.distance_to(p_point); - if (d < closest_point_d) { - closest_point = inters; - closest_point_normal = f.get_plane().normal; - closest_point_d = d; - } - } - } - - return closest_point_normal; + gd::ClosestPointQueryResult cp = get_closest_point_info(p_point); + return cp.normal; } RID NavMap::get_closest_point_owner(const Vector3 &p_point) const { - // TODO this is really not optimal, please redesign the API to directly return all this data + gd::ClosestPointQueryResult cp = get_closest_point_info(p_point); + return cp.owner; +} - Vector3 closest_point; - RID closest_point_owner; - real_t closest_point_d = 1e20; +gd::ClosestPointQueryResult NavMap::get_closest_point_info(const Vector3 &p_point) const { + gd::ClosestPointQueryResult result; + real_t closest_point_ds = 1e20; - // Find the initial poly and the end poly on this map. for (size_t i(0); i < polygons.size(); i++) { const gd::Polygon &p = polygons[i]; - // For each point cast a face and check the distance to the point + // For each face check the distance to the point for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) { - const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos); + const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos); const Vector3 inters = f.get_closest_point_to(p_point); - const real_t d = inters.distance_to(p_point); - if (d < closest_point_d) { - closest_point = inters; - closest_point_owner = p.owner->get_self(); - closest_point_d = d; + const real_t ds = inters.distance_squared_to(p_point); + if (ds < closest_point_ds) { + result.point = inters; + result.normal = f.get_plane().normal; + result.owner = p.owner->get_self(); + closest_point_ds = ds; } } } - return closest_point_owner; + return result; } void NavMap::add_region(NavRegion *p_region) { diff --git a/modules/navigation/nav_map.h b/modules/navigation/nav_map.h index 1802f4e907..f46297a7ce 100644 --- a/modules/navigation/nav_map.h +++ b/modules/navigation/nav_map.h @@ -104,6 +104,7 @@ public: Vector3 get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const; Vector3 get_closest_point(const Vector3 &p_point) const; Vector3 get_closest_point_normal(const Vector3 &p_point) const; + gd::ClosestPointQueryResult get_closest_point_info(const Vector3 &p_point) const; RID get_closest_point_owner(const Vector3 &p_point) const; void add_region(NavRegion *p_region); diff --git a/modules/navigation/nav_utils.h b/modules/navigation/nav_utils.h index a6f51a4698..0c02885b10 100644 --- a/modules/navigation/nav_utils.h +++ b/modules/navigation/nav_utils.h @@ -32,6 +32,7 @@ #define NAV_UTILS_H #include "core/math/vector3.h" +#include "core/templates/vector.h" #include <vector> @@ -131,6 +132,12 @@ struct NavigationPoly { } }; +struct ClosestPointQueryResult { + Vector3 point; + Vector3 normal; + RID owner; +}; + } // namespace gd #endif // NAV_UTILS_H diff --git a/modules/navigation/navigation_mesh_editor_plugin.cpp b/modules/navigation/navigation_mesh_editor_plugin.cpp index 6db3cbc1a3..511490ba07 100644 --- a/modules/navigation/navigation_mesh_editor_plugin.cpp +++ b/modules/navigation/navigation_mesh_editor_plugin.cpp @@ -33,6 +33,7 @@ #include "core/io/marshalls.h" #include "core/io/resource_saver.h" +#include "editor/editor_node.h" #include "navigation_mesh_generator.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/gui/box_container.h" @@ -45,10 +46,12 @@ void NavigationMeshEditor::_node_removed(Node *p_node) { } } -void NavigationMeshEditor::_notification(int p_option) { - if (p_option == NOTIFICATION_ENTER_TREE) { - button_bake->set_icon(get_theme_icon(SNAME("Bake"), SNAME("EditorIcons"))); - button_reset->set_icon(get_theme_icon(SNAME("Reload"), SNAME("EditorIcons"))); +void NavigationMeshEditor::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_TREE: { + button_bake->set_icon(get_theme_icon(SNAME("Bake"), SNAME("EditorIcons"))); + button_reset->set_icon(get_theme_icon(SNAME("Reload"), SNAME("EditorIcons"))); + } break; } } @@ -139,10 +142,9 @@ void NavigationMeshEditorPlugin::make_visible(bool p_visible) { } } -NavigationMeshEditorPlugin::NavigationMeshEditorPlugin(EditorNode *p_node) { - editor = p_node; +NavigationMeshEditorPlugin::NavigationMeshEditorPlugin() { navigation_mesh_editor = memnew(NavigationMeshEditor); - editor->get_main_control()->add_child(navigation_mesh_editor); + EditorNode::get_singleton()->get_main_control()->add_child(navigation_mesh_editor); add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, navigation_mesh_editor->bake_hbox); navigation_mesh_editor->hide(); navigation_mesh_editor->bake_hbox->hide(); diff --git a/modules/navigation/navigation_mesh_editor_plugin.h b/modules/navigation/navigation_mesh_editor_plugin.h index 6517a7be5b..d581b453b3 100644 --- a/modules/navigation/navigation_mesh_editor_plugin.h +++ b/modules/navigation/navigation_mesh_editor_plugin.h @@ -33,7 +33,6 @@ #ifdef TOOLS_ENABLED -#include "editor/editor_node.h" #include "editor/editor_plugin.h" class NavigationRegion3D; @@ -58,7 +57,7 @@ class NavigationMeshEditor : public Control { protected: void _node_removed(Node *p_node); static void _bind_methods(); - void _notification(int p_option); + void _notification(int p_what); public: void edit(NavigationRegion3D *p_nav_region); @@ -70,7 +69,6 @@ class NavigationMeshEditorPlugin : public EditorPlugin { GDCLASS(NavigationMeshEditorPlugin, EditorPlugin); NavigationMeshEditor *navigation_mesh_editor; - EditorNode *editor; public: virtual String get_name() const override { return "NavigationMesh"; } @@ -79,7 +77,7 @@ public: virtual bool handles(Object *p_object) const override; virtual void make_visible(bool p_visible) override; - NavigationMeshEditorPlugin(EditorNode *p_node); + NavigationMeshEditorPlugin(); ~NavigationMeshEditorPlugin(); }; diff --git a/modules/navigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp index 52d5379e8b..61c3cefc7a 100644 --- a/modules/navigation/navigation_mesh_generator.cpp +++ b/modules/navigation/navigation_mesh_generator.cpp @@ -50,7 +50,6 @@ #ifdef TOOLS_ENABLED #include "editor/editor_node.h" -#include "editor/editor_settings.h" #endif #include "modules/modules_enabled.gen.h" // For csg, gridmap. diff --git a/modules/navigation/rvo_agent.cpp b/modules/navigation/rvo_agent.cpp index c967d0bf98..a6a5660c0c 100644 --- a/modules/navigation/rvo_agent.cpp +++ b/modules/navigation/rvo_agent.cpp @@ -75,5 +75,5 @@ void RvoAgent::dispatch_callback() { const Variant *vp[2] = { &callback.new_velocity, &callback.udata }; int argc = (callback.udata.get_type() == Variant::NIL) ? 1 : 2; - obj->call(callback.method, vp, argc, responseCallError); + obj->callp(callback.method, vp, argc, responseCallError); } diff --git a/modules/ogg/doc_classes/OGGPacketSequence.xml b/modules/ogg/doc_classes/OGGPacketSequence.xml index deac5b67e2..bff3691ce0 100644 --- a/modules/ogg/doc_classes/OGGPacketSequence.xml +++ b/modules/ogg/doc_classes/OGGPacketSequence.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="OGGPacketSequence" inherits="Resource" version="4.0"> +<class name="OGGPacketSequence" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A sequence of OGG packets. </brief_description> diff --git a/modules/ogg/doc_classes/OGGPacketSequencePlayback.xml b/modules/ogg/doc_classes/OGGPacketSequencePlayback.xml index 86dee15567..11fc1f4cb6 100644 --- a/modules/ogg/doc_classes/OGGPacketSequencePlayback.xml +++ b/modules/ogg/doc_classes/OGGPacketSequencePlayback.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="OGGPacketSequencePlayback" inherits="RefCounted" version="4.0"> +<class name="OGGPacketSequencePlayback" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/ogg/ogg_packet_sequence.cpp b/modules/ogg/ogg_packet_sequence.cpp index 65058f088e..da52ecfdd5 100644 --- a/modules/ogg/ogg_packet_sequence.cpp +++ b/modules/ogg/ogg_packet_sequence.cpp @@ -162,6 +162,7 @@ bool OGGPacketSequencePlayback::next_ogg_packet(ogg_packet **p_packet) const { } uint32_t OGGPacketSequencePlayback::seek_page_internal(int64_t granule, uint32_t after_page_inclusive, uint32_t before_page_inclusive) { + // FIXME: This function needs better corner case handling. if (before_page_inclusive == after_page_inclusive) { return before_page_inclusive; } @@ -169,7 +170,8 @@ uint32_t OGGPacketSequencePlayback::seek_page_internal(int64_t granule, uint32_t // Complicating the bisection search algorithm, the middle page might not have a packet that ends on it, // which means it might not have a correct granule position. Find a nearby page that does have a packet ending on it. uint32_t bisection_page = -1; - for (uint32_t test_page = actual_middle_page; test_page <= before_page_inclusive; test_page++) { + // Don't include before_page_inclusive because that always succeeds and will cause infinite recursion later. + for (uint32_t test_page = actual_middle_page; test_page < before_page_inclusive; test_page++) { if (ogg_packet_sequence->page_data[test_page].size() > 0) { bisection_page = test_page; break; diff --git a/modules/opensimplex/doc_classes/NoiseTexture.xml b/modules/opensimplex/doc_classes/NoiseTexture.xml index 16fea228b1..497735ccf3 100644 --- a/modules/opensimplex/doc_classes/NoiseTexture.xml +++ b/modules/opensimplex/doc_classes/NoiseTexture.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="NoiseTexture" inherits="Texture2D" version="4.0"> +<class name="NoiseTexture" inherits="Texture2D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> [OpenSimplexNoise] filled texture. </brief_description> diff --git a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml index 604b07b645..51dd83efc3 100644 --- a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml +++ b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="OpenSimplexNoise" inherits="Resource" version="4.0"> +<class name="OpenSimplexNoise" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Noise generator based on Open Simplex. </brief_description> diff --git a/modules/openxr/SCsub b/modules/openxr/SCsub new file mode 100644 index 0000000000..37a8f3909a --- /dev/null +++ b/modules/openxr/SCsub @@ -0,0 +1,87 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +env_openxr = env_modules.Clone() + +################################################# +# Add in our Khronos OpenXR loader + +thirdparty_obj = [] +thirdparty_dir = "#thirdparty/openxr" + +env_openxr.Prepend( + CPPPATH=[ + thirdparty_dir, + thirdparty_dir + "/include", + thirdparty_dir + "/src", + thirdparty_dir + "/src/common", + thirdparty_dir + "/src/external/jsoncpp/include", + thirdparty_dir + "/src/loader", + ] +) + +# may need to check and set: +# - XR_USE_TIMESPEC + +env_thirdparty = env_openxr.Clone() +env_thirdparty.disable_warnings() +env_thirdparty.AppendUnique(CPPDEFINES=["DISABLE_STD_FILESYSTEM"]) + +if env["platform"] == "android": + # may need to set OPENXR_ANDROID_VERSION_SUFFIX + env_thirdparty.AppendUnique(CPPDEFINES=["XR_OS_ANDROID", "XR_USE_PLATFORM_ANDROID"]) + + # may need to include java parts of the openxr loader +elif env["platform"] == "linuxbsd": + env_thirdparty.AppendUnique(CPPDEFINES=["XR_OS_LINUX", "XR_USE_PLATFORM_XLIB"]) + # FIXME: Review what needs to be set for Android and macOS. + env_thirdparty.AppendUnique(CPPDEFINES=["HAVE_SECURE_GETENV"]) +elif env["platform"] == "windows": + env_thirdparty.AppendUnique(CPPDEFINES=["XR_OS_WINDOWS", "NOMINMAX", "XR_USE_PLATFORM_WIN32"]) + +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/xr_generated_dispatch_table.c") + +# add in common files (hope these don't clash with us) +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/common/filesystem_utils.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/common/object_info.cpp") + +# add in external jsoncpp dependency +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/external/jsoncpp/src/lib_json/json_reader.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/external/jsoncpp/src/lib_json/json_value.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/external/jsoncpp/src/lib_json/json_writer.cpp") + +# add in load +if env["platform"] == "android": + env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/android_utilities.cpp") + +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/api_layer_interface.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_core.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_instance.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_logger_recorders.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_logger.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/manifest_file.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/runtime_interface.cpp") +env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/xr_generated_loader.cpp") + +env.modules_sources += thirdparty_obj + +################################################# +# And include our module source + +module_obj = [] + +env_openxr.add_source_files(module_obj, "*.cpp") +env_openxr.add_source_files(module_obj, "action_map/*.cpp") + +# We're a little more targetted with our extensions +if env["platform"] == "android": + env_openxr.add_source_files(module_obj, "extensions/openxr_android_extension.cpp") +if env["vulkan"]: + env_openxr.add_source_files(module_obj, "extensions/openxr_vulkan_extension.cpp") + +env.modules_sources += module_obj + +# Needed to force rebuilding the module files when the thirdparty library is updated. +env.Depends(module_obj, thirdparty_obj) diff --git a/modules/openxr/action_map/openxr_action.cpp b/modules/openxr/action_map/openxr_action.cpp new file mode 100644 index 0000000000..59ee3f4292 --- /dev/null +++ b/modules/openxr/action_map/openxr_action.cpp @@ -0,0 +1,91 @@ +/*************************************************************************/ +/* openxr_action.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_action.h" + +void OpenXRAction::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_localized_name", "localized_name"), &OpenXRAction::set_localized_name); + ClassDB::bind_method(D_METHOD("get_localized_name"), &OpenXRAction::get_localized_name); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "localized_name"), "set_localized_name", "get_localized_name"); + + ClassDB::bind_method(D_METHOD("set_action_type", "action_type"), &OpenXRAction::set_action_type); + ClassDB::bind_method(D_METHOD("get_action_type"), &OpenXRAction::get_action_type); + ADD_PROPERTY(PropertyInfo(Variant::INT, "action_type", PROPERTY_HINT_ENUM, "bool,float,vector2,pose"), "set_action_type", "get_action_type"); + + ClassDB::bind_method(D_METHOD("set_toplevel_paths", "toplevel_paths"), &OpenXRAction::set_toplevel_paths); + ClassDB::bind_method(D_METHOD("get_toplevel_paths"), &OpenXRAction::get_toplevel_paths); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "toplevel_paths", PROPERTY_HINT_ARRAY_TYPE, "STRING"), "set_toplevel_paths", "get_toplevel_paths"); + + BIND_ENUM_CONSTANT(OPENXR_ACTION_BOOL); + BIND_ENUM_CONSTANT(OPENXR_ACTION_FLOAT); + BIND_ENUM_CONSTANT(OPENXR_ACTION_VECTOR2); + BIND_ENUM_CONSTANT(OPENXR_ACTION_POSE); +} + +Ref<OpenXRAction> OpenXRAction::new_action(const char *p_name, const char *p_localized_name, const ActionType p_action_type, const char *p_toplevel_paths) { + // This is a helper function to help build our default action sets + + Ref<OpenXRAction> action; + action.instantiate(); + action->set_name(String(p_name)); + action->set_localized_name(String(p_localized_name)); + action->set_action_type(p_action_type); + action->parse_toplevel_paths(String(p_toplevel_paths)); + + return action; +} + +void OpenXRAction::set_localized_name(const String p_localized_name) { + localized_name = p_localized_name; +} + +String OpenXRAction::get_localized_name() const { + return localized_name; +} + +void OpenXRAction::set_action_type(const OpenXRAction::ActionType p_action_type) { + action_type = p_action_type; +} + +OpenXRAction::ActionType OpenXRAction::get_action_type() const { + return action_type; +} + +void OpenXRAction::set_toplevel_paths(const PackedStringArray p_toplevel_paths) { + toplevel_paths = p_toplevel_paths; +} + +PackedStringArray OpenXRAction::get_toplevel_paths() const { + return toplevel_paths; +} + +void OpenXRAction::parse_toplevel_paths(const String p_toplevel_paths) { + toplevel_paths = p_toplevel_paths.split(",", false); +} diff --git a/modules/bullet/constraint_bullet.h b/modules/openxr/action_map/openxr_action.h index 5dc3958ee1..e2cfe79e64 100644 --- a/modules/bullet/constraint_bullet.h +++ b/modules/openxr/action_map/openxr_action.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* constraint_bullet.h */ +/* openxr_action.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,41 +28,47 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef CONSTRAINT_BULLET_H -#define CONSTRAINT_BULLET_H +#ifndef OPENXR_ACTION_H +#define OPENXR_ACTION_H -#include "bullet_utilities.h" -#include "rid_bullet.h" +#include "core/io/resource.h" -#include <BulletDynamics/ConstraintSolver/btTypedConstraint.h> +class OpenXRAction : public Resource { + GDCLASS(OpenXRAction, Resource); -class RigidBodyBullet; -class SpaceBullet; -class btTypedConstraint; +public: + enum ActionType { + OPENXR_ACTION_BOOL, + OPENXR_ACTION_FLOAT, + OPENXR_ACTION_VECTOR2, + OPENXR_ACTION_POSE, + OPENXR_ACTION_HAPTIC, + }; + +private: + String localized_name; + ActionType action_type = OPENXR_ACTION_FLOAT; + + PackedStringArray toplevel_paths; -class ConstraintBullet : public RIDBullet { protected: - SpaceBullet *space = nullptr; - btTypedConstraint *constraint = nullptr; - bool disabled_collisions_between_bodies = true; + static void _bind_methods(); public: - ConstraintBullet(); + static Ref<OpenXRAction> new_action(const char *p_name, const char *p_localized_name, const ActionType p_action_type, const char *p_toplevel_paths); - virtual void setup(btTypedConstraint *p_constraint); - virtual void set_space(SpaceBullet *p_space); - virtual void destroy_internal_constraint(); + void set_localized_name(const String p_localized_name); + String get_localized_name() const; - void disable_collisions_between_bodies(const bool p_disabled); - _FORCE_INLINE_ bool is_disabled_collisions_between_bodies() const { return disabled_collisions_between_bodies; } + void set_action_type(const ActionType p_action_type); + ActionType get_action_type() const; -public: - virtual ~ConstraintBullet() { - bulletdelete(constraint); - constraint = nullptr; - } + void set_toplevel_paths(const PackedStringArray p_toplevel_paths); + PackedStringArray get_toplevel_paths() const; - _FORCE_INLINE_ btTypedConstraint *get_bt_constraint() { return constraint; } + void parse_toplevel_paths(const String p_toplevel_paths); }; -#endif // CONSTRAINT_BULLET_H +VARIANT_ENUM_CAST(OpenXRAction::ActionType); + +#endif // !OPENXR_ACTION_H diff --git a/modules/openxr/action_map/openxr_action_map.cpp b/modules/openxr/action_map/openxr_action_map.cpp new file mode 100644 index 0000000000..5391f9569a --- /dev/null +++ b/modules/openxr/action_map/openxr_action_map.cpp @@ -0,0 +1,261 @@ +/*************************************************************************/ +/* openxr_action_map.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_action_map.h" + +void OpenXRActionMap::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_action_sets", "action_sets"), &OpenXRActionMap::set_action_sets); + ClassDB::bind_method(D_METHOD("get_action_sets"), &OpenXRActionMap::get_action_sets); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "action_sets", PROPERTY_HINT_RESOURCE_TYPE, "OpenXRActionSet", PROPERTY_USAGE_NO_EDITOR), "set_action_sets", "get_action_sets"); + + ClassDB::bind_method(D_METHOD("add_action_set", "action_set"), &OpenXRActionMap::add_action_set); + ClassDB::bind_method(D_METHOD("remove_action_set", "action_set"), &OpenXRActionMap::remove_action_set); + + ClassDB::bind_method(D_METHOD("set_interaction_profiles", "interaction_profiles"), &OpenXRActionMap::set_interaction_profiles); + ClassDB::bind_method(D_METHOD("get_interaction_profiles"), &OpenXRActionMap::get_interaction_profiles); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "interaction_profiles", PROPERTY_HINT_RESOURCE_TYPE, "OpenXRInteractionProfile", PROPERTY_USAGE_NO_EDITOR), "set_interaction_profiles", "get_interaction_profiles"); + + ClassDB::bind_method(D_METHOD("add_interaction_profile", "interaction_profile"), &OpenXRActionMap::add_interaction_profile); + ClassDB::bind_method(D_METHOD("remove_interaction_profile", "interaction_profile"), &OpenXRActionMap::remove_interaction_profile); + + ClassDB::bind_method(D_METHOD("create_default_action_sets"), &OpenXRActionMap::create_default_action_sets); +} + +void OpenXRActionMap::set_action_sets(Array p_action_sets) { + action_sets = p_action_sets; +} + +Array OpenXRActionMap::get_action_sets() const { + return action_sets; +} + +void OpenXRActionMap::add_action_set(Ref<OpenXRActionSet> p_action_set) { + ERR_FAIL_COND(p_action_set.is_null()); + + if (action_sets.find(p_action_set) == -1) { + action_sets.push_back(p_action_set); + } +} + +void OpenXRActionMap::remove_action_set(Ref<OpenXRActionSet> p_action_set) { + int idx = action_sets.find(p_action_set); + if (idx != -1) { + action_sets.remove_at(idx); + } +} + +void OpenXRActionMap::set_interaction_profiles(Array p_interaction_profiles) { + interaction_profiles = p_interaction_profiles; +} + +Array OpenXRActionMap::get_interaction_profiles() const { + return interaction_profiles; +} + +void OpenXRActionMap::add_interaction_profile(Ref<OpenXRInteractionProfile> p_interaction_profile) { + ERR_FAIL_COND(p_interaction_profile.is_null()); + + if (interaction_profiles.find(p_interaction_profile) == -1) { + interaction_profiles.push_back(p_interaction_profile); + } +} + +void OpenXRActionMap::remove_interaction_profile(Ref<OpenXRInteractionProfile> p_interaction_profile) { + int idx = interaction_profiles.find(p_interaction_profile); + if (idx != -1) { + interaction_profiles.remove_at(idx); + } +} + +void OpenXRActionMap::create_default_action_sets() { + // Note, if you make changes here make sure to delete your default_action_map.tres file of it will load an old version. + + // Create our Godot action set + Ref<OpenXRActionSet> action_set = OpenXRActionSet::new_action_set("godot", "Godot action set"); + add_action_set(action_set); + + // Create our actions + Ref<OpenXRAction> trigger = action_set->add_new_action("trigger", "Trigger", OpenXRAction::OPENXR_ACTION_FLOAT, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> trigger_click = action_set->add_new_action("trigger_click", "Trigger click", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> trigger_touch = action_set->add_new_action("trigger_touch", "Trigger touching", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> grip = action_set->add_new_action("grip", "Grip", OpenXRAction::OPENXR_ACTION_FLOAT, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> grip_click = action_set->add_new_action("grip_click", "Grip click", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> grip_touch = action_set->add_new_action("grip_touch", "Grip touching", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> primary = action_set->add_new_action("primary", "Primary joystick/thumbstick/trackpad", OpenXRAction::OPENXR_ACTION_VECTOR2, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> primary_click = action_set->add_new_action("primary_click", "Primary joystick/thumbstick/trackpad click", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> primary_touch = action_set->add_new_action("primary_touch", "Primary joystick/thumbstick/trackpad touching", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> secondary = action_set->add_new_action("secondary", "Secondary joystick/thumbstick/trackpad", OpenXRAction::OPENXR_ACTION_VECTOR2, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> secondary_click = action_set->add_new_action("secondary_click", "Secondary joystick/thumbstick/trackpad click", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> secondary_touch = action_set->add_new_action("secondary_touch", "Secondary joystick/thumbstick/trackpad touching", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> menu_button = action_set->add_new_action("menu_button", "Menu button", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> select_button = action_set->add_new_action("select_button", "Select button", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> ax_button = action_set->add_new_action("ax_button", "A/X button", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> ax_touch = action_set->add_new_action("ax_touch", "A/X touching", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> by_button = action_set->add_new_action("by_button", "B/Y button", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> by_touch = action_set->add_new_action("by_touch", "B/Y touching", OpenXRAction::OPENXR_ACTION_BOOL, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> default_pose = action_set->add_new_action("default_pose", "Default pose", OpenXRAction::OPENXR_ACTION_POSE, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> aim_pose = action_set->add_new_action("aim_pose", "Aim pose", OpenXRAction::OPENXR_ACTION_POSE, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> grip_pose = action_set->add_new_action("grip_pose", "Grip pose", OpenXRAction::OPENXR_ACTION_POSE, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> haptic = action_set->add_new_action("haptic", "Haptic", OpenXRAction::OPENXR_ACTION_HAPTIC, "/user/hand/left,/user/hand/right"); + + // Create our interaction profiles + Ref<OpenXRInteractionProfile> profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/khr/simple_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); + profile->add_new_binding(select_button, "/user/hand/left/input/select/click,/user/hand/right/input/select/click"); + // generic has no support for triggers, grip, A/B buttons, nor joystick/trackpad inputs + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our Vive controller profile + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); + profile->add_new_binding(select_button, "/user/hand/left/input/system/click,/user/hand/right/input/system/click"); + // wmr controller has no a/b/x/y buttons + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/click,/user/hand/right/input/trigger/click"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); // OpenXR will convert bool to float + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + // primary on our vive controller is our trackpad + profile->add_new_binding(primary, "/user/hand/left/input/trackpad,/user/hand/right/input/trackpad"); + profile->add_new_binding(primary_click, "/user/hand/left/input/trackpad/click,/user/hand/right/input/trackpad/click"); + profile->add_new_binding(primary_touch, "/user/hand/left/input/trackpad/touch,/user/hand/right/input/trackpad/touch"); + // vive controllers have no secondary input + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our WMR controller profile + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/microsoft/motion_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + // wmr controllers have no select button we can use + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); + // wmr controller has no a/b/x/y buttons + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); // OpenXR will conver float to bool + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); // OpenXR will convert bool to float + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + // primary on our wmr controller is our thumbstick, no touch + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + // secondary on our wmr controller is our trackpad + profile->add_new_binding(secondary, "/user/hand/left/input/trackpad,/user/hand/right/input/trackpad"); + profile->add_new_binding(secondary_click, "/user/hand/left/input/trackpad/click,/user/hand/right/input/trackpad/click"); + profile->add_new_binding(secondary_touch, "/user/hand/left/input/trackpad/touch,/user/hand/right/input/trackpad/touch"); + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our HP MR controller profile + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/hp/mixed_reality_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + // hpmr controllers have no select button we can use + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); + // hpmr controllers only register click, not touch, on our a/b/x/y buttons + profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand + profile->add_new_binding(by_button, "/user/hand/left/input/y/click,/user/hand/right/input/b/click"); // y on left hand, b on right hand + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); + // primary on our hpmr controller is our thumbstick + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + // No secondary on our hpmr controller + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our Meta touch controller profile + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/oculus/touch_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + // touch controllers have no select button we can use + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/system/click"); // right hand system click may not be available + profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand + profile->add_new_binding(ax_touch, "/user/hand/left/input/x/touch,/user/hand/right/input/a/touch"); + profile->add_new_binding(by_button, "/user/hand/left/input/y/click,/user/hand/right/input/b/click"); // y on left hand, b on right hand + profile->add_new_binding(by_touch, "/user/hand/left/input/y/touch,/user/hand/right/input/b/touch"); + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); // should be converted to boolean + profile->add_new_binding(trigger_touch, "/user/hand/left/input/trigger/touch,/user/hand/right/input/trigger/touch"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); // should be converted to boolean + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); + // primary on our touch controller is our thumbstick + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + profile->add_new_binding(primary_touch, "/user/hand/left/input/thumbstick/touch,/user/hand/right/input/thumbstick/touch"); + // touch controller has no secondary input + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our Valve index controller profile + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/valve/index_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + // index controllers have no select button we can use + profile->add_new_binding(menu_button, "/user/hand/left/input/system/click,/user/hand/right/input/system/click"); + profile->add_new_binding(ax_button, "/user/hand/left/input/a/click,/user/hand/right/input/a/click"); // a on both controllers + profile->add_new_binding(ax_touch, "/user/hand/left/input/a/touch,/user/hand/right/input/a/touch"); + profile->add_new_binding(by_button, "/user/hand/left/input/b/click,/user/hand/right/input/b/click"); // b on both controllers + profile->add_new_binding(by_touch, "/user/hand/left/input/b/touch,/user/hand/right/input/b/touch"); + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/click,/user/hand/right/input/trigger/click"); + profile->add_new_binding(trigger_touch, "/user/hand/left/input/trigger/touch,/user/hand/right/input/trigger/touch"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); // this should do a float to bool conversion + // primary on our index controller is our thumbstick + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + profile->add_new_binding(primary_touch, "/user/hand/left/input/thumbstick/touch,/user/hand/right/input/thumbstick/touch"); + // secondary on our index controller is our trackpad + profile->add_new_binding(secondary, "/user/hand/left/input/trackpad,/user/hand/right/input/trackpad"); + profile->add_new_binding(secondary_click, "/user/hand/left/input/trackpad/force,/user/hand/right/input/trackpad/force"); // not sure if this will work but doesn't seem to support click... + profile->add_new_binding(secondary_touch, "/user/hand/left/input/trackpad/touch,/user/hand/right/input/trackpad/touch"); + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); +} + +void OpenXRActionMap::create_editor_action_sets() { + // TODO implement +} + +OpenXRActionMap::~OpenXRActionMap() { + action_sets.clear(); + interaction_profiles.clear(); +} diff --git a/modules/gdnative/gdnative_library_singleton_editor.h b/modules/openxr/action_map/openxr_action_map.h index 16155723bc..866e170468 100644 --- a/modules/gdnative/gdnative_library_singleton_editor.h +++ b/modules/openxr/action_map/openxr_action_map.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* gdnative_library_singleton_editor.h */ +/* openxr_action_map.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,35 +28,41 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GD_NATIVE_LIBRARY_EDITOR_H -#define GD_NATIVE_LIBRARY_EDITOR_H +#ifndef OPENXR_ACTION_SETS_H +#define OPENXR_ACTION_SETS_H -#ifdef TOOLS_ENABLED -#include "editor/editor_file_system.h" -#include "editor/project_settings_editor.h" +#include "core/io/resource.h" -class GDNativeLibrarySingletonEditor : public VBoxContainer { - GDCLASS(GDNativeLibrarySingletonEditor, VBoxContainer); +#include "openxr_action_set.h" +#include "openxr_interaction_profile.h" -private: - Tree *libraries; - UndoRedo *undo_redo; - - bool updating; +class OpenXRActionMap : public Resource { + GDCLASS(OpenXRActionMap, Resource); - static Set<String> _find_singletons_recursive(EditorFileSystemDirectory *p_dir); +private: + Array action_sets; + Array interaction_profiles; protected: - void _notification(int p_what); static void _bind_methods(); - void _discover_singletons(); - void _item_edited(); - void _update_libraries(); - public: - GDNativeLibrarySingletonEditor(); + void set_action_sets(Array p_action_sets); + Array get_action_sets() const; + + void add_action_set(Ref<OpenXRActionSet> p_action_set); + void remove_action_set(Ref<OpenXRActionSet> p_action_set); + + void set_interaction_profiles(Array p_interaction_profiles); + Array get_interaction_profiles() const; + + void add_interaction_profile(Ref<OpenXRInteractionProfile> p_interaction_profile); + void remove_interaction_profile(Ref<OpenXRInteractionProfile> p_interaction_profile); + + void create_default_action_sets(); + void create_editor_action_sets(); + + ~OpenXRActionMap(); }; -#endif -#endif // GD_NATIVE_LIBRARY_EDITOR_H +#endif // !OPENXR_ACTION_SETS_H diff --git a/modules/openxr/action_map/openxr_action_set.cpp b/modules/openxr/action_map/openxr_action_set.cpp new file mode 100644 index 0000000000..465a709b60 --- /dev/null +++ b/modules/openxr/action_map/openxr_action_set.cpp @@ -0,0 +1,111 @@ +/*************************************************************************/ +/* openxr_action_set.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_action_set.h" + +void OpenXRActionSet::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_localized_name", "localized_name"), &OpenXRActionSet::set_localized_name); + ClassDB::bind_method(D_METHOD("get_localized_name"), &OpenXRActionSet::get_localized_name); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "localized_name"), "set_localized_name", "get_localized_name"); + + ClassDB::bind_method(D_METHOD("set_priority", "priority"), &OpenXRActionSet::set_priority); + ClassDB::bind_method(D_METHOD("get_priority"), &OpenXRActionSet::get_priority); + ADD_PROPERTY(PropertyInfo(Variant::INT, "priority"), "set_priority", "get_priority"); + + ClassDB::bind_method(D_METHOD("set_actions", "actions"), &OpenXRActionSet::set_actions); + ClassDB::bind_method(D_METHOD("get_actions"), &OpenXRActionSet::get_actions); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "actions", PROPERTY_HINT_RESOURCE_TYPE, "OpenXRAction", PROPERTY_USAGE_NO_EDITOR), "set_actions", "get_actions"); + + ClassDB::bind_method(D_METHOD("add_action", "action"), &OpenXRActionSet::add_action); + ClassDB::bind_method(D_METHOD("remove_action", "action"), &OpenXRActionSet::remove_action); +} + +Ref<OpenXRActionSet> OpenXRActionSet::new_action_set(const char *p_name, const char *p_localized_name, const int p_priority) { + // This is a helper function to help build our default action sets + + Ref<OpenXRActionSet> action_set; + action_set.instantiate(); + action_set->set_name(String(p_name)); + action_set->set_localized_name(p_localized_name); + action_set->set_priority(p_priority); + + return action_set; +} + +void OpenXRActionSet::set_localized_name(const String p_localized_name) { + localized_name = p_localized_name; +} + +String OpenXRActionSet::get_localized_name() const { + return localized_name; +} + +void OpenXRActionSet::set_priority(const int p_priority) { + priority = p_priority; +} + +int OpenXRActionSet::get_priority() const { + return priority; +} + +void OpenXRActionSet::set_actions(Array p_actions) { + actions = p_actions; +} + +Array OpenXRActionSet::get_actions() const { + return actions; +} + +void OpenXRActionSet::add_action(Ref<OpenXRAction> p_action) { + ERR_FAIL_COND(p_action.is_null()); + + if (actions.find(p_action) == -1) { + actions.push_back(p_action); + } +} + +void OpenXRActionSet::remove_action(Ref<OpenXRAction> p_action) { + int idx = actions.find(p_action); + if (idx != -1) { + actions.remove_at(idx); + } +} + +Ref<OpenXRAction> OpenXRActionSet::add_new_action(const char *p_name, const char *p_localized_name, const OpenXRAction::ActionType p_action_type, const char *p_toplevel_paths) { + // This is a helper function to help build our default action sets + + Ref<OpenXRAction> new_action = OpenXRAction::new_action(p_name, p_localized_name, p_action_type, p_toplevel_paths); + add_action(new_action); + return new_action; +} + +OpenXRActionSet::~OpenXRActionSet() { + actions.clear(); +} diff --git a/modules/basis_universal/texture_basisu.h b/modules/openxr/action_map/openxr_action_set.h index 8c8be68254..012a088b1c 100644 --- a/modules/basis_universal/texture_basisu.h +++ b/modules/openxr/action_map/openxr_action_set.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* texture_basisu.h */ +/* openxr_action_set.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,53 +28,43 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef BASIS_UNIVERSAL_TEXTURE_BASISU_H -#define BASIS_UNIVERSAL_TEXTURE_BASISU_H +#ifndef OPENXR_ACTION_SET_H +#define OPENXR_ACTION_SET_H -#include "scene/resources/texture.h" +#include "core/io/resource.h" -#ifdef TOOLS_ENABLED -#include <encoder/basisu_comp.h> -#endif +#include "openxr_action.h" -#include <transcoder/basisu_transcoder.h> +class OpenXRActionSet : public Resource { + GDCLASS(OpenXRActionSet, Resource); -#if 0 -class TextureBasisU : public Texture { - GDCLASS(TextureBasisU, Texture); - RES_BASE_EXTENSION("butex"); +private: + String localized_name; + int priority = 0; - RID texture; - Size2 tex_size; - - uint32_t flags = FLAGS_DEFAULT; - - Vector<uint8_t> data; + Array actions; +protected: static void _bind_methods(); public: + static Ref<OpenXRActionSet> new_action_set(const char *p_name, const char *p_localized_name, const int p_priority = 0); - virtual int get_width() const; - virtual int get_height() const; - virtual RID get_rid() const; - virtual bool has_alpha() const; + void set_localized_name(const String p_localized_name); + String get_localized_name() const; - virtual void set_flags(uint32_t p_flags); - virtual uint32_t get_flags() const; + void set_priority(const int p_priority); + int get_priority() const; + void set_actions(Array p_actions); + Array get_actions() const; - Error import(const Ref<Image> &p_img); + void add_action(Ref<OpenXRAction> p_action); + void remove_action(Ref<OpenXRAction> p_action); - void set_basisu_data(const Vector<uint8_t>& p_data); + Ref<OpenXRAction> add_new_action(const char *p_name, const char *p_localized_name, const OpenXRAction::ActionType p_action_type, const char *p_toplevel_paths); - Vector<uint8_t> get_basisu_data() const; - String get_img_path() const; - - TextureBasisU(); - ~TextureBasisU(); + ~OpenXRActionSet(); }; -#endif - -#endif // BASIS_UNIVERSAL_TEXTURE_BASISU_H +#endif // !OPENXR_ACTION_SET_H diff --git a/modules/openxr/action_map/openxr_interaction_profile.cpp b/modules/openxr/action_map/openxr_interaction_profile.cpp new file mode 100644 index 0000000000..bc33814f17 --- /dev/null +++ b/modules/openxr/action_map/openxr_interaction_profile.cpp @@ -0,0 +1,136 @@ +/*************************************************************************/ +/* openxr_interaction_profile.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_interaction_profile.h" + +void OpenXRIPBinding::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_action", "action"), &OpenXRIPBinding::set_action); + ClassDB::bind_method(D_METHOD("get_action"), &OpenXRIPBinding::get_action); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "action", PROPERTY_HINT_RESOURCE_TYPE, "OpenXRAction"), "set_action", "get_action"); + + ClassDB::bind_method(D_METHOD("set_paths", "paths"), &OpenXRIPBinding::set_paths); + ClassDB::bind_method(D_METHOD("get_paths"), &OpenXRIPBinding::get_paths); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "paths", PROPERTY_HINT_ARRAY_TYPE, "STRING"), "set_paths", "get_paths"); +} + +Ref<OpenXRIPBinding> OpenXRIPBinding::new_binding(const Ref<OpenXRAction> p_action, const char *p_paths) { + // This is a helper function to help build our default action sets + + Ref<OpenXRIPBinding> binding; + binding.instantiate(); + binding->set_action(p_action); + binding->parse_paths(String(p_paths)); + + return binding; +} + +void OpenXRIPBinding::set_action(const Ref<OpenXRAction> p_action) { + action = p_action; +} + +Ref<OpenXRAction> OpenXRIPBinding::get_action() const { + return action; +} + +void OpenXRIPBinding::set_paths(const PackedStringArray p_paths) { + paths = p_paths; +} + +PackedStringArray OpenXRIPBinding::get_paths() const { + return paths; +} + +void OpenXRIPBinding::parse_paths(const String p_paths) { + paths = p_paths.split(",", false); +} + +OpenXRIPBinding::~OpenXRIPBinding() { + action.unref(); +} + +void OpenXRInteractionProfile::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_interaction_profile_path", "interaction_profile_path"), &OpenXRInteractionProfile::set_interaction_profile_path); + ClassDB::bind_method(D_METHOD("get_interaction_profile_path"), &OpenXRInteractionProfile::get_interaction_profile_path); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "interaction_profile_path"), "set_interaction_profile_path", "get_interaction_profile_path"); + + ClassDB::bind_method(D_METHOD("set_bindings", "bindings"), &OpenXRInteractionProfile::set_bindings); + ClassDB::bind_method(D_METHOD("get_bindings"), &OpenXRInteractionProfile::get_bindings); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "bindings", PROPERTY_HINT_RESOURCE_TYPE, "OpenXRIPBinding", PROPERTY_USAGE_NO_EDITOR), "set_bindings", "get_bindings"); +} + +Ref<OpenXRInteractionProfile> OpenXRInteractionProfile::new_profile(const char *p_input_profile_path) { + Ref<OpenXRInteractionProfile> profile; + profile.instantiate(); + profile->set_interaction_profile_path(String(p_input_profile_path)); + + return profile; +} + +void OpenXRInteractionProfile::set_interaction_profile_path(const String p_input_profile_path) { + interaction_profile_path = p_input_profile_path; +} + +String OpenXRInteractionProfile::get_interaction_profile_path() const { + return interaction_profile_path; +} + +void OpenXRInteractionProfile::set_bindings(Array p_bindings) { + bindings = p_bindings; +} + +Array OpenXRInteractionProfile::get_bindings() const { + return bindings; +} + +void OpenXRInteractionProfile::add_binding(Ref<OpenXRIPBinding> p_binding) { + ERR_FAIL_COND(p_binding.is_null()); + + if (bindings.find(p_binding) == -1) { + bindings.push_back(p_binding); + } +} + +void OpenXRInteractionProfile::remove_binding(Ref<OpenXRIPBinding> p_binding) { + int idx = bindings.find(p_binding); + if (idx != -1) { + bindings.remove_at(idx); + } +} + +void OpenXRInteractionProfile::add_new_binding(const Ref<OpenXRAction> p_action, const char *p_paths) { + // This is a helper function to help build our default action sets + + Ref<OpenXRIPBinding> binding = OpenXRIPBinding::new_binding(p_action, p_paths); + add_binding(binding); +} + +OpenXRInteractionProfile::~OpenXRInteractionProfile() { + bindings.clear(); +} diff --git a/modules/gdnative/gdnative/rect2.cpp b/modules/openxr/action_map/openxr_interaction_profile.h index 7e0ce76c26..abbc429e7d 100644 --- a/modules/gdnative/gdnative/rect2.cpp +++ b/modules/openxr/action_map/openxr_interaction_profile.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* rect2.cpp */ +/* openxr_interaction_profile.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,35 +28,62 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "gdnative/rect2.h" +#ifndef OPENXR_INTERACTION_PROFILE_H +#define OPENXR_INTERACTION_PROFILE_H -#include "core/math/rect2.h" -#include "core/math/rect2i.h" -#include "core/os/memory.h" +#include "core/io/resource.h" -static_assert(sizeof(godot_rect2) == sizeof(Rect2), "Rect2 size mismatch"); -static_assert(sizeof(godot_rect2i) == sizeof(Rect2i), "Rect2i size mismatch"); +#include "openxr_action.h" -#ifdef __cplusplus -extern "C" { -#endif +class OpenXRIPBinding : public Resource { + GDCLASS(OpenXRIPBinding, Resource); -void GDAPI godot_rect2_new(godot_rect2 *p_self) { - memnew_placement(p_self, Rect2); -} +private: + Ref<OpenXRAction> action; + PackedStringArray paths; -void GDAPI godot_rect2_new_copy(godot_rect2 *r_dest, const godot_rect2 *p_src) { - memnew_placement(r_dest, Rect2(*(Rect2 *)p_src)); -} +protected: + static void _bind_methods(); -void GDAPI godot_rect2i_new(godot_rect2i *p_self) { - memnew_placement(p_self, Rect2i); -} +public: + static Ref<OpenXRIPBinding> new_binding(const Ref<OpenXRAction> p_action, const char *p_paths); -void GDAPI godot_rect2i_new_copy(godot_rect2i *r_dest, const godot_rect2i *p_src) { - memnew_placement(r_dest, Rect2i(*(Rect2i *)p_src)); -} + void set_action(const Ref<OpenXRAction> p_action); + Ref<OpenXRAction> get_action() const; -#ifdef __cplusplus -} -#endif + void set_paths(const PackedStringArray p_paths); + PackedStringArray get_paths() const; + + void parse_paths(const String p_paths); + + ~OpenXRIPBinding(); +}; + +class OpenXRInteractionProfile : public Resource { + GDCLASS(OpenXRInteractionProfile, Resource); + +private: + String interaction_profile_path; + Array bindings; + +protected: + static void _bind_methods(); + +public: + static Ref<OpenXRInteractionProfile> new_profile(const char *p_input_profile_path); + + void set_interaction_profile_path(const String p_input_profile_path); + String get_interaction_profile_path() const; + + void set_bindings(Array p_bindings); + Array get_bindings() const; + + void add_binding(Ref<OpenXRIPBinding> p_binding); + void remove_binding(Ref<OpenXRIPBinding> p_binding); + + void add_new_binding(const Ref<OpenXRAction> p_action, const char *p_paths); + + ~OpenXRInteractionProfile(); +}; + +#endif // !OPENXR_INTERACTION_PROFILE_H diff --git a/modules/openxr/config.py b/modules/openxr/config.py new file mode 100644 index 0000000000..f91cb1359f --- /dev/null +++ b/modules/openxr/config.py @@ -0,0 +1,27 @@ +def can_build(env, platform): + if ( + platform == "linuxbsd" or platform == "windows" + ): # or platform == "android" -- temporarily disabled android support + return env["openxr"] + else: + # not supported on these platforms + return False + + +def configure(env): + pass + + +def get_doc_classes(): + return [ + "OpenXRInterface", + "OpenXRAction", + "OpenXRActionSet", + "OpenXRActionMap", + "OpenXRInteractionProfile", + "OpenXRIPBinding", + ] + + +def get_doc_path(): + return "doc_classes" diff --git a/modules/openxr/doc_classes/OpenXRAction.xml b/modules/openxr/doc_classes/OpenXRAction.xml new file mode 100644 index 0000000000..6ff8c1ad26 --- /dev/null +++ b/modules/openxr/doc_classes/OpenXRAction.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="OpenXRAction" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + An OpenXR action. + </brief_description> + <description> + This resource defines an OpenXR action. Actions can be used both for inputs (buttons/joystick/trigger/etc) and outputs (haptics). + OpenXR performs automatic conversion between action type and input type whenever possible. An analogue trigger bound to a boolean action will thus return [code]false[/core] if the trigger is depressed and [code]true[/code] if pressed fully. + Actions are not directly bound to specific devices, instead OpenXR recognises a limited number of top level paths that identify devices by usage. We can restrict which devices an action can be bound to by these top level paths. For instance an action that should only be used for hand held controllers can have the top level paths "/user/hand/left" and "/user/hand/right" associated with them. See the [url=https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved]reserved path section in the OpenXR specification[/url] for more info on the top level paths. + Note that the name of the resource is used to register the action with. + </description> + <tutorials> + </tutorials> + <members> + <member name="action_type" type="int" setter="set_action_type" getter="get_action_type" enum="OpenXRAction.ActionType" default="1"> + The type of action. + </member> + <member name="localized_name" type="String" setter="set_localized_name" getter="get_localized_name" default=""""> + The localised description of this action. + </member> + <member name="toplevel_paths" type="PackedStringArray" setter="set_toplevel_paths" getter="get_toplevel_paths" default="PackedStringArray()"> + A collections of toplevel paths to which this action can be bound. + </member> + </members> + <constants> + <constant name="OPENXR_ACTION_BOOL" value="0" enum="ActionType"> + This action provides a boolean value. + </constant> + <constant name="OPENXR_ACTION_FLOAT" value="1" enum="ActionType"> + This action provides a float value between [code]0.0[/code] and [code]1.0[/code] for any analogue input such as triggers. + </constant> + <constant name="OPENXR_ACTION_VECTOR2" value="2" enum="ActionType"> + This action provides a vector2 value and can be bound to embedded trackpads and joysticks + </constant> + <constant name="OPENXR_ACTION_POSE" value="3" enum="ActionType"> + </constant> + </constants> +</class> diff --git a/modules/openxr/doc_classes/OpenXRActionMap.xml b/modules/openxr/doc_classes/OpenXRActionMap.xml new file mode 100644 index 0000000000..f1def8aad8 --- /dev/null +++ b/modules/openxr/doc_classes/OpenXRActionMap.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="OpenXRActionMap" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Collection of [OpenXRActionSet] and [OpenXRInteractionProfile] resources for the OpenXR module. + </brief_description> + <description> + OpenXR uses an action system similar to Godots Input map system to bind inputs and outputs on various types of XR controllers to named actions. OpenXR specifies more detail on these inputs and outputs than Godot supports. + Another important distinction is that OpenXR offers no control over these bindings. The bindings we register are suggestions, it is up to the XR runtime to offer users the ability to change these bindings. This allows the XR runtime to fill in the gaps if new hardware becomes available. + The action map therefor needs to be loaded at startup and can't be changed afterwards. This resource is a container for the entire action map. + </description> + <tutorials> + </tutorials> + <methods> + <method name="add_action_set"> + <return type="void" /> + <argument index="0" name="action_set" type="OpenXRActionSet" /> + <description> + Add an action set. + </description> + </method> + <method name="add_interaction_profile"> + <return type="void" /> + <argument index="0" name="interaction_profile" type="OpenXRInteractionProfile" /> + <description> + Add an interaction profile. + </description> + </method> + <method name="create_default_action_sets"> + <return type="void" /> + <description> + Setup this action set with our default actions. + </description> + </method> + <method name="remove_action_set"> + <return type="void" /> + <argument index="0" name="action_set" type="OpenXRActionSet" /> + <description> + Remove an action set. + </description> + </method> + <method name="remove_interaction_profile"> + <return type="void" /> + <argument index="0" name="interaction_profile" type="OpenXRInteractionProfile" /> + <description> + Remove an interaction profile. + </description> + </method> + </methods> + <members> + <member name="action_sets" type="Array" setter="set_action_sets" getter="get_action_sets" default="[]"> + </member> + <member name="interaction_profiles" type="Array" setter="set_interaction_profiles" getter="get_interaction_profiles" default="[]"> + </member> + </members> +</class> diff --git a/modules/openxr/doc_classes/OpenXRActionSet.xml b/modules/openxr/doc_classes/OpenXRActionSet.xml new file mode 100644 index 0000000000..5a87de463e --- /dev/null +++ b/modules/openxr/doc_classes/OpenXRActionSet.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="OpenXRActionSet" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Collection of [OpenXRAction] resources that make up an action set. + </brief_description> + <description> + Action sets in OpenXR define a collection of actions that can be activated in unison. This allows games to easily change between different states that require different inputs or need to reinterpret inputs. For instance we could have an action set that is active when a menu is open, an action set that is active when the player is freely walking around and an action set that is active when the player is controlling a vehicle. + Action sets can contain the same actions, or actions with the same name, if such action sets are active at the same time the action set with the highest priority defines which binding is active. + Note that the name of the resource is used to identify the action set within OpenXR. + </description> + <tutorials> + </tutorials> + <methods> + <method name="add_action"> + <return type="void" /> + <argument index="0" name="action" type="OpenXRAction" /> + <description> + Add an action to this action set. + </description> + </method> + <method name="remove_action"> + <return type="void" /> + <argument index="0" name="action" type="OpenXRAction" /> + <description> + Remove an action from this action set. + </description> + </method> + </methods> + <members> + <member name="actions" type="Array" setter="set_actions" getter="get_actions" default="[]"> + Collection of actions for this action set. + </member> + <member name="localized_name" type="String" setter="set_localized_name" getter="get_localized_name" default=""""> + The localised name of this action set. + </member> + <member name="priority" type="int" setter="set_priority" getter="get_priority" default="0"> + The priority for this action set. + </member> + </members> +</class> diff --git a/modules/openxr/doc_classes/OpenXRIPBinding.xml b/modules/openxr/doc_classes/OpenXRIPBinding.xml new file mode 100644 index 0000000000..3fdcde5eb5 --- /dev/null +++ b/modules/openxr/doc_classes/OpenXRIPBinding.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="OpenXRIPBinding" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Defines a binding between an [OpenXRAction] and an XR input or output. + </brief_description> + <description> + This binding resource binds an OpenXR action to inputs or outputs. As most controllers have left hand and right versions that are handled by the same interaction profile we can specify multiple bindings. For instance an action "Fire" could be bound to both "/user/hand/left/input/trigger" and "/user/hand/right/input/trigger". + </description> + <tutorials> + </tutorials> + <members> + <member name="action" type="OpenXRAction" setter="set_action" getter="get_action"> + Action that is bound to these paths. + </member> + <member name="paths" type="PackedStringArray" setter="set_paths" getter="get_paths" default="PackedStringArray()"> + Paths that define the inputs or outputs bound on the device. + </member> + </members> +</class> diff --git a/modules/openxr/doc_classes/OpenXRInteractionProfile.xml b/modules/openxr/doc_classes/OpenXRInteractionProfile.xml new file mode 100644 index 0000000000..a8629caae4 --- /dev/null +++ b/modules/openxr/doc_classes/OpenXRInteractionProfile.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="OpenXRInteractionProfile" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Suggested bindings object for OpenXR. + </brief_description> + <description> + This object stores suggested bindings for an interaction profile. Interaction profiles define the meta data for a tracked XR device such as an XR controller. + For more information see the [url=https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-interaction-profiles]interaction profiles info in the OpenXR specification[/url]. + </description> + <tutorials> + </tutorials> + <members> + <member name="bindings" type="Array" setter="set_bindings" getter="get_bindings" default="[]"> + Action bindings for this interaction profile. + </member> + <member name="interaction_profile_path" type="String" setter="set_interaction_profile_path" getter="get_interaction_profile_path" default=""""> + The interaction profile path identifying the XR device. + </member> + </members> +</class> diff --git a/modules/openxr/doc_classes/OpenXRInterface.xml b/modules/openxr/doc_classes/OpenXRInterface.xml new file mode 100644 index 0000000000..74f708bc95 --- /dev/null +++ b/modules/openxr/doc_classes/OpenXRInterface.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="OpenXRInterface" inherits="XRInterface" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Our OpenXR interface. + </brief_description> + <description> + The OpenXR interface allows Godot to interact with OpenXR runtimes and make it possible to create XR experiences and games. + Due to the needs of OpenXR this interface works slightly different then other plugin based XR interfaces. It needs to be initialised when Godot starts. You need to enable OpenXR, settings for this can be found in your games project settings under the XR heading. You do need to mark a viewport for use with XR in order for Godot to know which render result should be output to the headset. + </description> + <tutorials> + <link title="OpenXR documentation">$DOCS_URL/tutorials/vr/openxr/index.html</link> + </tutorials> + <signals> + <signal name="pose_recentered"> + <description> + Informs the user queued a recenter of the player position. + </description> + </signal> + <signal name="session_begun"> + <description> + Informs our OpenXR session has been started. + </description> + </signal> + <signal name="session_focussed"> + <description> + Informs our OpenXR session now has focus. + </description> + </signal> + <signal name="session_stopping"> + <description> + Informs our OpenXR session is stopping. + </description> + </signal> + <signal name="session_visible"> + <description> + Informs our OpenXR session is now visible (output is being sent to the HMD). + </description> + </signal> + </signals> +</class> diff --git a/modules/gdnative/gdnative/string_name.cpp b/modules/openxr/extensions/openxr_android_extension.cpp index 0bdacd2e5d..3bd4db169c 100644 --- a/modules/gdnative/gdnative/string_name.cpp +++ b/modules/openxr/extensions/openxr_android_extension.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* string_name.cpp */ +/* openxr_android_extension.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,35 +28,44 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "gdnative/string_name.h" +#include "openxr_android_extension.h" -#include "core/string/string_name.h" +#include <openxr/openxr.h> +#include <openxr/openxr_platform.h> -static_assert(sizeof(godot_string_name) == sizeof(StringName), "StringName size mismatch"); +OpenXRAndroidExtension *OpenXRAndroidExtension::singleton = nullptr; -#ifdef __cplusplus -extern "C" { -#endif - -void GDAPI godot_string_name_new(godot_string_name *r_dest) { - StringName *dest = (StringName *)r_dest; - memnew_placement(dest, StringName); +OpenXRAndroidExtension *OpenXRAndroidExtension::get_singleton() { + return singleton; } -void GDAPI godot_string_name_new_copy(godot_string_name *r_dest, const godot_string_name *p_src) { - memnew_placement(r_dest, StringName(*(StringName *)p_src)); -} +OpenXRAndroidExtension::OpenXRAndroidExtension(OpenXRAPI *p_openxr_api) : + OpenXRExtensionWrapper(p_openxr_api) { + singleton = this; -void GDAPI godot_string_name_new_with_latin1_chars(godot_string_name *r_dest, const char *p_contents) { - StringName *dest = (StringName *)r_dest; - memnew_placement(dest, StringName(p_contents)); -} + request_extensions[XR_KHR_ANDROID_THREAD_SETTINGS_EXTENSION_NAME] = nullptr; // must be available + + // Initialize the loader + PFN_xrInitializeLoaderKHR xrInitializeLoaderKHR; + result = xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction *)(&xrInitializeLoaderKHR)); + ERR_FAIL_COND_MSG(XR_FAILED(result), "Failed to retrieve pointer to xrInitializeLoaderKHR"); + + // TODO fix this code, this is still code from GDNative! + JNIEnv *env = android_api->godot_android_get_env(); + JavaVM *vm; + env->GetJavaVM(&vm); + jobject activity_object = env->NewGlobalRef(android_api->godot_android_get_activity()); -void GDAPI godot_string_name_destroy(godot_string_name *p_self) { - StringName *self = (StringName *)p_self; - self->~StringName(); + XrLoaderInitInfoAndroidKHR loader_init_info_android = { + .type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR, + .next = nullptr, + .applicationVM = vm, + .applicationContext = activity_object + }; + xrInitializeLoaderKHR((const XrLoaderInitInfoBaseHeaderKHR *)&loader_init_info_android); + ERR_FAIL_COND_MSG(XR_FAILED(result), "Failed to call xrInitializeLoaderKHR"); } -#ifdef __cplusplus +OpenXRAndroidExtension::~OpenXRAndroidExtension() { + singleton = nullptr; } -#endif diff --git a/modules/bullet/joint_bullet.h b/modules/openxr/extensions/openxr_android_extension.h index 427221dd77..e102197a55 100644 --- a/modules/bullet/joint_bullet.h +++ b/modules/openxr/extensions/openxr_android_extension.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* joint_bullet.h */ +/* openxr_android_extension.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,21 +28,20 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef JOINT_BULLET_H -#define JOINT_BULLET_H +#ifndef OPENXR_ANDROID_EXTENSION_H +#define OPENXR_ANDROID_EXTENSION_H -#include "constraint_bullet.h" -#include "servers/physics_server_3d.h" +#include "openxr_extension_wrapper.h" -class RigidBodyBullet; -class btTypedConstraint; - -class JointBullet : public ConstraintBullet { +class OpenXRAndroidExtension : public OpenXRExtensionWrapper { public: - JointBullet() {} - virtual ~JointBullet() {} + static OpenXRAndroidExtension *get_singleton(); + + OpenXRAndroidExtension(OpenXRAPI *p_openxr_api); + virtual ~OpenXRAndroidExtension() override; - virtual PhysicsServer3D::JointType get_type() const = 0; +private: + static OpenXRAndroidExtension *singleton; }; -#endif // JOINT_BULLET_H +#endif // !OPENXR_ANDROID_EXTENSION_H diff --git a/modules/bullet/rid_bullet.h b/modules/openxr/extensions/openxr_composition_layer_provider.h index 260d303cac..019dffa2a8 100644 --- a/modules/bullet/rid_bullet.h +++ b/modules/openxr/extensions/openxr_composition_layer_provider.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* rid_bullet.h */ +/* openxr_composition_layer_provider.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,23 +28,18 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef RID_BULLET_H -#define RID_BULLET_H +#ifndef OPENXR_COMPOSITION_LAYER_PROVIDER_H +#define OPENXR_COMPOSITION_LAYER_PROVIDER_H -#include "core/templates/rid.h" - -class BulletPhysicsServer3D; - -class RIDBullet { - RID self; - BulletPhysicsServer3D *physicsServer = nullptr; +#include <openxr/openxr.h> +// Interface for OpenXR extensions that provide a composition layer. +class OpenXRCompositionLayerProvider { public: - _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } - _FORCE_INLINE_ RID get_self() const { return self; } - - _FORCE_INLINE_ void _set_physics_server(BulletPhysicsServer3D *p_physicsServer) { physicsServer = p_physicsServer; } - _FORCE_INLINE_ BulletPhysicsServer3D *get_physics_server() const { return physicsServer; } + // TODO changed to normal method definition for now + // CI complains until we implement this, haven't ported it yet from plugin + // virtual XrCompositionLayerBaseHeader *get_composition_layer() = 0; + XrCompositionLayerBaseHeader *get_composition_layer() { return nullptr; }; }; -#endif // RID_BULLET_H +#endif // OPENXR_COMPOSITION_LAYER_PROVIDER_H diff --git a/modules/openxr/extensions/openxr_extension_wrapper.h b/modules/openxr/extensions/openxr_extension_wrapper.h new file mode 100644 index 0000000000..5242ee6063 --- /dev/null +++ b/modules/openxr/extensions/openxr_extension_wrapper.h @@ -0,0 +1,106 @@ +/*************************************************************************/ +/* openxr_extension_wrapper.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_EXTENSION_WRAPPER_H +#define OPENXR_EXTENSION_WRAPPER_H + +#include "core/error/error_macros.h" +#include "core/math/camera_matrix.h" +#include "core/templates/map.h" +#include "core/templates/rid.h" + +#include "thirdparty/openxr/src/common/xr_linear.h" +#include <openxr/openxr.h> + +class OpenXRAPI; + +class OpenXRExtensionWrapper { +protected: + OpenXRAPI *openxr_api; + + // Store extension we require. + // If bool pointer is a nullptr this means this extension is mandatory and initialisation will fail if it is not available + // If bool pointer is set, value will be set to true or false depending on whether extension is available + Map<const char *, bool *> request_extensions; + +public: + virtual Map<const char *, bool *> get_request_extensions() { + return request_extensions; + } + + // These functions allow an extension to add entries to a struct chain. + // `p_next_pointer` points to the last struct that was created for this chain + // and should be used as the value for the `pNext` pointer in the first struct you add. + // You should return the pointer to the last struct you define as your result. + // If you are not adding any structs, just return `p_next_pointer`. + // See existing extensions for examples of this implementation. + virtual void *set_system_properties_and_get_next_pointer(void *p_next_pointer) { return p_next_pointer; } + virtual void *set_session_create_and_get_next_pointer(void *p_next_pointer) { return p_next_pointer; } + virtual void *set_swapchain_create_info_and_get_next_pointer(void *p_next_pointer) { return p_next_pointer; } + + virtual void on_instance_created(const XrInstance p_instance) {} + virtual void on_instance_destroyed() {} + virtual void on_session_created(const XrSession p_instance) {} + virtual void on_process() {} + virtual void on_pre_render() {} + virtual void on_session_destroyed() {} + + virtual void on_state_idle() {} + virtual void on_state_ready() {} + virtual void on_state_synchronized() {} + virtual void on_state_visible() {} + virtual void on_state_focused() {} + virtual void on_state_stopping() {} + virtual void on_state_loss_pending() {} + virtual void on_state_exiting() {} + + // Returns true if the event was handled, false otherwise. + virtual bool on_event_polled(const XrEventDataBuffer &event) { + return false; + } + + OpenXRExtensionWrapper(OpenXRAPI *p_openxr_api) { openxr_api = p_openxr_api; }; + virtual ~OpenXRExtensionWrapper() = default; +}; + +class OpenXRGraphicsExtensionWrapper : public OpenXRExtensionWrapper { +public: + virtual void get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) = 0; + virtual String get_swapchain_format_name(int64_t p_swapchain_format) const = 0; + virtual bool get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) = 0; + virtual void cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) = 0; + virtual bool create_projection_fov(const XrFovf p_fov, double p_z_near, double p_z_far, CameraMatrix &r_camera_matrix) = 0; + virtual bool copy_render_target_to_image(RID p_from_render_target, void *p_swapchain_graphics_data, int p_image_index) = 0; + + OpenXRGraphicsExtensionWrapper(OpenXRAPI *p_openxr_api) : + OpenXRExtensionWrapper(p_openxr_api){}; +}; + +#endif // ~OPENXR_EXTENSION_WRAPPER_H diff --git a/modules/openxr/extensions/openxr_vulkan_extension.cpp b/modules/openxr/extensions/openxr_vulkan_extension.cpp new file mode 100644 index 0000000000..c7c840fdf3 --- /dev/null +++ b/modules/openxr/extensions/openxr_vulkan_extension.cpp @@ -0,0 +1,750 @@ +/*************************************************************************/ +/* openxr_vulkan_extension.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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/string/print_string.h" + +#include "modules/openxr/extensions/openxr_vulkan_extension.h" +#include "modules/openxr/openxr_api.h" +#include "modules/openxr/openxr_util.h" +#include "servers/rendering/renderer_rd/renderer_storage_rd.h" +#include "servers/rendering/rendering_server_globals.h" +#include "servers/rendering_server.h" + +// need to include Vulkan so we know of type definitions +#define XR_USE_GRAPHICS_API_VULKAN + +#ifdef WINDOWS_ENABLED +// Including windows.h here is absolutely evil, we shouldn't be doing this outside of platform +// however due to the way the openxr headers are put together, we have no choice. +#include <windows.h> +#endif + +// include platform dependent structs +#include <openxr/openxr_platform.h> + +PFN_xrGetVulkanGraphicsRequirements2KHR xrGetVulkanGraphicsRequirements2KHR_ptr = nullptr; +PFN_xrCreateVulkanInstanceKHR xrCreateVulkanInstanceKHR_ptr = nullptr; +PFN_xrGetVulkanGraphicsDevice2KHR xrGetVulkanGraphicsDevice2KHR_ptr = nullptr; +PFN_xrCreateVulkanDeviceKHR xrCreateVulkanDeviceKHR_ptr = nullptr; + +OpenXRVulkanExtension::OpenXRVulkanExtension(OpenXRAPI *p_openxr_api) : + OpenXRGraphicsExtensionWrapper(p_openxr_api) { + VulkanContext::set_vulkan_hooks(this); + + request_extensions[XR_KHR_VULKAN_ENABLE2_EXTENSION_NAME] = nullptr; // must be available + + ERR_FAIL_NULL(openxr_api); +} + +OpenXRVulkanExtension::~OpenXRVulkanExtension() { + VulkanContext::set_vulkan_hooks(nullptr); +} + +void OpenXRVulkanExtension::on_instance_created(const XrInstance p_instance) { + XrResult result; + + ERR_FAIL_NULL(openxr_api); + + // Obtain pointers to functions we're accessing here, they are (not yet) part of core. + result = xrGetInstanceProcAddr(p_instance, "xrGetVulkanGraphicsRequirements2KHR", (PFN_xrVoidFunction *)&xrGetVulkanGraphicsRequirements2KHR_ptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to xrGetVulkanGraphicsRequirements2KHR entry point [", openxr_api->get_error_string(result), "]"); + } + + result = xrGetInstanceProcAddr(p_instance, "xrCreateVulkanInstanceKHR", (PFN_xrVoidFunction *)&xrCreateVulkanInstanceKHR_ptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to xrCreateVulkanInstanceKHR entry point [", openxr_api->get_error_string(result), "]"); + } + + result = xrGetInstanceProcAddr(p_instance, "xrGetVulkanGraphicsDevice2KHR", (PFN_xrVoidFunction *)&xrGetVulkanGraphicsDevice2KHR_ptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to xrGetVulkanGraphicsDevice2KHR entry point [", openxr_api->get_error_string(result), "]"); + } + + result = xrGetInstanceProcAddr(p_instance, "xrCreateVulkanDeviceKHR", (PFN_xrVoidFunction *)&xrCreateVulkanDeviceKHR_ptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to xrCreateVulkanDeviceKHR entry point [", openxr_api->get_error_string(result), "]"); + } +} + +XrResult OpenXRVulkanExtension::xrGetVulkanGraphicsRequirements2KHR(XrInstance p_instance, XrSystemId p_system_id, XrGraphicsRequirementsVulkanKHR *p_graphics_requirements) { + ERR_FAIL_NULL_V(xrGetVulkanGraphicsRequirements2KHR_ptr, XR_ERROR_HANDLE_INVALID); + + return (*xrGetVulkanGraphicsRequirements2KHR_ptr)(p_instance, p_system_id, p_graphics_requirements); +} + +bool OpenXRVulkanExtension::check_graphics_api_support(XrVersion p_desired_version) { + ERR_FAIL_NULL_V(openxr_api, false); + + XrGraphicsRequirementsVulkan2KHR vulkan_requirements = { + XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN2_KHR, // type + nullptr, // next + 0, // minApiVersionSupported + 0 // maxApiVersionSupported + }; + + XrResult result = xrGetVulkanGraphicsRequirements2KHR(openxr_api->get_instance(), openxr_api->get_system_id(), &vulkan_requirements); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get vulkan graphics requirements [", openxr_api->get_error_string(result), "]"); + return false; + } + + // #ifdef DEBUG + print_line("OpenXR: XrGraphicsRequirementsVulkan2KHR:"); + print_line(" - minApiVersionSupported: ", OpenXRUtil::make_xr_version_string(vulkan_requirements.minApiVersionSupported)); + print_line(" - maxApiVersionSupported: ", OpenXRUtil::make_xr_version_string(vulkan_requirements.maxApiVersionSupported)); + // #endif + + if (p_desired_version < vulkan_requirements.minApiVersionSupported) { + print_line("OpenXR: Requested Vulkan version does not meet the minimum version this runtime supports."); + print_line("- desired_version ", OpenXRUtil::make_xr_version_string(p_desired_version)); + print_line("- minApiVersionSupported ", OpenXRUtil::make_xr_version_string(vulkan_requirements.minApiVersionSupported)); + print_line("- maxApiVersionSupported ", OpenXRUtil::make_xr_version_string(vulkan_requirements.maxApiVersionSupported)); + return false; + } + + if (p_desired_version > vulkan_requirements.maxApiVersionSupported) { + print_line("OpenXR: Requested Vulkan version exceeds the maximum version this runtime has been tested on and is known to support."); + print_line("- desired_version ", OpenXRUtil::make_xr_version_string(p_desired_version)); + print_line("- minApiVersionSupported ", OpenXRUtil::make_xr_version_string(vulkan_requirements.minApiVersionSupported)); + print_line("- maxApiVersionSupported ", OpenXRUtil::make_xr_version_string(vulkan_requirements.maxApiVersionSupported)); + } + + return true; +} + +XrResult OpenXRVulkanExtension::xrCreateVulkanInstanceKHR(XrInstance p_instance, const XrVulkanInstanceCreateInfoKHR *p_create_info, VkInstance *r_vulkan_instance, VkResult *r_vulkan_result) { + ERR_FAIL_NULL_V(xrCreateVulkanInstanceKHR_ptr, XR_ERROR_HANDLE_INVALID); + + return (*xrCreateVulkanInstanceKHR_ptr)(p_instance, p_create_info, r_vulkan_instance, r_vulkan_result); +} + +bool OpenXRVulkanExtension::create_vulkan_instance(const VkInstanceCreateInfo *p_vulkan_create_info, VkInstance *r_instance) { + // get the vulkan version we are creating + uint32_t vulkan_version = p_vulkan_create_info->pApplicationInfo->apiVersion; + uint32_t major_version = VK_VERSION_MAJOR(vulkan_version); + uint32_t minor_version = VK_VERSION_MINOR(vulkan_version); + uint32_t patch_version = VK_VERSION_PATCH(vulkan_version); + XrVersion desired_version = XR_MAKE_VERSION(major_version, minor_version, patch_version); + + // check if this is supported + if (!check_graphics_api_support(desired_version)) { + return false; + } + + XrVulkanInstanceCreateInfoKHR xr_vulkan_instance_info = { + XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR, // type + nullptr, // next + openxr_api->get_system_id(), // systemId + 0, // createFlags + vkGetInstanceProcAddr, // pfnGetInstanceProcAddr + p_vulkan_create_info, // vulkanCreateInfo + nullptr, // vulkanAllocator + }; + + VkResult vk_result = VK_SUCCESS; + XrResult result = xrCreateVulkanInstanceKHR(openxr_api->get_instance(), &xr_vulkan_instance_info, &vulkan_instance, &vk_result); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to create vulkan instance [", openxr_api->get_error_string(result), "]"); + return false; + } + + ERR_FAIL_COND_V_MSG(vk_result == VK_ERROR_INCOMPATIBLE_DRIVER, false, + "Cannot find a compatible Vulkan installable client driver (ICD).\n\n" + "vkCreateInstance Failure"); + ERR_FAIL_COND_V_MSG(vk_result == VK_ERROR_EXTENSION_NOT_PRESENT, false, + "Cannot find a specified extension library.\n" + "Make sure your layers path is set appropriately.\n" + "vkCreateInstance Failure"); + ERR_FAIL_COND_V_MSG(vk_result, false, + "vkCreateInstance failed.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n" + "vkCreateInstance Failure"); + + *r_instance = vulkan_instance; + + return true; +} + +XrResult OpenXRVulkanExtension::xrGetVulkanGraphicsDevice2KHR(XrInstance p_instance, const XrVulkanGraphicsDeviceGetInfoKHR *p_get_info, VkPhysicalDevice *r_vulkan_physical_device) { + ERR_FAIL_NULL_V(xrGetVulkanGraphicsDevice2KHR_ptr, XR_ERROR_HANDLE_INVALID); + + return (*xrGetVulkanGraphicsDevice2KHR_ptr)(p_instance, p_get_info, r_vulkan_physical_device); +} + +bool OpenXRVulkanExtension::get_physical_device(VkPhysicalDevice *r_device) { + ERR_FAIL_NULL_V(openxr_api, false); + + XrVulkanGraphicsDeviceGetInfoKHR get_info = { + XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR, // type + nullptr, // next + openxr_api->get_system_id(), // systemId + vulkan_instance, // vulkanInstance + }; + + XrResult result = xrGetVulkanGraphicsDevice2KHR(openxr_api->get_instance(), &get_info, &vulkan_physical_device); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to obtain vulkan physical device [", openxr_api->get_error_string(result), "]"); + return false; + } + + *r_device = vulkan_physical_device; + + return true; +} + +XrResult OpenXRVulkanExtension::xrCreateVulkanDeviceKHR(XrInstance p_instance, const XrVulkanDeviceCreateInfoKHR *p_create_info, VkDevice *r_device, VkResult *r_result) { + ERR_FAIL_NULL_V(xrCreateVulkanDeviceKHR_ptr, XR_ERROR_HANDLE_INVALID); + + return (*xrCreateVulkanDeviceKHR_ptr)(p_instance, p_create_info, r_device, r_result); +} + +bool OpenXRVulkanExtension::create_vulkan_device(const VkDeviceCreateInfo *p_device_create_info, VkDevice *r_device) { + ERR_FAIL_NULL_V(openxr_api, false); + + // the first entry in our queue list should be the one we need to remember... + vulkan_queue_family_index = p_device_create_info->pQueueCreateInfos[0].queueFamilyIndex; + vulkan_queue_index = 0; // ?? + + XrVulkanDeviceCreateInfoKHR create_info = { + XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR, // type + nullptr, // next + openxr_api->get_system_id(), // systemId + 0, // createFlags + vkGetInstanceProcAddr, // pfnGetInstanceProcAddr + vulkan_physical_device, // vulkanPhysicalDevice + p_device_create_info, // vulkanCreateInfo + nullptr // vulkanAllocator + }; + + VkResult vk_result = VK_SUCCESS; + XrResult result = xrCreateVulkanDeviceKHR(openxr_api->get_instance(), &create_info, &vulkan_device, &vk_result); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to create vulkan device [", openxr_api->get_error_string(result), "]"); + return false; + } + + if (vk_result != VK_SUCCESS) { + print_line("OpenXR: Failed to create vulkan device [vulkan error", vk_result, "]"); + } + + *r_device = vulkan_device; + + return true; +} + +XrGraphicsBindingVulkanKHR OpenXRVulkanExtension::graphics_binding_vulkan; + +void *OpenXRVulkanExtension::set_session_create_and_get_next_pointer(void *p_next_pointer) { + graphics_binding_vulkan.type = XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR; + graphics_binding_vulkan.next = p_next_pointer; + graphics_binding_vulkan.instance = vulkan_instance; + graphics_binding_vulkan.physicalDevice = vulkan_physical_device; + graphics_binding_vulkan.device = vulkan_device; + graphics_binding_vulkan.queueFamilyIndex = vulkan_queue_family_index; + graphics_binding_vulkan.queueIndex = vulkan_queue_index; + + return &graphics_binding_vulkan; +} + +void OpenXRVulkanExtension::get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) { + // We might want to do more here especially if we keep things in linear color space + // Possibly add in R10G10B10A2 as an option if we're using the mobile renderer. + p_usable_swap_chains.push_back(VK_FORMAT_R8G8B8A8_SRGB); + p_usable_swap_chains.push_back(VK_FORMAT_B8G8R8A8_SRGB); + p_usable_swap_chains.push_back(VK_FORMAT_R8G8B8A8_UINT); + p_usable_swap_chains.push_back(VK_FORMAT_B8G8R8A8_UINT); +} + +bool OpenXRVulkanExtension::get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) { + XrSwapchainImageVulkanKHR *images = nullptr; + + RenderingServer *rendering_server = RenderingServer::get_singleton(); + ERR_FAIL_NULL_V(rendering_server, false); + RenderingDevice *rendering_device = rendering_server->get_rendering_device(); + ERR_FAIL_NULL_V(rendering_device, false); + + uint32_t swapchain_length; + XrResult result = xrEnumerateSwapchainImages(p_swapchain, 0, &swapchain_length, nullptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get swapchaim image count [", openxr_api->get_error_string(result), "]"); + return false; + } + + images = (XrSwapchainImageVulkanKHR *)memalloc(sizeof(XrSwapchainImageVulkanKHR) * swapchain_length); + ERR_FAIL_NULL_V_MSG(images, false, "OpenXR Couldn't allocate memory for swap chain image"); + + for (uint64_t i = 0; i < swapchain_length; i++) { + images[i].type = XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR; + images[i].next = nullptr; + images[i].image = VK_NULL_HANDLE; + } + + result = xrEnumerateSwapchainImages(p_swapchain, swapchain_length, &swapchain_length, (XrSwapchainImageBaseHeader *)images); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get swapchaim images [", openxr_api->get_error_string(result), "]"); + memfree(images); + return false; + } + + // SwapchainGraphicsData *data = (SwapchainGraphicsData *)memalloc(sizeof(SwapchainGraphicsData)); + SwapchainGraphicsData *data = memnew(SwapchainGraphicsData); + if (data == nullptr) { + print_line("OpenXR: Failed to allocate memory for swapchain data"); + memfree(images); + return false; + } + *r_swapchain_graphics_data = data; + data->is_multiview = (p_array_size > 1); + + RenderingDevice::DataFormat format = RenderingDevice::DATA_FORMAT_R8G8B8A8_SRGB; + RenderingDevice::TextureSamples samples = RenderingDevice::TEXTURE_SAMPLES_1; + uint64_t usage_flags = RenderingDevice::TEXTURE_USAGE_SAMPLING_BIT | RenderingDevice::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; + + switch (p_swapchain_format) { + case VK_FORMAT_R8G8B8A8_SRGB: + // Even though this is an sRGB framebuffer format we're using UNORM here. + // The reason here is because Godot does a linear to sRGB conversion while + // with the sRGB format, this conversion would be doubled by the hardware. + // This also means we're reading the values as is for our preview on screen. + // The OpenXR runtime however is still treating this as an sRGB format and + // will thus do an sRGB -> Linear conversion as expected. + // format = RenderingDevice::DATA_FORMAT_R8G8B8A8_SRGB; + format = RenderingDevice::DATA_FORMAT_R8G8B8A8_UNORM; + break; + case VK_FORMAT_B8G8R8A8_SRGB: + // format = RenderingDevice::DATA_FORMAT_B8G8R8A8_SRGB; + format = RenderingDevice::DATA_FORMAT_B8G8R8A8_UNORM; + break; + case VK_FORMAT_R8G8B8A8_UINT: + format = RenderingDevice::DATA_FORMAT_R8G8B8A8_UINT; + break; + case VK_FORMAT_B8G8R8A8_UINT: + format = RenderingDevice::DATA_FORMAT_B8G8R8A8_UINT; + break; + default: + // continue with our default value + print_line("Unsupported swapchain format ", p_swapchain_format); + break; + } + + switch (p_sample_count) { + case 1: + samples = RenderingDevice::TEXTURE_SAMPLES_1; + break; + case 2: + samples = RenderingDevice::TEXTURE_SAMPLES_2; + break; + case 4: + samples = RenderingDevice::TEXTURE_SAMPLES_4; + break; + case 8: + samples = RenderingDevice::TEXTURE_SAMPLES_8; + break; + case 16: + samples = RenderingDevice::TEXTURE_SAMPLES_16; + break; + case 32: + samples = RenderingDevice::TEXTURE_SAMPLES_32; + break; + case 64: + samples = RenderingDevice::TEXTURE_SAMPLES_64; + break; + default: + // continue with our default value + print_line("Unsupported sample count ", p_sample_count); + break; + } + + Vector<RID> image_rids; + Vector<RID> framebuffers; + + // create Godot texture objects for each entry in our swapchain + for (uint64_t i = 0; i < swapchain_length; i++) { + RID image_rid = rendering_device->texture_create_from_extension( + p_array_size == 1 ? RenderingDevice::TEXTURE_TYPE_2D : RenderingDevice::TEXTURE_TYPE_2D_ARRAY, + format, + samples, + usage_flags, + (uint64_t)images[i].image, + p_width, + p_height, + 1, + p_array_size); + + image_rids.push_back(image_rid); + + { + Vector<RID> fb; + fb.push_back(image_rid); + + RID fb_rid = rendering_device->framebuffer_create(fb, RenderingDevice::INVALID_ID, p_array_size); + framebuffers.push_back(fb_rid); + } + } + + data->image_rids = image_rids; + data->framebuffers = framebuffers; + + memfree(images); + + return true; +} + +bool OpenXRVulkanExtension::create_projection_fov(const XrFovf p_fov, double p_z_near, double p_z_far, CameraMatrix &r_camera_matrix) { + // Even though this is a Vulkan renderer we're using OpenGL coordinate systems + XrMatrix4x4f matrix; + XrMatrix4x4f_CreateProjectionFov(&matrix, GRAPHICS_OPENGL, p_fov, (float)p_z_near, (float)p_z_far); + + for (int j = 0; j < 4; j++) { + for (int i = 0; i < 4; i++) { + r_camera_matrix.matrix[j][i] = matrix.m[j * 4 + i]; + } + } + + return true; +} + +bool OpenXRVulkanExtension::copy_render_target_to_image(RID p_from_render_target, void *p_swapchain_graphics_data, int p_image_index) { + SwapchainGraphicsData *data = (SwapchainGraphicsData *)p_swapchain_graphics_data; + ERR_FAIL_NULL_V(data, false); + ERR_FAIL_COND_V(p_from_render_target.is_null(), false); + ERR_FAIL_NULL_V(RendererStorageRD::base_singleton, false); + + RID source_image = RendererStorageRD::base_singleton->render_target_get_rd_texture(p_from_render_target); + ERR_FAIL_COND_V(source_image.is_null(), false); + + RID depth_image; // TODO implement + + ERR_FAIL_INDEX_V(p_image_index, data->framebuffers.size(), false); + RID fb = data->framebuffers[p_image_index]; + ERR_FAIL_COND_V(fb.is_null(), false); + + // Our vulkan extension can only be used in conjunction with our vulkan renderer. + // We need access to the effects object in order to have access to our copy logic. + // Breaking all the rules but there is no nice way to do this. + EffectsRD *effects = RendererStorageRD::base_singleton->get_effects(); + ERR_FAIL_NULL_V(effects, false); + effects->copy_to_fb_rect(source_image, fb, Rect2i(), false, false, false, false, depth_image, data->is_multiview); + + return true; +} + +void OpenXRVulkanExtension::cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) { + if (*p_swapchain_graphics_data == nullptr) { + return; + } + + SwapchainGraphicsData *data = (SwapchainGraphicsData *)*p_swapchain_graphics_data; + + RenderingServer *rendering_server = RenderingServer::get_singleton(); + ERR_FAIL_NULL(rendering_server); + RenderingDevice *rendering_device = rendering_server->get_rendering_device(); + ERR_FAIL_NULL(rendering_device); + + for (int i = 0; i < data->image_rids.size(); i++) { + // This should clean up our RIDs and associated texture objects but shouldn't destroy the images, they are owned by our XrSwapchain + rendering_device->free(data->image_rids[i]); + } + data->image_rids.clear(); + + for (int i = 0; i < data->framebuffers.size(); i++) { + // This should clean up our RIDs and associated texture objects but shouldn't destroy the images, they are owned by our XrSwapchain + rendering_device->free(data->framebuffers[i]); + } + data->framebuffers.clear(); + + memdelete(data); + *p_swapchain_graphics_data = nullptr; +} + +#define ENUM_TO_STRING_CASE(e) \ + case e: { \ + return String(#e); \ + } break; + +String OpenXRVulkanExtension::get_swapchain_format_name(int64_t p_swapchain_format) const { + // This really should be in vulkan_context... + VkFormat format = VkFormat(p_swapchain_format); + switch (format) { + ENUM_TO_STRING_CASE(VK_FORMAT_UNDEFINED) + ENUM_TO_STRING_CASE(VK_FORMAT_R4G4_UNORM_PACK8) + ENUM_TO_STRING_CASE(VK_FORMAT_R4G4B4A4_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_B4G4R4A4_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R5G6B5_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_B5G6R5_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R5G5B5A1_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_B5G5R5A1_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_A1R5G5B5_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R8_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8_SRGB) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8_SRGB) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8_SRGB) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8_SRGB) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8A8_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8A8_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8A8_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8A8_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8A8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8A8_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R8G8B8A8_SRGB) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8A8_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8A8_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8A8_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8A8_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8A8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8A8_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8A8_SRGB) + ENUM_TO_STRING_CASE(VK_FORMAT_A8B8G8R8_UNORM_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A8B8G8R8_SNORM_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A8B8G8R8_USCALED_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A8B8G8R8_SSCALED_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A8B8G8R8_UINT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A8B8G8R8_SINT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A8B8G8R8_SRGB_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2R10G10B10_UNORM_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2R10G10B10_SNORM_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2R10G10B10_USCALED_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2R10G10B10_SSCALED_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2R10G10B10_UINT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2R10G10B10_SINT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2B10G10R10_UNORM_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2B10G10R10_SNORM_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2B10G10R10_USCALED_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2B10G10R10_SSCALED_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2B10G10R10_UINT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_A2B10G10R10_SINT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_R16_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16A16_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16A16_SNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16A16_USCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16A16_SSCALED) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16A16_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16A16_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R16G16B16A16_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32B32_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32B32_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32B32_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32B32A32_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32B32A32_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R32G32B32A32_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64B64_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64B64_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64B64_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64B64A64_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64B64A64_SINT) + ENUM_TO_STRING_CASE(VK_FORMAT_R64G64B64A64_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_B10G11R11_UFLOAT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_D16_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_X8_D24_UNORM_PACK32) + ENUM_TO_STRING_CASE(VK_FORMAT_D32_SFLOAT) + ENUM_TO_STRING_CASE(VK_FORMAT_S8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_D16_UNORM_S8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_D24_UNORM_S8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_D32_SFLOAT_S8_UINT) + ENUM_TO_STRING_CASE(VK_FORMAT_BC1_RGB_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC1_RGB_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC1_RGBA_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC1_RGBA_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC2_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC2_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC3_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC3_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC4_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC4_SNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC5_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC5_SNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC6H_UFLOAT_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC6H_SFLOAT_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC7_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_BC7_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_EAC_R11_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_EAC_R11_SNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_EAC_R11G11_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_EAC_R11G11_SNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_4x4_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_4x4_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_5x4_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_5x4_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_5x5_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_5x5_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_6x5_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_6x5_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_6x6_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_6x6_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x5_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x5_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x6_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x6_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x8_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x8_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x5_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x5_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x6_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x6_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x8_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x8_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x10_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x10_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_12x10_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_12x10_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_12x12_UNORM_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_12x12_SRGB_BLOCK) + ENUM_TO_STRING_CASE(VK_FORMAT_G8B8G8R8_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_B8G8R8G8_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G8_B8R8_2PLANE_420_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G8_B8R8_2PLANE_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_R10X6_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R10X6G10X6_UNORM_2PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R12X4_UNORM_PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R12X4G12X4_UNORM_2PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16) + ENUM_TO_STRING_CASE(VK_FORMAT_G16B16G16R16_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_B16G16R16G16_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G16_B16R16_2PLANE_420_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G16_B16R16_2PLANE_422_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_G8_B8R8_2PLANE_444_UNORM_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_G10X6_B10X6R10X6_2PLANE_444_UNORM_3PACK16_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_G12X4_B12X4R12X4_2PLANE_444_UNORM_3PACK16_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_G16_B16R16_2PLANE_444_UNORM_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_A4B4G4R4_UNORM_PACK16_EXT) + ENUM_TO_STRING_CASE(VK_FORMAT_MAX_ENUM) + default: { + return String("Swapchain format ") + String::num_int64(int64_t(p_swapchain_format)); + } break; + } +} diff --git a/modules/openxr/extensions/openxr_vulkan_extension.h b/modules/openxr/extensions/openxr_vulkan_extension.h new file mode 100644 index 0000000000..cf55ae264f --- /dev/null +++ b/modules/openxr/extensions/openxr_vulkan_extension.h @@ -0,0 +1,93 @@ +/*************************************************************************/ +/* openxr_vulkan_extension.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_VULKAN_EXTENSION_H +#define OPENXR_VULKAN_EXTENSION_H + +#include "core/templates/vector.h" +#include "openxr_extension_wrapper.h" + +#include "drivers/vulkan/vulkan_context.h" + +// Forward declare these so we don't need OpenXR headers where-ever this is included +// Including OpenXR at this point gives loads and loads of compile issues especially +// on Windows because windows.h is EVIL and really shouldn't be included outside of platform +// but we really don't have a choice in the matter + +struct XrGraphicsRequirementsVulkanKHR; +struct XrVulkanInstanceCreateInfoKHR; +struct XrVulkanGraphicsDeviceGetInfoKHR; +struct XrVulkanDeviceCreateInfoKHR; +struct XrGraphicsBindingVulkanKHR; + +class OpenXRVulkanExtension : public OpenXRGraphicsExtensionWrapper, VulkanHooks { +public: + OpenXRVulkanExtension(OpenXRAPI *p_openxr_api); + virtual ~OpenXRVulkanExtension() override; + + virtual void on_instance_created(const XrInstance p_instance) override; + virtual void *set_session_create_and_get_next_pointer(void *p_next_pointer) override; + + virtual bool create_vulkan_instance(const VkInstanceCreateInfo *p_vulkan_create_info, VkInstance *r_instance) override; + virtual bool get_physical_device(VkPhysicalDevice *r_device) override; + virtual bool create_vulkan_device(const VkDeviceCreateInfo *p_device_create_info, VkDevice *r_device) override; + + virtual void get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) override; + virtual String get_swapchain_format_name(int64_t p_swapchain_format) const override; + virtual bool get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) override; + virtual void cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) override; + virtual bool create_projection_fov(const XrFovf p_fov, double p_z_near, double p_z_far, CameraMatrix &r_camera_matrix) override; + virtual bool copy_render_target_to_image(RID p_from_render_target, void *p_swapchain_graphics_data, int p_image_index) override; + +private: + static OpenXRVulkanExtension *singleton; + static XrGraphicsBindingVulkanKHR graphics_binding_vulkan; // declaring this as static so we don't need to know its size and we only need it once when creating our session + + struct SwapchainGraphicsData { + bool is_multiview; + Vector<RID> image_rids; + Vector<RID> framebuffers; + }; + + bool check_graphics_api_support(XrVersion p_desired_version); + + VkInstance vulkan_instance; + VkPhysicalDevice vulkan_physical_device; + VkDevice vulkan_device; + uint32_t vulkan_queue_family_index; + uint32_t vulkan_queue_index; + + XrResult xrGetVulkanGraphicsRequirements2KHR(XrInstance p_instance, XrSystemId p_system_id, XrGraphicsRequirementsVulkanKHR *p_graphics_requirements); + XrResult xrCreateVulkanInstanceKHR(XrInstance p_instance, const XrVulkanInstanceCreateInfoKHR *p_create_info, VkInstance *r_vulkan_instance, VkResult *r_vulkan_result); + XrResult xrGetVulkanGraphicsDevice2KHR(XrInstance p_instance, const XrVulkanGraphicsDeviceGetInfoKHR *p_get_info, VkPhysicalDevice *r_vulkan_physical_device); + XrResult xrCreateVulkanDeviceKHR(XrInstance p_instance, const XrVulkanDeviceCreateInfoKHR *p_create_info, VkDevice *r_device, VkResult *r_result); +}; + +#endif // !OPENXR_VULKAN_EXTENSION_H diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp new file mode 100644 index 0000000000..4d533337f3 --- /dev/null +++ b/modules/openxr/openxr_api.cpp @@ -0,0 +1,2441 @@ +/*************************************************************************/ +/* openxr_api.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_api.h" +#include "openxr_util.h" + +#include "core/config/engine.h" +#include "core/config/project_settings.h" +#include "core/os/memory.h" +#include "core/version.h" + +#ifdef TOOLS_ENABLED +#include "editor/editor_settings.h" +#endif + +#ifdef ANDROID_ENABLED +#include "extensions/openxr_android_extension.h" +#endif + +#ifdef VULKAN_ENABLED +#include "extensions/openxr_vulkan_extension.h" +#endif + +#include "modules/openxr/openxr_interface.h" + +OpenXRAPI *OpenXRAPI::singleton = nullptr; + +void OpenXRAPI::setup_global_defs() { + // As OpenXRAPI is not constructed if OpenXR is not enabled, we register our project and editor settings here + + // Project settings + GLOBAL_DEF_BASIC("xr/openxr/enabled", false); + GLOBAL_DEF_BASIC("xr/openxr/default_action_map", "res://default_action_map.tres"); + ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/default_action_map", PropertyInfo(Variant::STRING, "xr/openxr/default_action_map", PROPERTY_HINT_FILE, "*.tres")); + + GLOBAL_DEF_BASIC("xr/openxr/form_factor", "0"); + ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/form_factor", PropertyInfo(Variant::INT, "xr/openxr/form_factor", PROPERTY_HINT_ENUM, "Head mounted,Handheld")); + + GLOBAL_DEF_BASIC("xr/openxr/view_configuration", "1"); + ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/view_configuration", PropertyInfo(Variant::INT, "xr/openxr/view_configuration", PROPERTY_HINT_ENUM, "Mono,Stereo")); // "Mono,Stereo,Quad,Observer" + + GLOBAL_DEF_BASIC("xr/openxr/reference_space", "1"); + ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/reference_space", PropertyInfo(Variant::INT, "xr/openxr/reference_space", PROPERTY_HINT_ENUM, "Local,Stage")); + +#ifdef TOOLS_ENABLED + // Disabled for now, using XR inside of the editor we'll be working on during the coming months. + + // editor settings (it seems we're too early in the process when setting up rendering, to access editor settings...) + // EDITOR_DEF_RST("xr/openxr/in_editor", false); + // GLOBAL_DEF("xr/openxr/in_editor", false); +#endif +} + +bool OpenXRAPI::openxr_is_enabled() { + // @TODO we need an overrule switch so we can force enable openxr, i.e run "godot --openxr_enabled" + + if (Engine::get_singleton()->is_editor_hint()) { +#ifdef TOOLS_ENABLED + // Disabled for now, using XR inside of the editor we'll be working on during the coming months. + return false; + + // bool enabled = GLOBAL_GET("xr/openxr/in_editor"); // EDITOR_GET("xr/openxr/in_editor"); + // return enabled; +#else + // we should never get here, editor hint won't be true if the editor isn't compiled in. + return false; +#endif + } else { + bool enabled = GLOBAL_GET("xr/openxr/enabled"); + return enabled; + } +} + +OpenXRAPI *OpenXRAPI::get_singleton() { + if (singleton != nullptr) { + // already constructed, return our singleton + return singleton; + } else if (openxr_is_enabled()) { + // construct our singleton and return it + singleton = memnew(OpenXRAPI); + return singleton; + } else { + // not enabled, don't instantiate, return nullptr + return nullptr; + } +} + +String OpenXRAPI::get_default_action_map_resource_name() { + String name = GLOBAL_GET("xr/openxr/default_action_map"); + + return name; +} + +String OpenXRAPI::get_error_string(XrResult result) { + if (XR_SUCCEEDED(result)) { + return String("Succeeded"); + } + + if (instance == XR_NULL_HANDLE) { + Array args; + args.push_back(Variant(result)); + return String("Error code {0}").format(args); + } + + char resultString[XR_MAX_RESULT_STRING_SIZE]; + xrResultToString(instance, result, resultString); + + return String(resultString); +} + +String OpenXRAPI::get_swapchain_format_name(int64_t p_swapchain_format) const { + // This is rendering engine dependend... + if (graphics_extension) { + return graphics_extension->get_swapchain_format_name(p_swapchain_format); + } + + return String("Swapchain format ") + String::num_int64(int64_t(p_swapchain_format)); +} + +bool OpenXRAPI::load_layer_properties() { + // This queries additional layers that are available and can be initialised when we create our OpenXR instance + if (layer_properties != nullptr) { + // already retrieved this + return true; + } + + // Note, instance is not yet setup so we can't use get_error_string to retrieve our error + XrResult result = xrEnumerateApiLayerProperties(0, &num_layer_properties, nullptr); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of api layer properties"); + + layer_properties = (XrApiLayerProperties *)memalloc(sizeof(XrApiLayerProperties) * num_layer_properties); + ERR_FAIL_NULL_V(layer_properties, false); + for (uint32_t i = 0; i < num_layer_properties; i++) { + layer_properties[i].type = XR_TYPE_API_LAYER_PROPERTIES; + layer_properties[i].next = nullptr; + } + + result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties"); + +#ifdef DEBUG + for (uint32_t i = 0; i < num_layer_properties; i++) { + print_line("OpenXR: Found OpenXR layer ", layer_properties[i].layerName); + } +#endif + + return true; +} + +bool OpenXRAPI::load_supported_extensions() { + // This queries supported extensions that are available and can be initialised when we create our OpenXR instance + + if (supported_extensions != nullptr) { + // already retrieved this + return true; + } + + // Note, instance is not yet setup so we can't use get_error_string to retrieve our error + XrResult result = xrEnumerateInstanceExtensionProperties(nullptr, 0, &num_supported_extensions, nullptr); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of extension properties"); + + supported_extensions = (XrExtensionProperties *)memalloc(sizeof(XrExtensionProperties) * num_supported_extensions); + ERR_FAIL_NULL_V(supported_extensions, false); + + // set our types + for (uint32_t i = 0; i < num_supported_extensions; i++) { + supported_extensions[i].type = XR_TYPE_EXTENSION_PROPERTIES; + supported_extensions[i].next = nullptr; + } + result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties"); + +#ifdef DEBUG + for (uint32_t i = 0; i < num_supported_extensions; i++) { + print_line("OpenXR: Found OpenXR extension ", supported_extensions[i].extensionName); + } +#endif + + return true; +} + +bool OpenXRAPI::is_extension_supported(const char *p_extension) const { + for (uint32_t i = 0; i < num_supported_extensions; i++) { + if (strcmp(supported_extensions[i].extensionName, p_extension)) { + return true; + } + } + + return false; +} + +void OpenXRAPI::copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len) { + CharString char_string = p_string.utf8(); + int len = char_string.length(); + if (len < p_buffer_len - 1) { + // was having weird CI issues with strcpy so.... + memcpy(p_buffer, char_string.get_data(), len); + p_buffer[len] = '\0'; + } else { + memcpy(p_buffer, char_string.get_data(), p_buffer_len - 1); + p_buffer[p_buffer_len - 1] = '\0'; + } +} + +bool OpenXRAPI::create_instance() { + // Create our OpenXR instance, this will query any registered extension wrappers for extensions we need to enable. + + // Append the extensions requested by the registered extension wrappers. + Map<const char *, bool *> requested_extensions; + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + Map<const char *, bool *> wrapper_request_extensions = wrapper->get_request_extensions(); + + // requested_extensions.insert(wrapper_request_extensions.begin(), wrapper_request_extensions.end()); + for (auto &requested_extension : wrapper_request_extensions) { + requested_extensions[requested_extension.key] = requested_extension.value; + } + } + + // Check which extensions are supported + enabled_extensions.clear(); + for (auto &requested_extension : requested_extensions) { + if (!is_extension_supported(requested_extension.key)) { + if (requested_extension.value == nullptr) { + // nullptr means this is a manditory extension so we fail + ERR_FAIL_V_MSG(false, "OpenXR: OpenXR Runtime does not support OpenGL extension!"); + } else { + // set this extension as not supported + *requested_extension.value = false; + } + } else if (requested_extension.value != nullptr) { + // set this extension as supported + *requested_extension.value = true; + + // and record that we want to enable it + enabled_extensions.push_back(requested_extension.key); + } else { + // record that we want to enable this + enabled_extensions.push_back(requested_extension.key); + } + } + + // Get our project name + String project_name = GLOBAL_GET("application/config/name"); + + // Create our OpenXR instance + XrApplicationInfo application_info{ + "", // applicationName, we'll set this down below + 1, // applicationVersion, we don't currently have this + "Godot Game Engine", // engineName + VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH, // engineVersion 4.0 -> 40000, 4.0.1 -> 40001, 4.1 -> 40100, etc. + XR_CURRENT_API_VERSION // apiVersion + }; + + XrInstanceCreateInfo instance_create_info = { + XR_TYPE_INSTANCE_CREATE_INFO, // type + nullptr, // next + 0, // createFlags + application_info, // applicationInfo + 0, // enabledApiLayerCount, need to find out if we need support for this? + nullptr, // enabledApiLayerNames + uint32_t(enabled_extensions.size()), // enabledExtensionCount + enabled_extensions.ptr() // enabledExtensionNames + }; + + copy_string_to_char_buffer(project_name, instance_create_info.applicationInfo.applicationName, XR_MAX_APPLICATION_NAME_SIZE); + + XrResult result = xrCreateInstance(&instance_create_info, &instance); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed to create XR instance."); + + // from this point on we can use get_error_string to get more info about our errors... + + XrInstanceProperties instanceProps = { + XR_TYPE_INSTANCE_PROPERTIES, // type; + nullptr, // next + 0, // runtimeVersion, from here will be set by our get call + "" // runtimeName + }; + result = xrGetInstanceProperties(instance, &instanceProps); + if (XR_FAILED(result)) { + // not fatal probably + print_line("OpenXR: Failed to get XR instance properties [", get_error_string(result), "]"); + } else { + print_line("OpenXR: Running on OpenXR runtime: ", instanceProps.runtimeName, " ", OpenXRUtil::make_xr_version_string(instanceProps.runtimeVersion)); + } + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_instance_created(instance); + } + + return true; +} + +bool OpenXRAPI::get_system_info() { + // Retrieve basic OpenXR system info based on the form factor we desire + + // Retrieve the system for our form factor, fails if form factor is not available + XrSystemGetInfo system_get_info = { + XR_TYPE_SYSTEM_GET_INFO, // type; + nullptr, // next + form_factor // formFactor + }; + + XrResult result = xrGetSystem(instance, &system_get_info, &system_id); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get system for our form factor [", get_error_string(result), "]"); + return false; + } + + // obtain info about our system, writing this out completely to make CI on Linux happy.. + void *next_pointer = nullptr; + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + void *np = wrapper->set_system_properties_and_get_next_pointer(next_pointer); + if (np != nullptr) { + next_pointer = np; + } + } + + XrSystemProperties system_properties = { + XR_TYPE_SYSTEM_PROPERTIES, // type + next_pointer, // next + 0, // systemId, from here will be set by our get call + 0, // vendorId + "", // systemName + { + 0, // maxSwapchainImageHeight + 0, // maxSwapchainImageWidth + 0, // maxLayerCount + }, // graphicsProperties + { + false, // orientationTracking + false // positionTracking + } // trackingProperties + }; + + result = xrGetSystemProperties(instance, system_id, &system_properties); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get System properties [", get_error_string(result), "]"); + return false; + } + + // remember this state, we'll use it later + system_name = String(system_properties.systemName); + vendor_id = system_properties.vendorId; + graphics_properties = system_properties.graphicsProperties; + tracking_properties = system_properties.trackingProperties; + + return true; +} + +bool OpenXRAPI::load_supported_view_configuration_types() { + // This queries the supported configuration types, likely there will only be one chosing between Mono (phone AR) and Stereo (HMDs) + + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false); + + if (supported_view_configuration_types != nullptr) { + // free previous results + memfree(supported_view_configuration_types); + supported_view_configuration_types = nullptr; + } + + XrResult result = xrEnumerateViewConfigurations(instance, system_id, 0, &num_view_configuration_types, nullptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]"); + return false; + } + + supported_view_configuration_types = (XrViewConfigurationType *)memalloc(sizeof(XrViewConfigurationType) * num_view_configuration_types); + ERR_FAIL_NULL_V(supported_view_configuration_types, false); + + result = xrEnumerateViewConfigurations(instance, system_id, num_view_configuration_types, &num_view_configuration_types, supported_view_configuration_types); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerateview configurations"); + +#ifdef DEBUG + for (uint32_t i = 0; i < num_view_configuration_types; i++) { + print_line("OpenXR: Found supported view configuration ", OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i])); + } +#endif + + return true; +} + +bool OpenXRAPI::is_view_configuration_supported(XrViewConfigurationType p_configuration_type) const { + ERR_FAIL_NULL_V(supported_view_configuration_types, false); + + for (uint32_t i = 0; i < num_view_configuration_types; i++) { + if (supported_view_configuration_types[i] == p_configuration_type) { + return true; + } + } + + return false; +} + +bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType p_configuration_type) { + // This loads our view configuration for each view so for a stereo HMD, we'll get two entries (that are likely identical) + // The returned data supplies us with the recommended render target size + + if (!is_view_configuration_supported(p_configuration_type)) { + print_line("OpenXR: View configuration ", OpenXRUtil::get_view_configuration_name(view_configuration), " is not supported."); + return false; + } + + if (view_configuration_views != nullptr) { + // free previous results + memfree(view_configuration_views); + view_configuration_views = nullptr; + } + + XrResult result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, 0, &view_count, nullptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]"); + return false; + } + + view_configuration_views = (XrViewConfigurationView *)memalloc(sizeof(XrViewConfigurationView) * view_count); + ERR_FAIL_NULL_V(view_configuration_views, false); + + for (uint32_t i = 0; i < view_count; i++) { + view_configuration_views[i].type = XR_TYPE_VIEW_CONFIGURATION_VIEW; + view_configuration_views[i].next = NULL; + } + + result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate view configurations"); + +#ifdef DEBUG + for (uint32_t i = 0; i < view_count; i++) { + print_line("OpenXR: Found supported view configuration view"); + print_line(" - width: ", view_configuration_views[i].maxImageRectWidth); + print_line(" - height: ", view_configuration_views[i].maxImageRectHeight); + print_line(" - sample count: ", view_configuration_views[i].maxSwapchainSampleCount); + print_line(" - recommended render width: ", view_configuration_views[i].recommendedImageRectWidth); + print_line(" - recommended render height: ", view_configuration_views[i].recommendedImageRectHeight); + print_line(" - recommended render sample count: ", view_configuration_views[i].recommendedSwapchainSampleCount); + } +#endif + + return true; +} + +void OpenXRAPI::destroy_instance() { + if (view_configuration_views != nullptr) { + memfree(view_configuration_views); + view_configuration_views = nullptr; + } + + if (supported_view_configuration_types != nullptr) { + memfree(supported_view_configuration_types); + supported_view_configuration_types = nullptr; + } + + if (instance != XR_NULL_HANDLE) { + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_instance_destroyed(); + } + + xrDestroyInstance(instance); + instance = XR_NULL_HANDLE; + } + enabled_extensions.clear(); +} + +bool OpenXRAPI::create_session() { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false); + ERR_FAIL_COND_V(session != XR_NULL_HANDLE, false); + + void *next_pointer = nullptr; + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + void *np = wrapper->set_session_create_and_get_next_pointer(next_pointer); + if (np != nullptr) { + next_pointer = np; + } + } + + XrSessionCreateInfo session_create_info = { + XR_TYPE_SESSION_CREATE_INFO, // type + next_pointer, // next + 0, // createFlags + system_id // systemId + }; + + XrResult result = xrCreateSession(instance, &session_create_info, &session); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to create session [", get_error_string(result), "]"); + return false; + } + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_session_created(session); + } + + return true; +} + +bool OpenXRAPI::load_supported_reference_spaces() { + // loads the supported reference spaces for our OpenXR session + + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + + if (supported_reference_spaces != nullptr) { + // free previous results + memfree(supported_reference_spaces); + supported_reference_spaces = nullptr; + } + + XrResult result = xrEnumerateReferenceSpaces(session, 0, &num_reference_spaces, nullptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get reference space count [", get_error_string(result), "]"); + return false; + } + + supported_reference_spaces = (XrReferenceSpaceType *)memalloc(sizeof(XrReferenceSpaceType) * num_reference_spaces); + ERR_FAIL_NULL_V(supported_reference_spaces, false); + + result = xrEnumerateReferenceSpaces(session, num_reference_spaces, &num_reference_spaces, supported_reference_spaces); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate reference spaces"); + + // #ifdef DEBUG + for (uint32_t i = 0; i < num_reference_spaces; i++) { + print_line("OpenXR: Found supported reference space ", OpenXRUtil::get_reference_space_name(supported_reference_spaces[i])); + } + // #endif + + return true; +} + +bool OpenXRAPI::is_reference_space_supported(XrReferenceSpaceType p_reference_space) { + ERR_FAIL_NULL_V(supported_reference_spaces, false); + + for (uint32_t i = 0; i < num_reference_spaces; i++) { + if (supported_reference_spaces[i] == p_reference_space) { + return true; + } + } + + return false; +} + +bool OpenXRAPI::setup_spaces() { + XrResult result; + + XrPosef identityPose = { + { 0.0, 0.0, 0.0, 1.0 }, + { 0.0, 0.0, 0.0 } + }; + + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + + // create play space + { + if (!is_reference_space_supported(reference_space)) { + print_line("OpenXR: reference space ", OpenXRUtil::get_reference_space_name(reference_space), " is not supported."); + return false; + } + + XrReferenceSpaceCreateInfo play_space_create_info = { + XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type + nullptr, // next + reference_space, // referenceSpaceType + identityPose // poseInReferenceSpace + }; + + result = xrCreateReferenceSpace(session, &play_space_create_info, &play_space); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to create play space [", get_error_string(result), "]"); + return false; + } + } + + // create view space + { + if (!is_reference_space_supported(XR_REFERENCE_SPACE_TYPE_VIEW)) { + print_line("OpenXR: reference space XR_REFERENCE_SPACE_TYPE_VIEW is not supported."); + return false; + } + + XrReferenceSpaceCreateInfo view_space_create_info = { + XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type + nullptr, // next + XR_REFERENCE_SPACE_TYPE_VIEW, // referenceSpaceType + identityPose // poseInReferenceSpace + }; + + result = xrCreateReferenceSpace(session, &view_space_create_info, &view_space); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to create view space [", get_error_string(result), "]"); + return false; + } + } + + return true; +} + +bool OpenXRAPI::load_supported_swapchain_formats() { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + + if (supported_swapchain_formats != nullptr) { + // free previous results + memfree(supported_swapchain_formats); + supported_swapchain_formats = nullptr; + } + + XrResult result = xrEnumerateSwapchainFormats(session, 0, &num_swapchain_formats, nullptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get swapchain format count [", get_error_string(result), "]"); + return false; + } + + supported_swapchain_formats = (int64_t *)memalloc(sizeof(int64_t) * num_swapchain_formats); + ERR_FAIL_NULL_V(supported_swapchain_formats, false); + + result = xrEnumerateSwapchainFormats(session, num_swapchain_formats, &num_swapchain_formats, supported_swapchain_formats); + ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate swapchain formats"); + + // #ifdef DEBUG + for (uint32_t i = 0; i < num_swapchain_formats; i++) { + print_line("OpenXR: Found supported swapchain format ", get_swapchain_format_name(supported_swapchain_formats[i])); + } + // #endif + + return true; +} + +bool OpenXRAPI::is_swapchain_format_supported(int64_t p_swapchain_format) { + ERR_FAIL_NULL_V(supported_swapchain_formats, false); + + for (uint32_t i = 0; i < num_swapchain_formats; i++) { + if (supported_swapchain_formats[i] == p_swapchain_format) { + return true; + } + } + + return false; +} + +bool OpenXRAPI::create_main_swapchain() { + ERR_FAIL_NULL_V(graphics_extension, false); + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + + /* + TODO: We need to improve on this, for now we're taking our old approach of creating our main swapchains and substituting + those for the ones Godot normally creates. + This however means we can only use swapchains for our main XR view. + + It would have been nicer if we could override the swapchain creation in Godot with ours but we have a timing issue here. + We can't create XR swapchains until after our XR session is fully instantiated, yet Godot creates its swapchain much earlier. + + Also Godot only creates a swapchain for the main output. + OpenXR will require us to create swapchains as the render target for additional viewports if we want to use the layer system + to optimise text rendering and background rendering as OpenXR may choose to re-use the results for reprojection while we're + already rendering the next frame. + + Finally an area we need to expand upon is that Foveated rendering is only enabled for the swap chain we create, + as we render 3D content into internal buffers that are copied into the swapchain, we don't get any of the performance gains + until such time as we implement VRS. + */ + + // Build a vector with swapchain formats we want to use, from best fit to worst + Vector<int64_t> usable_swapchain_formats; + int64_t swapchain_format_to_use = 0; + + graphics_extension->get_usable_swapchain_formats(usable_swapchain_formats); + + // now find out which one is supported + for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) { + if (is_swapchain_format_supported(usable_swapchain_formats[i])) { + swapchain_format_to_use = usable_swapchain_formats[i]; + } + } + + if (swapchain_format_to_use == 0) { + swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best... + print_line("Couldn't find usable swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead."); + } else { + print_line("Using swap chain format:", get_swapchain_format_name(swapchain_format_to_use)); + } + + Size2 recommended_size = get_recommended_target_size(); + + if (!create_swapchain(swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchain, &swapchain_graphics_data)) { + return false; + } + + views = (XrView *)memalloc(sizeof(XrView) * view_count); + ERR_FAIL_NULL_V_MSG(views, false, "OpenXR Couldn't allocate memory for views"); + + projection_views = (XrCompositionLayerProjectionView *)memalloc(sizeof(XrCompositionLayerProjectionView) * view_count); + ERR_FAIL_NULL_V_MSG(projection_views, false, "OpenXR Couldn't allocate memory for projection views"); + + for (uint32_t i = 0; i < view_count; i++) { + views[i].type = XR_TYPE_VIEW; + views[i].next = NULL; + + projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW; + projection_views[i].next = NULL; + projection_views[i].subImage.swapchain = swapchain; + projection_views[i].subImage.imageArrayIndex = i; + projection_views[i].subImage.imageRect.offset.x = 0; + projection_views[i].subImage.imageRect.offset.y = 0; + projection_views[i].subImage.imageRect.extent.width = recommended_size.width; + projection_views[i].subImage.imageRect.extent.height = recommended_size.height; + }; + + return true; +}; + +void OpenXRAPI::destroy_session() { + if (running && session != XR_NULL_HANDLE) { + xrEndSession(session); + } + + if (graphics_extension) { + graphics_extension->cleanup_swapchain_graphics_data(&swapchain_graphics_data); + } + + if (views != nullptr) { + memfree(views); + views = nullptr; + } + + if (projection_views != nullptr) { + memfree(projection_views); + projection_views = nullptr; + } + + if (swapchain != XR_NULL_HANDLE) { + xrDestroySwapchain(swapchain); + swapchain = XR_NULL_HANDLE; + } + + if (supported_swapchain_formats != nullptr) { + memfree(supported_swapchain_formats); + supported_swapchain_formats = nullptr; + } + + // destroy our spaces + if (play_space != XR_NULL_HANDLE) { + xrDestroySpace(play_space); + play_space = XR_NULL_HANDLE; + } + if (view_space != XR_NULL_HANDLE) { + xrDestroySpace(view_space); + view_space = XR_NULL_HANDLE; + } + + if (supported_reference_spaces != nullptr) { + // free previous results + memfree(supported_reference_spaces); + supported_reference_spaces = nullptr; + } + + if (session != XR_NULL_HANDLE) { + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_session_destroyed(); + } + + xrDestroySession(session); + session = XR_NULL_HANDLE; + } +} + +bool OpenXRAPI::create_swapchain(int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data) { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + ERR_FAIL_NULL_V(graphics_extension, false); + + XrResult result; + + void *next_pointer = nullptr; + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + void *np = wrapper->set_swapchain_create_info_and_get_next_pointer(next_pointer); + if (np != nullptr) { + next_pointer = np; + } + } + + XrSwapchainCreateInfo swapchain_create_info = { + XR_TYPE_SWAPCHAIN_CREATE_INFO, // type + next_pointer, // next + 0, // createFlags + XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, // usageFlags + p_swapchain_format, // format + p_sample_count, // sampleCount + p_width, // width + p_height, // height + 1, // faceCount + p_array_size, // arraySize + 1 // mipCount + }; + + XrSwapchain new_swapchain; + result = xrCreateSwapchain(session, &swapchain_create_info, &new_swapchain); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get swapchain [", get_error_string(result), "]"); + return false; + } + + if (!graphics_extension->get_swapchain_image_data(new_swapchain, p_swapchain_format, p_width, p_height, p_sample_count, p_array_size, r_swapchain_graphics_data)) { + xrDestroySwapchain(new_swapchain); + return false; + } + + r_swapchain = new_swapchain; + + return true; +} + +bool OpenXRAPI::on_state_idle() { +#ifdef DEBUG + print_line("On state idle"); +#endif + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_idle(); + } + + return true; +} + +bool OpenXRAPI::on_state_ready() { +#ifdef DEBUG + print_line("On state ready"); +#endif + + // begin session + XrSessionBeginInfo session_begin_info = { + XR_TYPE_SESSION_BEGIN_INFO, // type + nullptr, // next + view_configuration // primaryViewConfigurationType + }; + + XrResult result = xrBeginSession(session, &session_begin_info); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to begin session [", get_error_string(result), "]"); + return false; + } + + // This is when we create our swapchain, this can be a "long" time after Godot finishes, we can deal with this for now + // but once we want to provide Viewports for additional layers where OpenXR requires us to create further swapchains, + // we'll be creating those viewport WAY before we reach this point. + // We may need to implement a wait in our init in main.cpp polling our events until the session is ready. + // That will be very very ugly + // The other possibility is to create a separate OpenXRViewport type specifically for this goal as part of our OpenXR module + + if (!create_main_swapchain()) { + return false; + } + + // we're running + running = true; + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_ready(); + } + + if (xr_interface) { + xr_interface->on_state_ready(); + } + + // TODO Tell android + + return true; +} + +bool OpenXRAPI::on_state_synchronized() { +#ifdef DEBUG + print_line("On state synchronized"); +#endif + + // Just in case, see if we already have active trackers... + List<RID> trackers; + tracker_owner.get_owned_list(&trackers); + for (int i = 0; i < trackers.size(); i++) { + tracker_check_profile(trackers[i]); + } + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_synchronized(); + } + + return true; +} + +bool OpenXRAPI::on_state_visible() { +#ifdef DEBUG + print_line("On state visible"); +#endif + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_visible(); + } + + if (xr_interface) { + xr_interface->on_state_visible(); + } + + return true; +} + +bool OpenXRAPI::on_state_focused() { +#ifdef DEBUG + print_line("On state focused"); +#endif + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_focused(); + } + + if (xr_interface) { + xr_interface->on_state_focused(); + } + + return true; +} + +bool OpenXRAPI::on_state_stopping() { +#ifdef DEBUG + print_line("On state stopping"); +#endif + + if (xr_interface) { + xr_interface->on_state_stopping(); + } + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_stopping(); + } + + if (running) { + XrResult result = xrEndSession(session); + if (XR_FAILED(result)) { + // we only report this.. + print_line("OpenXR: Failed to end session [", get_error_string(result), "]"); + } + + running = false; + } + + // TODO further cleanup + + return true; +} + +bool OpenXRAPI::on_state_loss_pending() { +#ifdef DEBUG + print_line("On state loss pending"); +#endif + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_loss_pending(); + } + + // TODO need to look into the correct action here, read up on the spec but we may need to signal Godot to exit (if it's not already exiting) + + return true; +} + +bool OpenXRAPI::on_state_exiting() { +#ifdef DEBUG + print_line("On state existing"); +#endif + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_state_exiting(); + } + + // TODO need to look into the correct action here, read up on the spec but we may need to signal Godot to exit (if it's not already exiting) + + return true; +} + +bool OpenXRAPI::is_initialized() { + return (instance != XR_NULL_HANDLE); +} + +bool OpenXRAPI::is_running() { + if (instance == XR_NULL_HANDLE) { + return false; + } + if (session == XR_NULL_HANDLE) { + return false; + } + + return running; +} + +bool OpenXRAPI::initialise(const String &p_rendering_driver) { + ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created"); + + if (p_rendering_driver == "vulkan") { +#ifdef VULKAN_ENABLED + graphics_extension = memnew(OpenXRVulkanExtension(this)); + register_extension_wrapper(graphics_extension); +#else + // shouldn't be possible... + ERR_FAIL_V(false); +#endif + } else if (p_rendering_driver == "opengl3") { +#ifdef OPENGL3_ENABLED + // graphics_extension = memnew(OpenXROpenGLExtension(this)); + // register_extension_wrapper(graphics_extension); + ERR_FAIL_V_MSG(false, "OpenXR: OpenGL is not supported at this time."); +#else + // shouldn't be possible... + ERR_FAIL_V(false); +#endif + } else { + ERR_FAIL_V_MSG(false, "OpenXR: Unsupported rendering device."); + } + + // initialise + if (!load_layer_properties()) { + destroy_instance(); + return false; + } + + if (!load_supported_extensions()) { + destroy_instance(); + return false; + } + + if (!create_instance()) { + destroy_instance(); + return false; + } + + if (!get_system_info()) { + destroy_instance(); + return false; + } + + if (!load_supported_view_configuration_types()) { + destroy_instance(); + return false; + } + + if (!load_supported_view_configuration_views(view_configuration)) { + destroy_instance(); + return false; + } + + return true; +} + +bool OpenXRAPI::initialise_session() { + if (!create_session()) { + destroy_session(); + return false; + } + + if (!load_supported_reference_spaces()) { + destroy_session(); + return false; + } + + if (!setup_spaces()) { + destroy_session(); + return false; + } + + if (!load_supported_swapchain_formats()) { + destroy_session(); + return false; + } + + return true; +} + +void OpenXRAPI::finish() { + destroy_session(); + + destroy_instance(); +} + +void OpenXRAPI::set_xr_interface(OpenXRInterface *p_xr_interface) { + xr_interface = p_xr_interface; +} + +void OpenXRAPI::register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) { + registered_extension_wrappers.push_back(p_extension_wrapper); +} + +Size2 OpenXRAPI::get_recommended_target_size() { + ERR_FAIL_NULL_V(view_configuration_views, Size2()); + + Size2 target_size; + + target_size.width = view_configuration_views[0].recommendedImageRectWidth; + target_size.height = view_configuration_views[0].recommendedImageRectHeight; + + return target_size; +} + +XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) { + XrResult result; + + ERR_FAIL_COND_V(!running, XRPose::XR_TRACKING_CONFIDENCE_NONE); + + // xrWaitFrame not run yet + if (frame_state.predictedDisplayTime == 0) { + return XRPose::XR_TRACKING_CONFIDENCE_NONE; + } + + // Get timing for the next frame, as that is the current frame we're processing + XrTime display_time = get_next_frame_time(); + + XrSpaceVelocity velocity = { + XR_TYPE_SPACE_VELOCITY, // type + nullptr, // next + 0, // velocityFlags + { 0.0, 0.0, 0.0 }, // linearVelocity + { 0.0, 0.0, 0.0 } // angularVelocity + }; + + XrSpaceLocation location = { + XR_TYPE_SPACE_LOCATION, // type + &velocity, // next + 0, // locationFlags + { + { 0.0, 0.0, 0.0, 0.0 }, // orientation + { 0.0, 0.0, 0.0 } // position + } // pose + }; + + result = xrLocateSpace(view_space, play_space, display_time, &location); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to locate view space in play space [", get_error_string(result), "]"); + return XRPose::XR_TRACKING_CONFIDENCE_NONE; + } + + XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform); + parse_velocities(velocity, r_linear_velocity, r_angular_velocity); + + if (head_pose_confidence != confidence) { + // prevent error spam + head_pose_confidence = confidence; + if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) { + print_line("OpenXR head space location not valid (check tracking?)"); +#ifdef DEBUG + } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) { + print_line("OpenVR Head pose now tracking with low confidence"); + } else { + print_line("OpenVR Head pose now tracking with high confidence"); +#endif + } + } + + return confidence; +} + +bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) { + ERR_FAIL_COND_V(!running, false); + + // xrWaitFrame not run yet + if (frame_state.predictedDisplayTime == 0) { + return false; + } + + // we don't have valid view info + if (views == NULL || !view_pose_valid) { + return false; + } + + // Note, the timing of this is set right before rendering, which is what we need here. + r_transform = transform_from_pose(views[p_view].pose); + + return true; +} + +bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, CameraMatrix &p_camera_matrix) { + ERR_FAIL_COND_V(!running, false); + ERR_FAIL_NULL_V(graphics_extension, false); + + // xrWaitFrame not run yet + if (frame_state.predictedDisplayTime == 0) { + return false; + } + + // we don't have valid view info + if (views == NULL || !view_pose_valid) { + return false; + } + + return graphics_extension->create_projection_fov(views[p_view].fov, p_z_near, p_z_far, p_camera_matrix); +} + +bool OpenXRAPI::poll_events() { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false); + + XrEventDataBuffer runtimeEvent; + runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER; + runtimeEvent.next = nullptr; + // runtimeEvent.varying = ... + + XrResult pollResult = xrPollEvent(instance, &runtimeEvent); + while (pollResult == XR_SUCCESS) { + bool handled = false; + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + handled |= wrapper->on_event_polled(runtimeEvent); + } + switch (runtimeEvent.type) { + case XR_TYPE_EVENT_DATA_EVENTS_LOST: { + XrEventDataEventsLost *event = (XrEventDataEventsLost *)&runtimeEvent; + + // We probably didn't poll fast enough, just output warning + WARN_PRINT("OpenXR EVENT: " + itos(event->lostEventCount) + " event data lost!"); + } break; + case XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR: { + // XrEventDataVisibilityMaskChangedKHR *event = (XrEventDataVisibilityMaskChangedKHR *)&runtimeEvent; + + // TODO implement this in the future, we should call xrGetVisibilityMaskKHR to obtain a mask, + // this will allow us to prevent rendering the part of our view which is never displayed giving us + // a decent performance improvement. + + print_verbose("OpenXR EVENT: STUB: visibility mask changed"); + } break; + case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: { + XrEventDataInstanceLossPending *event = (XrEventDataInstanceLossPending *)&runtimeEvent; + + // TODO We get this event if we're about to loose our OpenXR instance. + // We should queue exiting Godot at this point. + + print_verbose("OpenXR EVENT: instance loss pending at " + itos(event->lossTime)); + return false; + } break; + case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: { + XrEventDataSessionStateChanged *event = (XrEventDataSessionStateChanged *)&runtimeEvent; + + session_state = event->state; + if (session_state >= XR_SESSION_STATE_MAX_ENUM) { + print_verbose("OpenXR EVENT: session state changed to UNKNOWN - " + itos(session_state)); + } else { + print_verbose("OpenXR EVENT: session state changed to " + OpenXRUtil::get_session_state_name(session_state)); + + switch (session_state) { + case XR_SESSION_STATE_IDLE: + on_state_idle(); + break; + case XR_SESSION_STATE_READY: + on_state_ready(); + break; + case XR_SESSION_STATE_SYNCHRONIZED: + on_state_synchronized(); + break; + case XR_SESSION_STATE_VISIBLE: + on_state_visible(); + break; + case XR_SESSION_STATE_FOCUSED: + on_state_focused(); + break; + case XR_SESSION_STATE_STOPPING: + on_state_stopping(); + break; + case XR_SESSION_STATE_LOSS_PENDING: + on_state_loss_pending(); + break; + case XR_SESSION_STATE_EXITING: + on_state_exiting(); + break; + default: + break; + } + } + } break; + case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: { + XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent; + + print_verbose("OpenXR EVENT: reference space type " + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!"); + if (event->poseValid && xr_interface) { + xr_interface->on_pose_recentered(); + } + } break; + case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: { + print_verbose("OpenXR EVENT: interaction profile changed!"); + + XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent; + + List<RID> trackers; + tracker_owner.get_owned_list(&trackers); + for (int i = 0; i < trackers.size(); i++) { + tracker_check_profile(trackers[i], event->session); + } + + } break; + default: + if (!handled) { + print_verbose("OpenXR Unhandled event type " + OpenXRUtil::get_structure_type_name(runtimeEvent.type)); + } + break; + } + + runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER; + pollResult = xrPollEvent(instance, &runtimeEvent); + } + + if (pollResult == XR_EVENT_UNAVAILABLE) { + // processed all events in the queue + return true; + } else { + ERR_FAIL_V_MSG(false, "OpenXR: Failed to poll events!"); + } +} + +bool OpenXRAPI::process() { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false); + + if (!poll_events()) { + return false; + } + + if (!running) { + return false; + } + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_process(); + } + + return true; +} + +bool OpenXRAPI::acquire_image(XrSwapchain p_swapchain, uint32_t &r_image_index) { + ERR_FAIL_COND_V(image_acquired, true); // this was not released when it should be, error out and re-use... + + XrResult result; + XrSwapchainImageAcquireInfo swapchain_image_acquire_info = { + XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type + nullptr // next + }; + result = xrAcquireSwapchainImage(p_swapchain, &swapchain_image_acquire_info, &r_image_index); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to acquire swapchain image [", get_error_string(result), "]"); + return false; + } + + XrSwapchainImageWaitInfo swapchain_image_wait_info = { + XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, // type + nullptr, // next + 17000000 // timeout in nanoseconds + }; + + result = xrWaitSwapchainImage(p_swapchain, &swapchain_image_wait_info); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to wait for swapchain image [", get_error_string(result), "]"); + return false; + } + + return true; +} + +bool OpenXRAPI::release_image(XrSwapchain p_swapchain) { + XrSwapchainImageReleaseInfo swapchain_image_release_info = { + XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type + nullptr // next + }; + XrResult result = xrReleaseSwapchainImage(swapchain, &swapchain_image_release_info); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to release swapchain image! [", get_error_string(result), "]"); + return false; + } + + return true; +} + +void OpenXRAPI::pre_render() { + ERR_FAIL_COND(instance == XR_NULL_HANDLE); + + if (!running) { + return; + } + + // Waitframe does 2 important things in our process: + // 1) It provides us with predictive timing, telling us when OpenXR expects to display the frame we're about to commit + // 2) It will use the previous timing to pause our thread so that rendering starts as close to displaying as possible + // This must thus be called as close to when we start rendering as possible + XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, nullptr }; + XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state); + if (XR_FAILED(result)) { + print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]"); + + // reset just in case + frame_state.predictedDisplayTime = 0; + frame_state.predictedDisplayPeriod = 0; + frame_state.shouldRender = false; + + return; + } + + if (frame_state.predictedDisplayPeriod > 500000000) { + // display period more then 0.5 seconds? must be wrong data + print_verbose("OpenXR resetting invalid display period " + rtos(frame_state.predictedDisplayPeriod)); + frame_state.predictedDisplayPeriod = 0; + } + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_pre_render(); + } + + // Get our view info for the frame we're about to render, note from the OpenXR manual: + // "Repeatedly calling xrLocateViews with the same time may not necessarily return the same result. Instead the prediction gets increasingly accurate as the function is called closer to the given time for which a prediction is made" + + // We're calling this "relatively" early, the positioning we're obtaining here will be used to do our frustum culling, + // occlusion culling, etc. There is however a technique that we can investigate in the future where after our entire + // Vulkan command buffer is build, but right before vkSubmitQueue is called, we call xrLocateViews one more time and + // update the view and projection matrix once more with a slightly more accurate predication and then submit the + // command queues. + + // That is not possible yet but worth investigating in the future. + + XrViewLocateInfo view_locate_info = { + XR_TYPE_VIEW_LOCATE_INFO, // type + nullptr, // next + view_configuration, // viewConfigurationType + frame_state.predictedDisplayTime, // displayTime + play_space // space + }; + XrViewState view_state = { + XR_TYPE_VIEW_STATE, // type + nullptr, // next + 0 // viewStateFlags + }; + uint32_t view_count_output; + result = xrLocateViews(session, &view_locate_info, &view_state, view_count, &view_count_output, views); + if (XR_FAILED(result)) { + print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]"); + return; + } + + bool pose_valid = true; + for (uint64_t i = 0; i < view_count_output; i++) { + if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 || + (view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) { + pose_valid = false; + } + } + if (view_pose_valid != pose_valid) { + view_pose_valid = pose_valid; +#ifdef DEBUG + if (!view_pose_valid) { + print_line("OpenXR View pose became invalid"); + } else { + print_line("OpenXR View pose became valid"); + } +#endif + } + + // let's start our frame.. + XrFrameBeginInfo frame_begin_info = { + XR_TYPE_FRAME_BEGIN_INFO, // type + nullptr // next + }; + result = xrBeginFrame(session, &frame_begin_info); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to being frame [", get_error_string(result), "]"); + return; + } +} + +bool OpenXRAPI::pre_draw_viewport(RID p_render_target) { + if (!can_render()) { + return false; + } + + // TODO: at some point in time we may support multiple viewports in which case we need to handle that... + + return true; +} + +void OpenXRAPI::post_draw_viewport(RID p_render_target) { + if (!can_render()) { + return; + } + + // TODO: at some point in time we may support multiple viewports in which case we need to handle that... + + // TODO: if we can get PR 51179 to work properly we can change away from this approach and move this into get_external_texture or something + if (!image_acquired) { + if (!acquire_image(swapchain, image_index)) { + return; + } + image_acquired = true; + + // print_line("OpenXR: acquired image " + itos(image_index) + ", copying..."); + + // Copy our buffer into our swap chain (remove once PR 51179 is done) + graphics_extension->copy_render_target_to_image(p_render_target, swapchain_graphics_data, image_index); + } +}; + +void OpenXRAPI::end_frame() { + XrResult result; + + ERR_FAIL_COND(instance == XR_NULL_HANDLE); + + if (!running) { + return; + } + + if (frame_state.shouldRender && view_pose_valid && !image_acquired) { + print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!"); + } + + // must have: + // - shouldRender set to true + // - a valid view pose for projection_views[eye].pose to submit layer + // - an image to render + if (!frame_state.shouldRender || !view_pose_valid || !image_acquired) { + // submit 0 layers when we shouldn't render + XrFrameEndInfo frame_end_info = { + XR_TYPE_FRAME_END_INFO, // type + nullptr, // next + frame_state.predictedDisplayTime, // displayTime + XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode + 0, // layerCount + nullptr // layers + }; + result = xrEndFrame(session, &frame_end_info); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to end frame! [", get_error_string(result), "]"); + return; + } + + // neither eye is rendered + return; + } + + // release our swapchain image if we acquired it + if (image_acquired) { + image_acquired = false; // whether we succeed or not, consider this released. + + release_image(swapchain); + } + + for (uint32_t eye = 0; eye < view_count; eye++) { + projection_views[eye].fov = views[eye].fov; + projection_views[eye].pose = views[eye].pose; + } + + Vector<const XrCompositionLayerBaseHeader *> layers_list; + + // Add composition layers from providers + for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) { + XrCompositionLayerBaseHeader *layer = provider->get_composition_layer(); + if (layer) { + layers_list.push_back(layer); + } + } + + XrCompositionLayerProjection projection_layer = { + XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type + nullptr, // next + layers_list.size() > 1 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags + play_space, // space + view_count, // viewCount + projection_views, // views + }; + layers_list.push_back((const XrCompositionLayerBaseHeader *)&projection_layer); + + XrFrameEndInfo frame_end_info = { + XR_TYPE_FRAME_END_INFO, // type + nullptr, // next + frame_state.predictedDisplayTime, // displayTime + XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode + static_cast<uint32_t>(layers_list.size()), // layerCount + layers_list.ptr() // layers + }; + result = xrEndFrame(session, &frame_end_info); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to end frame! [", get_error_string(result), "]"); + return; + } +} + +OpenXRAPI::OpenXRAPI() { + // OpenXRAPI is only constructed if OpenXR is enabled. + // It will be constructed when the rendering device first accesses OpenXR (be it the Vulkan or OpenGL rendering system) + + if (Engine::get_singleton()->is_editor_hint()) { + // Enabled OpenXR in the editor? Adjust our settings for the editor + + } else { + // Load settings from project settings + int ff = GLOBAL_GET("xr/openxr/form_factor"); + switch (ff) { + case 0: { + form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; + } break; + case 1: { + form_factor = XR_FORM_FACTOR_HANDHELD_DISPLAY; + } break; + default: + break; + } + + int vc = GLOBAL_GET("xr/openxr/view_configuration"); + switch (vc) { + case 0: { + view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO; + } break; + case 1: { + view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; + } break; + /* we don't support quad and observer configurations (yet) + case 2: { + view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO; + } break; + case 3: { + view_configuration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT; + } break; + */ + default: + break; + } + + int rs = GLOBAL_GET("xr/openxr/reference_space"); + switch (rs) { + case 0: { + reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL; + } break; + case 1: { + reference_space = XR_REFERENCE_SPACE_TYPE_STAGE; + } break; + default: + break; + } + } + + // reset a few things that can't be done in our class definition + frame_state.predictedDisplayTime = 0; + frame_state.predictedDisplayPeriod = 0; + +#ifdef ANDROID_ENABLED + // our android wrapper will initialise our android loader at this point + register_extension_wrapper(memnew(OpenXRAndroidExtension(this))); +#endif +} + +OpenXRAPI::~OpenXRAPI() { + // cleanup our composition layer providers + for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) { + memdelete(provider); + } + composition_layer_providers.clear(); + + // cleanup our extension wrappers + for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) { + memdelete(extension_wrapper); + } + registered_extension_wrappers.clear(); + + if (supported_extensions != nullptr) { + memfree(supported_extensions); + supported_extensions = nullptr; + } + + if (layer_properties != nullptr) { + memfree(layer_properties); + layer_properties = nullptr; + } +} + +Transform3D OpenXRAPI::transform_from_pose(const XrPosef &p_pose) { + Quaternion q(p_pose.orientation.x, p_pose.orientation.y, p_pose.orientation.z, p_pose.orientation.w); + Basis basis(q); + Vector3 origin(p_pose.position.x, p_pose.position.y, p_pose.position.z); + + return Transform3D(basis, origin); +} + +template <typename T> +XRPose::TrackingConfidence _transform_from_location(const T &p_location, Transform3D &r_transform) { + Basis basis; + Vector3 origin; + XRPose::TrackingConfidence confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE; + const auto &pose = p_location.pose; + + // Check orientation + if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) { + Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w); + r_transform.basis = Basis(q); + + if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) { + // Fully valid orientation, so either 3DOF or 6DOF tracking with high confidence so default to HIGH_TRACKING + confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH; + } else { + // Orientation is being tracked but we're using old/predicted data, so low tracking confidence + confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW; + } + } else { + r_transform.basis = Basis(); + } + + // Check location + if (p_location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) { + r_transform.origin = Vector3(pose.position.x, pose.position.y, pose.position.z); + + if (!(p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) { + // Location is being tracked but we're using old/predicted data, so low tracking confidence + confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW; + } else if (confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) { + // Position tracking without orientation tracking? + confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH; + } + } else { + // No tracking or 3DOF I guess.. + r_transform.origin = Vector3(); + } + + return confidence; +} + +XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform) { + return _transform_from_location(p_location, r_transform); +} + +XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform) { + return _transform_from_location(p_location, r_transform); +} + +void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 r_angular_velocity) { + if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT) { + XrVector3f linear_velocity = p_velocity.linearVelocity; + r_linear_velocity = Vector3(linear_velocity.x, linear_velocity.y, linear_velocity.z); + } else { + r_linear_velocity = Vector3(); + } + if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT) { + XrVector3f angular_velocity = p_velocity.angularVelocity; + r_angular_velocity = Vector3(angular_velocity.x, angular_velocity.y, angular_velocity.z); + } else { + r_angular_velocity = Vector3(); + } +} + +RID OpenXRAPI::get_tracker_rid(XrPath p_path) { + List<RID> current; + tracker_owner.get_owned_list(¤t); + for (int i = 0; i < current.size(); i++) { + Tracker *tracker = tracker_owner.get_or_null(current[i]); + if (tracker && tracker->toplevel_path == p_path) { + return current[i]; + } + } + + return RID(); +} + +RID OpenXRAPI::tracker_create(const String p_name) { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID()); + + Tracker new_tracker; + new_tracker.name = p_name; + new_tracker.toplevel_path = XR_NULL_PATH; + new_tracker.active_profile_rid = RID(); + + XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_tracker.toplevel_path); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]"); + return RID(); + } + + return tracker_owner.make_rid(new_tracker); +} + +String OpenXRAPI::tracker_get_name(RID p_tracker) { + if (p_tracker.is_null()) { + return String("None"); + } + + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL_V(tracker, String()); + + return tracker->name; +} + +void OpenXRAPI::tracker_check_profile(RID p_tracker, XrSession p_session) { + if (p_session == XR_NULL_HANDLE) { + p_session = session; + } + + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL(tracker); + + if (tracker->toplevel_path == XR_NULL_PATH) { + // no path, how was this even created? + return; + } + + XrInteractionProfileState profile_state = { + XR_TYPE_INTERACTION_PROFILE_STATE, // type + nullptr, // next + XR_NULL_PATH // interactionProfile + }; + + XrResult result = xrGetCurrentInteractionProfile(p_session, tracker->toplevel_path, &profile_state); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get interaction profile for", itos(tracker->toplevel_path), "[", get_error_string(result), "]"); + return; + } + + XrPath new_profile = profile_state.interactionProfile; + XrPath was_profile = get_interaction_profile_path(tracker->active_profile_rid); + if (was_profile != new_profile) { + tracker->active_profile_rid = get_interaction_profile_rid(new_profile); + + if (xr_interface) { + xr_interface->tracker_profile_changed(p_tracker, tracker->active_profile_rid); + } + } +} + +void OpenXRAPI::tracker_free(RID p_tracker) { + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL(tracker); + + // there is nothing to free here + + tracker_owner.free(p_tracker); +} + +RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_name, const int p_priority) { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID()); + ActionSet action_set; + + action_set.name = p_name; + action_set.is_attached = false; + + // create our action set... + XrActionSetCreateInfo action_set_info = { + XR_TYPE_ACTION_SET_CREATE_INFO, // type + nullptr, // next + "", // actionSetName + "", // localizedActionSetName + uint32_t(p_priority) // priority + }; + + copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE); + copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE); + + // print_line("Creating action set ", action_set_info.actionSetName, " - ", action_set_info.localizedActionSetName, " (", itos(action_set_info.priority), ")"); + + XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]"); + return RID(); + } + + return action_set_owner.make_rid(action_set); +} + +String OpenXRAPI::action_set_get_name(RID p_action_set) { + if (p_action_set.is_null()) { + return String("None"); + } + + ActionSet *action_set = action_set_owner.get_or_null(p_action_set); + ERR_FAIL_NULL_V(action_set, String()); + + return action_set->name; +} + +bool OpenXRAPI::action_set_attach(RID p_action_set) { + ActionSet *action_set = action_set_owner.get_or_null(p_action_set); + ERR_FAIL_NULL_V(action_set, false); + + if (action_set->is_attached) { + // already attached + return true; + } + + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + + // So according to the docs, once we attach our action set to our session it becomes read only.. + // https://www.khronos.org/registry/OpenXR/specs/1.0/man/html/xrAttachSessionActionSets.html + XrSessionActionSetsAttachInfo attach_info = { + XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // type + nullptr, // next + 1, // countActionSets, + &action_set->handle // actionSets + }; + + XrResult result = xrAttachSessionActionSets(session, &attach_info); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to attach action set! [", get_error_string(result), "]"); + return false; + } + + action_set->is_attached = true; + + /* For debugging: + print_verbose("Attached set " + action_set->name); + List<RID> action_rids; + action_owner.get_owned_list(&action_rids); + for (int i = 0; i < action_rids.size(); i++) { + Action * action = action_owner.get_or_null(action_rids[i]); + if (action && action->action_set_rid == p_action_set) { + print_verbose(" - Action " + action->name + ": " + OpenXRUtil::get_action_type_name(action->action_type)); + for (int j = 0; j < action->trackers.size(); j++) { + Tracker * tracker = tracker_owner.get_or_null(action->trackers[j].tracker_rid); + if (tracker) { + print_verbose(" - " + tracker->name); + } + } + } + } + */ + + return true; +} + +void OpenXRAPI::action_set_free(RID p_action_set) { + ActionSet *action_set = action_set_owner.get_or_null(p_action_set); + ERR_FAIL_NULL(action_set); + + if (action_set->handle != XR_NULL_HANDLE) { + xrDestroyActionSet(action_set->handle); + } + + action_set_owner.free(p_action_set); +} + +RID OpenXRAPI::get_action_rid(XrAction p_action) { + List<RID> current; + action_owner.get_owned_list(¤t); + for (int i = 0; i < current.size(); i++) { + Action *action = action_owner.get_or_null(current[i]); + if (action && action->handle == p_action) { + return current[i]; + } + } + + return RID(); +} + +RID OpenXRAPI::action_create(RID p_action_set, const String p_name, const String p_localized_name, OpenXRAction::ActionType p_action_type, const Vector<RID> &p_trackers) { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID()); + + Action action; + action.name = p_name; + + ActionSet *action_set = action_set_owner.get_or_null(p_action_set); + ERR_FAIL_NULL_V(action_set, RID()); + ERR_FAIL_COND_V(action_set->handle == XR_NULL_HANDLE, RID()); + action.action_set_rid = p_action_set; + + switch (p_action_type) { + case OpenXRAction::OPENXR_ACTION_BOOL: + action.action_type = XR_ACTION_TYPE_BOOLEAN_INPUT; + break; + case OpenXRAction::OPENXR_ACTION_FLOAT: + action.action_type = XR_ACTION_TYPE_FLOAT_INPUT; + break; + case OpenXRAction::OPENXR_ACTION_VECTOR2: + action.action_type = XR_ACTION_TYPE_VECTOR2F_INPUT; + break; + case OpenXRAction::OPENXR_ACTION_POSE: + action.action_type = XR_ACTION_TYPE_POSE_INPUT; + break; + case OpenXRAction::OPENXR_ACTION_HAPTIC: + action.action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT; + break; + default: + ERR_FAIL_V(RID()); + break; + } + + Vector<XrPath> toplevel_paths; + for (int i = 0; i < p_trackers.size(); i++) { + Tracker *tracker = tracker_owner.get_or_null(p_trackers[i]); + if (tracker != nullptr && tracker->toplevel_path != XR_NULL_PATH) { + ActionTracker action_tracker = { + p_trackers[i], // tracker + XR_NULL_HANDLE, // space + false // was_location_valid + }; + action.trackers.push_back(action_tracker); + + toplevel_paths.push_back(tracker->toplevel_path); + } + } + + XrActionCreateInfo action_info = { + XR_TYPE_ACTION_CREATE_INFO, // type + nullptr, // next + "", // actionName + action.action_type, // actionType + uint32_t(toplevel_paths.size()), // countSubactionPaths + toplevel_paths.ptr(), // subactionPaths + "" // localizedActionName + }; + + copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE); + copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE); + + // print_line("Creating action ", action_info.actionName, action_info.localizedActionName, action_info.countSubactionPaths); + + XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]"); + return RID(); + } + + return action_owner.make_rid(action); +} + +String OpenXRAPI::action_get_name(RID p_action) { + if (p_action.is_null()) { + return String("None"); + } + + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_NULL_V(action, String()); + + return action->name; +} + +void OpenXRAPI::action_free(RID p_action) { + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_NULL(action); + + if (action->handle != XR_NULL_HANDLE) { + xrDestroyAction(action->handle); + } + + action_owner.free(p_action); +} + +RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) { + List<RID> current; + interaction_profile_owner.get_owned_list(¤t); + for (int i = 0; i < current.size(); i++) { + InteractionProfile *ip = interaction_profile_owner.get_or_null(current[i]); + if (ip && ip->path == p_path) { + return current[i]; + } + } + + return RID(); +} + +XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) { + if (p_interaction_profile.is_null()) { + return XR_NULL_PATH; + } + + InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile); + ERR_FAIL_NULL_V(ip, XR_NULL_PATH); + + return ip->path; +} + +RID OpenXRAPI::interaction_profile_create(const String p_name) { + InteractionProfile new_interaction_profile; + + XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_interaction_profile.path); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]"); + return RID(); + } + + RID existing_ip = get_interaction_profile_rid(new_interaction_profile.path); + if (existing_ip.is_valid()) { + return existing_ip; + } + + new_interaction_profile.name = p_name; + return interaction_profile_owner.make_rid(new_interaction_profile); +} + +String OpenXRAPI::interaction_profile_get_name(RID p_interaction_profile) { + if (p_interaction_profile.is_null()) { + return String("None"); + } + + InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile); + ERR_FAIL_NULL_V(ip, String()); + + return ip->name; +} + +void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) { + InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile); + ERR_FAIL_NULL(ip); + + ip->bindings.clear(); +} + +bool OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path) { + InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile); + ERR_FAIL_NULL_V(ip, false); + + XrActionSuggestedBinding binding; + + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_COND_V(action == nullptr || action->handle == XR_NULL_HANDLE, false); + + binding.action = action->handle; + + XrResult result = xrStringToPath(instance, p_path.utf8().get_data(), &binding.binding); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]"); + return false; + } + + ip->bindings.push_back(binding); + + return true; +} + +bool OpenXRAPI::interaction_profile_suggest_bindings(RID p_interaction_profile) { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false); + + InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile); + ERR_FAIL_NULL_V(ip, false); + + const XrInteractionProfileSuggestedBinding suggested_bindings = { + XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // type + nullptr, // next + ip->path, // interactionProfile + uint32_t(ip->bindings.size()), // countSuggestedBindings + ip->bindings.ptr() // suggestedBindings + }; + + XrResult result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings); + if (result == XR_ERROR_PATH_UNSUPPORTED) { + // this is fine, not all runtimes support all devices. + print_verbose("OpenXR Interaction profile " + ip->name + " is not supported on this runtime"); + } else if (XR_FAILED(result)) { + print_line("OpenXR: failed to suggest bindings for ", ip->name, "! [", get_error_string(result), "]"); + // reporting is enough... + } + + /* For debugging: + print_verbose("Suggested bindings for " + ip->name); + for (int i = 0; i < ip->bindings.size(); i++) { + uint32_t strlen; + char path[XR_MAX_PATH_LENGTH]; + + String action_name = action_get_name(get_action_rid(ip->bindings[i].action)); + + XrResult result = xrPathToString(instance, ip->bindings[i].binding, XR_MAX_PATH_LENGTH, &strlen, path); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to retrieve bindings for ", action_name, "! [", get_error_string(result), "]"); + } + print_verbose(" - " + action_name + " => " + String(path)); + } + */ + + return true; +} + +void OpenXRAPI::interaction_profile_free(RID p_interaction_profile) { + InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile); + ERR_FAIL_NULL(ip); + + ip->bindings.clear(); + + interaction_profile_owner.free(p_interaction_profile); +} + +bool OpenXRAPI::sync_action_sets(const Vector<RID> p_active_sets) { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + + if (!running) { + return false; + } + + Vector<XrActiveActionSet> active_sets; + for (int i = 0; i < p_active_sets.size(); i++) { + ActionSet *action_set = action_set_owner.get_or_null(p_active_sets[i]); + if (action_set && action_set->handle != XR_NULL_HANDLE) { + XrActiveActionSet aset; + aset.actionSet = action_set->handle; + aset.subactionPath = XR_NULL_PATH; + active_sets.push_back(aset); + } + } + + ERR_FAIL_COND_V(active_sets.size() == 0, false); + + XrActionsSyncInfo sync_info = { + XR_TYPE_ACTIONS_SYNC_INFO, // type + nullptr, // next + uint32_t(active_sets.size()), // countActiveActionSets + active_sets.ptr() // activeActionSets + }; + + XrResult result = xrSyncActions(session, &sync_info); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to sync active action sets! [", get_error_string(result), "]"); + return false; + } + + return true; +} + +bool OpenXRAPI::get_action_bool(RID p_action, RID p_tracker) { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_NULL_V(action, false); + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL_V(tracker, false); + + if (!running) { + return false; + } + + ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT, false); + + XrActionStateGetInfo get_info = { + XR_TYPE_ACTION_STATE_GET_INFO, // type + nullptr, // next + action->handle, // action + tracker->toplevel_path // subactionPath + }; + + XrActionStateBoolean result_state; + result_state.type = XR_TYPE_ACTION_STATE_BOOLEAN, + result_state.next = nullptr; + XrResult result = xrGetActionStateBoolean(session, &get_info, &result_state); + if (XR_FAILED(result)) { + print_line("OpenXR: couldn't get action boolean! [", get_error_string(result), "]"); + return false; + } + + return result_state.isActive && result_state.currentState; +} + +float OpenXRAPI::get_action_float(RID p_action, RID p_tracker) { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, 0.0); + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_NULL_V(action, 0.0); + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL_V(tracker, 0.0); + + if (!running) { + return 0.0; + } + + ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_FLOAT_INPUT, 0.0); + + XrActionStateGetInfo get_info = { + XR_TYPE_ACTION_STATE_GET_INFO, // type + nullptr, // next + action->handle, // action + tracker->toplevel_path // subactionPath + }; + + XrActionStateFloat result_state; + result_state.type = XR_TYPE_ACTION_STATE_FLOAT, + result_state.next = nullptr; + XrResult result = xrGetActionStateFloat(session, &get_info, &result_state); + if (XR_FAILED(result)) { + print_line("OpenXR: couldn't get action float! [", get_error_string(result), "]"); + return 0.0; + } + + return result_state.isActive ? result_state.currentState : 0.0; +} + +Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Vector2()); + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_NULL_V(action, Vector2()); + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL_V(tracker, Vector2()); + + if (!running) { + return Vector2(); + } + + ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT, Vector2()); + + XrActionStateGetInfo get_info = { + XR_TYPE_ACTION_STATE_GET_INFO, // type + nullptr, // next + action->handle, // action + tracker->toplevel_path // subactionPath + }; + + XrActionStateVector2f result_state; + result_state.type = XR_TYPE_ACTION_STATE_VECTOR2F, + result_state.next = nullptr; + XrResult result = xrGetActionStateVector2f(session, &get_info, &result_state); + if (XR_FAILED(result)) { + print_line("OpenXR: couldn't get action vector2! [", get_error_string(result), "]"); + return Vector2(); + } + + return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2(); +} + +XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE); + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE); + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL_V(tracker, XRPose::XR_TRACKING_CONFIDENCE_NONE); + + if (!running) { + return XRPose::XR_TRACKING_CONFIDENCE_NONE; + } + + ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_POSE_INPUT, XRPose::XR_TRACKING_CONFIDENCE_NONE); + + // print_verbose("Checking " + action->name + " => " + tracker->name + " (" + itos(tracker->toplevel_path) + ")"); + + uint64_t index = 0xFFFFFFFF; + uint64_t size = uint64_t(action->trackers.size()); + for (uint64_t i = 0; i < size && index == 0xFFFFFFFF; i++) { + if (action->trackers[i].tracker_rid == p_tracker) { + index = i; + } + } + + if (index == 0xFFFFFFFF) { + // couldn't find it? + return XRPose::XR_TRACKING_CONFIDENCE_NONE; + } + + XrTime display_time = get_next_frame_time(); + if (display_time == 0) { + return XRPose::XR_TRACKING_CONFIDENCE_NONE; + } + + if (action->trackers[index].space == XR_NULL_HANDLE) { + // if this is a pose we need to define spaces + + XrActionSpaceCreateInfo action_space_info = { + XR_TYPE_ACTION_SPACE_CREATE_INFO, // type + nullptr, // next + action->handle, // action + tracker->toplevel_path, // subactionPath + { + { 0.0, 0.0, 0.0, 1.0 }, // orientation + { 0.0, 0.0, 0.0 } // position + } // poseInActionSpace + }; + + XrSpace space; + XrResult result = xrCreateActionSpace(session, &action_space_info, &space); + if (XR_FAILED(result)) { + print_line("OpenXR: couldn't create action space! [", get_error_string(result), "]"); + return XRPose::XR_TRACKING_CONFIDENCE_NONE; + } + + action->trackers.ptrw()[index].space = space; + } + + XrSpaceVelocity velocity = { + XR_TYPE_SPACE_VELOCITY, // type + nullptr, // next + 0, // velocityFlags + { 0.0, 0.0, 0.0 }, // linearVelocity + { 0.0, 0.0, 0.0 } // angularVelocity + }; + + XrSpaceLocation location = { + XR_TYPE_SPACE_LOCATION, // type + &velocity, // next + 0, // locationFlags + { + { 0.0, 0.0, 0.0, 0.0 }, // orientation + { 0.0, 0.0, 0.0 } // position + } // pose + }; + + XrResult result = xrLocateSpace(action->trackers[index].space, play_space, display_time, &location); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to locate space! [", get_error_string(result), "]"); + return XRPose::XR_TRACKING_CONFIDENCE_NONE; + } + + XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform); + parse_velocities(velocity, r_linear_velocity, r_angular_velocity); + + return confidence; +} + +bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns) { + ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); + Action *action = action_owner.get_or_null(p_action); + ERR_FAIL_NULL_V(action, false); + Tracker *tracker = tracker_owner.get_or_null(p_tracker); + ERR_FAIL_NULL_V(tracker, false); + + if (!running) { + return false; + } + + ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT, false); + + XrHapticActionInfo action_info = { + XR_TYPE_HAPTIC_ACTION_INFO, // type + nullptr, // next + action->handle, // action + tracker->toplevel_path // subactionPath + }; + + XrHapticVibration vibration = { + XR_TYPE_HAPTIC_VIBRATION, // type + nullptr, // next + p_duration_ns, // duration + p_frequency, // frequency + p_amplitude, // amplitude + }; + + XrResult result = xrApplyHapticFeedback(session, &action_info, (const XrHapticBaseHeader *)&vibration); + if (XR_FAILED(result)) { + print_line("OpenXR: failed to apply haptic feedback! [", get_error_string(result), "]"); + return false; + } + + return true; +} diff --git a/modules/openxr/openxr_api.h b/modules/openxr/openxr_api.h new file mode 100644 index 0000000000..e20826c849 --- /dev/null +++ b/modules/openxr/openxr_api.h @@ -0,0 +1,290 @@ +/*************************************************************************/ +/* openxr_api.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_DRIVER_H +#define OPENXR_DRIVER_H + +#include "core/error/error_macros.h" +#include "core/math/camera_matrix.h" +#include "core/math/transform_3d.h" +#include "core/math/vector2.h" +#include "core/os/memory.h" +#include "core/string/ustring.h" +#include "core/templates/map.h" +#include "core/templates/rid_owner.h" +#include "core/templates/vector.h" +#include "servers/xr/xr_pose.h" + +#include "thirdparty/openxr/src/common/xr_linear.h" +#include <openxr/openxr.h> + +#include "action_map/openxr_action.h" + +#include "extensions/openxr_composition_layer_provider.h" +#include "extensions/openxr_extension_wrapper.h" + +// Note, OpenXR code that we wrote for our plugin makes use of C++20 notation for initialising structs which ensures zeroing out unspecified members. +// Godot is currently restricted to C++17 which doesn't allow this notation. Make sure critical fields are set. + +// forward declarations, we don't want to include these fully +class OpenXRVulkanExtension; +class OpenXRInterface; + +class OpenXRAPI { +private: + // our singleton + static OpenXRAPI *singleton; + + // linked XR interface + OpenXRInterface *xr_interface = nullptr; + + // layers + uint32_t num_layer_properties = 0; + XrApiLayerProperties *layer_properties = nullptr; + + // extensions + uint32_t num_supported_extensions = 0; + XrExtensionProperties *supported_extensions = nullptr; + Vector<OpenXRExtensionWrapper *> registered_extension_wrappers; + Vector<const char *> enabled_extensions; + + // composition layer providers + Vector<OpenXRCompositionLayerProvider *> composition_layer_providers; + + // view configuration + uint32_t num_view_configuration_types = 0; + XrViewConfigurationType *supported_view_configuration_types = nullptr; + + // reference spaces + uint32_t num_reference_spaces = 0; + XrReferenceSpaceType *supported_reference_spaces = nullptr; + + // swapchains (note these are platform dependent) + uint32_t num_swapchain_formats = 0; + int64_t *supported_swapchain_formats = nullptr; + + // configuration + XrFormFactor form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; + XrViewConfigurationType view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; + XrReferenceSpaceType reference_space = XR_REFERENCE_SPACE_TYPE_STAGE; + XrEnvironmentBlendMode environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; + + // state + XrInstance instance = XR_NULL_HANDLE; + XrSystemId system_id; + String system_name; + uint32_t vendor_id; + XrSystemTrackingProperties tracking_properties; + XrSession session = XR_NULL_HANDLE; + XrSessionState session_state = XR_SESSION_STATE_UNKNOWN; + bool running = false; + XrFrameState frame_state = { XR_TYPE_FRAME_STATE, NULL, 0, 0, false }; + + OpenXRGraphicsExtensionWrapper *graphics_extension = nullptr; + XrSystemGraphicsProperties graphics_properties; + void *swapchain_graphics_data = nullptr; + uint32_t image_index = 0; + bool image_acquired = false; + + uint32_t view_count = 0; + XrViewConfigurationView *view_configuration_views = nullptr; + XrView *views = nullptr; + XrCompositionLayerProjectionView *projection_views = nullptr; + XrSwapchain swapchain = XR_NULL_HANDLE; + + XrSpace play_space = XR_NULL_HANDLE; + XrSpace view_space = XR_NULL_HANDLE; + bool view_pose_valid = false; + XRPose::TrackingConfidence head_pose_confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE; + + bool load_layer_properties(); + bool load_supported_extensions(); + bool is_extension_supported(const char *p_extension) const; + + // instance + bool create_instance(); + bool get_system_info(); + bool load_supported_view_configuration_types(); + bool is_view_configuration_supported(XrViewConfigurationType p_configuration_type) const; + bool load_supported_view_configuration_views(XrViewConfigurationType p_configuration_type); + void destroy_instance(); + + // session + bool create_session(); + bool load_supported_reference_spaces(); + bool is_reference_space_supported(XrReferenceSpaceType p_reference_space); + bool setup_spaces(); + bool load_supported_swapchain_formats(); + bool is_swapchain_format_supported(int64_t p_swapchain_format); + bool create_main_swapchain(); + void destroy_session(); + + // swapchains + bool create_swapchain(int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data); + bool acquire_image(XrSwapchain p_swapchain, uint32_t &r_image_index); + bool release_image(XrSwapchain p_swapchain); + + // action map + struct Tracker { // Trackers represent tracked physical objects such as controllers, pucks, etc. + String name; // Name for this tracker (i.e. "/user/hand/left") + XrPath toplevel_path; // OpenXR XrPath for this tracker + RID active_profile_rid; // RID of the active profile for this tracker + }; + RID_Owner<Tracker, true> tracker_owner; + RID get_tracker_rid(XrPath p_path); + + struct ActionSet { // Action sets define a set of actions that can be enabled together + String name; // Name for this action set (i.e. "godot_action_set") + bool is_attached; // If true our action set has been attached to the session and can no longer be modified + XrActionSet handle; // OpenXR handle for this action set + }; + RID_Owner<ActionSet, true> action_set_owner; + + struct ActionTracker { // Links and action to a tracker + RID tracker_rid; // RID of the tracker + XrSpace space; // Optional space for pose actions + bool was_location_valid; // If true the last position we obtained was valid + }; + + struct Action { // Actions define the inputs and outputs in OpenXR + RID action_set_rid; // RID of the action set this action belongs to + String name; // Name for this action (i.e. "aim_pose") + XrActionType action_type; // Type of action (bool, float, etc.) + Vector<ActionTracker> trackers; // The trackers this action can be used with + XrAction handle; // OpenXR handle for this action + }; + RID_Owner<Action, true> action_owner; + RID get_action_rid(XrAction p_action); + + struct InteractionProfile { // Interaction profiles define suggested bindings between the physical inputs on controller types and our actions + String name; // Name of the interaction profile (i.e. "/interaction_profiles/valve/index_controller") + XrPath path; // OpenXR path for this profile + Vector<XrActionSuggestedBinding> bindings; // OpenXR action bindings + }; + RID_Owner<InteractionProfile, true> interaction_profile_owner; + RID get_interaction_profile_rid(XrPath p_path); + XrPath get_interaction_profile_path(RID p_interaction_profile); + + // state changes + bool poll_events(); + bool on_state_idle(); + bool on_state_ready(); + bool on_state_synchronized(); + bool on_state_visible(); + bool on_state_focused(); + bool on_state_stopping(); + bool on_state_loss_pending(); + bool on_state_exiting(); + + // convencience + void copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len); + +protected: + friend class OpenXRVulkanExtension; + + XrInstance get_instance() const { return instance; }; + XrSystemId get_system_id() const { return system_id; }; + XrSession get_session() const { return session; }; + + // helper method to convert an XrPosef to a Transform3D + Transform3D transform_from_pose(const XrPosef &p_pose); + + // helper method to get a valid Transform3D from an openxr space location + XRPose::TrackingConfidence transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform); + XRPose::TrackingConfidence transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform); + void parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 r_angular_velocity); + +public: + static void setup_global_defs(); + static bool openxr_is_enabled(); + static OpenXRAPI *get_singleton(); + + String get_error_string(XrResult result); + String get_swapchain_format_name(int64_t p_swapchain_format) const; + + void set_xr_interface(OpenXRInterface *p_xr_interface); + void register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper); + + bool is_initialized(); + bool is_running(); + bool initialise(const String &p_rendering_driver); + bool initialise_session(); + void finish(); + + XrTime get_next_frame_time() { return frame_state.predictedDisplayTime + frame_state.predictedDisplayPeriod; }; + bool can_render() { return instance != XR_NULL_HANDLE && session != XR_NULL_HANDLE && running && view_pose_valid && frame_state.shouldRender; }; + + Size2 get_recommended_target_size(); + XRPose::TrackingConfidence get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity); + bool get_view_transform(uint32_t p_view, Transform3D &r_transform); + bool get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, CameraMatrix &p_camera_matrix); + bool process(); + + void pre_render(); + bool pre_draw_viewport(RID p_render_target); + void post_draw_viewport(RID p_render_target); + void end_frame(); + + // action map + String get_default_action_map_resource_name(); + + RID tracker_create(const String p_name); + String tracker_get_name(RID p_tracker); + void tracker_check_profile(RID p_tracker, XrSession p_session = XR_NULL_HANDLE); + void tracker_free(RID p_tracker); + + RID action_set_create(const String p_name, const String p_localized_name, const int p_priority); + String action_set_get_name(RID p_action_set); + bool action_set_attach(RID p_action_set); + void action_set_free(RID p_action_set); + + RID action_create(RID p_action_set, const String p_name, const String p_localized_name, OpenXRAction::ActionType p_action_type, const Vector<RID> &p_trackers); + String action_get_name(RID p_action); + void action_free(RID p_action); + + RID interaction_profile_create(const String p_name); + String interaction_profile_get_name(RID p_interaction_profile); + void interaction_profile_clear_bindings(RID p_interaction_profile); + bool interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path); + bool interaction_profile_suggest_bindings(RID p_interaction_profile); + void interaction_profile_free(RID p_interaction_profile); + + bool sync_action_sets(const Vector<RID> p_active_sets); + bool get_action_bool(RID p_action, RID p_tracker); + float get_action_float(RID p_action, RID p_tracker); + Vector2 get_action_vector2(RID p_action, RID p_tracker); + XRPose::TrackingConfidence get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity); + bool trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns); + + OpenXRAPI(); + ~OpenXRAPI(); +}; + +#endif // !OPENXR_DRIVER_H diff --git a/modules/openxr/openxr_interface.cpp b/modules/openxr/openxr_interface.cpp new file mode 100644 index 0000000000..39f9153f0d --- /dev/null +++ b/modules/openxr/openxr_interface.cpp @@ -0,0 +1,771 @@ +/*************************************************************************/ +/* openxr_interface.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_interface.h" + +#include "core/io/resource_loader.h" +#include "core/io/resource_saver.h" +#include "servers/rendering/rendering_server_globals.h" + +void OpenXRInterface::_bind_methods() { + // lifecycle signals + ADD_SIGNAL(MethodInfo("session_begun")); + ADD_SIGNAL(MethodInfo("session_stopping")); + ADD_SIGNAL(MethodInfo("session_focussed")); + ADD_SIGNAL(MethodInfo("session_visible")); + ADD_SIGNAL(MethodInfo("pose_recentered")); +} + +StringName OpenXRInterface::get_name() const { + return StringName("OpenXR"); +}; + +uint32_t OpenXRInterface::get_capabilities() const { + return XRInterface::XR_VR + XRInterface::XR_STEREO; +}; + +PackedStringArray OpenXRInterface::get_suggested_tracker_names() const { + // These are hardcoded in OpenXR, note that they will only be available if added to our action map + + PackedStringArray arr = { + "left_hand", // /user/hand/left is mapped to our defaults + "right_hand", // /user/hand/right is mapped to our defaults + "/user/treadmill" + }; + + return arr; +} + +XRInterface::TrackingStatus OpenXRInterface::get_tracking_status() const { + return tracking_state; +} + +void OpenXRInterface::_load_action_map() { + ERR_FAIL_NULL(openxr_api); + + // This may seem a bit duplicitous to a little bit of background info here. + // OpenXRActionMap (with all its sub resource classes) is a class that allows us to configure and store an action map in. + // This gives the user the ability to edit the action map in a UI and customise the actions. + // OpenXR however requires us to submit an action map and it takes over from that point and we can no longer change it. + // This system does that push and we store the info needed to then work with this action map going forward. + + // Within our openxr device we maintain a number of classes that wrap the relevant OpenXR objects for this. + // Within OpenXRInterface we have a few internal classes that keep track of what we've created. + // This allow us to process the relevant actions each frame. + + // just in case clean up + free_trackers(); + free_interaction_profiles(); + free_action_sets(); + + Ref<OpenXRActionMap> action_map; + if (Engine::get_singleton()->is_editor_hint()) { +#ifdef TOOLS_ENABLED + action_map.instantiate(); + action_map->create_editor_action_sets(); +#endif + } else { + String default_tres_name = openxr_api->get_default_action_map_resource_name(); + + // Check if we can load our default + if (ResourceLoader::exists(default_tres_name)) { + action_map = ResourceLoader::load(default_tres_name); + } + + // Check if we need to create default action set + if (action_map.is_null()) { + action_map.instantiate(); + action_map->create_default_action_sets(); +#ifdef TOOLS_ENABLED + // Save our action sets so our user can + action_map->set_path(default_tres_name, true); + ResourceSaver::save(default_tres_name, action_map); +#endif + } + } + + // process our action map + if (action_map.is_valid()) { + Map<Ref<OpenXRAction>, Action *> xr_actions; + + Array action_sets = action_map->get_action_sets(); + for (int i = 0; i < action_sets.size(); i++) { + // Create our action set + Ref<OpenXRActionSet> xr_action_set = action_sets[i]; + ActionSet *action_set = create_action_set(xr_action_set->get_name(), xr_action_set->get_localized_name(), xr_action_set->get_priority()); + if (!action_set) { + continue; + } + + // Now create our actions for these + Array actions = xr_action_set->get_actions(); + for (int j = 0; j < actions.size(); j++) { + Ref<OpenXRAction> xr_action = actions[j]; + + PackedStringArray toplevel_paths = xr_action->get_toplevel_paths(); + Vector<Tracker *> trackers; + + for (int k = 0; k < toplevel_paths.size(); k++) { + Tracker *tracker = find_tracker(toplevel_paths[k], true); + if (tracker) { + trackers.push_back(tracker); + } + } + + Action *action = create_action(action_set, xr_action->get_name(), xr_action->get_localized_name(), xr_action->get_action_type(), trackers); + if (action) { + // we link our actions back to our trackers so we know which actions to check when we're processing our trackers + for (int t = 0; t < trackers.size(); t++) { + link_action_to_tracker(trackers[t], action); + } + + // add this to our map for creating our interaction profiles + xr_actions[xr_action] = action; + } + } + } + + // now do our suggestions + Array interaction_profiles = action_map->get_interaction_profiles(); + for (int i = 0; i < interaction_profiles.size(); i++) { + Ref<OpenXRInteractionProfile> xr_interaction_profile = interaction_profiles[i]; + + // Note, we can only have one entry per interaction profile so if it already exists we clear it out + RID ip = openxr_api->interaction_profile_create(xr_interaction_profile->get_interaction_profile_path()); + openxr_api->interaction_profile_clear_bindings(ip); + + Array xr_bindings = xr_interaction_profile->get_bindings(); + for (int j = 0; j < xr_bindings.size(); j++) { + Ref<OpenXRIPBinding> xr_binding = xr_bindings[j]; + Ref<OpenXRAction> xr_action = xr_binding->get_action(); + + Action *action = nullptr; + if (xr_actions.has(xr_action)) { + action = xr_actions[xr_action]; + } else { + print_line("Action ", xr_action->get_name(), " isn't part of an action set!"); + continue; + } + + PackedStringArray paths = xr_binding->get_paths(); + for (int k = 0; k < paths.size(); k++) { + openxr_api->interaction_profile_add_binding(ip, action->action_rid, paths[k]); + } + } + + // Now submit our suggestions + openxr_api->interaction_profile_suggest_bindings(ip); + + // And record it in our array so we can clean it up later on + if (interaction_profiles.has(ip)) { + interaction_profiles.push_back(ip); + } + } + } +} + +OpenXRInterface::ActionSet *OpenXRInterface::create_action_set(const String &p_action_set_name, const String &p_localized_name, const int p_priority) { + ERR_FAIL_NULL_V(openxr_api, nullptr); + + // find if it already exists + for (int i = 0; i < action_sets.size(); i++) { + if (action_sets[i]->action_set_name == p_action_set_name) { + // already exists in this set + return nullptr; + } + } + + ActionSet *action_set = memnew(ActionSet); + action_set->action_set_name = p_action_set_name; + action_set->is_active = true; + action_set->action_set_rid = openxr_api->action_set_create(p_action_set_name, p_localized_name, p_priority); + action_sets.push_back(action_set); + + return action_set; +} + +void OpenXRInterface::free_action_sets() { + ERR_FAIL_NULL(openxr_api); + + for (int i = 0; i < action_sets.size(); i++) { + ActionSet *action_set = action_sets[i]; + + free_actions(action_set); + + openxr_api->action_set_free(action_set->action_set_rid); + + memfree(action_set); + } + action_sets.clear(); +} + +OpenXRInterface::Action *OpenXRInterface::create_action(ActionSet *p_action_set, const String &p_action_name, const String &p_localized_name, OpenXRAction::ActionType p_action_type, const Vector<Tracker *> p_trackers) { + ERR_FAIL_NULL_V(openxr_api, nullptr); + + for (int i = 0; i < p_action_set->actions.size(); i++) { + if (p_action_set->actions[i]->action_name == p_action_name) { + // already exists in this set + return nullptr; + } + } + + Vector<RID> tracker_rids; + for (int i = 0; i < p_trackers.size(); i++) { + tracker_rids.push_back(p_trackers[i]->tracker_rid); + } + + Action *action = memnew(Action); + if (p_action_type == OpenXRAction::OPENXR_ACTION_POSE) { + // We can't have dual action names in OpenXR hence we added _pose, + // but default, aim and grip and default pose action names in Godot so rename them on the tracker. + // NOTE need to decide on whether we should keep the naming convention or rename it on Godots side + if (p_action_name == "default_pose") { + action->action_name = "default"; + } else if (p_action_name == "aim_pose") { + action->action_name = "aim"; + } else if (p_action_name == "grip_pose") { + action->action_name = "grip"; + } else { + action->action_name = p_action_name; + } + } else { + action->action_name = p_action_name; + } + + action->action_type = p_action_type; + action->action_rid = openxr_api->action_create(p_action_set->action_set_rid, p_action_name, p_localized_name, p_action_type, tracker_rids); + p_action_set->actions.push_back(action); + + return action; +} + +OpenXRInterface::Action *OpenXRInterface::find_action(const String &p_action_name) { + // We just find the first action by this name + + for (int i = 0; i < action_sets.size(); i++) { + for (int j = 0; j < action_sets[i]->actions.size(); j++) { + if (action_sets[i]->actions[j]->action_name == p_action_name) { + return action_sets[i]->actions[j]; + } + } + } + + // not found + return nullptr; +} + +void OpenXRInterface::free_actions(ActionSet *p_action_set) { + ERR_FAIL_NULL(openxr_api); + + for (int i = 0; i < p_action_set->actions.size(); i++) { + Action *action = p_action_set->actions[i]; + + openxr_api->action_free(action->action_rid); + + memdelete(action); + } + p_action_set->actions.clear(); +} + +OpenXRInterface::Tracker *OpenXRInterface::find_tracker(const String &p_tracker_name, bool p_create) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, nullptr); + ERR_FAIL_NULL_V(openxr_api, nullptr); + + Tracker *tracker = nullptr; + for (int i = 0; i < trackers.size(); i++) { + tracker = trackers[i]; + if (tracker->tracker_name == p_tracker_name) { + return tracker; + } + } + + if (!p_create) { + return nullptr; + } + + // Create our RID + RID tracker_rid = openxr_api->tracker_create(p_tracker_name); + ERR_FAIL_COND_V(tracker_rid.is_null(), nullptr); + + // create our positional tracker + Ref<XRPositionalTracker> positional_tracker; + positional_tracker.instantiate(); + + // We have standardised some names to make things nicer to the user so lets recognise the toplevel paths related to these. + if (p_tracker_name == "/user/hand/left") { + positional_tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER); + positional_tracker->set_tracker_name("left_hand"); + positional_tracker->set_tracker_desc("Left hand controller"); + positional_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_LEFT); + } else if (p_tracker_name == "/user/hand/right") { + positional_tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER); + positional_tracker->set_tracker_name("right_hand"); + positional_tracker->set_tracker_desc("Right hand controller"); + positional_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_RIGHT); + } else { + positional_tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER); + positional_tracker->set_tracker_name(p_tracker_name); + positional_tracker->set_tracker_desc(p_tracker_name); + } + positional_tracker->set_tracker_profile(INTERACTION_PROFILE_NONE); + xr_server->add_tracker(positional_tracker); + + // create a new entry + tracker = memnew(Tracker); + tracker->tracker_name = p_tracker_name; + tracker->tracker_rid = tracker_rid; + tracker->positional_tracker = positional_tracker; + tracker->interaction_profile = RID(); + trackers.push_back(tracker); + + return tracker; +} + +void OpenXRInterface::tracker_profile_changed(RID p_tracker, RID p_interaction_profile) { + Tracker *tracker = nullptr; + for (int i = 0; i < trackers.size() && tracker == nullptr; i++) { + if (trackers[i]->tracker_rid == p_tracker) { + tracker = trackers[i]; + } + } + ERR_FAIL_NULL(tracker); + + tracker->interaction_profile = p_interaction_profile; + + if (p_interaction_profile.is_null()) { + print_verbose("OpenXR: Interaction profile for " + tracker->tracker_name + " changed to " + INTERACTION_PROFILE_NONE); + tracker->positional_tracker->set_tracker_profile(INTERACTION_PROFILE_NONE); + } else { + String name = openxr_api->interaction_profile_get_name(p_interaction_profile); + print_verbose("OpenXR: Interaction profile for " + tracker->tracker_name + " changed to " + name); + tracker->positional_tracker->set_tracker_profile(name); + } +} + +void OpenXRInterface::link_action_to_tracker(Tracker *p_tracker, Action *p_action) { + if (p_tracker->actions.find(p_action) == -1) { + p_tracker->actions.push_back(p_action); + } +} + +void OpenXRInterface::handle_tracker(Tracker *p_tracker) { + ERR_FAIL_NULL(openxr_api); + ERR_FAIL_COND(p_tracker->positional_tracker.is_null()); + + // Note, which actions are actually bound to inputs are handled by our interaction profiles however interaction + // profiles are suggested bindings for controller types we know about. OpenXR runtimes can stray away from these + // and rebind them or even offer bindings to controllers that are not known to us. + + // We don't really have a consistant way to detect whether a controller is active however as long as it is + // unbound it seems to be unavailable, so far unknown controller seem to mimic one of the profiles we've + // supplied. + if (p_tracker->interaction_profile.is_null()) { + return; + } + + // We check all actions that are related to our tracker. + for (int i = 0; i < p_tracker->actions.size(); i++) { + Action *action = p_tracker->actions[i]; + switch (action->action_type) { + case OpenXRAction::OPENXR_ACTION_BOOL: { + bool pressed = openxr_api->get_action_bool(action->action_rid, p_tracker->tracker_rid); + p_tracker->positional_tracker->set_input(action->action_name, Variant(pressed)); + } break; + case OpenXRAction::OPENXR_ACTION_FLOAT: { + real_t value = openxr_api->get_action_float(action->action_rid, p_tracker->tracker_rid); + p_tracker->positional_tracker->set_input(action->action_name, Variant(value)); + } break; + case OpenXRAction::OPENXR_ACTION_VECTOR2: { + Vector2 value = openxr_api->get_action_vector2(action->action_rid, p_tracker->tracker_rid); + p_tracker->positional_tracker->set_input(action->action_name, Variant(value)); + } break; + case OpenXRAction::OPENXR_ACTION_POSE: { + Transform3D transform; + Vector3 linear, angular; + + XRPose::TrackingConfidence confidence = openxr_api->get_action_pose(action->action_rid, p_tracker->tracker_rid, transform, linear, angular); + + if (confidence != XRPose::XR_TRACKING_CONFIDENCE_NONE) { + p_tracker->positional_tracker->set_pose(action->action_name, transform, linear, angular, confidence); + } else { + p_tracker->positional_tracker->invalidate_pose(action->action_name); + } + } break; + default: { + // not yet supported + } break; + } + } +} + +void OpenXRInterface::trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec) { + ERR_FAIL_NULL(openxr_api); + Action *action = find_action(p_action_name); + ERR_FAIL_NULL(action); + Tracker *tracker = find_tracker(p_tracker_name); + ERR_FAIL_NULL(tracker); + + // TODO OpenXR does not support delay, so we may need to add support for that somehow... + + XrDuration duration = XrDuration(p_duration_sec * 1000000000.0); // seconds -> nanoseconds + + openxr_api->trigger_haptic_pulse(action->action_rid, tracker->tracker_rid, p_frequency, p_amplitude, duration); +} + +void OpenXRInterface::free_trackers() { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + ERR_FAIL_NULL(openxr_api); + + for (int i = 0; i < trackers.size(); i++) { + Tracker *tracker = trackers[i]; + + openxr_api->tracker_free(tracker->tracker_rid); + xr_server->remove_tracker(tracker->positional_tracker); + tracker->positional_tracker.unref(); + + memdelete(tracker); + } + trackers.clear(); +} + +void OpenXRInterface::free_interaction_profiles() { + ERR_FAIL_NULL(openxr_api); + + for (int i = 0; i < interaction_profiles.size(); i++) { + openxr_api->interaction_profile_free(interaction_profiles[i]); + } + interaction_profiles.clear(); +} + +bool OpenXRInterface::initialise_on_startup() const { + if (openxr_api == nullptr) { + return false; + } else if (!openxr_api->is_initialized()) { + return false; + } else { + return true; + } +} + +bool OpenXRInterface::is_initialized() const { + return initialized; +}; + +bool OpenXRInterface::initialize() { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, false); + + if (openxr_api == nullptr) { + return false; + } else if (!openxr_api->is_initialized()) { + return false; + } else if (initialized) { + return true; + } + + // load up our action sets before setting up our session, note that our profiles are suggestions, OpenXR takes ownership of (re)binding + _load_action_map(); + + if (!openxr_api->initialise_session()) { + return false; + } + + // we must create a tracker for our head + head.instantiate(); + head->set_tracker_type(XRServer::TRACKER_HEAD); + head->set_tracker_name("head"); + head->set_tracker_desc("Players head"); + xr_server->add_tracker(head); + + // attach action sets + for (int i = 0; i < action_sets.size(); i++) { + openxr_api->action_set_attach(action_sets[i]->action_set_rid); + } + + // make this our primary interface + xr_server->set_primary_interface(this); + + initialized = true; + + return initialized; +} + +void OpenXRInterface::uninitialize() { + // Our OpenXR driver will clean itself up properly when Godot exits, so we just do some basic stuff here + + // end the session if we need to? + + // cleanup stuff + free_trackers(); + free_interaction_profiles(); + free_action_sets(); + + XRServer *xr_server = XRServer::get_singleton(); + if (xr_server) { + if (head.is_valid()) { + xr_server->remove_tracker(head); + head.unref(); + } + } + + initialized = false; +} + +bool OpenXRInterface::supports_play_area_mode(XRInterface::PlayAreaMode p_mode) { + return false; +} + +XRInterface::PlayAreaMode OpenXRInterface::get_play_area_mode() const { + return XRInterface::XR_PLAY_AREA_UNKNOWN; +} + +bool OpenXRInterface::set_play_area_mode(XRInterface::PlayAreaMode p_mode) { + return false; +} + +Size2 OpenXRInterface::get_render_target_size() { + if (openxr_api == nullptr) { + return Size2(); + } else { + return openxr_api->get_recommended_target_size(); + } +} + +uint32_t OpenXRInterface::get_view_count() { + // TODO set this based on our configuration + return 2; +} + +void OpenXRInterface::_set_default_pos(Transform3D &p_transform, double p_world_scale, uint64_t p_eye) { + p_transform = Transform3D(); + + // if we're not tracking, don't put our head on the floor... + p_transform.origin.y = 1.5 * p_world_scale; + + // overkill but.. + if (p_eye == 1) { + p_transform.origin.x = 0.03 * p_world_scale; + } else if (p_eye == 2) { + p_transform.origin.x = -0.03 * p_world_scale; + } +} + +Transform3D OpenXRInterface::get_camera_transform() { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, Transform3D()); + + Transform3D hmd_transform; + double world_scale = xr_server->get_world_scale(); + + // head_transform should be updated in process + + hmd_transform.basis = head_transform.basis; + hmd_transform.origin = head_transform.origin * world_scale; + + return hmd_transform; +} + +Transform3D OpenXRInterface::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, Transform3D()); + + Transform3D t; + if (openxr_api && openxr_api->get_view_transform(p_view, t)) { + // update our cached value if we have a valid transform + transform_for_view[p_view] = t; + } else { + // reuse cached value + t = transform_for_view[p_view]; + } + + // Apply our world scale + double world_scale = xr_server->get_world_scale(); + t.origin *= world_scale; + + return p_cam_transform * xr_server->get_reference_frame() * t; +} + +CameraMatrix OpenXRInterface::get_projection_for_view(uint32_t p_view, double p_aspect, double p_z_near, double p_z_far) { + CameraMatrix cm; + + if (openxr_api) { + if (openxr_api->get_view_projection(p_view, p_z_near, p_z_far, cm)) { + return cm; + } + } + + // Failed to get from our OpenXR device? Default to some sort of sensible camera matrix.. + cm.set_for_hmd(p_view + 1, 1.0, 6.0, 14.5, 4.0, 1.5, p_z_near, p_z_far); + + return cm; +} + +void OpenXRInterface::process() { + if (openxr_api) { + // do our normal process + if (openxr_api->process()) { + Transform3D t; + Vector3 linear_velocity; + Vector3 angular_velocity; + XRPose::TrackingConfidence confidence = openxr_api->get_head_center(t, linear_velocity, angular_velocity); + if (confidence != XRPose::XR_TRACKING_CONFIDENCE_NONE) { + // Only update our transform if we have one to update it with + // note that poses are stored without world scale and reference frame applied! + head_transform = t; + head_linear_velocity = linear_velocity; + head_angular_velocity = angular_velocity; + } + } + + // handle our action sets.... + Vector<RID> active_sets; + for (int i = 0; i < action_sets.size(); i++) { + if (action_sets[i]->is_active) { + active_sets.push_back(action_sets[i]->action_set_rid); + } + } + + if (openxr_api->sync_action_sets(active_sets)) { + for (int i = 0; i < trackers.size(); i++) { + handle_tracker(trackers[i]); + } + } + } + + if (head.is_valid()) { + // TODO figure out how to get our velocities + + head->set_pose("default", head_transform, head_linear_velocity, head_angular_velocity); + + // TODO set confidence on pose once we support tracking this.. + } +} + +void OpenXRInterface::pre_render() { + if (openxr_api) { + openxr_api->pre_render(); + } +} + +bool OpenXRInterface::pre_draw_viewport(RID p_render_target) { + if (openxr_api) { + return openxr_api->pre_draw_viewport(p_render_target); + } else { + // don't render + return false; + } +} + +Vector<BlitToScreen> OpenXRInterface::post_draw_viewport(RID p_render_target, const Rect2 &p_screen_rect) { + Vector<BlitToScreen> blit_to_screen; + + // If separate HMD we should output one eye to screen + if (p_screen_rect != Rect2()) { + BlitToScreen blit; + + blit.render_target = p_render_target; + blit.multi_view.use_layer = true; + blit.multi_view.layer = 0; + blit.lens_distortion.apply = false; + + Size2 render_size = get_render_target_size(); + Rect2 dst_rect = p_screen_rect; + float new_height = dst_rect.size.x * (render_size.y / render_size.x); + if (new_height > dst_rect.size.y) { + dst_rect.position.y = (0.5 * dst_rect.size.y) - (0.5 * new_height); + dst_rect.size.y = new_height; + } else { + float new_width = dst_rect.size.y * (render_size.x / render_size.y); + + dst_rect.position.x = (0.5 * dst_rect.size.x) - (0.5 * new_width); + dst_rect.size.x = new_width; + } + + blit.dst_rect = dst_rect; + blit_to_screen.push_back(blit); + } + + if (openxr_api) { + openxr_api->post_draw_viewport(p_render_target); + } + + return blit_to_screen; +} + +void OpenXRInterface::end_frame() { + if (openxr_api) { + openxr_api->end_frame(); + } +} + +void OpenXRInterface::on_state_ready() { + emit_signal(SNAME("session_begun")); +} + +void OpenXRInterface::on_state_visible() { + emit_signal(SNAME("session_visible")); +} + +void OpenXRInterface::on_state_focused() { + emit_signal(SNAME("session_focussed")); +} + +void OpenXRInterface::on_state_stopping() { + emit_signal(SNAME("session_stopping")); +} + +void OpenXRInterface::on_pose_recentered() { + emit_signal(SNAME("pose_recentered")); +} + +OpenXRInterface::OpenXRInterface() { + openxr_api = OpenXRAPI::get_singleton(); + if (openxr_api) { + openxr_api->set_xr_interface(this); + } + + // while we don't have head tracking, don't put the headset on the floor... + _set_default_pos(head_transform, 1.0, 0); + _set_default_pos(transform_for_view[0], 1.0, 1); + _set_default_pos(transform_for_view[1], 1.0, 2); +} + +OpenXRInterface::~OpenXRInterface() { + if (is_initialized()) { + uninitialize(); + } + + if (openxr_api) { + openxr_api->set_xr_interface(nullptr); + openxr_api = nullptr; + } +} diff --git a/modules/openxr/openxr_interface.h b/modules/openxr/openxr_interface.h new file mode 100644 index 0000000000..421838e445 --- /dev/null +++ b/modules/openxr/openxr_interface.h @@ -0,0 +1,143 @@ +/*************************************************************************/ +/* openxr_interface.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_INTERFACE_H +#define OPENXR_INTERFACE_H + +#include "servers/xr/xr_interface.h" +#include "servers/xr/xr_positional_tracker.h" + +#include "action_map/openxr_action_map.h" +#include "openxr_api.h" + +// declare some default strings +#define INTERACTION_PROFILE_NONE "/interaction_profiles/none" + +class OpenXRInterface : public XRInterface { + GDCLASS(OpenXRInterface, XRInterface); + +private: + OpenXRAPI *openxr_api = nullptr; + bool initialized = false; + XRInterface::TrackingStatus tracking_state; + + // At a minimum we need a tracker for our head + Ref<XRPositionalTracker> head; + Transform3D head_transform; + Vector3 head_linear_velocity; + Vector3 head_angular_velocity; + Transform3D transform_for_view[2]; // We currently assume 2, but could be 4 for VARJO which we do not support yet + + void _load_action_map(); + + struct Action { // An action we've registered with OpenXR + String action_name; // Name of our action as presented to Godot (can be altered from the action map) + OpenXRAction::ActionType action_type; // The action type of this action + RID action_rid; // RID of the action registered with our OpenXR API + }; + struct ActionSet { // An action set we've registered with OpenXR + String action_set_name; // Name of our action set + bool is_active; // If true this action set is active and we will sync it + Vector<Action *> actions; // List of actions in this action set + RID action_set_rid; // RID of the action registered with our OpenXR API + }; + struct Tracker { // A tracker we've registered with OpenXR + String tracker_name; // Name of our tracker (can be altered from the action map) + Vector<Action *> actions; // Actions related to this tracker + Ref<XRPositionalTracker> positional_tracker; // Our positional tracker object that holds our tracker state + RID tracker_rid; // RID of the tracker registered with our OpenXR API + RID interaction_profile; // RID of the interaction profile bound to this tracker (can be null) + }; + + Vector<ActionSet *> action_sets; + Vector<RID> interaction_profiles; + Vector<Tracker *> trackers; + + ActionSet *create_action_set(const String &p_action_set_name, const String &p_localized_name, const int p_priority); + void free_action_sets(); + + Action *create_action(ActionSet *p_action_set, const String &p_action_name, const String &p_localized_name, OpenXRAction::ActionType p_action_type, const Vector<Tracker *> p_trackers); + Action *find_action(const String &p_action_name); + void free_actions(ActionSet *p_action_set); + + Tracker *find_tracker(const String &p_tracker_name, bool p_create = false); + void link_action_to_tracker(Tracker *p_tracker, Action *p_action); + void handle_tracker(Tracker *p_tracker); + void free_trackers(); + + void free_interaction_profiles(); + + void _set_default_pos(Transform3D &p_transform, double p_world_scale, uint64_t p_eye); + +protected: + static void _bind_methods(); + +public: + virtual StringName get_name() const override; + virtual uint32_t get_capabilities() const override; + + virtual PackedStringArray get_suggested_tracker_names() const override; + virtual TrackingStatus get_tracking_status() const override; + + bool initialise_on_startup() const; + virtual bool is_initialized() const override; + virtual bool initialize() override; + virtual void uninitialize() override; + + virtual void trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec = 0) override; + + virtual bool supports_play_area_mode(XRInterface::PlayAreaMode p_mode) override; + virtual XRInterface::PlayAreaMode get_play_area_mode() const override; + virtual bool set_play_area_mode(XRInterface::PlayAreaMode p_mode) override; + + virtual Size2 get_render_target_size() override; + virtual uint32_t get_view_count() override; + virtual Transform3D get_camera_transform() override; + virtual Transform3D get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) override; + virtual CameraMatrix get_projection_for_view(uint32_t p_view, double p_aspect, double p_z_near, double p_z_far) override; + + virtual void process() override; + virtual void pre_render() override; + bool pre_draw_viewport(RID p_render_target) override; + virtual Vector<BlitToScreen> post_draw_viewport(RID p_render_target, const Rect2 &p_screen_rect) override; + virtual void end_frame() override; + + void on_state_ready(); + void on_state_visible(); + void on_state_focused(); + void on_state_stopping(); + void on_pose_recentered(); + void tracker_profile_changed(RID p_tracker, RID p_interaction_profile); + + OpenXRInterface(); + ~OpenXRInterface(); +}; + +#endif // !OPENXR_INTERFACE_H diff --git a/modules/openxr/openxr_util.cpp b/modules/openxr/openxr_util.cpp new file mode 100644 index 0000000000..230b10c5f1 --- /dev/null +++ b/modules/openxr/openxr_util.cpp @@ -0,0 +1,305 @@ +/*************************************************************************/ +/* openxr_util.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_util.h" + +#define ENUM_TO_STRING_CASE(e) \ + case e: { \ + return String(#e); \ + } break; + +// TODO see if we can generate this code further using the xml file with meta data supplied by OpenXR + +String OpenXRUtil::get_view_configuration_name(XrViewConfigurationType p_view_configuration) { + switch (p_view_configuration) { + ENUM_TO_STRING_CASE(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO) + ENUM_TO_STRING_CASE(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO) + ENUM_TO_STRING_CASE(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO) + ENUM_TO_STRING_CASE(XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT) + ENUM_TO_STRING_CASE(XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM) + default: { + return String("View Configuration ") + String::num_int64(int64_t(p_view_configuration)); + } break; + } +} + +String OpenXRUtil::get_reference_space_name(XrReferenceSpaceType p_reference_space) { + switch (p_reference_space) { + ENUM_TO_STRING_CASE(XR_REFERENCE_SPACE_TYPE_VIEW) + ENUM_TO_STRING_CASE(XR_REFERENCE_SPACE_TYPE_LOCAL) + ENUM_TO_STRING_CASE(XR_REFERENCE_SPACE_TYPE_STAGE) + ENUM_TO_STRING_CASE(XR_REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT) + ENUM_TO_STRING_CASE(XR_REFERENCE_SPACE_TYPE_COMBINED_EYE_VARJO) + ENUM_TO_STRING_CASE(XR_REFERENCE_SPACE_TYPE_MAX_ENUM) + default: { + return String("Reference space ") + String::num_int64(int64_t(p_reference_space)); + } break; + } +} + +String OpenXRUtil::get_structure_type_name(XrStructureType p_structure_type) { + switch (p_structure_type) { + ENUM_TO_STRING_CASE(XR_TYPE_UNKNOWN) + ENUM_TO_STRING_CASE(XR_TYPE_API_LAYER_PROPERTIES) + ENUM_TO_STRING_CASE(XR_TYPE_EXTENSION_PROPERTIES) + ENUM_TO_STRING_CASE(XR_TYPE_INSTANCE_CREATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_GET_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_PROPERTIES) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW_LOCATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW) + ENUM_TO_STRING_CASE(XR_TYPE_SESSION_CREATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_CREATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_SESSION_BEGIN_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW_STATE) + ENUM_TO_STRING_CASE(XR_TYPE_FRAME_END_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_HAPTIC_VIBRATION) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_BUFFER) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_STATE_BOOLEAN) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_STATE_FLOAT) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_STATE_VECTOR2F) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_STATE_POSE) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_SET_CREATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_CREATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_INSTANCE_PROPERTIES) + ENUM_TO_STRING_CASE(XR_TYPE_FRAME_WAIT_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_PROJECTION) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_QUAD) + ENUM_TO_STRING_CASE(XR_TYPE_REFERENCE_SPACE_CREATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_SPACE_CREATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW_CONFIGURATION_VIEW) + ENUM_TO_STRING_CASE(XR_TYPE_SPACE_LOCATION) + ENUM_TO_STRING_CASE(XR_TYPE_SPACE_VELOCITY) + ENUM_TO_STRING_CASE(XR_TYPE_FRAME_STATE) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW_CONFIGURATION_PROPERTIES) + ENUM_TO_STRING_CASE(XR_TYPE_FRAME_BEGIN_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_EVENTS_LOST) + ENUM_TO_STRING_CASE(XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED) + ENUM_TO_STRING_CASE(XR_TYPE_INTERACTION_PROFILE_STATE) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_ACTION_STATE_GET_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_HAPTIC_ACTION_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_ACTIONS_SYNC_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_CUBE_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_VULKAN_SWAPCHAIN_FORMAT_LIST_CREATE_INFO_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_PERF_SETTINGS_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_EQUIRECT_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_DEBUG_UTILS_LABEL_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_OPENGL_XCB_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_OPENGL_WAYLAND_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_D3D11_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_D3D12_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_D3D12_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_REQUIREMENTS_D3D12_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_EYE_GAZE_SAMPLE_TIME_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_VISIBILITY_MASK_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SESSION_CREATE_INFO_OVERLAY_EXTX) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_MAIN_SESSION_VISIBILITY_CHANGED_EXTX) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SPATIAL_ANCHOR_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SPATIAL_ANCHOR_SPACE_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_ALPHA_BLEND_FB) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW_CONFIGURATION_DEPTH_RANGE_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_GRAPHICS_BINDING_EGL_MNDX) + ENUM_TO_STRING_CASE(XR_TYPE_SPATIAL_GRAPH_NODE_SPACE_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_JOINT_LOCATIONS_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_JOINT_VELOCITIES_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_MESH_UPDATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_MESH_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_POSE_TYPE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SESSION_BEGIN_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_STATE_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_STATE_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_END_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_LAYER_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SWAPCHAIN_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_CONTROLLER_MODEL_NODE_STATE_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_CONTROLLER_MODEL_STATE_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW_CONFIGURATION_VIEW_FOV_EPIC) + ENUM_TO_STRING_CASE(XR_TYPE_HOLOGRAPHIC_WINDOW_ATTACHMENT_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_REPROJECTION_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_REPROJECTION_PLANE_OVERRIDE_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_ANDROID_SURFACE_SWAPCHAIN_CREATE_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_SECURE_CONTENT_FB) + ENUM_TO_STRING_CASE(XR_TYPE_INTERACTION_PROFILE_ANALOG_THRESHOLD_VALVE) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_JOINTS_MOTION_RANGE_INFO_EXT) + ENUM_TO_STRING_CASE(XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_OBSERVER_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_NEW_SCENE_COMPUTE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_VISUAL_MESH_COMPUTE_LOD_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_COMPONENTS_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_COMPONENTS_GET_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_COMPONENT_LOCATIONS_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_COMPONENTS_LOCATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_OBJECTS_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_COMPONENT_PARENT_FILTER_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_OBJECT_TYPES_FILTER_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_PLANES_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_PLANE_ALIGNMENT_FILTER_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_MESHES_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_MESH_BUFFERS_GET_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_MESH_BUFFERS_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_MESH_VERTEX_BUFFER_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_MESH_INDICES_UINT32_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_MESH_INDICES_UINT16_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SERIALIZED_SCENE_FRAGMENT_DATA_GET_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SCENE_DESERIALIZE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_DISPLAY_REFRESH_RATE_CHANGED_FB) + ENUM_TO_STRING_CASE(XR_TYPE_VIVE_TRACKER_PATHS_HTCX) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_VIVE_TRACKER_CONNECTED_HTCX) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_TRACKING_MESH_FB) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_TRACKING_SCALE_FB) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_TRACKING_AIM_STATE_FB) + ENUM_TO_STRING_CASE(XR_TYPE_HAND_TRACKING_CAPSULES_STATE_FB) + ENUM_TO_STRING_CASE(XR_TYPE_FOVEATION_PROFILE_CREATE_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_CREATE_INFO_FOVEATION_FB) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_STATE_FOVEATION_FB) + ENUM_TO_STRING_CASE(XR_TYPE_FOVEATION_LEVEL_PROFILE_CREATE_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_TRIANGLE_MESH_CREATE_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES_FB) + ENUM_TO_STRING_CASE(XR_TYPE_PASSTHROUGH_CREATE_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB) + ENUM_TO_STRING_CASE(XR_TYPE_GEOMETRY_INSTANCE_CREATE_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_GEOMETRY_INSTANCE_TRANSFORM_FB) + ENUM_TO_STRING_CASE(XR_TYPE_PASSTHROUGH_STYLE_FB) + ENUM_TO_STRING_CASE(XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_RGBA_FB) + ENUM_TO_STRING_CASE(XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_MONO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_PASSTHROUGH_STATE_CHANGED_FB) + ENUM_TO_STRING_CASE(XR_TYPE_BINDING_MODIFICATIONS_KHR) + ENUM_TO_STRING_CASE(XR_TYPE_VIEW_LOCATE_FOVEATED_RENDERING_VARJO) + ENUM_TO_STRING_CASE(XR_TYPE_FOVEATED_VIEW_CONFIGURATION_VIEW_VARJO) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_FOVEATED_RENDERING_PROPERTIES_VARJO) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_DEPTH_TEST_VARJO) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_MARKER_TRACKING_PROPERTIES_VARJO) + ENUM_TO_STRING_CASE(XR_TYPE_EVENT_DATA_MARKER_TRACKING_UPDATE_VARJO) + ENUM_TO_STRING_CASE(XR_TYPE_MARKER_SPACE_CREATE_INFO_VARJO) + ENUM_TO_STRING_CASE(XR_TYPE_SPATIAL_ANCHOR_PERSISTENCE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SPATIAL_ANCHOR_FROM_PERSISTED_ANCHOR_CREATE_INFO_MSFT) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_IMAGE_FOVEATION_VULKAN_FB) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_STATE_ANDROID_SURFACE_DIMENSIONS_FB) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_STATE_SAMPLER_OPENGL_ES_FB) + ENUM_TO_STRING_CASE(XR_TYPE_SWAPCHAIN_STATE_SAMPLER_VULKAN_FB) + ENUM_TO_STRING_CASE(XR_TYPE_COMPOSITION_LAYER_SPACE_WARP_INFO_FB) + ENUM_TO_STRING_CASE(XR_TYPE_SYSTEM_SPACE_WARP_PROPERTIES_FB) + ENUM_TO_STRING_CASE(XR_STRUCTURE_TYPE_MAX_ENUM) + default: { + return String("Structure type ") + String::num_int64(int64_t(p_structure_type)); + } break; + } +} + +String OpenXRUtil::get_session_state_name(XrSessionState p_session_state) { + switch (p_session_state) { + ENUM_TO_STRING_CASE(XR_SESSION_STATE_UNKNOWN) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_IDLE) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_READY) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_SYNCHRONIZED) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_VISIBLE) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_FOCUSED) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_STOPPING) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_LOSS_PENDING) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_EXITING) + ENUM_TO_STRING_CASE(XR_SESSION_STATE_MAX_ENUM) + default: { + return String("Session state ") + String::num_int64(int64_t(p_session_state)); + } break; + } +} + +String OpenXRUtil::get_action_type_name(XrActionType p_action_type) { + switch (p_action_type) { + ENUM_TO_STRING_CASE(XR_ACTION_TYPE_BOOLEAN_INPUT) + ENUM_TO_STRING_CASE(XR_ACTION_TYPE_FLOAT_INPUT) + ENUM_TO_STRING_CASE(XR_ACTION_TYPE_VECTOR2F_INPUT) + ENUM_TO_STRING_CASE(XR_ACTION_TYPE_POSE_INPUT) + ENUM_TO_STRING_CASE(XR_ACTION_TYPE_VIBRATION_OUTPUT) + ENUM_TO_STRING_CASE(XR_ACTION_TYPE_MAX_ENUM) + default: { + return String("Action type ") + String::num_int64(int64_t(p_action_type)); + } break; + } +} + +String OpenXRUtil::make_xr_version_string(XrVersion p_version) { + String version; + + version += String::num_int64(XR_VERSION_MAJOR(p_version)); + version += String("."); + version += String::num_int64(XR_VERSION_MINOR(p_version)); + version += String("."); + version += String::num_int64(XR_VERSION_PATCH(p_version)); + + return version; +} diff --git a/modules/gdnative/nativescript/api_generator.h b/modules/openxr/openxr_util.h index 58e141f07e..4371b74d2f 100644 --- a/modules/gdnative/nativescript/api_generator.h +++ b/modules/openxr/openxr_util.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* api_generator.h */ +/* openxr_util.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,13 +28,20 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef API_GENERATOR_H -#define API_GENERATOR_H +#ifndef OPENXR_UTIL_H +#define OPENXR_UTIL_H #include "core/string/ustring.h" -#include "core/typedefs.h" +#include <openxr/openxr.h> -Error generate_c_api(const String &p_path); -Error generate_c_builtin_api(const String &p_path); +class OpenXRUtil { +public: + static String get_view_configuration_name(XrViewConfigurationType p_view_configuration); + static String get_reference_space_name(XrReferenceSpaceType p_reference_space); + static String get_structure_type_name(XrStructureType p_structure_type); + static String get_session_state_name(XrSessionState p_session_state); + static String get_action_type_name(XrActionType p_action_type); + static String make_xr_version_string(XrVersion p_version); +}; -#endif // API_GENERATOR_H +#endif // !OPENXR_UTIL_H diff --git a/modules/gdnative/nativescript/register_types.cpp b/modules/openxr/register_types.cpp index ee63dca9a3..7a74c8c089 100644 --- a/modules/gdnative/nativescript/register_types.cpp +++ b/modules/openxr/register_types.cpp @@ -29,43 +29,72 @@ /*************************************************************************/ #include "register_types.h" +#include "main/main.h" -#include "core/io/resource_loader.h" -#include "core/io/resource_saver.h" +#include "openxr_interface.h" -#include "nativescript.h" +#include "action_map/openxr_action.h" +#include "action_map/openxr_action_map.h" +#include "action_map/openxr_action_set.h" +#include "action_map/openxr_interaction_profile.h" -#include "core/os/os.h" +OpenXRAPI *openxr_api = nullptr; +Ref<OpenXRInterface> openxr_interface; -NativeScriptLanguage *native_script_language; +void preregister_openxr_types() { + // For now we create our openxr device here. If we merge it with openxr_interface we'll create that here soon. -Ref<ResourceFormatLoaderNativeScript> resource_loader_gdns; -Ref<ResourceFormatSaverNativeScript> resource_saver_gdns; - -void register_nativescript_types() { - native_script_language = memnew(NativeScriptLanguage); + OpenXRAPI::setup_global_defs(); + openxr_api = OpenXRAPI::get_singleton(); + if (openxr_api) { + if (!openxr_api->initialise(Main::get_rendering_driver_name())) { + return; + } + } +} - GDREGISTER_CLASS(NativeScript); +void register_openxr_types() { + GDREGISTER_CLASS(OpenXRInterface); - native_script_language->set_language_index(ScriptServer::get_language_count()); - ScriptServer::register_language(native_script_language); + GDREGISTER_CLASS(OpenXRAction); + GDREGISTER_CLASS(OpenXRActionSet); + GDREGISTER_CLASS(OpenXRActionMap); + GDREGISTER_CLASS(OpenXRIPBinding); + GDREGISTER_CLASS(OpenXRInteractionProfile); - resource_saver_gdns.instantiate(); - ResourceSaver::add_resource_format_saver(resource_saver_gdns); + XRServer *xr_server = XRServer::get_singleton(); + if (xr_server) { + openxr_interface.instantiate(); + xr_server->add_interface(openxr_interface); - resource_loader_gdns.instantiate(); - ResourceLoader::add_resource_format_loader(resource_loader_gdns); + if (openxr_interface->initialise_on_startup()) { + openxr_interface->initialize(); + } + } } -void unregister_nativescript_types() { - ResourceLoader::remove_resource_format_loader(resource_loader_gdns); - resource_loader_gdns.unref(); +void unregister_openxr_types() { + if (openxr_interface.is_valid()) { + // uninitialise just in case + if (openxr_interface->is_initialized()) { + openxr_interface->uninitialize(); + } + + // unregister our interface from the XR server + XRServer *xr_server = XRServer::get_singleton(); + if (xr_server) { + if (xr_server->get_primary_interface() == openxr_interface) { + xr_server->set_primary_interface(Ref<XRInterface>()); + } + xr_server->remove_interface(openxr_interface); + } - ResourceSaver::remove_resource_format_saver(resource_saver_gdns); - resource_saver_gdns.unref(); + // and release + openxr_interface.unref(); + } - if (native_script_language) { - ScriptServer::unregister_language(native_script_language); - memdelete(native_script_language); + if (openxr_api) { + openxr_api->finish(); + memdelete(openxr_api); } } diff --git a/modules/bullet/register_types.h b/modules/openxr/register_types.h index 93847d6dc3..fb42770750 100644 --- a/modules/bullet/register_types.h +++ b/modules/openxr/register_types.h @@ -28,10 +28,13 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef REGISTER_BULLET_TYPES_H -#define REGISTER_BULLET_TYPES_H +#ifndef OPENXR_REGISTER_TYPES_H +#define OPENXR_REGISTER_TYPES_H -void register_bullet_types(); -void unregister_bullet_types(); +#define MODULE_OPENXR_HAS_PREREGISTER -#endif // REGISTER_BULLET_TYPES_H +void preregister_openxr_types(); +void register_openxr_types(); +void unregister_openxr_types(); + +#endif // OPENXR_REGISTER_TYPES_H diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml index 2ae2e53b02..deabc5ccd3 100644 --- a/modules/regex/doc_classes/RegEx.xml +++ b/modules/regex/doc_classes/RegEx.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="RegEx" inherits="RefCounted" version="4.0"> +<class name="RegEx" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Class for searching text for patterns using regular expressions. </brief_description> diff --git a/modules/regex/doc_classes/RegExMatch.xml b/modules/regex/doc_classes/RegExMatch.xml index 20680b41fd..530a541ae8 100644 --- a/modules/regex/doc_classes/RegExMatch.xml +++ b/modules/regex/doc_classes/RegExMatch.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="RegExMatch" inherits="RefCounted" version="4.0"> +<class name="RegExMatch" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Contains the results of a [RegEx] search. </brief_description> diff --git a/modules/svg/SCsub b/modules/svg/SCsub index bb03147731..93262f4f87 100644 --- a/modules/svg/SCsub +++ b/modules/svg/SCsub @@ -34,6 +34,7 @@ thirdparty_sources = [ "src/loaders/svg/tvgSvgSceneBuilder.cpp", "src/loaders/svg/tvgSvgPath.cpp", "src/loaders/svg/tvgSvgLoader.cpp", + "src/loaders/svg/tvgSvgCssStyle.cpp", "src/loaders/tvg/tvgTvgBinInterpreter.cpp", "src/loaders/tvg/tvgTvgLoader.cpp", "src/loaders/jpg/tvgJpgLoader.cpp", diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp index 96b83bf25a..79ef2de929 100644 --- a/modules/svg/image_loader_svg.cpp +++ b/modules/svg/image_loader_svg.cpp @@ -78,7 +78,7 @@ void ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_strin return; } float fw, fh; - picture->viewbox(nullptr, nullptr, &fw, &fh); + picture->size(&fw, &fh); uint32_t width = MIN(fw * p_scale, 16 * 1024); uint32_t height = MIN(fh * p_scale, 16 * 1024); diff --git a/modules/text_server_adv/SCsub b/modules/text_server_adv/SCsub index 6a06619840..5e5c284b57 100644 --- a/modules/text_server_adv/SCsub +++ b/modules/text_server_adv/SCsub @@ -49,6 +49,7 @@ if env["builtin_harfbuzz"]: "src/hb-aat-map.cc", "src/hb-blob.cc", "src/hb-buffer-serialize.cc", + "src/hb-buffer-verify.cc", "src/hb-buffer.cc", "src/hb-common.cc", #'src/hb-coretext.cc', diff --git a/modules/text_server_adv/doc_classes/TextServerAdvanced.xml b/modules/text_server_adv/doc_classes/TextServerAdvanced.xml index eff4aa5fae..bf86eb6406 100644 --- a/modules/text_server_adv/doc_classes/TextServerAdvanced.xml +++ b/modules/text_server_adv/doc_classes/TextServerAdvanced.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="TextServerAdvanced" inherits="TextServer" version="4.0"> +<class name="TextServerAdvanced" inherits="TextServer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Text Server using HarfBuzz, ICU and SIL Graphite to support BiDi, complex text layouts and contextual OpenType features. </brief_description> diff --git a/modules/text_server_adv/script_iterator.cpp b/modules/text_server_adv/script_iterator.cpp index 9e3d9138d0..06e934c67d 100644 --- a/modules/text_server_adv/script_iterator.cpp +++ b/modules/text_server_adv/script_iterator.cpp @@ -82,7 +82,7 @@ ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length paren_stack[paren_sp].pair_index = ch; paren_stack[paren_sp].script_code = script_code; } else if (paren_sp >= 0) { - // If it's a close character, find the matching open on the stack, and use that script code. Any non-matching open characters above it on the stack will be poped. + // If it's a close character, find the matching open on the stack, and use that script code. Any non-matching open characters above it on the stack will be popped. UChar32 paired_ch = u_getBidiPairedBracket(ch); while (paren_sp >= 0 && paren_stack[paren_sp].pair_index != paired_ch) { paren_sp -= 1; diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp index c7511f587e..7fd9cd42ed 100644 --- a/modules/text_server_adv/text_server_adv.cpp +++ b/modules/text_server_adv/text_server_adv.cpp @@ -704,7 +704,7 @@ String TextServerAdvanced::tag_to_name(int32_t p_tag) const { /* Font Glyph Rendering */ /*************************************************************************/ -_FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_texture_pos_for_glyph(FontDataForSizeAdvanced *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) const { +_FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_texture_pos_for_glyph(FontDataForSizeAdvanced *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const { FontTexturePosition ret; ret.index = -1; @@ -769,8 +769,11 @@ _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_ } texsize = next_power_of_2(texsize); - - texsize = MIN(texsize, 4096); + if (p_msdf) { + texsize = MIN(texsize, 2048); + } else { + texsize = MIN(texsize, 1024); + } FontTexture tex; tex.texture_w = texsize; @@ -935,10 +938,10 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf( int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 4096, FontGlyph()); - ERR_FAIL_COND_V(mh > 4096, FontGlyph()); + ERR_FAIL_COND_V(mw > 1024, FontGlyph()); + ERR_FAIL_COND_V(mh > 1024, FontGlyph()); - FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh); + FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); FontTexture &tex = p_data->textures.write[tex_pos.index]; @@ -1013,13 +1016,13 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitma int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 4096, FontGlyph()); - ERR_FAIL_COND_V(mh > 4096, FontGlyph()); + ERR_FAIL_COND_V(mw > 1024, FontGlyph()); + ERR_FAIL_COND_V(mh > 1024, FontGlyph()); int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2; Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8; - FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh); + FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh, false); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); // Fit character in char texture. @@ -1097,12 +1100,14 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitma _FORCE_INLINE_ bool TextServerAdvanced::_ensure_glyph(FontDataAdvanced *p_font_data, const Vector2i &p_size, int32_t p_glyph) const { ERR_FAIL_COND_V(!_ensure_cache_for_size(p_font_data, p_size), false); + int32_t glyph_index = p_glyph & 0xFFFFFF; // Remove subpixel shifts. + FontDataForSizeAdvanced *fd = p_font_data->cache[p_size]; if (fd->glyph_map.has(p_glyph)) { return fd->glyph_map[p_glyph].found; } - if (p_glyph == 0) { // Non graphical or invalid glyph, do not render. + if (glyph_index == 0) { // Non graphical or invalid glyph, do not render. fd->glyph_map[p_glyph] = FontGlyph(); return true; } @@ -1134,15 +1139,35 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_glyph(FontDataAdvanced *p_font_d } FT_Fixed v, h; - FT_Get_Advance(fd->face, p_glyph, flags, &h); - FT_Get_Advance(fd->face, p_glyph, flags | FT_LOAD_VERTICAL_LAYOUT, &v); + FT_Get_Advance(fd->face, glyph_index, flags, &h); + FT_Get_Advance(fd->face, glyph_index, flags | FT_LOAD_VERTICAL_LAYOUT, &v); - int error = FT_Load_Glyph(fd->face, p_glyph, flags); + int error = FT_Load_Glyph(fd->face, glyph_index, flags); if (error) { fd->glyph_map[p_glyph] = FontGlyph(); return false; } + if (!p_font_data->msdf) { + if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 4; + FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0); + } else if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 5; + FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0); + } + } + + if (p_font_data->embolden != 0.f) { + FT_Pos strength = p_font_data->embolden * p_size.x * 4; // 26.6 fractional units (1 / 64). + FT_Outline_Embolden(&fd->face->glyph->outline, strength); + } + + if (p_font_data->transform != Transform2D()) { + FT_Matrix mat = { FT_Fixed(p_font_data->transform[0][0] * 65536), FT_Fixed(p_font_data->transform[0][1] * 65536), FT_Fixed(p_font_data->transform[1][0] * 65536), FT_Fixed(p_font_data->transform[1][1] * 65536) }; // 16.16 fractional units (1 / 65536). + FT_Outline_Transform(&fd->face->glyph->outline, &mat); + } + if (!outline) { if (!p_font_data->msdf) { error = FT_Render_Glyph(fd->face->glyph, p_font_data->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO); @@ -1844,6 +1869,62 @@ TextServer::Hinting TextServerAdvanced::font_get_hinting(RID p_font_rid) const { return fd->hinting; } +void TextServerAdvanced::font_set_subpixel_positioning(RID p_font_rid, TextServer::SubpixelPositioning p_subpixel) { + FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND(!fd); + + MutexLock lock(fd->mutex); + if (fd->subpixel_positioning != p_subpixel) { + fd->subpixel_positioning = p_subpixel; + } +} + +TextServer::SubpixelPositioning TextServerAdvanced::font_get_subpixel_positioning(RID p_font_rid) const { + FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND_V(!fd, SUBPIXEL_POSITIONING_DISABLED); + + MutexLock lock(fd->mutex); + return fd->subpixel_positioning; +} + +void TextServerAdvanced::font_set_embolden(RID p_font_rid, float p_strength) { + FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND(!fd); + + MutexLock lock(fd->mutex); + if (fd->embolden != p_strength) { + _font_clear_cache(fd); + fd->embolden = p_strength; + } +} + +float TextServerAdvanced::font_get_embolden(RID p_font_rid) const { + FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND_V(!fd, 0.f); + + MutexLock lock(fd->mutex); + return fd->embolden; +} + +void TextServerAdvanced::font_set_transform(RID p_font_rid, Transform2D p_transform) { + FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND(!fd); + + MutexLock lock(fd->mutex); + if (fd->transform != p_transform) { + _font_clear_cache(fd); + fd->transform = p_transform; + } +} + +Transform2D TextServerAdvanced::font_get_transform(RID p_font_rid) const { + FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND_V(!fd, Transform2D()); + + MutexLock lock(fd->mutex); + return fd->transform; +} + void TextServerAdvanced::font_set_variation_coordinates(RID p_font_rid, const Dictionary &p_variation_coordinates) { FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2245,6 +2326,20 @@ void TextServerAdvanced::font_remove_glyph(RID p_font_rid, const Vector2i &p_siz fd->cache[size]->glyph_map.erase(p_glyph); } +float TextServerAdvanced::_get_extra_advance(RID p_font_rid, int p_font_size) const { + const FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND_V(!fd, 0.0); + + MutexLock lock(fd->mutex); + Vector2i size = _get_size(fd, p_font_size); + + if (fd->embolden != 0.0) { + return fd->embolden * float(size.x) / 64.0; + } else { + return 0.0; + } +} + Vector2 TextServerAdvanced::font_get_glyph_advance(RID p_font_rid, int p_size, int32_t p_glyph) const { FontDataAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -2259,10 +2354,17 @@ Vector2 TextServerAdvanced::font_get_glyph_advance(RID p_font_rid, int p_size, i const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map; + Vector2 ea; + if (fd->embolden != 0.0) { + ea.x = fd->embolden * float(size.x) / 64.0; + } + if (fd->msdf) { - return gl[p_glyph].advance * (float)p_size / (float)fd->msdf_source_size; + return (gl[p_glyph].advance + ea) * (float)p_size / (float)fd->msdf_source_size; + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + return (gl[p_glyph].advance + ea).round(); } else { - return gl[p_glyph].advance; + return gl[p_glyph].advance + ea; } } @@ -2628,12 +2730,25 @@ void TextServerAdvanced::font_render_range(RID p_font_rid, const Vector2i &p_siz ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); for (char32_t i = p_start; i <= p_end; i++) { #ifdef MODULE_FREETYPE_ENABLED + int32_t idx = FT_Get_Char_Index(fd->cache[size]->face, i); if (fd->cache[size]->face) { - _ensure_glyph(fd, size, FT_Get_Char_Index(fd->cache[size]->face, i)); - continue; + if (fd->msdf) { + _ensure_glyph(fd, size, (int32_t)idx); + } else { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (2 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (3 << 27)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + } else { + _ensure_glyph(fd, size, (int32_t)idx); + } + } } #endif - _ensure_glyph(fd, size, (int32_t)i); } } @@ -2644,7 +2759,26 @@ void TextServerAdvanced::font_render_glyph(RID p_font_rid, const Vector2i &p_siz MutexLock lock(fd->mutex); Vector2i size = _get_size_outline(fd, p_size); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); - ERR_FAIL_COND(!_ensure_glyph(fd, size, p_index)); +#ifdef MODULE_FREETYPE_ENABLED + int32_t idx = p_index; + if (fd->cache[size]->face) { + if (fd->msdf) { + _ensure_glyph(fd, size, (int32_t)idx); + } else { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (2 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (3 << 27)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + } else { + _ensure_glyph(fd, size, (int32_t)idx); + } + } + } +#endif } void TextServerAdvanced::font_draw_glyph(RID p_font_rid, RID p_canvas, int p_size, const Vector2 &p_pos, int32_t p_index, const Color &p_color) const { @@ -2654,11 +2788,26 @@ void TextServerAdvanced::font_draw_glyph(RID p_font_rid, RID p_canvas, int p_siz MutexLock lock(fd->mutex); Vector2i size = _get_size(fd, p_size); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); - if (!_ensure_glyph(fd, size, p_index)) { + + int32_t index = p_index; + +#ifdef MODULE_FREETYPE_ENABLED + if (!fd->msdf && fd->cache[size]->face) { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125)); + index = index | (xshift << 27); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25)); + index = index | (xshift << 27); + } + } +#endif + + if (!_ensure_glyph(fd, size, index)) { return; // Invalid or non-graphical glyph, do not display errors, nothing to draw. } - const FontGlyph &gl = fd->cache[size]->glyph_map[p_index]; + const FontGlyph &gl = fd->cache[size]->glyph_map[index]; if (gl.found) { ERR_FAIL_COND(gl.texture_idx < -1 || gl.texture_idx >= fd->cache[size]->textures.size()); @@ -2677,7 +2826,15 @@ void TextServerAdvanced::font_draw_glyph(RID p_font_rid, RID p_canvas, int p_siz Size2 csize = gl.rect.size * (float)p_size / (float)fd->msdf_source_size; RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, 0, fd->msdf_range); } else { - Point2 cpos = p_pos.floor(); + Point2 cpos = p_pos; + cpos.y = Math::floor(cpos.y); + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.125)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.25)); + } else { + cpos.x = Math::floor(cpos.x); + } cpos += gl.rect.position; Size2 csize = gl.rect.size; RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, false, false); @@ -2694,11 +2851,26 @@ void TextServerAdvanced::font_draw_glyph_outline(RID p_font_rid, RID p_canvas, i MutexLock lock(fd->mutex); Vector2i size = _get_size_outline(fd, Vector2i(p_size, p_outline_size)); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); - if (!_ensure_glyph(fd, size, p_index)) { + + int32_t index = p_index; + +#ifdef MODULE_FREETYPE_ENABLED + if (!fd->msdf && fd->cache[size]->face) { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125)); + index = index | (xshift << 27); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25)); + index = index | (xshift << 27); + } + } +#endif + + if (!_ensure_glyph(fd, size, index)) { return; // Invalid or non-graphical glyph, do not display errors, nothing to draw. } - const FontGlyph &gl = fd->cache[size]->glyph_map[p_index]; + const FontGlyph &gl = fd->cache[size]->glyph_map[index]; if (gl.found) { ERR_FAIL_COND(gl.texture_idx < -1 || gl.texture_idx >= fd->cache[size]->textures.size()); @@ -2717,7 +2889,15 @@ void TextServerAdvanced::font_draw_glyph_outline(RID p_font_rid, RID p_canvas, i Size2 csize = gl.rect.size * (float)p_size / (float)fd->msdf_source_size; RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, p_outline_size * 2, fd->msdf_range); } else { - Point2 cpos = p_pos.floor(); + Point2 cpos = p_pos; + cpos.y = Math::floor(cpos.y); + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.125)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.25)); + } else { + cpos.x = Math::floor(cpos.x); + } cpos += gl.rect.position; Size2 csize = gl.rect.size; RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, false, false); @@ -3559,7 +3739,7 @@ float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, } justification_width = sd->width_trimmed; } else { - return sd->width; + return Math::ceil(sd->width); } } else { justification_width = sd->width; @@ -3662,7 +3842,7 @@ float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, sd->width = justification_width; } - return justification_width; + return Math::ceil(justification_width); } float TextServerAdvanced::shaped_text_tab_align(RID p_shaped, const PackedFloat32Array &p_tab_stops) { @@ -4281,6 +4461,7 @@ bool TextServerAdvanced::shaped_text_update_justification_ops(RID p_shaped) { Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, RID p_font, int p_font_size) { hb_font_t *hb_font = _font_get_hb_handle(p_font, p_font_size); + bool subpos = (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_AUTO && p_font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); ERR_FAIL_COND_V(hb_font == nullptr, Glyph()); hb_buffer_clear_contents(p_sd->hb_buffer); @@ -4308,14 +4489,22 @@ Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char if (glyph_count > 0) { float scale = font_get_scale(p_font, p_font_size); if (p_sd->orientation == ORIENTATION_HORIZONTAL) { - gl.advance = Math::round(glyph_pos[0].x_advance / (64.0 / scale)); + if (subpos) { + gl.advance = glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size); + } else { + gl.advance = Math::round(glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size)); + } } else { gl.advance = -Math::round(glyph_pos[0].y_advance / (64.0 / scale)); } gl.count = 1; gl.index = glyph_info[0].codepoint; - gl.x_off = Math::round(glyph_pos[0].x_offset / (64.0 / scale)); + if (subpos) { + gl.x_off = glyph_pos[0].x_offset / (64.0 / scale); + } else { + gl.x_off = Math::round(glyph_pos[0].x_offset / (64.0 / scale)); + } gl.y_off = -Math::round(glyph_pos[0].y_offset / (64.0 / scale)); if ((glyph_info[0].codepoint != 0) || !u_isgraph(p_char)) { @@ -4380,6 +4569,8 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_star float scale = font_get_scale(f, fs); float sp_sp = font_get_spacing(f, fs, SPACING_SPACE); float sp_gl = font_get_spacing(f, fs, SPACING_GLYPH); + float ea = _get_extra_advance(f, fs); + bool subpos = (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_AUTO && fs <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); ERR_FAIL_COND(hb_font == nullptr); hb_buffer_clear_contents(p_sd->hb_buffer); @@ -4456,11 +4647,19 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_star gl.index = glyph_info[i].codepoint; if (gl.index != 0) { if (p_sd->orientation == ORIENTATION_HORIZONTAL) { - gl.advance = Math::round(glyph_pos[i].x_advance / (64.0 / scale)); + if (subpos) { + gl.advance = glyph_pos[i].x_advance / (64.0 / scale) + ea; + } else { + gl.advance = Math::round(glyph_pos[i].x_advance / (64.0 / scale) + ea); + } } else { gl.advance = -Math::round(glyph_pos[i].y_advance / (64.0 / scale)); } - gl.x_off = Math::round(glyph_pos[i].x_offset / (64.0 / scale)); + if (subpos) { + gl.x_off = glyph_pos[i].x_offset / (64.0 / scale); + } else { + gl.x_off = Math::round(glyph_pos[i].x_offset / (64.0 / scale)); + } gl.y_off = -Math::round(glyph_pos[i].y_offset / (64.0 / scale)); } if (sp_sp && is_whitespace(p_sd->text[glyph_info[i].cluster])) { @@ -4797,9 +4996,9 @@ Size2 TextServerAdvanced::shaped_text_get_size(RID p_shaped) const { const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); } if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) { - return Size2((sd->text_trimmed ? sd->width_trimmed : sd->width), sd->ascent + sd->descent); + return Size2((sd->text_trimmed ? sd->width_trimmed : sd->width), sd->ascent + sd->descent).ceil(); } else { - return Size2(sd->ascent + sd->descent, (sd->text_trimmed ? sd->width_trimmed : sd->width)); + return Size2(sd->ascent + sd->descent, (sd->text_trimmed ? sd->width_trimmed : sd->width)).ceil(); } } @@ -4833,7 +5032,7 @@ float TextServerAdvanced::shaped_text_get_width(RID p_shaped) const { if (!sd->valid) { const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); } - return (sd->text_trimmed ? sd->width_trimmed : sd->width); + return Math::ceil(sd->text_trimmed ? sd->width_trimmed : sd->width); } float TextServerAdvanced::shaped_text_get_underline_position(RID p_shaped) const { diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h index 145d740b68..e5958fc162 100644 --- a/modules/text_server_adv/text_server_adv.h +++ b/modules/text_server_adv/text_server_adv.h @@ -174,8 +174,11 @@ class TextServerAdvanced : public TextServer { int fixed_size = 0; bool force_autohinter = false; TextServer::Hinting hinting = TextServer::HINTING_LIGHT; + TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO; Dictionary variation_coordinates; float oversampling = 0.f; + float embolden = 0.f; + Transform2D transform; uint32_t style_flags = 0; String font_name; @@ -207,7 +210,7 @@ class TextServerAdvanced : public TextServer { } }; - _FORCE_INLINE_ FontTexturePosition find_texture_pos_for_glyph(FontDataForSizeAdvanced *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) const; + _FORCE_INLINE_ FontTexturePosition find_texture_pos_for_glyph(FontDataForSizeAdvanced *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const; #ifdef MODULE_MSDFGEN_ENABLED _FORCE_INLINE_ FontGlyph rasterize_msdf(FontDataAdvanced *p_font_data, FontDataForSizeAdvanced *p_data, int p_pixel_range, int p_rect_margin, FT_Outline *outline, const Vector2 &advance) const; #endif @@ -239,6 +242,8 @@ class TextServerAdvanced : public TextServer { } } + _FORCE_INLINE_ float _get_extra_advance(RID p_font_rid, int p_font_size) const; + // Shaped text cache data. struct ShapedTextDataAdvanced : public ShapedTextData { @@ -379,6 +384,15 @@ public: virtual void font_set_hinting(RID p_font_rid, TextServer::Hinting p_hinting) override; virtual TextServer::Hinting font_get_hinting(RID p_font_rid) const override; + virtual void font_set_subpixel_positioning(RID p_font_rid, SubpixelPositioning p_subpixel) override; + virtual SubpixelPositioning font_get_subpixel_positioning(RID p_font_rid) const override; + + virtual void font_set_embolden(RID p_font_rid, float p_strength) override; + virtual float font_get_embolden(RID p_font_rid) const override; + + virtual void font_set_transform(RID p_font_rid, Transform2D p_transform) override; + virtual Transform2D font_get_transform(RID p_font_rid) const override; + virtual void font_set_variation_coordinates(RID p_font_rid, const Dictionary &p_variation_coordinates) override; virtual Dictionary font_get_variation_coordinates(RID p_font_rid) const override; diff --git a/modules/text_server_fb/doc_classes/TextServerFallback.xml b/modules/text_server_fb/doc_classes/TextServerFallback.xml index 8aadf2b882..76194a7bda 100644 --- a/modules/text_server_fb/doc_classes/TextServerFallback.xml +++ b/modules/text_server_fb/doc_classes/TextServerFallback.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="TextServerFallback" inherits="TextServer" version="4.0"> +<class name="TextServerFallback" inherits="TextServer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Fallback implementation of the Text Server, without BiDi and complex text layout support. </brief_description> diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp index 182d2a02ad..0d7a9d0db8 100644 --- a/modules/text_server_fb/text_server_fb.cpp +++ b/modules/text_server_fb/text_server_fb.cpp @@ -155,7 +155,7 @@ String TextServerFallback::tag_to_name(int32_t p_tag) const { /* Font Glyph Rendering */ /*************************************************************************/ -_FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_texture_pos_for_glyph(FontDataForSizeFallback *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) const { +_FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_texture_pos_for_glyph(FontDataForSizeFallback *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const { FontTexturePosition ret; ret.index = -1; @@ -221,7 +221,11 @@ _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_ texsize = next_power_of_2(texsize); - texsize = MIN(texsize, 4096); + if (p_msdf) { + texsize = MIN(texsize, 2048); + } else { + texsize = MIN(texsize, 1024); + } FontTexture tex; tex.texture_w = texsize; @@ -386,10 +390,10 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_msdf( int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 4096, FontGlyph()); - ERR_FAIL_COND_V(mh > 4096, FontGlyph()); + ERR_FAIL_COND_V(mw > 1024, FontGlyph()); + ERR_FAIL_COND_V(mh > 1024, FontGlyph()); - FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh); + FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); FontTexture &tex = p_data->textures.write[tex_pos.index]; @@ -464,13 +468,13 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_bitma int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 4096, FontGlyph()); - ERR_FAIL_COND_V(mh > 4096, FontGlyph()); + ERR_FAIL_COND_V(mw > 1024, FontGlyph()); + ERR_FAIL_COND_V(mh > 1024, FontGlyph()); int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2; Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8; - FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh); + FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh, false); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); // Fit character in char texture. @@ -548,12 +552,14 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_bitma _FORCE_INLINE_ bool TextServerFallback::_ensure_glyph(FontDataFallback *p_font_data, const Vector2i &p_size, int32_t p_glyph) const { ERR_FAIL_COND_V(!_ensure_cache_for_size(p_font_data, p_size), false); + int32_t glyph_index = p_glyph & 0xFFFFFF; // Remove subpixel shifts. + FontDataForSizeFallback *fd = p_font_data->cache[p_size]; if (fd->glyph_map.has(p_glyph)) { return fd->glyph_map[p_glyph].found; } - if (p_glyph == 0) { // Non graphical or invalid glyph, do not render. + if (glyph_index == 0) { // Non graphical or invalid glyph, do not render. fd->glyph_map[p_glyph] = FontGlyph(); return true; } @@ -584,7 +590,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_glyph(FontDataFallback *p_font_d flags |= FT_LOAD_COLOR; } - int32_t glyph_index = FT_Get_Char_Index(fd->face, p_glyph); + glyph_index = FT_Get_Char_Index(fd->face, glyph_index); FT_Fixed v, h; FT_Get_Advance(fd->face, glyph_index, flags, &h); @@ -596,6 +602,26 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_glyph(FontDataFallback *p_font_d return false; } + if (!p_font_data->msdf) { + if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 4; + FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0); + } else if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 5; + FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0); + } + } + + if (p_font_data->embolden != 0.f) { + FT_Pos strength = p_font_data->embolden * p_size.x * 4; // 26.6 fractional units (1 / 64). + FT_Outline_Embolden(&fd->face->glyph->outline, strength); + } + + if (p_font_data->transform != Transform2D()) { + FT_Matrix mat = { FT_Fixed(p_font_data->transform[0][0] * 65536), FT_Fixed(p_font_data->transform[0][1] * 65536), FT_Fixed(p_font_data->transform[1][0] * 65536), FT_Fixed(p_font_data->transform[1][1] * 65536) }; // 16.16 fractional units (1 / 65536). + FT_Outline_Transform(&fd->face->glyph->outline, &mat); + } + if (!outline) { if (!p_font_data->msdf) { error = FT_Render_Glyph(fd->face->glyph, p_font_data->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO); @@ -1016,6 +1042,62 @@ TextServer::Hinting TextServerFallback::font_get_hinting(RID p_font_rid) const { return fd->hinting; } +void TextServerFallback::font_set_subpixel_positioning(RID p_font_rid, TextServer::SubpixelPositioning p_subpixel) { + FontDataFallback *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND(!fd); + + MutexLock lock(fd->mutex); + if (fd->subpixel_positioning != p_subpixel) { + fd->subpixel_positioning = p_subpixel; + } +} + +TextServer::SubpixelPositioning TextServerFallback::font_get_subpixel_positioning(RID p_font_rid) const { + FontDataFallback *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND_V(!fd, SUBPIXEL_POSITIONING_DISABLED); + + MutexLock lock(fd->mutex); + return fd->subpixel_positioning; +} + +void TextServerFallback::font_set_embolden(RID p_font_rid, float p_strength) { + FontDataFallback *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND(!fd); + + MutexLock lock(fd->mutex); + if (fd->embolden != p_strength) { + _font_clear_cache(fd); + fd->embolden = p_strength; + } +} + +float TextServerFallback::font_get_embolden(RID p_font_rid) const { + FontDataFallback *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND_V(!fd, 0.f); + + MutexLock lock(fd->mutex); + return fd->embolden; +} + +void TextServerFallback::font_set_transform(RID p_font_rid, Transform2D p_transform) { + FontDataFallback *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND(!fd); + + MutexLock lock(fd->mutex); + if (fd->transform != p_transform) { + _font_clear_cache(fd); + fd->transform = p_transform; + } +} + +Transform2D TextServerFallback::font_get_transform(RID p_font_rid) const { + FontDataFallback *fd = font_owner.get_or_null(p_font_rid); + ERR_FAIL_COND_V(!fd, Transform2D()); + + MutexLock lock(fd->mutex); + return fd->transform; +} + void TextServerFallback::font_set_variation_coordinates(RID p_font_rid, const Dictionary &p_variation_coordinates) { FontDataFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1431,10 +1513,17 @@ Vector2 TextServerFallback::font_get_glyph_advance(RID p_font_rid, int p_size, i const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map; + Vector2 ea; + if (fd->embolden != 0.0) { + ea.x = fd->embolden * float(size.x) / 64.0; + } + if (fd->msdf) { - return gl[p_glyph].advance * (float)p_size / (float)fd->msdf_source_size; + return (gl[p_glyph].advance + ea) * (float)p_size / (float)fd->msdf_source_size; + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + return (gl[p_glyph].advance + ea).round(); } else { - return gl[p_glyph].advance; + return gl[p_glyph].advance + ea; } } @@ -1781,7 +1870,26 @@ void TextServerFallback::font_render_range(RID p_font_rid, const Vector2i &p_siz Vector2i size = _get_size_outline(fd, p_size); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); for (char32_t i = p_start; i <= p_end; i++) { - _ensure_glyph(fd, size, (int32_t)i); +#ifdef MODULE_FREETYPE_ENABLED + int32_t idx = i; + if (fd->cache[size]->face) { + if (fd->msdf) { + _ensure_glyph(fd, size, (int32_t)idx); + } else { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (2 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (3 << 27)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + } else { + _ensure_glyph(fd, size, (int32_t)idx); + } + } + } +#endif } } @@ -1792,7 +1900,26 @@ void TextServerFallback::font_render_glyph(RID p_font_rid, const Vector2i &p_siz MutexLock lock(fd->mutex); Vector2i size = _get_size_outline(fd, p_size); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); - ERR_FAIL_COND(!_ensure_glyph(fd, size, p_index)); +#ifdef MODULE_FREETYPE_ENABLED + int32_t idx = p_index; + if (fd->cache[size]->face) { + if (fd->msdf) { + _ensure_glyph(fd, size, (int32_t)idx); + } else { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (2 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (3 << 27)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + _ensure_glyph(fd, size, (int32_t)idx | (1 << 27)); + _ensure_glyph(fd, size, (int32_t)idx | (0 << 27)); + } else { + _ensure_glyph(fd, size, (int32_t)idx); + } + } + } +#endif } void TextServerFallback::font_draw_glyph(RID p_font_rid, RID p_canvas, int p_size, const Vector2 &p_pos, int32_t p_index, const Color &p_color) const { @@ -1802,11 +1929,26 @@ void TextServerFallback::font_draw_glyph(RID p_font_rid, RID p_canvas, int p_siz MutexLock lock(fd->mutex); Vector2i size = _get_size(fd, p_size); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); - if (!_ensure_glyph(fd, size, p_index)) { + + int32_t index = p_index; + +#ifdef MODULE_FREETYPE_ENABLED + if (!fd->msdf && fd->cache[size]->face) { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125)); + index = index | (xshift << 27); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25)); + index = index | (xshift << 27); + } + } +#endif + + if (!_ensure_glyph(fd, size, index)) { return; // Invalid or non-graphical glyph, do not display errors, nothing to draw. } - const FontGlyph &gl = fd->cache[size]->glyph_map[p_index]; + const FontGlyph &gl = fd->cache[size]->glyph_map[index]; if (gl.found) { ERR_FAIL_COND(gl.texture_idx < -1 || gl.texture_idx >= fd->cache[size]->textures.size()); @@ -1825,7 +1967,15 @@ void TextServerFallback::font_draw_glyph(RID p_font_rid, RID p_canvas, int p_siz Size2 csize = gl.rect.size * (float)p_size / (float)fd->msdf_source_size; RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, 0, fd->msdf_range); } else { - Point2 cpos = p_pos.floor(); + Point2 cpos = p_pos; + cpos.y = Math::floor(cpos.y); + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.125)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.25)); + } else { + cpos.x = Math::floor(cpos.x); + } cpos += gl.rect.position; Size2 csize = gl.rect.size; RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, false, false); @@ -1842,11 +1992,26 @@ void TextServerFallback::font_draw_glyph_outline(RID p_font_rid, RID p_canvas, i MutexLock lock(fd->mutex); Vector2i size = _get_size_outline(fd, Vector2i(p_size, p_outline_size)); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); - if (!_ensure_glyph(fd, size, p_index)) { + + int32_t index = p_index; + +#ifdef MODULE_FREETYPE_ENABLED + if (!fd->msdf && fd->cache[size]->face) { + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125)); + index = index | (xshift << 27); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25)); + index = index | (xshift << 27); + } + } +#endif + + if (!_ensure_glyph(fd, size, index)) { return; // Invalid or non-graphical glyph, do not display errors, nothing to draw. } - const FontGlyph &gl = fd->cache[size]->glyph_map[p_index]; + const FontGlyph &gl = fd->cache[size]->glyph_map[index]; if (gl.found) { ERR_FAIL_COND(gl.texture_idx < -1 || gl.texture_idx >= fd->cache[size]->textures.size()); @@ -1865,7 +2030,15 @@ void TextServerFallback::font_draw_glyph_outline(RID p_font_rid, RID p_canvas, i Size2 csize = gl.rect.size * (float)p_size / (float)fd->msdf_source_size; RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, p_outline_size * 2, fd->msdf_range); } else { - Point2 cpos = p_pos.floor(); + Point2 cpos = p_pos; + cpos.y = Math::floor(cpos.y); + if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.125)); + } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + cpos.x = ((int)Math::floor(cpos.x + 0.25)); + } else { + cpos.x = Math::floor(cpos.x); + } cpos += gl.rect.position; Size2 csize = gl.rect.size; RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, false, false); @@ -2660,7 +2833,7 @@ float TextServerFallback::shaped_text_fit_to_width(RID p_shaped, float p_width, end_pos = sd->overrun_trim_data.trim_pos; justification_width = sd->width_trimmed; } else { - return sd->width; + return Math::ceil(sd->width); } } else { justification_width = sd->width; @@ -2720,7 +2893,7 @@ float TextServerFallback::shaped_text_fit_to_width(RID p_shaped, float p_width, sd->width = justification_width; } - return justification_width; + return Math::ceil(justification_width); } float TextServerFallback::shaped_text_tab_align(RID p_shaped, const PackedFloat32Array &p_tab_stops) { @@ -3109,6 +3282,7 @@ bool TextServerFallback::shaped_text_shape(RID p_shaped) { } if (gl.font_rid.is_valid()) { + bool subpos = (font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_AUTO && gl.font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); if (sd->text[j - sd->start] != 0 && !is_linebreak(sd->text[j - sd->start])) { if (sd->orientation == ORIENTATION_HORIZONTAL) { gl.advance = Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x); @@ -3143,6 +3317,9 @@ bool TextServerFallback::shaped_text_shape(RID p_shaped) { } } } + if (sd->orientation == ORIENTATION_HORIZONTAL && !subpos) { + gl.advance = Math::round(gl.advance); + } } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) { // Glyph not found, replace with hex code box. if (sd->orientation == ORIENTATION_HORIZONTAL) { @@ -3312,9 +3489,9 @@ Size2 TextServerFallback::shaped_text_get_size(RID p_shaped) const { const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); } if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) { - return Size2(sd->width, sd->ascent + sd->descent); + return Size2(sd->width, sd->ascent + sd->descent).ceil(); } else { - return Size2(sd->ascent + sd->descent, sd->width); + return Size2(sd->ascent + sd->descent, sd->width).ceil(); } } @@ -3348,7 +3525,7 @@ float TextServerFallback::shaped_text_get_width(RID p_shaped) const { if (!sd->valid) { const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); } - return sd->width; + return Math::ceil(sd->width); } float TextServerFallback::shaped_text_get_underline_position(RID p_shaped) const { diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h index be944cde58..d4c7b5666e 100644 --- a/modules/text_server_fb/text_server_fb.h +++ b/modules/text_server_fb/text_server_fb.h @@ -139,8 +139,11 @@ class TextServerFallback : public TextServer { int fixed_size = 0; bool force_autohinter = false; TextServer::Hinting hinting = TextServer::HINTING_LIGHT; + TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO; Dictionary variation_coordinates; float oversampling = 0.f; + float embolden = 0.f; + Transform2D transform; uint32_t style_flags = 0; String font_name; @@ -171,7 +174,7 @@ class TextServerFallback : public TextServer { } }; - _FORCE_INLINE_ FontTexturePosition find_texture_pos_for_glyph(FontDataForSizeFallback *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) const; + _FORCE_INLINE_ FontTexturePosition find_texture_pos_for_glyph(FontDataForSizeFallback *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const; #ifdef MODULE_MSDFGEN_ENABLED _FORCE_INLINE_ FontGlyph rasterize_msdf(FontDataFallback *p_font_data, FontDataForSizeFallback *p_data, int p_pixel_range, int p_rect_margin, FT_Outline *outline, const Vector2 &advance) const; #endif @@ -290,6 +293,15 @@ public: virtual void font_set_hinting(RID p_font_rid, TextServer::Hinting p_hinting) override; virtual TextServer::Hinting font_get_hinting(RID p_font_rid) const override; + virtual void font_set_subpixel_positioning(RID p_font_rid, SubpixelPositioning p_subpixel) override; + virtual SubpixelPositioning font_get_subpixel_positioning(RID p_font_rid) const override; + + virtual void font_set_embolden(RID p_font_rid, float p_strength) override; + virtual float font_get_embolden(RID p_font_rid) const override; + + virtual void font_set_transform(RID p_font_rid, Transform2D p_transform) override; + virtual Transform2D font_get_transform(RID p_font_rid) const override; + virtual void font_set_variation_coordinates(RID p_font_rid, const Dictionary &p_variation_coordinates) override; virtual Dictionary font_get_variation_coordinates(RID p_font_rid) const override; diff --git a/modules/theora/doc_classes/VideoStreamTheora.xml b/modules/theora/doc_classes/VideoStreamTheora.xml index 725f87b046..0f2dece8e7 100644 --- a/modules/theora/doc_classes/VideoStreamTheora.xml +++ b/modules/theora/doc_classes/VideoStreamTheora.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VideoStreamTheora" inherits="VideoStream" version="4.0"> +<class name="VideoStreamTheora" inherits="VideoStream" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> [VideoStream] resource for Ogg Theora videos. </brief_description> diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp index a9652cbba1..0a4ad96d97 100644 --- a/modules/theora/video_stream_theora.cpp +++ b/modules/theora/video_stream_theora.cpp @@ -604,7 +604,7 @@ float VideoStreamPlaybackTheora::get_playback_position() const { }; void VideoStreamPlaybackTheora::seek(float p_time) { - WARN_PRINT_ONCE("Seeking in Theora videos is not implemented yet (it's only supported for GDNative-provided video streams)."); + WARN_PRINT_ONCE("Seeking in Theora videos is not implemented yet (it's only supported for GDExtension-provided video streams)."); } void VideoStreamPlaybackTheora::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) { diff --git a/modules/upnp/doc_classes/UPNP.xml b/modules/upnp/doc_classes/UPNP.xml index 2cd0b8843a..066506922c 100644 --- a/modules/upnp/doc_classes/UPNP.xml +++ b/modules/upnp/doc_classes/UPNP.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="UPNP" inherits="RefCounted" version="4.0"> +<class name="UPNP" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> UPNP network functions. </brief_description> diff --git a/modules/upnp/doc_classes/UPNPDevice.xml b/modules/upnp/doc_classes/UPNPDevice.xml index b7c2ff7dd7..7749ac18ab 100644 --- a/modules/upnp/doc_classes/UPNPDevice.xml +++ b/modules/upnp/doc_classes/UPNPDevice.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="UPNPDevice" inherits="RefCounted" version="4.0"> +<class name="UPNPDevice" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> UPNP device. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml index a452974014..96310538bf 100644 --- a/modules/visual_script/doc_classes/VisualScript.xml +++ b/modules/visual_script/doc_classes/VisualScript.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScript" inherits="Script" version="4.0"> +<class name="VisualScript" inherits="Script" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A script implemented in the Visual Script programming environment. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml b/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml index ed5b814bb7..0ed66f44e1 100644 --- a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptBasicTypeConstant" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptBasicTypeConstant" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node representing a constant from the base types. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml index 1ac5768755..647b627d25 100644 --- a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml +++ b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptBuiltinFunc" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptBuiltinFunc" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node used to call built-in functions. </brief_description> @@ -96,123 +96,125 @@ <constant name="MATH_LERP" value="26" enum="BuiltinFunc"> Returns a number linearly interpolated between the first two inputs, based on the third input. Uses the formula [code]a + (a - b) * t[/code]. </constant> - <constant name="MATH_INVERSE_LERP" value="27" enum="BuiltinFunc"> + <constant name="MATH_CUBIC_INTERPOLATE" value="27" enum="BuiltinFunc"> </constant> - <constant name="MATH_RANGE_LERP" value="28" enum="BuiltinFunc"> + <constant name="MATH_INVERSE_LERP" value="28" enum="BuiltinFunc"> </constant> - <constant name="MATH_MOVE_TOWARD" value="29" enum="BuiltinFunc"> + <constant name="MATH_RANGE_LERP" value="29" enum="BuiltinFunc"> + </constant> + <constant name="MATH_MOVE_TOWARD" value="30" 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_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_RANDI" value="31" enum="BuiltinFunc"> + <constant name="MATH_RANDI" value="32" enum="BuiltinFunc"> Returns 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"> Returns 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_RANDI_RANGE" value="33" enum="BuiltinFunc"> + <constant name="MATH_RANDI_RANGE" value="34" enum="BuiltinFunc"> Returns a random 32-bit integer value between the two inputs. </constant> - <constant name="MATH_RANDF_RANGE" value="34" enum="BuiltinFunc"> + <constant name="MATH_RANDF_RANGE" value="35" enum="BuiltinFunc"> Returns a random floating-point value between the two inputs. </constant> - <constant name="MATH_RANDFN" value="35" enum="BuiltinFunc"> + <constant name="MATH_RANDFN" value="36" enum="BuiltinFunc"> Returns a normally-distributed pseudo-random number, using Box-Muller transform with the specified mean and a standard deviation. This is also called Gaussian distribution. </constant> - <constant name="MATH_SEED" value="36" enum="BuiltinFunc"> + <constant name="MATH_SEED" value="37" enum="BuiltinFunc"> Set the seed for the random number generator. </constant> - <constant name="MATH_RANDSEED" value="37" enum="BuiltinFunc"> + <constant name="MATH_RANDSEED" value="38" enum="BuiltinFunc"> Returns a random value from the given seed, along with the new seed. </constant> - <constant name="MATH_DEG2RAD" value="38" enum="BuiltinFunc"> + <constant name="MATH_DEG2RAD" value="39" enum="BuiltinFunc"> Convert the input from degrees to radians. </constant> - <constant name="MATH_RAD2DEG" value="39" enum="BuiltinFunc"> + <constant name="MATH_RAD2DEG" value="40" enum="BuiltinFunc"> Convert the input from radians to degrees. </constant> - <constant name="MATH_LINEAR2DB" value="40" enum="BuiltinFunc"> + <constant name="MATH_LINEAR2DB" value="41" enum="BuiltinFunc"> Convert the input from linear volume to decibel volume. </constant> - <constant name="MATH_DB2LINEAR" value="41" enum="BuiltinFunc"> + <constant name="MATH_DB2LINEAR" value="42" enum="BuiltinFunc"> Convert the input from decibel volume to linear volume. </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="MATH_PINGPONG" value="44" enum="BuiltinFunc"> + <constant name="MATH_PINGPONG" value="45" enum="BuiltinFunc"> Returns the [code]value[/code] wrapped between [code]0[/code] and the [code]length[/code]. If the limit is reached, the next value the function returned is decreased to the [code]0[/code] side or increased to the [code]length[/code] side (like a triangle wave). If [code]length[/code] is less than zero, it becomes positive. </constant> - <constant name="LOGIC_MAX" value="45" enum="BuiltinFunc"> + <constant name="LOGIC_MAX" value="46" enum="BuiltinFunc"> Returns the greater of the two numbers, also known as their maximum. </constant> - <constant name="LOGIC_MIN" value="46" enum="BuiltinFunc"> + <constant name="LOGIC_MIN" value="47" enum="BuiltinFunc"> Returns the lesser of the two numbers, also known as their minimum. </constant> - <constant name="LOGIC_CLAMP" value="47" enum="BuiltinFunc"> + <constant name="LOGIC_CLAMP" value="48" enum="BuiltinFunc"> Returns 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="48" enum="BuiltinFunc"> + <constant name="LOGIC_NEAREST_PO2" value="49" enum="BuiltinFunc"> Returns the nearest power of 2 to the input. </constant> - <constant name="OBJ_WEAKREF" value="49" enum="BuiltinFunc"> + <constant name="OBJ_WEAKREF" value="50" enum="BuiltinFunc"> Create a [WeakRef] 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"> Returns 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"> Returns 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="TEXT_PRINT_VERBOSE" value="58" enum="BuiltinFunc"> + <constant name="TEXT_PRINT_VERBOSE" value="59" enum="BuiltinFunc"> </constant> - <constant name="VAR_TO_STR" value="59" enum="BuiltinFunc"> + <constant name="VAR_TO_STR" value="60" enum="BuiltinFunc"> Serialize a [Variant] to a string. </constant> - <constant name="STR_TO_VAR" value="60" enum="BuiltinFunc"> + <constant name="STR_TO_VAR" value="61" enum="BuiltinFunc"> Deserialize a [Variant] from a string serialized using [constant VAR_TO_STR]. </constant> - <constant name="VAR_TO_BYTES" value="61" enum="BuiltinFunc"> + <constant name="VAR_TO_BYTES" value="62" enum="BuiltinFunc"> Serialize a [Variant] to a [PackedByteArray]. </constant> - <constant name="BYTES_TO_VAR" value="62" enum="BuiltinFunc"> + <constant name="BYTES_TO_VAR" value="63" enum="BuiltinFunc"> Deserialize a [Variant] from a [PackedByteArray] serialized using [constant VAR_TO_BYTES]. </constant> - <constant name="MATH_SMOOTHSTEP" value="63" enum="BuiltinFunc"> + <constant name="MATH_SMOOTHSTEP" value="64" enum="BuiltinFunc"> Returns 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="64" enum="BuiltinFunc"> + <constant name="MATH_POSMOD" value="65" enum="BuiltinFunc"> </constant> - <constant name="MATH_LERP_ANGLE" value="65" enum="BuiltinFunc"> + <constant name="MATH_LERP_ANGLE" value="66" enum="BuiltinFunc"> </constant> - <constant name="TEXT_ORD" value="66" enum="BuiltinFunc"> + <constant name="TEXT_ORD" value="67" enum="BuiltinFunc"> </constant> - <constant name="FUNC_MAX" value="67" enum="BuiltinFunc"> + <constant name="FUNC_MAX" value="68" enum="BuiltinFunc"> Represents the size of the [enum BuiltinFunc] enum. </constant> </constants> diff --git a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml index ae32500d2f..2509084f0e 100644 --- a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptClassConstant" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptClassConstant" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Gets a constant from a given class. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptComment.xml b/modules/visual_script/doc_classes/VisualScriptComment.xml index 5024aae384..cf4b57ca19 100644 --- a/modules/visual_script/doc_classes/VisualScriptComment.xml +++ b/modules/visual_script/doc_classes/VisualScriptComment.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptComment" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptComment" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node used to annotate the script. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptComposeArray.xml b/modules/visual_script/doc_classes/VisualScriptComposeArray.xml index ed065759c5..ea73867c4b 100644 --- a/modules/visual_script/doc_classes/VisualScriptComposeArray.xml +++ b/modules/visual_script/doc_classes/VisualScriptComposeArray.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptComposeArray" inherits="VisualScriptLists" version="4.0"> +<class name="VisualScriptComposeArray" inherits="VisualScriptLists" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script Node used to create array from a list of items. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptCondition.xml b/modules/visual_script/doc_classes/VisualScriptCondition.xml index a5dd8c7c1b..a29388569f 100644 --- a/modules/visual_script/doc_classes/VisualScriptCondition.xml +++ b/modules/visual_script/doc_classes/VisualScriptCondition.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptCondition" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptCondition" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node which branches the flow. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptConstant.xml b/modules/visual_script/doc_classes/VisualScriptConstant.xml index 388c2bddde..645ede9001 100644 --- a/modules/visual_script/doc_classes/VisualScriptConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptConstant.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptConstant" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptConstant" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Gets a contant's value. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptConstructor.xml b/modules/visual_script/doc_classes/VisualScriptConstructor.xml index 4a3d10aa8e..5ec17350bd 100644 --- a/modules/visual_script/doc_classes/VisualScriptConstructor.xml +++ b/modules/visual_script/doc_classes/VisualScriptConstructor.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptConstructor" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptConstructor" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node which calls a base type constructor. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml index 486f60400a..97b89fb987 100644 --- a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptCustomNode" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptCustomNode" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A scripted Visual Script node. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml b/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml index 1681da7653..f04c862174 100644 --- a/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml +++ b/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptCustomNodes" inherits="Object" version="4.0"> +<class name="VisualScriptCustomNodes" inherits="Object" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Manages custom nodes for the Visual Script editor. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml b/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml index fd9a91c2a5..b544fd9d90 100644 --- a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml +++ b/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptDeconstruct" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptDeconstruct" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node which deconstructs a base type instance into its parts. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml index e102e02aa9..c0cefa0ab7 100644 --- a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml +++ b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptEmitSignal" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptEmitSignal" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Emits a specified signal. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml b/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml index 468cae852f..f60a048845 100644 --- a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml +++ b/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptEngineSingleton" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptEngineSingleton" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node returning a singleton from [@GlobalScope]. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptExpression.xml b/modules/visual_script/doc_classes/VisualScriptExpression.xml index 15e16a15f0..14750e7c8d 100644 --- a/modules/visual_script/doc_classes/VisualScriptExpression.xml +++ b/modules/visual_script/doc_classes/VisualScriptExpression.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptExpression" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptExpression" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node that can execute a custom expression. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptFunction.xml b/modules/visual_script/doc_classes/VisualScriptFunction.xml index e0ca9eb280..74d9f194eb 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunction.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunction.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptFunction" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptFunction" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node representing a function. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml index a98cb79106..543263ff8e 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptFunctionCall" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptFunctionCall" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node for calling a function. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml b/modules/visual_script/doc_classes/VisualScriptFunctionState.xml index 0d7833446d..ef09c9d4a0 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunctionState.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptFunctionState" inherits="RefCounted" version="4.0"> +<class name="VisualScriptFunctionState" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node representing a function state. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml index c6b5b22590..42ada99257 100644 --- a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptGlobalConstant" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptGlobalConstant" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node returning a constant from [@GlobalScope]. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml b/modules/visual_script/doc_classes/VisualScriptIndexGet.xml index 78fd17c5fc..8828bf9039 100644 --- a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptIndexGet.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptIndexGet" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptIndexGet" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node for getting a value from an array or a dictionary. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml b/modules/visual_script/doc_classes/VisualScriptIndexSet.xml index 0e5e832c65..5c81dcd339 100644 --- a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptIndexSet.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptIndexSet" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptIndexSet" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node for setting a value in an array or a dictionary. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptInputAction.xml b/modules/visual_script/doc_classes/VisualScriptInputAction.xml index eb06d52314..51c2eaf353 100644 --- a/modules/visual_script/doc_classes/VisualScriptInputAction.xml +++ b/modules/visual_script/doc_classes/VisualScriptInputAction.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptInputAction" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptInputAction" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node returning a state of an action. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptIterator.xml b/modules/visual_script/doc_classes/VisualScriptIterator.xml index d8305728c6..ef6846deba 100644 --- a/modules/visual_script/doc_classes/VisualScriptIterator.xml +++ b/modules/visual_script/doc_classes/VisualScriptIterator.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptIterator" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptIterator" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Steps through items in a given input. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptLists.xml b/modules/visual_script/doc_classes/VisualScriptLists.xml index 373e3c7191..27a81fce2f 100644 --- a/modules/visual_script/doc_classes/VisualScriptLists.xml +++ b/modules/visual_script/doc_classes/VisualScriptLists.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptLists" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptLists" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script virtual class for in-graph editable nodes. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml index 29dbddcdf4..dbf9049f0a 100644 --- a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml +++ b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptLocalVar" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptLocalVar" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Gets a local variable's value. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml index 96de8ebfdd..1ae4e20f97 100644 --- a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptLocalVarSet" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptLocalVarSet" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Changes a local variable's value. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml b/modules/visual_script/doc_classes/VisualScriptMathConstant.xml index f559083c80..01c36e763b 100644 --- a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptMathConstant.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptMathConstant" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptMathConstant" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Commonly used mathematical constants. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptNode.xml b/modules/visual_script/doc_classes/VisualScriptNode.xml index d080d9eac1..2eb99dc25f 100644 --- a/modules/visual_script/doc_classes/VisualScriptNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptNode.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptNode" inherits="Resource" version="4.0"> +<class name="VisualScriptNode" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A node which is part of a [VisualScript]. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptOperator.xml b/modules/visual_script/doc_classes/VisualScriptOperator.xml index 73d28899f6..47ca6ddb90 100644 --- a/modules/visual_script/doc_classes/VisualScriptOperator.xml +++ b/modules/visual_script/doc_classes/VisualScriptOperator.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptOperator" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptOperator" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node that performs an operation on two values. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptPreload.xml b/modules/visual_script/doc_classes/VisualScriptPreload.xml index e3d60c77bb..146d6cd9c3 100644 --- a/modules/visual_script/doc_classes/VisualScriptPreload.xml +++ b/modules/visual_script/doc_classes/VisualScriptPreload.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptPreload" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptPreload" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Creates a new [Resource] or loads one from the filesystem. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml index e9f30cb605..77cd6393a9 100644 --- a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptPropertyGet" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptPropertyGet" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node returning a value of a property from an [Object]. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml index 96261d2c5e..6cffa328c7 100644 --- a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml +++ b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptPropertySet" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptPropertySet" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node that sets a property of an [Object]. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml b/modules/visual_script/doc_classes/VisualScriptResourcePath.xml index 77e97a7219..6ca8260ade 100644 --- a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml +++ b/modules/visual_script/doc_classes/VisualScriptResourcePath.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptResourcePath" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptResourcePath" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/visual_script/doc_classes/VisualScriptReturn.xml b/modules/visual_script/doc_classes/VisualScriptReturn.xml index 2193f45dc8..1d59392782 100644 --- a/modules/visual_script/doc_classes/VisualScriptReturn.xml +++ b/modules/visual_script/doc_classes/VisualScriptReturn.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptReturn" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptReturn" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Exits a function and returns an optional value. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml b/modules/visual_script/doc_classes/VisualScriptSceneNode.xml index ac672d9b3f..a769d11d94 100644 --- a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptSceneNode.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptSceneNode" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptSceneNode" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Node reference. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml b/modules/visual_script/doc_classes/VisualScriptSceneTree.xml index fc383593c5..84ab90892f 100644 --- a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml +++ b/modules/visual_script/doc_classes/VisualScriptSceneTree.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptSceneTree" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptSceneTree" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node for accessing [SceneTree] methods. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptSelect.xml b/modules/visual_script/doc_classes/VisualScriptSelect.xml index d536e623f7..1aa916f779 100644 --- a/modules/visual_script/doc_classes/VisualScriptSelect.xml +++ b/modules/visual_script/doc_classes/VisualScriptSelect.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptSelect" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptSelect" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Chooses between two input values. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptSelf.xml b/modules/visual_script/doc_classes/VisualScriptSelf.xml index 3c2bd16302..8cc59dbccd 100644 --- a/modules/visual_script/doc_classes/VisualScriptSelf.xml +++ b/modules/visual_script/doc_classes/VisualScriptSelf.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptSelf" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptSelf" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Outputs a reference to the current instance. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptSequence.xml b/modules/visual_script/doc_classes/VisualScriptSequence.xml index 32dcbb9837..9adbc30e0d 100644 --- a/modules/visual_script/doc_classes/VisualScriptSequence.xml +++ b/modules/visual_script/doc_classes/VisualScriptSequence.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptSequence" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptSequence" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Executes a series of Sequence ports. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptSubCall.xml b/modules/visual_script/doc_classes/VisualScriptSubCall.xml index fdf0e24d3e..535e89fc82 100644 --- a/modules/visual_script/doc_classes/VisualScriptSubCall.xml +++ b/modules/visual_script/doc_classes/VisualScriptSubCall.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptSubCall" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptSubCall" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Calls a method called [code]_subcall[/code] in this object. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptSwitch.xml b/modules/visual_script/doc_classes/VisualScriptSwitch.xml index 8e176b56f0..7befe89f50 100644 --- a/modules/visual_script/doc_classes/VisualScriptSwitch.xml +++ b/modules/visual_script/doc_classes/VisualScriptSwitch.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptSwitch" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptSwitch" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Branches program flow based on a given input's value. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml index ee8e2ad31e..ec84a75601 100644 --- a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml +++ b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptTypeCast" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptTypeCast" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node that casts the given value to another type. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml index e29765d616..8d99b4b9d0 100644 --- a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptVariableGet" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptVariableGet" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Gets a variable's value. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml index b2cc70d62e..4f568cc0f6 100644 --- a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptVariableSet" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptVariableSet" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Changes a variable's value. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptWhile.xml b/modules/visual_script/doc_classes/VisualScriptWhile.xml index f090568608..4e7cccef17 100644 --- a/modules/visual_script/doc_classes/VisualScriptWhile.xml +++ b/modules/visual_script/doc_classes/VisualScriptWhile.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptWhile" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptWhile" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Conditional loop. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptYield.xml b/modules/visual_script/doc_classes/VisualScriptYield.xml index bb7fd8bfb5..ec757a3ac4 100644 --- a/modules/visual_script/doc_classes/VisualScriptYield.xml +++ b/modules/visual_script/doc_classes/VisualScriptYield.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptYield" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptYield" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node used to pause a function execution. </brief_description> diff --git a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml index ad6a7fb4e2..c3f4bc49c5 100644 --- a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml +++ b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptYieldSignal" inherits="VisualScriptNode" version="4.0"> +<class name="VisualScriptYieldSignal" inherits="VisualScriptNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A Visual Script node yielding for a signal. </brief_description> diff --git a/modules/visual_script/editor/visual_script_editor.cpp b/modules/visual_script/editor/visual_script_editor.cpp index 5ea8eaff00..a2e59c9cdf 100644 --- a/modules/visual_script/editor/visual_script_editor.cpp +++ b/modules/visual_script/editor/visual_script_editor.cpp @@ -1081,6 +1081,7 @@ void VisualScriptEditor::_update_members() { Control::get_theme_icon(SNAME("Basis"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("Transform3D"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("Color"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("StringName"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("NodePath"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("RID"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("MiniObject"), SNAME("EditorIcons")), @@ -1090,7 +1091,9 @@ void VisualScriptEditor::_update_members() { Control::get_theme_icon(SNAME("Array"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("PackedByteArray"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("PackedInt32Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedInt64Array"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("PackedFloat32Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedFloat64Array"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("PackedStringArray"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("PackedVector2Array"), SNAME("EditorIcons")), Control::get_theme_icon(SNAME("PackedVector3Array"), SNAME("EditorIcons")), @@ -1099,6 +1102,7 @@ void VisualScriptEditor::_update_members() { List<StringName> var_names; script->get_variable_list(&var_names); + var_names.sort_custom<StringName::AlphCompare>(); for (const StringName &E : var_names) { TreeItem *ti = members->create_item(variables); @@ -1510,6 +1514,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt function_name_edit->popup(); function_name_box->set_text(selected); function_name_box->select_all(); + function_name_box->grab_focus(); } } @@ -1616,7 +1621,7 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { conn_map.get_key_list(&keys); for (const int &E : keys) { for (const Set<int>::Element *F = conn_map[E].front(); F; F = F->next()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", p_id, p_port, E, F); + undo_redo->add_undo_method(script.ptr(), "data_connect", p_id, p_port, E, F->get()); } } @@ -2098,11 +2103,15 @@ void VisualScriptEditor::_fn_name_box_input(const Ref<InputEvent> &p_event) { Ref<InputEventKey> key = p_event; if (key.is_valid() && key->is_pressed() && key->get_keycode() == Key::ENTER) { function_name_edit->hide(); - _rename_function(selected, function_name_box->get_text()); + _on_fn_name_box_confirmed(); function_name_box->clear(); } } +void VisualScriptEditor::_on_fn_name_box_confirmed() { + _rename_function(selected, function_name_box->get_text()); +} + 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); @@ -3527,7 +3536,7 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri print_error("Category not handled: " + p_category.quote()); } - if (Object::cast_to<VisualScriptFunctionCall>(vnode.ptr()) && p_category != "Class") { + if (Object::cast_to<VisualScriptFunctionCall>(vnode.ptr()) && p_category != "Class" && p_category != "VisualScriptNode") { Vector<String> property_path = p_text.split(":"); String class_of_method = property_path[0]; String method_name = property_path[1]; @@ -3973,6 +3982,7 @@ void VisualScriptEditor::_notification(int p_what) { _update_graph(); } } break; + case NOTIFICATION_VISIBILITY_CHANGED: { update_toggle_scripts_button(); members_section->set_visible(is_visible_in_tree()); @@ -4415,6 +4425,7 @@ void VisualScriptEditor::_member_option(int p_option) { function_name_edit->popup(); function_name_box->set_text(selected); function_name_box->select_all(); + function_name_box->grab_focus(); } } break; case MEMBER_VARIABLE: { @@ -4545,9 +4556,11 @@ VisualScriptEditor::VisualScriptEditor() { member_popup->connect("id_pressed", callable_mp(this, &VisualScriptEditor::_member_option)); function_name_edit = memnew(AcceptDialog); + function_name_edit->set_title(TTR("Rename Function")); function_name_box = memnew(LineEdit); function_name_edit->add_child(function_name_box); function_name_box->connect("gui_input", callable_mp(this, &VisualScriptEditor::_fn_name_box_input)); + function_name_edit->get_ok_button()->connect("pressed", callable_mp(this, &VisualScriptEditor::_on_fn_name_box_confirmed)); function_name_box->set_expand_to_text_length_enabled(true); add_child(function_name_edit); @@ -4712,8 +4725,6 @@ VisualScriptEditor::VisualScriptEditor() { undo_redo = EditorNode::get_singleton()->get_undo_redo(); - updating_members = false; - set_process_input(true); default_value_edit = memnew(CustomPropertyEditor); diff --git a/modules/visual_script/editor/visual_script_editor.h b/modules/visual_script/editor/visual_script_editor.h index b01732b2fd..5b355a71df 100644 --- a/modules/visual_script/editor/visual_script_editor.h +++ b/modules/visual_script/editor/visual_script_editor.h @@ -148,7 +148,7 @@ class VisualScriptEditor : public ScriptEditorBase { void _update_graph_connections(); void _update_graph(int p_only_id = -1); - bool updating_members; + bool updating_members = false; void _update_members(); String _sanitized_variant_text(const StringName &property_name); @@ -247,6 +247,7 @@ class VisualScriptEditor : public ScriptEditorBase { 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 _on_fn_name_box_confirmed(); void _rename_function(const String &p_name, const String &p_new_name); void _create_function_dialog(); diff --git a/modules/visual_script/editor/visual_script_property_selector.cpp b/modules/visual_script/editor/visual_script_property_selector.cpp index bba5410629..31406a2a6f 100644 --- a/modules/visual_script/editor/visual_script_property_selector.cpp +++ b/modules/visual_script/editor/visual_script_property_selector.cpp @@ -38,7 +38,6 @@ #include "core/os/keyboard.h" #include "editor/doc_tools.h" #include "editor/editor_feature_profile.h" -#include "editor/editor_node.h" #include "editor/editor_scale.h" #include "scene/main/node.h" #include "scene/main/window.h" @@ -119,9 +118,11 @@ void VisualScriptPropertySelector::_notification(int p_what) { case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { _update_icons(); } break; + case NOTIFICATION_ENTER_TREE: { connect("confirmed", callable_mp(this, &VisualScriptPropertySelector::_confirmed)); } break; + case NOTIFICATION_PROCESS: { // Update background search. if (search_runner.is_valid()) { @@ -493,7 +494,7 @@ VisualScriptPropertySelector::VisualScriptPropertySelector() { hbox->add_child(scope_combo); search_box = memnew(LineEdit); - search_box->set_tooltip(TTR("Enter \" \" to show all filterd options\nEnter \".\" to show all filterd methods, operators and constructors\nUse CTRL_KEY to drop property setters")); + search_box->set_tooltip(TTR("Enter \" \" to show all filtered options\nEnter \".\" to show all filtered methods, operators and constructors\nUse CTRL_KEY to drop property setters")); search_box->set_custom_minimum_size(Size2(200, 0) * EDSCALE); search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); search_box->connect("text_changed", callable_mp(this, &VisualScriptPropertySelector::_update_results_s)); @@ -694,7 +695,7 @@ bool VisualScriptPropertySelector::SearchRunner::_phase_match_classes_init() { class_doc.name = selector_ui->base_script; class_doc.inherits = script->get_instance_base_type(); - class_doc.brief_description = ".vs files not suported by EditorHelp::get_doc_data()"; + class_doc.brief_description = ".vs files not supported by EditorHelp::get_doc_data()"; class_doc.description = ""; Object *obj = ObjectDB::get_instance(script->get_instance_id()); @@ -711,9 +712,9 @@ bool VisualScriptPropertySelector::SearchRunner::_phase_match_classes_init() { class_doc.signals.push_back(_get_method_doc(S->get())); } - List<PropertyInfo> propertys; - Object::cast_to<Script>(obj)->get_script_property_list(&propertys); - for (List<PropertyInfo>::Element *P = propertys.front(); P; P = P->next()) { + List<PropertyInfo> properties; + Object::cast_to<Script>(obj)->get_script_property_list(&properties); + for (List<PropertyInfo>::Element *P = properties.front(); P; P = P->next()) { DocData::PropertyDoc pd = DocData::PropertyDoc(); pd.name = P->get().name; pd.type = Variant::get_type_name(P->get().type); diff --git a/modules/visual_script/register_types.cpp b/modules/visual_script/register_types.cpp index e7b5f58174..d19870921d 100644 --- a/modules/visual_script/register_types.cpp +++ b/modules/visual_script/register_types.cpp @@ -53,10 +53,10 @@ void register_visual_script_types() { ScriptServer::register_language(visual_script_language); GDREGISTER_CLASS(VisualScript); - GDREGISTER_VIRTUAL_CLASS(VisualScriptNode); + GDREGISTER_ABSTRACT_CLASS(VisualScriptNode); GDREGISTER_CLASS(VisualScriptFunctionState); GDREGISTER_CLASS(VisualScriptFunction); - GDREGISTER_VIRTUAL_CLASS(VisualScriptLists); + GDREGISTER_ABSTRACT_CLASS(VisualScriptLists); GDREGISTER_CLASS(VisualScriptComposeArray); GDREGISTER_CLASS(VisualScriptOperator); GDREGISTER_CLASS(VisualScriptVariableSet); diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 88445f2f98..e8c44e2556 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -930,8 +930,6 @@ void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const { get_variable_list(&vars); for (const StringName &E : vars) { - //if (!variables[E]._export) - // continue; PropertyInfo pi = variables[E].info; pi.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; p_list->push_back(pi); @@ -1707,7 +1705,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p return return_value; } -Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { +Variant VisualScriptInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { r_error.error = Callable::CallError::CALL_OK; //ok by default Map<StringName, Function>::Element *F = functions.find(p_method); @@ -1800,13 +1798,13 @@ void VisualScriptInstance::notification(int p_notification) { Variant what = p_notification; const Variant *whatp = &what; Callable::CallError ce; - call(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); // Do as call. + callp(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); // Do as call. } String VisualScriptInstance::to_string(bool *r_valid) { if (has_method(CoreStringNames::get_singleton()->_to_string)) { Callable::CallError ce; - Variant ret = call(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce); + Variant ret = callp(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce); if (ce.error == Callable::CallError::CALL_OK) { if (ret.get_type() != Variant::STRING) { if (r_valid) { diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h index e5c8ab48ee..d4dffdfc7a 100644 --- a/modules/visual_script/visual_script.h +++ b/modules/visual_script/visual_script.h @@ -410,7 +410,7 @@ public: virtual void get_method_list(List<MethodInfo> *p_list) const; virtual bool has_method(const StringName &p_method) const; - virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error); + virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error); virtual void notification(int p_notification); String to_string(bool *r_valid); diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp index fd55796a66..f6bc855a50 100644 --- a/modules/visual_script/visual_script_builtin_funcs.cpp +++ b/modules/visual_script/visual_script_builtin_funcs.cpp @@ -65,6 +65,7 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX "step_decimals", "snapped", "lerp", + "cubic_interpolate", "inverse_lerp", "range_lerp", "move_toward", @@ -212,6 +213,7 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) { case MATH_WRAPF: case LOGIC_CLAMP: return 3; + case MATH_CUBIC_INTERPOLATE: case MATH_RANGE_LERP: return 5; case FUNC_MAX: { @@ -329,6 +331,19 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const return PropertyInfo(Variant::FLOAT, "weight"); } } break; + case MATH_CUBIC_INTERPOLATE: { + if (p_idx == 0) { + return PropertyInfo(Variant::FLOAT, "from"); + } else if (p_idx == 1) { + return PropertyInfo(Variant::FLOAT, "to"); + } else if (p_idx == 2) { + return PropertyInfo(Variant::FLOAT, "pre"); + } else if (p_idx == 3) { + return PropertyInfo(Variant::FLOAT, "post"); + } else { + return PropertyInfo(Variant::FLOAT, "weight"); + } + } break; case MATH_RANGE_LERP: { if (p_idx == 0) { return PropertyInfo(Variant::FLOAT, "value"); @@ -525,6 +540,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons } break; case MATH_SNAPPED: case MATH_LERP: + case MATH_CUBIC_INTERPOLATE: case MATH_LERP_ANGLE: case MATH_INVERSE_LERP: case MATH_RANGE_LERP: @@ -795,6 +811,14 @@ 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_CUBIC_INTERPOLATE: { + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + VALIDATE_ARG_NUM(3); + VALIDATE_ARG_NUM(4); + *r_return = Math::cubic_interpolate((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2], (double)*p_inputs[3], (double)*p_inputs[4]); + } break; case VisualScriptBuiltinFunc::MATH_LERP_ANGLE: { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); @@ -1220,6 +1244,7 @@ void VisualScriptBuiltinFunc::_bind_methods() { BIND_ENUM_CONSTANT(MATH_STEP_DECIMALS); BIND_ENUM_CONSTANT(MATH_SNAPPED); BIND_ENUM_CONSTANT(MATH_LERP); + BIND_ENUM_CONSTANT(MATH_CUBIC_INTERPOLATE); BIND_ENUM_CONSTANT(MATH_INVERSE_LERP); BIND_ENUM_CONSTANT(MATH_RANGE_LERP); BIND_ENUM_CONSTANT(MATH_MOVE_TOWARD); @@ -1309,6 +1334,7 @@ void register_visual_script_builtin_func_node() { VisualScriptLanguage::singleton->add_register_func("functions/built_in/step_decimals", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_STEP_DECIMALS>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/snapped", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SNAPPED>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/cubic_interpolate", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_CUBIC_INTERPOLATE>); 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>); diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h index d689296233..18935b9995 100644 --- a/modules/visual_script/visual_script_builtin_funcs.h +++ b/modules/visual_script/visual_script_builtin_funcs.h @@ -65,6 +65,7 @@ public: MATH_STEP_DECIMALS, MATH_SNAPPED, MATH_LERP, + MATH_CUBIC_INTERPOLATE, MATH_INVERSE_LERP, MATH_RANGE_LERP, MATH_MOVE_TOWARD, diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp index e8942b9788..fef159bf87 100644 --- a/modules/visual_script/visual_script_expression.cpp +++ b/modules/visual_script/visual_script_expression.cpp @@ -176,7 +176,7 @@ PropertyInfo VisualScriptExpression::get_output_value_port_info(int p_idx) const } String VisualScriptExpression::get_caption() const { - return TTR("Expression"); + return RTR("Expression"); } String VisualScriptExpression::get_text() const { @@ -1500,7 +1500,7 @@ public: argp.write[i] = &arr[i]; } - base.call(call->method, (const Variant **)argp.ptr(), argp.size(), r_ret, ce); + base.callp(call->method, (const Variant **)argp.ptr(), argp.size(), r_ret, ce); if (ce.error != Callable::CallError::CALL_OK) { r_error_str = "On call to '" + String(call->method) + "':"; diff --git a/modules/visual_script/visual_script_flow_control.cpp b/modules/visual_script/visual_script_flow_control.cpp index fd1861abc4..d28744a09f 100644 --- a/modules/visual_script/visual_script_flow_control.cpp +++ b/modules/visual_script/visual_script_flow_control.cpp @@ -70,7 +70,7 @@ PropertyInfo VisualScriptReturn::get_output_value_port_info(int p_idx) const { } String VisualScriptReturn::get_caption() const { - return TTR("Return"); + return RTR("Return"); } String VisualScriptReturn::get_text() const { @@ -201,11 +201,11 @@ PropertyInfo VisualScriptCondition::get_output_value_port_info(int p_idx) const } String VisualScriptCondition::get_caption() const { - return TTR("Condition"); + return RTR("Condition"); } String VisualScriptCondition::get_text() const { - return TTR("if (cond) is:"); + return RTR("if (cond) is:"); } void VisualScriptCondition::_bind_methods() { @@ -281,11 +281,11 @@ PropertyInfo VisualScriptWhile::get_output_value_port_info(int p_idx) const { } String VisualScriptWhile::get_caption() const { - return TTR("While"); + return RTR("While"); } String VisualScriptWhile::get_text() const { - return TTR("while (cond):"); + return RTR("while (cond):"); } void VisualScriptWhile::_bind_methods() { @@ -364,11 +364,11 @@ PropertyInfo VisualScriptIterator::get_output_value_port_info(int p_idx) const { } String VisualScriptIterator::get_caption() const { - return TTR("Iterator"); + return RTR("Iterator"); } String VisualScriptIterator::get_text() const { - return TTR("for (elem) in (input):"); + return RTR("for (elem) in (input):"); } void VisualScriptIterator::_bind_methods() { @@ -478,11 +478,11 @@ PropertyInfo VisualScriptSequence::get_output_value_port_info(int p_idx) const { } String VisualScriptSequence::get_caption() const { - return TTR("Sequence"); + return RTR("Sequence"); } String VisualScriptSequence::get_text() const { - return TTR("in order:"); + return RTR("in order:"); } void VisualScriptSequence::set_steps(int p_steps) { @@ -587,11 +587,11 @@ PropertyInfo VisualScriptSwitch::get_output_value_port_info(int p_idx) const { } String VisualScriptSwitch::get_caption() const { - return TTR("Switch"); + return RTR("Switch"); } String VisualScriptSwitch::get_text() const { - return TTR("'input' is:"); + return RTR("'input' is:"); } class VisualScriptNodeInstanceSwitch : public VisualScriptNodeInstance { @@ -720,14 +720,14 @@ PropertyInfo VisualScriptTypeCast::get_output_value_port_info(int p_idx) const { } String VisualScriptTypeCast::get_caption() const { - return TTR("Type Cast"); + return RTR("Type Cast"); } String VisualScriptTypeCast::get_text() const { if (!script.is_empty()) { - return vformat(TTR("Is %s?"), script.get_file()); + return vformat(RTR("Is %s?"), script.get_file()); } else { - return vformat(TTR("Is %s?"), base_type); + return vformat(RTR("Is %s?"), base_type); } } diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp index ef6c1ecdb9..2c9d23e457 100644 --- a/modules/visual_script/visual_script_func_nodes.cpp +++ b/modules/visual_script/visual_script_func_nodes.cpp @@ -33,6 +33,7 @@ #include "core/config/engine.h" #include "core/io/resource_loader.h" #include "core/os/os.h" +#include "core/templates/local_vector.h" #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "visual_script_nodes.h" @@ -261,13 +262,13 @@ String VisualScriptFunctionCall::get_text() const { String text; if (call_mode == CALL_MODE_BASIC_TYPE) { - text = vformat(TTR("On %s"), Variant::get_type_name(basic_type)); + text = vformat(RTR("On %s"), Variant::get_type_name(basic_type)); } else if (call_mode == CALL_MODE_INSTANCE) { - text = vformat(TTR("On %s"), base_type); + text = vformat(RTR("On %s"), base_type); } else if (call_mode == CALL_MODE_NODE_PATH) { text = "[" + String(base_path.simplified()) + "]"; } else if (call_mode == CALL_MODE_SELF) { - text = TTR("On Self"); + text = RTR("On Self"); } else if (call_mode == CALL_MODE_SINGLETON) { text = String(singleton) + ":" + String(function) + "()"; } @@ -772,9 +773,9 @@ public: if (rpc_mode) { call_rpc(object, p_inputs, input_args); } else if (returns) { - *p_outputs[0] = object->call(function, p_inputs, input_args, r_error); + *p_outputs[0] = object->callp(function, p_inputs, input_args, r_error); } else { - object->call(function, p_inputs, input_args, r_error); + object->callp(function, p_inputs, input_args, r_error); } } break; case VisualScriptFunctionCall::CALL_MODE_NODE_PATH: { @@ -795,9 +796,9 @@ public: if (rpc_mode) { call_rpc(node, p_inputs, input_args); } else if (returns) { - *p_outputs[0] = another->call(function, p_inputs, input_args, r_error); + *p_outputs[0] = another->callp(function, p_inputs, input_args, r_error); } else { - another->call(function, p_inputs, input_args, r_error); + another->callp(function, p_inputs, input_args, r_error); } } break; @@ -813,21 +814,21 @@ public: } else if (returns) { if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) { if (returns >= 2) { - v.call(function, p_inputs + 1, input_args, *p_outputs[1], r_error); + v.callp(function, p_inputs + 1, input_args, *p_outputs[1], r_error); } else if (returns == 1) { Variant ret; - v.call(function, p_inputs + 1, input_args, ret, r_error); + v.callp(function, p_inputs + 1, input_args, ret, r_error); } else { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid returns count for call_mode == CALL_MODE_INSTANCE"; return 0; } } else { - v.call(function, p_inputs + 1, input_args, *p_outputs[0], r_error); + v.callp(function, p_inputs + 1, input_args, *p_outputs[0], r_error); } } else { Variant ret; - v.call(function, p_inputs + 1, input_args, ret, r_error); + v.callp(function, p_inputs + 1, input_args, ret, r_error); } if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) { @@ -846,9 +847,9 @@ public: if (rpc_mode) { call_rpc(object, p_inputs, input_args); } else if (returns) { - *p_outputs[0] = object->call(function, p_inputs, input_args, r_error); + *p_outputs[0] = object->callp(function, p_inputs, input_args, r_error); } else { - object->call(function, p_inputs, input_args, r_error); + object->callp(function, p_inputs, input_args, r_error); } } break; } @@ -1032,18 +1033,18 @@ PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) cons } String VisualScriptPropertySet::get_caption() const { - static const char *opname[ASSIGN_OP_MAX] = { - TTRC("Set %s"), - TTRC("Add %s"), - TTRC("Subtract %s"), - TTRC("Multiply %s"), - TTRC("Divide %s"), - TTRC("Mod %s"), - TTRC("ShiftLeft %s"), - TTRC("ShiftRight %s"), - TTRC("BitAnd %s"), - TTRC("BitOr %s"), - TTRC("BitXor %s") + static const LocalVector<String> opname = { + RTR("Set %s"), + RTR("Add %s"), + RTR("Subtract %s"), + RTR("Multiply %s"), + RTR("Divide %s"), + RTR("Mod %s"), + RTR("ShiftLeft %s"), + RTR("ShiftRight %s"), + RTR("BitAnd %s"), + RTR("BitOr %s"), + RTR("BitXor %s"), }; String prop = property; @@ -1051,7 +1052,7 @@ String VisualScriptPropertySet::get_caption() const { prop += "." + String(index); } - return vformat(TTRGET(opname[assign_op]), prop); + return vformat(opname[assign_op], prop); } String VisualScriptPropertySet::get_text() const { @@ -1059,13 +1060,13 @@ String VisualScriptPropertySet::get_text() const { return ""; } if (call_mode == CALL_MODE_BASIC_TYPE) { - return vformat(TTR("On %s"), Variant::get_type_name(basic_type)); + return vformat(RTR("On %s"), Variant::get_type_name(basic_type)); } else if (call_mode == CALL_MODE_INSTANCE) { - return vformat(TTR("On %s"), base_type); + return vformat(RTR("On %s"), base_type); } else if (call_mode == CALL_MODE_NODE_PATH) { return " [" + String(base_path.simplified()) + "]"; } else { - return TTR("On Self"); + return RTR("On Self"); } } @@ -1776,18 +1777,18 @@ String VisualScriptPropertyGet::get_caption() const { prop += "." + String(index); } - return vformat(TTR("Get %s"), prop); + return vformat(RTR("Get %s"), prop); } String VisualScriptPropertyGet::get_text() const { if (call_mode == CALL_MODE_BASIC_TYPE) { - return vformat(TTR("On %s"), Variant::get_type_name(basic_type)); + return vformat(RTR("On %s"), Variant::get_type_name(basic_type)); } else if (call_mode == CALL_MODE_INSTANCE) { - return vformat(TTR("On %s"), base_type); + return vformat(RTR("On %s"), base_type); } else if (call_mode == CALL_MODE_NODE_PATH) { return " [" + String(base_path.simplified()) + "]"; } else { - return TTR("On Self"); + return RTR("On Self"); } } @@ -2303,7 +2304,7 @@ PropertyInfo VisualScriptEmitSignal::get_output_value_port_info(int p_idx) const } String VisualScriptEmitSignal::get_caption() const { - return vformat(TTR("Emit %s"), name); + return vformat(RTR("Emit %s"), name); } void VisualScriptEmitSignal::set_signal(const StringName &p_type) { @@ -2373,7 +2374,7 @@ public: virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { Object *obj = instance->get_owner_ptr(); - obj->emit_signal(name, p_inputs, argcount); + obj->emit_signalp(name, p_inputs, argcount); return 0; } diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp index e7f4e542c1..b65b9f090a 100644 --- a/modules/visual_script/visual_script_nodes.cpp +++ b/modules/visual_script/visual_script_nodes.cpp @@ -204,7 +204,7 @@ PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const { } String VisualScriptFunction::get_caption() const { - return TTR("Function"); + return RTR("Function"); } String VisualScriptFunction::get_text() const { @@ -767,7 +767,7 @@ PropertyInfo VisualScriptComposeArray::get_output_value_port_info(int p_idx) con } String VisualScriptComposeArray::get_caption() const { - return TTR("Compose Array"); + return RTR("Compose Array"); } String VisualScriptComposeArray::get_text() const { @@ -1186,11 +1186,11 @@ PropertyInfo VisualScriptSelect::get_output_value_port_info(int p_idx) const { } String VisualScriptSelect::get_caption() const { - return TTR("Select"); + return RTR("Select"); } String VisualScriptSelect::get_text() const { - return TTR("a if cond, else b"); + return RTR("a if cond, else b"); } void VisualScriptSelect::set_typed(Variant::Type p_op) { @@ -1284,7 +1284,7 @@ PropertyInfo VisualScriptVariableGet::get_output_value_port_info(int p_idx) cons } String VisualScriptVariableGet::get_caption() const { - return vformat(TTR("Get %s"), variable); + return vformat(RTR("Get %s"), variable); } void VisualScriptVariableGet::set_variable(StringName p_variable) { @@ -1394,7 +1394,7 @@ PropertyInfo VisualScriptVariableSet::get_output_value_port_info(int p_idx) cons } String VisualScriptVariableSet::get_caption() const { - return vformat(TTR("Set %s"), variable); + return vformat(RTR("Set %s"), variable); } void VisualScriptVariableSet::set_variable(StringName p_variable) { @@ -1501,7 +1501,7 @@ PropertyInfo VisualScriptConstant::get_output_value_port_info(int p_idx) const { } String VisualScriptConstant::get_caption() const { - return TTR("Constant"); + return RTR("Constant"); } void VisualScriptConstant::set_constant_type(Variant::Type p_type) { @@ -1628,7 +1628,7 @@ PropertyInfo VisualScriptPreload::get_output_value_port_info(int p_idx) const { } String VisualScriptPreload::get_caption() const { - return TTR("Preload"); + return RTR("Preload"); } void VisualScriptPreload::set_preload(const Ref<Resource> &p_preload) { @@ -1708,7 +1708,7 @@ PropertyInfo VisualScriptIndexGet::get_output_value_port_info(int p_idx) const { } String VisualScriptIndexGet::get_caption() const { - return TTR("Get Index"); + return RTR("Get Index"); } class VisualScriptNodeInstanceIndexGet : public VisualScriptNodeInstance { @@ -1775,7 +1775,7 @@ PropertyInfo VisualScriptIndexSet::get_output_value_port_info(int p_idx) const { } String VisualScriptIndexSet::get_caption() const { - return TTR("Set Index"); + return RTR("Set Index"); } class VisualScriptNodeInstanceIndexSet : public VisualScriptNodeInstance { @@ -1784,10 +1784,7 @@ public: virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { bool valid; - // *p_output[0] points to the same place as *p_inputs[2] so we need a temp to store the value before the change in the next line - Variant temp = *p_inputs[2]; - *p_outputs[0] = *p_inputs[0]; - p_outputs[0]->set(*p_inputs[1], temp, &valid); + ((Variant *)p_inputs[0])->set(*p_inputs[1], *p_inputs[2], &valid); if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; @@ -1839,7 +1836,7 @@ PropertyInfo VisualScriptGlobalConstant::get_output_value_port_info(int p_idx) c } String VisualScriptGlobalConstant::get_caption() const { - return TTR("Global Constant"); + return RTR("Global Constant"); } void VisualScriptGlobalConstant::set_global_constant(int p_which) { @@ -1925,7 +1922,7 @@ PropertyInfo VisualScriptClassConstant::get_output_value_port_info(int p_idx) co } String VisualScriptClassConstant::get_caption() const { - return TTR("Class Constant"); + return RTR("Class Constant"); } void VisualScriptClassConstant::set_class_constant(const StringName &p_which) { @@ -2050,7 +2047,7 @@ PropertyInfo VisualScriptBasicTypeConstant::get_output_value_port_info(int p_idx } String VisualScriptBasicTypeConstant::get_caption() const { - return TTR("Basic Constant"); + return RTR("Basic Constant"); } String VisualScriptBasicTypeConstant::get_text() const { @@ -2215,7 +2212,7 @@ PropertyInfo VisualScriptMathConstant::get_output_value_port_info(int p_idx) con } String VisualScriptMathConstant::get_caption() const { - return TTR("Math Constant"); + return RTR("Math Constant"); } void VisualScriptMathConstant::set_math_constant(MathConstant p_which) { @@ -2307,7 +2304,7 @@ PropertyInfo VisualScriptEngineSingleton::get_output_value_port_info(int p_idx) } String VisualScriptEngineSingleton::get_caption() const { - return TTR("Get Engine Singleton"); + return RTR("Get Engine Singleton"); } void VisualScriptEngineSingleton::set_singleton(const String &p_string) { @@ -2417,7 +2414,7 @@ PropertyInfo VisualScriptSceneNode::get_output_value_port_info(int p_idx) const } String VisualScriptSceneNode::get_caption() const { - return TTR("Get Scene Node"); + return RTR("Get Scene Node"); } void VisualScriptSceneNode::set_node_path(const NodePath &p_path) { @@ -2608,7 +2605,7 @@ PropertyInfo VisualScriptSceneTree::get_output_value_port_info(int p_idx) const } String VisualScriptSceneTree::get_caption() const { - return TTR("Get Scene Tree"); + return RTR("Get Scene Tree"); } class VisualScriptNodeInstanceSceneTree : public VisualScriptNodeInstance { @@ -2695,7 +2692,7 @@ PropertyInfo VisualScriptResourcePath::get_output_value_port_info(int p_idx) con } String VisualScriptResourcePath::get_caption() const { - return TTR("Resource Path"); + return RTR("Resource Path"); } void VisualScriptResourcePath::set_resource_path(const String &p_path) { @@ -2777,7 +2774,7 @@ PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const { } String VisualScriptSelf::get_caption() const { - return TTR("Get Self"); + return RTR("Get Self"); } class VisualScriptNodeInstanceSelf : public VisualScriptNodeInstance { @@ -2947,7 +2944,7 @@ String VisualScriptCustomNode::get_caption() const { if (GDVIRTUAL_CALL(_get_caption, ret)) { return ret; } - return TTR("CustomNode"); + return RTR("CustomNode"); } String VisualScriptCustomNode::get_text() const { @@ -3141,7 +3138,7 @@ PropertyInfo VisualScriptSubCall::get_output_value_port_info(int p_idx) const { } String VisualScriptSubCall::get_caption() const { - return TTR("SubCall"); + return RTR("SubCall"); } String VisualScriptSubCall::get_text() const { @@ -3177,7 +3174,7 @@ public: r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return 0; } - *p_outputs[0] = subcall->call(VisualScriptLanguage::singleton->_subcall, p_inputs, input_args, r_error); + *p_outputs[0] = subcall->callp(VisualScriptLanguage::singleton->_subcall, p_inputs, input_args, r_error); return 0; } }; @@ -3352,7 +3349,7 @@ PropertyInfo VisualScriptConstructor::get_output_value_port_info(int p_idx) cons } String VisualScriptConstructor::get_caption() const { - return vformat(TTR("Construct %s"), Variant::get_type_name(type)); + return vformat(RTR("Construct %s"), Variant::get_type_name(type)); } String VisualScriptConstructor::get_category() const { @@ -3469,7 +3466,7 @@ PropertyInfo VisualScriptLocalVar::get_output_value_port_info(int p_idx) const { } String VisualScriptLocalVar::get_caption() const { - return TTR("Get Local Var"); + return RTR("Get Local Var"); } String VisualScriptLocalVar::get_category() const { @@ -3572,7 +3569,7 @@ PropertyInfo VisualScriptLocalVarSet::get_output_value_port_info(int p_idx) cons } String VisualScriptLocalVarSet::get_caption() const { - return TTR("Set Local Var"); + return RTR("Set Local Var"); } String VisualScriptLocalVarSet::get_text() const { @@ -3696,7 +3693,7 @@ PropertyInfo VisualScriptInputAction::get_output_value_port_info(int p_idx) cons } String VisualScriptInputAction::get_caption() const { - return vformat(TTR("Action %s"), name); + return vformat(RTR("Action %s"), name); } String VisualScriptInputAction::get_category() const { @@ -3850,7 +3847,7 @@ PropertyInfo VisualScriptDeconstruct::get_output_value_port_info(int p_idx) cons } String VisualScriptDeconstruct::get_caption() const { - return vformat(TTR("Deconstruct %s"), Variant::get_type_name(type)); + return vformat(RTR("Deconstruct %s"), Variant::get_type_name(type)); } String VisualScriptDeconstruct::get_category() const { diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp index fbd5ad35ab..dcd8815394 100644 --- a/modules/visual_script/visual_script_yield_nodes.cpp +++ b/modules/visual_script/visual_script_yield_nodes.cpp @@ -68,7 +68,7 @@ PropertyInfo VisualScriptYield::get_output_value_port_info(int p_idx) const { } String VisualScriptYield::get_caption() const { - return yield_mode == YIELD_RETURN ? TTR("Yield") : TTR("Wait"); + return yield_mode == YIELD_RETURN ? RTR("Yield") : RTR("Wait"); } String VisualScriptYield::get_text() const { @@ -77,13 +77,13 @@ String VisualScriptYield::get_text() const { return ""; break; case YIELD_FRAME: - return TTR("Next Frame"); + return RTR("Next Frame"); break; case YIELD_PHYSICS_FRAME: - return TTR("Next Physics Frame"); + return RTR("Next Physics Frame"); break; case YIELD_WAIT: - return vformat(TTR("%s sec(s)"), rtos(wait_time)); + return vformat(RTR("%s sec(s)"), rtos(wait_time)); break; } @@ -335,13 +335,18 @@ PropertyInfo VisualScriptYieldSignal::get_output_value_port_info(int p_idx) cons } String VisualScriptYieldSignal::get_caption() const { - static const char *cname[3] = { - TTRC("WaitSignal"), - TTRC("WaitNodeSignal"), - TTRC("WaitInstanceSignal"), - }; - - return TTRGET(cname[call_mode]); + switch (call_mode) { + case CALL_MODE_SELF: { + return RTR("WaitSignal"); + } break; + case CALL_MODE_NODE_PATH: { + return RTR("WaitNodeSignal"); + } break; + case CALL_MODE_INSTANCE: { + return RTR("WaitInstanceSignal"); + } break; + } + return String(); } String VisualScriptYieldSignal::get_text() const { diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp index 049d816a5a..5ff5b2339c 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp @@ -166,7 +166,7 @@ void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { active = true; seek(p_from_pos); loops = 0; - _begin_resample(); + begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { diff --git a/modules/vorbis/doc_classes/AudioStreamOGGVorbis.xml b/modules/vorbis/doc_classes/AudioStreamOGGVorbis.xml index 4cd278fe83..2f210a6cb4 100644 --- a/modules/vorbis/doc_classes/AudioStreamOGGVorbis.xml +++ b/modules/vorbis/doc_classes/AudioStreamOGGVorbis.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="AudioStreamOGGVorbis" inherits="AudioStream" version="4.0"> +<class name="AudioStreamOGGVorbis" inherits="AudioStream" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml b/modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml index 05c70d88da..68aa46147f 100644 --- a/modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml +++ b/modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="AudioStreamPlaybackOGGVorbis" inherits="AudioStreamPlaybackResampled" version="4.0"> +<class name="AudioStreamPlaybackOGGVorbis" inherits="AudioStreamPlaybackResampled" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/vorbis/resource_importer_ogg_vorbis.cpp b/modules/vorbis/resource_importer_ogg_vorbis.cpp index ccd463fd52..d12e65a96a 100644 --- a/modules/vorbis/resource_importer_ogg_vorbis.cpp +++ b/modules/vorbis/resource_importer_ogg_vorbis.cpp @@ -136,11 +136,11 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin // Have a page now. if (!initialized_stream) { - ogg_stream_init(&stream_state, ogg_page_serialno(&page)); - ERR_FAIL_COND_V_MSG((err = ogg_stream_check(&stream_state)), Error::ERR_INVALID_DATA, "Ogg stream error " + itos(err)); + if (ogg_stream_init(&stream_state, ogg_page_serialno(&page))) { + ERR_FAIL_V_MSG(Error::ERR_OUT_OF_MEMORY, "Failed allocating memory for OGG Vorbis stream."); + } initialized_stream = true; } - ERR_FAIL_COND_V_MSG((err = ogg_stream_check(&stream_state)), Error::ERR_INVALID_DATA, "Ogg stream error " + itos(err)); ogg_stream_pagein(&stream_state, &page); ERR_FAIL_COND_V_MSG((err = ogg_stream_check(&stream_state)), Error::ERR_INVALID_DATA, "Ogg stream error " + itos(err)); int desync_iters = 0; @@ -160,10 +160,12 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin break; } if (packet_count == 0 && vorbis_synthesis_idheader(&packet) == 0) { - WARN_PRINT("Found a non-vorbis-header packet in a header position"); + print_verbose("Found a non-vorbis-header packet in a header position"); // Clearly this logical stream is not a vorbis stream, so destroy it and try again with the next page. - ogg_stream_destroy(&stream_state); - initialized_stream = false; + if (initialized_stream) { + ogg_stream_clear(&stream_state); + initialized_stream = false; + } break; } granule_pos = packet.granulepos; @@ -178,6 +180,14 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin ogg_packet_sequence->push_page(granule_pos, packet_data); } } + if (initialized_stream) { + ogg_stream_clear(&stream_state); + } + ogg_sync_clear(&sync_state); + + if (ogg_packet_sequence->get_packet_granule_positions().is_empty()) { + ERR_FAIL_V_MSG(Error::ERR_FILE_CORRUPT, "OGG Vorbis decoding failed. Check that your data is a valid OGG Vorbis audio stream."); + } ogg_vorbis_stream->set_packet_sequence(ogg_packet_sequence); ogg_vorbis_stream->set_loop(loop); diff --git a/modules/webrtc/doc_classes/WebRTCDataChannel.xml b/modules/webrtc/doc_classes/WebRTCDataChannel.xml index cf5735bab5..a9ba8a23de 100644 --- a/modules/webrtc/doc_classes/WebRTCDataChannel.xml +++ b/modules/webrtc/doc_classes/WebRTCDataChannel.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebRTCDataChannel" inherits="PacketPeer" version="4.0"> +<class name="WebRTCDataChannel" inherits="PacketPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/webrtc/doc_classes/WebRTCDataChannelExtension.xml b/modules/webrtc/doc_classes/WebRTCDataChannelExtension.xml index 746fabd6e5..f937fba9d6 100644 --- a/modules/webrtc/doc_classes/WebRTCDataChannelExtension.xml +++ b/modules/webrtc/doc_classes/WebRTCDataChannelExtension.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebRTCDataChannelExtension" inherits="WebRTCDataChannel" version="4.0"> +<class name="WebRTCDataChannelExtension" inherits="WebRTCDataChannel" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml index 780791c0d9..3996a002ed 100644 --- a/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml +++ b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebRTCMultiplayerPeer" inherits="MultiplayerPeer" version="4.0"> +<class name="WebRTCMultiplayerPeer" inherits="MultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI]. </brief_description> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml index 416a674435..b4d97077e3 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebRTCPeerConnection" inherits="RefCounted" version="4.0"> +<class name="WebRTCPeerConnection" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Interface to a WebRTC peer connection. </brief_description> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml b/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml index d296fcd6e7..e88acdc845 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebRTCPeerConnectionExtension" inherits="WebRTCPeerConnection" version="4.0"> +<class name="WebRTCPeerConnectionExtension" inherits="WebRTCPeerConnection" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> </brief_description> <description> diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp index e6a8dcc31a..283e421e11 100644 --- a/modules/webrtc/register_types.cpp +++ b/modules/webrtc/register_types.cpp @@ -47,7 +47,7 @@ void register_webrtc_types() { ClassDB::register_custom_instance_class<WebRTCPeerConnection>(); GDREGISTER_CLASS(WebRTCPeerConnectionExtension); - GDREGISTER_VIRTUAL_CLASS(WebRTCDataChannel); + GDREGISTER_ABSTRACT_CLASS(WebRTCDataChannel); GDREGISTER_CLASS(WebRTCDataChannelExtension); GDREGISTER_CLASS(WebRTCMultiplayerPeer); diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp index 4c41a4c7ee..0fb074b0c2 100644 --- a/modules/webrtc/webrtc_data_channel_js.cpp +++ b/modules/webrtc/webrtc_data_channel_js.cpp @@ -31,6 +31,7 @@ #ifdef JAVASCRIPT_ENABLED #include "webrtc_data_channel_js.h" + #include "emscripten.h" extern "C" { @@ -104,8 +105,9 @@ int WebRTCDataChannelJS::get_available_packet_count() const { 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) + if (queue_count == 0) { return ERR_UNAVAILABLE; + } uint32_t to_read = 0; uint32_t left = 0; diff --git a/modules/webrtc/webrtc_multiplayer_peer.cpp b/modules/webrtc/webrtc_multiplayer_peer.cpp index bc3c0d9265..0bc42b104c 100644 --- a/modules/webrtc/webrtc_multiplayer_peer.cpp +++ b/modules/webrtc/webrtc_multiplayer_peer.cpp @@ -353,10 +353,8 @@ Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_si ch += CH_RESERVED_MAX - 1; } - Map<int, Ref<ConnectedPeer>>::Element *E = nullptr; - if (target_peer > 0) { - E = peer_map.find(target_peer); + Map<int, Ref<ConnectedPeer>>::Element *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_MSG(E->value()->channels.size() <= ch, ERR_INVALID_PARAMETER, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value()->channels.size())); @@ -372,7 +370,7 @@ Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_si continue; } - ERR_CONTINUE_MSG(F.value->channels.size() <= ch, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value()->channels.size())); + ERR_CONTINUE_MSG(F.value->channels.size() <= ch, vformat("Unable to send packet on channel %d, max channels: %d", ch, F.value->channels.size())); ERR_CONTINUE(F.value->channels[ch].is_null()); F.value->channels[ch]->put_packet(p_buffer, p_buffer_size); } diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml index 5fcf51293d..ad2acf8a21 100644 --- a/modules/websocket/doc_classes/WebSocketClient.xml +++ b/modules/websocket/doc_classes/WebSocketClient.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebSocketClient" inherits="WebSocketMultiplayerPeer" version="4.0"> +<class name="WebSocketClient" inherits="WebSocketMultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A WebSocket client implementation. </brief_description> diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml index 8d8ab220e2..4a617f4c82 100644 --- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml +++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebSocketMultiplayerPeer" inherits="MultiplayerPeer" version="4.0"> +<class name="WebSocketMultiplayerPeer" inherits="MultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> Base class for WebSocket server and client. </brief_description> diff --git a/modules/websocket/doc_classes/WebSocketPeer.xml b/modules/websocket/doc_classes/WebSocketPeer.xml index 2f455c32fd..6466654517 100644 --- a/modules/websocket/doc_classes/WebSocketPeer.xml +++ b/modules/websocket/doc_classes/WebSocketPeer.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebSocketPeer" inherits="PacketPeer" version="4.0"> +<class name="WebSocketPeer" inherits="PacketPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A class representing a specific WebSocket connection. </brief_description> diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml index f901b089ea..ef3279aac4 100644 --- a/modules/websocket/doc_classes/WebSocketServer.xml +++ b/modules/websocket/doc_classes/WebSocketServer.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebSocketServer" inherits="WebSocketMultiplayerPeer" version="4.0"> +<class name="WebSocketServer" inherits="WebSocketMultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> A WebSocket server implementation. </brief_description> diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp index 2d029dfbbc..e051a3b564 100644 --- a/modules/websocket/emws_client.cpp +++ b/modules/websocket/emws_client.cpp @@ -31,6 +31,7 @@ #ifdef JAVASCRIPT_ENABLED #include "emws_client.h" + #include "core/config/project_settings.h" #include "core/io/ip.h" #include "emscripten.h" @@ -45,8 +46,9 @@ void EMWSClient::_esws_on_message(void *obj, const uint8_t *p_data, int p_data_s EMWSClient *client = static_cast<EMWSClient *>(obj); Error err = static_cast<EMWSPeer *>(*client->get_peer(1))->read_msg(p_data, p_data_size, p_is_string == 1); - if (err == OK) + if (err == OK) { client->_on_peer_packet(); + } } void EMWSClient::_esws_on_error(void *obj) { @@ -71,8 +73,9 @@ Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, String proto_string; for (int i = 0; i < p_protocols.size(); i++) { - if (i != 0) + if (i != 0) { proto_string += ","; + } proto_string += p_protocols[i]; } @@ -109,8 +112,9 @@ Ref<WebSocketPeer> EMWSClient::get_peer(int p_peer_id) const { MultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const { if (_peer->is_connected_to_host()) { - if (_is_connecting) + if (_is_connecting) { return CONNECTION_CONNECTING; + } return CONNECTION_CONNECTED; } diff --git a/modules/websocket/emws_peer.cpp b/modules/websocket/emws_peer.cpp index 77a96c8e4f..86169f88e9 100644 --- a/modules/websocket/emws_peer.cpp +++ b/modules/websocket/emws_peer.cpp @@ -31,6 +31,7 @@ #ifdef JAVASCRIPT_ENABLED #include "emws_peer.h" + #include "core/io/ip.h" void EMWSPeer::set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size) { @@ -66,8 +67,9 @@ Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { } Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - if (_in_buffer.packets_left() == 0) + if (_in_buffer.packets_left() == 0) { return ERR_UNAVAILABLE; + } int read = 0; Error err = _in_buffer.read_packet(_packet_buffer.ptrw(), _packet_buffer.size(), &_is_string, read); @@ -109,7 +111,7 @@ void EMWSPeer::close(int p_code, String p_reason) { IPAddress EMWSPeer::get_connected_host() const { ERR_FAIL_V_MSG(IPAddress(), "Not supported in HTML5 export."); -}; +} uint16_t EMWSPeer::get_connected_port() const { ERR_FAIL_V_MSG(0, "Not supported in HTML5 export."); diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp index 1e9a4c0392..ff900f496f 100644 --- a/modules/websocket/register_types.cpp +++ b/modules/websocket/register_types.cpp @@ -63,7 +63,7 @@ void register_websocket_types() { WSLServer::make_default(); #endif - GDREGISTER_VIRTUAL_CLASS(WebSocketMultiplayerPeer); + GDREGISTER_ABSTRACT_CLASS(WebSocketMultiplayerPeer); ClassDB::register_custom_instance_class<WebSocketServer>(); ClassDB::register_custom_instance_class<WebSocketClient>(); ClassDB::register_custom_instance_class<WebSocketPeer>(); diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp index bebb198126..1ef571b6ee 100644 --- a/modules/websocket/wsl_client.cpp +++ b/modules/websocket/wsl_client.cpp @@ -177,7 +177,7 @@ Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, } } - // We assume OK while hostname resultion is pending. + // We assume OK while hostname resolution is pending. Error err = _resolver_id != IP::RESOLVER_INVALID_ID ? OK : FAILED; while (_ip_candidates.size()) { err = _tcp->connect_to_host(_ip_candidates.pop_front(), p_port); diff --git a/modules/webxr/doc_classes/WebXRInterface.xml b/modules/webxr/doc_classes/WebXRInterface.xml index 6e224a8242..48447eb074 100644 --- a/modules/webxr/doc_classes/WebXRInterface.xml +++ b/modules/webxr/doc_classes/WebXRInterface.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebXRInterface" inherits="XRInterface" version="4.0"> +<class name="WebXRInterface" inherits="XRInterface" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> AR/VR interface using WebXR. </brief_description> diff --git a/modules/webxr/register_types.cpp b/modules/webxr/register_types.cpp index 78fed3fbd6..a15dc93248 100644 --- a/modules/webxr/register_types.cpp +++ b/modules/webxr/register_types.cpp @@ -38,7 +38,7 @@ Ref<WebXRInterfaceJS> webxr; #endif void register_webxr_types() { - GDREGISTER_VIRTUAL_CLASS(WebXRInterface); + GDREGISTER_ABSTRACT_CLASS(WebXRInterface); #ifdef JAVASCRIPT_ENABLED webxr.instantiate(); diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp index 86b857f72c..06b0e31801 100644 --- a/modules/webxr/webxr_interface_js.cpp +++ b/modules/webxr/webxr_interface_js.cpp @@ -31,11 +31,13 @@ #ifdef JAVASCRIPT_ENABLED #include "webxr_interface_js.h" + #include "core/input/input.h" #include "core/os/os.h" #include "emscripten.h" #include "godot_webxr.h" #include "servers/rendering/renderer_compositor.h" + #include <stdlib.h> void _emwebxr_on_session_supported(char *p_session_mode, int p_supported) { @@ -481,7 +483,6 @@ void WebXRInterfaceJS::_update_tracker(int p_controller_id) { sprintf(name, "axis_%i", i); float value = *((float *)axes + (i + 1)); - ; tracker->set_input(name, value); } free(axes); diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp index 6f397fe285..139df9c735 100644 --- a/modules/xatlas_unwrap/register_types.cpp +++ b/modules/xatlas_unwrap/register_types.cpp @@ -120,6 +120,8 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver xatlas::ChartOptions chart_options; chart_options.fixWinding = true; + ERR_FAIL_COND_V_MSG(p_texel_size <= 0.0f, false, "Texel size must be greater than 0."); + xatlas::PackOptions pack_options; pack_options.padding = 1; pack_options.maxChartSize = 4094; // Lightmap atlassing needs 2 for padding between meshes, so 4096-2 |