summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/actions/godot-deps/action.yml2
-rw-r--r--.github/actions/upload-artifact/action.yml2
-rw-r--r--.github/workflows/android_builds.yml13
-rw-r--r--.github/workflows/ios_builds.yml4
-rw-r--r--.github/workflows/javascript_builds.yml12
-rw-r--r--.github/workflows/linux_builds.yml39
-rw-r--r--.github/workflows/macos_builds.yml6
-rw-r--r--.github/workflows/static_checks.yml16
-rw-r--r--.github/workflows/windows_builds.yml6
-rw-r--r--CONTRIBUTING.md8
-rw-r--r--SConstruct21
-rw-r--r--core/config/engine.cpp44
-rw-r--r--core/config/engine.h15
-rw-r--r--core/config/project_settings.cpp19
-rw-r--r--core/config/project_settings.h5
-rw-r--r--core/core_bind.cpp53
-rw-r--r--core/core_bind.h33
-rw-r--r--core/core_constants.cpp1
-rw-r--r--core/extension/extension_api_dump.cpp16
-rw-r--r--core/extension/gdnative_interface.h10
-rw-r--r--core/extension/native_extension.cpp2
-rw-r--r--core/input/input.cpp11
-rw-r--r--core/input/input.h20
-rw-r--r--core/input/input_event.cpp14
-rw-r--r--core/input/input_event.h2
-rw-r--r--core/input/input_map.cpp9
-rw-r--r--core/input/input_map.h7
-rw-r--r--core/io/file_access.cpp4
-rw-r--r--core/io/file_access.h1
-rw-r--r--core/io/image_loader.cpp6
-rw-r--r--core/io/image_loader.h9
-rw-r--r--core/io/ip.cpp17
-rw-r--r--core/io/ip.h9
-rw-r--r--core/io/json.cpp23
-rw-r--r--core/io/json.h3
-rw-r--r--core/io/resource_saver.cpp2
-rw-r--r--core/math/a_star.cpp6
-rw-r--r--core/math/a_star.h4
-rw-r--r--core/math/basis.cpp61
-rw-r--r--core/math/basis.h3
-rw-r--r--core/math/math_funcs.h23
-rw-r--r--core/math/quaternion.cpp56
-rw-r--r--core/math/quaternion.h1
-rw-r--r--core/math/vector2.h8
-rw-r--r--core/math/vector3.cpp16
-rw-r--r--core/math/vector3.h11
-rw-r--r--core/math/vector4.cpp9
-rw-r--r--core/math/vector4.h1
-rw-r--r--core/object/class_db.cpp4
-rw-r--r--core/object/object.cpp88
-rw-r--r--core/object/object.h68
-rw-r--r--core/object/ref_counted.cpp3
-rw-r--r--core/object/script_language.cpp13
-rw-r--r--core/object/script_language.h14
-rw-r--r--core/object/script_language_extension.cpp1
-rw-r--r--core/object/script_language_extension.h13
-rw-r--r--core/os/keyboard.h44
-rw-r--r--core/os/os.cpp8
-rw-r--r--core/os/os.h4
-rw-r--r--core/string/translation.cpp8
-rw-r--r--core/string/translation.h2
-rw-r--r--core/string/ustring.cpp106
-rw-r--r--core/variant/variant_call.cpp5
-rw-r--r--core/variant/variant_construct.cpp1
-rw-r--r--core/variant/variant_utility.cpp6
-rw-r--r--doc/classes/@GlobalScope.xml28
-rw-r--r--doc/classes/AABB.xml2
-rw-r--r--doc/classes/AStar2D.xml2
-rw-r--r--doc/classes/AStar3D.xml2
-rw-r--r--doc/classes/Animation.xml30
-rw-r--r--doc/classes/AnimationLibrary.xml12
-rw-r--r--doc/classes/AnimationNodeStateMachineTransition.xml5
-rw-r--r--doc/classes/AnimationNodeTransition.xml4
-rw-r--r--doc/classes/Area2D.xml4
-rw-r--r--doc/classes/Area3D.xml2
-rw-r--r--doc/classes/Array.xml4
-rw-r--r--doc/classes/AudioEffectChorus.xml2
-rw-r--r--doc/classes/AudioEffectDelay.xml24
-rw-r--r--doc/classes/AudioServer.xml6
-rw-r--r--doc/classes/BaseMaterial3D.xml6
-rw-r--r--doc/classes/Basis.xml6
-rw-r--r--doc/classes/BitMap.xml4
-rw-r--r--doc/classes/Button.xml2
-rw-r--r--doc/classes/ButtonGroup.xml2
-rw-r--r--doc/classes/Camera3D.xml2
-rw-r--r--doc/classes/CameraServer.xml2
-rw-r--r--doc/classes/CanvasItem.xml22
-rw-r--r--doc/classes/CanvasLayer.xml4
-rw-r--r--doc/classes/CharacterBody2D.xml28
-rw-r--r--doc/classes/CharacterBody3D.xml28
-rw-r--r--doc/classes/CheckBox.xml2
-rw-r--r--doc/classes/CheckButton.xml2
-rw-r--r--doc/classes/ClassDB.xml6
-rw-r--r--doc/classes/CodeEdit.xml10
-rw-r--r--doc/classes/CollisionObject2D.xml5
-rw-r--r--doc/classes/CollisionObject3D.xml5
-rw-r--r--doc/classes/CollisionShape2D.xml3
-rw-r--r--doc/classes/CollisionShape3D.xml3
-rw-r--r--doc/classes/ConcavePolygonShape2D.xml1
-rw-r--r--doc/classes/ConcavePolygonShape3D.xml1
-rw-r--r--doc/classes/ConeTwistJoint3D.xml4
-rw-r--r--doc/classes/Control.xml2
-rw-r--r--doc/classes/DisplayServer.xml71
-rw-r--r--doc/classes/EditorImportPlugin.xml2
-rw-r--r--doc/classes/EditorInterface.xml11
-rw-r--r--doc/classes/EditorNode3DGizmo.xml2
-rw-r--r--doc/classes/EditorPlugin.xml4
-rw-r--r--doc/classes/EditorResourcePicker.xml4
-rw-r--r--doc/classes/EditorSelection.xml2
-rw-r--r--doc/classes/EditorSettings.xml30
-rw-r--r--doc/classes/EditorSyntaxHighlighter.xml2
-rw-r--r--doc/classes/EditorUndoRedoManager.xml118
-rw-r--r--doc/classes/EditorVCSInterface.xml2
-rw-r--r--doc/classes/Engine.xml2
-rw-r--r--doc/classes/FontFile.xml6
-rw-r--r--doc/classes/GPUParticlesCollision3D.xml4
-rw-r--r--doc/classes/GPUParticlesCollisionBox3D.xml2
-rw-r--r--doc/classes/GPUParticlesCollisionHeightField3D.xml2
-rw-r--r--doc/classes/GPUParticlesCollisionSDF3D.xml2
-rw-r--r--doc/classes/GPUParticlesCollisionSphere3D.xml2
-rw-r--r--doc/classes/Generic6DOFJoint3D.xml12
-rw-r--r--doc/classes/Geometry2D.xml16
-rw-r--r--doc/classes/Geometry3D.xml6
-rw-r--r--doc/classes/GraphEdit.xml4
-rw-r--r--doc/classes/HTTPRequest.xml2
-rw-r--r--doc/classes/HingeJoint3D.xml4
-rw-r--r--doc/classes/IP.xml6
-rw-r--r--doc/classes/ImageTexture.xml6
-rw-r--r--doc/classes/ImporterMesh.xml4
-rw-r--r--doc/classes/InputMap.xml4
-rw-r--r--doc/classes/JSON.xml17
-rw-r--r--doc/classes/Joint3D.xml8
-rw-r--r--doc/classes/Label.xml10
-rw-r--r--doc/classes/Label3D.xml7
-rw-r--r--doc/classes/Line2D.xml2
-rw-r--r--doc/classes/LineEdit.xml4
-rw-r--r--doc/classes/Marker2D.xml (renamed from doc/classes/Position2D.xml)2
-rw-r--r--doc/classes/Marker3D.xml (renamed from doc/classes/Position3D.xml)2
-rw-r--r--doc/classes/MenuBar.xml172
-rw-r--r--doc/classes/MenuButton.xml2
-rw-r--r--doc/classes/Mesh.xml8
-rw-r--r--doc/classes/MeshInstance3D.xml2
-rw-r--r--doc/classes/MultiMeshInstance3D.xml2
-rw-r--r--doc/classes/NavigationAgent2D.xml4
-rw-r--r--doc/classes/NavigationAgent3D.xml4
-rw-r--r--doc/classes/NavigationMeshGenerator.xml2
-rw-r--r--doc/classes/NavigationServer2D.xml12
-rw-r--r--doc/classes/NavigationServer3D.xml12
-rw-r--r--doc/classes/Node.xml4
-rw-r--r--doc/classes/Node3D.xml16
-rw-r--r--doc/classes/OS.xml8
-rw-r--r--doc/classes/Object.xml42
-rw-r--r--doc/classes/OptionButton.xml2
-rw-r--r--doc/classes/PackedByteArray.xml32
-rw-r--r--doc/classes/PackedColorArray.xml5
-rw-r--r--doc/classes/PackedFloat32Array.xml7
-rw-r--r--doc/classes/PackedFloat64Array.xml6
-rw-r--r--doc/classes/PackedInt32Array.xml5
-rw-r--r--doc/classes/PackedInt64Array.xml4
-rw-r--r--doc/classes/PackedStringArray.xml5
-rw-r--r--doc/classes/PackedVector2Array.xml6
-rw-r--r--doc/classes/PackedVector3Array.xml6
-rw-r--r--doc/classes/ParticlesMaterial.xml25
-rw-r--r--doc/classes/PathFollow2D.xml12
-rw-r--r--doc/classes/PathFollow3D.xml12
-rw-r--r--doc/classes/Performance.xml2
-rw-r--r--doc/classes/PhysicsBody2D.xml4
-rw-r--r--doc/classes/PhysicsBody3D.xml4
-rw-r--r--doc/classes/PhysicsDirectSpaceState2D.xml8
-rw-r--r--doc/classes/PhysicsDirectSpaceState3D.xml8
-rw-r--r--doc/classes/PhysicsServer2D.xml19
-rw-r--r--doc/classes/PhysicsServer3D.xml19
-rw-r--r--doc/classes/PhysicsServer3DExtension.xml13
-rw-r--r--doc/classes/PlaneMesh.xml16
-rw-r--r--doc/classes/Polygon2D.xml6
-rw-r--r--doc/classes/PopupMenu.xml37
-rw-r--r--doc/classes/PrimitiveMesh.xml2
-rw-r--r--doc/classes/ProjectSettings.xml68
-rw-r--r--doc/classes/Projection.xml10
-rw-r--r--doc/classes/ProxyTexture.xml13
-rw-r--r--doc/classes/QuadMesh.xml21
-rw-r--r--doc/classes/Quaternion.xml16
-rw-r--r--doc/classes/RDUniform.xml2
-rw-r--r--doc/classes/RayCast2D.xml6
-rw-r--r--doc/classes/RayCast3D.xml6
-rw-r--r--doc/classes/ReflectionProbe.xml2
-rw-r--r--doc/classes/RenderingServer.xml12
-rw-r--r--doc/classes/ResourceFormatSaver.xml4
-rw-r--r--doc/classes/RichTextLabel.xml8
-rw-r--r--doc/classes/RigidDynamicBody2D.xml28
-rw-r--r--doc/classes/RigidDynamicBody3D.xml30
-rw-r--r--doc/classes/SceneTree.xml4
-rw-r--r--doc/classes/Script.xml6
-rw-r--r--doc/classes/ScriptEditor.xml4
-rw-r--r--doc/classes/ScriptExtension.xml6
-rw-r--r--doc/classes/ShaderMaterial.xml14
-rw-r--r--doc/classes/Shape2D.xml4
-rw-r--r--doc/classes/Skeleton3D.xml23
-rw-r--r--doc/classes/SkeletonModification2DCCDIK.xml2
-rw-r--r--doc/classes/SkeletonModification2DFABRIK.xml2
-rw-r--r--doc/classes/SkeletonModification2DPhysicalBones.xml2
-rw-r--r--doc/classes/SkeletonModification3DCCDIK.xml2
-rw-r--r--doc/classes/SkeletonModificationStack3D.xml2
-rw-r--r--doc/classes/SliderJoint3D.xml4
-rw-r--r--doc/classes/SoftDynamicBody3D.xml2
-rw-r--r--doc/classes/StreamPeer.xml6
-rw-r--r--doc/classes/String.xml4
-rw-r--r--doc/classes/SubViewport.xml2
-rw-r--r--doc/classes/SystemFont.xml3
-rw-r--r--doc/classes/TextEdit.xml10
-rw-r--r--doc/classes/TextServer.xml14
-rw-r--r--doc/classes/TextServerExtension.xml8
-rw-r--r--doc/classes/TextServerManager.xml2
-rw-r--r--doc/classes/TileMap.xml19
-rw-r--r--doc/classes/TranslationServer.xml2
-rw-r--r--doc/classes/Tree.xml5
-rw-r--r--doc/classes/TreeItem.xml2
-rw-r--r--doc/classes/Variant.xml1
-rw-r--r--doc/classes/Vector2.xml14
-rw-r--r--doc/classes/Vector3.xml14
-rw-r--r--doc/classes/Vector4.xml14
-rw-r--r--doc/classes/VelocityTracker3D.xml32
-rw-r--r--doc/classes/VisualShader.xml16
-rw-r--r--doc/classes/VisualShaderNodeCustom.xml4
-rw-r--r--doc/classes/VisualShaderNodeExpression.xml2
-rw-r--r--doc/classes/VisualShaderNodeGroupBase.xml2
-rw-r--r--doc/classes/XMLParser.xml2
-rw-r--r--doc/classes/XRServer.xml2
-rw-r--r--drivers/alsa/audio_driver_alsa.cpp31
-rw-r--r--drivers/alsa/audio_driver_alsa.h8
-rw-r--r--drivers/alsamidi/midi_driver_alsamidi.cpp8
-rw-r--r--drivers/alsamidi/midi_driver_alsamidi.h3
-rw-r--r--drivers/coreaudio/audio_driver_coreaudio.cpp10
-rw-r--r--drivers/coreaudio/audio_driver_coreaudio.h6
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.cpp4
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.cpp5
-rw-r--r--drivers/gles3/shaders/scene.glsl22
-rw-r--r--drivers/gles3/storage/material_storage.cpp66
-rw-r--r--drivers/gles3/storage/material_storage.h2
-rw-r--r--drivers/gles3/storage/mesh_storage.cpp41
-rw-r--r--drivers/gles3/storage/mesh_storage.h8
-rw-r--r--drivers/png/SCsub2
-rw-r--r--drivers/png/image_loader_png.cpp4
-rw-r--r--drivers/png/image_loader_png.h2
-rw-r--r--drivers/pulseaudio/audio_driver_pulseaudio.cpp35
-rw-r--r--drivers/pulseaudio/audio_driver_pulseaudio.h14
-rw-r--r--drivers/vulkan/rendering_device_vulkan.cpp6
-rw-r--r--drivers/wasapi/audio_driver_wasapi.cpp43
-rw-r--r--drivers/wasapi/audio_driver_wasapi.h12
-rw-r--r--drivers/windows/dir_access_windows.cpp2
-rw-r--r--drivers/xaudio2/audio_driver_xaudio2.cpp17
-rw-r--r--drivers/xaudio2/audio_driver_xaudio2.h6
-rw-r--r--editor/action_map_editor.cpp3
-rw-r--r--editor/animation_bezier_editor.cpp293
-rw-r--r--editor/animation_bezier_editor.h43
-rw-r--r--editor/animation_track_editor.cpp442
-rw-r--r--editor/animation_track_editor.h41
-rw-r--r--editor/animation_track_editor_plugins.cpp1
-rw-r--r--editor/array_property_edit.cpp7
-rw-r--r--editor/code_editor.cpp4
-rw-r--r--editor/connections_dialog.cpp5
-rw-r--r--editor/connections_dialog.h6
-rw-r--r--editor/create_dialog.cpp8
-rw-r--r--editor/create_dialog.h2
-rw-r--r--editor/debugger/editor_debugger_inspector.cpp1
-rw-r--r--editor/debugger/editor_debugger_inspector.h1
-rw-r--r--editor/debugger/editor_debugger_node.cpp8
-rw-r--r--editor/debugger/editor_debugger_node.h2
-rw-r--r--editor/debugger/script_editor_debugger.cpp3
-rw-r--r--editor/dictionary_property_edit.cpp5
-rw-r--r--editor/editor_audio_buses.cpp39
-rw-r--r--editor/editor_autoload_settings.cpp11
-rw-r--r--editor/editor_data.cpp82
-rw-r--r--editor/editor_data.h22
-rw-r--r--editor/editor_file_system.cpp5
-rw-r--r--editor/editor_help.cpp2
-rw-r--r--editor/editor_inspector.cpp50
-rw-r--r--editor/editor_inspector.h11
-rw-r--r--editor/editor_locale_dialog.cpp1
-rw-r--r--editor/editor_locale_dialog.h4
-rw-r--r--editor/editor_log.cpp6
-rw-r--r--editor/editor_log.h3
-rw-r--r--editor/editor_node.cpp518
-rw-r--r--editor/editor_node.h27
-rw-r--r--editor/editor_path.cpp2
-rw-r--r--editor/editor_plugin.cpp29
-rw-r--r--editor/editor_plugin.h14
-rw-r--r--editor/editor_properties.cpp159
-rw-r--r--editor/editor_properties.h21
-rw-r--r--editor/editor_resource_picker.cpp108
-rw-r--r--editor/editor_resource_picker.h2
-rw-r--r--editor/editor_run.cpp9
-rw-r--r--editor/editor_sectioned_inspector.cpp8
-rw-r--r--editor/editor_settings.cpp24
-rw-r--r--editor/editor_settings.h6
-rw-r--r--editor/editor_settings_dialog.cpp10
-rw-r--r--editor/editor_settings_dialog.h4
-rw-r--r--editor/editor_spin_slider.cpp4
-rw-r--r--editor/editor_spin_slider.h2
-rw-r--r--editor/editor_themes.cpp319
-rw-r--r--editor/editor_themes.h16
-rw-r--r--editor/editor_undo_redo_manager.cpp442
-rw-r--r--editor/editor_undo_redo_manager.h134
-rw-r--r--editor/editor_vcs_interface.cpp8
-rw-r--r--editor/editor_vcs_interface.h4
-rw-r--r--editor/groups_editor.cpp9
-rw-r--r--editor/groups_editor.h11
-rw-r--r--editor/icons/BezierHandlesBalanced.svg2
-rw-r--r--editor/icons/BezierHandlesFree.svg2
-rw-r--r--editor/icons/BezierHandlesLinear.svg1
-rw-r--r--editor/icons/BezierHandlesMirror.svg2
-rw-r--r--editor/icons/ContainerLayout.svg1
-rw-r--r--editor/icons/ControlLayout.svg2
-rw-r--r--editor/icons/CurveIn.svg2
-rw-r--r--editor/icons/CurveInOut.svg2
-rw-r--r--editor/icons/CurveLinear.svg2
-rw-r--r--editor/icons/CurveOut.svg2
-rw-r--r--editor/icons/CurveOutIn.svg2
-rw-r--r--editor/icons/DefaultProjectIcon.svg2
-rw-r--r--editor/icons/InterpCubicInTime.svg1
-rw-r--r--editor/icons/Marker2D.svg (renamed from editor/icons/Position2D.svg)0
-rw-r--r--editor/icons/Marker3D.svg (renamed from editor/icons/Position3D.svg)0
-rw-r--r--editor/icons/MenuBar.svg1
-rw-r--r--editor/icons/NodeInfo.svg1
-rw-r--r--editor/import/editor_import_plugin.cpp2
-rw-r--r--editor/import/editor_import_plugin.h3
-rw-r--r--editor/import/post_import_plugin_skeleton_rest_fixer.cpp270
-rw-r--r--editor/import/resource_importer_layered_texture.cpp2
-rw-r--r--editor/import/resource_importer_scene.cpp16
-rw-r--r--editor/import/resource_importer_scene.h2
-rw-r--r--editor/import/resource_importer_texture.cpp29
-rw-r--r--editor/import/resource_importer_texture_atlas.cpp1
-rw-r--r--editor/inspector_dock.cpp58
-rw-r--r--editor/inspector_dock.h9
-rw-r--r--editor/localization_editor.cpp1
-rw-r--r--editor/localization_editor.h2
-rw-r--r--editor/multi_node_edit.cpp3
-rw-r--r--editor/node_dock.cpp2
-rw-r--r--editor/plugins/abstract_polygon_2d_editor.cpp1
-rw-r--r--editor/plugins/abstract_polygon_2d_editor.h3
-rw-r--r--editor/plugins/animation_blend_space_1d_editor.cpp1
-rw-r--r--editor/plugins/animation_blend_space_1d_editor.h4
-rw-r--r--editor/plugins/animation_blend_space_2d_editor.cpp1
-rw-r--r--editor/plugins/animation_blend_space_2d_editor.h4
-rw-r--r--editor/plugins/animation_blend_tree_editor_plugin.cpp1
-rw-r--r--editor/plugins/animation_blend_tree_editor_plugin.h3
-rw-r--r--editor/plugins/animation_library_editor.cpp25
-rw-r--r--editor/plugins/animation_player_editor_plugin.cpp6
-rw-r--r--editor/plugins/animation_player_editor_plugin.h5
-rw-r--r--editor/plugins/animation_state_machine_editor.cpp1
-rw-r--r--editor/plugins/animation_state_machine_editor.h3
-rw-r--r--editor/plugins/audio_stream_randomizer_editor_plugin.cpp5
-rw-r--r--editor/plugins/bone_map_editor_plugin.cpp931
-rw-r--r--editor/plugins/bone_map_editor_plugin.h65
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp130
-rw-r--r--editor/plugins/canvas_item_editor_plugin.h5
-rw-r--r--editor/plugins/cast_2d_editor_plugin.cpp1
-rw-r--r--editor/plugins/cast_2d_editor_plugin.h3
-rw-r--r--editor/plugins/collision_shape_2d_editor_plugin.cpp1
-rw-r--r--editor/plugins/collision_shape_2d_editor_plugin.h3
-rw-r--r--editor/plugins/control_editor_plugin.cpp849
-rw-r--r--editor/plugins/control_editor_plugin.h172
-rw-r--r--editor/plugins/cpu_particles_2d_editor_plugin.cpp1
-rw-r--r--editor/plugins/cpu_particles_2d_editor_plugin.h3
-rw-r--r--editor/plugins/curve_editor_plugin.cpp54
-rw-r--r--editor/plugins/debugger_editor_plugin.cpp73
-rw-r--r--editor/plugins/debugger_editor_plugin.h4
-rw-r--r--editor/plugins/font_config_plugin.cpp14
-rw-r--r--editor/plugins/font_config_plugin.h6
-rw-r--r--editor/plugins/gpu_particles_2d_editor_plugin.cpp3
-rw-r--r--editor/plugins/gpu_particles_2d_editor_plugin.h3
-rw-r--r--editor/plugins/gpu_particles_3d_editor_plugin.cpp5
-rw-r--r--editor/plugins/gradient_editor_plugin.cpp3
-rw-r--r--editor/plugins/gradient_texture_2d_editor_plugin.cpp5
-rw-r--r--editor/plugins/gradient_texture_2d_editor_plugin.h6
-rw-r--r--editor/plugins/material_editor_plugin.cpp7
-rw-r--r--editor/plugins/mesh_instance_3d_editor_plugin.cpp15
-rw-r--r--editor/plugins/node_3d_editor_gizmos.cpp61
-rw-r--r--editor/plugins/node_3d_editor_gizmos.h6
-rw-r--r--editor/plugins/node_3d_editor_plugin.cpp68
-rw-r--r--editor/plugins/node_3d_editor_plugin.h9
-rw-r--r--editor/plugins/path_2d_editor_plugin.cpp1
-rw-r--r--editor/plugins/path_2d_editor_plugin.h3
-rw-r--r--editor/plugins/path_3d_editor_plugin.cpp13
-rw-r--r--editor/plugins/polygon_3d_editor_plugin.cpp1
-rw-r--r--editor/plugins/polygon_3d_editor_plugin.h3
-rw-r--r--editor/plugins/resource_preloader_editor_plugin.cpp6
-rw-r--r--editor/plugins/resource_preloader_editor_plugin.h5
-rw-r--r--editor/plugins/script_editor_plugin.cpp23
-rw-r--r--editor/plugins/script_editor_plugin.h10
-rw-r--r--editor/plugins/script_text_editor.cpp12
-rw-r--r--editor/plugins/script_text_editor.h2
-rw-r--r--editor/plugins/shader_editor_plugin.cpp2
-rw-r--r--editor/plugins/skeleton_2d_editor_plugin.cpp5
-rw-r--r--editor/plugins/skeleton_3d_editor_plugin.cpp38
-rw-r--r--editor/plugins/skeleton_3d_editor_plugin.h10
-rw-r--r--editor/plugins/sprite_2d_editor_plugin.cpp9
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.cpp7
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.h5
-rw-r--r--editor/plugins/text_editor.cpp6
-rw-r--r--editor/plugins/text_editor.h2
-rw-r--r--editor/plugins/texture_region_editor_plugin.cpp1
-rw-r--r--editor/plugins/texture_region_editor_plugin.h3
-rw-r--r--editor/plugins/theme_editor_plugin.cpp49
-rw-r--r--editor/plugins/tiles/atlas_merging_dialog.cpp1
-rw-r--r--editor/plugins/tiles/atlas_merging_dialog.h3
-rw-r--r--editor/plugins/tiles/tile_atlas_view.cpp30
-rw-r--r--editor/plugins/tiles/tile_atlas_view.h2
-rw-r--r--editor/plugins/tiles/tile_data_editors.cpp26
-rw-r--r--editor/plugins/tiles/tile_data_editors.h14
-rw-r--r--editor/plugins/tiles/tile_map_editor.cpp5
-rw-r--r--editor/plugins/tiles/tile_map_editor.h8
-rw-r--r--editor/plugins/tiles/tile_proxies_manager_dialog.cpp1
-rw-r--r--editor/plugins/tiles/tile_proxies_manager_dialog.h2
-rw-r--r--editor/plugins/tiles/tile_set_atlas_source_editor.cpp16
-rw-r--r--editor/plugins/tiles/tile_set_atlas_source_editor.h2
-rw-r--r--editor/plugins/tiles/tile_set_editor.cpp9
-rw-r--r--editor/plugins/tiles/tile_set_editor.h4
-rw-r--r--editor/plugins/tiles/tile_set_scenes_collection_source_editor.h2
-rw-r--r--editor/plugins/version_control_editor_plugin.cpp2
-rw-r--r--editor/plugins/visual_shader_editor_plugin.cpp46
-rw-r--r--editor/plugins/visual_shader_editor_plugin.h13
-rw-r--r--editor/project_converter_3_to_4.cpp37
-rw-r--r--editor/project_manager.cpp47
-rw-r--r--editor/project_settings_editor.cpp5
-rw-r--r--editor/project_settings_editor.h4
-rw-r--r--editor/rename_dialog.cpp5
-rw-r--r--editor/rename_dialog.h7
-rw-r--r--editor/scene_tree_dock.cpp365
-rw-r--r--editor/scene_tree_editor.cpp28
-rw-r--r--editor/scene_tree_editor.h7
-rw-r--r--editor/shader_create_dialog.cpp7
-rw-r--r--editor/shader_create_dialog.h7
-rw-r--r--editor/shader_globals_editor.cpp7
-rw-r--r--editor/shader_globals_editor.h1
-rw-r--r--gles3_builders.py8
-rw-r--r--glsl_builders.py126
-rw-r--r--main/main.cpp107
-rw-r--r--main/main.h11
-rw-r--r--main/performance.cpp7
-rw-r--r--main/performance.h6
-rw-r--r--methods.py19
-rwxr-xr-xmisc/scripts/clang_format.sh3
-rwxr-xr-xmisc/scripts/pytest_builders.sh5
-rw-r--r--modules/bmp/image_loader_bmp.cpp2
-rw-r--r--modules/bmp/image_loader_bmp.h2
-rw-r--r--modules/csg/csg_shape.cpp44
-rw-r--r--modules/csg/csg_shape.h8
-rw-r--r--modules/csg/doc_classes/CSGShape3D.xml2
-rw-r--r--modules/csg/editor/csg_gizmos.cpp10
-rw-r--r--modules/denoise/config.py9
-rw-r--r--modules/enet/doc_classes/ENetConnection.xml2
-rw-r--r--modules/enet/enet_connection.cpp5
-rw-r--r--modules/enet/enet_connection.h5
-rw-r--r--modules/gdscript/doc_classes/@GDScript.xml178
-rw-r--r--modules/gdscript/editor/gdscript_highlighter.cpp77
-rw-r--r--modules/gdscript/editor/gdscript_highlighter.h2
-rw-r--r--modules/gdscript/gdscript.cpp43
-rw-r--r--modules/gdscript/gdscript.h5
-rw-r--r--modules/gdscript/gdscript_parser.cpp2
-rw-r--r--modules/gdscript/gdscript_utility_functions.cpp5
-rw-r--r--modules/gdscript/gdscript_utility_functions.h3
-rw-r--r--modules/gltf/doc_classes/GLTFCamera.xml13
-rw-r--r--modules/gltf/doc_classes/GLTFSkeleton.xml4
-rw-r--r--modules/gltf/doc_classes/GLTFSkin.xml4
-rw-r--r--modules/gltf/doc_classes/GLTFState.xml60
-rw-r--r--modules/gltf/gltf_document.cpp89
-rw-r--r--modules/gltf/gltf_state.cpp68
-rw-r--r--modules/gltf/gltf_state.h64
-rw-r--r--modules/gltf/gltf_template_convert.h6
-rw-r--r--modules/gltf/register_types.cpp25
-rw-r--r--modules/gltf/structures/gltf_camera.cpp15
-rw-r--r--modules/gltf/structures/gltf_camera.h27
-rw-r--r--modules/gltf/structures/gltf_skeleton.cpp4
-rw-r--r--modules/gltf/structures/gltf_skeleton.h4
-rw-r--r--modules/gltf/structures/gltf_skin.cpp5
-rw-r--r--modules/gltf/structures/gltf_skin.h7
-rw-r--r--modules/gridmap/doc_classes/GridMap.xml27
-rw-r--r--modules/gridmap/editor/grid_map_editor_plugin.cpp61
-rw-r--r--modules/gridmap/editor/grid_map_editor_plugin.h3
-rw-r--r--modules/gridmap/grid_map.cpp90
-rw-r--r--modules/gridmap/grid_map.h7
-rw-r--r--modules/hdr/image_loader_hdr.cpp4
-rw-r--r--modules/hdr/image_loader_hdr.h2
-rw-r--r--modules/jpg/image_loader_jpegd.cpp2
-rw-r--r--modules/jpg/image_loader_jpegd.h2
-rw-r--r--modules/mono/.editorconfig29
-rw-r--r--modules/mono/Directory.Build.props5
-rw-r--r--modules/mono/Directory.Build.targets22
-rw-r--r--modules/mono/README.md45
-rw-r--r--modules/mono/SCsub35
-rw-r--r--modules/mono/SdkPackageVersions.props5
-rw-r--r--modules/mono/build_scripts/api_solution_build.py80
-rwxr-xr-xmodules/mono/build_scripts/build_assemblies.py329
-rw-r--r--modules/mono/build_scripts/gen_cs_glue_version.py20
-rw-r--r--modules/mono/build_scripts/godot_net_sdk_build.py55
-rw-r--r--modules/mono/build_scripts/godot_tools_build.py38
-rw-r--r--modules/mono/build_scripts/make_android_mono_config.py55
-rw-r--r--modules/mono/build_scripts/mono_android_config.xml28
-rw-r--r--modules/mono/build_scripts/mono_configure.py697
-rw-r--r--modules/mono/build_scripts/mono_reg_utils.py112
-rw-r--r--modules/mono/build_scripts/solution_builder.py145
-rw-r--r--modules/mono/config.py30
-rw-r--r--modules/mono/csharp_script.cpp2179
-rw-r--r--modules/mono/csharp_script.h188
-rw-r--r--modules/mono/doc_classes/GodotSharp.xml47
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln2
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj10
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props18
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets6
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/EventSignals.cs7
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs109
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs109
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Generic.cs5
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Godot.SourceGenerators.Sample.csproj4
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Methods.cs31
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs36
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Common.cs311
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs236
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj14
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.props3
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotClasses.cs9
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotEnums.cs148
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotMemberData.cs84
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs60
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs73
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs678
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MethodInfo.cs24
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MustBeVariantAnalyzer.cs100
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/PropertyInfo.cs23
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs408
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs36
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs657
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs293
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptRegistrarGenerator.cs19
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs283
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs432
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj26
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe0
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs6
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs13
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.sln14
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs57
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs224
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs28
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs208
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildTool.cs10
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs99
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs10
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs233
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs14
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs47
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs388
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs130
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj20
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs6
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs12
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs6
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs25
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs63
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs214
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs173
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs8
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs267
-rw-r--r--modules/mono/editor/bindings_generator.cpp1878
-rw-r--r--modules/mono/editor/bindings_generator.h205
-rw-r--r--modules/mono/editor/editor_internal_calls.cpp330
-rw-r--r--modules/mono/editor/editor_internal_calls.h6
-rw-r--r--modules/mono/editor/godotsharp_export.cpp144
-rw-r--r--modules/mono/editor/godotsharp_export.h48
-rw-r--r--modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs2
-rw-r--r--modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs4
-rw-r--r--modules/mono/editor/script_templates/VisualShaderNodeCustom/basic.cs2
-rw-r--r--modules/mono/glue/GodotSharp/.editorconfig8
-rw-r--r--modules/mono/glue/GodotSharp/ExternalAnnotations/System.Runtime.InteropServices.xml5
-rw-r--r--modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/CallbacksInfo.cs24
-rw-r--r--modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Common.cs65
-rw-r--r--modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/ExtensionMethods.cs119
-rw-r--r--modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/GeneratorClasses.cs6
-rw-r--r--modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Godot.SourceGenerators.Internal.csproj11
-rw-r--r--modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/UnmanagedCallbacksGenerator.cs463
-rw-r--r--modules/mono/glue/GodotSharp/GodotPlugins/GodotPlugins.csproj17
-rw-r--r--modules/mono/glue/GodotSharp/GodotPlugins/Main.cs270
-rw-r--r--modules/mono/glue/GodotSharp/GodotPlugins/PluginLoadContext.cs64
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp.sln12
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp.sln.DotSettings8
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs666
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/AssemblyHasScriptsAttribute.cs17
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/DisableGodotGeneratorsAttribute.cs10
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportAttribute.cs2
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportCategoryAttribute.cs22
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportGroupAttribute.cs25
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportSubgroupAttribute.cs25
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/GodotMethodAttribute.cs24
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/MustBeVariantAttribute.cs11
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ScriptPathAttribute.cs4
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs83
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/AlcReloadCfg.cs18
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs253
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GCHandleBridge.cs22
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GodotSerializationInfo.cs87
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs89
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/MethodInfo.cs25
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/PropertyInfo.cs24
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs1028
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.types.cs92
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs70
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs8
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs292
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/CustomGCHandle.cs98
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/DebuggingUtils.cs107
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs243
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs677
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Dispatcher.cs20
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/DisposablesTracker.cs95
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs220
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/NodeExtensions.cs21
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/ObjectExtensions.cs17
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs21
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs192
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs30
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs154
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs12
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/CustomUnsafe.cs313
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/ExceptionUtils.cs139
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/GodotDllImportResolver.cs59
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropStructs.cs1091
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropUtils.cs96
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs1092
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs522
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs99
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs20
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs976
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantSpanHelpers.cs33
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs611
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/NodePath.cs146
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs164
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Object.exceptions.cs135
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Projection.cs90
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs98
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/RID.cs85
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/ReflectionUtils.cs16
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/SignalAwaiter.cs73
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/SignalInfo.cs2
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs92
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/StringName.cs120
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs44
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs236
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/UnhandledExceptionArgs.cs20
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs19
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs35
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs22
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs38
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs17
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4i.cs37
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/GlobalUsings.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj73
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj.DotSettings5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Variant.cs841
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj17
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj.DotSettings4
-rw-r--r--modules/mono/glue/arguments_vector.h67
-rw-r--r--modules/mono/glue/base_object_glue.cpp257
-rw-r--r--modules/mono/glue/callable_glue.cpp79
-rw-r--r--modules/mono/glue/collections_glue.cpp374
-rw-r--r--modules/mono/glue/gd_glue.cpp348
-rw-r--r--modules/mono/glue/glue_header.h91
-rw-r--r--modules/mono/glue/nodepath_glue.cpp102
-rw-r--r--modules/mono/glue/rid_glue.cpp64
-rw-r--r--modules/mono/glue/runtime_interop.cpp1513
-rw-r--r--modules/mono/glue/runtime_interop.h (renamed from modules/visual_script/register_types.h)15
-rw-r--r--modules/mono/glue/scene_tree_glue.cpp86
-rw-r--r--modules/mono/glue/string_glue.cpp85
-rw-r--r--modules/mono/glue/string_name_glue.cpp62
-rw-r--r--modules/mono/godotsharp_defs.h4
-rw-r--r--modules/mono/godotsharp_dirs.cpp62
-rw-r--r--modules/mono/godotsharp_dirs.h9
-rw-r--r--modules/mono/interop_types.h208
-rw-r--r--modules/mono/managed_callable.cpp60
-rw-r--r--modules/mono/managed_callable.h14
-rw-r--r--modules/mono/mono_gc_handle.cpp32
-rw-r--r--modules/mono/mono_gc_handle.h56
-rw-r--r--modules/mono/mono_gd/gd_mono.cpp1471
-rw-r--r--modules/mono/mono_gd/gd_mono.h246
-rw-r--r--modules/mono/mono_gd/gd_mono_assembly.cpp482
-rw-r--r--modules/mono/mono_gd/gd_mono_assembly.h138
-rw-r--r--modules/mono/mono_gd/gd_mono_cache.cpp350
-rw-r--r--modules/mono/mono_gd/gd_mono_cache.h258
-rw-r--r--modules/mono/mono_gd/gd_mono_class.cpp576
-rw-r--r--modules/mono/mono_gd/gd_mono_class.h160
-rw-r--r--modules/mono/mono_gd/gd_mono_field.cpp556
-rw-r--r--modules/mono/mono_gd/gd_mono_field.h78
-rw-r--r--modules/mono/mono_gd/gd_mono_header.h52
-rw-r--r--modules/mono/mono_gd/gd_mono_internals.cpp145
-rw-r--r--modules/mono/mono_gd/gd_mono_internals.h52
-rw-r--r--modules/mono/mono_gd/gd_mono_log.cpp209
-rw-r--r--modules/mono/mono_gd/gd_mono_log.h71
-rw-r--r--modules/mono/mono_gd/gd_mono_marshal.cpp1824
-rw-r--r--modules/mono/mono_gd/gd_mono_marshal.h605
-rw-r--r--modules/mono/mono_gd/gd_mono_method.cpp296
-rw-r--r--modules/mono/mono_gd/gd_mono_method.h97
-rw-r--r--modules/mono/mono_gd/gd_mono_method_thunk.h320
-rw-r--r--modules/mono/mono_gd/gd_mono_property.cpp202
-rw-r--r--modules/mono/mono_gd/gd_mono_property.h80
-rw-r--r--modules/mono/mono_gd/gd_mono_utils.cpp677
-rw-r--r--modules/mono/mono_gd/gd_mono_utils.h205
-rw-r--r--modules/mono/mono_gd/gd_mono_wasm_m2n.cpp79
-rw-r--r--modules/mono/mono_gd/gd_mono_wasm_m2n.h263
-rw-r--r--modules/mono/mono_gd/i_mono_class_member.h70
-rw-r--r--modules/mono/mono_gd/managed_type.cpp58
-rw-r--r--modules/mono/mono_gd/managed_type.h55
-rw-r--r--modules/mono/mono_gd/support/android_support.cpp2
-rw-r--r--modules/mono/signal_awaiter_utils.cpp82
-rw-r--r--modules/mono/signal_awaiter_utils.h21
-rw-r--r--modules/mono/utils/mono_reg_utils.cpp242
-rw-r--r--modules/mono/utils/mono_reg_utils.h54
-rw-r--r--modules/mono/utils/path_utils.cpp31
-rw-r--r--modules/mono/utils/path_utils.h2
-rw-r--r--modules/mono/utils/string_utils.cpp29
-rw-r--r--modules/mono/utils/string_utils.h3
-rw-r--r--modules/multiplayer/editor/replication_editor_plugin.cpp7
-rw-r--r--modules/navigation/godot_navigation_server.cpp16
-rw-r--r--modules/navigation/godot_navigation_server.h8
-rw-r--r--modules/noise/fastnoise_lite.cpp18
-rw-r--r--modules/noise/fastnoise_lite.h2
-rw-r--r--modules/noise/noise_texture.cpp10
-rw-r--r--modules/noise/noise_texture.h2
-rw-r--r--modules/raycast/SCsub4
-rw-r--r--modules/raycast/config.py16
-rw-r--r--modules/regex/doc_classes/RegEx.xml2
-rw-r--r--modules/regex/regex.cpp4
-rw-r--r--modules/regex/regex.h2
-rw-r--r--modules/regex/tests/test_regex.h2
-rw-r--r--modules/svg/image_loader_svg.cpp26
-rw-r--r--modules/svg/image_loader_svg.h9
-rw-r--r--modules/text_server_adv/text_server_adv.cpp32
-rw-r--r--modules/text_server_adv/text_server_adv.h6
-rw-r--r--modules/text_server_fb/text_server_fb.cpp32
-rw-r--r--modules/text_server_fb/text_server_fb.h6
-rw-r--r--modules/tga/image_loader_tga.cpp2
-rw-r--r--modules/tga/image_loader_tga.h2
-rw-r--r--modules/tinyexr/image_loader_tinyexr.cpp6
-rw-r--r--modules/tinyexr/image_loader_tinyexr.h2
-rw-r--r--modules/visual_script/SCsub11
-rw-r--r--modules/visual_script/config.py63
-rw-r--r--modules/visual_script/doc_classes/VisualScript.xml357
-rw-r--r--modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml19
-rw-r--r--modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml221
-rw-r--r--modules/visual_script/doc_classes/VisualScriptClassConstant.xml23
-rw-r--r--modules/visual_script/doc_classes/VisualScriptComment.xml23
-rw-r--r--modules/visual_script/doc_classes/VisualScriptComposeArray.xml11
-rw-r--r--modules/visual_script/doc_classes/VisualScriptCondition.xml18
-rw-r--r--modules/visual_script/doc_classes/VisualScriptConstant.xml23
-rw-r--r--modules/visual_script/doc_classes/VisualScriptConstructor.xml35
-rw-r--r--modules/visual_script/doc_classes/VisualScriptCustomNode.xml166
-rw-r--r--modules/visual_script/doc_classes/VisualScriptCustomNodes.xml37
-rw-r--r--modules/visual_script/doc_classes/VisualScriptDeconstruct.xml16
-rw-r--r--modules/visual_script/doc_classes/VisualScriptEmitSignal.xml20
-rw-r--r--modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml16
-rw-r--r--modules/visual_script/doc_classes/VisualScriptExpression.xml11
-rw-r--r--modules/visual_script/doc_classes/VisualScriptFunction.xml11
-rw-r--r--modules/visual_script/doc_classes/VisualScriptFunctionCall.xml75
-rw-r--r--modules/visual_script/doc_classes/VisualScriptFunctionState.xml35
-rw-r--r--modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml16
-rw-r--r--modules/visual_script/doc_classes/VisualScriptIndexGet.xml11
-rw-r--r--modules/visual_script/doc_classes/VisualScriptIndexSet.xml11
-rw-r--r--modules/visual_script/doc_classes/VisualScriptInputAction.xml33
-rw-r--r--modules/visual_script/doc_classes/VisualScriptIterator.xml18
-rw-r--r--modules/visual_script/doc_classes/VisualScriptLists.xml77
-rw-r--r--modules/visual_script/doc_classes/VisualScriptLocalVar.xml23
-rw-r--r--modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml25
-rw-r--r--modules/visual_script/doc_classes/VisualScriptMathConstant.xml49
-rw-r--r--modules/visual_script/doc_classes/VisualScriptNode.xml47
-rw-r--r--modules/visual_script/doc_classes/VisualScriptOperator.xml23
-rw-r--r--modules/visual_script/doc_classes/VisualScriptPreload.xml20
-rw-r--r--modules/visual_script/doc_classes/VisualScriptPropertyGet.xml48
-rw-r--r--modules/visual_script/doc_classes/VisualScriptPropertySet.xml84
-rw-r--r--modules/visual_script/doc_classes/VisualScriptResourcePath.xml13
-rw-r--r--modules/visual_script/doc_classes/VisualScriptReturn.xml24
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSceneNode.xml20
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSceneTree.xml11
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSelect.xml22
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSelf.xml15
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSequence.xml22
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSubCall.xml11
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSwitch.xml20
-rw-r--r--modules/visual_script/doc_classes/VisualScriptTypeCast.xml19
-rw-r--r--modules/visual_script/doc_classes/VisualScriptVariableGet.xml20
-rw-r--r--modules/visual_script/doc_classes/VisualScriptVariableSet.xml21
-rw-r--r--modules/visual_script/doc_classes/VisualScriptWhile.xml17
-rw-r--r--modules/visual_script/doc_classes/VisualScriptYield.xml30
-rw-r--r--modules/visual_script/doc_classes/VisualScriptYieldSignal.xml36
-rw-r--r--modules/visual_script/editor/visual_script_editor.cpp4979
-rw-r--r--modules/visual_script/editor/visual_script_editor.h395
-rw-r--r--modules/visual_script/editor/visual_script_property_selector.cpp1277
-rw-r--r--modules/visual_script/editor/visual_script_property_selector.h229
-rw-r--r--modules/visual_script/icons/VisualScript.svg1
-rw-r--r--modules/visual_script/icons/VisualScriptInternal.svg1
-rw-r--r--modules/visual_script/register_types.cpp150
-rw-r--r--modules/visual_script/visual_script.cpp2506
-rw-r--r--modules/visual_script/visual_script.h627
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.cpp1380
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.h153
-rw-r--r--modules/visual_script/visual_script_expression.cpp1570
-rw-r--r--modules/visual_script/visual_script_expression.h284
-rw-r--r--modules/visual_script/visual_script_flow_control.cpp880
-rw-r--r--modules/visual_script/visual_script_flow_control.h268
-rw-r--r--modules/visual_script/visual_script_func_nodes.cpp2444
-rw-r--r--modules/visual_script/visual_script_func_nodes.h363
-rw-r--r--modules/visual_script/visual_script_nodes.cpp4072
-rw-r--r--modules/visual_script/visual_script_nodes.h1092
-rw-r--r--modules/visual_script/visual_script_yield_nodes.cpp598
-rw-r--r--modules/visual_script/visual_script_yield_nodes.h147
-rw-r--r--modules/webp/SCsub238
-rw-r--r--modules/webp/image_loader_webp.cpp2
-rw-r--r--modules/webp/image_loader_webp.h2
-rw-r--r--platform/android/README.md7
-rw-r--r--platform/android/SCsub8
-rw-r--r--platform/android/detect.py44
-rw-r--r--platform/android/dir_access_jandroid.cpp14
-rw-r--r--platform/android/dir_access_jandroid.h1
-rw-r--r--platform/android/display_server_android.cpp4
-rw-r--r--platform/android/display_server_android.h4
-rw-r--r--platform/android/export/export_plugin.cpp8
-rw-r--r--platform/android/java/build.gradle4
-rw-r--r--platform/android/java/lib/build.gradle2
-rw-r--r--platform/android/java_godot_io_wrapper.cpp4
-rw-r--r--platform/android/java_godot_io_wrapper.h4
-rw-r--r--platform/android/os_android.cpp6
-rw-r--r--platform/ios/README.md14
-rw-r--r--platform/ios/detect.py15
-rw-r--r--platform/ios/display_server_ios.h2
-rw-r--r--platform/ios/display_server_ios.mm4
-rw-r--r--platform/ios/export/export_plugin.cpp63
-rw-r--r--platform/javascript/README.md11
-rw-r--r--platform/javascript/detect.py10
-rw-r--r--platform/javascript/display_server_javascript.cpp2
-rw-r--r--platform/javascript/display_server_javascript.h2
-rw-r--r--platform/javascript/js/libs/library_godot_display.js28
-rw-r--r--platform/javascript/os_javascript.h1
-rw-r--r--platform/linuxbsd/README.md14
-rw-r--r--platform/linuxbsd/detect.py42
-rw-r--r--platform/linuxbsd/display_server_x11.cpp4
-rw-r--r--platform/linuxbsd/display_server_x11.h2
-rw-r--r--platform/macos/README.md19
-rw-r--r--platform/macos/detect.py29
-rw-r--r--platform/macos/display_server_macos.h25
-rw-r--r--platform/macos/display_server_macos.mm412
-rw-r--r--platform/macos/godot_menu_item.h1
-rw-r--r--platform/uwp/README.md20
-rw-r--r--platform/uwp/detect.py39
-rw-r--r--platform/windows/README.md15
-rw-r--r--platform/windows/detect.py100
-rw-r--r--platform/windows/display_server_windows.cpp4
-rw-r--r--platform/windows/display_server_windows.h2
-rw-r--r--platform/windows/platform_windows_builders.py2
-rw-r--r--platform_methods.py36
-rw-r--r--scene/2d/animated_sprite_2d.cpp26
-rw-r--r--scene/2d/animated_sprite_2d.h2
-rw-r--r--scene/2d/area_2d.cpp26
-rw-r--r--scene/2d/area_2d.h2
-rw-r--r--scene/2d/audio_stream_player_2d.cpp6
-rw-r--r--scene/2d/audio_stream_player_2d.h2
-rw-r--r--scene/2d/camera_2d.cpp6
-rw-r--r--scene/2d/camera_2d.h2
-rw-r--r--scene/2d/collision_object_2d.cpp18
-rw-r--r--scene/2d/collision_object_2d.h6
-rw-r--r--scene/2d/cpu_particles_2d.cpp30
-rw-r--r--scene/2d/cpu_particles_2d.h2
-rw-r--r--scene/2d/gpu_particles_2d.cpp2
-rw-r--r--scene/2d/gpu_particles_2d.h2
-rw-r--r--scene/2d/light_2d.cpp6
-rw-r--r--scene/2d/light_2d.h2
-rw-r--r--scene/2d/marker_2d.cpp (renamed from scene/2d/position_2d.cpp)26
-rw-r--r--scene/2d/marker_2d.h (renamed from scene/2d/position_2d.h)14
-rw-r--r--scene/2d/navigation_agent_2d.cpp14
-rw-r--r--scene/2d/navigation_agent_2d.h8
-rw-r--r--scene/2d/navigation_obstacle_2d.cpp2
-rw-r--r--scene/2d/navigation_obstacle_2d.h2
-rw-r--r--scene/2d/path_2d.cpp50
-rw-r--r--scene/2d/path_2d.h12
-rw-r--r--scene/2d/physical_bone_2d.cpp2
-rw-r--r--scene/2d/physics_body_2d.cpp93
-rw-r--r--scene/2d/physics_body_2d.h33
-rw-r--r--scene/2d/polygon_2d.cpp12
-rw-r--r--scene/2d/polygon_2d.h2
-rw-r--r--scene/2d/ray_cast_2d.cpp7
-rw-r--r--scene/2d/ray_cast_2d.h2
-rw-r--r--scene/2d/sprite_2d.cpp18
-rw-r--r--scene/2d/sprite_2d.h2
-rw-r--r--scene/2d/tile_map.cpp19
-rw-r--r--scene/2d/tile_map.h2
-rw-r--r--scene/3d/area_3d.cpp28
-rw-r--r--scene/3d/area_3d.h2
-rw-r--r--scene/3d/audio_stream_player_3d.cpp8
-rw-r--r--scene/3d/audio_stream_player_3d.h2
-rw-r--r--scene/3d/bone_attachment_3d.cpp14
-rw-r--r--scene/3d/bone_attachment_3d.h2
-rw-r--r--scene/3d/camera_3d.cpp9
-rw-r--r--scene/3d/camera_3d.h3
-rw-r--r--scene/3d/collision_object_3d.cpp18
-rw-r--r--scene/3d/collision_object_3d.h6
-rw-r--r--scene/3d/cpu_particles_3d.cpp32
-rw-r--r--scene/3d/cpu_particles_3d.h2
-rw-r--r--scene/3d/decal.cpp7
-rw-r--r--scene/3d/decal.h2
-rw-r--r--scene/3d/fog_volume.cpp7
-rw-r--r--scene/3d/fog_volume.h2
-rw-r--r--scene/3d/gpu_particles_3d.cpp10
-rw-r--r--scene/3d/gpu_particles_3d.h2
-rw-r--r--scene/3d/joint_3d.cpp168
-rw-r--r--scene/3d/joint_3d.h36
-rw-r--r--scene/3d/label_3d.cpp24
-rw-r--r--scene/3d/label_3d.h2
-rw-r--r--scene/3d/light_3d.cpp36
-rw-r--r--scene/3d/light_3d.h4
-rw-r--r--scene/3d/lightmap_gi.cpp15
-rw-r--r--scene/3d/lightmap_gi.h2
-rw-r--r--scene/3d/marker_3d.cpp (renamed from scene/3d/position_3d.cpp)6
-rw-r--r--scene/3d/marker_3d.h (renamed from scene/3d/position_3d.h)14
-rw-r--r--scene/3d/navigation_agent_3d.cpp14
-rw-r--r--scene/3d/navigation_agent_3d.h8
-rw-r--r--scene/3d/navigation_obstacle_3d.cpp2
-rw-r--r--scene/3d/navigation_obstacle_3d.h2
-rw-r--r--scene/3d/node_3d.cpp60
-rw-r--r--scene/3d/node_3d.h8
-rw-r--r--scene/3d/path_3d.cpp65
-rw-r--r--scene/3d/path_3d.h12
-rw-r--r--scene/3d/physics_body_3d.cpp102
-rw-r--r--scene/3d/physics_body_3d.h35
-rw-r--r--scene/3d/ray_cast_3d.cpp7
-rw-r--r--scene/3d/ray_cast_3d.h2
-rw-r--r--scene/3d/reflection_probe.cpp7
-rw-r--r--scene/3d/reflection_probe.h2
-rw-r--r--scene/3d/skeleton_3d.cpp78
-rw-r--r--scene/3d/skeleton_3d.h5
-rw-r--r--scene/3d/skeleton_ik_3d.cpp14
-rw-r--r--scene/3d/skeleton_ik_3d.h2
-rw-r--r--scene/3d/soft_dynamic_body_3d.cpp10
-rw-r--r--scene/3d/soft_dynamic_body_3d.h3
-rw-r--r--scene/3d/sprite_3d.cpp75
-rw-r--r--scene/3d/sprite_3d.h4
-rw-r--r--scene/3d/velocity_tracker_3d.h2
-rw-r--r--scene/3d/xr_nodes.cpp12
-rw-r--r--scene/3d/xr_nodes.h2
-rw-r--r--scene/animation/animation_blend_space_1d.cpp9
-rw-r--r--scene/animation/animation_blend_space_1d.h2
-rw-r--r--scene/animation/animation_blend_space_2d.cpp13
-rw-r--r--scene/animation/animation_blend_space_2d.h2
-rw-r--r--scene/animation/animation_blend_tree.cpp53
-rw-r--r--scene/animation/animation_blend_tree.h14
-rw-r--r--scene/animation/animation_node_state_machine.cpp21
-rw-r--r--scene/animation/animation_node_state_machine.h7
-rw-r--r--scene/animation/animation_player.cpp19
-rw-r--r--scene/animation/animation_player.h2
-rw-r--r--scene/animation/animation_tree.cpp6
-rw-r--r--scene/animation/animation_tree.h2
-rw-r--r--scene/animation/tween.cpp8
-rw-r--r--scene/audio/audio_stream_player.cpp8
-rw-r--r--scene/audio/audio_stream_player.h2
-rw-r--r--scene/gui/aspect_ratio_container.cpp12
-rw-r--r--scene/gui/base_button.cpp10
-rw-r--r--scene/gui/base_button.h4
-rw-r--r--scene/gui/box_container.cpp3
-rw-r--r--scene/gui/button.cpp10
-rw-r--r--scene/gui/check_box.cpp2
-rw-r--r--scene/gui/check_button.cpp2
-rw-r--r--scene/gui/code_edit.cpp14
-rw-r--r--scene/gui/code_edit.h8
-rw-r--r--scene/gui/color_picker.cpp18
-rw-r--r--scene/gui/color_rect.cpp3
-rw-r--r--scene/gui/control.cpp219
-rw-r--r--scene/gui/control.h14
-rw-r--r--scene/gui/dialogs.cpp3
-rw-r--r--scene/gui/file_dialog.cpp14
-rw-r--r--scene/gui/graph_edit.cpp21
-rw-r--r--scene/gui/graph_edit.h2
-rw-r--r--scene/gui/graph_node.cpp59
-rw-r--r--scene/gui/graph_node.h2
-rw-r--r--scene/gui/grid_container.cpp5
-rw-r--r--scene/gui/item_list.cpp87
-rw-r--r--scene/gui/label.cpp63
-rw-r--r--scene/gui/line_edit.cpp42
-rw-r--r--scene/gui/line_edit.h2
-rw-r--r--scene/gui/link_button.cpp4
-rw-r--r--scene/gui/menu_bar.cpp868
-rw-r--r--scene/gui/menu_bar.h156
-rw-r--r--scene/gui/menu_button.cpp15
-rw-r--r--scene/gui/nine_patch_rect.cpp17
-rw-r--r--scene/gui/option_button.cpp11
-rw-r--r--scene/gui/option_button.h2
-rw-r--r--scene/gui/popup_menu.cpp194
-rw-r--r--scene/gui/popup_menu.h11
-rw-r--r--scene/gui/range.cpp20
-rw-r--r--scene/gui/reference_rect.cpp15
-rw-r--r--scene/gui/rich_text_label.cpp72
-rw-r--r--scene/gui/rich_text_label.h4
-rw-r--r--scene/gui/slider.cpp12
-rw-r--r--scene/gui/spin_box.cpp8
-rw-r--r--scene/gui/split_container.cpp12
-rw-r--r--scene/gui/split_container.h1
-rw-r--r--scene/gui/subviewport_container.cpp4
-rw-r--r--scene/gui/tab_bar.cpp40
-rw-r--r--scene/gui/tab_container.cpp30
-rw-r--r--scene/gui/text_edit.cpp115
-rw-r--r--scene/gui/text_edit.h3
-rw-r--r--scene/gui/texture_button.cpp35
-rw-r--r--scene/gui/texture_progress_bar.cpp59
-rw-r--r--scene/gui/texture_rect.cpp16
-rw-r--r--scene/gui/tree.cpp224
-rw-r--r--scene/gui/tree.h9
-rw-r--r--scene/gui/video_stream_player.cpp8
-rw-r--r--scene/gui/video_stream_player.h2
-rw-r--r--scene/main/canvas_item.cpp4
-rw-r--r--scene/main/canvas_layer.cpp8
-rw-r--r--scene/main/canvas_layer.h2
-rw-r--r--scene/main/multiplayer_api.cpp22
-rw-r--r--scene/main/node.cpp4
-rw-r--r--scene/main/node.h2
-rw-r--r--scene/main/scene_tree.cpp8
-rw-r--r--scene/main/scene_tree.h4
-rw-r--r--scene/main/viewport.cpp19
-rw-r--r--scene/main/viewport.h2
-rw-r--r--scene/main/window.cpp10
-rw-r--r--scene/main/window.h2
-rw-r--r--scene/register_scene_types.cpp36
-rw-r--r--scene/resources/animation.cpp782
-rw-r--r--scene/resources/animation.h55
-rw-r--r--scene/resources/bit_map.cpp5
-rw-r--r--scene/resources/bit_map.h5
-rw-r--r--scene/resources/bone_map.cpp10
-rw-r--r--scene/resources/bone_map.h6
-rw-r--r--scene/resources/camera_effects.cpp10
-rw-r--r--scene/resources/camera_effects.h2
-rw-r--r--scene/resources/canvas_item_material.cpp6
-rw-r--r--scene/resources/canvas_item_material.h2
-rw-r--r--scene/resources/default_theme/default_theme.cpp24
-rw-r--r--scene/resources/environment.cpp42
-rw-r--r--scene/resources/environment.h2
-rw-r--r--scene/resources/font.cpp34
-rw-r--r--scene/resources/font.h10
-rw-r--r--scene/resources/immediate_mesh.cpp4
-rw-r--r--scene/resources/immediate_mesh.h2
-rw-r--r--scene/resources/material.cpp186
-rw-r--r--scene/resources/material.h8
-rw-r--r--scene/resources/mesh.cpp169
-rw-r--r--scene/resources/mesh.h14
-rw-r--r--scene/resources/mesh_library.h2
-rw-r--r--scene/resources/navigation_mesh.cpp12
-rw-r--r--scene/resources/navigation_mesh.h4
-rw-r--r--scene/resources/particles_material.cpp110
-rw-r--r--scene/resources/particles_material.h21
-rw-r--r--scene/resources/primitive_meshes.cpp131
-rw-r--r--scene/resources/primitive_meshes.h46
-rw-r--r--scene/resources/shape_2d.cpp20
-rw-r--r--scene/resources/shape_2d.h4
-rw-r--r--scene/resources/skeleton_modification_3d_ccdik.h6
-rw-r--r--scene/resources/skeleton_modification_3d_fabrik.h6
-rw-r--r--scene/resources/skeleton_modification_3d_jiggle.h6
-rw-r--r--scene/resources/skeleton_modification_3d_lookat.h6
-rw-r--r--scene/resources/skeleton_modification_3d_stackholder.h6
-rw-r--r--scene/resources/skeleton_modification_3d_twoboneik.h6
-rw-r--r--scene/resources/skeleton_profile.cpp16
-rw-r--r--scene/resources/skeleton_profile.h2
-rw-r--r--scene/resources/style_box.cpp6
-rw-r--r--scene/resources/style_box.h2
-rw-r--r--scene/resources/texture.cpp21
-rw-r--r--scene/resources/texture.h10
-rw-r--r--scene/resources/tile_set.cpp10
-rw-r--r--scene/resources/tile_set.h2
-rw-r--r--scene/resources/visual_shader.cpp104
-rw-r--r--scene/resources/visual_shader.h8
-rw-r--r--scene/resources/visual_shader_nodes.cpp16
-rw-r--r--servers/audio/audio_driver_dummy.cpp19
-rw-r--r--servers/audio/audio_driver_dummy.h6
-rw-r--r--servers/audio/effects/audio_effect_chorus.cpp8
-rw-r--r--servers/audio/effects/audio_effect_chorus.h2
-rw-r--r--servers/audio/effects/audio_effect_compressor.cpp6
-rw-r--r--servers/audio/effects/audio_effect_compressor.h2
-rw-r--r--servers/audio/effects/audio_effect_delay.cpp51
-rw-r--r--servers/audio/effects/audio_effect_delay.h29
-rw-r--r--servers/audio/effects/audio_effect_filter.h18
-rw-r--r--servers/audio_server.cpp12
-rw-r--r--servers/audio_server.h8
-rw-r--r--servers/camera_server.cpp5
-rw-r--r--servers/camera_server.h4
-rw-r--r--servers/display_server.cpp44
-rw-r--r--servers/display_server.h24
-rw-r--r--servers/extensions/physics_server_3d_extension.cpp3
-rw-r--r--servers/extensions/physics_server_3d_extension.h3
-rw-r--r--servers/navigation_server_2d.cpp12
-rw-r--r--servers/navigation_server_2d.h8
-rw-r--r--servers/navigation_server_3d.cpp4
-rw-r--r--servers/navigation_server_3d.h8
-rw-r--r--servers/physics_2d/godot_collision_object_2d.h8
-rw-r--r--servers/physics_2d/godot_physics_server_2d.cpp14
-rw-r--r--servers/physics_2d/godot_physics_server_2d.h3
-rw-r--r--servers/physics_2d/godot_space_2d.cpp14
-rw-r--r--servers/physics_3d/godot_collision_object_3d.h8
-rw-r--r--servers/physics_3d/godot_physics_server_3d.cpp14
-rw-r--r--servers/physics_3d/godot_physics_server_3d.h3
-rw-r--r--servers/physics_3d/godot_space_3d.cpp14
-rw-r--r--servers/physics_server_2d.cpp34
-rw-r--r--servers/physics_server_2d.h13
-rw-r--r--servers/physics_server_2d_wrap_mt.h3
-rw-r--r--servers/physics_server_3d.cpp36
-rw-r--r--servers/physics_server_3d.h13
-rw-r--r--servers/physics_server_3d_wrap_mt.h3
-rw-r--r--servers/rendering/renderer_rd/environment/sky.cpp14
-rw-r--r--servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp14
-rw-r--r--servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h1
-rw-r--r--servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp12
-rw-r--r--servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp29
-rw-r--r--servers/rendering/renderer_rd/renderer_canvas_render_rd.h1
-rw-r--r--servers/rendering/renderer_rd/renderer_scene_render_rd.cpp10
-rw-r--r--servers/rendering/renderer_rd/shaders/effects/bokeh_dof.glsl2
-rw-r--r--servers/rendering/renderer_rd/shaders/effects/bokeh_dof_raster.glsl2
-rw-r--r--servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl18
-rw-r--r--servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl18
-rw-r--r--servers/rendering/renderer_rd/shaders/skeleton.glsl64
-rw-r--r--servers/rendering/renderer_rd/storage_rd/material_storage.cpp14
-rw-r--r--servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp40
-rw-r--r--servers/rendering/renderer_scene_cull.cpp2
-rw-r--r--servers/rendering/renderer_viewport.cpp52
-rw-r--r--servers/rendering/renderer_viewport.h15
-rw-r--r--servers/rendering/rendering_device_binds.h6
-rw-r--r--servers/rendering/shader_compiler.cpp43
-rw-r--r--servers/rendering/shader_compiler.h1
-rw-r--r--servers/rendering/shader_language.cpp50
-rw-r--r--servers/rendering/shader_language.h6
-rw-r--r--servers/rendering/shader_preprocessor.cpp325
-rw-r--r--servers/rendering/shader_preprocessor.h36
-rw-r--r--servers/rendering_server.cpp95
-rw-r--r--servers/rendering_server.h19
-rw-r--r--servers/text/text_server_extension.cpp24
-rw-r--r--servers/text/text_server_extension.h17
-rw-r--r--servers/text_server.cpp21
-rw-r--r--servers/text_server.h19
-rw-r--r--servers/xr_server.cpp2
-rw-r--r--servers/xr_server.h2
-rw-r--r--tests/core/object/test_object.h6
-rw-r--r--tests/core/string/test_string.h118
-rw-r--r--tests/create_test.py132
-rw-r--r--tests/python_build/conftest.py26
-rw-r--r--tests/python_build/fixtures/gles3/_included.glsl1
-rw-r--r--tests/python_build/fixtures/gles3/vertex_fragment.glsl34
-rw-r--r--tests/python_build/fixtures/gles3/vertex_fragment_expected_full.glsl50
-rw-r--r--tests/python_build/fixtures/gles3/vertex_fragment_expected_parts.json52
-rw-r--r--tests/python_build/fixtures/glsl/_included.glsl1
-rw-r--r--tests/python_build/fixtures/glsl/compute.glsl12
-rw-r--r--tests/python_build/fixtures/glsl/compute_expected_full.glsl8
-rw-r--r--tests/python_build/fixtures/glsl/compute_expected_parts.json3
-rw-r--r--tests/python_build/fixtures/glsl/vertex_fragment.glsl32
-rw-r--r--tests/python_build/fixtures/glsl/vertex_fragment_expected_full.glsl8
-rw-r--r--tests/python_build/fixtures/glsl/vertex_fragment_expected_parts.json3
-rw-r--r--tests/python_build/fixtures/rd_glsl/_included.glsl1
-rw-r--r--tests/python_build/fixtures/rd_glsl/compute.glsl13
-rw-r--r--tests/python_build/fixtures/rd_glsl/compute_expected_full.glsl20
-rw-r--r--tests/python_build/fixtures/rd_glsl/compute_expected_parts.json28
-rw-r--r--tests/python_build/fixtures/rd_glsl/vertex_fragment.glsl25
-rw-r--r--tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_full.glsl23
-rw-r--r--tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_parts.json40
-rw-r--r--tests/python_build/test_gles3_builder.py31
-rw-r--r--tests/python_build/test_glsl_builder.py37
-rw-r--r--tests/scene/test_code_edit.h6
-rw-r--r--tests/scene/test_path_follow_2d.h94
-rw-r--r--tests/scene/test_path_follow_3d.h94
-rw-r--r--thirdparty/README.md5
-rw-r--r--thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp37
-rw-r--r--thirdparty/glslang/glslang/OSDependent/osinclude.h2
-rw-r--r--thirdparty/glslang/patches/unused_cleanup.diff61
-rw-r--r--thirdparty/libwebp/AUTHORS4
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv.c498
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv.h81
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_csp.c110
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_csp.h59
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_dsp.c102
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_dsp.h29
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_gamma.c114
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_gamma.h35
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_neon.c182
-rw-r--r--thirdparty/libwebp/sharpyuv/sharpyuv_sse2.c204
-rw-r--r--thirdparty/libwebp/src/dec/vp8i_dec.h2
-rw-r--r--thirdparty/libwebp/src/dec/vp8l_dec.c6
-rw-r--r--thirdparty/libwebp/src/demux/demux.c5
-rw-r--r--thirdparty/libwebp/src/dsp/alpha_processing_neon.c6
-rw-r--r--thirdparty/libwebp/src/dsp/cpu.c2
-rw-r--r--thirdparty/libwebp/src/dsp/cpu.h254
-rw-r--r--thirdparty/libwebp/src/dsp/dsp.h229
-rw-r--r--thirdparty/libwebp/src/dsp/lossless.h8
-rw-r--r--thirdparty/libwebp/src/dsp/lossless_enc.c12
-rw-r--r--thirdparty/libwebp/src/dsp/lossless_enc_mips32.c22
-rw-r--r--thirdparty/libwebp/src/dsp/lossless_enc_sse2.c4
-rw-r--r--thirdparty/libwebp/src/dsp/yuv.c64
-rw-r--r--thirdparty/libwebp/src/dsp/yuv_neon.c108
-rw-r--r--thirdparty/libwebp/src/dsp/yuv_sse2.c119
-rw-r--r--thirdparty/libwebp/src/enc/alpha_enc.c2
-rw-r--r--thirdparty/libwebp/src/enc/backward_references_cost_enc.c75
-rw-r--r--thirdparty/libwebp/src/enc/backward_references_enc.c86
-rw-r--r--thirdparty/libwebp/src/enc/backward_references_enc.h12
-rw-r--r--thirdparty/libwebp/src/enc/histogram_enc.c208
-rw-r--r--thirdparty/libwebp/src/enc/histogram_enc.h24
-rw-r--r--thirdparty/libwebp/src/enc/picture_csp_enc.c492
-rw-r--r--thirdparty/libwebp/src/enc/picture_enc.c44
-rw-r--r--thirdparty/libwebp/src/enc/picture_rescale_enc.c72
-rw-r--r--thirdparty/libwebp/src/enc/picture_tools_enc.c45
-rw-r--r--thirdparty/libwebp/src/enc/predictor_enc.c50
-rw-r--r--thirdparty/libwebp/src/enc/quant_enc.c62
-rw-r--r--thirdparty/libwebp/src/enc/vp8i_enc.h24
-rw-r--r--thirdparty/libwebp/src/enc/vp8l_enc.c527
-rw-r--r--thirdparty/libwebp/src/enc/vp8li_enc.h26
-rw-r--r--thirdparty/libwebp/src/enc/webp_enc.c4
-rw-r--r--thirdparty/libwebp/src/mux/muxedit.c1
-rw-r--r--thirdparty/libwebp/src/mux/muxi.h2
-rw-r--r--thirdparty/libwebp/src/mux/muxinternal.c9
-rw-r--r--thirdparty/libwebp/src/webp/encode.h6
-rw-r--r--thirdparty/spirv-reflect/patches/zero-calloc.patch28
-rw-r--r--thirdparty/spirv-reflect/spirv_reflect.c16
1231 files changed, 38786 insertions, 52645 deletions
diff --git a/.github/actions/godot-deps/action.yml b/.github/actions/godot-deps/action.yml
index ee4d7d3751..e99167ff2b 100644
--- a/.github/actions/godot-deps/action.yml
+++ b/.github/actions/godot-deps/action.yml
@@ -12,7 +12,7 @@ runs:
steps:
# Use python 3.x release (works cross platform)
- name: Set up Python 3.x
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
# Semantic version range syntax or exact version of a Python version
python-version: ${{ inputs.python-version }}
diff --git a/.github/actions/upload-artifact/action.yml b/.github/actions/upload-artifact/action.yml
index bc1871b914..ae0e634cbf 100644
--- a/.github/actions/upload-artifact/action.yml
+++ b/.github/actions/upload-artifact/action.yml
@@ -12,7 +12,7 @@ runs:
using: "composite"
steps:
- name: Upload Godot Artifact
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
diff --git a/.github/workflows/android_builds.yml b/.github/workflows/android_builds.yml
index a9a580247b..4f54f6629e 100644
--- a/.github/workflows/android_builds.yml
+++ b/.github/workflows/android_builds.yml
@@ -17,7 +17,7 @@ jobs:
name: Template (target=release, tools=no)
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
# Azure repositories are not reliable, we need to prevent azure giving us packages.
- name: Make apt sources.list use the default Ubuntu repositories
@@ -27,8 +27,9 @@ jobs:
sudo apt-get update
- name: Set up Java 11
- uses: actions/setup-java@v1
+ uses: actions/setup-java@v3
with:
+ distribution: temurin
java-version: 11
- name: Setup Godot build cache
@@ -38,19 +39,19 @@ jobs:
- name: Setup python and scons
uses: ./.github/actions/godot-deps
- - name: Compilation (armv7)
+ - name: Compilation (arm32)
uses: ./.github/actions/godot-build
with:
- sconsflags: ${{ env.SCONSFLAGS }} android_arch=armv7
+ sconsflags: ${{ env.SCONSFLAGS }} arch=arm32
platform: android
target: release
tools: false
tests: false
- - name: Compilation (arm64v8)
+ - name: Compilation (arm64)
uses: ./.github/actions/godot-build
with:
- sconsflags: ${{ env.SCONSFLAGS }} android_arch=arm64v8
+ sconsflags: ${{ env.SCONSFLAGS }} arch=arm64
platform: android
target: release
tools: false
diff --git a/.github/workflows/ios_builds.yml b/.github/workflows/ios_builds.yml
index 03277edc1d..bc00fad569 100644
--- a/.github/workflows/ios_builds.yml
+++ b/.github/workflows/ios_builds.yml
@@ -17,7 +17,7 @@ jobs:
name: Template (target=release, tools=no)
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Setup Godot build cache
uses: ./.github/actions/godot-cache
@@ -26,7 +26,7 @@ jobs:
- name: Setup python and scons
uses: ./.github/actions/godot-deps
- - name: Compilation (arm64v8)
+ - name: Compilation (arm64)
uses: ./.github/actions/godot-build
with:
sconsflags: ${{ env.SCONSFLAGS }}
diff --git a/.github/workflows/javascript_builds.yml b/.github/workflows/javascript_builds.yml
index 00c79e8ba0..54bde92b16 100644
--- a/.github/workflows/javascript_builds.yml
+++ b/.github/workflows/javascript_builds.yml
@@ -19,18 +19,10 @@ jobs:
name: Template (target=release, tools=no)
steps:
- - uses: actions/checkout@v2
-
- # Additional cache for Emscripten generated system libraries
- - name: Load Emscripten cache
- id: javascript-template-emscripten-cache
- uses: actions/cache@v2
- with:
- path: ${{env.EM_CACHE_FOLDER}}
- key: ${{env.EM_VERSION}}-${{github.job}}
+ - uses: actions/checkout@v3
- name: Set up Emscripten latest
- uses: mymindstorm/setup-emsdk@v10
+ uses: mymindstorm/setup-emsdk@v11
with:
version: ${{env.EM_VERSION}}
actions-cache-folder: ${{env.EM_CACHE_FOLDER}}
diff --git a/.github/workflows/linux_builds.yml b/.github/workflows/linux_builds.yml
index 0a0160326c..2e8bd101e5 100644
--- a/.github/workflows/linux_builds.yml
+++ b/.github/workflows/linux_builds.yml
@@ -4,8 +4,10 @@ on: [push, pull_request]
# Global Settings
env:
# Only used for the cache key. Increment version to force clean build.
- GODOT_BASE_BRANCH: master-v2
+ GODOT_BASE_BRANCH: master
SCONSFLAGS: verbose=yes warnings=extra werror=yes module_text_server_fb_enabled=yes
+ DOTNET_NOLOGO: true
+ DOTNET_CLI_TELEMETRY_OPTOUT: false
concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-linux
@@ -24,9 +26,9 @@ jobs:
target: release_debug
tools: true
tests: false # Disabled due freeze caused by mix Mono build and CI
- sconsflags: module_mono_enabled=yes mono_static=yes mono_glue=no
+ sconsflags: module_mono_enabled=yes
doc-test: true
- bin: "./bin/godot.linuxbsd.opt.tools.64.mono"
+ bin: "./bin/godot.linuxbsd.opt.tools.x86_64.mono"
build-mono: true
proj-conv: true
artifact: true
@@ -41,7 +43,7 @@ jobs:
# Can be turned off for PRs that intentionally break compat with godot-cpp,
# until both the upstream PR and the matching godot-cpp changes are merged.
godot-cpp-test: true
- bin: "./bin/godot.linuxbsd.double.tools.64.san"
+ bin: "./bin/godot.linuxbsd.double.tools.x86_64.san"
build-mono: false
# Skip 2GiB artifact speeding up action.
artifact: false
@@ -52,7 +54,7 @@ jobs:
tools: true
tests: true
sconsflags: use_asan=yes use_ubsan=yes use_llvm=yes linker=lld
- bin: "./bin/godot.linuxbsd.tools.64.llvm.san"
+ bin: "./bin/godot.linuxbsd.tools.x86_64.llvm.san"
build-mono: false
# Skip 2GiB artifact speeding up action.
artifact: false
@@ -62,7 +64,7 @@ jobs:
target: release
tools: false
tests: false
- sconsflags: module_mono_enabled=yes mono_static=yes mono_glue=no debug_symbols=no
+ sconsflags: module_mono_enabled=yes debug_symbols=no
build-mono: false
artifact: true
@@ -75,7 +77,7 @@ jobs:
artifact: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Linux dependencies
shell: bash
@@ -99,6 +101,12 @@ jobs:
- name: Setup python and scons
uses: ./.github/actions/godot-deps
+ - name: Set up .NET Sdk
+ uses: actions/setup-dotnet@v2
+ if: ${{ matrix.build-mono }}
+ with:
+ dotnet-version: '6.0.x'
+
- name: Compilation
uses: ./.github/actions/godot-build
with:
@@ -108,20 +116,15 @@ jobs:
tools: ${{ matrix.tools }}
tests: ${{ matrix.tests }}
- - name: Generate Mono glue
+ - name: Generate C# glue
if: ${{ matrix.build-mono }}
run: |
- ${{ matrix.bin }} --headless --generate-mono-glue modules/mono/glue || true
+ ${{ matrix.bin }} --headless --generate-mono-glue ./modules/mono/glue || true
- # Rebuild with mono
- - name: Compilation (mono_glue=yes)
- uses: ./.github/actions/godot-build
+ - name: Build .NET solutions
if: ${{ matrix.build-mono }}
- with:
- sconsflags: ${{ env.SCONSFLAGS }} ${{ matrix.sconsflags }} mono_glue=yes
- platform: linuxbsd
- target: ${{ matrix.target }}
- tools: ${{ matrix.tools }}
+ run: |
+ ./modules/mono/build_scripts/build_assemblies.py --godot-output-dir=./bin --godot-platform=linuxbsd
# Execute unit tests for the editor
- name: Unit tests
@@ -192,7 +195,7 @@ jobs:
# Checkout godot-cpp
- name: Checkout godot-cpp
if: ${{ matrix.godot-cpp-test }}
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
repository: godotengine/godot-cpp
submodules: 'recursive'
diff --git a/.github/workflows/macos_builds.yml b/.github/workflows/macos_builds.yml
index 0ad0995bb7..be1fb8de85 100644
--- a/.github/workflows/macos_builds.yml
+++ b/.github/workflows/macos_builds.yml
@@ -4,7 +4,7 @@ on: [push, pull_request]
# Global Settings
env:
# Only used for the cache key. Increment version to force clean build.
- GODOT_BASE_BRANCH: master-v3
+ GODOT_BASE_BRANCH: master
SCONSFLAGS: verbose=yes warnings=extra werror=yes module_text_server_fb_enabled=yes
concurrency:
@@ -24,7 +24,7 @@ jobs:
target: release_debug
tools: true
tests: true
- bin: "./bin/godot.macos.opt.tools.64"
+ bin: "./bin/godot.macos.opt.tools.x86_64"
- name: Template (target=release, tools=no)
cache-name: macos-template
@@ -34,7 +34,7 @@ jobs:
sconsflags: debug_symbols=no
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Setup Godot build cache
uses: ./.github/actions/godot-cache
diff --git a/.github/workflows/static_checks.yml b/.github/workflows/static_checks.yml
index 81c7042663..557b67c970 100644
--- a/.github/workflows/static_checks.yml
+++ b/.github/workflows/static_checks.yml
@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-20.04
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
# Azure repositories are not reliable, we need to prevent Azure giving us packages.
- name: Make apt sources.list use the default Ubuntu repositories
@@ -27,16 +27,12 @@ jobs:
sudo apt-get install -qq dos2unix recode clang-format-13 libxml2-utils
sudo update-alternatives --remove-all clang-format
sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-13 100
- sudo pip3 install black==22.3.0 pygments
+ sudo pip3 install black==22.3.0 pygments pytest
- name: File formatting checks (file_format.sh)
run: |
bash ./misc/scripts/file_format.sh
- - name: Style checks via clang-format (clang_format.sh)
- run: |
- bash ./misc/scripts/clang_format.sh
-
- name: Header guards formatting checks (header_guards.sh)
run: |
bash ./misc/scripts/header_guards.sh
@@ -45,6 +41,10 @@ jobs:
run: |
bash ./misc/scripts/black_format.sh
+ - name: Python builders checks via pytest (pytest_builders.sh)
+ run: |
+ bash ./misc/scripts/pytest_builders.sh
+
- name: JavaScript style and documentation checks via ESLint and JSDoc
run: |
cd platform/javascript
@@ -59,3 +59,7 @@ jobs:
- name: Documentation checks
run: |
doc/tools/make_rst.py --dry-run --color doc/classes modules
+
+ - name: Style checks via clang-format (clang_format.sh)
+ run: |
+ bash ./misc/scripts/clang_format.sh
diff --git a/.github/workflows/windows_builds.yml b/.github/workflows/windows_builds.yml
index e04d49adde..9033e1ab1d 100644
--- a/.github/workflows/windows_builds.yml
+++ b/.github/workflows/windows_builds.yml
@@ -5,7 +5,7 @@ on: [push, pull_request]
# SCONS_CACHE for windows must be set in the build environment
env:
# Only used for the cache key. Increment version to force clean build.
- GODOT_BASE_BRANCH: master-v2
+ GODOT_BASE_BRANCH: master
SCONSFLAGS: verbose=yes warnings=all werror=yes module_text_server_fb_enabled=yes
SCONS_CACHE_MSVC_CONFIG: true
@@ -29,7 +29,7 @@ jobs:
tests: true
# Skip debug symbols, they're way too big with MSVC.
sconsflags: debug_symbols=no
- bin: "./bin/godot.windows.opt.tools.64.exe"
+ bin: "./bin/godot.windows.opt.tools.x86_64.exe"
- name: Template (target=release, tools=no)
cache-name: windows-template
@@ -39,7 +39,7 @@ jobs:
sconsflags: debug_symbols=no
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Setup Godot build cache
uses: ./.github/actions/godot-cache
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 49355d2782..a1e8d3a59d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -37,7 +37,7 @@ Godot runs on a large variety of platforms and operating systems and devices.
For bugs that are likely OS-specific and/or graphics-related, please also specify:
-- Device (CPU model including architecture, e.g. x86, x86_64, ARM, etc.)
+- Device (CPU model including architecture, e.g. x86_64, arm64, etc.)
- GPU model (and the driver version in use if you know it)
**Bug reports not including the required information may be closed at the
@@ -74,10 +74,10 @@ if your ZIP file isn't accepted by GitHub because it's too large.
We recommend always attaching a minimal reproduction project, even if the issue
may seem simple to reproduce manually.
-**Note for C# users:** If your issue is not Mono-specific, please upload a
-minimal reproduction project written in GDScript or VisualScript.
+**Note for C# users:** If your issue is not .NET-specific, please upload a
+minimal reproduction project written in GDScript.
This will make it easier for contributors to reproduce the issue
-locally as not everyone has a Mono setup available.
+locally as not everyone has a .NET setup available.
**If you've been asked by a maintainer to upload a minimal reproduction project,
you *must* do so within 7 days.** Otherwise, your bug report will be closed as
diff --git a/SConstruct b/SConstruct
index d0d03bd8dc..55ed3771ac 100644
--- a/SConstruct
+++ b/SConstruct
@@ -55,6 +55,7 @@ _helper_module("modules.modules_builders", "modules/modules_builders.py")
import methods
import glsl_builders
import gles3_builders
+from platform_methods import architectures, architecture_aliases
if methods.get_cmdline_bool("tools", True):
_helper_module("editor.editor_builders", "editor/editor_builders.py")
@@ -161,12 +162,11 @@ if profile:
opts = Variables(customs, ARGUMENTS)
# Target build options
-opts.Add("p", "Platform (alias for 'platform')", "")
opts.Add("platform", "Target platform (%s)" % ("|".join(platform_list),), "")
+opts.Add("p", "Platform (alias for 'platform')", "")
opts.Add(BoolVariable("tools", "Build the tools (a.k.a. the Godot editor)", True))
opts.Add(EnumVariable("target", "Compilation target", "debug", ("debug", "release_debug", "release")))
-opts.Add("arch", "Platform-dependent architecture (arm/arm64/x86/x64/mips/...)", "")
-opts.Add(EnumVariable("bits", "Target platform bits", "default", ("default", "32", "64")))
+opts.Add(EnumVariable("arch", "CPU architecture", "auto", ["auto"] + architectures, architecture_aliases))
opts.Add(EnumVariable("float", "Floating-point precision", "default", ("default", "32", "64")))
opts.Add(EnumVariable("optimize", "Optimization type", "speed", ("speed", "size", "none")))
opts.Add(BoolVariable("production", "Set defaults to build Godot for use in production", False))
@@ -502,12 +502,17 @@ if selected_platform in platform_list:
# Platform specific flags
flag_list = platform_flags[selected_platform]
for f in flag_list:
- if not (f[0] in ARGUMENTS): # allow command line to override platform flags
+ if not (f[0] in ARGUMENTS) or ARGUMENTS[f[0]] == "auto": # Allow command line to override platform flags
env[f[0]] = f[1]
# Must happen after the flags' definition, so that they can be used by platform detect
detect.configure(env)
+ print(
+ 'Building for platform "%s", architecture "%s", %s, target "%s".'
+ % (selected_platform, env["arch"], "editor" if env["tools"] else "template", env["target"])
+ )
+
# Set our C and C++ standard requirements.
# C++17 is required as we need guaranteed copy elision as per GH-36436.
# Prepending to make it possible to override.
@@ -693,13 +698,7 @@ if selected_platform in platform_list:
)
suffix += ".debug"
- if env["arch"] != "":
- suffix += "." + env["arch"]
- elif env["bits"] == "32":
- suffix += ".32"
- elif env["bits"] == "64":
- suffix += ".64"
-
+ suffix += "." + env["arch"]
suffix += env.extra_suffix
sys.path.remove(tmppath)
diff --git a/core/config/engine.cpp b/core/config/engine.cpp
index e1da9eb44e..3efc0e822a 100644
--- a/core/config/engine.cpp
+++ b/core/config/engine.cpp
@@ -33,7 +33,10 @@
#include "core/authors.gen.h"
#include "core/config/project_settings.h"
#include "core/donors.gen.h"
+#include "core/io/json.h"
#include "core/license.gen.h"
+#include "core/os/os.h"
+#include "core/variant/typed_array.h"
#include "core/version.h"
void Engine::set_physics_ticks_per_second(int p_ips) {
@@ -134,8 +137,8 @@ Dictionary Engine::get_author_info() const {
return dict;
}
-Array Engine::get_copyright_info() const {
- Array components;
+TypedArray<Dictionary> Engine::get_copyright_info() const {
+ TypedArray<Dictionary> components;
for (int component_index = 0; component_index < COPYRIGHT_INFO_COUNT; component_index++) {
const ComponentCopyright &cp_info = COPYRIGHT_INFO[component_index];
Dictionary component_dict;
@@ -307,6 +310,43 @@ Engine::Engine() {
singleton = this;
}
+void Engine::startup_begin() {
+ startup_benchmark_total_from = OS::get_singleton()->get_ticks_usec();
+}
+
+void Engine::startup_benchmark_begin_measure(const String &p_what) {
+ startup_benchmark_section = p_what;
+ startup_benchmark_from = OS::get_singleton()->get_ticks_usec();
+}
+void Engine::startup_benchmark_end_measure() {
+ uint64_t total = OS::get_singleton()->get_ticks_usec() - startup_benchmark_from;
+ double total_f = double(total) / double(1000000);
+
+ startup_benchmark_json[startup_benchmark_section] = total_f;
+}
+
+void Engine::startup_dump(const String &p_to_file) {
+ uint64_t total = OS::get_singleton()->get_ticks_usec() - startup_benchmark_total_from;
+ double total_f = double(total) / double(1000000);
+ startup_benchmark_json["total_time"] = total_f;
+
+ if (!p_to_file.is_empty()) {
+ Ref<FileAccess> f = FileAccess::open(p_to_file, FileAccess::WRITE);
+ if (f.is_valid()) {
+ Ref<JSON> json;
+ json.instantiate();
+ f->store_string(json->stringify(startup_benchmark_json, "\t", false, true));
+ }
+ } else {
+ List<Variant> keys;
+ startup_benchmark_json.get_key_list(&keys);
+ print_line("STARTUP BENCHMARK:");
+ for (const Variant &K : keys) {
+ print_line("\t-", K, ": ", startup_benchmark_json[K], +" sec.");
+ }
+ }
+}
+
Engine::Singleton::Singleton(const StringName &p_name, Object *p_ptr, const StringName &p_class_name) :
name(p_name),
ptr(p_ptr),
diff --git a/core/config/engine.h b/core/config/engine.h
index 649be23717..121fd4d541 100644
--- a/core/config/engine.h
+++ b/core/config/engine.h
@@ -36,6 +36,9 @@
#include "core/templates/list.h"
#include "core/templates/vector.h"
+template <typename T>
+class TypedArray;
+
class Engine {
public:
struct Singleton {
@@ -79,6 +82,11 @@ private:
String write_movie_path;
String shader_cache_path;
+ Dictionary startup_benchmark_json;
+ String startup_benchmark_section;
+ uint64_t startup_benchmark_from = 0;
+ uint64_t startup_benchmark_total_from = 0;
+
public:
static Engine *get_singleton();
@@ -134,7 +142,7 @@ public:
Dictionary get_version_info() const;
Dictionary get_author_info() const;
- Array get_copyright_info() const;
+ TypedArray<Dictionary> get_copyright_info() const;
Dictionary get_donor_info() const;
Dictionary get_license_info() const;
String get_license_text() const;
@@ -151,6 +159,11 @@ public:
bool is_validation_layers_enabled() const;
int32_t get_gpu_index() const;
+ void startup_begin();
+ void startup_benchmark_begin_measure(const String &p_what);
+ void startup_benchmark_end_measure();
+ void startup_dump(const String &p_to_file);
+
Engine();
virtual ~Engine() {}
};
diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp
index 5c4bcc687a..26b683db82 100644
--- a/core/config/project_settings.cpp
+++ b/core/config/project_settings.cpp
@@ -1070,7 +1070,7 @@ bool ProjectSettings::is_using_datapack() const {
return using_datapack;
}
-bool ProjectSettings::property_can_revert(const String &p_name) {
+bool ProjectSettings::_property_can_revert(const StringName &p_name) const {
if (!props.has(p_name)) {
return false;
}
@@ -1078,12 +1078,13 @@ bool ProjectSettings::property_can_revert(const String &p_name) {
return props[p_name].initial != props[p_name].variant;
}
-Variant ProjectSettings::property_get_revert(const String &p_name) {
+bool ProjectSettings::_property_get_revert(const StringName &p_name, Variant &r_property) const {
if (!props.has(p_name)) {
- return Variant();
+ return false;
}
- return props[p_name].initial;
+ r_property = props[p_name].initial;
+ return true;
}
void ProjectSettings::set_setting(const String &p_setting, const Variant &p_value) {
@@ -1134,8 +1135,6 @@ void ProjectSettings::_bind_methods() {
ClassDB::bind_method(D_METHOD("globalize_path", "path"), &ProjectSettings::globalize_path);
ClassDB::bind_method(D_METHOD("save"), &ProjectSettings::save);
ClassDB::bind_method(D_METHOD("load_resource_pack", "pack", "replace_files", "offset"), &ProjectSettings::_load_resource_pack, DEFVAL(true), DEFVAL(0));
- ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &ProjectSettings::property_can_revert);
- ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &ProjectSettings::property_get_revert);
ClassDB::bind_method(D_METHOD("save_custom", "file"), &ProjectSettings::_save_custom_bnd);
}
@@ -1183,10 +1182,14 @@ ProjectSettings::ProjectSettings() {
GLOBAL_DEF("application/config/custom_user_dir_name", "");
GLOBAL_DEF("application/config/project_settings_override", "");
- GLOBAL_DEF_BASIC("display/window/size/viewport_width", 1024);
+ // The default window size is tuned to:
+ // - Have a 16:9 aspect ratio,
+ // - Have both dimensions divisible by 8 to better play along with video recording,
+ // - Be displayable correctly in windowed mode on a 1366×768 display (tested on Windows 10 with default settings).
+ GLOBAL_DEF_BASIC("display/window/size/viewport_width", 1152);
custom_prop_info["display/window/size/viewport_width"] = PropertyInfo(Variant::INT, "display/window/size/viewport_width", PROPERTY_HINT_RANGE, "0,7680,1,or_greater"); // 8K resolution
- GLOBAL_DEF_BASIC("display/window/size/viewport_height", 600);
+ GLOBAL_DEF_BASIC("display/window/size/viewport_height", 648);
custom_prop_info["display/window/size/viewport_height"] = PropertyInfo(Variant::INT, "display/window/size/viewport_height", PROPERTY_HINT_RANGE, "0,4320,1,or_greater"); // 8K resolution
GLOBAL_DEF_BASIC("display/window/size/resizable", true);
diff --git a/core/config/project_settings.h b/core/config/project_settings.h
index c3992a4db2..c845120a26 100644
--- a/core/config/project_settings.h
+++ b/core/config/project_settings.h
@@ -102,6 +102,8 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
+ bool _property_can_revert(const StringName &p_name) const;
+ bool _property_get_revert(const StringName &p_name, Variant &r_property) const;
static ProjectSettings *singleton;
@@ -147,9 +149,6 @@ public:
void set_ignore_value_in_docs(const String &p_name, bool p_ignore);
bool get_ignore_value_in_docs(const String &p_name) const;
- bool property_can_revert(const String &p_name);
- Variant property_get_revert(const String &p_name);
-
String get_project_data_dir_name() const;
String get_project_data_path() const;
String get_resource_path() const;
diff --git a/core/core_bind.cpp b/core/core_bind.cpp
index 630bd68e65..bcc87d78c4 100644
--- a/core/core_bind.cpp
+++ b/core/core_bind.cpp
@@ -39,6 +39,7 @@
#include "core/math/geometry_2d.h"
#include "core/math/geometry_3d.h"
#include "core/os/keyboard.h"
+#include "core/variant/typed_array.h"
namespace core_bind {
@@ -436,10 +437,6 @@ bool OS::is_stdout_verbose() const {
return ::OS::get_singleton()->is_stdout_verbose();
}
-void OS::dump_memory_to_file(const String &p_file) {
- ::OS::get_singleton()->dump_memory_to_file(p_file.utf8().get_data());
-}
-
struct OSCoreBindImg {
String path;
Size2 size;
@@ -666,7 +663,6 @@ void OS::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_debug_build"), &OS::is_debug_build);
- ClassDB::bind_method(D_METHOD("dump_memory_to_file", "file"), &OS::dump_memory_to_file);
ClassDB::bind_method(D_METHOD("dump_resources_to_file", "file"), &OS::dump_resources_to_file);
ClassDB::bind_method(D_METHOD("print_resources_in_use", "short"), &OS::print_resources_in_use, DEFVAL(false));
ClassDB::bind_method(D_METHOD("print_all_resources", "tofile"), &OS::print_all_resources, DEFVAL(""));
@@ -818,7 +814,7 @@ Vector<Point2> Geometry2D::convex_hull(const Vector<Point2> &p_points) {
return ::Geometry2D::convex_hull(p_points);
}
-Array Geometry2D::merge_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
+TypedArray<PackedVector2Array> Geometry2D::merge_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
Vector<Vector<Point2>> polys = ::Geometry2D::merge_polygons(p_polygon_a, p_polygon_b);
Array ret;
@@ -829,10 +825,10 @@ Array Geometry2D::merge_polygons(const Vector<Vector2> &p_polygon_a, const Vecto
return ret;
}
-Array Geometry2D::clip_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
+TypedArray<PackedVector2Array> Geometry2D::clip_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
Vector<Vector<Point2>> polys = ::Geometry2D::clip_polygons(p_polygon_a, p_polygon_b);
- Array ret;
+ TypedArray<PackedVector2Array> ret;
for (int i = 0; i < polys.size(); ++i) {
ret.push_back(polys[i]);
@@ -840,7 +836,7 @@ Array Geometry2D::clip_polygons(const Vector<Vector2> &p_polygon_a, const Vector
return ret;
}
-Array Geometry2D::intersect_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
+TypedArray<PackedVector2Array> Geometry2D::intersect_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
Vector<Vector<Point2>> polys = ::Geometry2D::intersect_polygons(p_polygon_a, p_polygon_b);
Array ret;
@@ -851,7 +847,7 @@ Array Geometry2D::intersect_polygons(const Vector<Vector2> &p_polygon_a, const V
return ret;
}
-Array Geometry2D::exclude_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
+TypedArray<PackedVector2Array> Geometry2D::exclude_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
Vector<Vector<Point2>> polys = ::Geometry2D::exclude_polygons(p_polygon_a, p_polygon_b);
Array ret;
@@ -862,7 +858,7 @@ Array Geometry2D::exclude_polygons(const Vector<Vector2> &p_polygon_a, const Vec
return ret;
}
-Array Geometry2D::clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
+TypedArray<PackedVector2Array> Geometry2D::clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
Vector<Vector<Point2>> polys = ::Geometry2D::clip_polyline_with_polygon(p_polyline, p_polygon);
Array ret;
@@ -873,7 +869,7 @@ Array Geometry2D::clip_polyline_with_polygon(const Vector<Vector2> &p_polyline,
return ret;
}
-Array Geometry2D::intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
+TypedArray<PackedVector2Array> Geometry2D::intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
Vector<Vector<Point2>> polys = ::Geometry2D::intersect_polyline_with_polygon(p_polyline, p_polygon);
Array ret;
@@ -884,7 +880,7 @@ Array Geometry2D::intersect_polyline_with_polygon(const Vector<Vector2> &p_polyl
return ret;
}
-Array Geometry2D::offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
+TypedArray<PackedVector2Array> Geometry2D::offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
Vector<Vector<Point2>> polys = ::Geometry2D::offset_polygon(p_polygon, p_delta, ::Geometry2D::PolyJoinType(p_join_type));
Array ret;
@@ -895,7 +891,7 @@ Array Geometry2D::offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delt
return ret;
}
-Array Geometry2D::offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
+TypedArray<PackedVector2Array> Geometry2D::offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
Vector<Vector<Point2>> polys = ::Geometry2D::offset_polyline(p_polygon, p_delta, ::Geometry2D::PolyJoinType(p_join_type), ::Geometry2D::PolyEndType(p_end_type));
Array ret;
@@ -988,16 +984,19 @@ Geometry3D *Geometry3D::get_singleton() {
return singleton;
}
-Vector<Plane> Geometry3D::build_box_planes(const Vector3 &p_extents) {
- return ::Geometry3D::build_box_planes(p_extents);
+TypedArray<Plane> Geometry3D::build_box_planes(const Vector3 &p_extents) {
+ Variant ret = ::Geometry3D::build_box_planes(p_extents);
+ return ret;
}
-Vector<Plane> Geometry3D::build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis) {
- return ::Geometry3D::build_cylinder_planes(p_radius, p_height, p_sides, p_axis);
+TypedArray<Plane> Geometry3D::build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis) {
+ Variant ret = ::Geometry3D::build_cylinder_planes(p_radius, p_height, p_sides, p_axis);
+ return ret;
}
-Vector<Plane> Geometry3D::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
- return ::Geometry3D::build_capsule_planes(p_radius, p_height, p_sides, p_lats, p_axis);
+TypedArray<Plane> Geometry3D::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
+ Variant ret = ::Geometry3D::build_capsule_planes(p_radius, p_height, p_sides, p_lats, p_axis);
+ return ret;
}
Vector<Vector3> Geometry3D::get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2) {
@@ -2022,10 +2021,10 @@ Dictionary ClassDB::get_signal(StringName p_class, StringName p_signal) const {
}
}
-Array ClassDB::get_signal_list(StringName p_class, bool p_no_inheritance) const {
+TypedArray<Dictionary> ClassDB::get_signal_list(StringName p_class, bool p_no_inheritance) const {
List<MethodInfo> signals;
::ClassDB::get_signal_list(p_class, &signals, p_no_inheritance);
- Array ret;
+ TypedArray<Dictionary> ret;
for (const MethodInfo &E : signals) {
ret.push_back(E.operator Dictionary());
@@ -2034,10 +2033,10 @@ Array ClassDB::get_signal_list(StringName p_class, bool p_no_inheritance) const
return ret;
}
-Array ClassDB::get_property_list(StringName p_class, bool p_no_inheritance) const {
+TypedArray<Dictionary> ClassDB::get_property_list(StringName p_class, bool p_no_inheritance) const {
List<PropertyInfo> plist;
::ClassDB::get_property_list(p_class, &plist, p_no_inheritance);
- Array ret;
+ TypedArray<Dictionary> ret;
for (const PropertyInfo &E : plist) {
ret.push_back(E.operator Dictionary());
}
@@ -2066,10 +2065,10 @@ bool ClassDB::has_method(StringName p_class, StringName p_method, bool p_no_inhe
return ::ClassDB::has_method(p_class, p_method, p_no_inheritance);
}
-Array ClassDB::get_method_list(StringName p_class, bool p_no_inheritance) const {
+TypedArray<Dictionary> ClassDB::get_method_list(StringName p_class, bool p_no_inheritance) const {
List<MethodInfo> methods;
::ClassDB::get_method_list(p_class, &methods, p_no_inheritance);
- Array ret;
+ TypedArray<Dictionary> ret;
for (const MethodInfo &E : methods) {
#ifdef DEBUG_METHODS_ENABLED
@@ -2254,7 +2253,7 @@ Dictionary Engine::get_author_info() const {
return ::Engine::get_singleton()->get_author_info();
}
-Array Engine::get_copyright_info() const {
+TypedArray<Dictionary> Engine::get_copyright_info() const {
return ::Engine::get_singleton()->get_copyright_info();
}
diff --git a/core/core_bind.h b/core/core_bind.h
index 79230bd685..642a0c00c7 100644
--- a/core/core_bind.h
+++ b/core/core_bind.h
@@ -45,6 +45,8 @@
#include "core/templates/safe_refcount.h"
class MainLoop;
+template <typename T>
+class TypedArray;
namespace core_bind {
@@ -199,7 +201,6 @@ public:
String get_model_name() const;
- void dump_memory_to_file(const String &p_file);
void dump_resources_to_file(const String &p_file);
void print_resources_in_use(bool p_short = false);
@@ -301,14 +302,14 @@ public:
OPERATION_XOR
};
// 2D polygon boolean operations.
- Array merge_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // Union (add).
- Array clip_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // Difference (subtract).
- Array intersect_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // Common area (multiply).
- Array exclude_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // All but common area (xor).
+ TypedArray<PackedVector2Array> merge_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // Union (add).
+ TypedArray<PackedVector2Array> clip_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // Difference (subtract).
+ TypedArray<PackedVector2Array> intersect_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // Common area (multiply).
+ TypedArray<PackedVector2Array> exclude_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b); // All but common area (xor).
// 2D polyline vs polygon operations.
- Array clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon); // Cut.
- Array intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon); // Chop.
+ TypedArray<PackedVector2Array> clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon); // Cut.
+ TypedArray<PackedVector2Array> intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon); // Chop.
// 2D offset polygons/polylines.
enum PolyJoinType {
@@ -323,8 +324,8 @@ public:
END_SQUARE,
END_ROUND
};
- Array offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type = JOIN_SQUARE);
- Array offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type = JOIN_SQUARE, PolyEndType p_end_type = END_SQUARE);
+ TypedArray<PackedVector2Array> offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type = JOIN_SQUARE);
+ TypedArray<PackedVector2Array> offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type = JOIN_SQUARE, PolyEndType p_end_type = END_SQUARE);
Dictionary make_atlas(const Vector<Size2> &p_rects);
@@ -341,9 +342,9 @@ protected:
public:
static Geometry3D *get_singleton();
- Vector<Plane> build_box_planes(const Vector3 &p_extents);
- Vector<Plane> build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z);
- Vector<Plane> build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z);
+ TypedArray<Plane> build_box_planes(const Vector3 &p_extents);
+ TypedArray<Plane> build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z);
+ TypedArray<Plane> build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z);
Vector<Vector3> get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2);
Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b);
Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b);
@@ -602,15 +603,15 @@ public:
bool has_signal(StringName p_class, StringName p_signal) const;
Dictionary get_signal(StringName p_class, StringName p_signal) const;
- Array get_signal_list(StringName p_class, bool p_no_inheritance = false) const;
+ TypedArray<Dictionary> get_signal_list(StringName p_class, bool p_no_inheritance = false) const;
- Array get_property_list(StringName p_class, bool p_no_inheritance = false) const;
+ TypedArray<Dictionary> get_property_list(StringName p_class, bool p_no_inheritance = false) const;
Variant get_property(Object *p_object, const StringName &p_property) const;
Error set_property(Object *p_object, const StringName &p_property, const Variant &p_value) const;
bool has_method(StringName p_class, StringName p_method, bool p_no_inheritance = false) const;
- Array get_method_list(StringName p_class, bool p_no_inheritance = false) const;
+ TypedArray<Dictionary> get_method_list(StringName p_class, bool p_no_inheritance = false) const;
PackedStringArray get_integer_constant_list(const StringName &p_class, bool p_no_inheritance = false) const;
bool has_integer_constant(const StringName &p_class, const StringName &p_name) const;
@@ -661,7 +662,7 @@ public:
Dictionary get_version_info() const;
Dictionary get_author_info() const;
- Array get_copyright_info() const;
+ TypedArray<Dictionary> get_copyright_info() const;
Dictionary get_donor_info() const;
Dictionary get_license_info() const;
String get_license_text() const;
diff --git a/core/core_constants.cpp b/core/core_constants.cpp
index dc0ab72a86..299b60872d 100644
--- a/core/core_constants.cpp
+++ b/core/core_constants.cpp
@@ -612,6 +612,7 @@ void register_global_constants() {
BIND_CORE_ENUM_CONSTANT(PROPERTY_HINT_LOCALE_ID);
BIND_CORE_ENUM_CONSTANT(PROPERTY_HINT_LOCALIZABLE_STRING);
BIND_CORE_ENUM_CONSTANT(PROPERTY_HINT_NODE_TYPE);
+ BIND_CORE_ENUM_CONSTANT(PROPERTY_HINT_HIDE_QUATERNION_EDIT);
BIND_CORE_ENUM_CONSTANT(PROPERTY_HINT_MAX);
BIND_CORE_ENUM_CONSTANT(PROPERTY_USAGE_NONE);
diff --git a/core/extension/extension_api_dump.cpp b/core/extension/extension_api_dump.cpp
index 867b1fc637..5cf951a93c 100644
--- a/core/extension/extension_api_dump.cpp
+++ b/core/extension/extension_api_dump.cpp
@@ -52,6 +52,9 @@ static String get_type_name(const PropertyInfo &p_info) {
if (p_info.type == Variant::INT && (p_info.usage & (PROPERTY_USAGE_CLASS_IS_BITFIELD))) {
return String("bitfield::") + String(p_info.class_name);
}
+ if (p_info.type == Variant::INT && (p_info.usage & PROPERTY_USAGE_ARRAY)) {
+ return "int";
+ }
if (p_info.class_name != StringName()) {
return p_info.class_name;
}
@@ -88,6 +91,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
}
const uint32_t vec3_elems = 3;
+ const uint32_t vec4_elems = 4;
const uint32_t ptrsize_32 = 4;
const uint32_t ptrsize_64 = 8;
static const char *build_config_name[4] = { "float_32", "float_64", "double_32", "double_64" };
@@ -138,7 +142,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
{ Variant::AABB, (vec3_elems * 2) * sizeof(float), (vec3_elems * 2) * sizeof(float), (vec3_elems * 2) * sizeof(double), (vec3_elems * 2) * sizeof(double) },
{ Variant::BASIS, (vec3_elems * 3) * sizeof(float), (vec3_elems * 3) * sizeof(float), (vec3_elems * 3) * sizeof(double), (vec3_elems * 3) * sizeof(double) },
{ Variant::TRANSFORM3D, (vec3_elems * 4) * sizeof(float), (vec3_elems * 4) * sizeof(float), (vec3_elems * 4) * sizeof(double), (vec3_elems * 4) * sizeof(double) },
- { Variant::PROJECTION, 4 * 4 * sizeof(float), 4 * 4 * sizeof(float), 4 * 4 * sizeof(double), 4 * 4 * sizeof(double) },
+ { Variant::PROJECTION, (vec4_elems * 4) * sizeof(float), (vec4_elems * 4) * sizeof(float), (vec4_elems * 4) * sizeof(double), (vec4_elems * 4) * sizeof(double) },
{ Variant::COLOR, 4 * sizeof(float), 4 * sizeof(float), 4 * sizeof(float), 4 * sizeof(float) },
{ Variant::STRING_NAME, ptrsize_32, ptrsize_64, ptrsize_32, ptrsize_64 },
{ Variant::NODE_PATH, ptrsize_32, ptrsize_64, ptrsize_32, ptrsize_64 },
@@ -284,6 +288,10 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
{ Variant::BASIS, "z", vec3_elems * 2 * sizeof(float), vec3_elems * 2 * sizeof(float), vec3_elems * 2 * sizeof(double), vec3_elems * 2 * sizeof(double) },
{ Variant::TRANSFORM3D, "basis", 0, 0, 0, 0 },
{ Variant::TRANSFORM3D, "origin", (vec3_elems * 3) * sizeof(float), (vec3_elems * 3) * sizeof(float), (vec3_elems * 3) * sizeof(double), (vec3_elems * 3) * sizeof(double) },
+ { Variant::PROJECTION, "x", 0, 0, 0, 0 },
+ { Variant::PROJECTION, "y", vec4_elems * sizeof(float), vec4_elems * sizeof(float), vec4_elems * sizeof(double), vec4_elems * sizeof(double) },
+ { Variant::PROJECTION, "z", vec4_elems * 2 * sizeof(float), vec4_elems * 2 * sizeof(float), vec4_elems * 2 * sizeof(double), vec4_elems * 2 * sizeof(double) },
+ { Variant::PROJECTION, "w", vec4_elems * 3 * sizeof(float), vec4_elems * 3 * sizeof(float), vec4_elems * 3 * sizeof(double), vec4_elems * 3 * sizeof(double) },
{ Variant::COLOR, "r", 0, 0, 0, 0 },
{ Variant::COLOR, "g", sizeof(float), sizeof(float), sizeof(float), sizeof(float) },
{ Variant::COLOR, "b", 2 * sizeof(float), 2 * sizeof(float), 2 * sizeof(float), 2 * sizeof(float) },
@@ -840,12 +848,16 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
List<PropertyInfo> property_list;
ClassDB::get_property_list(class_name, &property_list, true);
for (const PropertyInfo &F : property_list) {
- if (F.usage & PROPERTY_USAGE_CATEGORY || F.usage & PROPERTY_USAGE_GROUP || F.usage & PROPERTY_USAGE_SUBGROUP) {
+ if (F.usage & PROPERTY_USAGE_CATEGORY || F.usage & PROPERTY_USAGE_GROUP || F.usage & PROPERTY_USAGE_SUBGROUP || (F.type == Variant::NIL && F.usage & PROPERTY_USAGE_ARRAY)) {
continue; //not real properties
}
if (F.name.begins_with("_")) {
continue; //hidden property
}
+ if (F.name.find("/") >= 0) {
+ // Ignore properties with '/' (slash) in the name. These are only meant for use in the inspector.
+ continue;
+ }
StringName property_name = F.name;
Dictionary d2;
d2["type"] = get_type_name(F);
diff --git a/core/extension/gdnative_interface.h b/core/extension/gdnative_interface.h
index 041a6e5112..cb2adcb562 100644
--- a/core/extension/gdnative_interface.h
+++ b/core/extension/gdnative_interface.h
@@ -222,6 +222,8 @@ typedef struct {
typedef const GDNativePropertyInfo *(*GDNativeExtensionClassGetPropertyList)(GDExtensionClassInstancePtr p_instance, uint32_t *r_count);
typedef void (*GDNativeExtensionClassFreePropertyList)(GDExtensionClassInstancePtr p_instance, const GDNativePropertyInfo *p_list);
+typedef GDNativeBool (*GDNativeExtensionClassPropertyCanRevert)(GDExtensionClassInstancePtr p_instance, const GDNativeStringNamePtr p_name);
+typedef GDNativeBool (*GDNativeExtensionClassPropertyGetRevert)(GDExtensionClassInstancePtr p_instance, const GDNativeStringNamePtr p_name, GDNativeVariantPtr r_ret);
typedef void (*GDNativeExtensionClassNotification)(GDExtensionClassInstancePtr p_instance, int32_t p_what);
typedef void (*GDNativeExtensionClassToString)(GDExtensionClassInstancePtr p_instance, GDNativeStringPtr p_out);
typedef void (*GDNativeExtensionClassReference)(GDExtensionClassInstancePtr p_instance);
@@ -237,6 +239,8 @@ typedef struct {
GDNativeExtensionClassGet get_func;
GDNativeExtensionClassGetPropertyList get_property_list_func;
GDNativeExtensionClassFreePropertyList free_property_list_func;
+ GDNativeExtensionClassPropertyCanRevert property_can_revert_func;
+ GDNativeExtensionClassPropertyGetRevert property_get_revert_func;
GDNativeExtensionClassNotification notification_func;
GDNativeExtensionClassToString to_string_func;
GDNativeExtensionClassReference reference_func;
@@ -309,6 +313,9 @@ typedef const GDNativePropertyInfo *(*GDNativeExtensionScriptInstanceGetProperty
typedef void (*GDNativeExtensionScriptInstanceFreePropertyList)(GDNativeExtensionScriptInstanceDataPtr p_instance, const GDNativePropertyInfo *p_list);
typedef GDNativeVariantType (*GDNativeExtensionScriptInstanceGetPropertyType)(GDNativeExtensionScriptInstanceDataPtr p_instance, const GDNativeStringNamePtr p_name, GDNativeBool *r_is_valid);
+typedef GDNativeBool (*GDNativeExtensionScriptInstancePropertyCanRevert)(GDNativeExtensionScriptInstanceDataPtr p_instance, const GDNativeStringNamePtr p_name);
+typedef GDNativeBool (*GDNativeExtensionScriptInstancePropertyGetRevert)(GDNativeExtensionScriptInstanceDataPtr p_instance, const GDNativeStringNamePtr p_name, GDNativeVariantPtr r_ret);
+
typedef GDNativeObjectPtr (*GDNativeExtensionScriptInstanceGetOwner)(GDNativeExtensionScriptInstanceDataPtr p_instance);
typedef void (*GDNativeExtensionScriptInstancePropertyStateAdd)(const GDNativeStringNamePtr p_name, const GDNativeVariantPtr p_value, void *p_userdata);
typedef void (*GDNativeExtensionScriptInstanceGetPropertyState)(GDNativeExtensionScriptInstanceDataPtr p_instance, GDNativeExtensionScriptInstancePropertyStateAdd p_add_func, void *p_userdata);
@@ -343,6 +350,9 @@ typedef struct {
GDNativeExtensionScriptInstanceFreePropertyList free_property_list_func;
GDNativeExtensionScriptInstanceGetPropertyType get_property_type_func;
+ GDNativeExtensionScriptInstancePropertyCanRevert property_can_revert_func;
+ GDNativeExtensionScriptInstancePropertyGetRevert property_get_revert_func;
+
GDNativeExtensionScriptInstanceGetOwner get_owner_func;
GDNativeExtensionScriptInstanceGetPropertyState get_property_state_func;
diff --git a/core/extension/native_extension.cpp b/core/extension/native_extension.cpp
index a085df874e..fdb4e50d90 100644
--- a/core/extension/native_extension.cpp
+++ b/core/extension/native_extension.cpp
@@ -156,6 +156,8 @@ void NativeExtension::_register_extension_class(const GDNativeExtensionClassLibr
extension->native_extension.get = p_extension_funcs->get_func;
extension->native_extension.get_property_list = p_extension_funcs->get_property_list_func;
extension->native_extension.free_property_list = p_extension_funcs->free_property_list_func;
+ extension->native_extension.property_can_revert = p_extension_funcs->property_can_revert_func;
+ extension->native_extension.property_get_revert = p_extension_funcs->property_get_revert_func;
extension->native_extension.notification = p_extension_funcs->notification_func;
extension->native_extension.to_string = p_extension_funcs->to_string_func;
extension->native_extension.reference = p_extension_funcs->reference_func;
diff --git a/core/input/input.cpp b/core/input/input.cpp
index e08647f5ea..4e538a85ae 100644
--- a/core/input/input.cpp
+++ b/core/input/input.cpp
@@ -767,9 +767,6 @@ Point2i Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, con
return rel_warped;
}
-void Input::iteration(float p_step) {
-}
-
void Input::action_press(const StringName &p_action, float p_strength) {
Action action;
@@ -974,11 +971,9 @@ void Input::joy_axis(int p_device, JoyAxis p_axis, float p_value) {
if (map.type == TYPE_BUTTON) {
bool pressed = map.value > 0.5;
- if (pressed == joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
- // Button already pressed or released; so ignore.
- return;
+ if (pressed != joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
+ _button_event(p_device, (JoyButton)map.index, pressed);
}
- _button_event(p_device, (JoyButton)map.index, pressed);
// Ensure opposite D-Pad button is also released.
switch ((JoyButton)map.index) {
@@ -1129,7 +1124,7 @@ Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, J
value = -value;
}
if (binding.input.axis.range == FULL_AXIS ||
- (binding.input.axis.range == POSITIVE_HALF_AXIS && value > 0) ||
+ (binding.input.axis.range == POSITIVE_HALF_AXIS && value >= 0) ||
(binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
event.type = binding.outputType;
float shifted_positive_value = 0;
diff --git a/core/input/input.h b/core/input/input.h
index 3ad8c91ddf..a07174b887 100644
--- a/core/input/input.h
+++ b/core/input/input.h
@@ -114,6 +114,15 @@ private:
int mouse_from_touch_index = -1;
+ struct VibrationInfo {
+ float weak_magnitude;
+ float strong_magnitude;
+ float duration; // Duration in seconds
+ uint64_t timestamp;
+ };
+
+ HashMap<int, VibrationInfo> joy_vibration;
+
struct VelocityTrack {
uint64_t last_tick = 0;
Vector2 velocity;
@@ -226,15 +235,6 @@ private:
EventDispatchFunc event_dispatch_function = nullptr;
protected:
- struct VibrationInfo {
- float weak_magnitude;
- float strong_magnitude;
- float duration; // Duration in seconds
- uint64_t timestamp;
- };
-
- HashMap<int, VibrationInfo> joy_vibration;
-
static void _bind_methods();
public:
@@ -295,8 +295,6 @@ public:
void action_press(const StringName &p_action, float p_strength = 1.f);
void action_release(const StringName &p_action);
- void iteration(float p_step);
-
void set_emulate_touch_from_mouse(bool p_emulate);
bool is_emulating_touch_from_mouse() const;
void ensure_touch_mouse_raised();
diff --git a/core/input/input_event.cpp b/core/input/input_event.cpp
index 8ad2193fca..3f02d80c26 100644
--- a/core/input/input_event.cpp
+++ b/core/input/input_event.cpp
@@ -274,24 +274,24 @@ void InputEventWithModifiers::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "command_pressed"), "set_command_pressed", "is_command_pressed");
}
-void InputEventWithModifiers::_validate_property(PropertyInfo &property) const {
+void InputEventWithModifiers::_validate_property(PropertyInfo &p_property) const {
if (store_command) {
// If we only want to Store "Command".
#ifdef APPLE_STYLE_KEYS
// Don't store "Meta" on Mac.
- if (property.name == "meta_pressed") {
- property.usage ^= PROPERTY_USAGE_STORAGE;
+ if (p_property.name == "meta_pressed") {
+ p_property.usage ^= PROPERTY_USAGE_STORAGE;
}
#else
// Don't store "Ctrl".
- if (property.name == "ctrl_pressed") {
- property.usage ^= PROPERTY_USAGE_STORAGE;
+ if (p_property.name == "ctrl_pressed") {
+ p_property.usage ^= PROPERTY_USAGE_STORAGE;
}
#endif
} else {
// We don't want to store command, only ctrl or meta (on mac).
- if (property.name == "command_pressed") {
- property.usage ^= PROPERTY_USAGE_STORAGE;
+ if (p_property.name == "command_pressed") {
+ p_property.usage ^= PROPERTY_USAGE_STORAGE;
}
}
}
diff --git a/core/input/input_event.h b/core/input/input_event.h
index 59a2df497c..6cfc031c8a 100644
--- a/core/input/input_event.h
+++ b/core/input/input_event.h
@@ -128,7 +128,7 @@ class InputEventWithModifiers : public InputEventFromWindow {
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_store_command(bool p_enabled);
diff --git a/core/input/input_map.cpp b/core/input/input_map.cpp
index 942c5248df..702e257fb4 100644
--- a/core/input/input_map.cpp
+++ b/core/input/input_map.cpp
@@ -34,6 +34,7 @@
#include "core/input/input.h"
#include "core/os/keyboard.h"
#include "core/os/os.h"
+#include "core/variant/typed_array.h"
InputMap *InputMap::singleton = nullptr;
@@ -99,8 +100,8 @@ void InputMap::erase_action(const StringName &p_action) {
input_map.erase(p_action);
}
-Array InputMap::_get_actions() {
- Array ret;
+TypedArray<StringName> InputMap::_get_actions() {
+ TypedArray<StringName> ret;
List<StringName> actions = get_actions();
if (actions.is_empty()) {
return ret;
@@ -190,8 +191,8 @@ void InputMap::action_erase_events(const StringName &p_action) {
input_map[p_action].inputs.clear();
}
-Array InputMap::_action_get_events(const StringName &p_action) {
- Array ret;
+TypedArray<InputEvent> InputMap::_action_get_events(const StringName &p_action) {
+ TypedArray<InputEvent> ret;
const List<Ref<InputEvent>> *al = action_get_events(p_action);
if (al) {
for (const List<Ref<InputEvent>>::Element *E = al->front(); E; E = E->next()) {
diff --git a/core/input/input_map.h b/core/input/input_map.h
index 2400a4a3f7..414a06b2f1 100644
--- a/core/input/input_map.h
+++ b/core/input/input_map.h
@@ -36,6 +36,9 @@
#include "core/object/object.h"
#include "core/templates/hash_map.h"
+template <typename T>
+class TypedArray;
+
class InputMap : public Object {
GDCLASS(InputMap, Object);
@@ -60,8 +63,8 @@ private:
List<Ref<InputEvent>>::Element *_find_event(Action &p_action, const Ref<InputEvent> &p_event, bool p_exact_match = false, bool *r_pressed = nullptr, float *r_strength = nullptr, float *r_raw_strength = nullptr) const;
- Array _action_get_events(const StringName &p_action);
- Array _get_actions();
+ TypedArray<InputEvent> _action_get_events(const StringName &p_action);
+ TypedArray<StringName> _get_actions();
protected:
static void _bind_methods();
diff --git a/core/io/file_access.cpp b/core/io/file_access.cpp
index 8ed3d40c22..72c00bd678 100644
--- a/core/io/file_access.cpp
+++ b/core/io/file_access.cpp
@@ -115,6 +115,10 @@ FileAccess::CreateFunc FileAccess::get_create_func(AccessType p_access) {
return create_func[p_access];
}
+FileAccess::AccessType FileAccess::get_access_type() const {
+ return _access_type;
+}
+
String FileAccess::fix_path(const String &p_path) const {
//helper used by file accesses that use a single filesystem
diff --git a/core/io/file_access.h b/core/io/file_access.h
index 3386800686..fc0eb95d44 100644
--- a/core/io/file_access.h
+++ b/core/io/file_access.h
@@ -60,6 +60,7 @@ public:
virtual Error _set_unix_permissions(const String &p_file, uint32_t p_permissions) = 0;
protected:
+ AccessType get_access_type() const;
String fix_path(const String &p_path) const;
virtual Error _open(const String &p_path, int p_mode_flags) = 0; ///< open a file
virtual uint64_t _get_modified_time(const String &p_file) = 0;
diff --git a/core/io/image_loader.cpp b/core/io/image_loader.cpp
index 9cf7c9caba..d09697b951 100644
--- a/core/io/image_loader.cpp
+++ b/core/io/image_loader.cpp
@@ -44,7 +44,7 @@ bool ImageFormatLoader::recognize(const String &p_extension) const {
return false;
}
-Error ImageLoader::load_image(String p_file, Ref<Image> p_image, Ref<FileAccess> p_custom, bool p_force_linear, float p_scale) {
+Error ImageLoader::load_image(String p_file, Ref<Image> p_image, Ref<FileAccess> p_custom, uint32_t p_flags, float p_scale) {
ERR_FAIL_COND_V_MSG(p_image.is_null(), ERR_INVALID_PARAMETER, "It's not a reference to a valid Image object.");
Ref<FileAccess> f = p_custom;
@@ -60,7 +60,7 @@ Error ImageLoader::load_image(String p_file, Ref<Image> p_image, Ref<FileAccess>
if (!loader[i]->recognize(extension)) {
continue;
}
- Error err = loader[i]->load_image(p_image, f, p_force_linear, p_scale);
+ Error err = loader[i]->load_image(p_image, f, p_flags, p_scale);
if (err != OK) {
ERR_PRINT("Error loading image: " + p_file);
}
@@ -152,7 +152,7 @@ Ref<Resource> ResourceFormatLoaderImage::load(const String &p_path, const String
Ref<Image> image;
image.instantiate();
- Error err = ImageLoader::loader[idx]->load_image(image, f, false, 1.0);
+ Error err = ImageLoader::loader[idx]->load_image(image, f);
if (err != OK) {
if (r_error) {
diff --git a/core/io/image_loader.h b/core/io/image_loader.h
index c91d382c25..cb64d2310e 100644
--- a/core/io/image_loader.h
+++ b/core/io/image_loader.h
@@ -44,11 +44,16 @@ class ImageFormatLoader {
friend class ResourceFormatLoaderImage;
protected:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) = 0;
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, uint32_t p_flags = (uint32_t)FLAG_NONE, float p_scale = 1.0) = 0;
virtual void get_recognized_extensions(List<String> *p_extensions) const = 0;
bool recognize(const String &p_extension) const;
public:
+ enum LoaderFlags {
+ FLAG_NONE = 0,
+ FLAG_FORCE_LINEAR = 1,
+ };
+
virtual ~ImageFormatLoader() {}
};
@@ -58,7 +63,7 @@ class ImageLoader {
protected:
public:
- static Error load_image(String p_file, Ref<Image> p_image, Ref<FileAccess> p_custom = Ref<FileAccess>(), bool p_force_linear = false, float p_scale = 1.0);
+ static Error load_image(String p_file, Ref<Image> p_image, Ref<FileAccess> p_custom = Ref<FileAccess>(), uint32_t p_flags = (uint32_t)ImageFormatLoader::FLAG_NONE, float p_scale = 1.0);
static void get_recognized_extensions(List<String> *p_extensions);
static ImageFormatLoader *recognize(const String &p_extension);
diff --git a/core/io/ip.cpp b/core/io/ip.cpp
index 25e3bef5fc..a4d8dc3d5b 100644
--- a/core/io/ip.cpp
+++ b/core/io/ip.cpp
@@ -33,6 +33,7 @@
#include "core/os/semaphore.h"
#include "core/os/thread.h"
#include "core/templates/hash_map.h"
+#include "core/variant/typed_array.h"
VARIANT_ENUM_CAST(IP::ResolverStatus);
@@ -124,11 +125,11 @@ struct _IP_ResolverPrivate {
};
IPAddress IP::resolve_hostname(const String &p_hostname, IP::Type p_type) {
- const Array addresses = resolve_hostname_addresses(p_hostname, p_type);
- return addresses.size() ? addresses[0].operator IPAddress() : IPAddress();
+ const PackedStringArray addresses = resolve_hostname_addresses(p_hostname, p_type);
+ return addresses.size() ? (IPAddress)addresses[0] : IPAddress();
}
-Array IP::resolve_hostname_addresses(const String &p_hostname, Type p_type) {
+PackedStringArray IP::resolve_hostname_addresses(const String &p_hostname, Type p_type) {
List<IPAddress> res;
String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type);
@@ -148,7 +149,7 @@ Array IP::resolve_hostname_addresses(const String &p_hostname, Type p_type) {
}
resolver->mutex.unlock();
- Array result;
+ PackedStringArray result;
for (int i = 0; i < res.size(); ++i) {
result.push_back(String(res[i]));
}
@@ -254,8 +255,8 @@ void IP::clear_cache(const String &p_hostname) {
}
}
-Array IP::_get_local_addresses() const {
- Array addresses;
+PackedStringArray IP::_get_local_addresses() const {
+ PackedStringArray addresses;
List<IPAddress> ip_addresses;
get_local_addresses(&ip_addresses);
for (const IPAddress &E : ip_addresses) {
@@ -265,8 +266,8 @@ Array IP::_get_local_addresses() const {
return addresses;
}
-Array IP::_get_local_interfaces() const {
- Array results;
+TypedArray<Dictionary> IP::_get_local_interfaces() const {
+ TypedArray<Dictionary> results;
HashMap<String, Interface_Info> interfaces;
get_local_interfaces(&interfaces);
for (KeyValue<String, Interface_Info> &E : interfaces) {
diff --git a/core/io/ip.h b/core/io/ip.h
index 4d83515e2b..f2d93a454d 100644
--- a/core/io/ip.h
+++ b/core/io/ip.h
@@ -34,6 +34,9 @@
#include "core/io/ip_address.h"
#include "core/os/os.h"
+template <typename T>
+class TypedArray;
+
struct _IP_ResolverPrivate;
class IP : public Object {
@@ -68,8 +71,8 @@ protected:
static IP *singleton;
static void _bind_methods();
- Array _get_local_addresses() const;
- Array _get_local_interfaces() const;
+ PackedStringArray _get_local_addresses() const;
+ TypedArray<Dictionary> _get_local_interfaces() const;
static IP *(*_create)();
@@ -82,7 +85,7 @@ public:
};
IPAddress resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY);
- Array resolve_hostname_addresses(const String &p_hostname, Type p_type = TYPE_ANY);
+ PackedStringArray resolve_hostname_addresses(const String &p_hostname, Type p_type = TYPE_ANY);
// async resolver hostname
ResolverID resolve_hostname_queue_item(const String &p_hostname, Type p_type = TYPE_ANY);
ResolverStatus get_resolve_item_status(ResolverID p_id) const;
diff --git a/core/io/json.cpp b/core/io/json.cpp
index 4c4d91f851..91500ff3d5 100644
--- a/core/io/json.cpp
+++ b/core/io/json.cpp
@@ -528,11 +528,6 @@ Error JSON::_parse_string(const String &p_json, Variant &r_ret, String &r_err_st
return err;
}
-String JSON::stringify(const Variant &p_var, const String &p_indent, bool p_sort_keys, bool p_full_precision) {
- HashSet<const void *> markers;
- return _stringify(p_var, p_indent, 0, p_sort_keys, markers, p_full_precision);
-}
-
Error JSON::parse(const String &p_json_string) {
Error err = _parse_string(p_json_string, data, err_str, err_line);
if (err == Error::OK) {
@@ -541,8 +536,24 @@ Error JSON::parse(const String &p_json_string) {
return err;
}
+String JSON::stringify(const Variant &p_var, const String &p_indent, bool p_sort_keys, bool p_full_precision) {
+ Ref<JSON> jason;
+ jason.instantiate();
+ HashSet<const void *> markers;
+ return jason->_stringify(p_var, p_indent, 0, p_sort_keys, markers, p_full_precision);
+}
+
+Variant JSON::parse_string(const String &p_json_string) {
+ Ref<JSON> jason;
+ jason.instantiate();
+ Error error = jason->parse(p_json_string);
+ ERR_FAIL_COND_V_MSG(error != Error::OK, Variant(), vformat("Parse JSON failed. Error at line %d: %s", jason->get_error_line(), jason->get_error_message()));
+ return jason->get_data();
+}
+
void JSON::_bind_methods() {
- ClassDB::bind_method(D_METHOD("stringify", "data", "indent", "sort_keys", "full_precision"), &JSON::stringify, DEFVAL(""), DEFVAL(true), DEFVAL(false));
+ ClassDB::bind_static_method("JSON", D_METHOD("stringify", "data", "indent", "sort_keys", "full_precision"), &JSON::stringify, DEFVAL(""), DEFVAL(true), DEFVAL(false));
+ ClassDB::bind_static_method("JSON", D_METHOD("parse_string", "json_string"), &JSON::parse_string);
ClassDB::bind_method(D_METHOD("parse", "json_string"), &JSON::parse);
ClassDB::bind_method(D_METHOD("get_data"), &JSON::get_data);
diff --git a/core/io/json.h b/core/io/json.h
index 6ba0a8c76b..840b1cc08a 100644
--- a/core/io/json.h
+++ b/core/io/json.h
@@ -81,8 +81,9 @@ protected:
static void _bind_methods();
public:
- String stringify(const Variant &p_var, const String &p_indent = "", bool p_sort_keys = true, bool p_full_precision = false);
Error parse(const String &p_json_string);
+ static String stringify(const Variant &p_var, const String &p_indent = "", bool p_sort_keys = true, bool p_full_precision = false);
+ static Variant parse_string(const String &p_json_string);
inline Variant get_data() const { return data; }
inline int get_error_line() const { return err_line; }
diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp
index 274316f058..386ccb78e9 100644
--- a/core/io/resource_saver.cpp
+++ b/core/io/resource_saver.cpp
@@ -70,7 +70,7 @@ void ResourceFormatSaver::get_recognized_extensions(const Ref<Resource> &p_resou
}
void ResourceFormatSaver::_bind_methods() {
- GDVIRTUAL_BIND(_save, "path", "resource", "flags");
+ GDVIRTUAL_BIND(_save, "resource", "path", "flags");
GDVIRTUAL_BIND(_recognize, "resource");
GDVIRTUAL_BIND(_get_recognized_extensions, "resource");
}
diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp
index 41a0848d01..b4281820e2 100644
--- a/core/math/a_star.cpp
+++ b/core/math/a_star.cpp
@@ -209,8 +209,8 @@ bool AStar3D::has_point(int64_t p_id) const {
return points.has(p_id);
}
-Array AStar3D::get_point_ids() {
- Array point_list;
+PackedInt64Array AStar3D::get_point_ids() {
+ PackedInt64Array point_list;
for (OAHashMap<int64_t, Point *>::Iterator it = points.iter(); it.valid; it = points.next_iter(it)) {
point_list.push_back(*(it.key));
@@ -605,7 +605,7 @@ Vector<int64_t> AStar2D::get_point_connections(int64_t p_id) {
return astar.get_point_connections(p_id);
}
-Array AStar2D::get_point_ids() {
+PackedInt64Array AStar2D::get_point_ids() {
return astar.get_point_ids();
}
diff --git a/core/math/a_star.h b/core/math/a_star.h
index c1497d133f..a9e2a62bb2 100644
--- a/core/math/a_star.h
+++ b/core/math/a_star.h
@@ -133,7 +133,7 @@ public:
void remove_point(int64_t p_id);
bool has_point(int64_t p_id) const;
Vector<int64_t> get_point_connections(int64_t p_id);
- Array get_point_ids();
+ PackedInt64Array get_point_ids();
void set_point_disabled(int64_t p_id, bool p_disabled = true);
bool is_point_disabled(int64_t p_id) const;
@@ -183,7 +183,7 @@ public:
void remove_point(int64_t p_id);
bool has_point(int64_t p_id) const;
Vector<int64_t> get_point_connections(int64_t p_id);
- Array get_point_ids();
+ PackedInt64Array get_point_ids();
void set_point_disabled(int64_t p_id, bool p_disabled = true);
bool is_point_disabled(int64_t p_id) const;
diff --git a/core/math/basis.cpp b/core/math/basis.cpp
index f8e7c47107..bc50d0e64c 100644
--- a/core/math/basis.cpp
+++ b/core/math/basis.cpp
@@ -749,67 +749,6 @@ Quaternion Basis::get_quaternion() const {
return Quaternion(temp[0], temp[1], temp[2], temp[3]);
}
-static const Basis _ortho_bases[24] = {
- Basis(1, 0, 0, 0, 1, 0, 0, 0, 1),
- Basis(0, -1, 0, 1, 0, 0, 0, 0, 1),
- Basis(-1, 0, 0, 0, -1, 0, 0, 0, 1),
- Basis(0, 1, 0, -1, 0, 0, 0, 0, 1),
- Basis(1, 0, 0, 0, 0, -1, 0, 1, 0),
- Basis(0, 0, 1, 1, 0, 0, 0, 1, 0),
- Basis(-1, 0, 0, 0, 0, 1, 0, 1, 0),
- Basis(0, 0, -1, -1, 0, 0, 0, 1, 0),
- Basis(1, 0, 0, 0, -1, 0, 0, 0, -1),
- Basis(0, 1, 0, 1, 0, 0, 0, 0, -1),
- Basis(-1, 0, 0, 0, 1, 0, 0, 0, -1),
- Basis(0, -1, 0, -1, 0, 0, 0, 0, -1),
- Basis(1, 0, 0, 0, 0, 1, 0, -1, 0),
- Basis(0, 0, -1, 1, 0, 0, 0, -1, 0),
- Basis(-1, 0, 0, 0, 0, -1, 0, -1, 0),
- Basis(0, 0, 1, -1, 0, 0, 0, -1, 0),
- Basis(0, 0, 1, 0, 1, 0, -1, 0, 0),
- Basis(0, -1, 0, 0, 0, 1, -1, 0, 0),
- Basis(0, 0, -1, 0, -1, 0, -1, 0, 0),
- Basis(0, 1, 0, 0, 0, -1, -1, 0, 0),
- Basis(0, 0, 1, 0, -1, 0, 1, 0, 0),
- Basis(0, 1, 0, 0, 0, 1, 1, 0, 0),
- Basis(0, 0, -1, 0, 1, 0, 1, 0, 0),
- Basis(0, -1, 0, 0, 0, -1, 1, 0, 0)
-};
-
-int Basis::get_orthogonal_index() const {
- //could be sped up if i come up with a way
- Basis orth = *this;
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- real_t v = orth[i][j];
- if (v > 0.5f) {
- v = 1.0f;
- } else if (v < -0.5f) {
- v = -1.0f;
- } else {
- v = 0;
- }
-
- orth[i][j] = v;
- }
- }
-
- for (int i = 0; i < 24; i++) {
- if (_ortho_bases[i] == orth) {
- return i;
- }
- }
-
- return 0;
-}
-
-void Basis::set_orthogonal_index(int p_index) {
- //there only exist 24 orthogonal bases in r3
- ERR_FAIL_INDEX(p_index, 24);
-
- *this = _ortho_bases[p_index];
-}
-
void Basis::get_axis_angle(Vector3 &r_axis, real_t &r_angle) const {
/* checking this is a bad idea, because obtaining from scaled transform is a valid use case
#ifdef MATH_CHECKS
diff --git a/core/math/basis.h b/core/math/basis.h
index 4be325cdd2..2853947ba7 100644
--- a/core/math/basis.h
+++ b/core/math/basis.h
@@ -149,9 +149,6 @@ struct _NO_DISCARD_ Basis {
_FORCE_INLINE_ void operator*=(const real_t p_val);
_FORCE_INLINE_ Basis operator*(const real_t p_val) const;
- int get_orthogonal_index() const;
- void set_orthogonal_index(int p_index);
-
bool is_orthogonal() const;
bool is_diagonal() const;
bool is_rotation() const;
diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h
index 53deb9bd42..463e119add 100644
--- a/core/math/math_funcs.h
+++ b/core/math/math_funcs.h
@@ -253,6 +253,29 @@ public:
(-p_pre + 3.0f * p_from - 3.0f * p_to + p_post) * (p_weight * p_weight * p_weight));
}
+ static _ALWAYS_INLINE_ double cubic_interpolate_in_time(double p_from, double p_to, double p_pre, double p_post, double p_weight,
+ double p_to_t, double p_pre_t, double p_post_t) {
+ /* Barry-Goldman method */
+ double t = Math::lerp(0.0, p_to_t, p_weight);
+ double a1 = Math::lerp(p_pre, p_from, p_pre_t == 0 ? 0.0 : (t - p_pre_t) / -p_pre_t);
+ double a2 = Math::lerp(p_from, p_to, p_to_t == 0 ? 0.5 : t / p_to_t);
+ double a3 = Math::lerp(p_to, p_post, p_post_t - p_to_t == 0 ? 1.0 : (t - p_to_t) / (p_post_t - p_to_t));
+ double b1 = Math::lerp(a1, a2, p_to_t - p_pre_t == 0 ? 0.0 : (t - p_pre_t) / (p_to_t - p_pre_t));
+ double b2 = Math::lerp(a2, a3, p_post_t == 0 ? 1.0 : t / p_post_t);
+ return Math::lerp(b1, b2, p_to_t == 0 ? 0.5 : t / p_to_t);
+ }
+ static _ALWAYS_INLINE_ float cubic_interpolate_in_time(float p_from, float p_to, float p_pre, float p_post, float p_weight,
+ float p_to_t, float p_pre_t, float p_post_t) {
+ /* Barry-Goldman method */
+ float t = Math::lerp(0.0f, p_to_t, p_weight);
+ float a1 = Math::lerp(p_pre, p_from, p_pre_t == 0 ? 0.0f : (t - p_pre_t) / -p_pre_t);
+ float a2 = Math::lerp(p_from, p_to, p_to_t == 0 ? 0.5f : t / p_to_t);
+ float a3 = Math::lerp(p_to, p_post, p_post_t - p_to_t == 0 ? 1.0f : (t - p_to_t) / (p_post_t - p_to_t));
+ float b1 = Math::lerp(a1, a2, p_to_t - p_pre_t == 0 ? 0.0f : (t - p_pre_t) / (p_to_t - p_pre_t));
+ float b2 = Math::lerp(a2, a3, p_post_t == 0 ? 1.0f : t / p_post_t);
+ return Math::lerp(b1, b2, p_to_t == 0 ? 0.5f : t / p_to_t);
+ }
+
static _ALWAYS_INLINE_ double bezier_interpolate(double p_start, double p_control_1, double p_control_2, double p_end, double p_t) {
/* Formula from Wikipedia article on Bezier curves. */
double omt = (1.0 - p_t);
diff --git a/core/math/quaternion.cpp b/core/math/quaternion.cpp
index c681c60694..c836a82e37 100644
--- a/core/math/quaternion.cpp
+++ b/core/math/quaternion.cpp
@@ -112,10 +112,11 @@ Quaternion Quaternion::exp() const {
Quaternion src = *this;
Vector3 src_v = Vector3(src.x, src.y, src.z);
real_t theta = src_v.length();
- if (theta < CMP_EPSILON) {
+ src_v = src_v.normalized();
+ if (theta < CMP_EPSILON || !src_v.is_normalized()) {
return Quaternion(0, 0, 0, 1);
}
- return Quaternion(src_v.normalized(), theta);
+ return Quaternion(src_v, theta);
}
Quaternion Quaternion::slerp(const Quaternion &p_to, const real_t &p_weight) const {
@@ -233,6 +234,57 @@ Quaternion Quaternion::spherical_cubic_interpolate(const Quaternion &p_b, const
return q1.slerp(q2, p_weight);
}
+Quaternion Quaternion::spherical_cubic_interpolate_in_time(const Quaternion &p_b, const Quaternion &p_pre_a, const Quaternion &p_post_b, const real_t &p_weight,
+ const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const {
+#ifdef MATH_CHECKS
+ ERR_FAIL_COND_V_MSG(!is_normalized(), Quaternion(), "The start quaternion must be normalized.");
+ ERR_FAIL_COND_V_MSG(!p_b.is_normalized(), Quaternion(), "The end quaternion must be normalized.");
+#endif
+ Quaternion from_q = *this;
+ Quaternion pre_q = p_pre_a;
+ Quaternion to_q = p_b;
+ Quaternion post_q = p_post_b;
+
+ // Align flip phases.
+ from_q = Basis(from_q).get_rotation_quaternion();
+ pre_q = Basis(pre_q).get_rotation_quaternion();
+ to_q = Basis(to_q).get_rotation_quaternion();
+ post_q = Basis(post_q).get_rotation_quaternion();
+
+ // Flip quaternions to shortest path if necessary.
+ bool flip1 = signbit(from_q.dot(pre_q));
+ pre_q = flip1 ? -pre_q : pre_q;
+ bool flip2 = signbit(from_q.dot(to_q));
+ to_q = flip2 ? -to_q : to_q;
+ bool flip3 = flip2 ? to_q.dot(post_q) <= 0 : signbit(to_q.dot(post_q));
+ post_q = flip3 ? -post_q : post_q;
+
+ // Calc by Expmap in from_q space.
+ Quaternion ln_from = Quaternion(0, 0, 0, 0);
+ Quaternion ln_to = (from_q.inverse() * to_q).log();
+ Quaternion ln_pre = (from_q.inverse() * pre_q).log();
+ Quaternion ln_post = (from_q.inverse() * post_q).log();
+ Quaternion ln = Quaternion(0, 0, 0, 0);
+ ln.x = Math::cubic_interpolate_in_time(ln_from.x, ln_to.x, ln_pre.x, ln_post.x, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ ln.y = Math::cubic_interpolate_in_time(ln_from.y, ln_to.y, ln_pre.y, ln_post.y, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ ln.z = Math::cubic_interpolate_in_time(ln_from.z, ln_to.z, ln_pre.z, ln_post.z, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ Quaternion q1 = from_q * ln.exp();
+
+ // Calc by Expmap in to_q space.
+ ln_from = (to_q.inverse() * from_q).log();
+ ln_to = Quaternion(0, 0, 0, 0);
+ ln_pre = (to_q.inverse() * pre_q).log();
+ ln_post = (to_q.inverse() * post_q).log();
+ ln = Quaternion(0, 0, 0, 0);
+ ln.x = Math::cubic_interpolate_in_time(ln_from.x, ln_to.x, ln_pre.x, ln_post.x, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ ln.y = Math::cubic_interpolate_in_time(ln_from.y, ln_to.y, ln_pre.y, ln_post.y, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ ln.z = Math::cubic_interpolate_in_time(ln_from.z, ln_to.z, ln_pre.z, ln_post.z, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ Quaternion q2 = to_q * ln.exp();
+
+ // To cancel error made by Expmap ambiguity, do blends.
+ return q1.slerp(q2, p_weight);
+}
+
Quaternion::operator String() const {
return "(" + String::num_real(x, false) + ", " + String::num_real(y, false) + ", " + String::num_real(z, false) + ", " + String::num_real(w, false) + ")";
}
diff --git a/core/math/quaternion.h b/core/math/quaternion.h
index cb54a6f540..43d7bffcfc 100644
--- a/core/math/quaternion.h
+++ b/core/math/quaternion.h
@@ -72,6 +72,7 @@ struct _NO_DISCARD_ Quaternion {
Quaternion slerp(const Quaternion &p_to, const real_t &p_weight) const;
Quaternion slerpni(const Quaternion &p_to, const real_t &p_weight) const;
Quaternion spherical_cubic_interpolate(const Quaternion &p_b, const Quaternion &p_pre_a, const Quaternion &p_post_b, const real_t &p_weight) const;
+ Quaternion spherical_cubic_interpolate_in_time(const Quaternion &p_b, const Quaternion &p_pre_a, const Quaternion &p_post_b, const real_t &p_weight, const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const;
Vector3 get_axis() const;
real_t get_angle() const;
diff --git a/core/math/vector2.h b/core/math/vector2.h
index 91d3d3a56b..caa6b226e7 100644
--- a/core/math/vector2.h
+++ b/core/math/vector2.h
@@ -114,6 +114,7 @@ struct _NO_DISCARD_ Vector2 {
_FORCE_INLINE_ Vector2 lerp(const Vector2 &p_to, const real_t p_weight) const;
_FORCE_INLINE_ Vector2 slerp(const Vector2 &p_to, const real_t p_weight) const;
_FORCE_INLINE_ Vector2 cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, const real_t p_weight) const;
+ _FORCE_INLINE_ Vector2 cubic_interpolate_in_time(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, const real_t p_weight, const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const;
_FORCE_INLINE_ Vector2 bezier_interpolate(const Vector2 &p_control_1, const Vector2 &p_control_2, const Vector2 &p_end, const real_t p_t) const;
Vector2 move_toward(const Vector2 &p_to, const real_t p_delta) const;
@@ -270,6 +271,13 @@ Vector2 Vector2::cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, c
return res;
}
+Vector2 Vector2::cubic_interpolate_in_time(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, const real_t p_weight, const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const {
+ Vector2 res = *this;
+ res.x = Math::cubic_interpolate_in_time(res.x, p_b.x, p_pre_a.x, p_post_b.x, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ res.y = Math::cubic_interpolate_in_time(res.y, p_b.y, p_pre_a.y, p_post_b.y, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ return res;
+}
+
Vector2 Vector2::bezier_interpolate(const Vector2 &p_control_1, const Vector2 &p_control_2, const Vector2 &p_end, const real_t p_t) const {
Vector2 res = *this;
diff --git a/core/math/vector3.cpp b/core/math/vector3.cpp
index d71d365053..fdbbb8cb5c 100644
--- a/core/math/vector3.cpp
+++ b/core/math/vector3.cpp
@@ -117,6 +117,22 @@ Vector3 Vector3::octahedron_decode(const Vector2 &p_oct) {
return n.normalized();
}
+Vector2 Vector3::octahedron_tangent_encode(const float sign) const {
+ Vector2 res = this->octahedron_encode();
+ res.y = res.y * 0.5f + 0.5f;
+ res.y = sign >= 0.0f ? res.y : 1 - res.y;
+ return res;
+}
+
+Vector3 Vector3::octahedron_tangent_decode(const Vector2 &p_oct, float *sign) {
+ Vector2 oct_compressed = p_oct;
+ oct_compressed.y = oct_compressed.y * 2 - 1;
+ *sign = oct_compressed.y >= 0.0f ? 1.0f : -1.0f;
+ oct_compressed.y = Math::abs(oct_compressed.y);
+ Vector3 res = Vector3::octahedron_decode(oct_compressed);
+ return res;
+}
+
Basis Vector3::outer(const Vector3 &p_with) const {
Vector3 row0(x * p_with.x, x * p_with.y, x * p_with.z);
Vector3 row1(y * p_with.x, y * p_with.y, y * p_with.z);
diff --git a/core/math/vector3.h b/core/math/vector3.h
index 4ce01da60e..7cae6e2481 100644
--- a/core/math/vector3.h
+++ b/core/math/vector3.h
@@ -105,12 +105,15 @@ struct _NO_DISCARD_ Vector3 {
_FORCE_INLINE_ Vector3 lerp(const Vector3 &p_to, const real_t p_weight) const;
_FORCE_INLINE_ Vector3 slerp(const Vector3 &p_to, const real_t p_weight) const;
_FORCE_INLINE_ Vector3 cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, const real_t p_weight) const;
+ _FORCE_INLINE_ Vector3 cubic_interpolate_in_time(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, const real_t p_weight, const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const;
_FORCE_INLINE_ Vector3 bezier_interpolate(const Vector3 &p_control_1, const Vector3 &p_control_2, const Vector3 &p_end, const real_t p_t) const;
Vector3 move_toward(const Vector3 &p_to, const real_t p_delta) const;
Vector2 octahedron_encode() const;
static Vector3 octahedron_decode(const Vector2 &p_oct);
+ Vector2 octahedron_tangent_encode(const float sign) const;
+ static Vector3 octahedron_tangent_decode(const Vector2 &p_oct, float *sign);
_FORCE_INLINE_ Vector3 cross(const Vector3 &p_with) const;
_FORCE_INLINE_ real_t dot(const Vector3 &p_with) const;
@@ -246,6 +249,14 @@ Vector3 Vector3::cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, c
return res;
}
+Vector3 Vector3::cubic_interpolate_in_time(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, const real_t p_weight, const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const {
+ Vector3 res = *this;
+ res.x = Math::cubic_interpolate_in_time(res.x, p_b.x, p_pre_a.x, p_post_b.x, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ res.y = Math::cubic_interpolate_in_time(res.y, p_b.y, p_pre_a.y, p_post_b.y, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ res.z = Math::cubic_interpolate_in_time(res.z, p_b.z, p_pre_a.z, p_post_b.z, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ return res;
+}
+
Vector3 Vector3::bezier_interpolate(const Vector3 &p_control_1, const Vector3 &p_control_2, const Vector3 &p_end, const real_t p_t) const {
Vector3 res = *this;
diff --git a/core/math/vector4.cpp b/core/math/vector4.cpp
index 1dd5adad2b..273a111891 100644
--- a/core/math/vector4.cpp
+++ b/core/math/vector4.cpp
@@ -138,6 +138,15 @@ Vector4 Vector4::cubic_interpolate(const Vector4 &p_b, const Vector4 &p_pre_a, c
return res;
}
+Vector4 Vector4::cubic_interpolate_in_time(const Vector4 &p_b, const Vector4 &p_pre_a, const Vector4 &p_post_b, const real_t p_weight, const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const {
+ Vector4 res = *this;
+ res.x = Math::cubic_interpolate_in_time(res.x, p_b.x, p_pre_a.x, p_post_b.x, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ res.y = Math::cubic_interpolate_in_time(res.y, p_b.y, p_pre_a.y, p_post_b.y, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ res.z = Math::cubic_interpolate_in_time(res.z, p_b.z, p_pre_a.z, p_post_b.z, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ res.w = Math::cubic_interpolate_in_time(res.w, p_b.w, p_pre_a.w, p_post_b.w, p_weight, p_b_t, p_pre_a_t, p_post_b_t);
+ return res;
+}
+
Vector4 Vector4::posmod(const real_t p_mod) const {
return Vector4(Math::fposmod(x, p_mod), Math::fposmod(y, p_mod), Math::fposmod(z, p_mod), Math::fposmod(w, p_mod));
}
diff --git a/core/math/vector4.h b/core/math/vector4.h
index d26fe15941..17d0de18e1 100644
--- a/core/math/vector4.h
+++ b/core/math/vector4.h
@@ -89,6 +89,7 @@ struct _NO_DISCARD_ Vector4 {
Vector4 round() const;
Vector4 lerp(const Vector4 &p_to, const real_t p_weight) const;
Vector4 cubic_interpolate(const Vector4 &p_b, const Vector4 &p_pre_a, const Vector4 &p_post_b, const real_t p_weight) const;
+ Vector4 cubic_interpolate_in_time(const Vector4 &p_b, const Vector4 &p_pre_a, const Vector4 &p_post_b, const real_t p_weight, const real_t &p_b_t, const real_t &p_pre_a_t, const real_t &p_post_b_t) const;
Vector4 posmod(const real_t p_mod) const;
Vector4 posmodv(const Vector4 &p_modv) const;
diff --git a/core/object/class_db.cpp b/core/object/class_db.cpp
index 9790cc44e3..99b20560da 100644
--- a/core/object/class_db.cpp
+++ b/core/object/class_db.cpp
@@ -981,7 +981,7 @@ void ClassDB::get_property_list(const StringName &p_class, List<PropertyInfo> *p
if (p_validator) {
// Making a copy as we may modify it.
PropertyInfo pi_mut = pi;
- p_validator->_validate_property(pi_mut);
+ p_validator->validate_property(pi_mut);
p_list->push_back(pi_mut);
} else {
p_list->push_back(pi);
@@ -1022,7 +1022,7 @@ bool ClassDB::get_property_info(const StringName &p_class, const StringName &p_p
if (check->property_map.has(p_property)) {
PropertyInfo pinfo = check->property_map[p_property];
if (p_validator) {
- p_validator->_validate_property(pinfo);
+ p_validator->validate_property(pinfo);
}
if (r_info) {
*r_info = pinfo;
diff --git a/core/object/object.cpp b/core/object/object.cpp
index 0fcd1c0e40..4f7f55c8b6 100644
--- a/core/object/object.cpp
+++ b/core/object/object.cpp
@@ -38,6 +38,7 @@
#include "core/os/os.h"
#include "core/string/print_string.h"
#include "core/string/translation.h"
+#include "core/variant/typed_array.h"
#ifdef DEBUG_ENABLED
@@ -102,8 +103,8 @@ PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) {
return pi;
}
-Array convert_property_list(const List<PropertyInfo> *p_list) {
- Array va;
+TypedArray<Dictionary> convert_property_list(const List<PropertyInfo> *p_list) {
+ TypedArray<Dictionary> va;
for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) {
va.push_back(Dictionary(E->get()));
}
@@ -515,7 +516,61 @@ void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) cons
}
}
-void Object::_validate_property(PropertyInfo &property) const {
+void Object::validate_property(PropertyInfo &p_property) const {
+ _validate_propertyv(p_property);
+}
+
+bool Object::property_can_revert(const StringName &p_name) const {
+ if (script_instance) {
+ if (script_instance->property_can_revert(p_name)) {
+ return true;
+ }
+ }
+
+// C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wignored-qualifiers"
+#endif
+ if (_extension && _extension->property_can_revert) {
+ if (_extension->property_can_revert(_extension_instance, (const GDNativeStringNamePtr)&p_name)) {
+ return true;
+ }
+ }
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic pop
+#endif
+
+ return _property_can_revertv(p_name);
+}
+
+Variant Object::property_get_revert(const StringName &p_name) const {
+ Variant ret;
+
+ if (script_instance) {
+ if (script_instance->property_get_revert(p_name, ret)) {
+ return ret;
+ }
+ }
+
+// C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wignored-qualifiers"
+#endif
+ if (_extension && _extension->property_get_revert) {
+ if (_extension->property_get_revert(_extension_instance, (const GDNativeStringNamePtr)&p_name, (GDNativeVariantPtr)&ret)) {
+ return ret;
+ }
+ }
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic pop
+#endif
+
+ if (_property_get_revertv(p_name, ret)) {
+ return ret;
+ }
+ return Variant();
}
void Object::get_method_list(List<MethodInfo> *p_list) const {
@@ -858,16 +913,16 @@ void Object::remove_meta(const StringName &p_name) {
set_meta(p_name, Variant());
}
-Array Object::_get_property_list_bind() const {
+TypedArray<Dictionary> Object::_get_property_list_bind() const {
List<PropertyInfo> lpi;
get_property_list(&lpi);
return convert_property_list(&lpi);
}
-Array Object::_get_method_list_bind() const {
+TypedArray<Dictionary> Object::_get_method_list_bind() const {
List<MethodInfo> ml;
get_method_list(&ml);
- Array ret;
+ TypedArray<Dictionary> ret;
for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) {
Dictionary d = E->get();
@@ -1055,11 +1110,11 @@ void Object::_add_user_signal(const String &p_name, const Array &p_args) {
add_user_signal(mi);
}
-Array Object::_get_signal_list() const {
+TypedArray<Dictionary> Object::_get_signal_list() const {
List<MethodInfo> signal_list;
get_signal_list(&signal_list);
- Array ret;
+ TypedArray<Dictionary> ret;
for (const MethodInfo &E : signal_list) {
ret.push_back(Dictionary(E));
}
@@ -1067,11 +1122,11 @@ Array Object::_get_signal_list() const {
return ret;
}
-Array Object::_get_signal_connection_list(const StringName &p_signal) const {
+TypedArray<Dictionary> Object::_get_signal_connection_list(const StringName &p_signal) const {
List<Connection> conns;
get_all_signal_connections(&conns);
- Array ret;
+ TypedArray<Dictionary> ret;
for (const Connection &c : conns) {
if (c.signal.get_name() == p_signal) {
@@ -1082,8 +1137,8 @@ Array Object::_get_signal_connection_list(const StringName &p_signal) const {
return ret;
}
-Array Object::_get_incoming_connections() const {
- Array ret;
+TypedArray<Dictionary> Object::_get_incoming_connections() const {
+ TypedArray<Dictionary> ret;
int connections_amount = connections.size();
for (int idx_conn = 0; idx_conn < connections_amount; idx_conn++) {
ret.push_back(connections[idx_conn]);
@@ -1500,10 +1555,17 @@ void Object::_bind_methods() {
BIND_OBJ_CORE_METHOD(miget);
MethodInfo plget("_get_property_list");
-
plget.return_val.type = Variant::ARRAY;
+ plget.return_val.hint = PROPERTY_HINT_ARRAY_TYPE;
+ plget.return_val.hint_string = "Dictionary";
BIND_OBJ_CORE_METHOD(plget);
+ BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_property_can_revert", PropertyInfo(Variant::STRING_NAME, "property")));
+ MethodInfo mipgr("_property_get_revert", PropertyInfo(Variant::STRING_NAME, "property"));
+ mipgr.return_val.name = "Variant";
+ mipgr.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ BIND_OBJ_CORE_METHOD(mipgr);
+
#endif
BIND_OBJ_CORE_METHOD(MethodInfo("_init"));
BIND_OBJ_CORE_METHOD(MethodInfo(Variant::STRING, "_to_string"));
diff --git a/core/object/object.h b/core/object/object.h
index 35d0aaaa7d..13a40191e6 100644
--- a/core/object/object.h
+++ b/core/object/object.h
@@ -45,6 +45,9 @@
#include "core/variant/callable_bind.h"
#include "core/variant/variant.h"
+template <typename T>
+class TypedArray;
+
enum PropertyHint {
PROPERTY_HINT_NONE, ///< no hint provided.
PROPERTY_HINT_RANGE, ///< hint_text = "min,max[,step][,or_greater][,or_lesser][,no_slider][,radians][,degrees][,exp][,suffix:<keyword>] range.
@@ -91,6 +94,7 @@ enum PropertyHint {
PROPERTY_HINT_LOCALE_ID,
PROPERTY_HINT_LOCALIZABLE_STRING,
PROPERTY_HINT_NODE_TYPE, ///< a node object type
+ PROPERTY_HINT_HIDE_QUATERNION_EDIT, /// Only Node3D::transform should hide the quaternion editor.
PROPERTY_HINT_MAX,
// When updating PropertyHint, also sync the hardcoded list in VisualScriptEditorVariableEdit
};
@@ -207,7 +211,7 @@ struct PropertyInfo {
}
};
-Array convert_property_list(const List<PropertyInfo> *p_list);
+TypedArray<Dictionary> convert_property_list(const List<PropertyInfo> *p_list);
enum MethodFlags {
METHOD_FLAG_NORMAL = 1,
@@ -294,6 +298,8 @@ struct ObjectNativeExtension {
GDNativeExtensionClassGet get;
GDNativeExtensionClassGetPropertyList get_property_list;
GDNativeExtensionClassFreePropertyList free_property_list;
+ GDNativeExtensionClassPropertyCanRevert property_can_revert;
+ GDNativeExtensionClassPropertyGetRevert property_get_revert;
GDNativeExtensionClassNotification notification;
GDNativeExtensionClassToString to_string;
GDNativeExtensionClassReference reference;
@@ -469,6 +475,37 @@ protected:
m_inherits::_get_property_listv(p_list, p_reversed); \
} \
} \
+ _FORCE_INLINE_ void (Object::*_get_validate_property() const)(PropertyInfo & p_property) const { \
+ return (void(Object::*)(PropertyInfo &) const) & m_class::_validate_property; \
+ } \
+ virtual void _validate_propertyv(PropertyInfo &p_property) const override { \
+ m_inherits::_validate_propertyv(p_property); \
+ if (m_class::_get_validate_property() != m_inherits::_get_validate_property()) { \
+ _validate_property(p_property); \
+ } \
+ } \
+ _FORCE_INLINE_ bool (Object::*_get_property_can_revert() const)(const StringName &p_name) const { \
+ return (bool(Object::*)(const StringName &) const) & m_class::_property_can_revert; \
+ } \
+ virtual bool _property_can_revertv(const StringName &p_name) const override { \
+ if (m_class::_get_property_can_revert() != m_inherits::_get_property_can_revert()) { \
+ if (_property_can_revert(p_name)) { \
+ return true; \
+ } \
+ } \
+ return m_inherits::_property_can_revertv(p_name); \
+ } \
+ _FORCE_INLINE_ bool (Object::*_get_property_get_revert() const)(const StringName &p_name, Variant &) const { \
+ return (bool(Object::*)(const StringName &, Variant &) const) & m_class::_property_get_revert; \
+ } \
+ virtual bool _property_get_revertv(const StringName &p_name, Variant &r_ret) const override { \
+ if (m_class::_get_property_get_revert() != m_inherits::_get_property_get_revert()) { \
+ if (_property_get_revert(p_name, r_ret)) { \
+ return true; \
+ } \
+ } \
+ return m_inherits::_property_get_revertv(p_name, r_ret); \
+ } \
_FORCE_INLINE_ void (Object::*_get_notification() const)(int) { \
return (void(Object::*)(int)) & m_class::_notification; \
} \
@@ -564,9 +601,9 @@ private:
void _add_user_signal(const String &p_name, const Array &p_args = Array());
bool _has_user_signal(const StringName &p_name) const;
Error _emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- Array _get_signal_list() const;
- Array _get_signal_connection_list(const StringName &p_signal) const;
- Array _get_incoming_connections() const;
+ TypedArray<Dictionary> _get_signal_list() const;
+ TypedArray<Dictionary> _get_signal_connection_list(const StringName &p_signal) const;
+ TypedArray<Dictionary> _get_incoming_connections() const;
void _set_bind(const StringName &p_set, const Variant &p_value);
Variant _get_bind(const StringName &p_name) const;
void _set_indexed_bind(const NodePath &p_name, const Variant &p_value);
@@ -613,12 +650,18 @@ protected:
virtual bool _setv(const StringName &p_name, const Variant &p_property) { return false; };
virtual bool _getv(const StringName &p_name, Variant &r_property) const { return false; };
virtual void _get_property_listv(List<PropertyInfo> *p_list, bool p_reversed) const {};
+ virtual void _validate_propertyv(PropertyInfo &p_property) const {};
+ virtual bool _property_can_revertv(const StringName &p_name) const { return false; };
+ virtual bool _property_get_revertv(const StringName &p_name, Variant &r_property) const { return false; };
virtual void _notificationv(int p_notification, bool p_reversed) {}
static void _bind_methods();
bool _set(const StringName &p_name, const Variant &p_property) { return false; };
bool _get(const StringName &p_name, Variant &r_property) const { return false; };
void _get_property_list(List<PropertyInfo> *p_list) const {};
+ void _validate_property(PropertyInfo &p_property) const {};
+ bool _property_can_revert(const StringName &p_name) const { return false; };
+ bool _property_get_revert(const StringName &p_name, Variant &r_property) const { return false; };
void _notification(int p_notification) {}
_FORCE_INLINE_ static void (*_get_bind_methods())() {
@@ -633,6 +676,15 @@ protected:
_FORCE_INLINE_ void (Object::*_get_get_property_list() const)(List<PropertyInfo> *p_list) const {
return &Object::_get_property_list;
}
+ _FORCE_INLINE_ void (Object::*_get_validate_property() const)(PropertyInfo &p_property) const {
+ return &Object::_validate_property;
+ }
+ _FORCE_INLINE_ bool (Object::*_get_property_can_revert() const)(const StringName &p_name) const {
+ return &Object::_property_can_revert;
+ }
+ _FORCE_INLINE_ bool (Object::*_get_property_get_revert() const)(const StringName &p_name, Variant &) const {
+ return &Object::_property_get_revert;
+ }
_FORCE_INLINE_ void (Object::*_get_notification() const)(int) {
return &Object::_notification;
}
@@ -650,13 +702,12 @@ protected:
}
Vector<StringName> _get_meta_list_bind() const;
- Array _get_property_list_bind() const;
- Array _get_method_list_bind() const;
+ TypedArray<Dictionary> _get_property_list_bind() const;
+ TypedArray<Dictionary> _get_method_list_bind() const;
void _clear_internal_resource_paths(const Variant &p_var);
friend class ClassDB;
- virtual void _validate_property(PropertyInfo &property) const;
void _disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force = false);
@@ -757,6 +808,9 @@ public:
Variant get_indexed(const Vector<StringName> &p_names, bool *r_valid = nullptr) const;
void get_property_list(List<PropertyInfo> *p_list, bool p_reversed = false) const;
+ void validate_property(PropertyInfo &p_property) const;
+ bool property_can_revert(const StringName &p_name) const;
+ Variant property_get_revert(const StringName &p_name) const;
bool has_method(const StringName &p_method) const;
void get_method_list(List<MethodInfo> *p_list) const;
diff --git a/core/object/ref_counted.cpp b/core/object/ref_counted.cpp
index 726e2c012c..cac2400744 100644
--- a/core/object/ref_counted.cpp
+++ b/core/object/ref_counted.cpp
@@ -85,7 +85,8 @@ bool RefCounted::unreference() {
_get_extension()->unreference(_get_extension_instance());
}
- die = die && _instance_binding_reference(false);
+ bool binding_ret = _instance_binding_reference(false);
+ die = die && binding_ret;
}
return die;
diff --git a/core/object/script_language.cpp b/core/object/script_language.cpp
index b06c2e8896..e56d2e80b9 100644
--- a/core/object/script_language.cpp
+++ b/core/object/script_language.cpp
@@ -34,6 +34,7 @@
#include "core/core_string_names.h"
#include "core/debugger/engine_debugger.h"
#include "core/debugger/script_debugger.h"
+#include "core/variant/typed_array.h"
#include <stdint.h>
@@ -61,8 +62,8 @@ Variant Script::_get_property_default_value(const StringName &p_property) {
return ret;
}
-Array Script::_get_script_property_list() {
- Array ret;
+TypedArray<Dictionary> Script::_get_script_property_list() {
+ TypedArray<Dictionary> ret;
List<PropertyInfo> list;
get_script_property_list(&list);
for (const PropertyInfo &E : list) {
@@ -71,8 +72,8 @@ Array Script::_get_script_property_list() {
return ret;
}
-Array Script::_get_script_method_list() {
- Array ret;
+TypedArray<Dictionary> Script::_get_script_method_list() {
+ TypedArray<Dictionary> ret;
List<MethodInfo> list;
get_script_method_list(&list);
for (const MethodInfo &E : list) {
@@ -81,8 +82,8 @@ Array Script::_get_script_method_list() {
return ret;
}
-Array Script::_get_script_signal_list() {
- Array ret;
+TypedArray<Dictionary> Script::_get_script_signal_list() {
+ TypedArray<Dictionary> ret;
List<MethodInfo> list;
get_script_signal_list(&list);
for (const MethodInfo &E : list) {
diff --git a/core/object/script_language.h b/core/object/script_language.h
index f5f052b600..12a21150bc 100644
--- a/core/object/script_language.h
+++ b/core/object/script_language.h
@@ -37,6 +37,8 @@
#include "core/templates/rb_map.h"
class ScriptLanguage;
+template <typename T>
+class TypedArray;
typedef void (*ScriptEditRequestFunction)(const String &p_path);
@@ -108,9 +110,9 @@ protected:
virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {}
Variant _get_property_default_value(const StringName &p_property);
- Array _get_script_property_list();
- Array _get_script_method_list();
- Array _get_script_signal_list();
+ TypedArray<Dictionary> _get_script_property_list();
+ TypedArray<Dictionary> _get_script_method_list();
+ TypedArray<Dictionary> _get_script_signal_list();
Dictionary _get_script_constant_map();
public:
@@ -171,6 +173,9 @@ public:
virtual void get_property_list(List<PropertyInfo> *p_properties) const = 0;
virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = nullptr) const = 0;
+ virtual bool property_can_revert(const StringName &p_name) const = 0;
+ virtual bool property_get_revert(const StringName &p_name, Variant &r_ret) const = 0;
+
virtual Object *get_owner() { return nullptr; }
virtual void get_property_state(List<Pair<StringName, Variant>> &state);
@@ -447,6 +452,9 @@ public:
virtual void get_property_list(List<PropertyInfo> *p_properties) const override;
virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = nullptr) const override;
+ virtual bool property_can_revert(const StringName &p_name) const override { return false; };
+ virtual bool property_get_revert(const StringName &p_name, Variant &r_ret) const override { return false; };
+
virtual void get_method_list(List<MethodInfo> *p_list) const override;
virtual bool has_method(const StringName &p_method) const override;
diff --git a/core/object/script_language_extension.cpp b/core/object/script_language_extension.cpp
index 9de784ea7f..78e9038b66 100644
--- a/core/object/script_language_extension.cpp
+++ b/core/object/script_language_extension.cpp
@@ -62,6 +62,7 @@ void ScriptExtension::_bind_methods() {
GDVIRTUAL_BIND(_has_script_signal, "signal");
GDVIRTUAL_BIND(_get_script_signal_list);
+ GDVIRTUAL_BIND(_has_property_default_value, "property");
GDVIRTUAL_BIND(_get_property_default_value, "property");
GDVIRTUAL_BIND(_update_exports);
diff --git a/core/object/script_language_extension.h b/core/object/script_language_extension.h
index 2869f4ad98..7e74f6a2be 100644
--- a/core/object/script_language_extension.h
+++ b/core/object/script_language_extension.h
@@ -692,6 +692,19 @@ public:
return Variant::NIL;
}
+ virtual bool property_can_revert(const StringName &p_name) const override {
+ if (native_info->property_can_revert_func) {
+ return native_info->property_can_revert_func(instance, (const GDNativeStringNamePtr)&p_name);
+ }
+ return false;
+ }
+ virtual bool property_get_revert(const StringName &p_name, Variant &r_ret) const override {
+ if (native_info->property_get_revert_func) {
+ return native_info->property_get_revert_func(instance, (const GDNativeStringNamePtr)&p_name, (GDNativeVariantPtr)&r_ret);
+ }
+ return false;
+ }
+
virtual Object *get_owner() override {
if (native_info->get_owner_func) {
return (Object *)native_info->get_owner_func(instance);
diff --git a/core/os/keyboard.h b/core/os/keyboard.h
index 517a53e505..29418049cb 100644
--- a/core/os/keyboard.h
+++ b/core/os/keyboard.h
@@ -329,67 +329,71 @@ enum class KeyModifierMask {
// To avoid having unnecessary operators, only define the ones that are needed.
-inline Key operator-(uint32_t a, Key b) {
+constexpr Key operator-(uint32_t a, Key b) {
return (Key)(a - (uint32_t)b);
}
-inline Key &operator-=(Key &a, int b) {
- return (Key &)((int &)a -= b);
+constexpr Key &operator-=(Key &a, int b) {
+ a = static_cast<Key>(static_cast<int>(a) - static_cast<int>(b));
+ return a;
}
-inline Key operator+(Key a, int b) {
+constexpr Key operator+(Key a, int b) {
return (Key)((int)a + (int)b);
}
-inline Key operator+(Key a, Key b) {
+constexpr Key operator+(Key a, Key b) {
return (Key)((int)a + (int)b);
}
-inline Key operator-(Key a, Key b) {
+constexpr Key operator-(Key a, Key b) {
return (Key)((int)a - (int)b);
}
-inline Key operator&(Key a, Key b) {
+constexpr Key operator&(Key a, Key b) {
return (Key)((int)a & (int)b);
}
-inline Key operator|(Key a, Key b) {
+constexpr Key operator|(Key a, Key b) {
return (Key)((int)a | (int)b);
}
-inline Key &operator|=(Key &a, Key b) {
- return (Key &)((int &)a |= (int)b);
+constexpr Key &operator|=(Key &a, Key b) {
+ a = static_cast<Key>(static_cast<int>(a) | static_cast<int>(b));
+ return a;
}
-inline Key &operator|=(Key &a, KeyModifierMask b) {
- return (Key &)((int &)a |= (int)b);
+constexpr Key &operator|=(Key &a, KeyModifierMask b) {
+ a = static_cast<Key>(static_cast<int>(a) | static_cast<int>(b));
+ return a;
}
-inline Key &operator&=(Key &a, KeyModifierMask b) {
- return (Key &)((int &)a &= (int)b);
+constexpr Key &operator&=(Key &a, KeyModifierMask b) {
+ a = static_cast<Key>(static_cast<int>(a) & static_cast<int>(b));
+ return a;
}
-inline Key operator|(Key a, KeyModifierMask b) {
+constexpr Key operator|(Key a, KeyModifierMask b) {
return (Key)((int)a | (int)b);
}
-inline Key operator&(Key a, KeyModifierMask b) {
+constexpr Key operator&(Key a, KeyModifierMask b) {
return (Key)((int)a & (int)b);
}
-inline Key operator+(KeyModifierMask a, Key b) {
+constexpr Key operator+(KeyModifierMask a, Key b) {
return (Key)((int)a + (int)b);
}
-inline Key operator|(KeyModifierMask a, Key b) {
+constexpr Key operator|(KeyModifierMask a, Key b) {
return (Key)((int)a | (int)b);
}
-inline KeyModifierMask operator+(KeyModifierMask a, KeyModifierMask b) {
+constexpr KeyModifierMask operator+(KeyModifierMask a, KeyModifierMask b) {
return (KeyModifierMask)((int)a + (int)b);
}
-inline KeyModifierMask operator|(KeyModifierMask a, KeyModifierMask b) {
+constexpr KeyModifierMask operator|(KeyModifierMask a, KeyModifierMask b) {
return (KeyModifierMask)((int)a | (int)b);
}
diff --git a/core/os/os.cpp b/core/os/os.cpp
index 1358c926d1..45cd7109e2 100644
--- a/core/os/os.cpp
+++ b/core/os/os.cpp
@@ -166,10 +166,6 @@ bool OS::is_stdout_verbose() const {
return _verbose_stdout;
}
-bool OS::is_single_window() const {
- return _single_window;
-}
-
bool OS::is_stdout_debug_enabled() const {
return _debug_stdout;
}
@@ -190,10 +186,6 @@ void OS::set_stderr_enabled(bool p_enabled) {
_stderr_enabled = p_enabled;
}
-void OS::dump_memory_to_file(const char *p_file) {
- //Memory::dump_static_mem_to_file(p_file);
-}
-
static Ref<FileAccess> _OSPRF;
static void _OS_printres(Object *p_obj) {
diff --git a/core/os/os.h b/core/os/os.h
index 9152b797ef..ff769cc4f1 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -52,7 +52,6 @@ class OS {
int low_processor_usage_mode_sleep_usec = 10000;
bool _verbose_stdout = false;
bool _debug_stdout = false;
- bool _single_window = false;
String _local_clipboard;
int _exit_code = EXIT_FAILURE; // unexpected exit is marked as failure
bool _allow_hidpi = false;
@@ -243,13 +242,10 @@ public:
void set_stdout_enabled(bool p_enabled);
void set_stderr_enabled(bool p_enabled);
- virtual bool is_single_window() const;
-
virtual void disable_crash_handler() {}
virtual bool is_disable_crash_handler() const { return false; }
virtual void initialize_debugging() {}
- virtual void dump_memory_to_file(const char *p_file);
virtual void dump_resources_to_file(const char *p_file);
virtual void print_resources_in_use(bool p_short = false);
virtual void print_all_resources(String p_to_file = "");
diff --git a/core/string/translation.cpp b/core/string/translation.cpp
index b83b7c786f..4748f1a0cb 100644
--- a/core/string/translation.cpp
+++ b/core/string/translation.cpp
@@ -70,7 +70,7 @@ void Translation::_set_messages(const Dictionary &p_messages) {
void Translation::set_locale(const String &p_locale) {
locale = TranslationServer::get_singleton()->standardize_locale(p_locale);
- if (OS::get_singleton()->get_main_loop() && TranslationServer::get_singleton()->get_loaded_locales().has(this)) {
+ if (OS::get_singleton()->get_main_loop() && TranslationServer::get_singleton()->get_loaded_locales().has(get_locale())) {
OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
}
}
@@ -505,11 +505,11 @@ String TranslationServer::get_locale() const {
return locale;
}
-Array TranslationServer::get_loaded_locales() const {
- Array locales;
+PackedStringArray TranslationServer::get_loaded_locales() const {
+ PackedStringArray locales;
for (const Ref<Translation> &E : translations) {
const Ref<Translation> &t = E;
- ERR_FAIL_COND_V(t.is_null(), Array());
+ ERR_FAIL_COND_V(t.is_null(), PackedStringArray());
String l = t->get_locale();
locales.push_back(l);
diff --git a/core/string/translation.h b/core/string/translation.h
index 20c6ebd5a5..3f97a8d4fc 100644
--- a/core/string/translation.h
+++ b/core/string/translation.h
@@ -145,7 +145,7 @@ public:
String get_locale_name(const String &p_locale) const;
- Array get_loaded_locales() const;
+ PackedStringArray get_loaded_locales() const;
void add_translation(const Ref<Translation> &p_translation);
void remove_translation(const Ref<Translation> &p_translation);
diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp
index e93375bff7..0c43ba9ccc 100644
--- a/core/string/ustring.cpp
+++ b/core/string/ustring.cpp
@@ -531,10 +531,12 @@ String &String::operator+=(const String &p_str) {
resize(lhs_len + rhs_len + 1);
- const char32_t *src = p_str.get_data();
+ const char32_t *src = p_str.ptr();
char32_t *dst = ptrw() + lhs_len;
- memcpy(dst, src, (rhs_len + 1) * sizeof(char32_t));
+ // Don't copy the terminating null with `memcpy` to avoid undefined behavior when string is being added to itself (it would overlap the destination).
+ memcpy(dst, src, rhs_len * sizeof(char32_t));
+ *(dst + rhs_len) = _null;
return *this;
}
@@ -3449,18 +3451,19 @@ String String::replacen(const String &p_key, const String &p_with) const {
String String::repeat(int p_count) const {
ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
- String new_string;
- const char32_t *src = this->get_data();
-
- new_string.resize(length() * p_count + 1);
- new_string[length() * p_count] = 0;
-
- for (int i = 0; i < p_count; i++) {
- for (int j = 0; j < length(); j++) {
- new_string[i * length() + j] = src[j];
- }
- }
-
+ int len = length();
+ String new_string = *this;
+ new_string.resize(p_count * len + 1);
+
+ char32_t *dst = new_string.ptrw();
+ int offset = 1;
+ int stride = 1;
+ while (offset < p_count) {
+ memcpy(dst + offset * len, dst, stride * len * sizeof(char32_t));
+ offset += stride;
+ stride = MIN(stride * 2, p_count - offset);
+ }
+ dst[p_count * len] = _null;
return new_string;
}
@@ -4664,6 +4667,71 @@ String String::sprintf(const Array &values, bool *error) const {
in_format = false;
break;
}
+ case 'v': { // Vector2/3/4/2i/3i/4i
+ if (value_index >= values.size()) {
+ return "not enough arguments for format string";
+ }
+
+ int count;
+ switch (values[value_index].get_type()) {
+ case Variant::VECTOR2:
+ case Variant::VECTOR2I: {
+ count = 2;
+ } break;
+ case Variant::VECTOR3:
+ case Variant::VECTOR3I: {
+ count = 3;
+ } break;
+ case Variant::VECTOR4:
+ case Variant::VECTOR4I: {
+ count = 4;
+ } break;
+ default: {
+ return "%v requires a vector type (Vector2/3/4/2i/3i/4i)";
+ }
+ }
+
+ Vector4 vec = values[value_index];
+ String str = "(";
+ for (int i = 0; i < count; i++) {
+ double val = vec[i];
+ // Pad decimals out.
+ String number_str = String::num(ABS(val), min_decimals).pad_decimals(min_decimals);
+
+ int initial_len = number_str.length();
+
+ // Padding. Leave room for sign later if required.
+ int pad_chars_count = val < 0 ? min_chars - 1 : min_chars;
+ String pad_char = pad_with_zeros ? String("0") : String(" ");
+ if (left_justified) {
+ number_str = number_str.rpad(pad_chars_count, pad_char);
+ } else {
+ number_str = number_str.lpad(pad_chars_count, pad_char);
+ }
+
+ // Add sign if needed.
+ if (val < 0) {
+ if (left_justified) {
+ number_str = number_str.insert(0, "-");
+ } else {
+ number_str = number_str.insert(pad_with_zeros ? 0 : number_str.length() - initial_len, "-");
+ }
+ }
+
+ // Add number to combined string
+ str += number_str;
+
+ if (i < count - 1) {
+ str += ", ";
+ }
+ }
+ str += ")";
+
+ formatted += str;
+ ++value_index;
+ in_format = false;
+ break;
+ }
case 's': { // String
if (value_index >= values.size()) {
return "not enough arguments for format string";
@@ -4756,7 +4824,7 @@ String String::sprintf(const Array &values, bool *error) const {
}
break;
}
- case '.': { // Float separator.
+ case '.': { // Float/Vector separator.
if (in_decimals) {
return "too many decimal points in format";
}
@@ -4770,8 +4838,12 @@ String String::sprintf(const Array &values, bool *error) const {
return "not enough arguments for format string";
}
- if (!values[value_index].is_num()) {
- return "* wants number";
+ Variant::Type value_type = values[value_index].get_type();
+ if (!values[value_index].is_num() &&
+ value_type != Variant::VECTOR2 && value_type != Variant::VECTOR2I &&
+ value_type != Variant::VECTOR3 && value_type != Variant::VECTOR3I &&
+ value_type != Variant::VECTOR4 && value_type != Variant::VECTOR4I) {
+ return "* wants number or vector";
}
int size = values[value_index];
diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp
index eba12b68bb..9b7dc5012b 100644
--- a/core/variant/variant_call.cpp
+++ b/core/variant/variant_call.cpp
@@ -1608,6 +1608,7 @@ static void _register_variant_builtin_methods() {
bind_method(Vector2, lerp, sarray("to", "weight"), varray());
bind_method(Vector2, slerp, sarray("to", "weight"), varray());
bind_method(Vector2, cubic_interpolate, sarray("b", "pre_a", "post_b", "weight"), varray());
+ bind_method(Vector2, cubic_interpolate_in_time, sarray("b", "pre_a", "post_b", "weight", "b_t", "pre_a_t", "post_b_t"), varray());
bind_method(Vector2, bezier_interpolate, sarray("control_1", "control_2", "end", "t"), varray());
bind_method(Vector2, max_axis_index, sarray(), varray());
bind_method(Vector2, min_axis_index, sarray(), varray());
@@ -1696,6 +1697,7 @@ static void _register_variant_builtin_methods() {
bind_method(Vector3, lerp, sarray("to", "weight"), varray());
bind_method(Vector3, slerp, sarray("to", "weight"), varray());
bind_method(Vector3, cubic_interpolate, sarray("b", "pre_a", "post_b", "weight"), varray());
+ bind_method(Vector3, cubic_interpolate_in_time, sarray("b", "pre_a", "post_b", "weight", "b_t", "pre_a_t", "post_b_t"), varray());
bind_method(Vector3, bezier_interpolate, sarray("control_1", "control_2", "end", "t"), varray());
bind_method(Vector3, move_toward, sarray("to", "delta"), varray());
bind_method(Vector3, dot, sarray("with"), varray());
@@ -1738,6 +1740,7 @@ static void _register_variant_builtin_methods() {
bind_method(Vector4, round, sarray(), varray());
bind_method(Vector4, lerp, sarray("to", "weight"), varray());
bind_method(Vector4, cubic_interpolate, sarray("b", "pre_a", "post_b", "weight"), varray());
+ bind_method(Vector4, cubic_interpolate_in_time, sarray("b", "pre_a", "post_b", "weight", "b_t", "pre_a_t", "post_b_t"), varray());
bind_method(Vector4, posmod, sarray("mod"), varray());
bind_method(Vector4, posmodv, sarray("modv"), varray());
bind_method(Vector4, snapped, sarray("step"), varray());
@@ -1789,6 +1792,7 @@ static void _register_variant_builtin_methods() {
bind_method(Quaternion, slerp, sarray("to", "weight"), varray());
bind_method(Quaternion, slerpni, sarray("to", "weight"), varray());
bind_method(Quaternion, spherical_cubic_interpolate, sarray("b", "pre_a", "post_b", "weight"), varray());
+ bind_method(Quaternion, spherical_cubic_interpolate_in_time, sarray("b", "pre_a", "post_b", "weight", "b_t", "pre_a_t", "post_b_t"), varray());
bind_method(Quaternion, get_euler, sarray(), varray());
bind_method(Quaternion, get_axis, sarray(), varray());
bind_method(Quaternion, get_angle, sarray(), varray());
@@ -1916,7 +1920,6 @@ static void _register_variant_builtin_methods() {
bind_method(Basis, tdotx, sarray("with"), varray());
bind_method(Basis, tdoty, sarray("with"), varray());
bind_method(Basis, tdotz, sarray("with"), varray());
- bind_method(Basis, get_orthogonal_index, sarray(), varray());
bind_method(Basis, slerp, sarray("to", "weight"), varray());
bind_method(Basis, is_equal_approx, sarray("b"), varray());
bind_method(Basis, get_rotation_quaternion, sarray(), varray());
diff --git a/core/variant/variant_construct.cpp b/core/variant/variant_construct.cpp
index 3a0b6c1bb9..d048f45737 100644
--- a/core/variant/variant_construct.cpp
+++ b/core/variant/variant_construct.cpp
@@ -162,6 +162,7 @@ void Variant::_register_variant_constructors() {
add_constructor<VariantConstructNoArgs<Projection>>(sarray());
add_constructor<VariantConstructor<Projection, Projection>>(sarray("from"));
add_constructor<VariantConstructor<Projection, Transform3D>>(sarray("from"));
+ add_constructor<VariantConstructor<Projection, Vector4, Vector4, Vector4, Vector4>>(sarray("x_axis", "y_axis", "z_axis", "w_axis"));
add_constructor<VariantConstructNoArgs<Color>>(sarray());
add_constructor<VariantConstructor<Color, Color>>(sarray("from"));
diff --git a/core/variant/variant_utility.cpp b/core/variant/variant_utility.cpp
index 1f1439ab24..21c9c483a5 100644
--- a/core/variant/variant_utility.cpp
+++ b/core/variant/variant_utility.cpp
@@ -367,6 +367,11 @@ struct VariantUtilityFunctions {
return Math::cubic_interpolate(from, to, pre, post, weight);
}
+ static inline double cubic_interpolate_in_time(double from, double to, double pre, double post, double weight,
+ double to_t, double pre_t, double post_t) {
+ return Math::cubic_interpolate_in_time(from, to, pre, post, weight, to_t, pre_t, post_t);
+ }
+
static inline double bezier_interpolate(double p_start, double p_control_1, double p_control_2, double p_end, double p_t) {
return Math::bezier_interpolate(p_start, p_control_1, p_control_2, p_end, p_t);
}
@@ -1414,6 +1419,7 @@ void Variant::_register_variant_utility_functions() {
FUNCBINDVR3(lerp, sarray("from", "to", "weight"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(lerpf, sarray("from", "to", "weight"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(cubic_interpolate, sarray("from", "to", "pre", "post", "weight"), Variant::UTILITY_FUNC_TYPE_MATH);
+ FUNCBINDR(cubic_interpolate_in_time, sarray("from", "to", "pre", "post", "weight", "to_t", "pre_t", "post_t"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(bezier_interpolate, sarray("start", "control_1", "control_2", "end", "t"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(lerp_angle, sarray("from", "to", "weight"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(inverse_lerp, sarray("from", "to", "weight"), Variant::UTILITY_FUNC_TYPE_MATH);
diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml
index e6901bbe27..bd500f6b35 100644
--- a/doc/classes/@GlobalScope.xml
+++ b/doc/classes/@GlobalScope.xml
@@ -260,6 +260,21 @@
Cubic interpolates between two values by the factor defined in [param weight] with pre and post values.
</description>
</method>
+ <method name="cubic_interpolate_in_time">
+ <return type="float" />
+ <param index="0" name="from" type="float" />
+ <param index="1" name="to" type="float" />
+ <param index="2" name="pre" type="float" />
+ <param index="3" name="post" type="float" />
+ <param index="4" name="weight" type="float" />
+ <param index="5" name="to_t" type="float" />
+ <param index="6" name="pre_t" type="float" />
+ <param index="7" name="post_t" type="float" />
+ <description>
+ Cubic interpolates between two values by the factor defined in [param weight] with pre and post values.
+ It can perform smoother interpolation than [code]cubic_interpolate()[/code] by the time values.
+ </description>
+ </method>
<method name="db2linear">
<return type="float" />
<param index="0" name="db" type="float" />
@@ -1288,10 +1303,8 @@
<member name="TranslationServer" type="TranslationServer" setter="" getter="">
The [TranslationServer] singleton.
</member>
- <member name="VisualScriptCustomNodes" type="VisualScriptCustomNodes" setter="" getter="">
- The [VisualScriptCustomNodes] singleton.
- </member>
<member name="WorkerThreadPool" type="WorkerThreadPool" setter="" getter="">
+ The [WorkerThreadPool] singleton.
</member>
<member name="XRServer" type="XRServer" setter="" getter="">
The [XRServer] singleton.
@@ -2573,7 +2586,7 @@
</constant>
<constant name="PROPERTY_HINT_RANGE" value="1" enum="PropertyHint">
Hints that an integer or float property should be within a range specified via the hint string [code]"min,max"[/code] or [code]"min,max,step"[/code]. The hint string can optionally include [code]"or_greater"[/code] and/or [code]"or_lesser"[/code] to allow manual input going respectively above the max or below the min values. Example: [code]"-360,360,1,or_greater,or_lesser"[/code].
- Additionally, other keywords can be included: "exp" for exponential range editing, "radians" for editing radian angles in degrees, "degrees" to hint at an angle and "no_slider" to hide the slider.
+ Additionally, other keywords can be included: [code]"exp"[/code] for exponential range editing, [code]"radians"[/code] for editing radian angles in degrees, [code]"degrees"[/code] to hint at an angle and [code]"no_slider"[/code] to hide the slider.
</constant>
<constant name="PROPERTY_HINT_ENUM" value="2" enum="PropertyHint">
Hints that an integer, float or string property is an enumerated value to pick in a list specified via a hint string.
@@ -2584,7 +2597,7 @@
Unlike [constant PROPERTY_HINT_ENUM] a property with this hint still accepts arbitrary values and can be empty. The list of values serves to suggest possible values.
</constant>
<constant name="PROPERTY_HINT_EXP_EASING" value="4" enum="PropertyHint">
- Hints that a float property should be edited via an exponential easing function. The hint string can include [code]"attenuation"[/code] to flip the curve horizontally and/or [code]"inout"[/code] to also include in/out easing.
+ Hints that a float property should be edited via an exponential easing function. The hint string can include [code]"attenuation"[/code] to flip the curve horizontally and/or [code]"positive_only"[/code] to exclude in/out easing and limit values to be greater than or equal to zero.
</constant>
<constant name="PROPERTY_HINT_LINK" value="5" enum="PropertyHint">
Hints that a vector property should allow linking values (e.g. to edit both [code]x[/code] and [code]y[/code] together).
@@ -2695,7 +2708,10 @@
</constant>
<constant name="PROPERTY_HINT_NODE_TYPE" value="44" enum="PropertyHint">
</constant>
- <constant name="PROPERTY_HINT_MAX" value="45" enum="PropertyHint">
+ <constant name="PROPERTY_HINT_HIDE_QUATERNION_EDIT" value="45" enum="PropertyHint">
+ Hints that a quaternion property should disable the temporary euler editor.
+ </constant>
+ <constant name="PROPERTY_HINT_MAX" value="46" enum="PropertyHint">
</constant>
<constant name="PROPERTY_USAGE_NONE" value="0" enum="PropertyUsageFlags">
</constant>
diff --git a/doc/classes/AABB.xml b/doc/classes/AABB.xml
index 2fa191faa6..e2e4e7c61d 100644
--- a/doc/classes/AABB.xml
+++ b/doc/classes/AABB.xml
@@ -139,7 +139,7 @@
<return type="AABB" />
<param index="0" name="by" type="float" />
<description>
- Returns a copy of the [AABB] grown a given amount of units towards all the sides.
+ Returns a copy of the [AABB] grown a given number of units towards all the sides.
</description>
</method>
<method name="has_no_surface" qualifiers="const">
diff --git a/doc/classes/AStar2D.xml b/doc/classes/AStar2D.xml
index 977e73e7ca..6e76df647e 100644
--- a/doc/classes/AStar2D.xml
+++ b/doc/classes/AStar2D.xml
@@ -218,7 +218,7 @@
</description>
</method>
<method name="get_point_ids">
- <return type="Array" />
+ <return type="PackedInt64Array" />
<description>
Returns an array of all point IDs.
</description>
diff --git a/doc/classes/AStar3D.xml b/doc/classes/AStar3D.xml
index efce94e25d..45b1019bab 100644
--- a/doc/classes/AStar3D.xml
+++ b/doc/classes/AStar3D.xml
@@ -245,7 +245,7 @@
</description>
</method>
<method name="get_point_ids">
- <return type="Array" />
+ <return type="PackedInt64Array" />
<description>
Returns an array of all point IDs.
</description>
diff --git a/doc/classes/Animation.xml b/doc/classes/Animation.xml
index ac956eacba..faa9ae3569 100644
--- a/doc/classes/Animation.xml
+++ b/doc/classes/Animation.xml
@@ -130,14 +130,6 @@
Sets the stream of the key identified by [param key_idx] to value [param stream]. The [param track_idx] must be the index of an Audio Track.
</description>
</method>
- <method name="bezier_track_get_key_handle_mode" qualifiers="const">
- <return type="int" />
- <param index="0" name="track_idx" type="int" />
- <param index="1" name="key_idx" type="int" />
- <description>
- Returns the handle mode of the key identified by [param key_idx]. See [enum HandleMode] for possible values. The [param track_idx] must be the index of a Bezier Track.
- </description>
- </method>
<method name="bezier_track_get_key_in_handle" qualifiers="const">
<return type="Vector2" />
<param index="0" name="track_idx" type="int" />
@@ -169,7 +161,6 @@
<param index="2" name="value" type="float" />
<param index="3" name="in_handle" type="Vector2" default="Vector2(0, 0)" />
<param index="4" name="out_handle" type="Vector2" default="Vector2(0, 0)" />
- <param index="5" name="handle_mode" type="int" enum="Animation.HandleMode" default="1" />
<description>
Inserts a Bezier Track key at the given [param time] in seconds. The [param track_idx] must be the index of a Bezier Track.
[param in_handle] is the left-side weight of the added Bezier curve point, [param out_handle] is the right-side one, while [param value] is the actual value at this point.
@@ -183,16 +174,6 @@
Returns the interpolated value at the given [param time] (in seconds). The [param track_idx] must be the index of a Bezier Track.
</description>
</method>
- <method name="bezier_track_set_key_handle_mode">
- <return type="void" />
- <param index="0" name="track_idx" type="int" />
- <param index="1" name="key_idx" type="int" />
- <param index="2" name="key_handle_mode" type="int" enum="Animation.HandleMode" />
- <param index="3" name="balanced_value_time_ratio" type="float" default="1.0" />
- <description>
- Changes the handle mode of the keyframe at the given [param key_idx]. See [enum HandleMode] for possible values. The [param track_idx] must be the index of a Bezier Track.
- </description>
- </method>
<method name="bezier_track_set_key_in_handle">
<return type="void" />
<param index="0" name="track_idx" type="int" />
@@ -349,7 +330,7 @@
<return type="int" />
<param index="0" name="track_idx" type="int" />
<description>
- Returns the amount of keys in a given track.
+ Returns the number of keys in a given track.
</description>
</method>
<method name="track_get_key_time" qualifiers="const">
@@ -619,6 +600,9 @@
<constant name="INTERPOLATION_CUBIC" value="2" enum="InterpolationType">
Cubic interpolation.
</constant>
+ <constant name="INTERPOLATION_CUBIC_IN_TIME" value="3" enum="InterpolationType">
+ Cubic interpolation with uniformed time.
+ </constant>
<constant name="UPDATE_CONTINUOUS" value="0" enum="UpdateMode">
Update between keyframes.
</constant>
@@ -640,11 +624,5 @@
<constant name="LOOP_PINGPONG" value="2" enum="LoopMode">
Repeats playback and reverse playback at both ends of the animation.
</constant>
- <constant name="HANDLE_MODE_FREE" value="0" enum="HandleMode">
- Assigning the free handle mode to a Bezier Track's keyframe allows you to edit the keyframe's left and right handles independently from one another.
- </constant>
- <constant name="HANDLE_MODE_BALANCED" value="1" enum="HandleMode">
- Assigning the balanced handle mode to a Bezier Track's keyframe makes it so the two handles of the keyframe always stay aligned when changing either the keyframe's left or right handle.
- </constant>
</constants>
</class>
diff --git a/doc/classes/AnimationLibrary.xml b/doc/classes/AnimationLibrary.xml
index 015d306b41..fbbf9a3be4 100644
--- a/doc/classes/AnimationLibrary.xml
+++ b/doc/classes/AnimationLibrary.xml
@@ -1,10 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="AnimationLibrary" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
+ Container for [Animation] resources.
</brief_description>
<description>
+ An animation library stores a set of animations accessible through [StringName] keys, for use with [AnimationPlayer] nodes.
</description>
<tutorials>
+ <link title="Animation tutorial index">$DOCS_URL/tutorials/animation/index.html</link>
</tutorials>
<methods>
<method name="add_animation">
@@ -12,29 +15,34 @@
<param index="0" name="name" type="StringName" />
<param index="1" name="animation" type="Animation" />
<description>
+ Adds the [param animation] to the library, accesible by the key [param name].
</description>
</method>
<method name="get_animation" qualifiers="const">
<return type="Animation" />
<param index="0" name="name" type="StringName" />
<description>
+ Returns the [Animation] with the key [param name], or [code]null[/code] if none is found.
</description>
</method>
<method name="get_animation_list" qualifiers="const">
<return type="StringName[]" />
<description>
+ Returns the keys for the [Animation]s stored in the library.
</description>
</method>
<method name="has_animation" qualifiers="const">
<return type="bool" />
<param index="0" name="name" type="StringName" />
<description>
+ Returns [code]true[/code] if the library stores an [Animation] with [param name] as the key.
</description>
</method>
<method name="remove_animation">
<return type="void" />
<param index="0" name="name" type="StringName" />
<description>
+ Removes the [Animation] with the key [param name].
</description>
</method>
<method name="rename_animation">
@@ -42,6 +50,7 @@
<param index="0" name="name" type="StringName" />
<param index="1" name="newname" type="StringName" />
<description>
+ Changes the key of the [Animation] associated with the key [param name] to [param newname].
</description>
</method>
</methods>
@@ -53,17 +62,20 @@
<signal name="animation_added">
<param index="0" name="name" type="StringName" />
<description>
+ Emitted when an [Animation] is added, under the key [param name].
</description>
</signal>
<signal name="animation_removed">
<param index="0" name="name" type="StringName" />
<description>
+ Emitted when an [Animation] stored with the key [param name] is removed.
</description>
</signal>
<signal name="animation_renamed">
<param index="0" name="name" type="StringName" />
<param index="1" name="to_name" type="StringName" />
<description>
+ Emitted when the key for an [Animation] is changed, from [param name] to [param to_name].
</description>
</signal>
</signals>
diff --git a/doc/classes/AnimationNodeStateMachineTransition.xml b/doc/classes/AnimationNodeStateMachineTransition.xml
index 0badb831de..1b5a795b3c 100644
--- a/doc/classes/AnimationNodeStateMachineTransition.xml
+++ b/doc/classes/AnimationNodeStateMachineTransition.xml
@@ -9,7 +9,7 @@
</tutorials>
<members>
<member name="advance_condition" type="StringName" setter="set_advance_condition" getter="get_advance_condition" default="&amp;&quot;&quot;">
- Turn on auto advance when this condition is set. The provided name will become a boolean parameter on the [AnimationTree] that can be controlled from code (see [url=$DOCS_URL/tutorials/animation/animation_tree.html#controlling-from-code][/url]). For example, if [member AnimationTree.tree_root] is an [AnimationNodeStateMachine] and [member advance_condition] is set to [code]"idle"[/code]:
+ Turn on auto advance when this condition is set. The provided name will become a boolean parameter on the [AnimationTree] that can be controlled from code (see [url=$DOCS_URL/tutorials/animation/animation_tree.html#controlling-from-code]Using AnimationTree[/url]). For example, if [member AnimationTree.tree_root] is an [AnimationNodeStateMachine] and [member advance_condition] is set to [code]"idle"[/code]:
[codeblocks]
[gdscript]
$animation_tree.set("parameters/conditions/idle", is_on_floor and (linear_velocity.x == 0))
@@ -37,6 +37,9 @@
<member name="switch_mode" type="int" setter="set_switch_mode" getter="get_switch_mode" enum="AnimationNodeStateMachineTransition.SwitchMode" default="0">
The transition type.
</member>
+ <member name="xfade_curve" type="Curve" setter="set_xfade_curve" getter="get_xfade_curve">
+ Ease curve for better control over cross-fade between this state and the next.
+ </member>
<member name="xfade_time" type="float" setter="set_xfade_time" getter="get_xfade_time" default="0.0">
The time to cross-fade between this state and the next.
</member>
diff --git a/doc/classes/AnimationNodeTransition.xml b/doc/classes/AnimationNodeTransition.xml
index a5de170ccd..d574bc044d 100644
--- a/doc/classes/AnimationNodeTransition.xml
+++ b/doc/classes/AnimationNodeTransition.xml
@@ -46,7 +46,9 @@
<member name="input_count" type="int" setter="set_enabled_inputs" getter="get_enabled_inputs" default="0">
The number of available input ports for this node.
</member>
- <member name="xfade_time" type="float" setter="set_cross_fade_time" getter="get_cross_fade_time" default="0.0">
+ <member name="xfade_curve" type="Curve" setter="set_xfade_curve" getter="get_xfade_curve">
+ </member>
+ <member name="xfade_time" type="float" setter="set_xfade_time" getter="get_xfade_time" default="0.0">
Cross-fading time (in seconds) between each animation connected to the inputs.
</member>
</members>
diff --git a/doc/classes/Area2D.xml b/doc/classes/Area2D.xml
index c61705505e..f1e40d4979 100644
--- a/doc/classes/Area2D.xml
+++ b/doc/classes/Area2D.xml
@@ -4,7 +4,9 @@
2D area for detection and physics and audio influence.
</brief_description>
<description>
- 2D area that detects [CollisionObject2D] nodes overlapping, entering, or exiting. Can also alter or override local physics parameters (gravity, damping) and route audio to a custom audio bus.
+ 2D area that detects [CollisionObject2D] nodes overlapping, entering, or exiting. Can also alter or override local physics parameters (gravity, damping) and route audio to custom audio buses.
+ To give the area its shape, add a [CollisionShape2D] or a [CollisionPolygon2D] node as a [i]direct[/i] child (or add multiple such nodes as direct children) of the area.
+ [b]Warning:[/b] See [ConcavePolygonShape2D] for a warning about possibly unexpected behavior when using that shape for an area.
</description>
<tutorials>
<link title="Using Area2D">$DOCS_URL/tutorials/physics/using_area_2d.html</link>
diff --git a/doc/classes/Area3D.xml b/doc/classes/Area3D.xml
index 3c50a1ac05..14081918cf 100644
--- a/doc/classes/Area3D.xml
+++ b/doc/classes/Area3D.xml
@@ -5,6 +5,8 @@
</brief_description>
<description>
3D area that detects [CollisionObject3D] nodes overlapping, entering, or exiting. Can also alter or override local physics parameters (gravity, damping) and route audio to custom audio buses.
+ To give the area its shape, add a [CollisionShape3D] or a [CollisionPolygon3D] node as a [i]direct[/i] child (or add multiple such nodes as direct children) of the area.
+ [b]Warning:[/b] See [ConcavePolygonShape3D] (also called "trimesh") for a warning about possibly unexpected behavior when using that shape for an area.
</description>
<tutorials>
<link title="3D Platformer Demo">https://godotengine.org/asset-library/asset/125</link>
diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml
index 35656dbd70..f6d926031d 100644
--- a/doc/classes/Array.xml
+++ b/doc/classes/Array.xml
@@ -576,14 +576,14 @@
<return type="bool" />
<param index="0" name="right" type="Array" />
<description>
- Performs a comparison for each index between the left operand [Array] and the [param right] [Array], considering the highest common index of both arrays for this comparison: Returns [code]true[/code] on the first occurrence of an element that is less, or [code]false[/code] if the element is greater. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns [code]false[/code] if the left operand [Array] has less elements, otherwise it returns [code]true[/code].
+ Performs a comparison for each index between the left operand [Array] and the [param right] [Array], considering the highest common index of both arrays for this comparison: Returns [code]true[/code] on the first occurrence of an element that is less, or [code]false[/code] if the element is greater. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns [code]false[/code] if the left operand [Array] has fewer elements, otherwise it returns [code]true[/code].
</description>
</operator>
<operator name="operator &lt;=">
<return type="bool" />
<param index="0" name="right" type="Array" />
<description>
- Performs a comparison for each index between the left operand [Array] and the [param right] [Array], considering the highest common index of both arrays for this comparison: Returns [code]true[/code] on the first occurrence of an element that is less, or [code]false[/code] if the element is greater. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns [code]true[/code] if the left operand [Array] has less or the same number of elements, otherwise it returns [code]false[/code].
+ Performs a comparison for each index between the left operand [Array] and the [param right] [Array], considering the highest common index of both arrays for this comparison: Returns [code]true[/code] on the first occurrence of an element that is less, or [code]false[/code] if the element is greater. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns [code]true[/code] if the left operand [Array] has the same number of elements or fewer, otherwise it returns [code]false[/code].
</description>
</operator>
<operator name="operator ==">
diff --git a/doc/classes/AudioEffectChorus.xml b/doc/classes/AudioEffectChorus.xml
index 83cbcff70c..de168cdfb0 100644
--- a/doc/classes/AudioEffectChorus.xml
+++ b/doc/classes/AudioEffectChorus.xml
@@ -166,7 +166,7 @@
The voice's filter rate.
</member>
<member name="voice_count" type="int" setter="set_voice_count" getter="get_voice_count" default="2">
- The amount of voices in the effect.
+ The number of voices in the effect.
</member>
<member name="wet" type="float" setter="set_wet" getter="get_wet" default="0.5">
The effect's processed signal.
diff --git a/doc/classes/AudioEffectDelay.xml b/doc/classes/AudioEffectDelay.xml
index 8223ccd6bd..b9ae12204e 100644
--- a/doc/classes/AudioEffectDelay.xml
+++ b/doc/classes/AudioEffectDelay.xml
@@ -14,40 +14,40 @@
<member name="dry" type="float" setter="set_dry" getter="get_dry" default="1.0">
Output percent of original sound. At 0, only delayed sounds are output. Value can range from 0 to 1.
</member>
- <member name="feedback/active" type="bool" setter="set_feedback_active" getter="is_feedback_active" default="false">
+ <member name="feedback_active" type="bool" setter="set_feedback_active" getter="is_feedback_active" default="false">
If [code]true[/code], feedback is enabled.
</member>
- <member name="feedback/delay_ms" type="float" setter="set_feedback_delay_ms" getter="get_feedback_delay_ms" default="340.0">
+ <member name="feedback_delay_ms" type="float" setter="set_feedback_delay_ms" getter="get_feedback_delay_ms" default="340.0">
Feedback delay time in milliseconds.
</member>
- <member name="feedback/level_db" type="float" setter="set_feedback_level_db" getter="get_feedback_level_db" default="-6.0">
+ <member name="feedback_level_db" type="float" setter="set_feedback_level_db" getter="get_feedback_level_db" default="-6.0">
Sound level for [code]tap1[/code].
</member>
- <member name="feedback/lowpass" type="float" setter="set_feedback_lowpass" getter="get_feedback_lowpass" default="16000.0">
+ <member name="feedback_lowpass" type="float" setter="set_feedback_lowpass" getter="get_feedback_lowpass" default="16000.0">
Low-pass filter for feedback, in Hz. Frequencies below this value are filtered out of the source signal.
</member>
- <member name="tap1/active" type="bool" setter="set_tap1_active" getter="is_tap1_active" default="true">
+ <member name="tap1_active" type="bool" setter="set_tap1_active" getter="is_tap1_active" default="true">
If [code]true[/code], [code]tap1[/code] will be enabled.
</member>
- <member name="tap1/delay_ms" type="float" setter="set_tap1_delay_ms" getter="get_tap1_delay_ms" default="250.0">
+ <member name="tap1_delay_ms" type="float" setter="set_tap1_delay_ms" getter="get_tap1_delay_ms" default="250.0">
[code]tap1[/code] delay time in milliseconds.
</member>
- <member name="tap1/level_db" type="float" setter="set_tap1_level_db" getter="get_tap1_level_db" default="-6.0">
+ <member name="tap1_level_db" type="float" setter="set_tap1_level_db" getter="get_tap1_level_db" default="-6.0">
Sound level for [code]tap1[/code].
</member>
- <member name="tap1/pan" type="float" setter="set_tap1_pan" getter="get_tap1_pan" default="0.2">
+ <member name="tap1_pan" type="float" setter="set_tap1_pan" getter="get_tap1_pan" default="0.2">
Pan position for [code]tap1[/code]. Value can range from -1 (fully left) to 1 (fully right).
</member>
- <member name="tap2/active" type="bool" setter="set_tap2_active" getter="is_tap2_active" default="true">
+ <member name="tap2_active" type="bool" setter="set_tap2_active" getter="is_tap2_active" default="true">
If [code]true[/code], [code]tap2[/code] will be enabled.
</member>
- <member name="tap2/delay_ms" type="float" setter="set_tap2_delay_ms" getter="get_tap2_delay_ms" default="500.0">
+ <member name="tap2_delay_ms" type="float" setter="set_tap2_delay_ms" getter="get_tap2_delay_ms" default="500.0">
[b]Tap2[/b] delay time in milliseconds.
</member>
- <member name="tap2/level_db" type="float" setter="set_tap2_level_db" getter="get_tap2_level_db" default="-12.0">
+ <member name="tap2_level_db" type="float" setter="set_tap2_level_db" getter="get_tap2_level_db" default="-12.0">
Sound level for [code]tap2[/code].
</member>
- <member name="tap2/pan" type="float" setter="set_tap2_pan" getter="get_tap2_pan" default="-0.4">
+ <member name="tap2_pan" type="float" setter="set_tap2_pan" getter="get_tap2_pan" default="-0.4">
Pan position for [code]tap2[/code]. Value can range from -1 (fully left) to 1 (fully right).
</member>
</members>
diff --git a/doc/classes/AudioServer.xml b/doc/classes/AudioServer.xml
index 4ded906dc1..8dc80e3bdc 100644
--- a/doc/classes/AudioServer.xml
+++ b/doc/classes/AudioServer.xml
@@ -30,7 +30,7 @@
</description>
</method>
<method name="capture_get_device_list">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Returns the names of all audio input devices detected on the system.
</description>
@@ -45,7 +45,7 @@
<return type="int" />
<param index="0" name="bus_idx" type="int" />
<description>
- Returns the amount of channels of the bus at index [param bus_idx].
+ Returns the number of channels of the bus at index [param bus_idx].
</description>
</method>
<method name="get_bus_effect">
@@ -117,7 +117,7 @@
</description>
</method>
<method name="get_device_list">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Returns the names of all audio devices detected on the system.
</description>
diff --git a/doc/classes/BaseMaterial3D.xml b/doc/classes/BaseMaterial3D.xml
index d2425313f7..fcdf59e36e 100644
--- a/doc/classes/BaseMaterial3D.xml
+++ b/doc/classes/BaseMaterial3D.xml
@@ -398,6 +398,7 @@
</member>
<member name="uv1_triplanar_sharpness" type="float" setter="set_uv1_triplanar_blend_sharpness" getter="get_uv1_triplanar_blend_sharpness" default="1.0">
A lower number blends the texture more softly while a higher number blends the texture more sharply.
+ [b]Note:[/b] [member uv1_triplanar_sharpness] is clamped between [code]0.0[/code] and [code]150.0[/code] (inclusive) as values outside that range can look broken depending on the mesh.
</member>
<member name="uv1_world_triplanar" type="bool" setter="set_flag" getter="get_flag" default="false">
If [code]true[/code], triplanar mapping for [code]UV[/code] is calculated in world space rather than object local space. See also [member uv1_triplanar].
@@ -413,6 +414,7 @@
</member>
<member name="uv2_triplanar_sharpness" type="float" setter="set_uv2_triplanar_blend_sharpness" getter="get_uv2_triplanar_blend_sharpness" default="1.0">
A lower number blends the texture more softly while a higher number blends the texture more sharply.
+ [b]Note:[/b] [member uv2_triplanar_sharpness] is clamped between [code]0.0[/code] and [code]150.0[/code] (inclusive) as values outside that range can look broken depending on the mesh.
</member>
<member name="uv2_world_triplanar" type="bool" setter="set_flag" getter="get_flag" default="false">
If [code]true[/code], triplanar mapping for [code]UV2[/code] is calculated in world space rather than object local space. See also [member uv2_triplanar].
@@ -496,10 +498,10 @@
The texture filter blends between the nearest 4 pixels and between the nearest 2 mipmaps. Use this for most cases as mipmaps are important to smooth out pixels that are far from the camera.
</constant>
<constant name="TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC" value="4" enum="TextureFilter">
- The texture filter reads from the nearest pixel, but selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera.
+ The texture filter reads from the nearest pixel, but selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. The anisotropic filtering level can be changed by adjusting [member ProjectSettings.rendering/textures/default_filters/anisotropic_filtering_level].
</constant>
<constant name="TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC" value="5" enum="TextureFilter">
- The texture filter blends between the nearest 4 pixels and selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. This is the slowest of the filtering options, but results in the highest quality texturing.
+ The texture filter blends between the nearest 4 pixels and selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. This is the slowest of the filtering options, but results in the highest quality texturing. The anisotropic filtering level can be changed by adjusting [member ProjectSettings.rendering/textures/default_filters/anisotropic_filtering_level].
</constant>
<constant name="TEXTURE_FILTER_MAX" value="6" enum="TextureFilter">
Represents the size of the [enum TextureFilter] enum.
diff --git a/doc/classes/Basis.xml b/doc/classes/Basis.xml
index 8aa6278296..d62f704528 100644
--- a/doc/classes/Basis.xml
+++ b/doc/classes/Basis.xml
@@ -87,12 +87,6 @@
Consider using the [method get_rotation_quaternion] method instead, which returns a [Quaternion] quaternion instead of Euler angles.
</description>
</method>
- <method name="get_orthogonal_index" qualifiers="const">
- <return type="int" />
- <description>
- This function considers a discretization of rotations into 24 points on unit sphere, lying along the vectors (x,y,z) with each component being either -1, 0, or 1, and returns the index of the point best representing the orientation of the object. It is mainly used by the [GridMap] editor. For further details, refer to the Godot source code.
- </description>
- </method>
<method name="get_rotation_quaternion" qualifiers="const">
<return type="Quaternion" />
<description>
diff --git a/doc/classes/BitMap.xml b/doc/classes/BitMap.xml
index b286a66f34..9323642274 100644
--- a/doc/classes/BitMap.xml
+++ b/doc/classes/BitMap.xml
@@ -46,7 +46,7 @@
<method name="get_true_bit_count" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of bitmap elements that are set to [code]true[/code].
+ Returns the number of bitmap elements that are set to [code]true[/code].
</description>
</method>
<method name="grow_mask">
@@ -58,7 +58,7 @@
</description>
</method>
<method name="opaque_to_polygons" qualifiers="const">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="rect" type="Rect2" />
<param index="1" name="epsilon" type="float" default="2.0" />
<description>
diff --git a/doc/classes/Button.xml b/doc/classes/Button.xml
index 1cd9ca0afb..e78cdfc951 100644
--- a/doc/classes/Button.xml
+++ b/doc/classes/Button.xml
@@ -114,7 +114,7 @@
Icon modulate [Color] used when the [Button] is being pressed.
</theme_item>
<theme_item name="h_separation" data_type="constant" type="int" default="2">
- The horizontal space between [Button]'s icon and text.
+ The horizontal space between [Button]'s icon and text. Negative values will be treated as [code]0[/code] when used.
</theme_item>
<theme_item name="outline_size" data_type="constant" type="int" default="0">
The size of the text outline.
diff --git a/doc/classes/ButtonGroup.xml b/doc/classes/ButtonGroup.xml
index 8bedb5a1ac..277bda2836 100644
--- a/doc/classes/ButtonGroup.xml
+++ b/doc/classes/ButtonGroup.xml
@@ -11,7 +11,7 @@
</tutorials>
<methods>
<method name="get_buttons">
- <return type="Array" />
+ <return type="BaseButton[]" />
<description>
Returns an [Array] of [Button]s who have this as their [ButtonGroup] (see [member BaseButton.button_group]).
</description>
diff --git a/doc/classes/Camera3D.xml b/doc/classes/Camera3D.xml
index 6b379e0509..65fdecc3c6 100644
--- a/doc/classes/Camera3D.xml
+++ b/doc/classes/Camera3D.xml
@@ -37,7 +37,7 @@
</description>
</method>
<method name="get_frustum" qualifiers="const">
- <return type="Array" />
+ <return type="Plane[]" />
<description>
Returns the camera's frustum planes in world space units as an array of [Plane]s in the following order: near, far, left, top, right, bottom. Not to be confused with [member frustum_offset].
</description>
diff --git a/doc/classes/CameraServer.xml b/doc/classes/CameraServer.xml
index d7a9888fac..d346fbde4f 100644
--- a/doc/classes/CameraServer.xml
+++ b/doc/classes/CameraServer.xml
@@ -19,7 +19,7 @@
</description>
</method>
<method name="feeds">
- <return type="Array" />
+ <return type="CameraFeed[]" />
<description>
Returns an array of [CameraFeed]s.
</description>
diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml
index 1423b39e4a..fe1fe498d1 100644
--- a/doc/classes/CanvasItem.xml
+++ b/doc/classes/CanvasItem.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
Base class of anything 2D. Canvas items are laid out in a tree; children inherit and extend their parent's transform. [CanvasItem] is extended by [Control] for anything GUI-related, and by [Node2D] for anything related to the 2D engine.
- Any [CanvasItem] can draw. For this, [method update] must be called, then [constant NOTIFICATION_DRAW] will be received on idle time to request redraw. Because of this, canvas items don't need to be redrawn on every frame, improving the performance significantly. Several functions for drawing on the [CanvasItem] are provided (see [code]draw_*[/code] functions). However, they can only be used inside the [method Object._notification], signal or [method _draw] virtual functions.
+ Any [CanvasItem] can draw. For this, [method update] is called by the engine, then [constant NOTIFICATION_DRAW] will be received on idle time to request redraw. Because of this, canvas items don't need to be redrawn on every frame, improving the performance significantly. Several functions for drawing on the [CanvasItem] are provided (see [code]draw_*[/code] functions). However, they can only be used inside [method _draw], its corresponding [method Object._notification] or methods connected to the [signal draw] signal.
Canvas items are drawn in tree order. By default, children are on top of their parents so a root [CanvasItem] will be drawn behind everything. This behavior can be changed on a per-item basis.
A [CanvasItem] can also be hidden, which will also hide its children. It provides many ways to change parameters such as modulation (for itself and its children) and self modulation (only for itself), as well as its blend mode.
Ultimately, a transform notification can be requested, which will notify the node that its global position changed in case the parent tree changed.
@@ -20,7 +20,8 @@
<method name="_draw" qualifiers="virtual">
<return type="void" />
<description>
- Overridable function called by the engine (if defined) to draw the canvas item.
+ Called when [CanvasItem] has been requested to redraw (when [method update] is called, either manually or by the engine).
+ Corresponds to the [constant NOTIFICATION_DRAW] notification in [method Object._notification].
</description>
</method>
<method name="draw_animation_slice">
@@ -86,7 +87,7 @@
<param index="2" name="uvs" type="PackedVector2Array" default="PackedVector2Array()" />
<param index="3" name="texture" type="Texture2D" default="null" />
<description>
- Draws a colored polygon of any amount of points, convex or concave. Unlike [method draw_polygon], a single color must be specified for the whole polygon.
+ Draws a colored polygon of any number of points, convex or concave. Unlike [method draw_polygon], a single color must be specified for the whole polygon.
</description>
</method>
<method name="draw_dashed_line">
@@ -211,7 +212,7 @@
<param index="2" name="uvs" type="PackedVector2Array" default="PackedVector2Array()" />
<param index="3" name="texture" type="Texture2D" default="null" />
<description>
- Draws a solid polygon of any amount of points, convex or concave. Unlike [method draw_colored_polygon], each point's color can be changed individually. See also [method draw_polyline] and [method draw_polyline_colors].
+ Draws a solid polygon of any number of points, convex or concave. Unlike [method draw_colored_polygon], each point's color can be changed individually. See also [method draw_polyline] and [method draw_polyline_colors].
</description>
</method>
<method name="draw_polyline">
@@ -465,7 +466,7 @@
<method name="is_visible_in_tree" qualifiers="const">
<return type="bool" />
<description>
- Returns [code]true[/code] if the node is present in the [SceneTree], its [member visible] property is [code]true[/code] and all its antecedents are also visible. If any antecedent is hidden, this node will not be visible in the scene tree.
+ Returns [code]true[/code] if the node is present in the [SceneTree], its [member visible] property is [code]true[/code] and all its antecedents are also visible. If any antecedent is hidden, this node will not be visible in the scene tree, and is consequently not drawn (see [method _draw]).
</description>
</method>
<method name="make_canvas_position_local" qualifiers="const">
@@ -505,7 +506,7 @@
<method name="update">
<return type="void" />
<description>
- Queue the [CanvasItem] for update. [constant NOTIFICATION_DRAW] will be called on idle time to request redraw.
+ Queues the [CanvasItem] to redraw. During idle time, if [CanvasItem] is visible, [constant NOTIFICATION_DRAW] is sent and [method _draw] is called. This only occurs [b]once[/b] per frame, even if this method has been called multiple times.
</description>
</method>
</methods>
@@ -547,7 +548,8 @@
<signals>
<signal name="draw">
<description>
- Emitted when the [CanvasItem] must redraw. This can only be connected realtime, as deferred will not allow drawing.
+ Emitted when the [CanvasItem] must redraw, [i]after[/i] the related [constant NOTIFICATION_DRAW] notification, and [i]before[/i] [method _draw] is called.
+ [b]Note:[/b] Deferred connections do not allow drawing through the [code]draw_*[/code] methods.
</description>
</signal>
<signal name="hidden">
@@ -574,7 +576,7 @@
The [CanvasItem]'s local transform has changed. This notification is only received if enabled by [method set_notify_local_transform].
</constant>
<constant name="NOTIFICATION_DRAW" value="30">
- The [CanvasItem] is requested to draw.
+ The [CanvasItem] is requested to draw (see [method _draw]).
</constant>
<constant name="NOTIFICATION_VISIBILITY_CHANGED" value="31">
The [CanvasItem]'s visibility has changed.
@@ -601,11 +603,11 @@
The texture filter blends between the nearest 4 pixels and between the nearest 2 mipmaps. Use this for non-pixel art textures that may be viewed at a low scale (e.g. due to [Camera2D] zoom), as mipmaps are important to smooth out pixels that are smaller than on-screen pixels.
</constant>
<constant name="TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC" value="5" enum="TextureFilter">
- The texture filter reads from the nearest pixel, but selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera.
+ The texture filter reads from the nearest pixel, but selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. The anisotropic filtering level can be changed by adjusting [member ProjectSettings.rendering/textures/default_filters/anisotropic_filtering_level].
[b]Note:[/b] This texture filter is rarely useful in 2D projects. [constant TEXTURE_FILTER_NEAREST_WITH_MIPMAPS] is usually more appropriate.
</constant>
<constant name="TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC" value="6" enum="TextureFilter">
- The texture filter blends between the nearest 4 pixels and selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. This is the slowest of the filtering options, but results in the highest quality texturing.
+ The texture filter blends between the nearest 4 pixels and selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. This is the slowest of the filtering options, but results in the highest quality texturing. The anisotropic filtering level can be changed by adjusting [member ProjectSettings.rendering/textures/default_filters/anisotropic_filtering_level].
[b]Note:[/b] This texture filter is rarely useful in 2D projects. [constant TEXTURE_FILTER_LINEAR_WITH_MIPMAPS] is usually more appropriate.
</constant>
<constant name="TEXTURE_FILTER_MAX" value="7" enum="TextureFilter">
diff --git a/doc/classes/CanvasLayer.xml b/doc/classes/CanvasLayer.xml
index ff2c3a8855..555137ac45 100644
--- a/doc/classes/CanvasLayer.xml
+++ b/doc/classes/CanvasLayer.xml
@@ -35,11 +35,11 @@
<member name="custom_viewport" type="Node" setter="set_custom_viewport" getter="get_custom_viewport">
The custom [Viewport] node assigned to the [CanvasLayer]. If [code]null[/code], uses the default viewport instead.
</member>
- <member name="follow_viewport_enable" type="bool" setter="set_follow_viewport" getter="is_following_viewport" default="false">
+ <member name="follow_viewport_enabled" type="bool" setter="set_follow_viewport" getter="is_following_viewport" default="false">
Sets the layer to follow the viewport in order to simulate a pseudo 3D effect.
</member>
<member name="follow_viewport_scale" type="float" setter="set_follow_viewport_scale" getter="get_follow_viewport_scale" default="1.0">
- Scales the layer when using [member follow_viewport_enable]. Layers moving into the foreground should have increasing scales, while layers moving into the background should have decreasing scales.
+ Scales the layer when using [member follow_viewport_enabled]. Layers moving into the foreground should have increasing scales, while layers moving into the background should have decreasing scales.
</member>
<member name="layer" type="int" setter="set_layer" getter="get_layer" default="1">
Layer index for draw order. Lower values are drawn first.
diff --git a/doc/classes/CharacterBody2D.xml b/doc/classes/CharacterBody2D.xml
index 95612de284..2d169904f7 100644
--- a/doc/classes/CharacterBody2D.xml
+++ b/doc/classes/CharacterBody2D.xml
@@ -140,12 +140,6 @@
</method>
</methods>
<members>
- <member name="collision/safe_margin" type="float" setter="set_safe_margin" getter="get_safe_margin" default="0.08">
- Extra margin used for collision recovery when calling [method move_and_slide].
- If the body is at least this close to another body, it will consider them to be colliding and will be pushed away before performing the actual motion.
- A higher value means it's more flexible for detecting collision, which helps with consistently detecting walls and floors.
- A lower value forces the collision algorithm to use more exact detection, so it can be used in cases that specifically require precision, e.g at very low scale to avoid visible jittering, or for stability with a stack of character bodies.
- </member>
<member name="floor_block_on_wall" type="bool" setter="set_floor_block_on_wall_enabled" getter="is_floor_block_on_wall_enabled" default="true">
If [code]true[/code], the body will be able to move on the floor only. This option avoids to be able to walk on walls, it will however allow to slide down along them.
</member>
@@ -170,15 +164,21 @@
<member name="motion_mode" type="int" setter="set_motion_mode" getter="get_motion_mode" enum="CharacterBody2D.MotionMode" default="0">
Sets the motion mode which defines the behavior of [method move_and_slide]. See [enum MotionMode] constants for available modes.
</member>
- <member name="moving_platform_apply_velocity_on_leave" type="int" setter="set_moving_platform_apply_velocity_on_leave" getter="get_moving_platform_apply_velocity_on_leave" enum="CharacterBody2D.MovingPlatformApplyVelocityOnLeave" default="0">
- Sets the behavior to apply when you leave a moving platform. By default, to be physically accurate, when you leave the last platform velocity is applied. See [enum MovingPlatformApplyVelocityOnLeave] constants for available behavior.
- </member>
- <member name="moving_platform_floor_layers" type="int" setter="set_moving_platform_floor_layers" getter="get_moving_platform_floor_layers" default="4294967295">
+ <member name="platform_floor_layers" type="int" setter="set_platform_floor_layers" getter="get_platform_floor_layers" default="4294967295">
Collision layers that will be included for detecting floor bodies that will act as moving platforms to be followed by the [CharacterBody2D]. By default, all floor bodies are detected and propagate their velocity.
</member>
- <member name="moving_platform_wall_layers" type="int" setter="set_moving_platform_wall_layers" getter="get_moving_platform_wall_layers" default="0">
+ <member name="platform_on_leave" type="int" setter="set_platform_on_leave" getter="get_platform_on_leave" enum="CharacterBody2D.PlatformOnLeave" default="0">
+ Sets the behavior to apply when you leave a moving platform. By default, to be physically accurate, when you leave the last platform velocity is applied. See [enum PlatformOnLeave] constants for available behavior.
+ </member>
+ <member name="platform_wall_layers" type="int" setter="set_platform_wall_layers" getter="get_platform_wall_layers" default="0">
Collision layers that will be included for detecting wall bodies that will act as moving platforms to be followed by the [CharacterBody2D]. By default, all wall bodies are ignored.
</member>
+ <member name="safe_margin" type="float" setter="set_safe_margin" getter="get_safe_margin" default="0.08">
+ Extra margin used for collision recovery when calling [method move_and_slide].
+ If the body is at least this close to another body, it will consider them to be colliding and will be pushed away before performing the actual motion.
+ A higher value means it's more flexible for detecting collision, which helps with consistently detecting walls and floors.
+ A lower value forces the collision algorithm to use more exact detection, so it can be used in cases that specifically require precision, e.g at very low scale to avoid visible jittering, or for stability with a stack of character bodies.
+ </member>
<member name="slide_on_ceiling" type="bool" setter="set_slide_on_ceiling_enabled" getter="is_slide_on_ceiling_enabled" default="true">
If [code]true[/code], during a jump against the ceiling, the body will slide, if [code]false[/code] it will be stopped and will fall vertically.
</member>
@@ -199,13 +199,13 @@
<constant name="MOTION_MODE_FLOATING" value="1" enum="MotionMode">
Apply when there is no notion of floor or ceiling. All collisions will be reported as [code]on_wall[/code]. In this mode, when you slide, the speed will always be constant. This mode is suitable for top-down games.
</constant>
- <constant name="PLATFORM_VEL_ON_LEAVE_ALWAYS" value="0" enum="MovingPlatformApplyVelocityOnLeave">
+ <constant name="PLATFORM_ON_LEAVE_ADD_VELOCITY" value="0" enum="PlatformOnLeave">
Add the last platform velocity to the [member velocity] when you leave a moving platform.
</constant>
- <constant name="PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY" value="1" enum="MovingPlatformApplyVelocityOnLeave">
+ <constant name="PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY" value="1" enum="PlatformOnLeave">
Add the last platform velocity to the [member velocity] when you leave a moving platform, but any downward motion is ignored. It's useful to keep full jump height even when the platform is moving down.
</constant>
- <constant name="PLATFORM_VEL_ON_LEAVE_NEVER" value="2" enum="MovingPlatformApplyVelocityOnLeave">
+ <constant name="PLATFORM_ON_LEAVE_DO_NOTHING" value="2" enum="PlatformOnLeave">
Do nothing when leaving a platform.
</constant>
</constants>
diff --git a/doc/classes/CharacterBody3D.xml b/doc/classes/CharacterBody3D.xml
index deb93253ea..cbcd6b3af7 100644
--- a/doc/classes/CharacterBody3D.xml
+++ b/doc/classes/CharacterBody3D.xml
@@ -125,12 +125,6 @@
</method>
</methods>
<members>
- <member name="collision/safe_margin" type="float" setter="set_safe_margin" getter="get_safe_margin" default="0.001">
- Extra margin used for collision recovery when calling [method move_and_slide].
- If the body is at least this close to another body, it will consider them to be colliding and will be pushed away before performing the actual motion.
- A higher value means it's more flexible for detecting collision, which helps with consistently detecting walls and floors.
- A lower value forces the collision algorithm to use more exact detection, so it can be used in cases that specifically require precision, e.g at very low scale to avoid visible jittering, or for stability with a stack of character bodies.
- </member>
<member name="floor_block_on_wall" type="bool" setter="set_floor_block_on_wall_enabled" getter="is_floor_block_on_wall_enabled" default="true">
If [code]true[/code], the body will be able to move on the floor only. This option avoids to be able to walk on walls, it will however allow to slide down along them.
</member>
@@ -155,15 +149,21 @@
<member name="motion_mode" type="int" setter="set_motion_mode" getter="get_motion_mode" enum="CharacterBody3D.MotionMode" default="0">
Sets the motion mode which defines the behavior of [method move_and_slide]. See [enum MotionMode] constants for available modes.
</member>
- <member name="moving_platform_apply_velocity_on_leave" type="int" setter="set_moving_platform_apply_velocity_on_leave" getter="get_moving_platform_apply_velocity_on_leave" enum="CharacterBody3D.MovingPlatformApplyVelocityOnLeave" default="0">
- Sets the behavior to apply when you leave a moving platform. By default, to be physically accurate, when you leave the last platform velocity is applied. See [enum MovingPlatformApplyVelocityOnLeave] constants for available behavior.
- </member>
- <member name="moving_platform_floor_layers" type="int" setter="set_moving_platform_floor_layers" getter="get_moving_platform_floor_layers" default="4294967295">
+ <member name="platform_floor_layers" type="int" setter="set_platform_floor_layers" getter="get_platform_floor_layers" default="4294967295">
Collision layers that will be included for detecting floor bodies that will act as moving platforms to be followed by the [CharacterBody3D]. By default, all floor bodies are detected and propagate their velocity.
</member>
- <member name="moving_platform_wall_layers" type="int" setter="set_moving_platform_wall_layers" getter="get_moving_platform_wall_layers" default="0">
+ <member name="platform_on_leave" type="int" setter="set_platform_on_leave" getter="get_platform_on_leave" enum="CharacterBody3D.PlatformOnLeave" default="0">
+ Sets the behavior to apply when you leave a moving platform. By default, to be physically accurate, when you leave the last platform velocity is applied. See [enum PlatformOnLeave] constants for available behavior.
+ </member>
+ <member name="platform_wall_layers" type="int" setter="set_platform_wall_layers" getter="get_platform_wall_layers" default="0">
Collision layers that will be included for detecting wall bodies that will act as moving platforms to be followed by the [CharacterBody3D]. By default, all wall bodies are ignored.
</member>
+ <member name="safe_margin" type="float" setter="set_safe_margin" getter="get_safe_margin" default="0.001">
+ Extra margin used for collision recovery when calling [method move_and_slide].
+ If the body is at least this close to another body, it will consider them to be colliding and will be pushed away before performing the actual motion.
+ A higher value means it's more flexible for detecting collision, which helps with consistently detecting walls and floors.
+ A lower value forces the collision algorithm to use more exact detection, so it can be used in cases that specifically require precision, e.g at very low scale to avoid visible jittering, or for stability with a stack of character bodies.
+ </member>
<member name="slide_on_ceiling" type="bool" setter="set_slide_on_ceiling_enabled" getter="is_slide_on_ceiling_enabled" default="true">
If [code]true[/code], during a jump against the ceiling, the body will slide, if [code]false[/code] it will be stopped and will fall vertically.
</member>
@@ -184,13 +184,13 @@
<constant name="MOTION_MODE_FLOATING" value="1" enum="MotionMode">
Apply when there is no notion of floor or ceiling. All collisions will be reported as [code]on_wall[/code]. In this mode, when you slide, the speed will always be constant. This mode is suitable for games without ground like space games.
</constant>
- <constant name="PLATFORM_VEL_ON_LEAVE_ALWAYS" value="0" enum="MovingPlatformApplyVelocityOnLeave">
+ <constant name="PLATFORM_ON_LEAVE_ADD_VELOCITY" value="0" enum="PlatformOnLeave">
Add the last platform velocity to the [member velocity] when you leave a moving platform.
</constant>
- <constant name="PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY" value="1" enum="MovingPlatformApplyVelocityOnLeave">
+ <constant name="PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY" value="1" enum="PlatformOnLeave">
Add the last platform velocity to the [member velocity] when you leave a moving platform, but any downward motion is ignored. It's useful to keep full jump height even when the platform is moving down.
</constant>
- <constant name="PLATFORM_VEL_ON_LEAVE_NEVER" value="2" enum="MovingPlatformApplyVelocityOnLeave">
+ <constant name="PLATFORM_ON_LEAVE_DO_NOTHING" value="2" enum="PlatformOnLeave">
Do nothing when leaving a platform.
</constant>
</constants>
diff --git a/doc/classes/CheckBox.xml b/doc/classes/CheckBox.xml
index 6483faf763..d39b75ae52 100644
--- a/doc/classes/CheckBox.xml
+++ b/doc/classes/CheckBox.xml
@@ -39,7 +39,7 @@
The vertical offset used when rendering the check icons (in pixels).
</theme_item>
<theme_item name="h_separation" data_type="constant" type="int" default="4">
- The separation between the check icon and the text (in pixels).
+ The separation between the check icon and the text (in pixels). Negative values will be treated as [code]0[/code] when used.
</theme_item>
<theme_item name="outline_size" data_type="constant" type="int" default="0">
The size of the text outline.
diff --git a/doc/classes/CheckButton.xml b/doc/classes/CheckButton.xml
index 51b0411f4e..f49da69926 100644
--- a/doc/classes/CheckButton.xml
+++ b/doc/classes/CheckButton.xml
@@ -39,7 +39,7 @@
The vertical offset used when rendering the toggle icons (in pixels).
</theme_item>
<theme_item name="h_separation" data_type="constant" type="int" default="4">
- The separation between the toggle icon and the text (in pixels).
+ The separation between the toggle icon and the text (in pixels). Negative values will be treated as [code]0[/code] when used.
</theme_item>
<theme_item name="outline_size" data_type="constant" type="int" default="0">
The size of the text outline.
diff --git a/doc/classes/ClassDB.xml b/doc/classes/ClassDB.xml
index 90ce52fdb0..58a536406f 100644
--- a/doc/classes/ClassDB.xml
+++ b/doc/classes/ClassDB.xml
@@ -66,7 +66,7 @@
</description>
</method>
<method name="class_get_method_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="class" type="StringName" />
<param index="1" name="no_inheritance" type="bool" default="false" />
<description>
@@ -83,7 +83,7 @@
</description>
</method>
<method name="class_get_property_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="class" type="StringName" />
<param index="1" name="no_inheritance" type="bool" default="false" />
<description>
@@ -99,7 +99,7 @@
</description>
</method>
<method name="class_get_signal_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="class" type="StringName" />
<param index="1" name="no_inheritance" type="bool" default="false" />
<description>
diff --git a/doc/classes/CodeEdit.xml b/doc/classes/CodeEdit.xml
index 5277df399e..ca482a39e0 100644
--- a/doc/classes/CodeEdit.xml
+++ b/doc/classes/CodeEdit.xml
@@ -18,7 +18,7 @@
</description>
</method>
<method name="_filter_code_completion_candidates" qualifiers="virtual const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="candidates" type="Dictionary[]" />
<description>
Override this method to define what items in [param candidates] should be displayed.
@@ -159,13 +159,13 @@
</description>
</method>
<method name="get_bookmarked_lines" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<description>
Gets all bookmarked lines.
</description>
</method>
<method name="get_breakpointed_lines" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<description>
Gets all breakpointed lines.
</description>
@@ -226,7 +226,7 @@
</description>
</method>
<method name="get_executing_lines" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<description>
Gets all executing lines.
</description>
@@ -482,7 +482,7 @@
Prefixes to trigger an automatic indent.
</member>
<member name="indent_size" type="int" setter="set_indent_size" getter="get_indent_size" default="4">
- Size of tabs, if [code]indent_use_spaces[/code] is enabled the amount of spaces to use.
+ Size of tabs, if [code]indent_use_spaces[/code] is enabled the number of spaces to use.
</member>
<member name="indent_use_spaces" type="bool" setter="set_indent_using_spaces" getter="is_indent_using_spaces" default="false">
Use spaces instead of tabs for indentation.
diff --git a/doc/classes/CollisionObject2D.xml b/doc/classes/CollisionObject2D.xml
index 4353d97597..67d5a667e8 100644
--- a/doc/classes/CollisionObject2D.xml
+++ b/doc/classes/CollisionObject2D.xml
@@ -55,7 +55,7 @@
</description>
</method>
<method name="get_shape_owners">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<description>
Returns an [Array] of [code]owner_id[/code] identifiers. You can use these ids in other methods that take [code]owner_id[/code] as an argument.
</description>
@@ -206,6 +206,9 @@
The physics layers this CollisionObject2D scans. Collision objects can scan one or more of 32 different layers. See also [member collision_layer].
[b]Note:[/b] Object A can detect a contact with object B only if object B is in any of the layers that object A scans. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</member>
+ <member name="collision_priority" type="float" setter="set_collision_priority" getter="get_collision_priority" default="1.0">
+ The priority used to solve colliding when occurring penetration. The higher the priority is, the lower the penetration into the object will be. This can for example be used to prevent the player from breaking through the boundaries of a level.
+ </member>
<member name="disable_mode" type="int" setter="set_disable_mode" getter="get_disable_mode" enum="CollisionObject2D.DisableMode" default="0">
Defines the behavior in physics when [member Node.process_mode] is set to [constant Node.PROCESS_MODE_DISABLED]. See [enum DisableMode] for more details about the different modes.
</member>
diff --git a/doc/classes/CollisionObject3D.xml b/doc/classes/CollisionObject3D.xml
index f9e28824df..4d10a33032 100644
--- a/doc/classes/CollisionObject3D.xml
+++ b/doc/classes/CollisionObject3D.xml
@@ -49,7 +49,7 @@
</description>
</method>
<method name="get_shape_owners">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<description>
Returns an [Array] of [code]owner_id[/code] identifiers. You can use these ids in other methods that take [code]owner_id[/code] as an argument.
</description>
@@ -177,6 +177,9 @@
The physics layers this CollisionObject3D [b]scans[/b]. Collision objects can scan one or more of 32 different layers. See also [member collision_layer].
[b]Note:[/b] Object A can detect a contact with object B only if object B is in any of the layers that object A scans. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</member>
+ <member name="collision_priority" type="float" setter="set_collision_priority" getter="get_collision_priority" default="1.0">
+ The priority used to solve colliding when occurring penetration. The higher the priority is, the lower the penetration into the object will be. This can for example be used to prevent the player from breaking through the boundaries of a level.
+ </member>
<member name="disable_mode" type="int" setter="set_disable_mode" getter="get_disable_mode" enum="CollisionObject3D.DisableMode" default="0">
Defines the behavior in physics when [member Node.process_mode] is set to [constant Node.PROCESS_MODE_DISABLED]. See [enum DisableMode] for more details about the different modes.
</member>
diff --git a/doc/classes/CollisionShape2D.xml b/doc/classes/CollisionShape2D.xml
index 246e0e8663..fa8fbd0d3e 100644
--- a/doc/classes/CollisionShape2D.xml
+++ b/doc/classes/CollisionShape2D.xml
@@ -4,7 +4,8 @@
Node that represents collision shape data in 2D space.
</brief_description>
<description>
- Editor facility for creating and editing collision shapes in 2D space. You can use this node to represent all sorts of collision shapes, for example, add this to an [Area2D] to give it a detection shape, or add it to a [PhysicsBody2D] to create a solid object. [b]IMPORTANT[/b]: this is an Editor-only helper to create shapes, use [method CollisionObject2D.shape_owner_get_shape] to get the actual shape.
+ Editor facility for creating and editing collision shapes in 2D space. Set the [member shape] property to configure the shape. [b]IMPORTANT[/b]: this is an Editor-only helper to create shapes, use [method CollisionObject2D.shape_owner_get_shape] to get the actual shape.
+ You can use this node to represent all sorts of collision shapes, for example, add this to an [Area2D] to give it a detection shape, or add it to a [PhysicsBody2D] to create a solid object.
</description>
<tutorials>
<link title="Physics introduction">$DOCS_URL/tutorials/physics/physics_introduction.html</link>
diff --git a/doc/classes/CollisionShape3D.xml b/doc/classes/CollisionShape3D.xml
index c8423dac9e..304b46ba27 100644
--- a/doc/classes/CollisionShape3D.xml
+++ b/doc/classes/CollisionShape3D.xml
@@ -4,7 +4,8 @@
Node that represents collision shape data in 3D space.
</brief_description>
<description>
- Editor facility for creating and editing collision shapes in 3D space. You can use this node to represent all sorts of collision shapes, for example, add this to an [Area3D] to give it a detection shape, or add it to a [PhysicsBody3D] to create a solid object. [b]IMPORTANT[/b]: this is an Editor-only helper to create shapes, use [method CollisionObject3D.shape_owner_get_shape] to get the actual shape.
+ Editor facility for creating and editing collision shapes in 3D space. Set the [member shape] property to configure the shape. [b]IMPORTANT[/b]: this is an Editor-only helper to create shapes, use [method CollisionObject3D.shape_owner_get_shape] to get the actual shape.
+ You can use this node to represent all sorts of collision shapes, for example, add this to an [Area3D] to give it a detection shape, or add it to a [PhysicsBody3D] to create a solid object.
</description>
<tutorials>
<link title="Physics introduction">$DOCS_URL/tutorials/physics/physics_introduction.html</link>
diff --git a/doc/classes/ConcavePolygonShape2D.xml b/doc/classes/ConcavePolygonShape2D.xml
index f3c245c229..902993e439 100644
--- a/doc/classes/ConcavePolygonShape2D.xml
+++ b/doc/classes/ConcavePolygonShape2D.xml
@@ -7,6 +7,7 @@
2D concave polygon shape to be added as a [i]direct[/i] child of a [PhysicsBody2D] or [Area2D] using a [CollisionShape2D] node. It is made out of segments and is optimal for complex polygonal concave collisions. However, it is not advised to use for [RigidDynamicBody2D] nodes. A CollisionPolygon2D in convex decomposition mode (solids) or several convex objects are advised for that instead. Otherwise, a concave polygon 2D shape is better for static collisions.
The main difference between a [ConvexPolygonShape2D] and a [ConcavePolygonShape2D] is that a concave polygon assumes it is concave and uses a more complex method of collision detection, and a convex one forces itself to be convex to speed up collision detection.
[b]Performance:[/b] Due to its complexity, [ConcavePolygonShape2D] is the slowest collision shape to check collisions against. Its use should generally be limited to level geometry. For convex geometry, using [ConvexPolygonShape2D] will perform better. For dynamic physics bodies that need concave collision, several [ConvexPolygonShape2D]s can be used to represent its collision by using convex decomposition; see [ConvexPolygonShape2D]'s documentation for instructions. However, consider using primitive collision shapes such as [CircleShape2D] or [RectangleShape2D] first.
+ [b]Warning:[/b] Using this shape for an [Area2D] (via a [CollisionShape2D] node) may give unexpected results: the area will only detect collisions with the segments in the [ConcavePolygonShape2D] (and not with any "inside" of the shape, for example).
</description>
<tutorials>
</tutorials>
diff --git a/doc/classes/ConcavePolygonShape3D.xml b/doc/classes/ConcavePolygonShape3D.xml
index 6a54b4bda7..d22793e52c 100644
--- a/doc/classes/ConcavePolygonShape3D.xml
+++ b/doc/classes/ConcavePolygonShape3D.xml
@@ -7,6 +7,7 @@
3D concave polygon shape resource (also called "trimesh") to be added as a [i]direct[/i] child of a [PhysicsBody3D] or [Area3D] using a [CollisionShape3D] node. This shape is created by feeding a list of triangles. Despite its name, [ConcavePolygonShape3D] can also store convex polygon shapes. However, unlike [ConvexPolygonShape3D], [ConcavePolygonShape3D] is [i]not[/i] limited to storing convex shapes exclusively.
[b]Note:[/b] When used for collision, [ConcavePolygonShape3D] is intended to work with static [PhysicsBody3D] nodes like [StaticBody3D] and will not work with [CharacterBody3D] or [RigidDynamicBody3D] with a mode other than Static.
[b]Performance:[/b] Due to its complexity, [ConcavePolygonShape3D] is the slowest collision shape to check collisions against. Its use should generally be limited to level geometry. For convex geometry, using [ConvexPolygonShape3D] will perform better. For dynamic physics bodies that need concave collision, several [ConvexPolygonShape3D]s can be used to represent its collision by using convex decomposition; see [ConvexPolygonShape3D]'s documentation for instructions. However, consider using primitive collision shapes such as [SphereShape3D] or [BoxShape3D] first.
+ [b]Warning:[/b] Using this shape for an [Area3D] (via a [CollisionShape3D] node, created e.g. by using the [i]Create Trimesh Collision Sibling[/i] option in the [i]Mesh[/i] menu that appears when selecting a [MeshInstance3D] node) may give unexpected results: the area will only detect collisions with the triangle faces in the [ConcavePolygonShape3D] (and not with any "inside" of the shape, for example); moreover it will only detect all such collisions if [member backface_collision] is [code]true[/code].
</description>
<tutorials>
<link title="3D Physics Tests Demo">https://godotengine.org/asset-library/asset/675</link>
diff --git a/doc/classes/ConeTwistJoint3D.xml b/doc/classes/ConeTwistJoint3D.xml
index 5f2ad109f2..1cfe9d197d 100644
--- a/doc/classes/ConeTwistJoint3D.xml
+++ b/doc/classes/ConeTwistJoint3D.xml
@@ -36,13 +36,13 @@
<member name="softness" type="float" setter="set_param" getter="get_param" default="0.8">
The ease with which the joint starts to twist. If it's too low, it takes more force to start twisting the joint.
</member>
- <member name="swing_span" type="float" setter="_set_swing_span" getter="_get_swing_span" default="45.0">
+ <member name="swing_span" type="float" setter="set_param" getter="get_param" default="0.785398">
Swing is rotation from side to side, around the axis perpendicular to the twist axis.
The swing span defines, how much rotation will not get corrected along the swing axis.
Could be defined as looseness in the [ConeTwistJoint3D].
If below 0.05, this behavior is locked.
</member>
- <member name="twist_span" type="float" setter="_set_twist_span" getter="_get_twist_span" default="180.0">
+ <member name="twist_span" type="float" setter="set_param" getter="get_param" default="3.14159">
Twist is the rotation around the twist axis, this value defined how far the joint can twist.
Twist is locked if below 0.05.
</member>
diff --git a/doc/classes/Control.xml b/doc/classes/Control.xml
index 30d34e4f4d..b7a9ae235e 100644
--- a/doc/classes/Control.xml
+++ b/doc/classes/Control.xml
@@ -196,7 +196,7 @@
</description>
</method>
<method name="_structured_text_parser" qualifiers="virtual const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="args" type="Array" />
<param index="1" name="text" type="String" />
<description>
diff --git a/doc/classes/DisplayServer.xml b/doc/classes/DisplayServer.xml
index cb2474384a..bcad75215a 100644
--- a/doc/classes/DisplayServer.xml
+++ b/doc/classes/DisplayServer.xml
@@ -105,7 +105,7 @@
</description>
</method>
<method name="get_display_cutouts" qualifiers="const">
- <return type="Array" />
+ <return type="Rect2[]" />
<description>
Returns an [Array] of [Rect2], each of which is the bounding rectangle for a display cutout or notch. These are non-functional areas on edge-to-edge screens used by cameras and sensors. Returns an empty array if the device does not have cutouts. See also [method get_display_safe_area].
[b]Note:[/b] Currently only implemented on Android. Other platforms will return an empty array even if they do have display cutouts or notches.
@@ -144,7 +144,7 @@
</description>
</method>
<method name="global_menu_add_check_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="label" type="String" />
<param index="2" name="callback" type="Callable" />
@@ -153,16 +153,17 @@
<param index="5" name="index" type="int" default="-1" />
<description>
Adds a new checkable item with text [param label] to the global menu with ID [param menu_root].
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_icon_check_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="icon" type="Texture2D" />
<param index="2" name="label" type="String" />
@@ -172,16 +173,17 @@
<param index="6" name="index" type="int" default="-1" />
<description>
Adds a new checkable item with text [param label] and icon [param icon] to the global menu with ID [param menu_root].
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_icon_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="icon" type="Texture2D" />
<param index="2" name="label" type="String" />
@@ -191,16 +193,17 @@
<param index="6" name="index" type="int" default="-1" />
<description>
Adds a new item with text [param label] and icon [param icon] to the global menu with ID [param menu_root].
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_icon_radio_check_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="icon" type="Texture2D" />
<param index="2" name="label" type="String" />
@@ -210,17 +213,18 @@
<param index="6" name="index" type="int" default="-1" />
<description>
Adds a new radio-checkable item with text [param label] and icon [param icon] to the global menu with ID [param menu_root].
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] Radio-checkable items just display a checkmark, but don't have any built-in checking behavior and must be checked/unchecked manually. See [method global_menu_set_item_checked] for more info on how to control it.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="label" type="String" />
<param index="2" name="callback" type="Callable" />
@@ -229,16 +233,17 @@
<param index="5" name="index" type="int" default="-1" />
<description>
Adds a new item with text [param label] to the global menu with ID [param menu_root].
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_multistate_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="labe" type="String" />
<param index="2" name="max_states" type="int" />
@@ -250,16 +255,18 @@
<description>
Adds a new item with text [param labe] to the global menu with ID [param menu_root].
Contrarily to normal binary items, multistate items can have more than two states, as defined by [param max_states]. Each press or activate of the item will increase the state by one. The default value is defined by [param default_state].
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
+ [b]Note:[/b] By default, there's no indication of the current item state, it should be changed manually.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_radio_check_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="label" type="String" />
<param index="2" name="callback" type="Callable" />
@@ -268,41 +275,44 @@
<param index="5" name="index" type="int" default="-1" />
<description>
Adds a new radio-checkable item with text [param label] to the global menu with ID [param menu_root].
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] Radio-checkable items just display a checkmark, but don't have any built-in checking behavior and must be checked/unchecked manually. See [method global_menu_set_item_checked] for more info on how to control it.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_separator">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="index" type="int" default="-1" />
<description>
Adds a separator between items to the global menu with ID [param menu_root]. Separators also occupy an index.
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
</method>
<method name="global_menu_add_submenu_item">
- <return type="void" />
+ <return type="int" />
<param index="0" name="menu_root" type="String" />
<param index="1" name="label" type="String" />
<param index="2" name="submenu" type="String" />
<param index="3" name="index" type="int" default="-1" />
<description>
Adds an item that will act as a submenu of the global menu [param menu_root]. The [param submenu] argument is the ID of the global menu root that will be shown when the item is clicked.
+ Returns index of the inserted item, it's not guaranteed to be the same as [param index] value.
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
@@ -315,7 +325,7 @@
[b]Note:[/b] This method is implemented on macOS.
[b]Supported system menu IDs:[/b]
[codeblock]
- "" - Main menu (macOS).
+ "_main" - Main menu (macOS).
"_dock" - Dock popup menu (macOS).
[/codeblock]
</description>
@@ -347,6 +357,15 @@
[b]Note:[/b] This method is implemented on macOS.
</description>
</method>
+ <method name="global_menu_get_item_indentation_level" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="menu_root" type="String" />
+ <param index="1" name="idx" type="int" />
+ <description>
+ Returns the horizontal offset of the item at the given [param idx].
+ [b]Note:[/b] This method is implemented on macOS.
+ </description>
+ </method>
<method name="global_menu_get_item_index_from_tag" qualifiers="const">
<return type="int" />
<param index="0" name="menu_root" type="String" />
@@ -528,6 +547,16 @@
[b]Note:[/b] This method is not supported by macOS "_dock" menu items.
</description>
</method>
+ <method name="global_menu_set_item_indentation_level">
+ <return type="void" />
+ <param index="0" name="menu_root" type="String" />
+ <param index="1" name="idx" type="int" />
+ <param index="2" name="level" type="int" />
+ <description>
+ Sets the horizontal offset of the item at the given [param idx].
+ [b]Note:[/b] This method is implemented on macOS.
+ </description>
+ </method>
<method name="global_menu_set_item_max_states">
<return type="void" />
<param index="0" name="menu_root" type="String" />
@@ -828,7 +857,7 @@
</description>
</method>
<method name="tts_get_voices" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns an [Array] of voice information dictionaries.
Each [Dictionary] contains two [String] entries:
diff --git a/doc/classes/EditorImportPlugin.xml b/doc/classes/EditorImportPlugin.xml
index 3555d2fd48..f7f1d456d0 100644
--- a/doc/classes/EditorImportPlugin.xml
+++ b/doc/classes/EditorImportPlugin.xml
@@ -115,7 +115,7 @@
</tutorials>
<methods>
<method name="_get_import_options" qualifiers="virtual const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="path" type="String" />
<param index="1" name="preset_index" type="int" />
<description>
diff --git a/doc/classes/EditorInterface.xml b/doc/classes/EditorInterface.xml
index 1dd53e1394..49cd715f5e 100644
--- a/doc/classes/EditorInterface.xml
+++ b/doc/classes/EditorInterface.xml
@@ -101,7 +101,7 @@
</description>
</method>
<method name="get_open_scenes" qualifiers="const">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Returns an [Array] with the file paths of the currently opened scenes.
</description>
@@ -166,7 +166,7 @@
</description>
</method>
<method name="make_mesh_previews">
- <return type="Array" />
+ <return type="Texture2D[]" />
<param index="0" name="meshes" type="Array" />
<param index="1" name="preview_size" type="int" />
<description>
@@ -206,6 +206,13 @@
Reloads the scene at the given path.
</description>
</method>
+ <method name="restart_editor">
+ <return type="void" />
+ <param index="0" name="save" type="bool" default="true" />
+ <description>
+ Restarts the editor. This closes the editor and then opens the same project. If [param save] is [code]true[/code], the project will be saved before restarting.
+ </description>
+ </method>
<method name="save_scene">
<return type="int" enum="Error" />
<description>
diff --git a/doc/classes/EditorNode3DGizmo.xml b/doc/classes/EditorNode3DGizmo.xml
index 74870f34db..9ee21fd63b 100644
--- a/doc/classes/EditorNode3DGizmo.xml
+++ b/doc/classes/EditorNode3DGizmo.xml
@@ -129,7 +129,7 @@
<param index="4" name="secondary" type="bool" default="false" />
<description>
Adds a list of handles (points) which can be used to edit the properties of the gizmo's Node3D. The [param ids] argument can be used to specify a custom identifier for each handle, if an empty [code]Array[/code] is passed, the ids will be assigned automatically from the [param handles] argument order.
- The [param secondary] argument marks the added handles as secondary, meaning they will normally have less selection priority than regular handles. When the user is holding the shift key secondary handles will switch to have higher priority than regular handles. This change in priority can be used to place multiple handles at the same point while still giving the user control on their selection.
+ The [param secondary] argument marks the added handles as secondary, meaning they will normally have lower selection priority than regular handles. When the user is holding the shift key secondary handles will switch to have higher priority than regular handles. This change in priority can be used to place multiple handles at the same point while still giving the user control on their selection.
There are virtual methods which will be called upon editing of these handles. Call this method during [method _redraw].
</description>
</method>
diff --git a/doc/classes/EditorPlugin.xml b/doc/classes/EditorPlugin.xml
index a961068b7b..fdd3807b69 100644
--- a/doc/classes/EditorPlugin.xml
+++ b/doc/classes/EditorPlugin.xml
@@ -532,7 +532,7 @@
</description>
</method>
<method name="get_undo_redo">
- <return type="UndoRedo" />
+ <return type="EditorUndoRedoManager" />
<description>
Gets the undo/redo object. Most actions in the editor can be undoable, so use this object to make sure this happens when it's worth it.
</description>
@@ -729,7 +729,7 @@
</constant>
<constant name="CONTAINER_CANVAS_EDITOR_BOTTOM" value="8" enum="CustomControlContainer">
</constant>
- <constant name="CONTAINER_PROPERTY_EDITOR_BOTTOM" value="9" enum="CustomControlContainer">
+ <constant name="CONTAINER_INSPECTOR_BOTTOM" value="9" enum="CustomControlContainer">
</constant>
<constant name="CONTAINER_PROJECT_SETTING_TAB_LEFT" value="10" enum="CustomControlContainer">
</constant>
diff --git a/doc/classes/EditorResourcePicker.xml b/doc/classes/EditorResourcePicker.xml
index c88a7b75b0..4182ab3c16 100644
--- a/doc/classes/EditorResourcePicker.xml
+++ b/doc/classes/EditorResourcePicker.xml
@@ -62,9 +62,9 @@
</signal>
<signal name="resource_selected">
<param index="0" name="resource" type="Resource" />
- <param index="1" name="edit" type="bool" />
+ <param index="1" name="inspect" type="bool" />
<description>
- Emitted when the resource value was set and user clicked to edit it. When [param edit] is [code]true[/code], the signal was caused by the context menu "Edit" option.
+ Emitted when the resource value was set and user clicked to edit it. When [param inspect] is [code]true[/code], the signal was caused by the context menu "Edit" or "Inspect" option.
</description>
</signal>
</signals>
diff --git a/doc/classes/EditorSelection.xml b/doc/classes/EditorSelection.xml
index 9c3e87ddb0..54029c2ccf 100644
--- a/doc/classes/EditorSelection.xml
+++ b/doc/classes/EditorSelection.xml
@@ -31,7 +31,7 @@
</description>
</method>
<method name="get_transformable_selected_nodes">
- <return type="Array" />
+ <return type="Node[]" />
<description>
Gets the list of selected nodes, optimized for transform operations (i.e. moving them, rotating, etc). This list avoids situations where a node is selected and also child/grandchild.
</description>
diff --git a/doc/classes/EditorSettings.xml b/doc/classes/EditorSettings.xml
index 6079cc48c8..7fc9c81985 100644
--- a/doc/classes/EditorSettings.xml
+++ b/doc/classes/EditorSettings.xml
@@ -85,7 +85,7 @@
</description>
</method>
<method name="get_changed_settings" qualifiers="const">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Gets an array of the settings which have been changed since the last save. Note that internally [code]changed_settings[/code] is cleared after a successful save, so generally the most appropriate place to use this method is when processing [constant NOTIFICATION_EDITOR_SETTINGS_CHANGED]
</description>
@@ -132,20 +132,6 @@
Marks the passed editor setting as being changed, see [method get_changed_settings]. Only settings which exist (see [method has_setting]) will be accepted.
</description>
</method>
- <method name="property_can_revert">
- <return type="bool" />
- <param index="0" name="name" type="String" />
- <description>
- Returns [code]true[/code] if the setting specified by [param name] can have its value reverted to the default value, [code]false[/code] otherwise. When this method returns [code]true[/code], a Revert button will display next to the setting in the Editor Settings.
- </description>
- </method>
- <method name="property_get_revert">
- <return type="Variant" />
- <param index="0" name="name" type="String" />
- <description>
- Returns the default value of the setting specified by [param name]. This is the value that would be applied when clicking the Revert button in the Editor Settings.
- </description>
- </method>
<method name="set_builtin_action_override">
<return type="void" />
<param index="0" name="name" type="String" />
@@ -479,15 +465,15 @@
</member>
<member name="interface/editor/code_font_contextual_ligatures" type="int" setter="" getter="">
The font ligatures to enable for the currently configured code font. Not all fonts include support for ligatures.
- [b]Note:[/b] The default editor code font (Hack) does not have contextual ligatures in its font file.
+ [b]Note:[/b] The default editor code font ([url=https://www.jetbrains.com/lp/mono/]JetBrains Mono[/url]) has contextual ligatures in its font file.
</member>
<member name="interface/editor/code_font_custom_opentype_features" type="String" setter="" getter="">
List of custom OpenType features to use, if supported by the currently configured code font. Not all fonts include support for custom OpenType features. The string should follow the OpenType specification.
- [b]Note:[/b] The default editor code font (Hack) does not have custom OpenType features in its font file.
+ [b]Note:[/b] The default editor code font ([url=https://www.jetbrains.com/lp/mono/]JetBrains Mono[/url]) has custom OpenType features in its font file, but there is no documented list yet.
</member>
<member name="interface/editor/code_font_custom_variations" type="String" setter="" getter="">
List of alternative characters to use, if supported by the currently configured code font. Not all fonts include support for custom variations. The string should follow the OpenType specification.
- [b]Note:[/b] The default editor code font (Hack) does not have alternate characters in its font file.
+ [b]Note:[/b] The default editor code font ([url=https://www.jetbrains.com/lp/mono/]JetBrains Mono[/url]) has alternate characters in its font file, but there is no documented list yet.
</member>
<member name="interface/editor/code_font_size" type="int" setter="" getter="">
The size of the font in the script editor. This setting does not impact the font size of the Output panel (see [member run/output/font_size]).
@@ -553,6 +539,10 @@
<member name="interface/editor/unfocused_low_processor_mode_sleep_usec" type="float" setter="" getter="">
When the editor window is unfocused, the amount of sleeping between frames when the low-processor usage mode is enabled (in microseconds). Higher values will result in lower CPU/GPU usage, which can improve battery life on laptops (in addition to improving the running project's performance if the editor has to redraw continuously). However, higher values will result in a less responsive editor. The default value is set to limit the editor to 20 FPS when the editor window is unfocused. See also [member interface/editor/low_processor_mode_sleep_usec].
</member>
+ <member name="interface/editor/use_embedded_menu" type="bool" setter="" getter="">
+ If [code]true[/code], editor main menu is using embedded [MenuBar] instead of system global menu.
+ Specific to the macOS platform.
+ </member>
<member name="interface/inspector/max_array_dictionary_items_per_page" type="int" setter="" getter="">
The number of [Array] or [Dictionary] items to display on each "page" in the inspector. Higher values allow viewing more values per page, but take more time to load. This increased load time is noticeable when selecting nodes that have array or dictionary properties in the editor.
</member>
@@ -710,7 +700,7 @@
If [code]true[/code], draws tab characters as chevrons.
</member>
<member name="text_editor/appearance/whitespace/line_spacing" type="int" setter="" getter="">
- The space to add between lines (in pixels). Greater line spacing can help improve readability at the cost of displaying less lines on screen.
+ The space to add between lines (in pixels). Greater line spacing can help improve readability at the cost of displaying fewer lines on screen.
</member>
<member name="text_editor/behavior/files/auto_reload_scripts_on_external_change" type="bool" setter="" getter="">
If [code]true[/code], automatically reloads scripts in the editor when they have been modified and saved by external editors.
@@ -866,7 +856,7 @@
</member>
<member name="text_editor/theme/highlighting/function_color" type="Color" setter="" getter="">
The script editor's function call color.
- [b]Note:[/b] When using the GDScript syntax highlighter, this is replaced by the function declaration color configured in the syntax theme for function declarations (e.g. [code]func _ready():[/code]).
+ [b]Note:[/b] When using the GDScript syntax highlighter, this is replaced by the function definition color configured in the syntax theme for function definitions (e.g. [code]func _ready():[/code]).
</member>
<member name="text_editor/theme/highlighting/keyword_color" type="Color" setter="" getter="">
The script editor's non-control flow keyword color (used for keywords like [code]var[/code], [code]func[/code], some built-in methods, ...).
diff --git a/doc/classes/EditorSyntaxHighlighter.xml b/doc/classes/EditorSyntaxHighlighter.xml
index 15b730acb4..51f4474fe7 100644
--- a/doc/classes/EditorSyntaxHighlighter.xml
+++ b/doc/classes/EditorSyntaxHighlighter.xml
@@ -17,7 +17,7 @@
</description>
</method>
<method name="_get_supported_languages" qualifiers="virtual const">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Virtual method which can be overridden to return the supported language names.
</description>
diff --git a/doc/classes/EditorUndoRedoManager.xml b/doc/classes/EditorUndoRedoManager.xml
new file mode 100644
index 0000000000..1350e4487c
--- /dev/null
+++ b/doc/classes/EditorUndoRedoManager.xml
@@ -0,0 +1,118 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="EditorUndoRedoManager" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
+ <brief_description>
+ Manages undo history of scenes opened in the editor.
+ </brief_description>
+ <description>
+ [EditorUndoRedoManager] is a manager for [UndoRedo] objects associated with edited scenes. Each scene has its own undo history and [EditorUndoRedoManager] ensures that each action performed in the editor gets associated with a proper scene. For actions not related to scenes ([ProjectSettings] edits, external resources, etc.), a separate global history is used.
+ The usage is mostly the same as [UndoRedo]. You create and commit actions and the manager automatically decides under-the-hood what scenes it belongs to. The scene is deduced based on the first operation in an action, using the object from the operation. The rules are as follows:
+ - If the object is a [Node], use the currently edited scene;
+ - If the object is a built-in resource, use the scene from its path;
+ - If the object is external resource or anything else, use global history.
+ This guessing can sometimes yield false results, so you can provide a custom context object when creating an action.
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="add_do_method" qualifiers="vararg">
+ <return type="void" />
+ <param index="0" name="object" type="Object" />
+ <param index="1" name="method" type="StringName" />
+ <description>
+ Register a method that will be called when the action is committed (i.e. the "do" action).
+ If this is the first operation, the [param object] will be used to deduce target undo history.
+ </description>
+ </method>
+ <method name="add_do_property">
+ <return type="void" />
+ <param index="0" name="object" type="Object" />
+ <param index="1" name="property" type="StringName" />
+ <param index="2" name="value" type="Variant" />
+ <description>
+ Register a property value change for "do".
+ If this is the first operation, the [param object] will be used to deduce target undo history.
+ </description>
+ </method>
+ <method name="add_do_reference">
+ <return type="void" />
+ <param index="0" name="object" type="Object" />
+ <description>
+ Register a reference for "do" that will be erased if the "do" history is lost. This is useful mostly for new nodes created for the "do" call. Do not use for resources.
+ </description>
+ </method>
+ <method name="add_undo_method" qualifiers="vararg">
+ <return type="void" />
+ <param index="0" name="object" type="Object" />
+ <param index="1" name="method" type="StringName" />
+ <description>
+ Register a method that will be called when the action is undone (i.e. the "undo" action).
+ If this is the first operation, the [param object] will be used to deduce target undo history.
+ </description>
+ </method>
+ <method name="add_undo_property">
+ <return type="void" />
+ <param index="0" name="object" type="Object" />
+ <param index="1" name="property" type="StringName" />
+ <param index="2" name="value" type="Variant" />
+ <description>
+ Register a property value change for "undo".
+ If this is the first operation, the [param object] will be used to deduce target undo history.
+ </description>
+ </method>
+ <method name="add_undo_reference">
+ <return type="void" />
+ <param index="0" name="object" type="Object" />
+ <description>
+ Register a reference for "undo" that will be erased if the "undo" history is lost. This is useful mostly for nodes removed with the "do" call (not the "undo" call!).
+ </description>
+ </method>
+ <method name="commit_action">
+ <return type="void" />
+ <param index="0" name="execute" type="bool" default="true" />
+ <description>
+ Commit the action. If [param execute] is true (default), all "do" methods/properties are called/set when this function is called.
+ </description>
+ </method>
+ <method name="create_action">
+ <return type="void" />
+ <param index="0" name="name" type="String" />
+ <param index="1" name="merge_mode" type="int" enum="UndoRedo.MergeMode" default="0" />
+ <param index="2" name="custom_context" type="Object" default="null" />
+ <description>
+ Create a new action. After this is called, do all your calls to [method add_do_method], [method add_undo_method], [method add_do_property], and [method add_undo_property], then commit the action with [method commit_action].
+ The way actions are merged is dictated by the [param merge_mode] argument. See [enum UndoRedo.MergeMode] for details.
+ If [param custom_context] object is provided, it will be used for deducing target history (instead of using the first operation).
+ </description>
+ </method>
+ <method name="get_history_undo_redo" qualifiers="const">
+ <return type="UndoRedo" />
+ <param index="0" name="id" type="int" />
+ <description>
+ Returns the [UndoRedo] object associated with the given history [param id].
+ [param id] above [code]0[/code] are mapped to the opened scene tabs (but it doesn't match their order). [param id] of [code]0[/code] or lower have special meaning (see [enum SpecialHistory]).
+ Best used with [method get_object_history_id]. This method is only provided in case you need some more advanced methods of [UndoRedo] (but keep in mind that directly operating on the [UndoRedo] object might affect editor's stability).
+ </description>
+ </method>
+ <method name="get_object_history_id" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="object" type="Object" />
+ <description>
+ Returns the history ID deduced from the given [param object]. It can be used with [method get_history_undo_redo].
+ </description>
+ </method>
+ <method name="is_committing_action" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if the [EditorUndoRedoManager] is currently committing the action, i.e. running its "do" method or property change (see [method commit_action]).
+ </description>
+ </method>
+ </methods>
+ <constants>
+ <constant name="GLOBAL_HISTORY" value="0" enum="SpecialHistory">
+ Global history not associated with any scene, but with external resources etc.
+ </constant>
+ <constant name="INVALID_HISTORY" value="-99" enum="SpecialHistory">
+ Invalid "null" history. It's a special value, not associated with any object.
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/EditorVCSInterface.xml b/doc/classes/EditorVCSInterface.xml
index cc75861130..89ba79f7d9 100644
--- a/doc/classes/EditorVCSInterface.xml
+++ b/doc/classes/EditorVCSInterface.xml
@@ -17,7 +17,7 @@
</description>
</method>
<method name="get_file_diff">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="file_path" type="String" />
<description>
Returns an [Array] of [Dictionary] objects containing the diff output from the VCS in use, if a VCS addon is initialized, else returns an empty [Array] object. The diff contents also consist of some contextual lines which provide context to the observed line change in the file.
diff --git a/doc/classes/Engine.xml b/doc/classes/Engine.xml
index 2350a1f51b..301a3e55fb 100644
--- a/doc/classes/Engine.xml
+++ b/doc/classes/Engine.xml
@@ -34,7 +34,7 @@
</description>
</method>
<method name="get_copyright_info" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns an Array of copyright information Dictionaries.
[code]name[/code] - String, component name
diff --git a/doc/classes/FontFile.xml b/doc/classes/FontFile.xml
index 0f229ea19a..b9b20dc75b 100644
--- a/doc/classes/FontFile.xml
+++ b/doc/classes/FontFile.xml
@@ -146,7 +146,7 @@
</description>
</method>
<method name="get_glyph_list" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<param index="0" name="cache_index" type="int" />
<param index="1" name="size" type="Vector2i" />
<description>
@@ -199,7 +199,7 @@
</description>
</method>
<method name="get_kerning_list" qualifiers="const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="cache_index" type="int" />
<param index="1" name="size" type="int" />
<description>
@@ -233,7 +233,7 @@
</description>
</method>
<method name="get_size_cache_list" qualifiers="const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="cache_index" type="int" />
<description>
Returns list of the font sizes in the cache. Each size is [code]Vector2i[/code] with font size and outline size.
diff --git a/doc/classes/GPUParticlesCollision3D.xml b/doc/classes/GPUParticlesCollision3D.xml
index 435f9781f0..27e3590e75 100644
--- a/doc/classes/GPUParticlesCollision3D.xml
+++ b/doc/classes/GPUParticlesCollision3D.xml
@@ -7,7 +7,7 @@
Particle collision shapes can be used to make particles stop or bounce against them.
Particle collision shapes in real-time and can be moved, rotated and scaled during gameplay. Unlike attractors, non-uniform scaling of collision shapes is [i]not[/i] supported.
Particle collision shapes can be temporarily disabled by hiding them.
- [b]Note:[/b] [member ParticlesMaterial.collision_enabled] must be [code]true[/code] on the [GPUParticles3D]'s process material for collision to work.
+ [b]Note:[/b] [member ParticlesMaterial.collision_mode] must be [constant ParticlesMaterial.COLLISION_RIGID] or [constant ParticlesMaterial.COLLISION_HIDE_ON_CONTACT] on the [GPUParticles3D]'s process material for collision to work.
[b]Note:[/b] Particle collision only affects [GPUParticles3D], not [CPUParticles3D].
[b]Note:[/b] Particles pushed by a collider that is being moved will not be interpolated, which can result in visible stuttering. This can be alleviated by setting [member GPUParticles3D.fixed_fps] to [code]0[/code] or a value that matches or exceeds the target framerate.
</description>
@@ -15,7 +15,7 @@
</tutorials>
<members>
<member name="cull_mask" type="int" setter="set_cull_mask" getter="get_cull_mask" default="4294967295">
- The particle rendering layers ([member VisualInstance3D.layers]) that will be affected by the collision shape. By default, all particles that have [member ParticlesMaterial.collision_enabled] set to [code]true[/code] will be affected by a collision shape.
+ The particle rendering layers ([member VisualInstance3D.layers]) that will be affected by the collision shape. By default, all particles that have [member ParticlesMaterial.collision_mode] set to [constant ParticlesMaterial.COLLISION_RIGID] or [constant ParticlesMaterial.COLLISION_HIDE_ON_CONTACT] will be affected by a collision shape.
After configuring particle nodes accordingly, specific layers can be unchecked to prevent certain particles from being affected by attractors. For example, this can be used if you're using an attractor as part of a spell effect but don't want the attractor to affect unrelated weather particles at the same position.
Particle attraction can also be disabled on a per-process material basis by setting [member ParticlesMaterial.attractor_interaction_enabled] on the [GPUParticles3D] node.
</member>
diff --git a/doc/classes/GPUParticlesCollisionBox3D.xml b/doc/classes/GPUParticlesCollisionBox3D.xml
index 60d66ca682..65b69c0098 100644
--- a/doc/classes/GPUParticlesCollisionBox3D.xml
+++ b/doc/classes/GPUParticlesCollisionBox3D.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
Box-shaped 3D particle collision shape affecting [GPUParticles3D] nodes.
- [b]Note:[/b] [member ParticlesMaterial.collision_enabled] must be [code]true[/code] on the [GPUParticles3D]'s process material for collision to work.
+ [b]Note:[/b] [member ParticlesMaterial.collision_mode] must be [constant ParticlesMaterial.COLLISION_RIGID] or [constant ParticlesMaterial.COLLISION_HIDE_ON_CONTACT] on the [GPUParticles3D]'s process material for collision to work.
[b]Note:[/b] Particle collision only affects [GPUParticles3D], not [CPUParticles3D].
</description>
<tutorials>
diff --git a/doc/classes/GPUParticlesCollisionHeightField3D.xml b/doc/classes/GPUParticlesCollisionHeightField3D.xml
index 3fcad43efb..72d273112e 100644
--- a/doc/classes/GPUParticlesCollisionHeightField3D.xml
+++ b/doc/classes/GPUParticlesCollisionHeightField3D.xml
@@ -7,7 +7,7 @@
Real-time heightmap-shaped 3D particle attractor affecting [GPUParticles3D] nodes.
Heightmap shapes allow for efficiently representing collisions for convex and concave objects with a single "floor" (such as terrain). This is less flexible than [GPUParticlesCollisionSDF3D], but it doesn't require a baking step.
[GPUParticlesCollisionHeightField3D] can also be regenerated in real-time when it is moved, when the camera moves, or even continuously. This makes [GPUParticlesCollisionHeightField3D] a good choice for weather effects such as rain and snow and games with highly dynamic geometry. However, since heightmaps cannot represent overhangs, [GPUParticlesCollisionHeightField3D] is not suited for indoor particle collision.
- [b]Note:[/b] [member ParticlesMaterial.collision_enabled] must be [code]true[/code] on the [GPUParticles3D]'s process material for collision to work.
+ [b]Note:[/b] [member ParticlesMaterial.collision_mode] must be [constant ParticlesMaterial.COLLISION_RIGID] or [constant ParticlesMaterial.COLLISION_HIDE_ON_CONTACT] on the [GPUParticles3D]'s process material for collision to work.
[b]Note:[/b] Particle collision only affects [GPUParticles3D], not [CPUParticles3D].
</description>
<tutorials>
diff --git a/doc/classes/GPUParticlesCollisionSDF3D.xml b/doc/classes/GPUParticlesCollisionSDF3D.xml
index 29adf4fbc1..0e7640ba89 100644
--- a/doc/classes/GPUParticlesCollisionSDF3D.xml
+++ b/doc/classes/GPUParticlesCollisionSDF3D.xml
@@ -8,7 +8,7 @@
Signed distance fields (SDF) allow for efficiently representing approximate collision shapes for convex and concave objects of any shape. This is more flexible than [GPUParticlesCollisionHeightField3D], but it requires a baking step.
[b]Baking:[/b] The signed distance field texture can be baked by selecting the [GPUParticlesCollisionSDF3D] node in the editor, then clicking [b]Bake SDF[/b] at the top of the 3D viewport. Any [i]visible[/i] [MeshInstance3D]s touching the [member extents] will be taken into account for baking, regardless of their [member GeometryInstance3D.gi_mode].
[b]Note:[/b] Baking a [GPUParticlesCollisionSDF3D]'s [member texture] is only possible within the editor, as there is no bake method exposed for use in exported projects. However, it's still possible to load pre-baked [Texture3D]s into its [member texture] property in an exported project.
- [b]Note:[/b] [member ParticlesMaterial.collision_enabled] must be [code]true[/code] on the [GPUParticles3D]'s process material for collision to work.
+ [b]Note:[/b] [member ParticlesMaterial.collision_mode] must be [constant ParticlesMaterial.COLLISION_RIGID] or [constant ParticlesMaterial.COLLISION_HIDE_ON_CONTACT] on the [GPUParticles3D]'s process material for collision to work.
[b]Note:[/b] Particle collision only affects [GPUParticles3D], not [CPUParticles3D].
</description>
<tutorials>
diff --git a/doc/classes/GPUParticlesCollisionSphere3D.xml b/doc/classes/GPUParticlesCollisionSphere3D.xml
index 6651a732da..bfebe05005 100644
--- a/doc/classes/GPUParticlesCollisionSphere3D.xml
+++ b/doc/classes/GPUParticlesCollisionSphere3D.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
Sphere-shaped 3D particle collision shape affecting [GPUParticles3D] nodes.
- [b]Note:[/b] [member ParticlesMaterial.collision_enabled] must be [code]true[/code] on the [GPUParticles3D]'s process material for collision to work.
+ [b]Note:[/b] [member ParticlesMaterial.collision_mode] must be [constant ParticlesMaterial.COLLISION_RIGID] or [constant ParticlesMaterial.COLLISION_HIDE_ON_CONTACT] on the [GPUParticles3D]'s process material for collision to work.
[b]Note:[/b] Particle collision only affects [GPUParticles3D], not [CPUParticles3D].
</description>
<tutorials>
diff --git a/doc/classes/Generic6DOFJoint3D.xml b/doc/classes/Generic6DOFJoint3D.xml
index 5eec089a6f..e6058b1bf9 100644
--- a/doc/classes/Generic6DOFJoint3D.xml
+++ b/doc/classes/Generic6DOFJoint3D.xml
@@ -102,7 +102,7 @@
<member name="angular_limit_x/force_limit" type="float" setter="set_param_x" getter="get_param_x" default="0.0">
The maximum amount of force that can occur, when rotating around the X axis.
</member>
- <member name="angular_limit_x/lower_angle" type="float" setter="_set_angular_lo_limit_x" getter="_get_angular_lo_limit_x" default="0.0">
+ <member name="angular_limit_x/lower_angle" type="float" setter="set_param_x" getter="get_param_x" default="0.0">
The minimum rotation in negative direction to break loose and rotate around the X axis.
</member>
<member name="angular_limit_x/restitution" type="float" setter="set_param_x" getter="get_param_x" default="0.0">
@@ -111,7 +111,7 @@
<member name="angular_limit_x/softness" type="float" setter="set_param_x" getter="get_param_x" default="0.5">
The speed of all rotations across the X axis.
</member>
- <member name="angular_limit_x/upper_angle" type="float" setter="_set_angular_hi_limit_x" getter="_get_angular_hi_limit_x" default="0.0">
+ <member name="angular_limit_x/upper_angle" type="float" setter="set_param_x" getter="get_param_x" default="0.0">
The minimum rotation in positive direction to break loose and rotate around the X axis.
</member>
<member name="angular_limit_y/damping" type="float" setter="set_param_y" getter="get_param_y" default="1.0">
@@ -126,7 +126,7 @@
<member name="angular_limit_y/force_limit" type="float" setter="set_param_y" getter="get_param_y" default="0.0">
The maximum amount of force that can occur, when rotating around the Y axis.
</member>
- <member name="angular_limit_y/lower_angle" type="float" setter="_set_angular_lo_limit_y" getter="_get_angular_lo_limit_y" default="0.0">
+ <member name="angular_limit_y/lower_angle" type="float" setter="set_param_y" getter="get_param_y" default="0.0">
The minimum rotation in negative direction to break loose and rotate around the Y axis.
</member>
<member name="angular_limit_y/restitution" type="float" setter="set_param_y" getter="get_param_y" default="0.0">
@@ -135,7 +135,7 @@
<member name="angular_limit_y/softness" type="float" setter="set_param_y" getter="get_param_y" default="0.5">
The speed of all rotations across the Y axis.
</member>
- <member name="angular_limit_y/upper_angle" type="float" setter="_set_angular_hi_limit_y" getter="_get_angular_hi_limit_y" default="0.0">
+ <member name="angular_limit_y/upper_angle" type="float" setter="set_param_y" getter="get_param_y" default="0.0">
The minimum rotation in positive direction to break loose and rotate around the Y axis.
</member>
<member name="angular_limit_z/damping" type="float" setter="set_param_z" getter="get_param_z" default="1.0">
@@ -150,7 +150,7 @@
<member name="angular_limit_z/force_limit" type="float" setter="set_param_z" getter="get_param_z" default="0.0">
The maximum amount of force that can occur, when rotating around the Z axis.
</member>
- <member name="angular_limit_z/lower_angle" type="float" setter="_set_angular_lo_limit_z" getter="_get_angular_lo_limit_z" default="0.0">
+ <member name="angular_limit_z/lower_angle" type="float" setter="set_param_z" getter="get_param_z" default="0.0">
The minimum rotation in negative direction to break loose and rotate around the Z axis.
</member>
<member name="angular_limit_z/restitution" type="float" setter="set_param_z" getter="get_param_z" default="0.0">
@@ -159,7 +159,7 @@
<member name="angular_limit_z/softness" type="float" setter="set_param_z" getter="get_param_z" default="0.5">
The speed of all rotations across the Z axis.
</member>
- <member name="angular_limit_z/upper_angle" type="float" setter="_set_angular_hi_limit_z" getter="_get_angular_hi_limit_z" default="0.0">
+ <member name="angular_limit_z/upper_angle" type="float" setter="set_param_z" getter="get_param_z" default="0.0">
The minimum rotation in positive direction to break loose and rotate around the Z axis.
</member>
<member name="angular_motor_x/enabled" type="bool" setter="set_flag_x" getter="get_flag_x" default="false">
diff --git a/doc/classes/Geometry2D.xml b/doc/classes/Geometry2D.xml
index 80d19e22c5..392ca2cabb 100644
--- a/doc/classes/Geometry2D.xml
+++ b/doc/classes/Geometry2D.xml
@@ -10,7 +10,7 @@
</tutorials>
<methods>
<method name="clip_polygons">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polygon_a" type="PackedVector2Array" />
<param index="1" name="polygon_b" type="PackedVector2Array" />
<description>
@@ -19,7 +19,7 @@
</description>
</method>
<method name="clip_polyline_with_polygon">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polyline" type="PackedVector2Array" />
<param index="1" name="polygon" type="PackedVector2Array" />
<description>
@@ -34,7 +34,7 @@
</description>
</method>
<method name="exclude_polygons">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polygon_a" type="PackedVector2Array" />
<param index="1" name="polygon_b" type="PackedVector2Array" />
<description>
@@ -71,7 +71,7 @@
</description>
</method>
<method name="intersect_polygons">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polygon_a" type="PackedVector2Array" />
<param index="1" name="polygon_b" type="PackedVector2Array" />
<description>
@@ -80,7 +80,7 @@
</description>
</method>
<method name="intersect_polyline_with_polygon">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polyline" type="PackedVector2Array" />
<param index="1" name="polygon" type="PackedVector2Array" />
<description>
@@ -130,7 +130,7 @@
</description>
</method>
<method name="merge_polygons">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polygon_a" type="PackedVector2Array" />
<param index="1" name="polygon_b" type="PackedVector2Array" />
<description>
@@ -139,7 +139,7 @@
</description>
</method>
<method name="offset_polygon">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polygon" type="PackedVector2Array" />
<param index="1" name="delta" type="float" />
<param index="2" name="join_type" type="int" enum="Geometry2D.PolyJoinType" default="0" />
@@ -166,7 +166,7 @@
</description>
</method>
<method name="offset_polyline">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="polyline" type="PackedVector2Array" />
<param index="1" name="delta" type="float" />
<param index="2" name="join_type" type="int" enum="Geometry2D.PolyJoinType" default="0" />
diff --git a/doc/classes/Geometry3D.xml b/doc/classes/Geometry3D.xml
index c841842d14..d37b0b7b81 100644
--- a/doc/classes/Geometry3D.xml
+++ b/doc/classes/Geometry3D.xml
@@ -10,14 +10,14 @@
</tutorials>
<methods>
<method name="build_box_planes">
- <return type="Array" />
+ <return type="Plane[]" />
<param index="0" name="extents" type="Vector3" />
<description>
Returns an array with 6 [Plane]s that describe the sides of a box centered at the origin. The box size is defined by [param extents], which represents one (positive) corner of the box (i.e. half its actual size).
</description>
</method>
<method name="build_capsule_planes">
- <return type="Array" />
+ <return type="Plane[]" />
<param index="0" name="radius" type="float" />
<param index="1" name="height" type="float" />
<param index="2" name="sides" type="int" />
@@ -28,7 +28,7 @@
</description>
</method>
<method name="build_cylinder_planes">
- <return type="Array" />
+ <return type="Plane[]" />
<param index="0" name="radius" type="float" />
<param index="1" name="height" type="float" />
<param index="2" name="sides" type="int" />
diff --git a/doc/classes/GraphEdit.xml b/doc/classes/GraphEdit.xml
index 03206fa8ca..e5aa78971e 100644
--- a/doc/classes/GraphEdit.xml
+++ b/doc/classes/GraphEdit.xml
@@ -149,7 +149,7 @@
</description>
</method>
<method name="get_connection_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns an Array containing the list of connections. A connection consists in a structure of the form [code]{ from_port: 0, from: "GraphNode name 0", to_port: 1, to: "GraphNode name 1" }[/code].
</description>
@@ -285,7 +285,7 @@
</signal>
<signal name="connection_drag_started">
<param index="0" name="from" type="String" />
- <param index="1" name="slot" type="String" />
+ <param index="1" name="slot" type="int" />
<param index="2" name="is_output" type="bool" />
<description>
Emitted at the beginning of a connection drag.
diff --git a/doc/classes/HTTPRequest.xml b/doc/classes/HTTPRequest.xml
index 490b918f40..4b098bf585 100644
--- a/doc/classes/HTTPRequest.xml
+++ b/doc/classes/HTTPRequest.xml
@@ -176,7 +176,7 @@
<method name="get_downloaded_bytes" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of bytes this HTTPRequest downloaded.
+ Returns the number of bytes this HTTPRequest downloaded.
</description>
</method>
<method name="get_http_client_status" qualifiers="const">
diff --git a/doc/classes/HingeJoint3D.xml b/doc/classes/HingeJoint3D.xml
index d2547434e7..99524795f9 100644
--- a/doc/classes/HingeJoint3D.xml
+++ b/doc/classes/HingeJoint3D.xml
@@ -47,7 +47,7 @@
<member name="angular_limit/enable" type="bool" setter="set_flag" getter="get_flag" default="false">
If [code]true[/code], the hinges maximum and minimum rotation, defined by [member angular_limit/lower] and [member angular_limit/upper] has effects.
</member>
- <member name="angular_limit/lower" type="float" setter="_set_lower_limit" getter="_get_lower_limit" default="-90.0">
+ <member name="angular_limit/lower" type="float" setter="set_param" getter="get_param" default="-1.5708">
The minimum rotation. Only active if [member angular_limit/enable] is [code]true[/code].
</member>
<member name="angular_limit/relaxation" type="float" setter="set_param" getter="get_param" default="1.0">
@@ -55,7 +55,7 @@
</member>
<member name="angular_limit/softness" type="float" setter="set_param" getter="get_param" default="0.9">
</member>
- <member name="angular_limit/upper" type="float" setter="_set_upper_limit" getter="_get_upper_limit" default="90.0">
+ <member name="angular_limit/upper" type="float" setter="set_param" getter="get_param" default="1.5708">
The maximum rotation. Only active if [member angular_limit/enable] is [code]true[/code].
</member>
<member name="motor/enable" type="bool" setter="set_flag" getter="get_flag" default="false">
diff --git a/doc/classes/IP.xml b/doc/classes/IP.xml
index e476a86a49..1e5e6da513 100644
--- a/doc/classes/IP.xml
+++ b/doc/classes/IP.xml
@@ -24,13 +24,13 @@
</description>
</method>
<method name="get_local_addresses" qualifiers="const">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Returns all the user's current IPv4 and IPv6 addresses as an array.
</description>
</method>
<method name="get_local_interfaces" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns all network adapters as an array.
Each adapter is a dictionary of the form:
@@ -74,7 +74,7 @@
</description>
</method>
<method name="resolve_hostname_addresses">
- <return type="Array" />
+ <return type="PackedStringArray" />
<param index="0" name="host" type="String" />
<param index="1" name="ip_type" type="int" enum="IP.Type" default="3" />
<description>
diff --git a/doc/classes/ImageTexture.xml b/doc/classes/ImageTexture.xml
index c750b540a4..45cbd7ac87 100644
--- a/doc/classes/ImageTexture.xml
+++ b/doc/classes/ImageTexture.xml
@@ -6,20 +6,20 @@
<description>
A [Texture2D] based on an [Image]. For an image to be displayed, an [ImageTexture] has to be created from it using the [method create_from_image] method:
[codeblock]
- var image = Image.load_from_file("res://icon.png")
+ var image = Image.load_from_file("res://icon.svg")
var texture = ImageTexture.create_from_image(image)
$Sprite2D.texture = texture
[/codeblock]
This way, textures can be created at run-time by loading images both from within the editor and externally.
[b]Warning:[/b] Prefer to load imported textures with [method @GDScript.load] over loading them from within the filesystem dynamically with [method Image.load], as it may not work in exported projects:
[codeblock]
- var texture = load("res://icon.png")
+ var texture = load("res://icon.svg")
$Sprite2D.texture = texture
[/codeblock]
This is because images have to be imported as a [CompressedTexture2D] first to be loaded with [method @GDScript.load]. If you'd still like to load an image file just like any other [Resource], import it as an [Image] resource instead, and then load it normally using the [method @GDScript.load] method.
[b]Note:[/b] The image can be retrieved from an imported texture using the [method Texture2D.get_image] method, which returns a copy of the image:
[codeblock]
- var texture = load("res://icon.png")
+ var texture = load("res://icon.svg")
var image : Image = texture.get_image()
[/codeblock]
An [ImageTexture] is not meant to be operated from within the editor interface directly, and is mostly useful for rendering images on screen dynamically via code. If you need to generate images procedurally from within the editor, consider saving and importing images as custom texture resources implementing a new [EditorImportPlugin].
diff --git a/doc/classes/ImporterMesh.xml b/doc/classes/ImporterMesh.xml
index 7a658cb52a..e15cfcd2c0 100644
--- a/doc/classes/ImporterMesh.xml
+++ b/doc/classes/ImporterMesh.xml
@@ -101,7 +101,7 @@
<method name="get_surface_count" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of surfaces that the mesh holds.
+ Returns the number of surfaces that the mesh holds.
</description>
</method>
<method name="get_surface_format" qualifiers="const">
@@ -115,7 +115,7 @@
<return type="int" />
<param index="0" name="surface_idx" type="int" />
<description>
- Returns the amount of lods that the mesh holds on a given surface.
+ Returns the number of lods that the mesh holds on a given surface.
</description>
</method>
<method name="get_surface_lod_indices" qualifiers="const">
diff --git a/doc/classes/InputMap.xml b/doc/classes/InputMap.xml
index d60abd7975..1d7d54f681 100644
--- a/doc/classes/InputMap.xml
+++ b/doc/classes/InputMap.xml
@@ -41,7 +41,7 @@
</description>
</method>
<method name="action_get_events">
- <return type="Array" />
+ <return type="InputEvent[]" />
<param index="0" name="action" type="StringName" />
<description>
Returns an array of [InputEvent]s associated with a given action.
@@ -91,7 +91,7 @@
</description>
</method>
<method name="get_actions">
- <return type="Array" />
+ <return type="StringName[]" />
<description>
Returns an array of all actions in the [InputMap].
</description>
diff --git a/doc/classes/JSON.xml b/doc/classes/JSON.xml
index 49ebb55a52..46e46cc164 100644
--- a/doc/classes/JSON.xml
+++ b/doc/classes/JSON.xml
@@ -10,8 +10,7 @@
[b]Example[/b]
[codeblock]
var data_to_send = ["a", "b", "c"]
- var json = JSON.new()
- var json_string = json.stringify(data_to_send)
+ var json_string = JSON.stringify(data_to_send)
# Save data
# ...
# Retrieve data
@@ -25,6 +24,10 @@
else:
print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
[/codeblock]
+ Alternatively, you can parse string using the static [method parse_string] method, but it doesn't allow to handle errors.
+ [codeblock]
+ var data = JSON.parse_string(json_string) # Returns null if parsing failed.
+ [/codeblock]
</description>
<tutorials>
</tutorials>
@@ -54,9 +57,17 @@
<description>
Attempts to parse the [param json_string] provided.
Returns an [enum Error]. If the parse was successful, it returns [code]OK[/code] and the result can be retrieved using [method get_data]. If unsuccessful, use [method get_error_line] and [method get_error_message] for identifying the source of the failure.
+ Non-static variant of [method parse_string], if you want custom error handling.
+ </description>
+ </method>
+ <method name="parse_string" qualifiers="static">
+ <return type="Variant" />
+ <param index="0" name="json_string" type="String" />
+ <description>
+ Attempts to parse the [param json_string] provided and returns the parsed data. Returns [code]null[/code] if parse failed.
</description>
</method>
- <method name="stringify">
+ <method name="stringify" qualifiers="static">
<return type="String" />
<param index="0" name="data" type="Variant" />
<param index="1" name="indent" type="String" default="&quot;&quot;" />
diff --git a/doc/classes/Joint3D.xml b/doc/classes/Joint3D.xml
index fef8fdf965..a9ca86d269 100644
--- a/doc/classes/Joint3D.xml
+++ b/doc/classes/Joint3D.xml
@@ -10,16 +10,16 @@
<link title="3D Truck Town Demo">https://godotengine.org/asset-library/asset/524</link>
</tutorials>
<members>
- <member name="collision/exclude_nodes" type="bool" setter="set_exclude_nodes_from_collision" getter="get_exclude_nodes_from_collision" default="true">
+ <member name="exclude_nodes_from_collision" type="bool" setter="set_exclude_nodes_from_collision" getter="get_exclude_nodes_from_collision" default="true">
If [code]true[/code], the two bodies of the nodes are not able to collide with each other.
</member>
- <member name="nodes/node_a" type="NodePath" setter="set_node_a" getter="get_node_a" default="NodePath(&quot;&quot;)">
+ <member name="node_a" type="NodePath" setter="set_node_a" getter="get_node_a" default="NodePath(&quot;&quot;)">
The node attached to the first side (A) of the joint.
</member>
- <member name="nodes/node_b" type="NodePath" setter="set_node_b" getter="get_node_b" default="NodePath(&quot;&quot;)">
+ <member name="node_b" type="NodePath" setter="set_node_b" getter="get_node_b" default="NodePath(&quot;&quot;)">
The node attached to the second side (B) of the joint.
</member>
- <member name="solver/priority" type="int" setter="set_solver_priority" getter="get_solver_priority" default="1">
+ <member name="solver_priority" type="int" setter="set_solver_priority" getter="get_solver_priority" default="1">
The priority used to define which solver is executed first for multiple joints. The lower the value, the higher the priority.
</member>
</members>
diff --git a/doc/classes/Label.xml b/doc/classes/Label.xml
index 7353e4df9c..52b2e9a729 100644
--- a/doc/classes/Label.xml
+++ b/doc/classes/Label.xml
@@ -14,7 +14,7 @@
<method name="get_line_count" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of lines of text the Label has.
+ Returns the number of lines of text the Label has.
</description>
</method>
<method name="get_line_height" qualifiers="const">
@@ -62,8 +62,8 @@
</member>
<member name="mouse_filter" type="int" setter="set_mouse_filter" getter="get_mouse_filter" overrides="Control" enum="Control.MouseFilter" default="2" />
<member name="percent_visible" type="float" setter="set_percent_visible" getter="get_percent_visible" default="1.0">
- Limits the amount of visible characters. If you set [code]percent_visible[/code] to 0.5, only up to half of the text's characters will display on screen. Useful to animate the text in a dialog box.
- [b]Note:[/b] Setting this property updates [member visible_characters] based on current [method get_total_character_count].
+ The fraction of characters to display, relative to the total number of characters (see [method get_total_character_count]). If set to [code]1.0[/code], all characters are displayed. If set to [code]0.5[/code], only half of the characters will be displayed. This can be useful when animating the text appearing in a dialog box.
+ [b]Note:[/b] Setting this property updates [member visible_characters] accordingly.
</member>
<member name="size_flags_vertical" type="int" setter="set_v_size_flags" getter="get_v_size_flags" overrides="Control" default="4" />
<member name="structured_text_bidi_override" type="int" setter="set_structured_text_bidi_override" getter="get_structured_text_bidi_override" enum="TextServer.StructuredTextParser" default="0">
@@ -88,8 +88,8 @@
Controls the text's vertical alignment. Supports top, center, bottom, and fill. Set it to one of the [enum VerticalAlignment] constants.
</member>
<member name="visible_characters" type="int" setter="set_visible_characters" getter="get_visible_characters" default="-1">
- Restricts the number of characters to display. Set to -1 to disable.
- [b]Note:[/b] Setting this property updates [member percent_visible] based on current [method get_total_character_count].
+ The number of characters to display. If set to [code]-1[/code], all characters are displayed. This can be useful when animating the text appearing in a dialog box.
+ [b]Note:[/b] Setting this property updates [member percent_visible] accordingly.
</member>
<member name="visible_characters_behavior" type="int" setter="set_visible_characters_behavior" getter="get_visible_characters_behavior" enum="TextServer.VisibleCharactersBehavior" default="0">
Sets the clipping behavior when [member visible_characters] or [member percent_visible] is set. See [enum TextServer.VisibleCharactersBehavior] for more info.
diff --git a/doc/classes/Label3D.xml b/doc/classes/Label3D.xml
index e4dc24d0b5..b741dc6e64 100644
--- a/doc/classes/Label3D.xml
+++ b/doc/classes/Label3D.xml
@@ -54,7 +54,8 @@
Font configuration used to display text.
</member>
<member name="font_size" type="int" setter="set_font_size" getter="get_font_size" default="32">
- Font size of the [Label3D]'s text.
+ Font size of the [Label3D]'s text. To make the font look more detailed when up close, increase [member font_size] while decreasing [member pixel_size] at the same time.
+ Higher font sizes require more time to render new characters, which can cause stuttering during gameplay.
</member>
<member name="horizontal_alignment" type="int" setter="set_horizontal_alignment" getter="get_horizontal_alignment" enum="HorizontalAlignment" default="1">
Controls the text's horizontal alignment. Supports left, center, right, and fill, or justify. Set it to one of the [enum HorizontalAlignment] constants.
@@ -86,7 +87,7 @@
Text outline size.
</member>
<member name="pixel_size" type="float" setter="set_pixel_size" getter="get_pixel_size" default="0.005">
- The size of one pixel's width on the label to scale it in 3D.
+ The size of one pixel's width on the label to scale it in 3D. To make the font look more detailed when up close, increase [member font_size] while decreasing [member pixel_size] at the same time.
</member>
<member name="render_priority" type="int" setter="set_render_priority" getter="get_render_priority" default="0">
Sets the render priority for the text. Higher priority objects will be sorted in front of lower priority objects.
@@ -138,7 +139,7 @@
Represents the size of the [enum DrawFlags] enum.
</constant>
<constant name="ALPHA_CUT_DISABLED" value="0" enum="AlphaCutMode">
- This mode performs standard alpha blending. It can display translucent areas, but transparency sorting issues may be visible when multiple transparent materials are overlapping.
+ This mode performs standard alpha blending. It can display translucent areas, but transparency sorting issues may be visible when multiple transparent materials are overlapping. [member GeometryInstance3D.cast_shadow] has no effect when this transparency mode is used; the [Label3D] will never cast shadows.
</constant>
<constant name="ALPHA_CUT_DISCARD" value="1" enum="AlphaCutMode">
This mode only allows fully transparent or fully opaque pixels. Harsh edges will be visible unless some form of screen-space antialiasing is enabled (see [member ProjectSettings.rendering/anti_aliasing/quality/screen_space_aa]). This mode is also known as [i]alpha testing[/i] or [i]1-bit transparency[/i].
diff --git a/doc/classes/Line2D.xml b/doc/classes/Line2D.xml
index f4bf803554..4547c3589f 100644
--- a/doc/classes/Line2D.xml
+++ b/doc/classes/Line2D.xml
@@ -29,7 +29,7 @@
<method name="get_point_count" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of points in the line.
+ Returns the number of points in the line.
</description>
</method>
<method name="get_point_position" qualifiers="const">
diff --git a/doc/classes/LineEdit.xml b/doc/classes/LineEdit.xml
index 9caaed8377..20703f680c 100644
--- a/doc/classes/LineEdit.xml
+++ b/doc/classes/LineEdit.xml
@@ -183,7 +183,7 @@
Language code used for line-breaking and text shaping algorithms, if left empty current locale is used instead.
</member>
<member name="max_length" type="int" setter="set_max_length" getter="get_max_length" default="0">
- Maximum amount of characters that can be entered inside the [LineEdit]. If [code]0[/code], there is no limit.
+ Maximum number of characters that can be entered inside the [LineEdit]. If [code]0[/code], there is no limit.
When a limit is defined, characters that would exceed [member max_length] are truncated. This happens both for existing [member text] contents when setting the max length, or for new text inserted in the [LineEdit], including pasting. If any input text is truncated, the [signal text_change_rejected] signal is emitted with the truncated substring as parameter.
[b]Example:[/b]
[codeblocks]
@@ -417,7 +417,7 @@
The caret's width in pixels. Greater values can be used to improve accessibility by ensuring the caret is easily visible, or to ensure consistency with a large font size.
</theme_item>
<theme_item name="minimum_character_width" data_type="constant" type="int" default="4">
- Minimum horizontal space for the text (not counting the clear button and content margins). This value is measured in count of 'M' characters (i.e. this amount of 'M' characters can be displayed without scrolling).
+ Minimum horizontal space for the text (not counting the clear button and content margins). This value is measured in count of 'M' characters (i.e. this number of 'M' characters can be displayed without scrolling).
</theme_item>
<theme_item name="outline_size" data_type="constant" type="int" default="0">
The size of the text outline.
diff --git a/doc/classes/Position2D.xml b/doc/classes/Marker2D.xml
index 754fd1fdf1..bf90438bf0 100644
--- a/doc/classes/Position2D.xml
+++ b/doc/classes/Marker2D.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<class name="Position2D" inherits="Node2D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
+<class name="Marker2D" inherits="Node2D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
Generic 2D position hint for editing.
</brief_description>
diff --git a/doc/classes/Position3D.xml b/doc/classes/Marker3D.xml
index d91e0fbfdf..5ad1cdf513 100644
--- a/doc/classes/Position3D.xml
+++ b/doc/classes/Marker3D.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<class name="Position3D" inherits="Node3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
+<class name="Marker3D" inherits="Node3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
Generic 3D position hint for editing.
</brief_description>
diff --git a/doc/classes/MenuBar.xml b/doc/classes/MenuBar.xml
new file mode 100644
index 0000000000..3ef0572e9f
--- /dev/null
+++ b/doc/classes/MenuBar.xml
@@ -0,0 +1,172 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="MenuBar" inherits="Control" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
+ <brief_description>
+ A horizontal menu bar, which displays [PopupMenu]s or system global menu.
+ </brief_description>
+ <description>
+ New items can be created by adding [PopupMenu] nodes to his node.
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="get_menu_count" qualifiers="const">
+ <return type="int" />
+ <description>
+ Returns number of menu items.
+ </description>
+ </method>
+ <method name="get_menu_popup" qualifiers="const">
+ <return type="PopupMenu" />
+ <param index="0" name="menu" type="int" />
+ <description>
+ Returns [PopupMenu] associated with menu item.
+ </description>
+ </method>
+ <method name="get_menu_title" qualifiers="const">
+ <return type="String" />
+ <param index="0" name="menu" type="int" />
+ <description>
+ Returns menu item title.
+ </description>
+ </method>
+ <method name="get_menu_tooltip" qualifiers="const">
+ <return type="String" />
+ <param index="0" name="menu" type="int" />
+ <description>
+ Returns menu item tooltip.
+ </description>
+ </method>
+ <method name="is_menu_disabled" qualifiers="const">
+ <return type="bool" />
+ <param index="0" name="menu" type="int" />
+ <description>
+ Returns [code]true[/code], if menu item is disabled.
+ </description>
+ </method>
+ <method name="is_menu_hidden" qualifiers="const">
+ <return type="bool" />
+ <param index="0" name="menu" type="int" />
+ <description>
+ Returns [code]true[/code], if menu item is hidden.
+ </description>
+ </method>
+ <method name="is_native_menu" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code], if system global menu is supported and used by this [MenuBar].
+ </description>
+ </method>
+ <method name="set_disable_shortcuts">
+ <return type="void" />
+ <param index="0" name="disabled" type="bool" />
+ <description>
+ If [code]true[/code], shortcuts are disabled and cannot be used to trigger the button.
+ </description>
+ </method>
+ <method name="set_menu_disabled">
+ <return type="void" />
+ <param index="0" name="menu" type="int" />
+ <param index="1" name="disabled" type="bool" />
+ <description>
+ If [code]true[/code], menu item is disabled.
+ </description>
+ </method>
+ <method name="set_menu_hidden">
+ <return type="void" />
+ <param index="0" name="menu" type="int" />
+ <param index="1" name="hidden" type="bool" />
+ <description>
+ If [code]true[/code], menu item is hidden.
+ </description>
+ </method>
+ <method name="set_menu_title">
+ <return type="void" />
+ <param index="0" name="menu" type="int" />
+ <param index="1" name="title" type="String" />
+ <description>
+ Sets menu item title.
+ </description>
+ </method>
+ <method name="set_menu_tooltip">
+ <return type="void" />
+ <param index="0" name="menu" type="int" />
+ <param index="1" name="tooltip" type="String" />
+ <description>
+ Sets menu item tooltip.
+ </description>
+ </method>
+ </methods>
+ <members>
+ <member name="flat" type="bool" setter="set_flat" getter="is_flat" default="false">
+ Flat [MenuBar] don't display item decoration.
+ </member>
+ <member name="language" type="String" setter="set_language" getter="get_language" default="&quot;&quot;">
+ Language code used for line-breaking and text shaping algorithms, if left empty current locale is used instead.
+ </member>
+ <member name="prefer_global_menu" type="bool" setter="set_prefer_global_menu" getter="is_prefer_global_menu" default="true">
+ If [code]true[/code], [MenuBar] will use system global menu when supported.
+ </member>
+ <member name="shortcut_context" type="Node" setter="set_shortcut_context" getter="get_shortcut_context">
+ The [Node] which must be a parent of the focused GUI [Control] for the shortcut to be activated. If [code]null[/code], the shortcut can be activated when any control is focused (a global shortcut). This allows shortcuts to be accepted only when the user has a certain area of the GUI focused.
+ </member>
+ <member name="start_index" type="int" setter="set_start_index" getter="get_start_index" default="-1">
+ Position in the global menu to insert first [MenuBar] item at.
+ </member>
+ <member name="switch_on_hover" type="bool" setter="set_switch_on_hover" getter="is_switch_on_hover" default="true">
+ If [code]true[/code], when the cursor hovers above menu item, it will close the current [PopupMenu] and open the other one.
+ </member>
+ <member name="text_direction" type="int" setter="set_text_direction" getter="get_text_direction" enum="Control.TextDirection" default="0">
+ Base text writing direction.
+ </member>
+ </members>
+ <theme_items>
+ <theme_item name="font_color" data_type="color" type="Color" default="Color(0.875, 0.875, 0.875, 1)">
+ Default text [Color] of the menu item.
+ </theme_item>
+ <theme_item name="font_disabled_color" data_type="color" type="Color" default="Color(0.875, 0.875, 0.875, 0.5)">
+ Text [Color] used when the menu item is disabled.
+ </theme_item>
+ <theme_item name="font_focus_color" data_type="color" type="Color" default="Color(0.95, 0.95, 0.95, 1)">
+ Text [Color] used when the menu item is focused. Only replaces the normal text color of the menu item. Disabled, hovered, and pressed states take precedence over this color.
+ </theme_item>
+ <theme_item name="font_hover_color" data_type="color" type="Color" default="Color(0.95, 0.95, 0.95, 1)">
+ Text [Color] used when the menu item is being hovered.
+ </theme_item>
+ <theme_item name="font_hover_pressed_color" data_type="color" type="Color" default="Color(1, 1, 1, 1)">
+ Text [Color] used when the menu item is being hovered and pressed.
+ </theme_item>
+ <theme_item name="font_outline_color" data_type="color" type="Color" default="Color(1, 1, 1, 1)">
+ The tint of text outline of the menu item.
+ </theme_item>
+ <theme_item name="font_pressed_color" data_type="color" type="Color" default="Color(1, 1, 1, 1)">
+ Text [Color] used when the menu item is being pressed.
+ </theme_item>
+ <theme_item name="h_separation" data_type="constant" type="int" default="4">
+ The horizontal space between menu items.
+ </theme_item>
+ <theme_item name="outline_size" data_type="constant" type="int" default="0">
+ The size of the text outline.
+ </theme_item>
+ <theme_item name="font" data_type="font" type="Font">
+ [Font] of the menu item's text.
+ </theme_item>
+ <theme_item name="font_size" data_type="font_size" type="int">
+ Font size of the menu item's text.
+ </theme_item>
+ <theme_item name="disabled" data_type="style" type="StyleBox">
+ [StyleBox] used when the menu item is disabled.
+ </theme_item>
+ <theme_item name="focus" data_type="style" type="StyleBox">
+ [StyleBox] used when the menu item is focused. The [code]focus[/code] [StyleBox] is displayed [i]over[/i] the base [StyleBox], so a partially transparent [StyleBox] should be used to ensure the base [StyleBox] remains visible. A [StyleBox] that represents an outline or an underline works well for this purpose. To disable the focus visual effect, assign a [StyleBoxEmpty] resource. Note that disabling the focus visual effect will harm keyboard/controller navigation usability, so this is not recommended for accessibility reasons.
+ </theme_item>
+ <theme_item name="hover" data_type="style" type="StyleBox">
+ [StyleBox] used when the menu item is being hovered.
+ </theme_item>
+ <theme_item name="normal" data_type="style" type="StyleBox">
+ Default [StyleBox] for the menu item.
+ </theme_item>
+ <theme_item name="pressed" data_type="style" type="StyleBox">
+ [StyleBox] used when the menu item is being pressed.
+ </theme_item>
+ </theme_items>
+</class>
diff --git a/doc/classes/MenuButton.xml b/doc/classes/MenuButton.xml
index 8baa724292..1f38510e83 100644
--- a/doc/classes/MenuButton.xml
+++ b/doc/classes/MenuButton.xml
@@ -65,7 +65,7 @@
Text [Color] used when the [MenuButton] is being pressed.
</theme_item>
<theme_item name="h_separation" data_type="constant" type="int" default="3">
- The horizontal space between [MenuButton]'s icon and text.
+ The horizontal space between [MenuButton]'s icon and text. Negative values will be treated as [code]0[/code] when used.
</theme_item>
<theme_item name="outline_size" data_type="constant" type="int" default="0">
The size of the text outline.
diff --git a/doc/classes/Mesh.xml b/doc/classes/Mesh.xml
index 0de42b64af..d3d5a7bfaa 100644
--- a/doc/classes/Mesh.xml
+++ b/doc/classes/Mesh.xml
@@ -60,7 +60,7 @@
</description>
</method>
<method name="_surface_get_blend_shape_arrays" qualifiers="virtual const">
- <return type="Array" />
+ <return type="Array[]" />
<param index="0" name="index" type="int" />
<description>
</description>
@@ -103,7 +103,7 @@
<description>
Calculate a [ConvexPolygonShape3D] from the mesh.
If [param clean] is [code]true[/code] (default), duplicate and interior vertices are removed automatically. You can set it to [code]false[/code] to make the process faster if not needed.
- If [param simplify] is [code]true[/code], the geometry can be further simplified to reduce the amount of vertices. Disabled by default.
+ If [param simplify] is [code]true[/code], the geometry can be further simplified to reduce the number of vertices. Disabled by default.
</description>
</method>
<method name="create_outline" qualifiers="const">
@@ -142,7 +142,7 @@
<method name="get_surface_count" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of surfaces that the [Mesh] holds.
+ Returns the number of surfaces that the [Mesh] holds.
</description>
</method>
<method name="surface_get_arrays" qualifiers="const">
@@ -153,7 +153,7 @@
</description>
</method>
<method name="surface_get_blend_shape_arrays" qualifiers="const">
- <return type="Array" />
+ <return type="Array[]" />
<param index="0" name="surf_idx" type="int" />
<description>
Returns the blend shape arrays for the requested surface.
diff --git a/doc/classes/MeshInstance3D.xml b/doc/classes/MeshInstance3D.xml
index 7dfee420d4..618503c8df 100644
--- a/doc/classes/MeshInstance3D.xml
+++ b/doc/classes/MeshInstance3D.xml
@@ -20,7 +20,7 @@
<description>
This helper creates a [StaticBody3D] child node with a [ConvexPolygonShape3D] collision shape calculated from the mesh geometry. It's mainly used for testing.
If [param clean] is [code]true[/code] (default), duplicate and interior vertices are removed automatically. You can set it to [code]false[/code] to make the process faster if not needed.
- If [param simplify] is [code]true[/code], the geometry can be further simplified to reduce the amount of vertices. Disabled by default.
+ If [param simplify] is [code]true[/code], the geometry can be further simplified to reduce the number of vertices. Disabled by default.
</description>
</method>
<method name="create_debug_tangents">
diff --git a/doc/classes/MultiMeshInstance3D.xml b/doc/classes/MultiMeshInstance3D.xml
index 52cc9cb65f..70fbf235e2 100644
--- a/doc/classes/MultiMeshInstance3D.xml
+++ b/doc/classes/MultiMeshInstance3D.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
[MultiMeshInstance3D] is a specialized node to instance [GeometryInstance3D]s based on a [MultiMesh] resource.
- This is useful to optimize the rendering of a high amount of instances of a given mesh (for example trees in a forest or grass strands).
+ This is useful to optimize the rendering of a high number of instances of a given mesh (for example trees in a forest or grass strands).
</description>
<tutorials>
<link title="Animating thousands of fish with MultiMeshInstance">$DOCS_URL/tutorials/performance/vertex_animation/animating_thousands_of_fish.html</link>
diff --git a/doc/classes/NavigationAgent2D.xml b/doc/classes/NavigationAgent2D.xml
index 30ad13ec93..bf3aff2c58 100644
--- a/doc/classes/NavigationAgent2D.xml
+++ b/doc/classes/NavigationAgent2D.xml
@@ -126,7 +126,7 @@
<member name="navigation_layers" type="int" setter="set_navigation_layers" getter="get_navigation_layers" default="1">
A bitfield determining what navigation layers of navigation regions this agent will use to calculate path. Changing it runtime will clear current navigation path and generate new one, according to new navigation layers.
</member>
- <member name="neighbor_dist" type="float" setter="set_neighbor_dist" getter="get_neighbor_dist" default="500.0">
+ <member name="neighbor_distance" type="float" setter="set_neighbor_distance" getter="get_neighbor_distance" default="500.0">
The distance to search for other agents.
</member>
<member name="path_desired_distance" type="float" setter="set_path_desired_distance" getter="get_path_desired_distance" default="1.0">
@@ -136,7 +136,7 @@
The maximum distance the agent is allowed away from the ideal path to the final location. This can happen due to trying to avoid collisions. When the maximum distance is exceeded, it recalculates the ideal path.
</member>
<member name="radius" type="float" setter="set_radius" getter="get_radius" default="10.0">
- The radius of the avoidance agent. This is the "body" of the avoidance agent and not the avoidance maneuver starting radius (which is controlled by [member neighbor_dist]).
+ The radius of the avoidance agent. This is the "body" of the avoidance agent and not the avoidance maneuver starting radius (which is controlled by [member neighbor_distance]).
Does not affect normal pathfinding. To change an actor's pathfinding radius bake [NavigationMesh] resources with a different [member NavigationMesh.agent_radius] property and use different navigation maps for each actor size.
</member>
<member name="target_desired_distance" type="float" setter="set_target_desired_distance" getter="get_target_desired_distance" default="1.0">
diff --git a/doc/classes/NavigationAgent3D.xml b/doc/classes/NavigationAgent3D.xml
index 22c468cb6b..7c48f0b52b 100644
--- a/doc/classes/NavigationAgent3D.xml
+++ b/doc/classes/NavigationAgent3D.xml
@@ -132,7 +132,7 @@
<member name="navigation_layers" type="int" setter="set_navigation_layers" getter="get_navigation_layers" default="1">
A bitfield determining what navigation layers of navigation regions this NavigationAgent will use to calculate path. Changing it runtime will clear current navigation path and generate new one, according to new navigation layers.
</member>
- <member name="neighbor_dist" type="float" setter="set_neighbor_dist" getter="get_neighbor_dist" default="50.0">
+ <member name="neighbor_distance" type="float" setter="set_neighbor_distance" getter="get_neighbor_distance" default="50.0">
The distance to search for other agents.
</member>
<member name="path_desired_distance" type="float" setter="set_path_desired_distance" getter="get_path_desired_distance" default="1.0">
@@ -142,7 +142,7 @@
The maximum distance the agent is allowed away from the ideal path to the final location. This can happen due to trying to avoid collisions. When the maximum distance is exceeded, it recalculates the ideal path.
</member>
<member name="radius" type="float" setter="set_radius" getter="get_radius" default="1.0">
- The radius of the avoidance agent. This is the "body" of the avoidance agent and not the avoidance maneuver starting radius (which is controlled by [member neighbor_dist]).
+ The radius of the avoidance agent. This is the "body" of the avoidance agent and not the avoidance maneuver starting radius (which is controlled by [member neighbor_distance]).
Does not affect normal pathfinding. To change an actor's pathfinding radius bake [NavigationMesh] resources with a different [member NavigationMesh.agent_radius] property and use different navigation maps for each actor size.
</member>
<member name="target_desired_distance" type="float" setter="set_target_desired_distance" getter="get_target_desired_distance" default="1.0">
diff --git a/doc/classes/NavigationMeshGenerator.xml b/doc/classes/NavigationMeshGenerator.xml
index faf777bbc9..4c337db90f 100644
--- a/doc/classes/NavigationMeshGenerator.xml
+++ b/doc/classes/NavigationMeshGenerator.xml
@@ -6,7 +6,7 @@
<description>
This class is responsible for creating and clearing 3D navigation meshes used as [NavigationMesh] resources inside [NavigationRegion3D]. The [NavigationMeshGenerator] has very limited to no use for 2D as the navigation mesh baking process expects 3D node types and 3D source geometry to parse.
The entire navigation mesh baking is best done in a separate thread as the voxelization, collision tests and mesh optimization steps involved are very performance and time hungry operations.
- Navigation mesh baking happens in multiple steps and the result depends on 3D source geometry and properties of the [NavigationMesh] resource. In the first step, starting from a root node and depending on [NavigationMesh] properties all valid 3D source geometry nodes are collected from the [SceneTree]. Second, all collected nodes are parsed for their relevant 3D geometry data and a combined 3D mesh is build. Due to the many different types of parsable objects, from normal [MeshInstance3D]s to [CSGShape3D]s or various [CollisionObject3D]s, some operations to collect geometry data can trigger [RenderingServer] and [PhysicsServer3D] synchronizations. Server synchronization can have a negative effect on baking time or framerate as it often involves [Mutex] locking for thread security. Many parsable objects and the continuous synchronization with other threaded Servers can increase the baking time significantly. On the other hand only a few but very large and complex objects will take some time to prepare for the Servers which can noticeably stall the next frame render. As a general rule the total amount of parsable objects and their individual size and complexity should be balanced to avoid framerate issues or very long baking times. The combined mesh is then passed to the Recast Navigation Object to test the source geometry for walkable terrain suitable to [NavigationMesh] agent properties by creating a voxel world around the meshes bounding area.
+ Navigation mesh baking happens in multiple steps and the result depends on 3D source geometry and properties of the [NavigationMesh] resource. In the first step, starting from a root node and depending on [NavigationMesh] properties all valid 3D source geometry nodes are collected from the [SceneTree]. Second, all collected nodes are parsed for their relevant 3D geometry data and a combined 3D mesh is build. Due to the many different types of parsable objects, from normal [MeshInstance3D]s to [CSGShape3D]s or various [CollisionObject3D]s, some operations to collect geometry data can trigger [RenderingServer] and [PhysicsServer3D] synchronizations. Server synchronization can have a negative effect on baking time or framerate as it often involves [Mutex] locking for thread security. Many parsable objects and the continuous synchronization with other threaded Servers can increase the baking time significantly. On the other hand only a few but very large and complex objects will take some time to prepare for the Servers which can noticeably stall the next frame render. As a general rule the total number of parsable objects and their individual size and complexity should be balanced to avoid framerate issues or very long baking times. The combined mesh is then passed to the Recast Navigation Object to test the source geometry for walkable terrain suitable to [NavigationMesh] agent properties by creating a voxel world around the meshes bounding area.
The finalized navigation mesh is then returned and stored inside the [NavigationMesh] for use as a resource inside [NavigationRegion3D] nodes.
[b]Note:[/b] Using meshes to not only define walkable surfaces but also obstruct navigation baking does not always work. The navigation baking has no concept of what is a geometry "inside" when dealing with mesh source geometry and this is intentional. Depending on current baking parameters, as soon as the obstructing mesh is large enough to fit a navigation mesh area inside, the baking will generate navigation mesh areas that are inside the obstructing source geometry mesh.
</description>
diff --git a/doc/classes/NavigationServer2D.xml b/doc/classes/NavigationServer2D.xml
index 43457e7d24..b85c1c6649 100644
--- a/doc/classes/NavigationServer2D.xml
+++ b/doc/classes/NavigationServer2D.xml
@@ -72,10 +72,10 @@
Sets the maximum speed of the agent. Must be positive.
</description>
</method>
- <method name="agent_set_neighbor_dist" qualifiers="const">
+ <method name="agent_set_neighbor_distance" qualifiers="const">
<return type="void" />
<param index="0" name="agent" type="RID" />
- <param index="1" name="dist" type="float" />
+ <param index="1" name="distance" type="float" />
<description>
Sets the maximum distance to other agents this agent takes into account in the navigation. The larger this number, the longer the running time of the simulation. If the number is too low, the simulation will not be safe.
</description>
@@ -128,7 +128,7 @@
</description>
</method>
<method name="get_maps" qualifiers="const">
- <return type="Array" />
+ <return type="RID[]" />
<description>
Returns all created navigation map [RID]s on the NavigationServer. This returns both 2D and 3D created navigation maps as there is technically no distinction between them.
</description>
@@ -150,7 +150,7 @@
</description>
</method>
<method name="map_get_agents" qualifiers="const">
- <return type="Array" />
+ <return type="RID[]" />
<param index="0" name="map" type="RID" />
<description>
Returns all navigation agents [RID]s that are currently assigned to the requested navigation [param map].
@@ -198,7 +198,7 @@
</description>
</method>
<method name="map_get_regions" qualifiers="const">
- <return type="Array" />
+ <return type="RID[]" />
<param index="0" name="map" type="RID" />
<description>
Returns all navigation regions [RID]s that are currently assigned to the requested navigation [param map].
@@ -206,7 +206,7 @@
</method>
<method name="map_is_active" qualifiers="const">
<return type="bool" />
- <param index="0" name="nap" type="RID" />
+ <param index="0" name="map" type="RID" />
<description>
Returns true if the map is active.
</description>
diff --git a/doc/classes/NavigationServer3D.xml b/doc/classes/NavigationServer3D.xml
index e5eee4827b..5b2a8fc08b 100644
--- a/doc/classes/NavigationServer3D.xml
+++ b/doc/classes/NavigationServer3D.xml
@@ -72,10 +72,10 @@
Sets the maximum speed of the agent. Must be positive.
</description>
</method>
- <method name="agent_set_neighbor_dist" qualifiers="const">
+ <method name="agent_set_neighbor_distance" qualifiers="const">
<return type="void" />
<param index="0" name="agent" type="RID" />
- <param index="1" name="dist" type="float" />
+ <param index="1" name="distance" type="float" />
<description>
Sets the maximum distance to other agents this agent takes into account in the navigation. The larger this number, the longer the running time of the simulation. If the number is too low, the simulation will not be safe.
</description>
@@ -128,7 +128,7 @@
</description>
</method>
<method name="get_maps" qualifiers="const">
- <return type="Array" />
+ <return type="RID[]" />
<description>
Returns all created navigation map [RID]s on the NavigationServer. This returns both 2D and 3D created navigation maps as there is technically no distinction between them.
</description>
@@ -150,7 +150,7 @@
</description>
</method>
<method name="map_get_agents" qualifiers="const">
- <return type="Array" />
+ <return type="RID[]" />
<param index="0" name="map" type="RID" />
<description>
Returns all navigation agents [RID]s that are currently assigned to the requested navigation [param map].
@@ -216,7 +216,7 @@
</description>
</method>
<method name="map_get_regions" qualifiers="const">
- <return type="Array" />
+ <return type="RID[]" />
<param index="0" name="map" type="RID" />
<description>
Returns all navigation regions [RID]s that are currently assigned to the requested navigation [param map].
@@ -231,7 +231,7 @@
</method>
<method name="map_is_active" qualifiers="const">
<return type="bool" />
- <param index="0" name="nap" type="RID" />
+ <param index="0" name="map" type="RID" />
<description>
Returns true if the map is active.
</description>
diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml
index d38a724d39..b882425960 100644
--- a/doc/classes/Node.xml
+++ b/doc/classes/Node.xml
@@ -241,7 +241,7 @@
<description>
Returns a child node by its index (see [method get_child_count]). This method is often used for iterating all children of a node.
Negative indices access the children from the last one.
- If [param include_internal] is [code]true[/code], internal children are skipped (see [code]internal[/code] parameter in [method add_child]).
+ If [param include_internal] is [code]false[/code], internal children are skipped (see [code]internal[/code] parameter in [method add_child]).
To access a child node via its name, use [method get_node].
</description>
</method>
@@ -262,7 +262,7 @@
</description>
</method>
<method name="get_groups" qualifiers="const">
- <return type="Array" />
+ <return type="StringName[]" />
<description>
Returns an array listing the groups that the node is a member of.
[b]Note:[/b] For performance reasons, the order of node groups is [i]not[/i] guaranteed. The order of node groups should not be relied upon as it can vary across project runs.
diff --git a/doc/classes/Node3D.xml b/doc/classes/Node3D.xml
index 8a8a68ec35..53b93beb40 100644
--- a/doc/classes/Node3D.xml
+++ b/doc/classes/Node3D.xml
@@ -39,7 +39,7 @@
</description>
</method>
<method name="get_gizmos" qualifiers="const">
- <return type="Array" />
+ <return type="Node3DGizmo[]" />
<description>
Returns all the gizmos attached to this [code]Node3D[/code].
</description>
@@ -134,20 +134,6 @@
Resets this node's transformations (like scale, skew and taper) preserving its rotation and translation by performing Gram-Schmidt orthonormalization on this node's [Transform3D].
</description>
</method>
- <method name="property_can_revert">
- <return type="bool" />
- <param index="0" name="name" type="String" />
- <description>
- Returns [code]true[/code] if the property identified by [param name] can be reverted to a default value.
- </description>
- </method>
- <method name="property_get_revert">
- <return type="Variant" />
- <param index="0" name="name" type="String" />
- <description>
- Returns the default value of the Node3D property with given [param name].
- </description>
- </method>
<method name="rotate">
<return type="void" />
<param index="0" name="axis" type="Vector3" />
diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml
index e4b5404c2c..e180c73733 100644
--- a/doc/classes/OS.xml
+++ b/doc/classes/OS.xml
@@ -88,14 +88,6 @@
[b]Note:[/b] When [method delay_usec] is called on the main thread, it will freeze the project and will prevent it from redrawing and registering input until the delay has passed. When using [method delay_usec] as part of an [EditorPlugin] or [EditorScript], it will freeze the editor but won't freeze the project if it is currently running (since the project is an independent child process).
</description>
</method>
- <method name="dump_memory_to_file">
- <return type="void" />
- <param index="0" name="file" type="String" />
- <description>
- Dumps the memory allocation ringlist to a file (only works in debug).
- Entry format per line: "Address - Size - Description".
- </description>
- </method>
<method name="dump_resources_to_file">
<return type="void" />
<param index="0" name="file" type="String" />
diff --git a/doc/classes/Object.xml b/doc/classes/Object.xml
index ba219d8603..3c71a02a21 100644
--- a/doc/classes/Object.xml
+++ b/doc/classes/Object.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
Every class which is not a built-in type inherits from this class.
- You can construct Objects from scripting languages, using [code]Object.new()[/code] in GDScript, [code]new Object[/code] in C#, or the "Construct Object" node in VisualScript.
+ You can construct Objects from scripting languages, using [code]Object.new()[/code] in GDScript, or [code]new Object[/code] in C#.
Objects do not manage memory. If a class inherits from Object, you will have to delete instances of it manually. To do so, call the [method free] method from your script or delete the instance from C++.
Some classes that extend Object add memory management. This is the case of [RefCounted], which counts references and deletes itself automatically when no longer referenced. [Node], another fundamental type, deletes all its children when freed from memory.
Objects export properties, which are mainly useful for storage and editing, but not really so much in programming. Properties are exported in [method _get_property_list] and handled in [method _get] and [method _set]. However, scripting languages and C++ have simpler means to export them.
@@ -43,7 +43,7 @@
</description>
</method>
<method name="_get_property_list" qualifiers="virtual">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Virtual method which can be overridden to customize the return value of [method get_property_list].
Returns the object's property list as an [Array] of dictionaries.
@@ -64,6 +64,22 @@
Called whenever the object receives a notification, which is identified in [param what] by a constant. The base [Object] has two constants [constant NOTIFICATION_POSTINITIALIZE] and [constant NOTIFICATION_PREDELETE], but subclasses such as [Node] define a lot more notifications which are also received by this method.
</description>
</method>
+ <method name="_property_can_revert" qualifiers="virtual">
+ <return type="bool" />
+ <param index="0" name="property" type="StringName" />
+ <description>
+ Virtual methods that can be overridden to customize the property revert behavior in the editor.
+ Returns [code]true[/code] if the property identified by [code]name[/code] can be reverted to a default value. Override [method _property_get_revert] to return the actual value.
+ </description>
+ </method>
+ <method name="_property_get_revert" qualifiers="virtual">
+ <return type="Variant" />
+ <param index="0" name="property" type="StringName" />
+ <description>
+ Virtual methods that can be overridden to customize the property revert behavior in the editor.
+ Returns the default value of the property identified by [code]name[/code]. [method _property_can_revert] must be overridden as well for this method to be called.
+ </description>
+ </method>
<method name="_set" qualifiers="virtual">
<return type="bool" />
<param index="0" name="property" type="StringName" />
@@ -337,7 +353,7 @@
</description>
</method>
<method name="get_incoming_connections" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns an [Array] of dictionaries with information about signals that are connected to the object.
Each [Dictionary] contains three String entries:
@@ -367,7 +383,8 @@
<param index="1" name="default" type="Variant" default="null" />
<description>
Returns the object's metadata entry for the given [param name].
- Throws error if the entry does not exist, unless [param default] is not [code]null[/code] (in which case the default value will be returned).
+ Throws error if the entry does not exist, unless [param default] is not [code]null[/code] (in which case the default value will be returned). See also [method has_meta], [method set_meta] and [method remove_meta].
+ [b]Note:[/b] Metadata that has a [param name] starting with an underscore ([code]_[/code]) is considered editor-only. Editor-only metadata is not displayed in the inspector and should not be edited.
</description>
</method>
<method name="get_meta_list" qualifiers="const">
@@ -377,13 +394,13 @@
</description>
</method>
<method name="get_method_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns the object's methods and their signatures as an [Array].
</description>
</method>
<method name="get_property_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns the object's property list as an [Array] of dictionaries.
Each property's [Dictionary] contain at least [code]name: String[/code] and [code]type: int[/code] (see [enum Variant.Type]) entries. Optionally, it can also include [code]hint: int[/code] (see [enum PropertyHint]), [code]hint_string: String[/code], and [code]usage: int[/code] (see [enum PropertyUsageFlags]).
@@ -396,14 +413,14 @@
</description>
</method>
<method name="get_signal_connection_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="signal" type="StringName" />
<description>
Returns an [Array] of connections for the given [param signal].
</description>
</method>
<method name="get_signal_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns the list of signals as an [Array] of dictionaries.
</description>
@@ -412,7 +429,8 @@
<return type="bool" />
<param index="0" name="name" type="StringName" />
<description>
- Returns [code]true[/code] if a metadata entry is found with the given [param name].
+ Returns [code]true[/code] if a metadata entry is found with the given [param name]. See also [method get_meta], [method set_meta] and [method remove_meta].
+ [b]Note:[/b] Metadata that has a [param name] starting with an underscore ([code]_[/code]) is considered editor-only. Editor-only metadata is not displayed in the inspector and should not be edited.
</description>
</method>
<method name="has_method" qualifiers="const">
@@ -483,7 +501,8 @@
<return type="void" />
<param index="0" name="name" type="StringName" />
<description>
- Removes a given entry from the object's metadata. See also [method set_meta].
+ Removes a given entry from the object's metadata. See also [method has_meta], [method get_meta] and [method set_meta].
+ [b]Note:[/b] Metadata that has a [param name] starting with an underscore ([code]_[/code]) is considered editor-only. Editor-only metadata is not displayed in the inspector and should not be edited.
</description>
</method>
<method name="set">
@@ -546,7 +565,8 @@
<param index="1" name="value" type="Variant" />
<description>
Adds, changes or removes a given entry in the object's metadata. Metadata are serialized and can take any [Variant] value.
- To remove a given entry from the object's metadata, use [method remove_meta]. Metadata is also removed if its value is set to [code]null[/code]. This means you can also use [code]set_meta("name", null)[/code] to remove metadata for [code]"name"[/code].
+ To remove a given entry from the object's metadata, use [method remove_meta]. Metadata is also removed if its value is set to [code]null[/code]. This means you can also use [code]set_meta("name", null)[/code] to remove metadata for [code]"name"[/code]. See also [method has_meta] and [method get_meta].
+ [b]Note:[/b] Metadata that has a [param name] starting with an underscore ([code]_[/code]) is considered editor-only. Editor-only metadata is not displayed in the inspector and should not be edited.
</description>
</method>
<method name="set_script">
diff --git a/doc/classes/OptionButton.xml b/doc/classes/OptionButton.xml
index a552a2c16c..f10c096c1b 100644
--- a/doc/classes/OptionButton.xml
+++ b/doc/classes/OptionButton.xml
@@ -246,7 +246,7 @@
The horizontal space between the arrow icon and the right edge of the button.
</theme_item>
<theme_item name="h_separation" data_type="constant" type="int" default="2">
- The horizontal space between [OptionButton]'s icon and text.
+ The horizontal space between [OptionButton]'s icon and text. Negative values will be treated as [code]0[/code] when used.
</theme_item>
<theme_item name="modulate_arrow" data_type="constant" type="int" default="0">
If different than [code]0[/code], the arrow icon will be modulated to the font color.
diff --git a/doc/classes/PackedByteArray.xml b/doc/classes/PackedByteArray.xml
index b02333667d..efb559522a 100644
--- a/doc/classes/PackedByteArray.xml
+++ b/doc/classes/PackedByteArray.xml
@@ -5,6 +5,7 @@
</brief_description>
<description>
An array specifically designed to hold bytes. Packs data tightly, so it saves memory for large array sizes.
+ [PackedByteArray] also provides methods to encode/decode various types to/from bytes. The way values are encoded is an implementation detail and shouldn't be relied upon when interacting with external apps.
</description>
<tutorials>
</tutorials>
@@ -78,66 +79,77 @@
<return type="float" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 64-bit floating point number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0.0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_float" qualifiers="const">
<return type="float" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 32-bit floating point number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0.0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_half" qualifiers="const">
<return type="float" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 16-bit floating point number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0.0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_s16" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 16-bit signed integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_s32" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 32-bit signed integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_s64" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 64-bit signed integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_s8" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 8-bit signed integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_u16" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 16-bit unsigned integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_u32" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 32-bit unsigned integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_u64" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 64-bit unsigned integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_u8" qualifiers="const">
<return type="int" />
<param index="0" name="byte_offset" type="int" />
<description>
+ Decodes a 8-bit unsigned integer number from the bytes starting at [param byte_offset]. Fails if the byte count is insufficient. Returns [code]0[/code] if a valid number can't be decoded.
</description>
</method>
<method name="decode_var" qualifiers="const">
@@ -145,6 +157,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="allow_objects" type="bool" default="false" />
<description>
+ Decodes a [Variant] from the bytes starting at [param byte_offset]. Returns [code]null[/code] if a valid variant can't be decoded or the value is [Object]-derived and [param allow_objects] is [code]false[/code].
</description>
</method>
<method name="decode_var_size" qualifiers="const">
@@ -152,6 +165,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="allow_objects" type="bool" default="false" />
<description>
+ Decodes a size of a [Variant] from the bytes starting at [param byte_offset]. Requires at least 4 bytes of data starting at the offset, otherwise fails.
</description>
</method>
<method name="decompress" qualifiers="const">
@@ -183,6 +197,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="float" />
<description>
+ Encodes a 64-bit floating point number as bytes at the index of [param byte_offset] bytes. The array must have at least 8 bytes of allocated space, starting at the offset.
</description>
</method>
<method name="encode_float">
@@ -190,6 +205,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="float" />
<description>
+ Encodes a 32-bit floating point number as bytes at the index of [param byte_offset] bytes. The array must have at least 4 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_half">
@@ -197,6 +213,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="float" />
<description>
+ Encodes a 16-bit floating point number as bytes at the index of [param byte_offset] bytes. The array must have at least 2 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_s16">
@@ -204,6 +221,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 16-bit signed integer number as bytes at the index of [param byte_offset] bytes. The array must have at least 2 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_s32">
@@ -211,6 +229,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 32-bit signed integer number as bytes at the index of [param byte_offset] bytes. The array must have at least 2 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_s64">
@@ -218,6 +237,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 64-bit signed integer number as bytes at the index of [param byte_offset] bytes. The array must have at least 2 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_s8">
@@ -225,6 +245,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 8-bit signed integer number (signed byte) at the index of [param byte_offset] bytes. The array must have at least 1 byte of space, starting at the offset.
</description>
</method>
<method name="encode_u16">
@@ -232,6 +253,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 16-bit unsigned integer number as bytes at the index of [param byte_offset] bytes. The array must have at least 2 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_u32">
@@ -239,6 +261,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 32-bit unsigned integer number as bytes at the index of [param byte_offset] bytes. The array must have at least 4 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_u64">
@@ -246,6 +269,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 64-bit unsigned integer number as bytes at the index of [param byte_offset] bytes. The array must have at least 8 bytes of space, starting at the offset.
</description>
</method>
<method name="encode_u8">
@@ -253,6 +277,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="value" type="int" />
<description>
+ Encodes a 8-bit unsigned integer number (byte) at the index of [param byte_offset] bytes. The array must have at least 1 byte of space, starting at the offset.
</description>
</method>
<method name="encode_var">
@@ -261,6 +286,7 @@
<param index="1" name="value" type="Variant" />
<param index="2" name="allow_objects" type="bool" default="false" />
<description>
+ Encodes a [Variant] at the index of [param byte_offset] bytes. A sufficient space must be allocated, depending on the encoded variant's size. If [param allow_objects] is [code]false[/code], [Object]-derived values are not permitted and will instead be serialized as ID-only.
</description>
</method>
<method name="fill">
@@ -314,6 +340,7 @@
<param index="0" name="byte_offset" type="int" />
<param index="1" name="allow_objects" type="bool" default="false" />
<description>
+ Returns [code]true[/code] if a valid [Variant] value can be decoded at the [param byte_offset]. Returns [code]false[/code] othewrise or when the value is [Object]-derived and [param allow_objects] is [code]false[/code].
</description>
</method>
<method name="hex_encode" qualifiers="const">
@@ -449,24 +476,29 @@
<return type="bool" />
<param index="0" name="right" type="PackedByteArray" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator +">
<return type="PackedByteArray" />
<param index="0" name="right" type="PackedByteArray" />
<description>
+ Returns a new [PackedByteArray] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedByteArray" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal bytes at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="int" />
<param index="0" name="index" type="int" />
<description>
+ Returns the byte at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
+ Note that the byte is returned as a 64-bit [int].
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedColorArray.xml b/doc/classes/PackedColorArray.xml
index c694927175..a2dc8e8f1d 100644
--- a/doc/classes/PackedColorArray.xml
+++ b/doc/classes/PackedColorArray.xml
@@ -177,6 +177,7 @@
<method name="to_byte_array" qualifiers="const">
<return type="PackedByteArray" />
<description>
+ Returns a [PackedByteArray] with each color encoded as bytes.
</description>
</method>
</methods>
@@ -185,24 +186,28 @@
<return type="bool" />
<param index="0" name="right" type="PackedColorArray" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator +">
<return type="PackedColorArray" />
<param index="0" name="right" type="PackedColorArray" />
<description>
+ Returns a new [PackedColorArray] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedColorArray" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal [Color]s at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="Color" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [Color] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedFloat32Array.xml b/doc/classes/PackedFloat32Array.xml
index 41d0679099..d350d64f38 100644
--- a/doc/classes/PackedFloat32Array.xml
+++ b/doc/classes/PackedFloat32Array.xml
@@ -4,7 +4,7 @@
A packed array of 32-bit floating-point values.
</brief_description>
<description>
- An array specifically designed to hold 32-bit floating-point values. Packs data tightly, so it saves memory for large array sizes.
+ An array specifically designed to hold 32-bit floating-point values (float). Packs data tightly, so it saves memory for large array sizes.
If you need to pack 64-bit floats tightly, see [PackedFloat64Array].
</description>
<tutorials>
@@ -188,24 +188,29 @@
<return type="bool" />
<param index="0" name="right" type="PackedFloat32Array" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator +">
<return type="PackedFloat32Array" />
<param index="0" name="right" type="PackedFloat32Array" />
<description>
+ Returns a new [PackedFloat32Array] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedFloat32Array" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal floats at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="float" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [float] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
+ Note that [float] type is 64-bit, unlike the values stored in the array.
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedFloat64Array.xml b/doc/classes/PackedFloat64Array.xml
index bedbe3603c..690cb15fa7 100644
--- a/doc/classes/PackedFloat64Array.xml
+++ b/doc/classes/PackedFloat64Array.xml
@@ -4,7 +4,7 @@
A packed array of 64-bit floating-point values.
</brief_description>
<description>
- An array specifically designed to hold 64-bit floating-point values. Packs data tightly, so it saves memory for large array sizes.
+ An array specifically designed to hold 64-bit floating-point values (double). Packs data tightly, so it saves memory for large array sizes.
If you only need to pack 32-bit floats tightly, see [PackedFloat32Array] for a more memory-friendly alternative.
</description>
<tutorials>
@@ -188,24 +188,28 @@
<return type="bool" />
<param index="0" name="right" type="PackedFloat64Array" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator +">
<return type="PackedFloat64Array" />
<param index="0" name="right" type="PackedFloat64Array" />
<description>
+ Returns a new [PackedFloat64Array] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedFloat64Array" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal doubles at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="float" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [float] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedInt32Array.xml b/doc/classes/PackedInt32Array.xml
index db4c8c0937..2f9032e214 100644
--- a/doc/classes/PackedInt32Array.xml
+++ b/doc/classes/PackedInt32Array.xml
@@ -188,24 +188,29 @@
<return type="bool" />
<param index="0" name="right" type="PackedInt32Array" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator +">
<return type="PackedInt32Array" />
<param index="0" name="right" type="PackedInt32Array" />
<description>
+ Returns a new [PackedInt32Array] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedInt32Array" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal ints at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="int" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [int] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
+ Note that [int] type is 64-bit, unlike the values stored in the array.
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedInt64Array.xml b/doc/classes/PackedInt64Array.xml
index 56d72692a2..5f762cde3e 100644
--- a/doc/classes/PackedInt64Array.xml
+++ b/doc/classes/PackedInt64Array.xml
@@ -188,24 +188,28 @@
<return type="bool" />
<param index="0" name="right" type="PackedInt64Array" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator +">
<return type="PackedInt64Array" />
<param index="0" name="right" type="PackedInt64Array" />
<description>
+ Returns a new [PackedInt64Array] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedInt64Array" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal ints at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="int" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [int] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedStringArray.xml b/doc/classes/PackedStringArray.xml
index b58a3b2553..2c3376d659 100644
--- a/doc/classes/PackedStringArray.xml
+++ b/doc/classes/PackedStringArray.xml
@@ -184,6 +184,7 @@
<method name="to_byte_array" qualifiers="const">
<return type="PackedByteArray" />
<description>
+ Returns a [PackedByteArray] with each string encoded as bytes.
</description>
</method>
</methods>
@@ -192,24 +193,28 @@
<return type="bool" />
<param index="0" name="right" type="PackedStringArray" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator +">
<return type="PackedStringArray" />
<param index="0" name="right" type="PackedStringArray" />
<description>
+ Returns a new [PackedStringArray] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedStringArray" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal [String]s at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="String" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [String] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedVector2Array.xml b/doc/classes/PackedVector2Array.xml
index 7cf63d3d5e..25650ef40a 100644
--- a/doc/classes/PackedVector2Array.xml
+++ b/doc/classes/PackedVector2Array.xml
@@ -178,6 +178,7 @@
<method name="to_byte_array" qualifiers="const">
<return type="PackedByteArray" />
<description>
+ Returns a [PackedByteArray] with each vector encoded as bytes.
</description>
</method>
</methods>
@@ -186,30 +187,35 @@
<return type="bool" />
<param index="0" name="right" type="PackedVector2Array" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator *">
<return type="PackedVector2Array" />
<param index="0" name="right" type="Transform2D" />
<description>
+ Transforms (multiplies) all vectors in the array by the [Transform2D] matrix.
</description>
</operator>
<operator name="operator +">
<return type="PackedVector2Array" />
<param index="0" name="right" type="PackedVector2Array" />
<description>
+ Returns a new [PackedVector2Array] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedVector2Array" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal [Vector2]s at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="Vector2" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [Vector2] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
</description>
</operator>
</operators>
diff --git a/doc/classes/PackedVector3Array.xml b/doc/classes/PackedVector3Array.xml
index 5ab42474f0..22979a5a37 100644
--- a/doc/classes/PackedVector3Array.xml
+++ b/doc/classes/PackedVector3Array.xml
@@ -177,6 +177,7 @@
<method name="to_byte_array" qualifiers="const">
<return type="PackedByteArray" />
<description>
+ Returns a [PackedByteArray] with each vector encoded as bytes.
</description>
</method>
</methods>
@@ -185,30 +186,35 @@
<return type="bool" />
<param index="0" name="right" type="PackedVector3Array" />
<description>
+ Returns [code]true[/code] if contents of the arrays differ.
</description>
</operator>
<operator name="operator *">
<return type="PackedVector3Array" />
<param index="0" name="right" type="Transform3D" />
<description>
+ Transforms (multiplies) all vectors in the array by the [Transform3D] matrix.
</description>
</operator>
<operator name="operator +">
<return type="PackedVector3Array" />
<param index="0" name="right" type="PackedVector3Array" />
<description>
+ Returns a new [PackedVector3Array] with contents of [param right] added at the end of this array. For better performance, consider using [method append_array] instead.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="PackedVector3Array" />
<description>
+ Returns [code]true[/code] if contents of both arrays are the same, i.e. they have all equal [Vector3]s at the corresponding indices.
</description>
</operator>
<operator name="operator []">
<return type="Vector3" />
<param index="0" name="index" type="int" />
<description>
+ Returns the [Vector3] at index [param index]. Negative indices can be used to access the elements starting from the end. Using index out of array's bounds will result in an error.
</description>
</operator>
</operators>
diff --git a/doc/classes/ParticlesMaterial.xml b/doc/classes/ParticlesMaterial.xml
index fe4caaa10c..55f4c4dcdd 100644
--- a/doc/classes/ParticlesMaterial.xml
+++ b/doc/classes/ParticlesMaterial.xml
@@ -115,14 +115,15 @@
<member name="attractor_interaction_enabled" type="bool" setter="set_attractor_interaction_enabled" getter="is_attractor_interaction_enabled" default="true">
True if the interaction with particle attractors is enabled.
</member>
- <member name="collision_bounce" type="float" setter="set_collision_bounce" getter="get_collision_bounce" default="0.0">
- Collision bounciness.
+ <member name="collision_bounce" type="float" setter="set_collision_bounce" getter="get_collision_bounce">
+ The particles' bounciness. Values range from [code]0[/code] (no bounce) to [code]1[/code] (full bounciness). Only effective if [member collision_mode] is [constant COLLISION_RIGID].
</member>
- <member name="collision_enabled" type="bool" setter="set_collision_enabled" getter="is_collision_enabled" default="false">
- True if collisions are enabled for this particle system.
+ <member name="collision_friction" type="float" setter="set_collision_friction" getter="get_collision_friction">
+ The particles' friction. Values range from [code]0[/code] (frictionless) to [code]1[/code] (maximum friction). Only effective if [member collision_mode] is [constant COLLISION_RIGID].
</member>
- <member name="collision_friction" type="float" setter="set_collision_friction" getter="get_collision_friction" default="0.0">
- Collision friction.
+ <member name="collision_mode" type="int" setter="set_collision_mode" getter="get_collision_mode" enum="ParticlesMaterial.CollisionMode" default="0">
+ The particles' collision mode.
+ [b]Note:[/b] Particles can only collide with [GPUParticlesCollision3D] nodes, not [PhysicsBody3D] nodes. To make particles collide with various objects, you can add [GPUParticlesCollision3D] nodes as children of [PhysicsBody3D] nodes.
</member>
<member name="collision_use_scale" type="bool" setter="set_collision_use_scale" getter="is_collision_using_scale" default="false">
Should collision take scale into account.
@@ -404,5 +405,17 @@
<constant name="SUB_EMITTER_MAX" value="4" enum="SubEmitterMode">
Represents the size of the [enum SubEmitterMode] enum.
</constant>
+ <constant name="COLLISION_DISABLED" value="0" enum="CollisionMode">
+ No collision for particles. Particles will go through [GPUParticlesCollision3D] nodes.
+ </constant>
+ <constant name="COLLISION_RIGID" value="1" enum="CollisionMode">
+ [RigidDynamicBody3D]-style collision for particles using [GPUParticlesCollision3D] nodes.
+ </constant>
+ <constant name="COLLISION_HIDE_ON_CONTACT" value="2" enum="CollisionMode">
+ Hide particles instantly when colliding with a [GPUParticlesCollision3D] node. This can be combined with a subemitter that uses the [constant COLLISION_RIGID] collision mode to "replace" the parent particle with the subemitter on impact.
+ </constant>
+ <constant name="COLLISION_MAX" value="3" enum="CollisionMode">
+ Represents the size of the [enum CollisionMode] enum.
+ </constant>
</constants>
</class>
diff --git a/doc/classes/PathFollow2D.xml b/doc/classes/PathFollow2D.xml
index ae4a4b2886..09d6872e10 100644
--- a/doc/classes/PathFollow2D.xml
+++ b/doc/classes/PathFollow2D.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
This node takes its parent [Path2D], and returns the coordinates of a point within it, given a distance from the first vertex.
- It is useful for making other nodes follow a path, without coding the movement pattern. For that, the nodes must be children of this node. The descendant nodes will then move accordingly when setting an offset in this node.
+ It is useful for making other nodes follow a path, without coding the movement pattern. For that, the nodes must be children of this node. The descendant nodes will then move accordingly when setting the [member progress] in this node.
</description>
<tutorials>
</tutorials>
@@ -24,15 +24,15 @@
<member name="loop" type="bool" setter="set_loop" getter="has_loop" default="true">
If [code]true[/code], any offset outside the path's length will wrap around, instead of stopping at the ends. Use it for cyclic paths.
</member>
- <member name="offset" type="float" setter="set_offset" getter="get_offset" default="0.0">
- The distance along the path in pixels.
+ <member name="progress" type="float" setter="set_progress" getter="get_progress" default="0.0">
+ The distance along the path, in pixels. Changing this value sets this node's position to a point within the path.
+ </member>
+ <member name="progress_ratio" type="float" setter="set_progress_ratio" getter="get_progress_ratio" default="0.0">
+ The distance along the path as a number in the range 0.0 (for the first vertex) to 1.0 (for the last). This is just another way of expressing the progress within the path, as the offset supplied is multiplied internally by the path's length.
</member>
<member name="rotates" type="bool" setter="set_rotates" getter="is_rotating" default="true">
If [code]true[/code], this node rotates to follow the path, with the +X direction facing forward on the path.
</member>
- <member name="unit_offset" type="float" setter="set_unit_offset" getter="get_unit_offset" default="0.0">
- The distance along the path as a number in the range 0.0 (for the first vertex) to 1.0 (for the last). This is just another way of expressing the offset within the path, as the offset supplied is multiplied internally by the path's length.
- </member>
<member name="v_offset" type="float" setter="set_v_offset" getter="get_v_offset" default="0.0">
The node's offset perpendicular to the curve.
</member>
diff --git a/doc/classes/PathFollow3D.xml b/doc/classes/PathFollow3D.xml
index f9fab07be5..ba7207be8f 100644
--- a/doc/classes/PathFollow3D.xml
+++ b/doc/classes/PathFollow3D.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
This node takes its parent [Path3D], and returns the coordinates of a point within it, given a distance from the first vertex.
- It is useful for making other nodes follow a path, without coding the movement pattern. For that, the nodes must be children of this node. The descendant nodes will then move accordingly when setting an offset in this node.
+ It is useful for making other nodes follow a path, without coding the movement pattern. For that, the nodes must be children of this node. The descendant nodes will then move accordingly when setting the [member progress] in this node.
</description>
<tutorials>
</tutorials>
@@ -21,15 +21,15 @@
<member name="loop" type="bool" setter="set_loop" getter="has_loop" default="true">
If [code]true[/code], any offset outside the path's length will wrap around, instead of stopping at the ends. Use it for cyclic paths.
</member>
- <member name="offset" type="float" setter="set_offset" getter="get_offset" default="0.0">
- The distance from the first vertex, measured in 3D units along the path. This sets this node's position to a point within the path.
+ <member name="progress" type="float" setter="set_progress" getter="get_progress" default="0.0">
+ The distance from the first vertex, measured in 3D units along the path. Changing this value sets this node's position to a point within the path.
+ </member>
+ <member name="progress_ratio" type="float" setter="set_progress_ratio" getter="get_progress_ratio" default="0.0">
+ The distance from the first vertex, considering 0.0 as the first vertex and 1.0 as the last. This is just another way of expressing the progress within the path, as the progress supplied is multiplied internally by the path's length.
</member>
<member name="rotation_mode" type="int" setter="set_rotation_mode" getter="get_rotation_mode" enum="PathFollow3D.RotationMode" default="3">
Allows or forbids rotation on one or more axes, depending on the [enum RotationMode] constants being used.
</member>
- <member name="unit_offset" type="float" setter="set_unit_offset" getter="get_unit_offset" default="0.0">
- The distance from the first vertex, considering 0.0 as the first vertex and 1.0 as the last. This is just another way of expressing the offset within the path, as the offset supplied is multiplied internally by the path's length.
- </member>
<member name="v_offset" type="float" setter="set_v_offset" getter="get_v_offset" default="0.0">
The node's offset perpendicular to the curve.
</member>
diff --git a/doc/classes/Performance.xml b/doc/classes/Performance.xml
index ddb290f007..92fa1040af 100644
--- a/doc/classes/Performance.xml
+++ b/doc/classes/Performance.xml
@@ -79,7 +79,7 @@
</description>
</method>
<method name="get_custom_monitor_names">
- <return type="Array" />
+ <return type="StringName[]" />
<description>
Returns the names of active custom monitors in an [Array].
</description>
diff --git a/doc/classes/PhysicsBody2D.xml b/doc/classes/PhysicsBody2D.xml
index 2350fd4458..e8d7ac9920 100644
--- a/doc/classes/PhysicsBody2D.xml
+++ b/doc/classes/PhysicsBody2D.xml
@@ -32,7 +32,7 @@
Moves the body along the vector [param distance]. In order to be frame rate independent in [method Node._physics_process] or [method Node._process], [param distance] should be computed using [code]delta[/code].
Returns a [KinematicCollision2D], which contains information about the collision when stopped, or when touching another body along the motion.
If [param test_only] is [code]true[/code], the body does not move but the would-be collision information is given.
- [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody2D.collision/safe_margin] for more details).
+ [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody2D.safe_margin] for more details).
</description>
</method>
<method name="remove_collision_exception_with">
@@ -52,7 +52,7 @@
Checks for collisions without moving the body. In order to be frame rate independent in [method Node._physics_process] or [method Node._process], [param distance] should be computed using [code]delta[/code].
Virtually sets the node's position, scale and rotation to that of the given [Transform2D], then tries to move the body along the vector [param distance]. Returns [code]true[/code] if a collision would stop the body from moving along the whole path.
[param collision] is an optional object of type [KinematicCollision2D], which contains additional information about the collision when stopped, or when touching another body along the motion.
- [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody2D.collision/safe_margin] for more details).
+ [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody2D.safe_margin] for more details).
</description>
</method>
</methods>
diff --git a/doc/classes/PhysicsBody3D.xml b/doc/classes/PhysicsBody3D.xml
index 3ef7fc9030..310671274f 100644
--- a/doc/classes/PhysicsBody3D.xml
+++ b/doc/classes/PhysicsBody3D.xml
@@ -40,7 +40,7 @@
Moves the body along the vector [param distance]. In order to be frame rate independent in [method Node._physics_process] or [method Node._process], [param distance] should be computed using [code]delta[/code].
The body will stop if it collides. Returns a [KinematicCollision3D], which contains information about the collision when stopped, or when touching another body along the motion.
If [param test_only] is [code]true[/code], the body does not move but the would-be collision information is given.
- [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody3D.collision/safe_margin] for more details).
+ [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody3D.safe_margin] for more details).
[param max_collisions] allows to retrieve more than one collision result.
</description>
</method>
@@ -70,7 +70,7 @@
Checks for collisions without moving the body. In order to be frame rate independent in [method Node._physics_process] or [method Node._process], [param distance] should be computed using [code]delta[/code].
Virtually sets the node's position, scale and rotation to that of the given [Transform3D], then tries to move the body along the vector [param distance]. Returns [code]true[/code] if a collision would stop the body from moving along the whole path.
[param collision] is an optional object of type [KinematicCollision3D], which contains additional information about the collision when stopped, or when touching another body along the motion.
- [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody3D.collision/safe_margin] for more details).
+ [param safe_margin] is the extra margin used for collision recovery (see [member CharacterBody3D.safe_margin] for more details).
[param max_collisions] allows to retrieve more than one collision result.
</description>
</method>
diff --git a/doc/classes/PhysicsDirectSpaceState2D.xml b/doc/classes/PhysicsDirectSpaceState2D.xml
index 6290ea315f..d4cb073d15 100644
--- a/doc/classes/PhysicsDirectSpaceState2D.xml
+++ b/doc/classes/PhysicsDirectSpaceState2D.xml
@@ -12,7 +12,7 @@
</tutorials>
<methods>
<method name="cast_motion">
- <return type="Array" />
+ <return type="PackedFloat32Array" />
<param index="0" name="parameters" type="PhysicsShapeQueryParameters2D" />
<description>
Checks how far a [Shape2D] can move without colliding. All the parameters for the query, including the shape and the motion, are supplied through a [PhysicsShapeQueryParameters2D] object.
@@ -21,7 +21,7 @@
</description>
</method>
<method name="collide_shape">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="parameters" type="PhysicsShapeQueryParameters2D" />
<param index="1" name="max_results" type="int" default="32" />
<description>
@@ -44,7 +44,7 @@
</description>
</method>
<method name="intersect_point">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="parameters" type="PhysicsPointQueryParameters2D" />
<param index="1" name="max_results" type="int" default="32" />
<description>
@@ -72,7 +72,7 @@
</description>
</method>
<method name="intersect_shape">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="parameters" type="PhysicsShapeQueryParameters2D" />
<param index="1" name="max_results" type="int" default="32" />
<description>
diff --git a/doc/classes/PhysicsDirectSpaceState3D.xml b/doc/classes/PhysicsDirectSpaceState3D.xml
index 619891df90..cc1cf8a323 100644
--- a/doc/classes/PhysicsDirectSpaceState3D.xml
+++ b/doc/classes/PhysicsDirectSpaceState3D.xml
@@ -12,7 +12,7 @@
</tutorials>
<methods>
<method name="cast_motion">
- <return type="Array" />
+ <return type="PackedFloat32Array" />
<param index="0" name="parameters" type="PhysicsShapeQueryParameters3D" />
<description>
Checks how far a [Shape3D] can move without colliding. All the parameters for the query, including the shape, are supplied through a [PhysicsShapeQueryParameters3D] object.
@@ -21,7 +21,7 @@
</description>
</method>
<method name="collide_shape">
- <return type="Array" />
+ <return type="PackedVector2Array[]" />
<param index="0" name="parameters" type="PhysicsShapeQueryParameters3D" />
<param index="1" name="max_results" type="int" default="32" />
<description>
@@ -46,7 +46,7 @@
</description>
</method>
<method name="intersect_point">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="parameters" type="PhysicsPointQueryParameters3D" />
<param index="1" name="max_results" type="int" default="32" />
<description>
@@ -73,7 +73,7 @@
</description>
</method>
<method name="intersect_shape">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="parameters" type="PhysicsShapeQueryParameters3D" />
<param index="1" name="max_results" type="int" default="32" />
<description>
diff --git a/doc/classes/PhysicsServer2D.xml b/doc/classes/PhysicsServer2D.xml
index d7b5f24f4a..7ba52c40c6 100644
--- a/doc/classes/PhysicsServer2D.xml
+++ b/doc/classes/PhysicsServer2D.xml
@@ -358,6 +358,13 @@
Returns the physics layer or layers a body can collide with.
</description>
</method>
+ <method name="body_get_collision_priority" qualifiers="const">
+ <return type="float" />
+ <param index="0" name="body" type="RID" />
+ <description>
+ Returns the body's collision priority.
+ </description>
+ </method>
<method name="body_get_constant_force" qualifiers="const">
<return type="Vector2" />
<param index="0" name="body" type="RID" />
@@ -509,6 +516,14 @@
Sets the physics layer or layers a body can collide with.
</description>
</method>
+ <method name="body_set_collision_priority">
+ <return type="void" />
+ <param index="0" name="body" type="RID" />
+ <param index="1" name="priority" type="float" />
+ <description>
+ Sets the body's collision priority.
+ </description>
+ </method>
<method name="body_set_constant_force">
<return type="void" />
<param index="0" name="body" type="RID" />
@@ -553,7 +568,7 @@
<param index="0" name="body" type="RID" />
<param index="1" name="amount" type="int" />
<description>
- Sets the maximum contacts to report. Bodies can keep a log of the contacts with other bodies, this is enabled by setting the maximum amount of contacts reported to a number greater than 0.
+ Sets the maximum contacts to report. Bodies can keep a log of the contacts with other bodies. This is enabled by setting the maximum number of contacts reported to a number greater than 0.
</description>
</method>
<method name="body_set_mode">
@@ -882,7 +897,7 @@
Constant to set/get the default solver bias for all physics constraints. A solver bias is a factor controlling how much two objects "rebound", after violating a constraint, to avoid leaving them in that state because of numerical imprecision.
</constant>
<constant name="SPACE_PARAM_SOLVER_ITERATIONS" value="8" enum="SpaceParameter">
- Constant to set/get the number of solver iterations for all contacts and constraints. The greater the amount of iterations, the more accurate the collisions will be. However, a greater amount of iterations requires more CPU power, which can decrease performance.
+ Constant to set/get the number of solver iterations for all contacts and constraints. The greater the number of iterations, the more accurate the collisions will be. However, a greater number of iterations requires more CPU power, which can decrease performance.
</constant>
<constant name="SHAPE_WORLD_BOUNDARY" value="0" enum="ShapeType">
This is the constant for creating world boundary shapes. A world boundary shape is an [i]infinite[/i] line with an origin point, and a normal. Thus, it can be used for front/behind checks.
diff --git a/doc/classes/PhysicsServer3D.xml b/doc/classes/PhysicsServer3D.xml
index c5456f7536..d4796fe2cf 100644
--- a/doc/classes/PhysicsServer3D.xml
+++ b/doc/classes/PhysicsServer3D.xml
@@ -338,6 +338,13 @@
Returns the physics layer or layers a body can collide with.
</description>
</method>
+ <method name="body_get_collision_priority" qualifiers="const">
+ <return type="float" />
+ <param index="0" name="body" type="RID" />
+ <description>
+ Returns the body's collision priority.
+ </description>
+ </method>
<method name="body_get_constant_force" qualifiers="const">
<return type="Vector3" />
<param index="0" name="body" type="RID" />
@@ -505,6 +512,14 @@
Sets the physics layer or layers a body can collide with.
</description>
</method>
+ <method name="body_set_collision_priority">
+ <return type="void" />
+ <param index="0" name="body" type="RID" />
+ <param index="1" name="priority" type="float" />
+ <description>
+ Sets the body's collision priority.
+ </description>
+ </method>
<method name="body_set_constant_force">
<return type="void" />
<param index="0" name="body" type="RID" />
@@ -549,7 +564,7 @@
<param index="0" name="body" type="RID" />
<param index="1" name="amount" type="int" />
<description>
- Sets the maximum contacts to report. Bodies can keep a log of the contacts with other bodies, this is enabled by setting the maximum amount of contacts reported to a number greater than 0.
+ Sets the maximum contacts to report. Bodies can keep a log of the contacts with other bodies. This is enabled by setting the maximum number of contacts reported to a number greater than 0.
</description>
</method>
<method name="body_set_mode">
@@ -1422,7 +1437,7 @@
Constant to set/get the maximum time of activity. A body marked as potentially inactive for both linear and angular velocity will be put to sleep after this time.
</constant>
<constant name="SPACE_PARAM_SOLVER_ITERATIONS" value="7" enum="SpaceParameter">
- Constant to set/get the number of solver iterations for contacts and constraints. The greater the amount of iterations, the more accurate the collisions and constraints will be. However, a greater amount of iterations requires more CPU power, which can decrease performance.
+ Constant to set/get the number of solver iterations for contacts and constraints. The greater the number of iterations, the more accurate the collisions and constraints will be. However, a greater number of iterations requires more CPU power, which can decrease performance.
</constant>
<constant name="BODY_AXIS_LINEAR_X" value="1" enum="BodyAxis">
</constant>
diff --git a/doc/classes/PhysicsServer3DExtension.xml b/doc/classes/PhysicsServer3DExtension.xml
index 4188b04e4a..200065de54 100644
--- a/doc/classes/PhysicsServer3DExtension.xml
+++ b/doc/classes/PhysicsServer3DExtension.xml
@@ -286,6 +286,12 @@
<description>
</description>
</method>
+ <method name="_body_get_collision_priority" qualifiers="virtual const">
+ <return type="float" />
+ <param index="0" name="body" type="RID" />
+ <description>
+ </description>
+ </method>
<method name="_body_get_constant_force" qualifiers="virtual const">
<return type="Vector3" />
<param index="0" name="body" type="RID" />
@@ -430,6 +436,13 @@
<description>
</description>
</method>
+ <method name="_body_set_collision_priority" qualifiers="virtual">
+ <return type="void" />
+ <param index="0" name="body" type="RID" />
+ <param index="1" name="priority" type="float" />
+ <description>
+ </description>
+ </method>
<method name="_body_set_constant_force" qualifiers="virtual">
<return type="void" />
<param index="0" name="body" type="RID" />
diff --git a/doc/classes/PlaneMesh.xml b/doc/classes/PlaneMesh.xml
index 6b3a7ed548..564b6fe743 100644
--- a/doc/classes/PlaneMesh.xml
+++ b/doc/classes/PlaneMesh.xml
@@ -4,7 +4,7 @@
Class representing a planar [PrimitiveMesh].
</brief_description>
<description>
- Class representing a planar [PrimitiveMesh]. This flat mesh does not have a thickness. By default, this mesh is aligned on the X and Z axes; this default rotation isn't suited for use with billboarded materials. For billboarded materials, use [QuadMesh] instead.
+ Class representing a planar [PrimitiveMesh]. This flat mesh does not have a thickness. By default, this mesh is aligned on the X and Z axes; this default rotation isn't suited for use with billboarded materials. For billboarded materials, change [member orientation] to [constant FACE_Z].
[b]Note:[/b] When using a large textured [PlaneMesh] (e.g. as a floor), you may stumble upon UV jittering issues depending on the camera angle. To solve this, increase [member subdivide_depth] and [member subdivide_width] until you no longer notice UV jittering.
</description>
<tutorials>
@@ -13,6 +13,9 @@
<member name="center_offset" type="Vector3" setter="set_center_offset" getter="get_center_offset" default="Vector3(0, 0, 0)">
Offset of the generated plane. Useful for particles.
</member>
+ <member name="orientation" type="int" setter="set_orientation" getter="get_orientation" enum="PlaneMesh.Orientation" default="1">
+ Direction that the [PlaneMesh] is facing. See [enum Orientation] for options.
+ </member>
<member name="size" type="Vector2" setter="set_size" getter="get_size" default="Vector2(2, 2)">
Size of the generated plane.
</member>
@@ -23,4 +26,15 @@
Number of subdivision along the X axis.
</member>
</members>
+ <constants>
+ <constant name="FACE_X" value="0" enum="Orientation">
+ [PlaneMesh] will face the positive X-axis.
+ </constant>
+ <constant name="FACE_Y" value="1" enum="Orientation">
+ [PlaneMesh] will face the positive Y-axis. This matches the behaviour of the [PlaneMesh] in Godot 3.x.
+ </constant>
+ <constant name="FACE_Z" value="2" enum="Orientation">
+ [PlaneMesh] will face the positive Z-axis. This matches the behvaiour of the QuadMesh in Godot 3.x.
+ </constant>
+ </constants>
</class>
diff --git a/doc/classes/Polygon2D.xml b/doc/classes/Polygon2D.xml
index 5d5c69aadd..12f8055180 100644
--- a/doc/classes/Polygon2D.xml
+++ b/doc/classes/Polygon2D.xml
@@ -79,10 +79,10 @@
<member name="internal_vertex_count" type="int" setter="set_internal_vertex_count" getter="get_internal_vertex_count" default="0">
</member>
<member name="invert_border" type="float" setter="set_invert_border" getter="get_invert_border" default="100.0">
- Added padding applied to the bounding box when using [code]invert[/code]. Setting this value too small may result in a "Bad Polygon" error.
+ Added padding applied to the bounding box when [member invert_enabled] is set to [code]true[/code]. Setting this value too small may result in a "Bad Polygon" error.
</member>
- <member name="invert_enable" type="bool" setter="set_invert" getter="get_invert" default="false">
- If [code]true[/code], polygon will be inverted, containing the area outside the defined points and extending to the [code]invert_border[/code].
+ <member name="invert_enabled" type="bool" setter="set_invert_enabled" getter="get_invert_enabled" default="false">
+ If [code]true[/code], the polygon will be inverted, containing the area outside the defined points and extending to the [member invert_border].
</member>
<member name="offset" type="Vector2" setter="set_offset" getter="get_offset" default="Vector2(0, 0)">
The offset applied to each vertex.
diff --git a/doc/classes/PopupMenu.xml b/doc/classes/PopupMenu.xml
index 26bc765ef4..0f47bea5df 100644
--- a/doc/classes/PopupMenu.xml
+++ b/doc/classes/PopupMenu.xml
@@ -195,13 +195,6 @@
Returns the accelerator of the item at the given [param index]. Accelerators are special combinations of keys that activate the item, no matter which control is focused.
</description>
</method>
- <method name="get_item_horizontal_offset" qualifiers="const">
- <return type="int" />
- <param index="0" name="index" type="int" />
- <description>
- Returns the horizontal offset of the item at the given [param index].
- </description>
- </method>
<method name="get_item_icon" qualifiers="const">
<return type="Texture2D" />
<param index="0" name="index" type="int" />
@@ -216,6 +209,13 @@
Returns the id of the item at the given [param index]. [code]id[/code] can be manually assigned, while index can not.
</description>
</method>
+ <method name="get_item_indent" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="index" type="int" />
+ <description>
+ Returns the horizontal offset of the item at the given [param index].
+ </description>
+ </method>
<method name="get_item_index" qualifiers="const">
<return type="int" />
<param index="0" name="id" type="int" />
@@ -388,14 +388,6 @@
Enables/disables the item at the given [param index]. When it is disabled, it can't be selected and its action can't be invoked.
</description>
</method>
- <method name="set_item_horizontal_offset">
- <return type="void" />
- <param index="0" name="index" type="int" />
- <param index="1" name="offset" type="int" />
- <description>
- Sets the horizontal offset of the item at the given [param index].
- </description>
- </method>
<method name="set_item_icon">
<return type="void" />
<param index="0" name="index" type="int" />
@@ -413,6 +405,14 @@
The [param id] is used in [signal id_pressed] and [signal id_focused] signals.
</description>
</method>
+ <method name="set_item_indent">
+ <return type="void" />
+ <param index="0" name="index" type="int" />
+ <param index="1" name="indent" type="int" />
+ <description>
+ Sets the horizontal offset of the item at the given [param index].
+ </description>
+ </method>
<method name="set_item_language">
<return type="void" />
<param index="0" name="index" type="int" />
@@ -540,6 +540,10 @@
Emitted when an item of some [param index] is pressed or its accelerator is activated.
</description>
</signal>
+ <signal name="menu_changed">
+ <description>
+ </description>
+ </signal>
</signals>
<theme_items>
<theme_item name="font_accelerator_color" data_type="color" type="Color" default="Color(0.7, 0.7, 0.7, 0.8)">
@@ -566,6 +570,9 @@
<theme_item name="h_separation" data_type="constant" type="int" default="4">
The horizontal space between the item's elements.
</theme_item>
+ <theme_item name="indent" data_type="constant" type="int" default="10">
+ Width of the single indentation level.
+ </theme_item>
<theme_item name="item_end_padding" data_type="constant" type="int" default="2">
</theme_item>
<theme_item name="item_start_padding" data_type="constant" type="int" default="2">
diff --git a/doc/classes/PrimitiveMesh.xml b/doc/classes/PrimitiveMesh.xml
index 7046a21f68..1b9ecdbfa0 100644
--- a/doc/classes/PrimitiveMesh.xml
+++ b/doc/classes/PrimitiveMesh.xml
@@ -4,7 +4,7 @@
Base class for all primitive meshes. Handles applying a [Material] to a primitive mesh.
</brief_description>
<description>
- Base class for all primitive meshes. Handles applying a [Material] to a primitive mesh. Examples include [BoxMesh], [CapsuleMesh], [CylinderMesh], [PlaneMesh], [PrismMesh], [QuadMesh], and [SphereMesh].
+ Base class for all primitive meshes. Handles applying a [Material] to a primitive mesh. Examples include [BoxMesh], [CapsuleMesh], [CylinderMesh], [PlaneMesh], [PrismMesh], and [SphereMesh].
</description>
<tutorials>
</tutorials>
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index 9dd41d270e..a2e202b218 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -129,20 +129,6 @@
Returns the localized path (starting with [code]res://[/code]) corresponding to the absolute, native OS [param path]. See also [method globalize_path].
</description>
</method>
- <method name="property_can_revert">
- <return type="bool" />
- <param index="0" name="name" type="String" />
- <description>
- Returns [code]true[/code] if the specified property exists and its initial value differs from the current value.
- </description>
- </method>
- <method name="property_get_revert">
- <return type="Variant" />
- <param index="0" name="name" type="String" />
- <description>
- Returns the specified property's initial value. Returns [code]null[/code] if the property does not exist.
- </description>
- </method>
<method name="save">
<return type="int" enum="Error" />
<description>
@@ -292,6 +278,8 @@
</member>
<member name="audio/driver/driver" type="String" setter="" getter="">
Specifies the audio driver to use. This setting is platform-dependent as each platform supports different audio drivers. If left empty, the default audio driver will be used.
+ The [code]Dummy[/code] audio driver disables all audio playback and recording, which is useful for non-game applications as it reduces CPU usage. It also prevents the engine from appearing as an application playing audio in the OS' audio mixer.
+ [b]Note:[/b] The driver in use can be overridden at runtime via the [code]--audio-driver[/code] command line argument.
</member>
<member name="audio/driver/enable_input" type="bool" setter="" getter="" default="false">
If [code]true[/code], microphone input will be allowed. This requires appropriate permissions to be set when exporting to Android or iOS.
@@ -344,7 +332,7 @@
Path to logs within the project. Using an [code]user://[/code] path is recommended.
</member>
<member name="debug/file_logging/max_log_files" type="int" setter="" getter="" default="5">
- Specifies the maximum amount of log files allowed (used for rotation).
+ Specifies the maximum number of log files allowed (used for rotation).
</member>
<member name="debug/gdscript/warnings/assert_always_false" type="int" setter="" getter="" default="1">
If [code]enabled[/code], prints a warning or an error when an [code]assert[/code] call always returns false.
@@ -466,7 +454,7 @@
Maximum call stack allowed for debugging GDScript.
</member>
<member name="debug/settings/profiler/max_functions" type="int" setter="" getter="" default="16384">
- Maximum amount of functions per frame allowed when profiling.
+ Maximum number of functions per frame allowed when profiling.
</member>
<member name="debug/settings/stdout/print_fps" type="bool" setter="" getter="" default="false">
Print frames per second to standard output every second.
@@ -476,9 +464,6 @@
<member name="debug/settings/stdout/verbose_stdout" type="bool" setter="" getter="" default="false">
Print more information to standard output when running. It displays information such as memory leaks, which scenes and resources are being loaded, etc. This can also be enabled using the [code]--verbose[/code] or [code]-v[/code] command line argument, even on an exported project. See also [method OS.is_stdout_verbose] and [method @GlobalScope.print_verbose].
</member>
- <member name="debug/settings/visual_script/max_call_stack" type="int" setter="" getter="" default="1024">
- Maximum call stack in visual scripting, to avoid infinite recursion.
- </member>
<member name="debug/shapes/collision/contact_color" type="Color" setter="" getter="" default="Color(1, 0.2, 0.1, 0.8)">
Color of the contact points between collision shapes, visible when "Visible Collision Shapes" is enabled in the Debug menu.
</member>
@@ -576,19 +561,19 @@
Allows the window to be resizable by default.
[b]Note:[/b] This setting is ignored on iOS.
</member>
- <member name="display/window/size/viewport_height" type="int" setter="" getter="" default="600">
- Sets the game's main viewport height. On desktop platforms, this is also the initial window height.
+ <member name="display/window/size/viewport_height" type="int" setter="" getter="" default="648">
+ Sets the game's main viewport height. On desktop platforms, this is also the initial window height, represented by an indigo-colored rectangle in the 2D editor. Stretch mode settings also use this as a reference when using the [code]canvas_items[/code] or [code]viewport[/code] stretch modes. See also [member display/window/size/viewport_width], [member display/window/size/window_width_override] and [member display/window/size/window_height_override].
</member>
- <member name="display/window/size/viewport_width" type="int" setter="" getter="" default="1024">
- Sets the game's main viewport width. On desktop platforms, this is also the initial window width.
+ <member name="display/window/size/viewport_width" type="int" setter="" getter="" default="1152">
+ Sets the game's main viewport width. On desktop platforms, this is also the initial window width, represented by an indigo-colored rectangle in the 2D editor. Stretch mode settings also use this as a reference when using the [code]canvas_items[/code] or [code]viewport[/code] stretch modes. See also [member display/window/size/viewport_height], [member display/window/size/window_width_override] and [member display/window/size/window_height_override].
</member>
<member name="display/window/size/window_height_override" type="int" setter="" getter="" default="0">
- On desktop platforms, sets the game's initial window height.
- [b]Note:[/b] By default, or when set to 0, the initial window height is the [member display/window/size/viewport_height]. This setting is ignored on iOS, Android, and HTML5.
+ On desktop platforms, overrides the game's initial window height. See also [member display/window/size/window_width_override], [member display/window/size/viewport_width] and [member display/window/size/viewport_height].
+ [b]Note:[/b] By default, or when set to [code]0[/code], the initial window height is the [member display/window/size/viewport_height]. This setting is ignored on iOS, Android, and HTML5.
</member>
<member name="display/window/size/window_width_override" type="int" setter="" getter="" default="0">
- On desktop platforms, sets the game's initial window width.
- [b]Note:[/b] By default, or when set to 0, the initial window width is the viewport [member display/window/size/viewport_width]. This setting is ignored on iOS, Android, and HTML5.
+ On desktop platforms, overrides the game's initial window width. See also [member display/window/size/window_height_override], [member display/window/size/viewport_width] and [member display/window/size/viewport_height].
+ [b]Note:[/b] By default, or when set to [code]0[/code], the initial window width is the viewport [member display/window/size/viewport_width]. This setting is ignored on iOS, Android, and HTML5.
</member>
<member name="display/window/vsync/vsync_mode" type="int" setter="" getter="" default="1">
Sets the V-Sync mode for the main game window.
@@ -867,6 +852,7 @@
</member>
<member name="input_devices/pen_tablet/driver" type="String" setter="" getter="">
Specifies the tablet driver to use. If left empty, the default driver will be used.
+ [b]Note:[/b] The driver in use can be overridden at runtime via the [code]--tablet-driver[/code] command line argument.
</member>
<member name="input_devices/pen_tablet/driver.windows" type="String" setter="" getter="">
Override for [member input_devices/pen_tablet/driver] on Windows.
@@ -930,6 +916,9 @@
</member>
<member name="internationalization/rendering/text_driver" type="String" setter="" getter="" default="&quot;&quot;">
Specifies the [TextServer] to use. If left empty, the default will be used.
+ "ICU / HarfBuzz / Graphite" is the most advanced text driver, supporting right-to-left typesetting and complex scripts (for languages like Arabic, Hebrew, etc). The "Fallback" text driver does not support right-to-left typesetting and complex scripts.
+ [b]Note:[/b] The driver in use can be overridden at runtime via the [code]--text-driver[/code] command line argument.
+ [b]Note:[/b] There is an additional [code]Dummy[/code] text driver available, which disables all text rendering and font-related functionality. This driver is not listed in the project settings, but it can be enabled when running the editor or project using the [code]--text-driver Dummy[/code] command line argument.
</member>
<member name="layer_names/2d_navigation/layer_1" type="String" setter="" getter="" default="&quot;&quot;">
Optional name for the 2D navigation layer 1. If left empty, the layer will display as "Layer 1".
@@ -1441,20 +1430,6 @@
<member name="memory/limits/multithreaded_server/rid_pool_prealloc" type="int" setter="" getter="" default="60">
This is used by servers when used in multi-threading mode (servers and visual). RIDs are preallocated to avoid stalling the server requesting them on threads. If servers get stalled too often when loading resources in a thread, increase this number.
</member>
- <member name="mono/debugger_agent/port" type="int" setter="" getter="" default="23685">
- </member>
- <member name="mono/debugger_agent/wait_for_debugger" type="bool" setter="" getter="" default="false">
- </member>
- <member name="mono/debugger_agent/wait_timeout" type="int" setter="" getter="" default="3000">
- </member>
- <member name="mono/profiler/args" type="String" setter="" getter="" default="&quot;log:calls,alloc,sample,output=output.mlpd&quot;">
- </member>
- <member name="mono/profiler/enabled" type="bool" setter="" getter="" default="false">
- </member>
- <member name="mono/runtime/unhandled_exception_policy" type="int" setter="" getter="" default="0">
- The policy to use for unhandled Mono (C#) exceptions. The default "Terminate Application" exits the project as soon as an unhandled exception is thrown. "Log Error" logs an error message to the console instead, and will not interrupt the project execution when an unhandled exception is thrown.
- [b]Note:[/b] The unhandled exception policy is always set to "Log Error" in the editor, which also includes C# [code]tool[/code] scripts running within the editor as well as editor plugin code.
- </member>
<member name="navigation/2d/default_cell_size" type="int" setter="" getter="" default="1">
Default cell size for 2D navigation maps. See [method NavigationServer2D.map_set_cell_size].
</member>
@@ -1468,13 +1443,13 @@
Default edge connection margin for 3D navigation maps. See [method NavigationServer3D.map_set_edge_connection_margin].
</member>
<member name="network/limits/debugger/max_chars_per_second" type="int" setter="" getter="" default="32768">
- Maximum amount of characters allowed to send as output from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
+ Maximum number of characters allowed to send as output from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
</member>
<member name="network/limits/debugger/max_errors_per_second" type="int" setter="" getter="" default="400">
Maximum number of errors allowed to be sent from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
</member>
<member name="network/limits/debugger/max_queued_messages" type="int" setter="" getter="" default="2048">
- Maximum amount of messages in the debugger queue. Over this value, content is dropped. This helps to limit the debugger memory usage.
+ Maximum number of messages in the debugger queue. Over this value, content is dropped. This helps to limit the debugger memory usage.
</member>
<member name="network/limits/debugger/max_warnings_per_second" type="int" setter="" getter="" default="400">
Maximum number of warnings allowed to be sent from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
@@ -1565,7 +1540,7 @@
Individual shapes can have a specific bias value (see [member Shape2D.custom_solver_bias]).
</member>
<member name="physics/2d/solver/solver_iterations" type="int" setter="" getter="" default="16">
- Number of solver iterations for all contacts and constraints. The greater the amount of iterations, the more accurate the collisions will be. However, a greater amount of iterations requires more CPU power, which can decrease performance. See [constant PhysicsServer2D.SPACE_PARAM_SOLVER_ITERATIONS].
+ Number of solver iterations for all contacts and constraints. The greater the number of iterations, the more accurate the collisions will be. However, a greater number of iterations requires more CPU power, which can decrease performance. See [constant PhysicsServer2D.SPACE_PARAM_SOLVER_ITERATIONS].
</member>
<member name="physics/2d/time_before_sleep" type="float" setter="" getter="" default="0.5">
Time (in seconds) of inactivity before which a 2D physics body will put to sleep. See [constant PhysicsServer2D.SPACE_PARAM_BODY_TIME_TO_SLEEP].
@@ -1633,7 +1608,7 @@
Individual shapes can have a specific bias value (see [member Shape3D.custom_solver_bias]).
</member>
<member name="physics/3d/solver/solver_iterations" type="int" setter="" getter="" default="16">
- Number of solver iterations for all contacts and constraints. The greater the amount of iterations, the more accurate the collisions will be. However, a greater amount of iterations requires more CPU power, which can decrease performance. See [constant PhysicsServer3D.SPACE_PARAM_SOLVER_ITERATIONS].
+ Number of solver iterations for all contacts and constraints. The greater the number of iterations, the more accurate the collisions will be. However, a greater number of iterations requires more CPU power, which can decrease performance. See [constant PhysicsServer3D.SPACE_PARAM_SOLVER_ITERATIONS].
</member>
<member name="physics/3d/time_before_sleep" type="float" setter="" getter="" default="0.5">
Time (in seconds) of inactivity before which a 3D physics body will put to sleep. See [constant PhysicsServer3D.SPACE_PARAM_BODY_TIME_TO_SLEEP].
@@ -1836,7 +1811,7 @@
Max number of omnilights and spotlights renderable per object. At the default value of 8, this means that each surface can be affected by up to 8 omnilights and 8 spotlights. This is further limited by hardware support and [member rendering/limits/opengl/max_renderable_lights]. Setting this low will slightly reduce memory usage, may decrease shader compile times, and may result in faster rendering on low-end, mobile, or web devices.
</member>
<member name="rendering/limits/opengl/max_renderable_elements" type="int" setter="" getter="" default="65536">
- Max amount of elements renderable in a frame. If more elements than this are visible per frame, they will not be drawn. Keep in mind elements refer to mesh surfaces and not meshes themselves. Setting this low will slightly reduce memory usage and may decrease shader compile times, particularly on web. For most uses, the default value is suitable, but consider lowering as much as possible on web export.
+ Max number of elements renderable in a frame. If more elements than this are visible per frame, they will not be drawn. Keep in mind elements refer to mesh surfaces and not meshes themselves. Setting this low will slightly reduce memory usage and may decrease shader compile times, particularly on web. For most uses, the default value is suitable, but consider lowering as much as possible on web export.
</member>
<member name="rendering/limits/opengl/max_renderable_lights" type="int" setter="" getter="" default="32">
Max number of positional lights renderable in a frame. If more lights than this number are used, they will be ignored. Setting this low will slightly reduce memory usage and may decrease shader compile times, particularly on web. For most uses, the default value is suitable, but consider lowering as much as possible on web export.
@@ -1970,6 +1945,7 @@
<member name="rendering/textures/default_filters/anisotropic_filtering_level" type="int" setter="" getter="" default="2">
Sets the maximum number of samples to take when using anisotropic filtering on textures (as a power of two). A higher sample count will result in sharper textures at oblique angles, but is more expensive to compute. A value of [code]0[/code] forcibly disables anisotropic filtering, even on materials where it is enabled.
The anisotropic filtering level also affects decals and light projectors if they are configured to use anisotropic filtering. See [member rendering/textures/decals/filter] and [member rendering/textures/light_projectors/filter].
+ [b]Note:[/b] For performance reasons, anisotropic filtering [i]is not enabled by default[/i] on 2D and 3D materials. For this setting to have an effect in 3D, set [member BaseMaterial3D.texture_filter] to [constant BaseMaterial3D.TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC] or [constant BaseMaterial3D.TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC] on materials. For this setting to have an effect in 2D, set [member CanvasItem.texture_filter] to [constant CanvasItem.TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC] or [constant CanvasItem.TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC] on the [CanvasItem] node displaying the texture (or in [CanvasTexture]). However, anisotropic filtering is rarely useful in 2D, so only enable it for textures in 2D if it makes a meaningful visual difference.
[b]Note:[/b] This property is only read when the project starts. There is currently no way to change this setting at run-time.
</member>
<member name="rendering/textures/default_filters/texture_mipmap_bias" type="float" setter="" getter="" default="0.0">
diff --git a/doc/classes/Projection.xml b/doc/classes/Projection.xml
index b8f6e54d87..5690ea5e95 100644
--- a/doc/classes/Projection.xml
+++ b/doc/classes/Projection.xml
@@ -24,6 +24,16 @@
<description>
</description>
</constructor>
+ <constructor name="Projection">
+ <return type="Projection" />
+ <param index="0" name="x_axis" type="Vector4" />
+ <param index="1" name="y_axis" type="Vector4" />
+ <param index="2" name="z_axis" type="Vector4" />
+ <param index="3" name="w_axis" type="Vector4" />
+ <description>
+ Constructs a Projection from four [Vector4] values (matrix columns).
+ </description>
+ </constructor>
</constructors>
<methods>
<method name="create_depth_correction" qualifiers="static">
diff --git a/doc/classes/ProxyTexture.xml b/doc/classes/ProxyTexture.xml
deleted file mode 100644
index 778e3f3f69..0000000000
--- a/doc/classes/ProxyTexture.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="ProxyTexture" inherits="Texture2D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
- <brief_description>
- </brief_description>
- <description>
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="base" type="Texture2D" setter="set_base" getter="get_base">
- </member>
- </members>
-</class>
diff --git a/doc/classes/QuadMesh.xml b/doc/classes/QuadMesh.xml
deleted file mode 100644
index d641ebaa1f..0000000000
--- a/doc/classes/QuadMesh.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="QuadMesh" inherits="PrimitiveMesh" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
- <brief_description>
- Class representing a square mesh.
- </brief_description>
- <description>
- Class representing a square [PrimitiveMesh]. This flat mesh does not have a thickness. By default, this mesh is aligned on the X and Y axes; this default rotation is more suited for use with billboarded materials. Unlike [PlaneMesh], this mesh doesn't provide subdivision options.
- </description>
- <tutorials>
- <link title="GUI in 3D Demo">https://godotengine.org/asset-library/asset/127</link>
- <link title="2D in 3D Demo">https://godotengine.org/asset-library/asset/129</link>
- </tutorials>
- <members>
- <member name="center_offset" type="Vector3" setter="set_center_offset" getter="get_center_offset" default="Vector3(0, 0, 0)">
- Offset of the generated Quad. Useful for particles.
- </member>
- <member name="size" type="Vector2" setter="set_size" getter="get_size" default="Vector2(1, 1)">
- Size on the X and Y axes.
- </member>
- </members>
-</class>
diff --git a/doc/classes/Quaternion.xml b/doc/classes/Quaternion.xml
index 6fb5b6d181..a521af5709 100644
--- a/doc/classes/Quaternion.xml
+++ b/doc/classes/Quaternion.xml
@@ -71,7 +71,7 @@
<param index="0" name="to" type="Quaternion" />
<description>
Returns the angle between this quaternion and [param to]. This is the magnitude of the angle you would need to rotate by to get from one to the other.
- [b]Note:[/b] This method has an abnormally high amount of floating-point error, so methods such as [code]is_zero_approx[/code] will not work reliably.
+ [b]Note:[/b] This method has an abnormally high number of floating-point errors, so methods such as [code]is_zero_approx[/code] will not work reliably.
</description>
</method>
<method name="dot" qualifiers="const">
@@ -171,6 +171,20 @@
Performs a spherical cubic interpolation between quaternions [param pre_a], this vector, [param b], and [param post_b], by the given amount [param weight].
</description>
</method>
+ <method name="spherical_cubic_interpolate_in_time" qualifiers="const">
+ <return type="Quaternion" />
+ <param index="0" name="b" type="Quaternion" />
+ <param index="1" name="pre_a" type="Quaternion" />
+ <param index="2" name="post_b" type="Quaternion" />
+ <param index="3" name="weight" type="float" />
+ <param index="4" name="b_t" type="float" />
+ <param index="5" name="pre_a_t" type="float" />
+ <param index="6" name="post_b_t" type="float" />
+ <description>
+ Performs a spherical cubic interpolation between quaternions [param pre_a], this vector, [param b], and [param post_b], by the given amount [param weight].
+ It can perform smoother interpolation than [code]spherical_cubic_interpolate()[/code] by the time values.
+ </description>
+ </method>
</methods>
<members>
<member name="w" type="float" setter="" getter="" default="1.0">
diff --git a/doc/classes/RDUniform.xml b/doc/classes/RDUniform.xml
index d144024000..e4b7883f02 100644
--- a/doc/classes/RDUniform.xml
+++ b/doc/classes/RDUniform.xml
@@ -19,7 +19,7 @@
</description>
</method>
<method name="get_ids" qualifiers="const">
- <return type="Array" />
+ <return type="RID[]" />
<description>
</description>
</method>
diff --git a/doc/classes/RayCast2D.xml b/doc/classes/RayCast2D.xml
index 4f4395a433..08627b0bd5 100644
--- a/doc/classes/RayCast2D.xml
+++ b/doc/classes/RayCast2D.xml
@@ -47,6 +47,12 @@
Returns the first object that the ray intersects, or [code]null[/code] if no object is intersecting the ray (i.e. [method is_colliding] returns [code]false[/code]).
</description>
</method>
+ <method name="get_collider_rid" qualifiers="const">
+ <return type="RID" />
+ <description>
+ Returns the [RID] of the first object that the ray intersects, or an empty [RID] if no object is intersecting the ray (i.e. [method is_colliding] returns [code]false[/code]).
+ </description>
+ </method>
<method name="get_collider_shape" qualifiers="const">
<return type="int" />
<description>
diff --git a/doc/classes/RayCast3D.xml b/doc/classes/RayCast3D.xml
index 7cc6fc55cd..1bcd6f1f31 100644
--- a/doc/classes/RayCast3D.xml
+++ b/doc/classes/RayCast3D.xml
@@ -48,6 +48,12 @@
Returns the first object that the ray intersects, or [code]null[/code] if no object is intersecting the ray (i.e. [method is_colliding] returns [code]false[/code]).
</description>
</method>
+ <method name="get_collider_rid" qualifiers="const">
+ <return type="RID" />
+ <description>
+ Returns the [RID] of the first object that the ray intersects, or an empty [RID] if no object is intersecting the ray (i.e. [method is_colliding] returns [code]false[/code]).
+ </description>
+ </method>
<method name="get_collider_shape" qualifiers="const">
<return type="int" />
<description>
diff --git a/doc/classes/ReflectionProbe.xml b/doc/classes/ReflectionProbe.xml
index ff66a89cb7..fee48dd246 100644
--- a/doc/classes/ReflectionProbe.xml
+++ b/doc/classes/ReflectionProbe.xml
@@ -50,7 +50,7 @@
[b]Note:[/b] [member mesh_lod_threshold] does not affect [GeometryInstance3D] visibility ranges (also known as "manual" LOD or hierarchical LOD).
</member>
<member name="origin_offset" type="Vector3" setter="set_origin_offset" getter="get_origin_offset" default="Vector3(0, 0, 0)">
- Sets the origin offset to be used when this [ReflectionProbe] is in [member box_projection] mode. This can be set to a non-zero value to ensure a reflection fits a rectangle-shaped room, while reducing the amount of objects that "get in the way" of the reflection.
+ Sets the origin offset to be used when this [ReflectionProbe] is in [member box_projection] mode. This can be set to a non-zero value to ensure a reflection fits a rectangle-shaped room, while reducing the number of objects that "get in the way" of the reflection.
</member>
<member name="update_mode" type="int" setter="set_update_mode" getter="get_update_mode" enum="ReflectionProbe.UpdateMode" default="0">
Sets how frequently the [ReflectionProbe] is updated. Can be [constant UPDATE_ONCE] or [constant UPDATE_ALWAYS].
diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml
index bd930bf93f..a12bd71454 100644
--- a/doc/classes/RenderingServer.xml
+++ b/doc/classes/RenderingServer.xml
@@ -1406,7 +1406,7 @@
</description>
</method>
<method name="instance_geometry_get_shader_uniform_list" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="instance" type="RID" />
<description>
</description>
@@ -1581,7 +1581,7 @@
</description>
</method>
<method name="instances_cull_aabb" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt64Array" />
<param index="0" name="aabb" type="AABB" />
<param index="1" name="scenario" type="RID" />
<description>
@@ -1590,7 +1590,7 @@
</description>
</method>
<method name="instances_cull_convex" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt64Array" />
<param index="0" name="convex" type="Array" />
<param index="1" name="scenario" type="RID" />
<description>
@@ -1599,7 +1599,7 @@
</description>
</method>
<method name="instances_cull_ray" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt64Array" />
<param index="0" name="from" type="Vector3" />
<param index="1" name="to" type="Vector3" />
<param index="2" name="scenario" type="RID" />
@@ -1801,7 +1801,7 @@
<param index="1" name="longitudes" type="int" />
<param index="2" name="radius" type="float" />
<description>
- Returns a mesh of a sphere with the given amount of horizontal and vertical subdivisions.
+ Returns a mesh of a sphere with the given number of horizontal and vertical subdivisions.
</description>
</method>
<method name="material_create">
@@ -1959,7 +1959,7 @@
</description>
</method>
<method name="mesh_surface_get_blend_shape_arrays" qualifiers="const">
- <return type="Array" />
+ <return type="Array[]" />
<param index="0" name="mesh" type="RID" />
<param index="1" name="surface" type="int" />
<description>
diff --git a/doc/classes/ResourceFormatSaver.xml b/doc/classes/ResourceFormatSaver.xml
index a84c2165f5..05bfcf3446 100644
--- a/doc/classes/ResourceFormatSaver.xml
+++ b/doc/classes/ResourceFormatSaver.xml
@@ -26,8 +26,8 @@
</method>
<method name="_save" qualifiers="virtual">
<return type="int" />
- <param index="0" name="path" type="Resource" />
- <param index="1" name="resource" type="String" />
+ <param index="0" name="resource" type="Resource" />
+ <param index="1" name="path" type="String" />
<param index="2" name="flags" type="int" />
<description>
Saves the given resource object to a file at the target [param path]. [param flags] is a bitmask composed with [enum ResourceSaver.SaverFlags] constants.
diff --git a/doc/classes/RichTextLabel.xml b/doc/classes/RichTextLabel.xml
index 62142fce8b..f96e136a57 100644
--- a/doc/classes/RichTextLabel.xml
+++ b/doc/classes/RichTextLabel.xml
@@ -481,8 +481,8 @@
If [code]true[/code], the label uses the custom font color.
</member>
<member name="percent_visible" type="float" setter="set_percent_visible" getter="get_percent_visible" default="1.0">
- The range of characters to display, as a [float] between 0.0 and 1.0. When assigned an out of range value, it's the same as assigning 1.0.
- [b]Note:[/b] Setting this property updates [member visible_characters] based on current [method get_total_character_count].
+ The fraction of characters to display, relative to the total number of characters (see [method get_total_character_count]). If set to [code]1.0[/code], all characters are displayed. If set to [code]0.5[/code], only half of the characters will be displayed. This can be useful when animating the text appearing in a dialog box.
+ [b]Note:[/b] Setting this property updates [member visible_characters] accordingly.
</member>
<member name="progress_bar_delay" type="int" setter="set_progress_bar_delay" getter="get_progress_bar_delay" default="1000">
The delay after which the loading progress bar is displayed, in milliseconds. Set to [code]-1[/code] to disable progress bar entirely.
@@ -520,8 +520,8 @@
If [code]true[/code], text processing is done in a background thread.
</member>
<member name="visible_characters" type="int" setter="set_visible_characters" getter="get_visible_characters" default="-1">
- The restricted number of characters to display in the label. If [code]-1[/code], all characters will be displayed.
- [b]Note:[/b] Setting this property updates [member percent_visible] based on current [method get_total_character_count].
+ The number of characters to display. If set to [code]-1[/code], all characters are displayed. This can be useful when animating the text appearing in a dialog box.
+ [b]Note:[/b] Setting this property updates [member percent_visible] accordingly.
</member>
<member name="visible_characters_behavior" type="int" setter="set_visible_characters_behavior" getter="get_visible_characters_behavior" enum="TextServer.VisibleCharactersBehavior" default="0">
Sets the clipping behavior when [member visible_characters] or [member percent_visible] is set. See [enum TextServer.VisibleCharactersBehavior] for more info.
diff --git a/doc/classes/RigidDynamicBody2D.xml b/doc/classes/RigidDynamicBody2D.xml
index 445e6d94ea..1434affee1 100644
--- a/doc/classes/RigidDynamicBody2D.xml
+++ b/doc/classes/RigidDynamicBody2D.xml
@@ -100,10 +100,17 @@
<method name="get_colliding_bodies" qualifiers="const">
<return type="Node2D[]" />
<description>
- Returns a list of the bodies colliding with this one. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions.
+ Returns a list of the bodies colliding with this one. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions.
[b]Note:[/b] The result of this test is not immediate after moving objects. For performance, list of collisions is updated once per frame and before the physics step. Consider using signals instead.
</description>
</method>
+ <method name="get_contact_count" qualifiers="const">
+ <return type="int" />
+ <description>
+ Returns the number of contacts this body has with other bodies. By default, this returns 0 unless bodies are configured to monitor contacts (see [member contact_monitor]).
+ [b]Note:[/b] To retrieve the colliding bodies, use [method get_colliding_bodies].
+ </description>
+ </method>
<method name="set_axis_velocity">
<return type="void" />
<param index="0" name="axis_velocity" type="Vector2" />
@@ -142,11 +149,8 @@
See [method add_constant_torque].
</member>
<member name="contact_monitor" type="bool" setter="set_contact_monitor" getter="is_contact_monitor_enabled" default="false">
- If [code]true[/code], the body will emit signals when it collides with another RigidDynamicBody2D. See also [member contacts_reported].
- </member>
- <member name="contacts_reported" type="int" setter="set_max_contacts_reported" getter="get_max_contacts_reported" default="0">
- The maximum number of contacts that will be recorded. Requires [member contact_monitor] to be set to [code]true[/code].
- [b]Note:[/b] The number of contacts is different from the number of collisions. Collisions between parallel edges will result in two contacts (one at each end).
+ If [code]true[/code], the RigidDynamicBody2D will emit signals when it collides with another RigidDynamicBody2D.
+ [b]Note:[/b] By default the maximum contacts reported is set to 0, meaning nothing will be recorded, see [member max_contacts_reported].
</member>
<member name="continuous_cd" type="int" setter="set_continuous_collision_detection_mode" getter="get_continuous_collision_detection_mode" enum="RigidDynamicBody2D.CCDMode" default="0">
Continuous collision detection mode.
@@ -187,6 +191,10 @@
<member name="mass" type="float" setter="set_mass" getter="get_mass" default="1.0">
The body's mass.
</member>
+ <member name="max_contacts_reported" type="int" setter="set_max_contacts_reported" getter="get_max_contacts_reported" default="0">
+ The maximum number of contacts that will be recorded. Requires a value greater than 0 and [member contact_monitor] to be set to [code]true[/code] to start to register contacts. Use [method get_contact_count] to retrieve the count or [method get_colliding_bodies] to retrieve bodies that have been collided with.
+ [b]Note:[/b] The number of contacts is different from the number of collisions. Collisions between parallel edges will result in two contacts (one at each end), and collisions between parallel faces will result in four contacts (one at each corner).
+ </member>
<member name="physics_material_override" type="PhysicsMaterial" setter="set_physics_material_override" getter="get_physics_material_override">
The physics material override for the body.
If a material is assigned to this property, it will be used instead of any other physics material, such as an inherited one.
@@ -199,14 +207,14 @@
<signal name="body_entered">
<param index="0" name="body" type="Node" />
<description>
- Emitted when a collision with another [PhysicsBody2D] or [TileMap] occurs. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
+ Emitted when a collision with another [PhysicsBody2D] or [TileMap] occurs. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody2D] or [TileMap].
</description>
</signal>
<signal name="body_exited">
<param index="0" name="body" type="Node" />
<description>
- Emitted when the collision with another [PhysicsBody2D] or [TileMap] ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
+ Emitted when the collision with another [PhysicsBody2D] or [TileMap] ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody2D] or [TileMap].
</description>
</signal>
@@ -216,7 +224,7 @@
<param index="2" name="body_shape_index" type="int" />
<param index="3" name="local_shape_index" type="int" />
<description>
- Emitted when one of this RigidDynamicBody2D's [Shape2D]s collides with another [PhysicsBody2D] or [TileMap]'s [Shape2D]s. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
+ Emitted when one of this RigidDynamicBody2D's [Shape2D]s collides with another [PhysicsBody2D] or [TileMap]'s [Shape2D]s. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
[param body_rid] the [RID] of the other [PhysicsBody2D] or [TileSet]'s [CollisionObject2D] used by the [PhysicsServer2D].
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody2D] or [TileMap].
[param body_shape_index] the index of the [Shape2D] of the other [PhysicsBody2D] or [TileMap] used by the [PhysicsServer2D]. Get the [CollisionShape2D] node with [code]body.shape_owner_get_owner(body.shape_find_owner(body_shape_index))[/code].
@@ -229,7 +237,7 @@
<param index="2" name="body_shape_index" type="int" />
<param index="3" name="local_shape_index" type="int" />
<description>
- Emitted when the collision between one of this RigidDynamicBody2D's [Shape2D]s and another [PhysicsBody2D] or [TileMap]'s [Shape2D]s ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
+ Emitted when the collision between one of this RigidDynamicBody2D's [Shape2D]s and another [PhysicsBody2D] or [TileMap]'s [Shape2D]s ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [TileMap]s are detected if the [TileSet] has Collision [Shape2D]s.
[param body_rid] the [RID] of the other [PhysicsBody2D] or [TileSet]'s [CollisionObject2D] used by the [PhysicsServer2D].
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody2D] or [TileMap].
[param body_shape_index] the index of the [Shape2D] of the other [PhysicsBody2D] or [TileMap] used by the [PhysicsServer2D]. Get the [CollisionShape2D] node with [code]body.shape_owner_get_owner(body.shape_find_owner(body_shape_index))[/code].
diff --git a/doc/classes/RigidDynamicBody3D.xml b/doc/classes/RigidDynamicBody3D.xml
index 83f24be418..fb747177ae 100644
--- a/doc/classes/RigidDynamicBody3D.xml
+++ b/doc/classes/RigidDynamicBody3D.xml
@@ -98,12 +98,19 @@
</description>
</method>
<method name="get_colliding_bodies" qualifiers="const">
- <return type="Array" />
+ <return type="Node3D[]" />
<description>
- Returns a list of the bodies colliding with this one. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions.
+ Returns a list of the bodies colliding with this one. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions.
[b]Note:[/b] The result of this test is not immediate after moving objects. For performance, list of collisions is updated once per frame and before the physics step. Consider using signals instead.
</description>
</method>
+ <method name="get_contact_count" qualifiers="const">
+ <return type="int" />
+ <description>
+ Returns the number of contacts this body has with other bodies. By default, this returns 0 unless bodies are configured to monitor contacts (see [member contact_monitor]).
+ [b]Note:[/b] To retrieve the colliding bodies, use [method get_colliding_bodies].
+ </description>
+ </method>
<method name="get_inverse_inertia_tensor" qualifiers="const">
<return type="Basis" />
<description>
@@ -148,11 +155,8 @@
See [method add_constant_torque].
</member>
<member name="contact_monitor" type="bool" setter="set_contact_monitor" getter="is_contact_monitor_enabled" default="false">
- If [code]true[/code], the RigidDynamicBody3D will emit signals when it collides with another RigidDynamicBody3D. See also [member contacts_reported].
- </member>
- <member name="contacts_reported" type="int" setter="set_max_contacts_reported" getter="get_max_contacts_reported" default="0">
- The maximum number of contacts that will be recorded. Requires [member contact_monitor] to be set to [code]true[/code].
- [b]Note:[/b] The number of contacts is different from the number of collisions. Collisions between parallel edges will result in two contacts (one at each end), and collisions between parallel faces will result in four contacts (one at each corner).
+ If [code]true[/code], the RigidDynamicBody3D will emit signals when it collides with another RigidDynamicBody3D.
+ [b]Note:[/b] By default the maximum contacts reported is set to 0, meaning nothing will be recorded, see [member max_contacts_reported].
</member>
<member name="continuous_cd" type="bool" setter="set_use_continuous_collision_detection" getter="is_using_continuous_collision_detection" default="false">
If [code]true[/code], continuous collision detection is used.
@@ -193,6 +197,10 @@
<member name="mass" type="float" setter="set_mass" getter="get_mass" default="1.0">
The body's mass.
</member>
+ <member name="max_contacts_reported" type="int" setter="set_max_contacts_reported" getter="get_max_contacts_reported" default="0">
+ The maximum number of contacts that will be recorded. Requires a value greater than 0 and [member contact_monitor] to be set to [code]true[/code] to start to register contacts. Use [method get_contact_count] to retrieve the count or [method get_colliding_bodies] to retrieve bodies that have been collided with.
+ [b]Note:[/b] The number of contacts is different from the number of collisions. Collisions between parallel edges will result in two contacts (one at each end), and collisions between parallel faces will result in four contacts (one at each corner).
+ </member>
<member name="physics_material_override" type="PhysicsMaterial" setter="set_physics_material_override" getter="get_physics_material_override">
The physics material override for the body.
If a material is assigned to this property, it will be used instead of any other physics material, such as an inherited one.
@@ -205,14 +213,14 @@
<signal name="body_entered">
<param index="0" name="body" type="Node" />
<description>
- Emitted when a collision with another [PhysicsBody3D] or [GridMap] occurs. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
+ Emitted when a collision with another [PhysicsBody3D] or [GridMap] occurs. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody3D] or [GridMap].
</description>
</signal>
<signal name="body_exited">
<param index="0" name="body" type="Node" />
<description>
- Emitted when the collision with another [PhysicsBody3D] or [GridMap] ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
+ Emitted when the collision with another [PhysicsBody3D] or [GridMap] ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody3D] or [GridMap].
</description>
</signal>
@@ -222,7 +230,7 @@
<param index="2" name="body_shape_index" type="int" />
<param index="3" name="local_shape_index" type="int" />
<description>
- Emitted when one of this RigidDynamicBody3D's [Shape3D]s collides with another [PhysicsBody3D] or [GridMap]'s [Shape3D]s. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
+ Emitted when one of this RigidDynamicBody3D's [Shape3D]s collides with another [PhysicsBody3D] or [GridMap]'s [Shape3D]s. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
[param body_rid] the [RID] of the other [PhysicsBody3D] or [MeshLibrary]'s [CollisionObject3D] used by the [PhysicsServer3D].
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody3D] or [GridMap].
[param body_shape_index] the index of the [Shape3D] of the other [PhysicsBody3D] or [GridMap] used by the [PhysicsServer3D]. Get the [CollisionShape3D] node with [code]body.shape_owner_get_owner(body.shape_find_owner(body_shape_index))[/code].
@@ -235,7 +243,7 @@
<param index="2" name="body_shape_index" type="int" />
<param index="3" name="local_shape_index" type="int" />
<description>
- Emitted when the collision between one of this RigidDynamicBody3D's [Shape3D]s and another [PhysicsBody3D] or [GridMap]'s [Shape3D]s ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
+ Emitted when the collision between one of this RigidDynamicBody3D's [Shape3D]s and another [PhysicsBody3D] or [GridMap]'s [Shape3D]s ends. Requires [member contact_monitor] to be set to [code]true[/code] and [member max_contacts_reported] to be set high enough to detect all the collisions. [GridMap]s are detected if the [MeshLibrary] has Collision [Shape3D]s.
[param body_rid] the [RID] of the other [PhysicsBody3D] or [MeshLibrary]'s [CollisionObject3D] used by the [PhysicsServer3D]. [GridMap]s are detected if the Meshes have [Shape3D]s.
[param body] the [Node], if it exists in the tree, of the other [PhysicsBody3D] or [GridMap].
[param body_shape_index] the index of the [Shape3D] of the other [PhysicsBody3D] or [GridMap] used by the [PhysicsServer3D]. Get the [CollisionShape3D] node with [code]body.shape_owner_get_owner(body.shape_find_owner(body_shape_index))[/code].
diff --git a/doc/classes/SceneTree.xml b/doc/classes/SceneTree.xml
index 0b358bd06f..417703ff01 100644
--- a/doc/classes/SceneTree.xml
+++ b/doc/classes/SceneTree.xml
@@ -113,14 +113,14 @@
</description>
</method>
<method name="get_nodes_in_group">
- <return type="Array" />
+ <return type="Node[]" />
<param index="0" name="group" type="StringName" />
<description>
Returns a list of all nodes assigned to the given group.
</description>
</method>
<method name="get_processed_tweens">
- <return type="Array" />
+ <return type="Tween[]" />
<description>
Returns an array of currently existing [Tween]s in the [SceneTree] (both running and paused).
</description>
diff --git a/doc/classes/Script.xml b/doc/classes/Script.xml
index 8202f9f536..40ec8ed429 100644
--- a/doc/classes/Script.xml
+++ b/doc/classes/Script.xml
@@ -44,19 +44,19 @@
</description>
</method>
<method name="get_script_method_list">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns the list of methods in this [Script].
</description>
</method>
<method name="get_script_property_list">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns the list of properties in this [Script].
</description>
</method>
<method name="get_script_signal_list">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns the list of user signals defined in this [Script].
</description>
diff --git a/doc/classes/ScriptEditor.xml b/doc/classes/ScriptEditor.xml
index 9118f38a3e..becaff975e 100644
--- a/doc/classes/ScriptEditor.xml
+++ b/doc/classes/ScriptEditor.xml
@@ -22,13 +22,13 @@
</description>
</method>
<method name="get_open_script_editors" qualifiers="const">
- <return type="Array" />
+ <return type="ScriptEditorBase[]" />
<description>
Returns an array with all [ScriptEditorBase] objects which are currently open in editor.
</description>
</method>
<method name="get_open_scripts" qualifiers="const">
- <return type="Array" />
+ <return type="Script[]" />
<description>
Returns an array with all [Script] objects which are currently open in editor.
</description>
diff --git a/doc/classes/ScriptExtension.xml b/doc/classes/ScriptExtension.xml
index b59c49d785..045eadda41 100644
--- a/doc/classes/ScriptExtension.xml
+++ b/doc/classes/ScriptExtension.xml
@@ -96,6 +96,12 @@
<description>
</description>
</method>
+ <method name="_has_property_default_value" qualifiers="virtual const">
+ <return type="bool" />
+ <param index="0" name="property" type="StringName" />
+ <description>
+ </description>
+ </method>
<method name="_has_script_signal" qualifiers="virtual const">
<return type="bool" />
<param index="0" name="signal" type="StringName" />
diff --git a/doc/classes/ShaderMaterial.xml b/doc/classes/ShaderMaterial.xml
index 92df3255b1..8d4df87b39 100644
--- a/doc/classes/ShaderMaterial.xml
+++ b/doc/classes/ShaderMaterial.xml
@@ -17,20 +17,6 @@
Returns the current value set for this material of a uniform in the shader.
</description>
</method>
- <method name="property_can_revert">
- <return type="bool" />
- <param index="0" name="name" type="String" />
- <description>
- Returns [code]true[/code] if the property identified by [param name] can be reverted to a default value.
- </description>
- </method>
- <method name="property_get_revert">
- <return type="Variant" />
- <param index="0" name="name" type="String" />
- <description>
- Returns the default value of the material property with given [param name].
- </description>
- </method>
<method name="set_shader_uniform">
<return type="void" />
<param index="0" name="param" type="StringName" />
diff --git a/doc/classes/Shape2D.xml b/doc/classes/Shape2D.xml
index 4d7031ab86..34ca228795 100644
--- a/doc/classes/Shape2D.xml
+++ b/doc/classes/Shape2D.xml
@@ -21,7 +21,7 @@
</description>
</method>
<method name="collide_and_get_contacts">
- <return type="Array" />
+ <return type="PackedVector2Array" />
<param index="0" name="local_xform" type="Transform2D" />
<param index="1" name="with_shape" type="Shape2D" />
<param index="2" name="shape_xform" type="Transform2D" />
@@ -45,7 +45,7 @@
</description>
</method>
<method name="collide_with_motion_and_get_contacts">
- <return type="Array" />
+ <return type="PackedVector2Array" />
<param index="0" name="local_xform" type="Transform2D" />
<param index="1" name="local_motion" type="Vector2" />
<param index="2" name="with_shape" type="Shape2D" />
diff --git a/doc/classes/Skeleton3D.xml b/doc/classes/Skeleton3D.xml
index 7f2a41e00c..75f7a37752 100644
--- a/doc/classes/Skeleton3D.xml
+++ b/doc/classes/Skeleton3D.xml
@@ -20,15 +20,6 @@
Adds a bone, with name [param name]. [method get_bone_count] will become the bone index.
</description>
</method>
- <method name="add_bone_child">
- <return type="void" />
- <param index="0" name="bone_idx" type="int" />
- <param index="1" name="child_bone_idx" type="int" />
- <description>
- Takes the given bone pose/transform and converts it to a world transform, relative to the [Skeleton3D] node.
- This is useful for using the bone transform in calculations with transforms from [Node3D]-based nodes.
- </description>
- </method>
<method name="clear_bones">
<return type="void" />
<description>
@@ -90,7 +81,7 @@
<method name="get_bone_count" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of bones in the skeleton.
+ Returns the number of bones in the skeleton.
</description>
</method>
<method name="get_bone_global_pose" qualifiers="const">
@@ -272,21 +263,17 @@
Binds the given Skin to the Skeleton.
</description>
</method>
- <method name="remove_bone_child">
+ <method name="reset_bone_pose">
<return type="void" />
<param index="0" name="bone_idx" type="int" />
- <param index="1" name="child_bone_idx" type="int" />
<description>
- Removes the passed in child bone index, [param child_bone_idx], from the passed-in bone, [param bone_idx], if it exists.
- [b]Note:[/b] This does not remove the child bone, but instead it removes the connection it has to the parent bone.
+ Sets the bone pose to rest for [param bone_idx].
</description>
</method>
- <method name="set_bone_children">
+ <method name="reset_bone_poses">
<return type="void" />
- <param index="0" name="bone_idx" type="int" />
- <param index="1" name="bone_children" type="PackedInt32Array" />
<description>
- Sets the children for the passed in bone, [param bone_idx], to the passed-in array of bone indexes, [param bone_children].
+ Sets all bone poses to rests.
</description>
</method>
<method name="set_bone_enabled">
diff --git a/doc/classes/SkeletonModification2DCCDIK.xml b/doc/classes/SkeletonModification2DCCDIK.xml
index e37dc62131..c8fee3f94d 100644
--- a/doc/classes/SkeletonModification2DCCDIK.xml
+++ b/doc/classes/SkeletonModification2DCCDIK.xml
@@ -121,7 +121,7 @@
</methods>
<members>
<member name="ccdik_data_chain_length" type="int" setter="set_ccdik_data_chain_length" getter="get_ccdik_data_chain_length" default="0">
- The amount of CCDIK joints in the CCDIK modification.
+ The number of CCDIK joints in the CCDIK modification.
</member>
<member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath(&quot;&quot;)">
The NodePath to the node that is the target for the CCDIK modification. This node is what the CCDIK chain will attempt to rotate the bone chain to.
diff --git a/doc/classes/SkeletonModification2DFABRIK.xml b/doc/classes/SkeletonModification2DFABRIK.xml
index 1240174946..ff3a65fe1a 100644
--- a/doc/classes/SkeletonModification2DFABRIK.xml
+++ b/doc/classes/SkeletonModification2DFABRIK.xml
@@ -77,7 +77,7 @@
</methods>
<members>
<member name="fabrik_data_chain_length" type="int" setter="set_fabrik_data_chain_length" getter="get_fabrik_data_chain_length" default="0">
- The amount of FABRIK joints in the FABRIK modification.
+ The number of FABRIK joints in the FABRIK modification.
</member>
<member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath(&quot;&quot;)">
The NodePath to the node that is the target for the FABRIK modification. This node is what the FABRIK chain will attempt to rotate the bone chain to.
diff --git a/doc/classes/SkeletonModification2DPhysicalBones.xml b/doc/classes/SkeletonModification2DPhysicalBones.xml
index 66ff160ab1..d5f46b2ea0 100644
--- a/doc/classes/SkeletonModification2DPhysicalBones.xml
+++ b/doc/classes/SkeletonModification2DPhysicalBones.xml
@@ -50,7 +50,7 @@
</methods>
<members>
<member name="physical_bone_chain_length" type="int" setter="set_physical_bone_chain_length" getter="get_physical_bone_chain_length" default="0">
- The amount of [PhysicalBone2D] nodes linked in this modification.
+ The number of [PhysicalBone2D] nodes linked in this modification.
</member>
</members>
</class>
diff --git a/doc/classes/SkeletonModification3DCCDIK.xml b/doc/classes/SkeletonModification3DCCDIK.xml
index 207896776f..dec0fbe99f 100644
--- a/doc/classes/SkeletonModification3DCCDIK.xml
+++ b/doc/classes/SkeletonModification3DCCDIK.xml
@@ -121,7 +121,7 @@
</methods>
<members>
<member name="ccdik_data_chain_length" type="int" setter="set_ccdik_data_chain_length" getter="get_ccdik_data_chain_length" default="0">
- The amount of CCDIK joints in the CCDIK modification.
+ The number of CCDIK joints in the CCDIK modification.
</member>
<member name="high_quality_solve" type="bool" setter="set_use_high_quality_solve" getter="get_use_high_quality_solve" default="true">
When true, the CCDIK algorithm will perform a higher quality solve that returns more natural results. A high quality solve requires more computation power to solve though, and therefore can be disabled to save performance.
diff --git a/doc/classes/SkeletonModificationStack3D.xml b/doc/classes/SkeletonModificationStack3D.xml
index fd4a8d462a..34c7099bca 100644
--- a/doc/classes/SkeletonModificationStack3D.xml
+++ b/doc/classes/SkeletonModificationStack3D.xml
@@ -79,7 +79,7 @@
When true, the modification's in the stack will be called. This is handled automatically through the [Skeleton3D] node.
</member>
<member name="modification_count" type="int" setter="set_modification_count" getter="get_modification_count" default="0">
- The amount of modifications in the stack.
+ The number of modifications in the stack.
</member>
<member name="strength" type="float" setter="set_strength" getter="get_strength" default="1.0">
The interpolation strength of the modifications in stack. A value of [code]0[/code] will make it where the modifications are not applied, a strength of [code]0.5[/code] will be half applied, and a strength of [code]1[/code] will allow the modifications to be fully applied and override the skeleton bone poses.
diff --git a/doc/classes/SliderJoint3D.xml b/doc/classes/SliderJoint3D.xml
index 7470f89979..a67c38b12d 100644
--- a/doc/classes/SliderJoint3D.xml
+++ b/doc/classes/SliderJoint3D.xml
@@ -28,7 +28,7 @@
The amount of damping of the rotation when the limit is surpassed.
A lower damping value allows a rotation initiated by body A to travel to body B slower.
</member>
- <member name="angular_limit/lower_angle" type="float" setter="_set_lower_limit_angular" getter="_get_lower_limit_angular" default="0.0">
+ <member name="angular_limit/lower_angle" type="float" setter="set_param" getter="get_param" default="0.0">
The lower limit of rotation in the slider.
</member>
<member name="angular_limit/restitution" type="float" setter="set_param" getter="get_param" default="0.7">
@@ -39,7 +39,7 @@
A factor applied to the all rotation once the limit is surpassed.
Makes all rotation slower when between 0 and 1.
</member>
- <member name="angular_limit/upper_angle" type="float" setter="_set_upper_limit_angular" getter="_get_upper_limit_angular" default="0.0">
+ <member name="angular_limit/upper_angle" type="float" setter="set_param" getter="get_param" default="0.0">
The upper limit of rotation in the slider.
</member>
<member name="angular_motion/damping" type="float" setter="set_param" getter="get_param" default="1.0">
diff --git a/doc/classes/SoftDynamicBody3D.xml b/doc/classes/SoftDynamicBody3D.xml
index 87492704d7..7f0a1d94d0 100644
--- a/doc/classes/SoftDynamicBody3D.xml
+++ b/doc/classes/SoftDynamicBody3D.xml
@@ -19,7 +19,7 @@
</description>
</method>
<method name="get_collision_exceptions">
- <return type="Array" />
+ <return type="PhysicsBody3D[]" />
<description>
Returns an array of nodes that were added as collision exceptions for this body.
</description>
diff --git a/doc/classes/StreamPeer.xml b/doc/classes/StreamPeer.xml
index 5bad9796b4..4188563695 100644
--- a/doc/classes/StreamPeer.xml
+++ b/doc/classes/StreamPeer.xml
@@ -37,14 +37,14 @@
<method name="get_available_bytes" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of bytes this [StreamPeer] has available.
+ Returns the number of bytes this [StreamPeer] has available.
</description>
</method>
<method name="get_data">
<return type="Array" />
<param index="0" name="bytes" type="int" />
<description>
- Returns a chunk data with the received bytes. The amount of bytes to be received can be requested in the [param bytes] argument. If not enough bytes are available, the function will block until the desired amount is received. This function returns two values, an [enum @GlobalScope.Error] code and a data array.
+ Returns a chunk data with the received bytes. The number of bytes to be received can be requested in the [param bytes] argument. If not enough bytes are available, the function will block until the desired amount is received. This function returns two values, an [enum @GlobalScope.Error] code and a data array.
</description>
</method>
<method name="get_double">
@@ -63,7 +63,7 @@
<return type="Array" />
<param index="0" name="bytes" type="int" />
<description>
- Returns a chunk data with the received bytes. The amount of bytes to be received can be requested in the "bytes" argument. If not enough bytes are available, the function will return how many were actually received. This function returns two values, an [enum @GlobalScope.Error] code, and a data array.
+ Returns a chunk data with the received bytes. The number of bytes to be received can be requested in the "bytes" argument. If not enough bytes are available, the function will return how many were actually received. This function returns two values, an [enum @GlobalScope.Error] code, and a data array.
</description>
</method>
<method name="get_string">
diff --git a/doc/classes/String.xml b/doc/classes/String.xml
index ee508cf70a..f1cd4d72f7 100644
--- a/doc/classes/String.xml
+++ b/doc/classes/String.xml
@@ -440,7 +440,7 @@
<method name="length" qualifiers="const">
<return type="int" />
<description>
- Returns the string's amount of characters.
+ Returns the number of characters in the string.
</description>
</method>
<method name="lpad" qualifiers="const">
@@ -522,7 +522,7 @@
# Last digit will be rounded up here, which reduces total digit count since
# trailing zeros are removed:
String.num(42.129999, 5) # "42.13"
- # If `decimals` is not specified, the total amount of significant digits is 14:
+ # If `decimals` is not specified, the total number of significant digits is 14:
String.num(-0.0000012345432123454321) # "-0.00000123454321"
String.num(-10000.0000012345432123454321) # "-10000.0000012345"
[/codeblock]
diff --git a/doc/classes/SubViewport.xml b/doc/classes/SubViewport.xml
index b62c294f2c..7020cae1de 100644
--- a/doc/classes/SubViewport.xml
+++ b/doc/classes/SubViewport.xml
@@ -25,7 +25,7 @@
The update mode when the sub-viewport is used as a render target.
</member>
<member name="size" type="Vector2i" setter="set_size" getter="get_size" default="Vector2i(512, 512)">
- The width and height of the sub-viewport.
+ The width and height of the sub-viewport. Must be set to a value greater than or equal to 2 pixels on both dimensions. Otherwise, nothing will be displayed.
</member>
<member name="size_2d_override" type="Vector2i" setter="set_size_2d_override" getter="get_size_2d_override" default="Vector2i(0, 0)">
The 2D size override of the sub-viewport. If either the width or height is [code]0[/code], the override is disabled.
diff --git a/doc/classes/SystemFont.xml b/doc/classes/SystemFont.xml
index b1b78f1705..b7454cc7d2 100644
--- a/doc/classes/SystemFont.xml
+++ b/doc/classes/SystemFont.xml
@@ -34,6 +34,9 @@
<member name="hinting" type="int" setter="set_hinting" getter="get_hinting" enum="TextServer.Hinting" default="1">
Font hinting mode.
</member>
+ <member name="multichannel_signed_distance_field" type="bool" setter="set_multichannel_signed_distance_field" getter="is_multichannel_signed_distance_field" default="false">
+ If set to [code]true[/code], glyphs of all sizes are rendered using single multichannel signed distance field generated from the dynamic font vector data.
+ </member>
<member name="oversampling" type="float" setter="set_oversampling" getter="get_oversampling" default="0.0">
Font oversampling factor, if set to [code]0.0[/code] global oversampling factor is used instead.
</member>
diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml
index 40d6d67f4c..aa7ce85f3a 100644
--- a/doc/classes/TextEdit.xml
+++ b/doc/classes/TextEdit.xml
@@ -161,7 +161,7 @@
<method name="get_gutter_count" qualifiers="const">
<return type="int" />
<description>
- Returns the total amount of gutters registered.
+ Returns the number of gutters registered.
</description>
</method>
<method name="get_gutter_name" qualifiers="const">
@@ -189,7 +189,7 @@
<return type="int" />
<param index="0" name="line" type="int" />
<description>
- Returns the amount of spaces and [code]tab * tab_size[/code] before the first char.
+ Returns the number of spaces and [code]tab * tab_size[/code] before the first char.
</description>
</method>
<method name="get_last_full_visible_line" qualifiers="const">
@@ -235,7 +235,7 @@
<method name="get_line_count" qualifiers="const">
<return type="int" />
<description>
- Returns the amount of total lines in the text.
+ Returns the number of lines in the text.
</description>
</method>
<method name="get_line_gutter_icon" qualifiers="const">
@@ -329,7 +329,7 @@
<method name="get_minimap_visible_lines" qualifiers="const">
<return type="int" />
<description>
- Returns the total amount of lines that can be draw on the minimap.
+ Returns the number of lines that may be drawn on the minimap.
</description>
</method>
<method name="get_next_visible_line_index_offset_from" qualifiers="const">
@@ -444,7 +444,7 @@
<method name="get_total_visible_line_count" qualifiers="const">
<return type="int" />
<description>
- Returns the total amount of lines that could be draw.
+ Returns the number of lines that may be drawn.
</description>
</method>
<method name="get_version" qualifiers="const">
diff --git a/doc/classes/TextServer.xml b/doc/classes/TextServer.xml
index ee3c87b8e6..9c4f7857c7 100644
--- a/doc/classes/TextServer.xml
+++ b/doc/classes/TextServer.xml
@@ -188,7 +188,7 @@
</description>
</method>
<method name="font_get_glyph_list" qualifiers="const">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<param index="0" name="font_rid" type="RID" />
<param index="1" name="size" type="Vector2i" />
<description>
@@ -268,7 +268,7 @@
</description>
</method>
<method name="font_get_kerning_list" qualifiers="const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="font_rid" type="RID" />
<param index="1" name="size" type="int" />
<description>
@@ -349,7 +349,7 @@
</description>
</method>
<method name="font_get_size_cache_list" qualifiers="const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="font_rid" type="RID" />
<description>
Returns list of the font sizes in the cache. Each size is [code]Vector2i[/code] with font size and outline size.
@@ -993,7 +993,7 @@
</description>
</method>
<method name="parse_structured_text" qualifiers="const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="parser_type" type="int" enum="TextServer.StructuredTextParser" />
<param index="1" name="args" type="Array" />
<param index="2" name="text" type="String" />
@@ -1162,7 +1162,7 @@
</description>
</method>
<method name="shaped_text_get_ellipsis_glyphs" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="shaped" type="RID" />
<description>
Returns array of the glyphs in the ellipsis.
@@ -1183,7 +1183,7 @@
</description>
</method>
<method name="shaped_text_get_glyphs" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="shaped" type="RID" />
<description>
Returns an array of glyphs in the visual order.
@@ -1463,7 +1463,7 @@
</description>
</method>
<method name="shaped_text_sort_logical">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="shaped" type="RID" />
<description>
Returns text glyphs in the logical order.
diff --git a/doc/classes/TextServerExtension.xml b/doc/classes/TextServerExtension.xml
index 219052d3d5..9eb7188846 100644
--- a/doc/classes/TextServerExtension.xml
+++ b/doc/classes/TextServerExtension.xml
@@ -180,7 +180,7 @@
</description>
</method>
<method name="font_get_glyph_list" qualifiers="virtual const">
- <return type="Array" />
+ <return type="PackedInt32Array" />
<param index="0" name="font_rid" type="RID" />
<param index="1" name="size" type="Vector2i" />
<description>
@@ -258,7 +258,7 @@
</description>
</method>
<method name="font_get_kerning_list" qualifiers="virtual const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="font_rid" type="RID" />
<param index="1" name="size" type="int" />
<description>
@@ -339,7 +339,7 @@
</description>
</method>
<method name="font_get_size_cache_list" qualifiers="virtual const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="font_rid" type="RID" />
<description>
Returns list of the font sizes in the cache. Each size is [code]Vector2i[/code] with font size and outline size.
@@ -979,7 +979,7 @@
</description>
</method>
<method name="parse_structured_text" qualifiers="virtual const">
- <return type="Array" />
+ <return type="Vector2i[]" />
<param index="0" name="parser_type" type="int" enum="TextServer.StructuredTextParser" />
<param index="1" name="args" type="Array" />
<param index="2" name="text" type="String" />
diff --git a/doc/classes/TextServerManager.xml b/doc/classes/TextServerManager.xml
index 19b0e9e6f2..9477e5ec54 100644
--- a/doc/classes/TextServerManager.xml
+++ b/doc/classes/TextServerManager.xml
@@ -38,7 +38,7 @@
</description>
</method>
<method name="get_interfaces" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns a list of available interfaces the index and name of each interface.
</description>
diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml
index 4266a414ce..5530759628 100644
--- a/doc/classes/TileMap.xml
+++ b/doc/classes/TileMap.xml
@@ -77,14 +77,14 @@
<description>
Triggers an update of the TileMap. If [param layer] is provided, only updates the given layer.
[b]Note:[/b] The TileMap node updates automatically when one of its properties is modified. A manual update is only needed if runtime modifications (implemented in [method _tile_data_runtime_update]) need to be applied.
- [b]Warning:[/b] Updating the TileMap is a performance demanding task. Limit occurrences of those updates to the minimum and limit the amount tiles they impact (by segregating tiles updated often to a dedicated layer for example).
+ [b]Warning:[/b] Updating the TileMap is computationally expensive and may impact performance. Try to limit the number of updates and the tiles they impact (by placing frequently updated tiles in a dedicated layer for example).
</description>
</method>
<method name="get_cell_alternative_tile" qualifiers="const">
<return type="int" />
<param index="0" name="layer" type="int" />
<param index="1" name="coords" type="Vector2i" />
- <param index="2" name="use_proxies" type="bool" />
+ <param index="2" name="use_proxies" type="bool" default="false" />
<description>
Returns the tile alternative ID of the cell on layer [param layer] at [param coords]. If [param use_proxies] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy].
</description>
@@ -93,7 +93,7 @@
<return type="Vector2i" />
<param index="0" name="layer" type="int" />
<param index="1" name="coords" type="Vector2i" />
- <param index="2" name="use_proxies" type="bool" />
+ <param index="2" name="use_proxies" type="bool" default="false" />
<description>
Returns the tile atlas coordinates ID of the cell on layer [param layer] at coordinates [param coords]. If [param use_proxies] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy].
</description>
@@ -102,11 +102,21 @@
<return type="int" />
<param index="0" name="layer" type="int" />
<param index="1" name="coords" type="Vector2i" />
- <param index="2" name="use_proxies" type="bool" />
+ <param index="2" name="use_proxies" type="bool" default="false" />
<description>
Returns the tile source ID of the cell on layer [param layer] at coordinates [param coords]. If [param use_proxies] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy].
</description>
</method>
+ <method name="get_cell_tile_data" qualifiers="const">
+ <return type="TileData" />
+ <param index="0" name="layer" type="int" />
+ <param index="1" name="coords" type="Vector2i" />
+ <param index="2" name="use_proxies" type="bool" default="false" />
+ <description>
+ Returns the [TileData] object associated with the given cell, or [code]null[/code] if the cell is not a [TileSetAtlasSource].
+ If [param use_proxies] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy].
+ </description>
+ </method>
<method name="get_coords_for_body_rid">
<return type="Vector2i" />
<param index="0" name="body" type="RID" />
@@ -253,7 +263,6 @@
<description>
Update all the cells in the [param cells] coordinates array so that they use the given [param terrain] for the given [param terrain_set]. If an updated cell has the same terrain as one of its neighboring cells, this function tries to join the two. This function might update neighboring tiles if needed to create correct terrain transitions.
If [param ignore_empty_terrains] is true, empty terrains will be ignored when trying to find the best fitting tile for the given terrain constraints.
- If [param ignore_empty_terrains] is true, empty terrains will be ignored when trying to find the best fitting tile for the given terrain constraints.
[b]Note:[/b] To work correctly, [code]set_cells_terrain_connect[/code] requires the TileMap's TileSet to have terrains set up with all required terrain combinations. Otherwise, it may produce unexpected results.
</description>
</method>
diff --git a/doc/classes/TranslationServer.xml b/doc/classes/TranslationServer.xml
index 3da9096555..7b18d8ddb6 100644
--- a/doc/classes/TranslationServer.xml
+++ b/doc/classes/TranslationServer.xml
@@ -65,7 +65,7 @@
</description>
</method>
<method name="get_loaded_locales" qualifiers="const">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Returns an array of all loaded locales of the project.
</description>
diff --git a/doc/classes/Tree.xml b/doc/classes/Tree.xml
index efa0e4e393..bf66d9f12a 100644
--- a/doc/classes/Tree.xml
+++ b/doc/classes/Tree.xml
@@ -351,10 +351,11 @@
Emitted when [method TreeItem.propagate_check] is called. Connect to this signal to process the items that are affected when [method TreeItem.propagate_check] is invoked. The order that the items affected will be processed is as follows: the item that invoked the method, children of that item, and finally parents of that item.
</description>
</signal>
- <signal name="column_title_pressed">
+ <signal name="column_title_clicked">
<param index="0" name="column" type="int" />
+ <param index="1" name="mouse_button_index" type="int" />
<description>
- Emitted when a column's title is pressed.
+ Emitted when a column's title is clicked with either [constant MOUSE_BUTTON_LEFT] or [constant MOUSE_BUTTON_RIGHT].
</description>
</signal>
<signal name="custom_item_clicked">
diff --git a/doc/classes/TreeItem.xml b/doc/classes/TreeItem.xml
index 6207477441..6d4408cf61 100644
--- a/doc/classes/TreeItem.xml
+++ b/doc/classes/TreeItem.xml
@@ -126,7 +126,7 @@
</description>
</method>
<method name="get_children">
- <return type="Array" />
+ <return type="TreeItem[]" />
<description>
Returns an array of references to the item's children.
</description>
diff --git a/doc/classes/Variant.xml b/doc/classes/Variant.xml
index 0d6fcd0ef5..6b384d6a77 100644
--- a/doc/classes/Variant.xml
+++ b/doc/classes/Variant.xml
@@ -23,7 +23,6 @@
[/codeblocks]
Godot tracks all scripting API variables within Variants. Without even realizing it, you use Variants all the time. When a particular language enforces its own rules for keeping data typed, then that language is applying its own custom logic over the base Variant scripting API.
- GDScript automatically wrap values in them. It keeps all data in plain Variants by default and then optionally enforces custom static typing rules on variable types.
- - VisualScript tracks properties inside Variants as well, but it also uses static typing. The GUI interface enforces that properties have a particular type that doesn't change over time.
- C# is statically typed, but uses the Mono [code]object[/code] type in place of Godot's Variant class when it needs to represent a dynamic value. [code]object[/code] is the Mono runtime's equivalent of the same concept.
The global [method @GlobalScope.typeof] function returns the enumerated value of the Variant type stored in the current variable (see [enum Variant.Type]).
[codeblocks]
diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml
index 904fc6d9e9..19fe2e2bfc 100644
--- a/doc/classes/Vector2.xml
+++ b/doc/classes/Vector2.xml
@@ -135,6 +135,20 @@
Cubically interpolates between this vector and [param b] using [param pre_a] and [param post_b] as handles, and returns the result at position [param weight]. [param weight] is on the range of 0.0 to 1.0, representing the amount of interpolation.
</description>
</method>
+ <method name="cubic_interpolate_in_time" qualifiers="const">
+ <return type="Vector2" />
+ <param index="0" name="b" type="Vector2" />
+ <param index="1" name="pre_a" type="Vector2" />
+ <param index="2" name="post_b" type="Vector2" />
+ <param index="3" name="weight" type="float" />
+ <param index="4" name="b_t" type="float" />
+ <param index="5" name="pre_a_t" type="float" />
+ <param index="6" name="post_b_t" type="float" />
+ <description>
+ Cubically interpolates between this vector and [param b] using [param pre_a] and [param post_b] as handles, and returns the result at position [param weight]. [param weight] is on the range of 0.0 to 1.0, representing the amount of interpolation.
+ It can perform smoother interpolation than [code]cubic_interpolate()[/code] by the time values.
+ </description>
+ </method>
<method name="direction_to" qualifiers="const">
<return type="Vector2" />
<param index="0" name="to" type="Vector2" />
diff --git a/doc/classes/Vector3.xml b/doc/classes/Vector3.xml
index 208e9935e3..150d53845c 100644
--- a/doc/classes/Vector3.xml
+++ b/doc/classes/Vector3.xml
@@ -109,6 +109,20 @@
Performs a cubic interpolation between this vector and [param b] using [param pre_a] and [param post_b] as handles, and returns the result at position [param weight]. [param weight] is on the range of 0.0 to 1.0, representing the amount of interpolation.
</description>
</method>
+ <method name="cubic_interpolate_in_time" qualifiers="const">
+ <return type="Vector3" />
+ <param index="0" name="b" type="Vector3" />
+ <param index="1" name="pre_a" type="Vector3" />
+ <param index="2" name="post_b" type="Vector3" />
+ <param index="3" name="weight" type="float" />
+ <param index="4" name="b_t" type="float" />
+ <param index="5" name="pre_a_t" type="float" />
+ <param index="6" name="post_b_t" type="float" />
+ <description>
+ Performs a cubic interpolation between this vector and [param b] using [param pre_a] and [param post_b] as handles, and returns the result at position [param weight]. [param weight] is on the range of 0.0 to 1.0, representing the amount of interpolation.
+ It can perform smoother interpolation than [code]cubic_interpolate()[/code] by the time values.
+ </description>
+ </method>
<method name="direction_to" qualifiers="const">
<return type="Vector3" />
<param index="0" name="to" type="Vector3" />
diff --git a/doc/classes/Vector4.xml b/doc/classes/Vector4.xml
index 538cdd4138..b9f509cfe7 100644
--- a/doc/classes/Vector4.xml
+++ b/doc/classes/Vector4.xml
@@ -73,6 +73,20 @@
Performs a cubic interpolation between this vector and [param b] using [param pre_a] and [param post_b] as handles, and returns the result at position [param weight]. [param weight] is on the range of 0.0 to 1.0, representing the amount of interpolation.
</description>
</method>
+ <method name="cubic_interpolate_in_time" qualifiers="const">
+ <return type="Vector4" />
+ <param index="0" name="b" type="Vector4" />
+ <param index="1" name="pre_a" type="Vector4" />
+ <param index="2" name="post_b" type="Vector4" />
+ <param index="3" name="weight" type="float" />
+ <param index="4" name="b_t" type="float" />
+ <param index="5" name="pre_a_t" type="float" />
+ <param index="6" name="post_b_t" type="float" />
+ <description>
+ Performs a cubic interpolation between this vector and [param b] using [param pre_a] and [param post_b] as handles, and returns the result at position [param weight]. [param weight] is on the range of 0.0 to 1.0, representing the amount of interpolation.
+ It can perform smoother interpolation than [code]cubic_interpolate()[/code] by the time values.
+ </description>
+ </method>
<method name="direction_to" qualifiers="const">
<return type="Vector4" />
<param index="0" name="to" type="Vector4" />
diff --git a/doc/classes/VelocityTracker3D.xml b/doc/classes/VelocityTracker3D.xml
deleted file mode 100644
index 56b60ba13c..0000000000
--- a/doc/classes/VelocityTracker3D.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="VelocityTracker3D" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
- <brief_description>
- </brief_description>
- <description>
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="get_tracked_linear_velocity" qualifiers="const">
- <return type="Vector3" />
- <description>
- </description>
- </method>
- <method name="reset">
- <return type="void" />
- <param index="0" name="position" type="Vector3" />
- <description>
- </description>
- </method>
- <method name="update_position">
- <return type="void" />
- <param index="0" name="position" type="Vector3" />
- <description>
- </description>
- </method>
- </methods>
- <members>
- <member name="track_physics_step" type="bool" setter="set_track_physics_step" getter="is_tracking_physics_step" default="false">
- </member>
- </members>
-</class>
diff --git a/doc/classes/VisualShader.xml b/doc/classes/VisualShader.xml
index 558b1086b7..a2089ae2b8 100644
--- a/doc/classes/VisualShader.xml
+++ b/doc/classes/VisualShader.xml
@@ -81,7 +81,7 @@
</description>
</method>
<method name="get_node_connections" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<param index="0" name="type" type="int" enum="VisualShader.Type" />
<description>
Returns the list of connected nodes with the specified type.
@@ -206,17 +206,19 @@
</constant>
<constant name="VARYING_TYPE_FLOAT" value="0" enum="VaryingType">
</constant>
- <constant name="VARYING_TYPE_VECTOR_2D" value="1" enum="VaryingType">
+ <constant name="VARYING_TYPE_INT" value="1" enum="VaryingType">
</constant>
- <constant name="VARYING_TYPE_VECTOR_3D" value="2" enum="VaryingType">
+ <constant name="VARYING_TYPE_VECTOR_2D" value="2" enum="VaryingType">
</constant>
- <constant name="VARYING_TYPE_VECTOR_4D" value="3" enum="VaryingType">
+ <constant name="VARYING_TYPE_VECTOR_3D" value="3" enum="VaryingType">
</constant>
- <constant name="VARYING_TYPE_COLOR" value="4" enum="VaryingType">
+ <constant name="VARYING_TYPE_VECTOR_4D" value="4" enum="VaryingType">
</constant>
- <constant name="VARYING_TYPE_TRANSFORM" value="5" enum="VaryingType">
+ <constant name="VARYING_TYPE_BOOLEAN" value="5" enum="VaryingType">
</constant>
- <constant name="VARYING_TYPE_MAX" value="6" enum="VaryingType">
+ <constant name="VARYING_TYPE_TRANSFORM" value="6" enum="VaryingType">
+ </constant>
+ <constant name="VARYING_TYPE_MAX" value="7" enum="VaryingType">
</constant>
<constant name="NODE_ID_INVALID" value="-1">
</constant>
diff --git a/doc/classes/VisualShaderNodeCustom.xml b/doc/classes/VisualShaderNodeCustom.xml
index 9813b4778d..d96969b383 100644
--- a/doc/classes/VisualShaderNodeCustom.xml
+++ b/doc/classes/VisualShaderNodeCustom.xml
@@ -68,7 +68,7 @@
<method name="_get_input_port_count" qualifiers="virtual const">
<return type="int" />
<description>
- Override this method to define the amount of input ports of the associated custom node.
+ Override this method to define the number of input ports of the associated custom node.
Defining this method is [b]required[/b]. If not overridden, the node has no input ports.
</description>
</method>
@@ -98,7 +98,7 @@
<method name="_get_output_port_count" qualifiers="virtual const">
<return type="int" />
<description>
- Override this method to define the amount of output ports of the associated custom node.
+ Override this method to define the number of output ports of the associated custom node.
Defining this method is [b]required[/b]. If not overridden, the node has no output ports.
</description>
</method>
diff --git a/doc/classes/VisualShaderNodeExpression.xml b/doc/classes/VisualShaderNodeExpression.xml
index c4f010f3c0..6b2dc2f2cb 100644
--- a/doc/classes/VisualShaderNodeExpression.xml
+++ b/doc/classes/VisualShaderNodeExpression.xml
@@ -4,7 +4,7 @@
A custom visual shader graph expression written in Godot Shading Language.
</brief_description>
<description>
- Custom Godot Shading Language expression, with a custom amount of input and output ports.
+ Custom Godot Shading Language expression, with a custom number of input and output ports.
The provided code is directly injected into the graph's matching shader function ([code]vertex[/code], [code]fragment[/code], or [code]light[/code]), so it cannot be used to declare functions, varyings, uniforms, or global constants. See [VisualShaderNodeGlobalExpression] for such global definitions.
</description>
<tutorials>
diff --git a/doc/classes/VisualShaderNodeGroupBase.xml b/doc/classes/VisualShaderNodeGroupBase.xml
index 450629a73f..dcc94f0b24 100644
--- a/doc/classes/VisualShaderNodeGroupBase.xml
+++ b/doc/classes/VisualShaderNodeGroupBase.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualShaderNodeGroupBase" inherits="VisualShaderNodeResizableBase" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
- Base class for a family of nodes with variable amount of input and output ports within the visual shader graph.
+ Base class for a family of nodes with variable number of input and output ports within the visual shader graph.
</brief_description>
<description>
Currently, has no direct usage, use the derived classes instead.
diff --git a/doc/classes/XMLParser.xml b/doc/classes/XMLParser.xml
index 69544f4895..26480f0c18 100644
--- a/doc/classes/XMLParser.xml
+++ b/doc/classes/XMLParser.xml
@@ -12,7 +12,7 @@
<method name="get_attribute_count" qualifiers="const">
<return type="int" />
<description>
- Gets the amount of attributes in the current element.
+ Gets the number of attributes in the current element.
</description>
</method>
<method name="get_attribute_name" qualifiers="const">
diff --git a/doc/classes/XRServer.xml b/doc/classes/XRServer.xml
index 7e96b33edd..48b00323d3 100644
--- a/doc/classes/XRServer.xml
+++ b/doc/classes/XRServer.xml
@@ -64,7 +64,7 @@
</description>
</method>
<method name="get_interfaces" qualifiers="const">
- <return type="Array" />
+ <return type="Dictionary[]" />
<description>
Returns a list of available interfaces the ID and name of each interface.
</description>
diff --git a/drivers/alsa/audio_driver_alsa.cpp b/drivers/alsa/audio_driver_alsa.cpp
index f86c4d82ef..f4c87da9e9 100644
--- a/drivers/alsa/audio_driver_alsa.cpp
+++ b/drivers/alsa/audio_driver_alsa.cpp
@@ -50,7 +50,7 @@ Error AudioDriverALSA::init_device() {
// If there is a specified device check that it is really present
if (device_name != "Default") {
- Array list = get_device_list();
+ PackedStringArray list = get_device_list();
if (list.find(device_name) == -1) {
device_name = "Default";
new_device = "Default";
@@ -168,9 +168,8 @@ Error AudioDriverALSA::init() {
return ERR_CANT_OPEN;
}
- active = false;
- thread_exited = false;
- exit_thread = false;
+ active.clear();
+ exit_thread.clear();
Error err = init_device();
if (err == OK) {
@@ -183,11 +182,11 @@ Error AudioDriverALSA::init() {
void AudioDriverALSA::thread_func(void *p_udata) {
AudioDriverALSA *ad = static_cast<AudioDriverALSA *>(p_udata);
- while (!ad->exit_thread) {
+ while (!ad->exit_thread.is_set()) {
ad->lock();
ad->start_counting_ticks();
- if (!ad->active) {
+ if (!ad->active.is_set()) {
for (uint64_t i = 0; i < ad->period_size * ad->channels; i++) {
ad->samples_out.write[i] = 0;
}
@@ -203,7 +202,7 @@ void AudioDriverALSA::thread_func(void *p_udata) {
int todo = ad->period_size;
int total = 0;
- while (todo && !ad->exit_thread) {
+ while (todo && !ad->exit_thread.is_set()) {
int16_t *src = (int16_t *)ad->samples_out.ptr();
int wrote = snd_pcm_writei(ad->pcm_handle, (void *)(src + (total * ad->channels)), todo);
@@ -222,8 +221,8 @@ void AudioDriverALSA::thread_func(void *p_udata) {
wrote = snd_pcm_recover(ad->pcm_handle, wrote, 0);
if (wrote < 0) {
ERR_PRINT("ALSA: Failed and can't recover: " + String(snd_strerror(wrote)));
- ad->active = false;
- ad->exit_thread = true;
+ ad->active.clear();
+ ad->exit_thread.set();
}
}
}
@@ -241,8 +240,8 @@ void AudioDriverALSA::thread_func(void *p_udata) {
err = ad->init_device();
if (err != OK) {
- ad->active = false;
- ad->exit_thread = true;
+ ad->active.clear();
+ ad->exit_thread.set();
}
}
}
@@ -250,12 +249,10 @@ void AudioDriverALSA::thread_func(void *p_udata) {
ad->stop_counting_ticks();
ad->unlock();
}
-
- ad->thread_exited = true;
}
void AudioDriverALSA::start() {
- active = true;
+ active.set();
}
int AudioDriverALSA::get_mix_rate() const {
@@ -266,8 +263,8 @@ AudioDriver::SpeakerMode AudioDriverALSA::get_speaker_mode() const {
return speaker_mode;
}
-Array AudioDriverALSA::get_device_list() {
- Array list;
+PackedStringArray AudioDriverALSA::get_device_list() {
+ PackedStringArray list;
list.push_back("Default");
@@ -327,7 +324,7 @@ void AudioDriverALSA::finish_device() {
}
void AudioDriverALSA::finish() {
- exit_thread = true;
+ exit_thread.set();
thread.wait_to_finish();
finish_device();
diff --git a/drivers/alsa/audio_driver_alsa.h b/drivers/alsa/audio_driver_alsa.h
index dbb40fa088..fa1dba38ed 100644
--- a/drivers/alsa/audio_driver_alsa.h
+++ b/drivers/alsa/audio_driver_alsa.h
@@ -35,6 +35,7 @@
#include "core/os/mutex.h"
#include "core/os/thread.h"
+#include "core/templates/safe_refcount.h"
#include "servers/audio_server.h"
#include "asound-so_wrap.h"
@@ -64,9 +65,8 @@ class AudioDriverALSA : public AudioDriver {
snd_pcm_uframes_t period_size;
int channels = 0;
- bool active = false;
- bool thread_exited = false;
- mutable bool exit_thread = false;
+ SafeFlag active;
+ SafeFlag exit_thread;
public:
const char *get_name() const {
@@ -77,7 +77,7 @@ public:
virtual void start();
virtual int get_mix_rate() const;
virtual SpeakerMode get_speaker_mode() const;
- virtual Array get_device_list();
+ virtual PackedStringArray get_device_list();
virtual String get_device();
virtual void set_device(String device);
virtual void lock();
diff --git a/drivers/alsamidi/midi_driver_alsamidi.cpp b/drivers/alsamidi/midi_driver_alsamidi.cpp
index c334146dd2..d2a0076023 100644
--- a/drivers/alsamidi/midi_driver_alsamidi.cpp
+++ b/drivers/alsamidi/midi_driver_alsamidi.cpp
@@ -79,7 +79,7 @@ void MIDIDriverALSAMidi::thread_func(void *p_udata) {
int expected_size = 255;
int bytes = 0;
- while (!md->exit_thread) {
+ while (!md->exit_thread.is_set()) {
int ret;
md->lock();
@@ -149,14 +149,14 @@ Error MIDIDriverALSAMidi::open() {
}
snd_device_name_free_hint(hints);
- exit_thread = false;
+ exit_thread.clear();
thread.start(MIDIDriverALSAMidi::thread_func, this);
return OK;
}
void MIDIDriverALSAMidi::close() {
- exit_thread = true;
+ exit_thread.set();
thread.wait_to_finish();
for (int i = 0; i < connected_inputs.size(); i++) {
@@ -193,7 +193,7 @@ PackedStringArray MIDIDriverALSAMidi::get_connected_inputs() {
}
MIDIDriverALSAMidi::MIDIDriverALSAMidi() {
- exit_thread = false;
+ exit_thread.clear();
}
MIDIDriverALSAMidi::~MIDIDriverALSAMidi() {
diff --git a/drivers/alsamidi/midi_driver_alsamidi.h b/drivers/alsamidi/midi_driver_alsamidi.h
index b0fa8c297a..ac3530b1b2 100644
--- a/drivers/alsamidi/midi_driver_alsamidi.h
+++ b/drivers/alsamidi/midi_driver_alsamidi.h
@@ -36,6 +36,7 @@
#include "core/os/midi_driver.h"
#include "core/os/mutex.h"
#include "core/os/thread.h"
+#include "core/templates/safe_refcount.h"
#include "core/templates/vector.h"
#include "../alsa/asound-so_wrap.h"
@@ -47,7 +48,7 @@ class MIDIDriverALSAMidi : public MIDIDriver {
Vector<snd_rawmidi_t *> connected_inputs;
- bool exit_thread;
+ SafeFlag exit_thread;
static void thread_func(void *p_udata);
diff --git a/drivers/coreaudio/audio_driver_coreaudio.cpp b/drivers/coreaudio/audio_driver_coreaudio.cpp
index cc38c2352f..1db85e2a60 100644
--- a/drivers/coreaudio/audio_driver_coreaudio.cpp
+++ b/drivers/coreaudio/audio_driver_coreaudio.cpp
@@ -215,6 +215,7 @@ OSStatus AudioDriverCoreAudio::input_callback(void *inRefCon,
}
ad->lock();
+ ad->start_counting_ticks();
AudioBufferList bufferList;
bufferList.mNumberBuffers = 1;
@@ -237,6 +238,7 @@ OSStatus AudioDriverCoreAudio::input_callback(void *inRefCon,
ERR_PRINT("AudioUnitRender failed, code: " + itos(result));
}
+ ad->stop_counting_ticks();
ad->unlock();
return result;
@@ -493,8 +495,8 @@ Error AudioDriverCoreAudio::capture_stop() {
#ifdef MACOS_ENABLED
-Array AudioDriverCoreAudio::_get_device_list(bool capture) {
- Array list;
+PackedStringArray AudioDriverCoreAudio::_get_device_list(bool capture) {
+ PackedStringArray list;
list.push_back("Default");
@@ -637,7 +639,7 @@ void AudioDriverCoreAudio::_set_device(const String &device, bool capture) {
}
}
-Array AudioDriverCoreAudio::get_device_list() {
+PackedStringArray AudioDriverCoreAudio::get_device_list() {
return _get_device_list();
}
@@ -659,7 +661,7 @@ void AudioDriverCoreAudio::capture_set_device(const String &p_name) {
}
}
-Array AudioDriverCoreAudio::capture_get_device_list() {
+PackedStringArray AudioDriverCoreAudio::capture_get_device_list() {
return _get_device_list(true);
}
diff --git a/drivers/coreaudio/audio_driver_coreaudio.h b/drivers/coreaudio/audio_driver_coreaudio.h
index 7fac8a99ed..aac5077bb1 100644
--- a/drivers/coreaudio/audio_driver_coreaudio.h
+++ b/drivers/coreaudio/audio_driver_coreaudio.h
@@ -59,7 +59,7 @@ class AudioDriverCoreAudio : public AudioDriver {
Vector<int16_t> input_buf;
#ifdef MACOS_ENABLED
- Array _get_device_list(bool capture = false);
+ PackedStringArray _get_device_list(bool capture = false);
void _set_device(const String &device, bool capture = false);
static OSStatus input_device_address_cb(AudioObjectID inObjectID,
@@ -107,11 +107,11 @@ public:
void stop();
#ifdef MACOS_ENABLED
- virtual Array get_device_list();
+ virtual PackedStringArray get_device_list();
virtual String get_device();
virtual void set_device(String device);
- virtual Array capture_get_device_list();
+ virtual PackedStringArray capture_get_device_list();
virtual void capture_set_device(const String &p_name);
virtual String capture_get_device();
#endif
diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp
index 83154acd51..28802f571c 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.cpp
+++ b/drivers/gles3/rasterizer_canvas_gles3.cpp
@@ -201,6 +201,7 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
bool material_screen_texture_found = false;
Rect2 back_buffer_rect;
bool backbuffer_copy = false;
+ bool backbuffer_gen_mipmaps = false;
Item *ci = p_item_list;
Item *canvas_group_owner = nullptr;
@@ -225,6 +226,7 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
if (!material_screen_texture_found) {
backbuffer_copy = true;
back_buffer_rect = Rect2();
+ backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
}
}
@@ -282,7 +284,7 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
_render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list);
item_count = 0;
- texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, true);
+ texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, backbuffer_gen_mipmaps);
backbuffer_copy = false;
material_screen_texture_found = true; //after a backbuffer copy, screen texture makes no further copies
diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp
index 3e416bc615..9bbe960d86 100644
--- a/drivers/gles3/rasterizer_scene_gles3.cpp
+++ b/drivers/gles3/rasterizer_scene_gles3.cpp
@@ -867,7 +867,6 @@ void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_p
GLES3::MaterialStorage::get_singleton()->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::TIME, time, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
GLES3::MaterialStorage::get_singleton()->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::PROJECTION, cm.matrix[2][0], cm.matrix[0][0], cm.matrix[2][1], cm.matrix[1][1], shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
- // Bind a vertex array or else OpenGL complains. We won't actually use it
glBindVertexArray(sky_globals.screen_triangle_array);
glViewport(0, 0, sky->radiance_size, sky->radiance_size);
@@ -2150,7 +2149,9 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params,
index_array_gl = mesh_storage->mesh_surface_get_index_buffer(mesh_surface, surf->lod_index);
if (prev_vertex_array_gl != vertex_array_gl) {
- glBindVertexArray(vertex_array_gl);
+ if (vertex_array_gl != 0) {
+ glBindVertexArray(vertex_array_gl);
+ }
prev_vertex_array_gl = vertex_array_gl;
}
diff --git a/drivers/gles3/shaders/scene.glsl b/drivers/gles3/shaders/scene.glsl
index 84daf839e9..c7fdd6ebd8 100644
--- a/drivers/gles3/shaders/scene.glsl
+++ b/drivers/gles3/shaders/scene.glsl
@@ -35,8 +35,8 @@ USE_RADIANCE_MAP = true
/*
from RenderingServer:
ARRAY_VERTEX = 0, // RG32F or RGB32F (depending on 2D bit)
-ARRAY_NORMAL = 1, // A2B10G10R10, A is ignored.
-ARRAY_TANGENT = 2, // A2B10G10R10, A flips sign of binormal.
+ARRAY_NORMAL = 1, // RG16 octahedral compression
+ARRAY_TANGENT = 2, // RG16 octahedral compression, sign stored in sign of G
ARRAY_COLOR = 3, // RGBA8
ARRAY_TEX_UV = 4, // RG32F
ARRAY_TEX_UV2 = 5, // RG32F
@@ -54,11 +54,11 @@ layout(location = 0) in highp vec3 vertex_attrib;
/* clang-format on */
#ifdef NORMAL_USED
-layout(location = 1) in vec3 normal_attrib;
+layout(location = 1) in vec2 normal_attrib;
#endif
#if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
-layout(location = 2) in vec4 tangent_attrib;
+layout(location = 2) in vec2 tangent_attrib;
#endif
#if defined(COLOR_USED)
@@ -97,6 +97,13 @@ layout(location = 10) in uvec4 bone_attrib;
layout(location = 11) in vec4 weight_attrib;
#endif
+vec3 oct_to_vec3(vec2 e) {
+ vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));
+ float t = max(-v.z, 0.0);
+ v.xy += t * -sign(v.xy);
+ return v;
+}
+
#ifdef USE_INSTANCING
layout(location = 12) in highp vec4 instance_xform0;
layout(location = 13) in highp vec4 instance_xform1;
@@ -209,13 +216,14 @@ void main() {
#endif
#ifdef NORMAL_USED
- vec3 normal = normal_attrib * 2.0 - 1.0;
+ vec3 normal = oct_to_vec3(normal_attrib * 2.0 - 1.0);
#endif
highp mat3 model_normal_matrix = mat3(model_matrix);
#if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
- vec3 tangent = tangent_attrib.xyz * 2.0 - 1.0;
- float binormalf = tangent_attrib.a * 2.0 - 1.0;
+ vec2 signed_tangent_attrib = tangent_attrib * 2.0 - 1.0;
+ vec3 tangent = oct_to_vec3(vec2(signed_tangent_attrib.x, abs(signed_tangent_attrib.y) * 2.0 - 1.0));
+ float binormalf = sign(signed_tangent_attrib.y);
vec3 binormal = normalize(cross(normal, tangent) * binormalf);
#endif
diff --git a/drivers/gles3/storage/material_storage.cpp b/drivers/gles3/storage/material_storage.cpp
index 26441fc726..a64c7f7200 100644
--- a/drivers/gles3/storage/material_storage.cpp
+++ b/drivers/gles3/storage/material_storage.cpp
@@ -1083,6 +1083,12 @@ void MaterialData::update_textures(const HashMap<StringName, Variant> &p_paramet
Vector<RID> textures;
+ if (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ continue;
+ }
+
if (p_texture_uniforms[i].global) {
uses_global_textures = true;
@@ -1450,8 +1456,8 @@ MaterialStorage::MaterialStorage() {
actions.renames["UV2"] = "uv2_interp";
actions.renames["COLOR"] = "color_interp";
actions.renames["POINT_SIZE"] = "gl_PointSize";
- actions.renames["INSTANCE_ID"] = "gl_InstanceIndex";
- actions.renames["VERTEX_ID"] = "gl_VertexIndex";
+ actions.renames["INSTANCE_ID"] = "gl_InstanceID";
+ actions.renames["VERTEX_ID"] = "gl_VertexID";
actions.renames["ALPHA_SCISSOR_THRESHOLD"] = "alpha_scissor_threshold";
actions.renames["ALPHA_HASH_SCALE"] = "alpha_hash_scale";
@@ -1492,9 +1498,9 @@ MaterialStorage::MaterialStorage() {
actions.renames["POINT_COORD"] = "gl_PointCoord";
actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
actions.renames["SCREEN_UV"] = "screen_uv";
- actions.renames["SCREEN_TEXTURE"] = "color_buffer";
- actions.renames["DEPTH_TEXTURE"] = "depth_buffer";
- actions.renames["NORMAL_ROUGHNESS_TEXTURE"] = "normal_roughness_buffer";
+ //actions.renames["SCREEN_TEXTURE"] = "color_buffer"; //Not implemented in 3D yet.
+ //actions.renames["DEPTH_TEXTURE"] = "depth_buffer"; // Not implemented in 3D yet.
+ //actions.renames["NORMAL_ROUGHNESS_TEXTURE"] = "normal_roughness_buffer"; // Not implemented in 3D yet
actions.renames["DEPTH"] = "gl_FragDepth";
actions.renames["OUTPUT_IS_SRGB"] = "true";
actions.renames["FOG"] = "fog";
@@ -2789,6 +2795,7 @@ void CanvasShaderData::set_code(const String &p_code) {
ubo_size = 0;
uniforms.clear();
uses_screen_texture = false;
+ uses_screen_texture_mipmaps = false;
uses_sdf = false;
uses_time = false;
@@ -2799,7 +2806,6 @@ void CanvasShaderData::set_code(const String &p_code) {
ShaderCompiler::GeneratedCode gen_code;
int blend_modei = BLEND_MODE_MIX;
- uses_screen_texture = false;
ShaderCompiler::IdentifierActions actions;
actions.entry_point_stages["vertex"] = ShaderCompiler::STAGE_VERTEX;
@@ -2826,6 +2832,7 @@ void CanvasShaderData::set_code(const String &p_code) {
}
blend_mode = BlendMode(blend_modei);
+ uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;
#if 0
print_line("**compiling shader:");
@@ -2833,12 +2840,16 @@ void CanvasShaderData::set_code(const String &p_code) {
for (int i = 0; i < gen_code.defines.size(); i++) {
print_line(gen_code.defines[i]);
}
+
+ HashMap<String, String>::Iterator el = gen_code.code.begin();
+ while (el) {
+ print_line("\n**code " + el->key + ":\n" + el->value);
+ ++el;
+ }
+
print_line("\n**uniforms:\n" + gen_code.uniforms);
- print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
- print_line("\n**vertex_code:\n" + gen_code.vertex);
- print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
- print_line("\n**fragment_code:\n" + gen_code.fragment);
- print_line("\n**light_code:\n" + gen_code.light);
+ print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
+ print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
#endif
Vector<StringName> texture_uniform_names;
@@ -2877,7 +2888,10 @@ void CanvasShaderData::get_shader_uniform_list(List<PropertyInfo> *p_param_list)
HashMap<int, StringName> order;
for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
- if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
+ if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
continue;
}
if (E.value.texture_order >= 0) {
@@ -3070,12 +3084,16 @@ void SkyShaderData::set_code(const String &p_code) {
for (int i = 0; i < gen_code.defines.size(); i++) {
print_line(gen_code.defines[i]);
}
+
+ HashMap<String, String>::Iterator el = gen_code.code.begin();
+ while (el) {
+ print_line("\n**code " + el->key + ":\n" + el->value);
+ ++el;
+ }
+
print_line("\n**uniforms:\n" + gen_code.uniforms);
- // print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
- // print_line("\n**vertex_code:\n" + gen_code.vertex);
- print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
- print_line("\n**fragment_code:\n" + gen_code.fragment);
- print_line("\n**light_code:\n" + gen_code.light);
+ print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
+ print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
#endif
Vector<StringName> texture_uniform_names;
@@ -3253,7 +3271,6 @@ void SceneShaderData::set_code(const String &p_code) {
valid = false;
ubo_size = 0;
uniforms.clear();
- uses_screen_texture = false;
if (code.is_empty()) {
return; //just invalid, but no error
@@ -3378,6 +3395,7 @@ void SceneShaderData::set_code(const String &p_code) {
vertex_input_mask |= uses_custom3 << 8;
vertex_input_mask |= uses_bones << 9;
vertex_input_mask |= uses_weights << 10;
+ uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;
#if 0
print_line("**compiling shader:");
@@ -3386,11 +3404,10 @@ void SceneShaderData::set_code(const String &p_code) {
print_line(gen_code.defines[i]);
}
- Map<String, String>::Element *el = gen_code.code.front();
+ HashMap<String, String>::Iterator el = gen_code.code.begin();
while (el) {
- print_line("\n**code " + el->key() + ":\n" + el->value());
-
- el = el->next();
+ print_line("\n**code " + el->key + ":\n" + el->value);
+ ++el;
}
print_line("\n**uniforms:\n" + gen_code.uniforms);
@@ -3439,7 +3456,10 @@ void SceneShaderData::get_shader_uniform_list(List<PropertyInfo> *p_param_list)
RBMap<int, StringName> order;
for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
- if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
+ if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
continue;
}
diff --git a/drivers/gles3/storage/material_storage.h b/drivers/gles3/storage/material_storage.h
index 2ca47351a4..d135357f6a 100644
--- a/drivers/gles3/storage/material_storage.h
+++ b/drivers/gles3/storage/material_storage.h
@@ -159,6 +159,7 @@ struct CanvasShaderData : public ShaderData {
HashMap<StringName, HashMap<int, RID>> default_texture_params;
bool uses_screen_texture = false;
+ bool uses_screen_texture_mipmaps = false;
bool uses_sdf = false;
bool uses_time = false;
@@ -312,6 +313,7 @@ struct SceneShaderData : public ShaderData {
bool uses_sss;
bool uses_transmittance;
bool uses_screen_texture;
+ bool uses_screen_texture_mipmaps;
bool uses_depth_texture;
bool uses_normal_texture;
bool uses_time;
diff --git a/drivers/gles3/storage/mesh_storage.cpp b/drivers/gles3/storage/mesh_storage.cpp
index d2c2aa0259..ddf94af5b8 100644
--- a/drivers/gles3/storage/mesh_storage.cpp
+++ b/drivers/gles3/storage/mesh_storage.cpp
@@ -124,11 +124,11 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
} break;
case RS::ARRAY_NORMAL: {
- stride += sizeof(int32_t);
+ stride += sizeof(uint16_t) * 2;
} break;
case RS::ARRAY_TANGENT: {
- stride += sizeof(int32_t);
+ stride += sizeof(uint16_t) * 2;
} break;
case RS::ARRAY_COLOR: {
@@ -186,11 +186,13 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
s->format = p_surface.format;
s->primitive = p_surface.primitive;
- glGenBuffers(1, &s->vertex_buffer);
- glBindBuffer(GL_ARRAY_BUFFER, s->vertex_buffer);
- glBufferData(GL_ARRAY_BUFFER, p_surface.vertex_data.size(), p_surface.vertex_data.ptr(), (s->format & RS::ARRAY_FLAG_USE_DYNAMIC_UPDATE) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
- s->vertex_buffer_size = p_surface.vertex_data.size();
+ if (p_surface.vertex_data.size()) {
+ glGenBuffers(1, &s->vertex_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, s->vertex_buffer);
+ glBufferData(GL_ARRAY_BUFFER, p_surface.vertex_data.size(), p_surface.vertex_data.ptr(), (s->format & RS::ARRAY_FLAG_USE_DYNAMIC_UPDATE) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
+ s->vertex_buffer_size = p_surface.vertex_data.size();
+ }
if (p_surface.attribute_data.size()) {
glGenBuffers(1, &s->attribute_buffer);
@@ -214,7 +216,7 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
}
if (p_surface.index_count) {
- bool is_index_16 = p_surface.vertex_count <= 65536;
+ bool is_index_16 = p_surface.vertex_count <= 65536 && p_surface.vertex_count > 0;
glGenBuffers(1, &s->index_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, p_surface.index_data.size(), p_surface.index_data.ptr(), GL_STATIC_DRAW);
@@ -238,6 +240,8 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
}
}
+ ERR_FAIL_COND_MSG(!p_surface.index_count && !p_surface.vertex_count, "Meshes must contain a vertex array, an index array, or both");
+
s->aabb = p_surface.aabb;
s->bone_aabbs = p_surface.bone_aabbs; //only really useful for returning them.
@@ -255,9 +259,9 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
mesh->bone_aabbs.resize(p_surface.bone_aabbs.size());
}
for (int i = 0; i < p_surface.bone_aabbs.size(); i++) {
- AABB bone = p_surface.bone_aabbs[i];
+ const AABB &bone = p_surface.bone_aabbs[i];
if (!bone.has_no_volume()) {
- mesh->bone_aabbs.write[i].merge_with(p_surface.bone_aabbs[i]);
+ mesh->bone_aabbs.write[i].merge_with(bone);
}
}
mesh->aabb.merge_with(p_surface.aabb);
@@ -340,7 +344,9 @@ RS::SurfaceData MeshStorage::mesh_get_surface(RID p_mesh, int p_surface) const {
RS::SurfaceData sd;
sd.format = s.format;
- sd.vertex_data = Utilities::buffer_get_data(GL_ARRAY_BUFFER, s.vertex_buffer, s.vertex_buffer_size);
+ if (s.vertex_buffer != 0) {
+ sd.vertex_data = Utilities::buffer_get_data(GL_ARRAY_BUFFER, s.vertex_buffer, s.vertex_buffer_size);
+ }
if (s.attribute_buffer != 0) {
sd.attribute_data = Utilities::buffer_get_data(GL_ARRAY_BUFFER, s.attribute_buffer, s.attribute_buffer_size);
@@ -598,17 +604,16 @@ void MeshStorage::_mesh_surface_generate_version_for_input_mask(Mesh::Surface::V
} break;
case RS::ARRAY_NORMAL: {
attribs[i].offset = vertex_stride;
- // Will need to change to accommodate octahedral compression
- attribs[i].size = 4;
- attribs[i].type = GL_UNSIGNED_INT_2_10_10_10_REV;
- vertex_stride += sizeof(float);
+ attribs[i].size = 2;
+ attribs[i].type = GL_UNSIGNED_SHORT;
+ vertex_stride += sizeof(uint16_t) * 2;
attribs[i].normalized = GL_TRUE;
} break;
case RS::ARRAY_TANGENT: {
attribs[i].offset = vertex_stride;
- attribs[i].size = 4;
- attribs[i].type = GL_UNSIGNED_INT_2_10_10_10_REV;
- vertex_stride += sizeof(float);
+ attribs[i].size = 2;
+ attribs[i].type = GL_UNSIGNED_SHORT;
+ vertex_stride += sizeof(uint16_t) * 2;
attribs[i].normalized = GL_TRUE;
} break;
case RS::ARRAY_COLOR: {
diff --git a/drivers/gles3/storage/mesh_storage.h b/drivers/gles3/storage/mesh_storage.h
index 339380b3b0..74f5800795 100644
--- a/drivers/gles3/storage/mesh_storage.h
+++ b/drivers/gles3/storage/mesh_storage.h
@@ -75,7 +75,7 @@ struct Mesh {
// Cache vertex arrays so they can be created
struct Version {
uint32_t input_mask = 0;
- GLuint vertex_array;
+ GLuint vertex_array = 0;
Attrib attribs[RS::ARRAY_MAX];
};
@@ -92,7 +92,7 @@ struct Mesh {
float edge_length = 0.0;
uint32_t index_count = 0;
uint32_t index_buffer_size = 0;
- GLuint index_buffer;
+ GLuint index_buffer = 0;
};
LOD *lods = nullptr;
@@ -175,7 +175,7 @@ struct MultiMesh {
bool *data_cache_dirty_regions = nullptr;
uint32_t data_cache_used_dirty_regions = 0;
- GLuint buffer;
+ GLuint buffer = 0;
bool dirty = false;
MultiMesh *dirty_list = nullptr;
@@ -362,7 +362,7 @@ public:
_FORCE_INLINE_ GLenum mesh_surface_get_index_type(void *p_surface) const {
Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface);
- return s->vertex_count <= 65536 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
+ return (s->vertex_count <= 65536 && s->vertex_count > 0) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
}
// Use this to cache Vertex Array Objects so they are only generated once
diff --git a/drivers/png/SCsub b/drivers/png/SCsub
index 39d296e7cf..ad7aaf1ee8 100644
--- a/drivers/png/SCsub
+++ b/drivers/png/SCsub
@@ -37,7 +37,7 @@ if env["builtin_libpng"]:
import os
# Enable ARM NEON instructions on 32-bit Android to compile more optimized code.
- use_neon = "android_arch" in env and env["android_arch"] == "armv7" and os.name != "nt"
+ use_neon = env["platform"] == "android" and env["arch"] == "arm32" and os.name != "nt"
if use_neon:
env_png.Append(CPPDEFINES=[("PNG_ARM_NEON_OPT", 2)])
else:
diff --git a/drivers/png/image_loader_png.cpp b/drivers/png/image_loader_png.cpp
index 917bfec574..8d2f8a7ed6 100644
--- a/drivers/png/image_loader_png.cpp
+++ b/drivers/png/image_loader_png.cpp
@@ -36,7 +36,7 @@
#include <string.h>
-Error ImageLoaderPNG::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) {
+Error ImageLoaderPNG::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) {
const uint64_t buffer_size = f->get_length();
Vector<uint8_t> file_buffer;
Error err = file_buffer.resize(buffer_size);
@@ -48,7 +48,7 @@ Error ImageLoaderPNG::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_f
f->get_buffer(writer, buffer_size);
}
const uint8_t *reader = file_buffer.ptr();
- return PNGDriverCommon::png_to_image(reader, buffer_size, p_force_linear, p_image);
+ return PNGDriverCommon::png_to_image(reader, buffer_size, p_flags & FLAG_FORCE_LINEAR, p_image);
}
void ImageLoaderPNG::get_recognized_extensions(List<String> *p_extensions) const {
diff --git a/drivers/png/image_loader_png.h b/drivers/png/image_loader_png.h
index 9bcfb720d3..91c3c8925f 100644
--- a/drivers/png/image_loader_png.h
+++ b/drivers/png/image_loader_png.h
@@ -40,7 +40,7 @@ private:
static Ref<Image> load_mem_png(const uint8_t *p_png, int p_size);
public:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale);
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderPNG();
};
diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.cpp b/drivers/pulseaudio/audio_driver_pulseaudio.cpp
index a6c35b6837..b25cf1d5b4 100644
--- a/drivers/pulseaudio/audio_driver_pulseaudio.cpp
+++ b/drivers/pulseaudio/audio_driver_pulseaudio.cpp
@@ -178,7 +178,7 @@ Error AudioDriverPulseAudio::detect_channels(bool capture) {
Error AudioDriverPulseAudio::init_device() {
// If there is a specified device check that it is really present
if (device_name != "Default") {
- Array list = get_device_list();
+ PackedStringArray list = get_device_list();
if (list.find(device_name) == -1) {
device_name = "Default";
new_device = "Default";
@@ -285,9 +285,8 @@ Error AudioDriverPulseAudio::init() {
return ERR_CANT_OPEN;
}
- active = false;
- thread_exited = false;
- exit_thread = false;
+ active.clear();
+ exit_thread.clear();
mix_rate = GLOBAL_GET("audio/driver/mix_rate");
@@ -384,7 +383,7 @@ void AudioDriverPulseAudio::thread_func(void *p_udata) {
size_t avail_bytes = 0;
uint64_t default_device_msec = OS::get_singleton()->get_ticks_msec();
- while (!ad->exit_thread) {
+ while (!ad->exit_thread.is_set()) {
size_t read_bytes = 0;
size_t written_bytes = 0;
@@ -392,7 +391,7 @@ void AudioDriverPulseAudio::thread_func(void *p_udata) {
ad->lock();
ad->start_counting_ticks();
- if (!ad->active) {
+ if (!ad->active.is_set()) {
ad->samples_out.fill(0);
} else {
ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
@@ -462,8 +461,8 @@ void AudioDriverPulseAudio::thread_func(void *p_udata) {
err = ad->init_device();
if (err != OK) {
- ad->active = false;
- ad->exit_thread = true;
+ ad->active.clear();
+ ad->exit_thread.set();
break;
}
}
@@ -501,8 +500,8 @@ void AudioDriverPulseAudio::thread_func(void *p_udata) {
Error err = ad->init_device();
if (err != OK) {
ERR_PRINT("PulseAudio: init_device error");
- ad->active = false;
- ad->exit_thread = true;
+ ad->active.clear();
+ ad->exit_thread.set();
break;
}
@@ -555,8 +554,8 @@ void AudioDriverPulseAudio::thread_func(void *p_udata) {
err = ad->capture_init_device();
if (err != OK) {
- ad->active = false;
- ad->exit_thread = true;
+ ad->active.clear();
+ ad->exit_thread.set();
break;
}
}
@@ -571,12 +570,10 @@ void AudioDriverPulseAudio::thread_func(void *p_udata) {
OS::get_singleton()->delay_usec(1000);
}
}
-
- ad->thread_exited = true;
}
void AudioDriverPulseAudio::start() {
- active = true;
+ active.set();
}
int AudioDriverPulseAudio::get_mix_rate() const {
@@ -599,7 +596,7 @@ void AudioDriverPulseAudio::pa_sinklist_cb(pa_context *c, const pa_sink_info *l,
ad->pa_status++;
}
-Array AudioDriverPulseAudio::get_device_list() {
+PackedStringArray AudioDriverPulseAudio::get_device_list() {
pa_devices.clear();
pa_devices.push_back("Default");
@@ -661,7 +658,7 @@ void AudioDriverPulseAudio::finish() {
return;
}
- exit_thread = true;
+ exit_thread.set();
thread.wait_to_finish();
finish_device();
@@ -681,7 +678,7 @@ void AudioDriverPulseAudio::finish() {
Error AudioDriverPulseAudio::capture_init_device() {
// If there is a specified device check that it is really present
if (capture_device_name != "Default") {
- Array list = capture_get_device_list();
+ PackedStringArray list = capture_get_device_list();
if (list.find(capture_device_name) == -1) {
capture_device_name = "Default";
capture_new_device = "Default";
@@ -785,7 +782,7 @@ void AudioDriverPulseAudio::pa_sourcelist_cb(pa_context *c, const pa_source_info
ad->pa_status++;
}
-Array AudioDriverPulseAudio::capture_get_device_list() {
+PackedStringArray AudioDriverPulseAudio::capture_get_device_list() {
pa_rec_devices.clear();
pa_rec_devices.push_back("Default");
diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.h b/drivers/pulseaudio/audio_driver_pulseaudio.h
index af96489972..85e328b49f 100644
--- a/drivers/pulseaudio/audio_driver_pulseaudio.h
+++ b/drivers/pulseaudio/audio_driver_pulseaudio.h
@@ -35,6 +35,7 @@
#include "core/os/mutex.h"
#include "core/os/thread.h"
+#include "core/templates/safe_refcount.h"
#include "servers/audio_server.h"
#include "pulse-so_wrap.h"
@@ -67,12 +68,11 @@ class AudioDriverPulseAudio : public AudioDriver {
int channels = 0;
int pa_ready = 0;
int pa_status = 0;
- Array pa_devices;
- Array pa_rec_devices;
+ PackedStringArray pa_devices;
+ PackedStringArray pa_rec_devices;
- bool active = false;
- bool thread_exited = false;
- mutable bool exit_thread = false;
+ SafeFlag active;
+ SafeFlag exit_thread;
float latency = 0;
@@ -103,11 +103,11 @@ public:
virtual int get_mix_rate() const;
virtual SpeakerMode get_speaker_mode() const;
- virtual Array get_device_list();
+ virtual PackedStringArray get_device_list();
virtual String get_device();
virtual void set_device(String device);
- virtual Array capture_get_device_list();
+ virtual PackedStringArray capture_get_device_list();
virtual void capture_set_device(const String &p_name);
virtual String capture_get_device();
diff --git a/drivers/vulkan/rendering_device_vulkan.cpp b/drivers/vulkan/rendering_device_vulkan.cpp
index bcb6092d87..2debba1b83 100644
--- a/drivers/vulkan/rendering_device_vulkan.cpp
+++ b/drivers/vulkan/rendering_device_vulkan.cpp
@@ -7805,12 +7805,6 @@ void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices
ERR_FAIL_COND_MSG(!dl->validation.index_array_size,
"Draw command requested indices, but no index buffer was set.");
- if (dl->validation.pipeline_vertex_format != INVALID_ID) {
- // Uses vertices, do some vertex validations.
- ERR_FAIL_COND_MSG(dl->validation.vertex_array_size < dl->validation.index_array_max_index,
- "Index array references (max index: " + itos(dl->validation.index_array_max_index) + ") indices beyond the vertex array size (" + itos(dl->validation.vertex_array_size) + ").");
- }
-
ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices,
"The usage of restart indices in index buffer does not match the render primitive in the pipeline.");
#endif
diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp
index 3a62850339..fb90b776cf 100644
--- a/drivers/wasapi/audio_driver_wasapi.cpp
+++ b/drivers/wasapi/audio_driver_wasapi.cpp
@@ -501,11 +501,11 @@ Error AudioDriverWASAPI::init_capture_device(bool reinit) {
}
Error AudioDriverWASAPI::audio_device_finish(AudioDeviceWASAPI *p_device) {
- if (p_device->active) {
+ if (p_device->active.is_set()) {
if (p_device->audio_client) {
p_device->audio_client->Stop();
}
- p_device->active = false;
+ p_device->active.clear();
}
SAFE_RELEASE(p_device->audio_client)
@@ -533,8 +533,7 @@ Error AudioDriverWASAPI::init() {
ERR_PRINT("WASAPI: init_render_device error");
}
- exit_thread = false;
- thread_exited = false;
+ exit_thread.clear();
thread.start(thread_func, this);
@@ -553,8 +552,8 @@ AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
return get_speaker_mode_by_total_channels(channels);
}
-Array AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
- Array list;
+PackedStringArray AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
+ PackedStringArray list;
IMMDeviceCollection *devices = nullptr;
IMMDeviceEnumerator *enumerator = nullptr;
@@ -563,14 +562,14 @@ Array AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
CoInitialize(nullptr);
HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
- ERR_FAIL_COND_V(hr != S_OK, Array());
+ ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());
hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
- ERR_FAIL_COND_V(hr != S_OK, Array());
+ ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());
UINT count = 0;
hr = devices->GetCount(&count);
- ERR_FAIL_COND_V(hr != S_OK, Array());
+ ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());
for (ULONG i = 0; i < count; i++) {
IMMDevice *device = nullptr;
@@ -600,7 +599,7 @@ Array AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
return list;
}
-Array AudioDriverWASAPI::get_device_list() {
+PackedStringArray AudioDriverWASAPI::get_device_list() {
return audio_device_get_list(false);
}
@@ -684,7 +683,7 @@ void AudioDriverWASAPI::thread_func(void *p_udata) {
uint32_t avail_frames = 0;
uint32_t write_ofs = 0;
- while (!ad->exit_thread) {
+ while (!ad->exit_thread.is_set()) {
uint32_t read_frames = 0;
uint32_t written_frames = 0;
@@ -692,7 +691,7 @@ void AudioDriverWASAPI::thread_func(void *p_udata) {
ad->lock();
ad->start_counting_ticks();
- if (ad->audio_output.active) {
+ if (ad->audio_output.active.is_set()) {
ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
} else {
for (int i = 0; i < ad->samples_in.size(); i++) {
@@ -758,7 +757,7 @@ void AudioDriverWASAPI::thread_func(void *p_udata) {
}
} else {
ERR_PRINT("WASAPI: Get buffer error");
- ad->exit_thread = true;
+ ad->exit_thread.set();
}
}
} else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
@@ -807,7 +806,7 @@ void AudioDriverWASAPI::thread_func(void *p_udata) {
write_ofs = 0;
}
- if (ad->audio_input.active) {
+ if (ad->audio_input.active.is_set()) {
UINT32 packet_length = 0;
BYTE *data;
UINT32 num_frames_available;
@@ -886,8 +885,6 @@ void AudioDriverWASAPI::thread_func(void *p_udata) {
OS::get_singleton()->delay_usec(1000);
}
}
-
- ad->thread_exited = true;
}
void AudioDriverWASAPI::start() {
@@ -896,7 +893,7 @@ void AudioDriverWASAPI::start() {
if (hr != S_OK) {
ERR_PRINT("WASAPI: Start failed");
} else {
- audio_output.active = true;
+ audio_output.active.set();
}
}
}
@@ -910,7 +907,7 @@ void AudioDriverWASAPI::unlock() {
}
void AudioDriverWASAPI::finish() {
- exit_thread = true;
+ exit_thread.set();
thread.wait_to_finish();
finish_capture_device();
@@ -924,19 +921,19 @@ Error AudioDriverWASAPI::capture_start() {
return err;
}
- if (audio_input.active) {
+ if (audio_input.active.is_set()) {
return FAILED;
}
audio_input.audio_client->Start();
- audio_input.active = true;
+ audio_input.active.set();
return OK;
}
Error AudioDriverWASAPI::capture_stop() {
- if (audio_input.active) {
+ if (audio_input.active.is_set()) {
audio_input.audio_client->Stop();
- audio_input.active = false;
+ audio_input.active.clear();
return OK;
}
@@ -950,7 +947,7 @@ void AudioDriverWASAPI::capture_set_device(const String &p_name) {
unlock();
}
-Array AudioDriverWASAPI::capture_get_device_list() {
+PackedStringArray AudioDriverWASAPI::capture_get_device_list() {
return audio_device_get_list(true);
}
diff --git a/drivers/wasapi/audio_driver_wasapi.h b/drivers/wasapi/audio_driver_wasapi.h
index 9058077a1f..c30a54c042 100644
--- a/drivers/wasapi/audio_driver_wasapi.h
+++ b/drivers/wasapi/audio_driver_wasapi.h
@@ -35,6 +35,7 @@
#include "core/os/mutex.h"
#include "core/os/thread.h"
+#include "core/templates/safe_refcount.h"
#include "servers/audio_server.h"
#include <audioclient.h>
@@ -48,7 +49,7 @@ class AudioDriverWASAPI : public AudioDriver {
IAudioClient *audio_client = nullptr;
IAudioRenderClient *render_client = nullptr;
IAudioCaptureClient *capture_client = nullptr;
- bool active = false;
+ SafeFlag active;
WORD format_tag = 0;
WORD bits_per_sample = 0;
@@ -76,8 +77,7 @@ class AudioDriverWASAPI : public AudioDriver {
float real_latency = 0.0;
bool using_audio_client_3 = false;
- bool thread_exited = false;
- mutable bool exit_thread = false;
+ SafeFlag exit_thread;
static _FORCE_INLINE_ void write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample);
static _FORCE_INLINE_ int32_t read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i);
@@ -91,7 +91,7 @@ class AudioDriverWASAPI : public AudioDriver {
Error audio_device_init(AudioDeviceWASAPI *p_device, bool p_capture, bool reinit);
Error audio_device_finish(AudioDeviceWASAPI *p_device);
- Array audio_device_get_list(bool p_capture);
+ PackedStringArray audio_device_get_list(bool p_capture);
public:
virtual const char *get_name() const {
@@ -103,7 +103,7 @@ public:
virtual int get_mix_rate() const;
virtual float get_latency();
virtual SpeakerMode get_speaker_mode() const;
- virtual Array get_device_list();
+ virtual PackedStringArray get_device_list();
virtual String get_device();
virtual void set_device(String device);
virtual void lock();
@@ -112,7 +112,7 @@ public:
virtual Error capture_start();
virtual Error capture_stop();
- virtual Array capture_get_device_list();
+ virtual PackedStringArray capture_get_device_list();
virtual void capture_set_device(const String &p_name);
virtual String capture_get_device();
diff --git a/drivers/windows/dir_access_windows.cpp b/drivers/windows/dir_access_windows.cpp
index 881575d245..2125709b32 100644
--- a/drivers/windows/dir_access_windows.cpp
+++ b/drivers/windows/dir_access_windows.cpp
@@ -402,6 +402,8 @@ DirAccessWindows::DirAccessWindows() {
}
DirAccessWindows::~DirAccessWindows() {
+ list_dir_end();
+
memdelete(p);
}
diff --git a/drivers/xaudio2/audio_driver_xaudio2.cpp b/drivers/xaudio2/audio_driver_xaudio2.cpp
index c32c7cf1e5..6c48c1a844 100644
--- a/drivers/xaudio2/audio_driver_xaudio2.cpp
+++ b/drivers/xaudio2/audio_driver_xaudio2.cpp
@@ -38,9 +38,8 @@ const char *AudioDriverXAudio2::get_name() const {
}
Error AudioDriverXAudio2::init() {
- active = false;
- thread_exited = false;
- exit_thread = false;
+ active.clear();
+ exit_thread.clear();
pcm_open = false;
samples_in = nullptr;
@@ -86,17 +85,19 @@ Error AudioDriverXAudio2::init() {
void AudioDriverXAudio2::thread_func(void *p_udata) {
AudioDriverXAudio2 *ad = static_cast<AudioDriverXAudio2 *>(p_udata);
- while (!ad->exit_thread) {
- if (!ad->active) {
+ while (!ad->exit_thread.is_set()) {
+ if (!ad->active.is_set()) {
for (int i = 0; i < AUDIO_BUFFERS; i++) {
ad->xaudio_buffer[i].Flags = XAUDIO2_END_OF_STREAM;
}
} else {
ad->lock();
+ ad->start_counting_ticks();
ad->audio_server_process(ad->buffer_size, ad->samples_in);
+ ad->stop_counting_ticks();
ad->unlock();
for (unsigned int i = 0; i < ad->buffer_size * ad->channels; i++) {
@@ -117,12 +118,10 @@ void AudioDriverXAudio2::thread_func(void *p_udata) {
}
}
}
-
- ad->thread_exited = true;
}
void AudioDriverXAudio2::start() {
- active = true;
+ active.set();
HRESULT hr = source_voice->Start(0);
ERR_FAIL_COND_MSG(hr != S_OK, "Error starting XAudio2 driver. Error code: " + itos(hr) + ".");
}
@@ -154,7 +153,7 @@ void AudioDriverXAudio2::unlock() {
}
void AudioDriverXAudio2::finish() {
- exit_thread = true;
+ exit_thread.set();
thread.wait_to_finish();
if (source_voice) {
diff --git a/drivers/xaudio2/audio_driver_xaudio2.h b/drivers/xaudio2/audio_driver_xaudio2.h
index 81432ceb8e..0f64d54a1f 100644
--- a/drivers/xaudio2/audio_driver_xaudio2.h
+++ b/drivers/xaudio2/audio_driver_xaudio2.h
@@ -33,6 +33,7 @@
#include "core/os/mutex.h"
#include "core/os/thread.h"
+#include "core/templates/safe_refcount.h"
#include "servers/audio_server.h"
#include <mmsystem.h>
@@ -77,9 +78,8 @@ class AudioDriverXAudio2 : public AudioDriver {
int channels = 0;
- bool active = false;
- bool thread_exited = false;
- mutable bool exit_thread = false;
+ SafeFlag active;
+ SafeFlag exit_thread;
bool pcm_open = false;
WAVEFORMATEX wave_format = { 0 };
diff --git a/editor/action_map_editor.cpp b/editor/action_map_editor.cpp
index 462f314471..648e950fd4 100644
--- a/editor/action_map_editor.cpp
+++ b/editor/action_map_editor.cpp
@@ -1061,6 +1061,9 @@ void ActionMapEditor::_notification(int p_what) {
case NOTIFICATION_ENTER_TREE:
case NOTIFICATION_THEME_CHANGED: {
action_list_search->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
+ if (!actions_cache.is_empty()) {
+ update_action_list();
+ }
} break;
}
}
diff --git a/editor/animation_bezier_editor.cpp b/editor/animation_bezier_editor.cpp
index e10ed7e976..9af8b907c4 100644
--- a/editor/animation_bezier_editor.cpp
+++ b/editor/animation_bezier_editor.cpp
@@ -32,6 +32,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/view_panner.h"
#include "scene/resources/text_line.h"
@@ -40,7 +41,7 @@
float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h) {
float h = p_h;
h = (h - v_scroll) / v_zoom;
- h = (get_size().height / 2) - h;
+ h = (get_size().height / 2.0) - h;
return h;
}
@@ -51,10 +52,10 @@ void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
int right_limit = get_size().width;
//selection may have altered the order of keys
- RBMap<float, int> key_order;
+ RBMap<real_t, int> key_order;
for (int i = 0; i < animation->track_get_key_count(p_track); i++) {
- float ofs = animation->track_get_key_time(p_track, i);
+ real_t ofs = animation->track_get_key_time(p_track, i);
if (moving_selection && selection.has(IntPair(p_track, i))) {
ofs += moving_selection_offset.x;
}
@@ -62,7 +63,7 @@ void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
key_order[ofs] = i;
}
- for (RBMap<float, int>::Element *E = key_order.front(); E; E = E->next()) {
+ for (RBMap<real_t, int>::Element *E = key_order.front(); E; E = E->next()) {
int i = E->get();
if (!E->next()) {
@@ -74,7 +75,7 @@ void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float offset = animation->track_get_key_time(p_track, i);
float height = animation->bezier_track_get_key_value(p_track, i);
Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i);
- if (p_track == moving_handle_track && moving_handle != 0 && moving_handle_key == i) {
+ if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i) {
out_handle = moving_handle_right;
}
@@ -88,7 +89,7 @@ void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float offset_n = animation->track_get_key_time(p_track, i_n);
float height_n = animation->bezier_track_get_key_value(p_track, i_n);
Vector2 in_handle = animation->bezier_track_get_key_in_handle(p_track, i_n);
- if (p_track == moving_handle_track && moving_handle != 0 && moving_handle_key == i_n) {
+ if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i_n) {
in_handle = moving_handle_left;
}
@@ -138,7 +139,7 @@ void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
//narrow high and low as much as possible
for (int k = 0; k < iterations; k++) {
- float middle = (low + high) / 2;
+ float middle = (low + high) / 2.0;
Vector2 interp = start.bezier_interpolate(out_handle, in_handle, end, middle);
@@ -315,7 +316,7 @@ void AnimationBezierTrackEdit::_notification(int p_what) {
int h = MAX(text_buf.get_size().y, icon->get_height());
- draw_texture(icon, Point2(ofs, vofs + int(h - icon->get_height()) / 2));
+ draw_texture(icon, Point2(ofs, vofs + int(h - icon->get_height()) / 2.0));
ofs += icon->get_width();
margin = icon->get_width();
@@ -402,29 +403,29 @@ void AnimationBezierTrackEdit::_notification(int p_what) {
Vector2 string_pos = Point2(margin, vofs);
text_buf.draw(get_canvas_item(), string_pos, cc);
- float icon_start_height = vofs + rect.size.y / 2;
- Rect2 remove_rect = Rect2(remove_hpos, icon_start_height - remove->get_height() / 2, remove->get_width(), remove->get_height());
+ float icon_start_height = vofs + rect.size.y / 2.0;
+ Rect2 remove_rect = Rect2(remove_hpos, icon_start_height - remove->get_height() / 2.0, remove->get_width(), remove->get_height());
if (read_only) {
draw_texture(remove, remove_rect.position, dc);
} else {
draw_texture(remove, remove_rect.position);
}
- Rect2 lock_rect = Rect2(lock_hpos, icon_start_height - lock->get_height() / 2, lock->get_width(), lock->get_height());
+ Rect2 lock_rect = Rect2(lock_hpos, icon_start_height - lock->get_height() / 2.0, lock->get_width(), lock->get_height());
if (locked_tracks.has(current_track)) {
draw_texture(lock, lock_rect.position);
} else {
draw_texture(unlock, lock_rect.position);
}
- Rect2 visible_rect = Rect2(visibility_hpos, icon_start_height - visible->get_height() / 2, visible->get_width(), visible->get_height());
+ Rect2 visible_rect = Rect2(visibility_hpos, icon_start_height - visible->get_height() / 2.0, visible->get_width(), visible->get_height());
if (hidden_tracks.has(current_track)) {
draw_texture(hidden, visible_rect.position);
} else {
draw_texture(visible, visible_rect.position);
}
- Rect2 solo_rect = Rect2(solo_hpos, icon_start_height - solo->get_height() / 2, solo->get_width(), solo->get_height());
+ Rect2 solo_rect = Rect2(solo_hpos, icon_start_height - solo->get_height() / 2.0, solo->get_width(), solo->get_height());
draw_texture(solo, solo_rect.position);
RBMap<int, Rect2> track_icons;
@@ -455,7 +456,7 @@ void AnimationBezierTrackEdit::_notification(int p_what) {
bool first = true;
int prev_iv = 0;
for (int i = font->get_height(font_size); i < get_size().height; i++) {
- float ofs = get_size().height / 2 - i;
+ float ofs = get_size().height / 2.0 - i;
ofs *= v_zoom;
ofs += v_scroll;
@@ -494,7 +495,7 @@ void AnimationBezierTrackEdit::_notification(int p_what) {
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (pos.x >= limit && pos.x <= right_limit) {
- draw_texture(point, pos - point->get_size() / 2, E.value);
+ draw_texture(point, pos - point->get_size() / 2.0, E.value);
}
}
}
@@ -546,14 +547,15 @@ void AnimationBezierTrackEdit::_notification(int p_what) {
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
Vector2 in_vec = animation->bezier_track_get_key_in_handle(i, j);
- if (moving_handle != 0 && moving_handle_track == i && moving_handle_key == j) {
+
+ if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
in_vec = moving_handle_left;
}
Vector2 pos_in(((offset + in_vec.x) - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value + in_vec.y));
Vector2 out_vec = animation->bezier_track_get_key_out_handle(i, j);
- if (moving_handle != 0 && moving_handle_track == i && moving_handle_key == j) {
+ if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
out_vec = moving_handle_right;
}
@@ -568,7 +570,7 @@ void AnimationBezierTrackEdit::_notification(int p_what) {
ep.track = i;
ep.key = j;
if (pos.x >= limit && pos.x <= right_limit) {
- ep.point_rect.position = (pos - bezier_icon->get_size() / 2).floor();
+ ep.point_rect.position = (pos - bezier_icon->get_size() / 2.0).floor();
ep.point_rect.size = bezier_icon->get_size();
if (selection.has(IntPair(i, j))) {
draw_texture(selected_icon, ep.point_rect.position);
@@ -583,18 +585,22 @@ void AnimationBezierTrackEdit::_notification(int p_what) {
}
ep.point_rect = ep.point_rect.grow(ep.point_rect.size.width * 0.5);
}
+ ep.point_rect = ep.point_rect.grow(ep.point_rect.size.width * 0.5);
+
if (i == selected_track || selection.has(IntPair(i, j))) {
- if (pos_in.x >= limit && pos_in.x <= right_limit) {
- ep.in_rect.position = (pos_in - bezier_handle_icon->get_size() / 2).floor();
- ep.in_rect.size = bezier_handle_icon->get_size();
- draw_texture(bezier_handle_icon, ep.in_rect.position);
- ep.in_rect = ep.in_rect.grow(ep.in_rect.size.width * 0.5);
- }
- if (pos_out.x >= limit && pos_out.x <= right_limit) {
- ep.out_rect.position = (pos_out - bezier_handle_icon->get_size() / 2).floor();
- ep.out_rect.size = bezier_handle_icon->get_size();
- draw_texture(bezier_handle_icon, ep.out_rect.position);
- ep.out_rect = ep.out_rect.grow(ep.out_rect.size.width * 0.5);
+ if (animation->bezier_track_get_key_handle_mode(i, j) != Animation::HANDLE_MODE_LINEAR) {
+ if (pos_in.x >= limit && pos_in.x <= right_limit) {
+ ep.in_rect.position = (pos_in - bezier_handle_icon->get_size() / 2.0).floor();
+ ep.in_rect.size = bezier_handle_icon->get_size();
+ draw_texture(bezier_handle_icon, ep.in_rect.position);
+ ep.in_rect = ep.in_rect.grow(ep.in_rect.size.width * 0.5);
+ }
+ if (pos_out.x >= limit && pos_out.x <= right_limit) {
+ ep.out_rect.position = (pos_out - bezier_handle_icon->get_size() / 2.0).floor();
+ ep.out_rect.size = bezier_handle_icon->get_size();
+ draw_texture(bezier_handle_icon, ep.out_rect.position);
+ ep.out_rect = ep.out_rect.grow(ep.out_rect.size.width * 0.5);
+ }
}
}
if (!locked_tracks.has(i)) {
@@ -649,7 +655,7 @@ Size2 AnimationBezierTrackEdit::get_minimum_size() const {
return Vector2(1, 1);
}
-void AnimationBezierTrackEdit::set_undo_redo(UndoRedo *p_undo_redo) {
+void AnimationBezierTrackEdit::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
undo_redo = p_undo_redo;
}
@@ -663,7 +669,6 @@ void AnimationBezierTrackEdit::set_editor(AnimationTrackEditor *p_editor) {
editor = p_editor;
connect("clear_selection", Callable(editor, "_clear_selection").bind(false));
connect("select_key", Callable(editor, "_key_selected"), CONNECT_DEFERRED);
- connect("deselect_key", Callable(editor, "_key_deselected"), CONNECT_DEFERRED);
}
void AnimationBezierTrackEdit::_play_position_draw() {
@@ -684,7 +689,7 @@ void AnimationBezierTrackEdit::_play_position_draw() {
}
}
-void AnimationBezierTrackEdit::set_play_position(float p_pos) {
+void AnimationBezierTrackEdit::set_play_position(real_t p_pos) {
play_position_pos = p_pos;
play_position->update();
}
@@ -785,13 +790,14 @@ void AnimationBezierTrackEdit::_clear_selection() {
update();
}
-void AnimationBezierTrackEdit::_change_selected_keys_handle_mode(Animation::HandleMode p_mode) {
+void AnimationBezierTrackEdit::_change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto) {
undo_redo->create_action(TTR("Update Selected Key Handles"));
- double ratio = timeline->get_zoom_scale() * v_zoom;
- for (const IntPair &E : selection) {
- const IntPair track_key_pair = E;
- undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_handle_mode", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_handle_mode(track_key_pair.first, track_key_pair.second), ratio);
- undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_handle_mode", track_key_pair.first, track_key_pair.second, p_mode, ratio);
+ for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
+ const IntPair track_key_pair = E->get();
+ undo_redo->add_undo_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_handle_mode(track_key_pair.first, track_key_pair.second), Animation::HANDLE_SET_MODE_NONE);
+ undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_in_handle(track_key_pair.first, track_key_pair.second));
+ undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_out_handle(track_key_pair.first, track_key_pair.second));
+ undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, p_mode, p_auto ? Animation::HANDLE_SET_MODE_AUTO : Animation::HANDLE_SET_MODE_RESET);
}
undo_redo->commit_action();
}
@@ -803,7 +809,7 @@ void AnimationBezierTrackEdit::_clear_selection_for_anim(const Ref<Animation> &p
_clear_selection();
}
-void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos) {
+void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos) {
if (!(animation == p_anim)) {
return;
}
@@ -812,7 +818,7 @@ void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int
ERR_FAIL_COND(idx < 0);
selection.insert(IntPair(p_track, idx));
- emit_signal(SNAME("select_key"), p_track, idx, true);
+ emit_signal(SNAME("select_key"), idx, true, p_track);
update();
}
@@ -868,16 +874,16 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
return;
}
- float minimum_time = INFINITY;
- float maximum_time = -INFINITY;
- float minimum_value = INFINITY;
- float maximum_value = -INFINITY;
+ real_t minimum_time = INFINITY;
+ real_t maximum_time = -INFINITY;
+ real_t minimum_value = INFINITY;
+ real_t maximum_value = -INFINITY;
for (const IntPair &E : selection) {
IntPair key_pair = E;
- float time = animation->track_get_key_time(key_pair.first, key_pair.second);
- float value = animation->bezier_track_get_key_value(key_pair.first, key_pair.second);
+ real_t time = animation->track_get_key_time(key_pair.first, key_pair.second);
+ real_t value = animation->bezier_track_get_key_value(key_pair.first, key_pair.second);
minimum_time = MIN(time, minimum_time);
maximum_time = MAX(time, maximum_time);
@@ -887,8 +893,8 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
float width = get_size().width - timeline->get_name_limit() - timeline->get_buttons_width();
float padding = width * 0.1;
- float desired_scale = (width - padding / 2) / (maximum_time - minimum_time);
- minimum_time = MAX(0, minimum_time - (padding / 2) / desired_scale);
+ float desired_scale = (width - padding / 2.0) / (maximum_time - minimum_time);
+ minimum_time = MAX(0, minimum_time - (padding / 2.0) / desired_scale);
float zv = Math::pow(100 / desired_scale, 0.125f);
if (zv < 1) {
@@ -942,7 +948,12 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
menu->add_icon_item(get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), TTR("Delete Selected Key(s)"), MENU_KEY_DELETE);
menu->add_separator();
menu->add_icon_item(get_theme_icon(SNAME("BezierHandlesFree"), SNAME("EditorIcons")), TTR("Make Handles Free"), MENU_KEY_SET_HANDLE_FREE);
+ menu->add_icon_item(get_theme_icon(SNAME("BezierHandlesLinear"), SNAME("EditorIcons")), TTR("Make Handles Linear"), MENU_KEY_SET_HANDLE_LINEAR);
menu->add_icon_item(get_theme_icon(SNAME("BezierHandlesBalanced"), SNAME("EditorIcons")), TTR("Make Handles Balanced"), MENU_KEY_SET_HANDLE_BALANCED);
+ menu->add_icon_item(get_theme_icon(SNAME("BezierHandlesMirror"), SNAME("EditorIcons")), TTR("Make Handles Mirrored"), MENU_KEY_SET_HANDLE_MIRRORED);
+ menu->add_separator();
+ menu->add_icon_item(get_theme_icon(SNAME("BezierHandlesBalanced"), SNAME("EditorIcons")), TTR("Make Handles Balanced (Auto Tangent)"), MENU_KEY_SET_HANDLE_AUTO_BALANCED);
+ menu->add_icon_item(get_theme_icon(SNAME("BezierHandlesMirror"), SNAME("EditorIcons")), TTR("Make Handles Mirrored (Auto Tangent)"), MENU_KEY_SET_HANDLE_AUTO_MIRRORED);
}
if (menu->get_item_count()) {
@@ -984,9 +995,10 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
for (int i = 0; i < animation->track_get_key_count(track); ++i) {
undo_redo->add_undo_method(
- animation.ptr(),
- "bezier_track_insert_key",
- track, animation->track_get_key_time(track, i),
+ this,
+ "_bezier_track_insert_key",
+ track,
+ animation->track_get_key_time(track, i),
animation->bezier_track_get_key_value(track, i),
animation->bezier_track_get_key_in_handle(track, i),
animation->bezier_track_get_key_out_handle(track, i),
@@ -1093,6 +1105,9 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
moving_selection = false;
moving_selection_from_key = pair.second;
moving_selection_from_track = pair.first;
+ moving_handle_track = pair.first;
+ moving_handle_left = animation->bezier_track_get_key_in_handle(pair.first, pair.second);
+ moving_handle_right = animation->bezier_track_get_key_out_handle(pair.first, pair.second);
moving_selection_offset = Vector2();
select_single_attempt = pair;
update();
@@ -1102,10 +1117,12 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
moving_selection_from_key = pair.second;
moving_selection_from_track = pair.first;
moving_selection_offset = Vector2();
- set_animation_and_track(animation, pair.first, read_only);
+ moving_handle_track = pair.first;
+ moving_handle_left = animation->bezier_track_get_key_in_handle(pair.first, pair.second);
+ moving_handle_right = animation->bezier_track_get_key_out_handle(pair.first, pair.second);
selection.clear();
selection.insert(pair);
- update();
+ set_animation_and_track(animation, pair.first, read_only);
}
return;
}
@@ -1137,24 +1154,23 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
//insert new point
if (mb->get_position().x >= limit && mb->get_position().x < get_size().width && mb->is_command_pressed()) {
Array new_point;
- new_point.resize(6);
+ new_point.resize(5);
- float h = (get_size().height / 2 - mb->get_position().y) * v_zoom + v_scroll;
+ float h = (get_size().height / 2.0 - mb->get_position().y) * v_zoom + v_scroll;
new_point[0] = h;
new_point[1] = -0.25;
new_point[2] = 0;
new_point[3] = 0.25;
new_point[4] = 0;
- new_point[5] = 0;
- float time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
+ real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
while (animation->track_find_key(selected_track, time, true) != -1) {
time += 0.001;
}
undo_redo->create_action(TTR("Add Bezier Point"));
- undo_redo->add_do_method(animation.ptr(), "track_insert_key", selected_track, time, new_point);
+ undo_redo->add_do_method(animation.ptr(), "bezier_track_insert_key", selected_track, time, new_point);
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", selected_track, time);
undo_redo->commit_action();
@@ -1218,10 +1234,10 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
//select by clicking on curve
int track_count = animation->get_track_count();
- float animation_length = animation->get_length();
+ real_t animation_length = animation->get_length();
animation->set_length(real_t(INT_MAX)); //bezier_track_interpolate doesn't find keys if they exist beyond anim length
- float time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
+ real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
for (int i = 0; i < track_count; ++i) {
if (animation->track_get_type(i) != Animation::TrackType::TYPE_BEZIER || hidden_tracks.has(i) || locked_tracks.has(i)) {
@@ -1245,20 +1261,6 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
update();
}
- if (moving_handle != 0 && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
- if (!read_only) {
- undo_redo->create_action(TTR("Move Bezier Points"));
- undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_in_handle", selected_track, moving_handle_key, moving_handle_left);
- undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_out_handle", selected_track, moving_handle_key, moving_handle_right);
- undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", selected_track, moving_handle_key, animation->bezier_track_get_key_in_handle(selected_track, moving_handle_key));
- undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", selected_track, moving_handle_key, animation->bezier_track_get_key_out_handle(selected_track, moving_handle_key));
- undo_redo->commit_action();
-
- moving_handle = 0;
- update();
- }
- }
-
if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (!read_only) {
if (moving_selection) {
@@ -1267,13 +1269,14 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
undo_redo->create_action(TTR("Move Bezier Points"));
List<AnimMoveRestore> to_restore;
+ List<Animation::HandleMode> to_restore_handle_modes;
// 1-remove the keys
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second);
}
// 2- remove overlapped keys
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
- float newtime = editor->snap_time(animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x);
+ real_t newtime = editor->snap_time(animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x);
int idx = animation->track_find_key(E->get().first, newtime, true);
if (idx == -1) {
@@ -1292,33 +1295,62 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
amr.time = newtime;
to_restore.push_back(amr);
+ to_restore_handle_modes.push_back(animation->bezier_track_get_key_handle_mode(E->get().first, idx));
}
// 3-move the keys (re insert them)
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
- float newpos = editor->snap_time(animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x);
+ real_t newpos = editor->snap_time(animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x);
Array key = animation->track_get_key_value(E->get().first, E->get().second);
- float h = key[0];
+ real_t h = key[0];
h += moving_selection_offset.y;
key[0] = h;
- undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->get().first, newpos, key, 1);
+ undo_redo->add_do_method(
+ this,
+ "_bezier_track_insert_key",
+ E->get().first,
+ newpos,
+ key[0],
+ Vector2(key[1], key[2]),
+ Vector2(key[3], key[4]),
+ animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 4-(undo) remove inserted keys
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
- float newpos = editor->snap_time(animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x);
+ real_t newpos = editor->snap_time(animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x);
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newpos);
}
// 5-(undo) reinsert keys
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
- float oldpos = animation->track_get_key_time(E->get().first, E->get().second);
- undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->get().first, oldpos, animation->track_get_key_value(E->get().first, E->get().second), 1);
+ real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
+ Array key = animation->track_get_key_value(E->get().first, E->get().second);
+ undo_redo->add_undo_method(
+ this,
+ "_bezier_track_insert_key",
+ E->get().first,
+ oldpos,
+ key[0],
+ Vector2(key[1], key[2]),
+ Vector2(key[3], key[4]),
+ animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 6-(undo) reinsert overlapped keys
- for (const AnimMoveRestore &amr : to_restore) {
+ for (int i = 0; i < to_restore.size(); i++) {
+ const AnimMoveRestore &amr = to_restore[i];
+ Array key = amr.key;
undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, 1);
+ undo_redo->add_undo_method(
+ this,
+ "_bezier_track_insert_key",
+ amr.track,
+ amr.time,
+ key[0],
+ Vector2(key[1], key[2]),
+ Vector2(key[3], key[4]),
+ to_restore_handle_modes[i]);
}
undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
@@ -1327,8 +1359,8 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
// 7-reselect
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
- float oldpos = animation->track_get_key_time(E->get().first, E->get().second);
- float newpos = editor->snap_time(oldpos + moving_selection_offset.x);
+ real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
+ real_t newpos = editor->snap_time(oldpos + moving_selection_offset.x);
undo_redo->add_do_method(this, "_select_at_anim", animation, E->get().first, newpos);
undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, oldpos);
@@ -1355,12 +1387,16 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
select_single_attempt = IntPair(-1, -1);
}
- float y = (get_size().height / 2 - mm->get_position().y) * v_zoom + v_scroll;
+ float y = (get_size().height / 2.0 - mm->get_position().y) * v_zoom + v_scroll;
float x = editor->snap_time(((mm->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value());
if (!read_only) {
moving_selection_offset = Vector2(x - animation->track_get_key_time(moving_selection_from_track, moving_selection_from_key), y - animation->bezier_track_get_key_value(moving_selection_from_track, moving_selection_from_key));
}
+
+ additional_moving_handle_lefts.clear();
+ additional_moving_handle_rights.clear();
+
update();
}
@@ -1379,8 +1415,8 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
update();
}
- if (moving_handle != 0 && mm.is_valid()) {
- float y = (get_size().height / 2 - mm->get_position().y) * v_zoom + v_scroll;
+ if ((moving_handle == 1 || moving_handle == -1) && mm.is_valid()) {
+ float y = (get_size().height / 2.0 - mm->get_position().y) * v_zoom + v_scroll;
float x = editor->snap_time((mm->get_position().x - timeline->get_name_limit()) / timeline->get_zoom_scale()) + timeline->get_value();
Vector2 key_pos = Vector2(animation->track_get_key_time(selected_track, moving_handle_key), animation->bezier_track_get_key_value(selected_track, moving_handle_key));
@@ -1393,8 +1429,10 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
if (moving_handle == -1) {
moving_handle_left = moving_handle_value;
- if (animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key) == Animation::HANDLE_MODE_BALANCED) {
- double ratio = timeline->get_zoom_scale() * v_zoom;
+ Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key);
+
+ if (handle_mode == Animation::HANDLE_MODE_BALANCED) {
+ real_t ratio = timeline->get_zoom_scale() * v_zoom;
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / ratio));
@@ -1402,12 +1440,16 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
Vector2 vec_in = xform.xform(moving_handle_left);
moving_handle_right = xform.affine_inverse().xform(-vec_in.normalized() * vec_out.length());
+ } else if (handle_mode == Animation::HANDLE_MODE_MIRRORED) {
+ moving_handle_right = -moving_handle_left;
}
} else if (moving_handle == 1) {
moving_handle_right = moving_handle_value;
- if (animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key) == Animation::HANDLE_MODE_BALANCED) {
- double ratio = timeline->get_zoom_scale() * v_zoom;
+ Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key);
+
+ if (handle_mode == Animation::HANDLE_MODE_BALANCED) {
+ real_t ratio = timeline->get_zoom_scale() * v_zoom;
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / ratio));
@@ -1415,26 +1457,26 @@ void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
Vector2 vec_out = xform.xform(moving_handle_right);
moving_handle_left = xform.affine_inverse().xform(-vec_out.normalized() * vec_in.length());
+ } else if (handle_mode == Animation::HANDLE_MODE_MIRRORED) {
+ moving_handle_left = -moving_handle_right;
}
}
update();
}
- bool is_finishing_key_handle_drag = moving_handle != 0 && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT;
- if (is_finishing_key_handle_drag) {
+ if ((moving_handle == -1 || moving_handle == 1) && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (!read_only) {
undo_redo->create_action(TTR("Move Bezier Points"));
if (moving_handle == -1) {
- double ratio = timeline->get_zoom_scale() * v_zoom;
+ real_t ratio = timeline->get_zoom_scale() * v_zoom;
undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_in_handle", moving_handle_track, moving_handle_key, moving_handle_left, ratio);
undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", moving_handle_track, moving_handle_key, animation->bezier_track_get_key_in_handle(moving_handle_track, moving_handle_key), ratio);
} else if (moving_handle == 1) {
- double ratio = timeline->get_zoom_scale() * v_zoom;
+ real_t ratio = timeline->get_zoom_scale() * v_zoom;
undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_out_handle", moving_handle_track, moving_handle_key, moving_handle_right, ratio);
undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", moving_handle_track, moving_handle_key, animation->bezier_track_get_key_out_handle(moving_handle_track, moving_handle_key), ratio);
}
undo_redo->commit_action();
-
moving_handle = 0;
update();
}
@@ -1468,7 +1510,7 @@ void AnimationBezierTrackEdit::_zoom_callback(Vector2 p_scroll_vec, Vector2 p_or
timeline->get_zoom()->set_value(timeline->get_zoom()->get_value() * 1.05);
}
}
- v_scroll = v_scroll + (p_origin.y - get_size().y / 2) * (v_zoom - v_zoom_orig);
+ v_scroll = v_scroll + (p_origin.y - get_size().y / 2.0) * (v_zoom - v_zoom_orig);
update();
}
@@ -1477,20 +1519,19 @@ void AnimationBezierTrackEdit::_menu_selected(int p_index) {
case MENU_KEY_INSERT: {
if (animation->get_track_count() > 0) {
Array new_point;
- new_point.resize(6);
+ new_point.resize(5);
- float h = (get_size().height / 2 - menu_insert_key.y) * v_zoom + v_scroll;
+ float h = (get_size().height / 2.0 - menu_insert_key.y) * v_zoom + v_scroll;
new_point[0] = h;
new_point[1] = -0.25;
new_point[2] = 0;
new_point[3] = 0.25;
new_point[4] = 0;
- new_point[5] = Animation::HANDLE_MODE_BALANCED;
int limit = timeline->get_name_limit();
- float time = ((menu_insert_key.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
+ real_t time = ((menu_insert_key.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
while (animation->track_find_key(selected_track, time, true) != -1) {
time += 0.001;
@@ -1500,8 +1541,8 @@ void AnimationBezierTrackEdit::_menu_selected(int p_index) {
undo_redo->add_do_method(animation.ptr(), "track_insert_key", selected_track, time, new_point);
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", selected_track, time);
undo_redo->commit_action();
+ update();
}
-
} break;
case MENU_KEY_DUPLICATE: {
duplicate_selection();
@@ -1512,9 +1553,21 @@ void AnimationBezierTrackEdit::_menu_selected(int p_index) {
case MENU_KEY_SET_HANDLE_FREE: {
_change_selected_keys_handle_mode(Animation::HANDLE_MODE_FREE);
} break;
+ case MENU_KEY_SET_HANDLE_LINEAR: {
+ _change_selected_keys_handle_mode(Animation::HANDLE_MODE_LINEAR);
+ } break;
case MENU_KEY_SET_HANDLE_BALANCED: {
_change_selected_keys_handle_mode(Animation::HANDLE_MODE_BALANCED);
} break;
+ case MENU_KEY_SET_HANDLE_MIRRORED: {
+ _change_selected_keys_handle_mode(Animation::HANDLE_MODE_MIRRORED);
+ } break;
+ case MENU_KEY_SET_HANDLE_AUTO_BALANCED: {
+ _change_selected_keys_handle_mode(Animation::HANDLE_MODE_BALANCED, true);
+ } break;
+ case MENU_KEY_SET_HANDLE_AUTO_MIRRORED: {
+ _change_selected_keys_handle_mode(Animation::HANDLE_MODE_MIRRORED, true);
+ } break;
}
}
@@ -1523,9 +1576,9 @@ void AnimationBezierTrackEdit::duplicate_selection() {
return;
}
- float top_time = 1e10;
+ real_t top_time = 1e10;
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
- float t = animation->track_get_key_time(E->get().first, E->get().second);
+ real_t t = animation->track_get_key_time(E->get().first, E->get().second);
if (t < top_time) {
top_time = t;
}
@@ -1533,17 +1586,17 @@ void AnimationBezierTrackEdit::duplicate_selection() {
undo_redo->create_action(TTR("Anim Duplicate Keys"));
- List<Pair<int, float>> new_selection_values;
+ List<Pair<int, real_t>> new_selection_values;
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
- float t = animation->track_get_key_time(E->get().first, E->get().second);
- float dst_time = t + (timeline->get_play_position() - top_time);
+ real_t t = animation->track_get_key_time(E->get().first, E->get().second);
+ real_t dst_time = t + (timeline->get_play_position() - top_time);
int existing_idx = animation->track_find_key(E->get().first, dst_time, true);
undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->get().first, dst_time, animation->track_get_key_value(E->get().first, E->get().second), animation->track_get_key_transition(E->get().first, E->get().second));
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, dst_time);
- Pair<int, float> p;
+ Pair<int, real_t> p;
p.first = E->get().first;
p.second = dst_time;
new_selection_values.push_back(p);
@@ -1558,9 +1611,9 @@ void AnimationBezierTrackEdit::duplicate_selection() {
//reselect duplicated
selection.clear();
- for (const Pair<int, float> &E : new_selection_values) {
+ for (const Pair<int, real_t> &E : new_selection_values) {
int track = E.first;
- float time = E.second;
+ real_t time = E.second;
int existing_idx = animation->track_find_key(track, time, true);
@@ -1590,18 +1643,24 @@ void AnimationBezierTrackEdit::delete_selection() {
}
}
+void AnimationBezierTrackEdit::_bezier_track_insert_key(int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode) {
+ ERR_FAIL_COND(animation.is_null());
+ int idx = animation->bezier_track_insert_key(p_track, p_time, p_value, p_in_handle, p_out_handle);
+ animation->bezier_track_set_key_handle_mode(p_track, idx, p_handle_mode);
+}
+
void AnimationBezierTrackEdit::_bind_methods() {
- ClassDB::bind_method("_clear_selection", &AnimationBezierTrackEdit::_clear_selection);
- ClassDB::bind_method("_clear_selection_for_anim", &AnimationBezierTrackEdit::_clear_selection_for_anim);
- ClassDB::bind_method("_select_at_anim", &AnimationBezierTrackEdit::_select_at_anim);
- ClassDB::bind_method("_update_hidden_tracks_after", &AnimationBezierTrackEdit::_update_hidden_tracks_after);
- ClassDB::bind_method("_update_locked_tracks_after", &AnimationBezierTrackEdit::_update_locked_tracks_after);
+ ClassDB::bind_method(D_METHOD("_clear_selection"), &AnimationBezierTrackEdit::_clear_selection);
+ ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationBezierTrackEdit::_clear_selection_for_anim);
+ ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationBezierTrackEdit::_select_at_anim);
+ ClassDB::bind_method(D_METHOD("_update_hidden_tracks_after"), &AnimationBezierTrackEdit::_update_hidden_tracks_after);
+ ClassDB::bind_method(D_METHOD("_update_locked_tracks_after"), &AnimationBezierTrackEdit::_update_locked_tracks_after);
+ ClassDB::bind_method(D_METHOD("_bezier_track_insert_key"), &AnimationBezierTrackEdit::_bezier_track_insert_key);
ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::FLOAT, "position"), PropertyInfo(Variant::BOOL, "drag")));
ADD_SIGNAL(MethodInfo("remove_request", PropertyInfo(Variant::INT, "track")));
ADD_SIGNAL(MethodInfo("insert_key", PropertyInfo(Variant::FLOAT, "offset")));
- ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "track"), PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single")));
- ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "track"), PropertyInfo(Variant::INT, "index")));
+ ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single"), PropertyInfo(Variant::INT, "track")));
ADD_SIGNAL(MethodInfo("clear_selection"));
ADD_SIGNAL(MethodInfo("close_request"));
diff --git a/editor/animation_bezier_editor.h b/editor/animation_bezier_editor.h
index 070a6589ad..beb7a5e9c6 100644
--- a/editor/animation_bezier_editor.h
+++ b/editor/animation_bezier_editor.h
@@ -32,8 +32,9 @@
#define ANIMATION_BEZIER_EDITOR_H
#include "animation_track_editor.h"
-#include "core/templates/rb_set.h"
+#include "core/templates/hashfuncs.h"
+class EditorUndoRedoManager;
class ViewPanner;
class AnimationBezierTrackEdit : public Control {
@@ -44,14 +45,18 @@ class AnimationBezierTrackEdit : public Control {
MENU_KEY_DUPLICATE,
MENU_KEY_DELETE,
MENU_KEY_SET_HANDLE_FREE,
+ MENU_KEY_SET_HANDLE_LINEAR,
MENU_KEY_SET_HANDLE_BALANCED,
+ MENU_KEY_SET_HANDLE_MIRRORED,
+ MENU_KEY_SET_HANDLE_AUTO_BALANCED,
+ MENU_KEY_SET_HANDLE_AUTO_MIRRORED,
};
AnimationTimelineEdit *timeline = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Node *root = nullptr;
Control *play_position = nullptr; //separate control used to draw so updates for only position changed are much faster
- float play_position_pos = 0;
+ real_t play_position_pos = 0;
Ref<Animation> animation;
bool read_only = false;
@@ -111,25 +116,37 @@ class AnimationBezierTrackEdit : public Control {
Vector2 box_selection_from;
Vector2 box_selection_to;
- int moving_handle = 0; //0 no move -1 or +1 out
+ int moving_handle = 0; //0 no move -1 or +1 out, 2 both (drawing only)
int moving_handle_key = 0;
int moving_handle_track = 0;
Vector2 moving_handle_left;
Vector2 moving_handle_right;
int moving_handle_mode = 0; // value from Animation::HandleMode
+ struct PairHasher {
+ static _FORCE_INLINE_ uint32_t hash(const Pair<int, int> &p_value) {
+ int32_t hash = 23;
+ hash = hash * 31 * hash_one_uint64(p_value.first);
+ hash = hash * 31 * hash_one_uint64(p_value.second);
+ return hash;
+ }
+ };
+
+ HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_lefts;
+ HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_rights;
+
void _clear_selection();
void _clear_selection_for_anim(const Ref<Animation> &p_anim);
- void _select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos);
- void _change_selected_keys_handle_mode(Animation::HandleMode p_mode);
+ void _select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos);
+ void _change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto = false);
Vector2 menu_insert_key;
struct AnimMoveRestore {
int track = 0;
- float time = 0;
+ double time = 0;
Variant key;
- float transition = 0;
+ real_t transition = 0;
};
AnimationTrackEditor *editor = nullptr;
@@ -144,7 +161,7 @@ class AnimationBezierTrackEdit : public Control {
Vector<EditPoint> edit_points;
- struct SelectionCompare {
+ struct PairCompare {
bool operator()(const IntPair &lh, const IntPair &rh) {
if (lh.first == rh.first) {
return lh.second < rh.second;
@@ -154,7 +171,7 @@ class AnimationBezierTrackEdit : public Control {
}
};
- typedef RBSet<IntPair, SelectionCompare> SelectionSet;
+ typedef RBSet<IntPair, PairCompare> SelectionSet;
SelectionSet selection;
@@ -180,18 +197,20 @@ public:
void set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only);
virtual Size2 get_minimum_size() const override;
- void set_undo_redo(UndoRedo *p_undo_redo);
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void set_timeline(AnimationTimelineEdit *p_timeline);
void set_editor(AnimationTrackEditor *p_editor);
void set_root(Node *p_root);
void set_filtered(bool p_filtered);
- void set_play_position(float p_pos);
+ void set_play_position(real_t p_pos);
void update_play_position();
void duplicate_selection();
void delete_selection();
+ void _bezier_track_insert_key(int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode);
+
AnimationBezierTrackEdit();
};
diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp
index 0db82551cb..5df413f0a7 100644
--- a/editor/animation_track_editor.cpp
+++ b/editor/animation_track_editor.cpp
@@ -35,8 +35,10 @@
#include "editor/animation_bezier_editor.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/animation_player_editor_plugin.h"
#include "scene/animation/animation_player.h"
+#include "scene/animation/tween.h"
#include "scene/gui/separator.h"
#include "scene/gui/view_panner.h"
#include "scene/main/window.h"
@@ -58,17 +60,17 @@ public:
return true;
}
- bool _read_only() {
+ bool _is_read_only() {
return animation_read_only;
}
static void _bind_methods() {
- ClassDB::bind_method("_update_obj", &AnimationTrackKeyEdit::_update_obj);
- ClassDB::bind_method("_key_ofs_changed", &AnimationTrackKeyEdit::_key_ofs_changed);
- ClassDB::bind_method("_hide_script_from_inspector", &AnimationTrackKeyEdit::_hide_script_from_inspector);
- ClassDB::bind_method("get_root_path", &AnimationTrackKeyEdit::get_root_path);
- ClassDB::bind_method("_dont_undo_redo", &AnimationTrackKeyEdit::_dont_undo_redo);
- ClassDB::bind_method("_read_only", &AnimationTrackKeyEdit::_read_only);
+ ClassDB::bind_method(D_METHOD("_update_obj"), &AnimationTrackKeyEdit::_update_obj);
+ ClassDB::bind_method(D_METHOD("_key_ofs_changed"), &AnimationTrackKeyEdit::_key_ofs_changed);
+ ClassDB::bind_method(D_METHOD("_hide_script_from_inspector"), &AnimationTrackKeyEdit::_hide_script_from_inspector);
+ ClassDB::bind_method(D_METHOD("get_root_path"), &AnimationTrackKeyEdit::get_root_path);
+ ClassDB::bind_method(D_METHOD("_dont_undo_redo"), &AnimationTrackKeyEdit::_dont_undo_redo);
+ ClassDB::bind_method(D_METHOD("_is_read_only"), &AnimationTrackKeyEdit::_is_read_only);
}
void _fix_node_path(Variant &value) {
@@ -349,8 +351,8 @@ public:
setting = true;
undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS);
int prev = animation->bezier_track_get_key_handle_mode(track, key);
- undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_handle_mode", track, key, value);
- undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_handle_mode", track, key, prev);
+ undo_redo->add_do_method(this, "_bezier_track_set_key_handle_mode", animation.ptr(), track, key, value);
+ undo_redo->add_undo_method(this, "_bezier_track_set_key_handle_mode", animation.ptr(), track, key, prev);
undo_redo->add_do_method(this, "_update_obj", animation);
undo_redo->add_undo_method(this, "_update_obj", animation);
undo_redo->commit_action();
@@ -635,10 +637,16 @@ public:
} break;
case Animation::TYPE_BEZIER: {
+ Animation::HandleMode hm = animation->bezier_track_get_key_handle_mode(track, key);
p_list->push_back(PropertyInfo(Variant::FLOAT, PNAME("value")));
- p_list->push_back(PropertyInfo(Variant::VECTOR2, PNAME("in_handle")));
- p_list->push_back(PropertyInfo(Variant::VECTOR2, PNAME("out_handle")));
- p_list->push_back(PropertyInfo(Variant::INT, PNAME("handle_mode"), PROPERTY_HINT_ENUM, "Free,Balanced"));
+ if (hm == Animation::HANDLE_MODE_LINEAR) {
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, PNAME("in_handle"), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, PNAME("out_handle"), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY));
+ } else {
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, PNAME("in_handle")));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, PNAME("out_handle")));
+ }
+ p_list->push_back(PropertyInfo(Variant::INT, PNAME("handle_mode"), PROPERTY_HINT_ENUM, "Free,Linear,Balanced,Mirrored"));
} break;
case Animation::TYPE_AUDIO: {
@@ -680,7 +688,7 @@ public:
}
}
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Ref<Animation> animation;
int track = -1;
float key_ofs = 0;
@@ -719,17 +727,17 @@ public:
return true;
}
- bool _read_only() {
+ bool _is_read_only() {
return animation_read_only;
}
static void _bind_methods() {
- ClassDB::bind_method("_update_obj", &AnimationMultiTrackKeyEdit::_update_obj);
- ClassDB::bind_method("_key_ofs_changed", &AnimationMultiTrackKeyEdit::_key_ofs_changed);
- ClassDB::bind_method("_hide_script_from_inspector", &AnimationMultiTrackKeyEdit::_hide_script_from_inspector);
- ClassDB::bind_method("get_root_path", &AnimationMultiTrackKeyEdit::get_root_path);
- ClassDB::bind_method("_dont_undo_redo", &AnimationMultiTrackKeyEdit::_dont_undo_redo);
- ClassDB::bind_method("_read_only", &AnimationMultiTrackKeyEdit::_read_only);
+ ClassDB::bind_method(D_METHOD("_update_obj"), &AnimationMultiTrackKeyEdit::_update_obj);
+ ClassDB::bind_method(D_METHOD("_key_ofs_changed"), &AnimationMultiTrackKeyEdit::_key_ofs_changed);
+ ClassDB::bind_method(D_METHOD("_hide_script_from_inspector"), &AnimationMultiTrackKeyEdit::_hide_script_from_inspector);
+ ClassDB::bind_method(D_METHOD("get_root_path"), &AnimationMultiTrackKeyEdit::get_root_path);
+ ClassDB::bind_method(D_METHOD("_dont_undo_redo"), &AnimationMultiTrackKeyEdit::_dont_undo_redo);
+ ClassDB::bind_method(D_METHOD("_is_read_only"), &AnimationMultiTrackKeyEdit::_is_read_only);
}
void _fix_node_path(Variant &value, NodePath &base) {
@@ -970,8 +978,8 @@ public:
undo_redo->create_action(TTR("Anim Multi Change Keyframe Value"), UndoRedo::MERGE_ENDS);
}
Vector2 prev = animation->bezier_track_get_key_in_handle(track, key);
- undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_in_handle", track, key, value);
- undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", track, key, prev);
+ undo_redo->add_do_method(this, "_bezier_track_set_key_in_handle", track, key, value);
+ undo_redo->add_undo_method(this, "_bezier_track_set_key_in_handle", track, key, prev);
update_obj = true;
} else if (name == "out_handle") {
const Variant &value = p_value;
@@ -981,8 +989,8 @@ public:
undo_redo->create_action(TTR("Anim Multi Change Keyframe Value"), UndoRedo::MERGE_ENDS);
}
Vector2 prev = animation->bezier_track_get_key_out_handle(track, key);
- undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_out_handle", track, key, value);
- undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", track, key, prev);
+ undo_redo->add_do_method(this, "_bezier_track_set_key_out_handle", track, key, value);
+ undo_redo->add_undo_method(this, "_bezier_track_set_key_out_handle", track, key, prev);
update_obj = true;
} else if (name == "handle_mode") {
const Variant &value = p_value;
@@ -992,8 +1000,8 @@ public:
undo_redo->create_action(TTR("Anim Multi Change Keyframe Value"), UndoRedo::MERGE_ENDS);
}
int prev = animation->bezier_track_get_key_handle_mode(track, key);
- undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_handle_mode", track, key, value);
- undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_handle_mode", track, key, prev);
+ undo_redo->add_do_method(this, "_bezier_track_set_key_handle_mode", animation.ptr(), track, key, value);
+ undo_redo->add_undo_method(this, "_bezier_track_set_key_handle_mode", animation.ptr(), track, key, prev);
update_obj = true;
}
} break;
@@ -1324,7 +1332,7 @@ public:
p_list->push_back(PropertyInfo(Variant::FLOAT, "value"));
p_list->push_back(PropertyInfo(Variant::VECTOR2, "in_handle"));
p_list->push_back(PropertyInfo(Variant::VECTOR2, "out_handle"));
- p_list->push_back(PropertyInfo(Variant::INT, "handle_mode", PROPERTY_HINT_ENUM, "Free,Balanced"));
+ p_list->push_back(PropertyInfo(Variant::INT, "handle_mode", PROPERTY_HINT_ENUM, "Free,Linear,Balanced,Mirrored"));
} break;
case Animation::TYPE_AUDIO: {
p_list->push_back(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"));
@@ -1374,7 +1382,7 @@ public:
bool use_fps = false;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void notify_change() {
notify_property_list_changed();
@@ -1708,7 +1716,7 @@ Size2 AnimationTimelineEdit::get_minimum_size() const {
return ms;
}
-void AnimationTimelineEdit::set_undo_redo(UndoRedo *p_undo_redo) {
+void AnimationTimelineEdit::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
undo_redo = p_undo_redo;
}
@@ -2114,11 +2122,11 @@ void AnimationTrackEdit::_notification(int p_what) {
get_theme_icon(SNAME("InterpWrapClamp"), SNAME("EditorIcons")),
get_theme_icon(SNAME("InterpWrapLoop"), SNAME("EditorIcons")),
};
-
- Ref<Texture2D> interp_icon[3] = {
+ Ref<Texture2D> interp_icon[4] = {
get_theme_icon(SNAME("InterpRaw"), SNAME("EditorIcons")),
get_theme_icon(SNAME("InterpLinear"), SNAME("EditorIcons")),
- get_theme_icon(SNAME("InterpCubic"), SNAME("EditorIcons"))
+ get_theme_icon(SNAME("InterpCubic"), SNAME("EditorIcons")),
+ get_theme_icon(SNAME("InterpCubicInTime"), SNAME("EditorIcons"))
};
Ref<Texture2D> cont_icon[4] = {
get_theme_icon(SNAME("TrackContinuous"), SNAME("EditorIcons")),
@@ -2507,10 +2515,14 @@ Size2 AnimationTrackEdit::get_minimum_size() const {
return Vector2(1, max_h + separation);
}
-void AnimationTrackEdit::set_undo_redo(UndoRedo *p_undo_redo) {
+void AnimationTrackEdit::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
undo_redo = p_undo_redo;
}
+Ref<EditorUndoRedoManager> AnimationTrackEdit::get_undo_redo() const {
+ return undo_redo;
+}
+
void AnimationTrackEdit::set_timeline(AnimationTimelineEdit *p_timeline) {
timeline = p_timeline;
timeline->set_track_edit(this);
@@ -2720,9 +2732,15 @@ String AnimationTrackEdit::get_tooltip(const Point2 &p_pos) const {
case Animation::HANDLE_MODE_FREE: {
text += TTR("Handle mode: Free\n");
} break;
+ case Animation::HANDLE_MODE_LINEAR: {
+ text += TTR("Handle mode: Linear\n");
+ } break;
case Animation::HANDLE_MODE_BALANCED: {
text += TTR("Handle mode: Balanced\n");
} break;
+ case Animation::HANDLE_MODE_MIRRORED: {
+ text += TTR("Handle mode: Mirrored\n");
+ } break;
}
} break;
case Animation::TYPE_AUDIO: {
@@ -2831,6 +2849,7 @@ void AnimationTrackEdit::gui_input(const Ref<InputEvent> &p_event) {
menu->add_icon_item(get_theme_icon(SNAME("InterpRaw"), SNAME("EditorIcons")), TTR("Nearest"), MENU_INTERPOLATION_NEAREST);
menu->add_icon_item(get_theme_icon(SNAME("InterpLinear"), SNAME("EditorIcons")), TTR("Linear"), MENU_INTERPOLATION_LINEAR);
menu->add_icon_item(get_theme_icon(SNAME("InterpCubic"), SNAME("EditorIcons")), TTR("Cubic"), MENU_INTERPOLATION_CUBIC);
+ menu->add_icon_item(get_theme_icon(SNAME("InterpCubicInTime"), SNAME("EditorIcons")), TTR("CubicInTime"), MENU_INTERPOLATION_CUBIC_IN_TIME);
menu->reset_size();
Vector2 popup_pos = get_screen_position() + interp_mode_rect.position + Vector2(0, interp_mode_rect.size.height);
@@ -3171,7 +3190,8 @@ void AnimationTrackEdit::_menu_selected(int p_index) {
} break;
case MENU_INTERPOLATION_NEAREST:
case MENU_INTERPOLATION_LINEAR:
- case MENU_INTERPOLATION_CUBIC: {
+ case MENU_INTERPOLATION_CUBIC:
+ case MENU_INTERPOLATION_CUBIC_IN_TIME: {
Animation::InterpolationType interp_mode = Animation::InterpolationType(p_index - MENU_INTERPOLATION_NEAREST);
undo_redo->create_action(TTR("Change Animation Interpolation Mode"));
undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_type", track, interp_mode);
@@ -3251,7 +3271,6 @@ void AnimationTrackEdit::_bind_methods() {
ADD_SIGNAL(MethodInfo("insert_key", PropertyInfo(Variant::FLOAT, "offset")));
ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single")));
ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "index")));
- ADD_SIGNAL(MethodInfo("bezier_edit"));
ADD_SIGNAL(MethodInfo("move_selection_begin"));
ADD_SIGNAL(MethodInfo("move_selection", PropertyInfo(Variant::FLOAT, "offset")));
@@ -3414,7 +3433,8 @@ void AnimationTrackEditor::set_animation(const Ref<Animation> &p_anim, bool p_re
track_edits[_get_track_selected()]->release_focus();
}
if (animation.is_valid()) {
- animation->disconnect("changed", callable_mp(this, &AnimationTrackEditor::_animation_changed));
+ animation->disconnect("tracks_changed", callable_mp(this, &AnimationTrackEditor::_animation_changed));
+ animation->disconnect("changed", callable_mp(this, &AnimationTrackEditor::_sync_animation_change));
_clear_selection();
}
animation = p_anim;
@@ -3425,7 +3445,8 @@ void AnimationTrackEditor::set_animation(const Ref<Animation> &p_anim, bool p_re
_update_tracks();
if (animation.is_valid()) {
- animation->connect("changed", callable_mp(this, &AnimationTrackEditor::_animation_changed));
+ animation->connect("tracks_changed", callable_mp(this, &AnimationTrackEditor::_animation_changed), CONNECT_DEFERRED);
+ animation->connect("changed", callable_mp(this, &AnimationTrackEditor::_sync_animation_change), CONNECT_DEFERRED);
hscroll->show();
edit->set_disabled(read_only);
@@ -4340,13 +4361,12 @@ AnimationTrackEditor::TrackIndices AnimationTrackEditor::_confirm_insert(InsertD
} break;
case Animation::TYPE_BEZIER: {
Array array;
- array.resize(6);
+ array.resize(5);
array[0] = p_id.value;
array[1] = -0.25;
array[2] = 0;
array[3] = 0.25;
array[4] = 0;
- array[5] = Animation::HANDLE_MODE_BALANCED;
value = array;
bezier_edit_icon->set_disabled(false);
@@ -4609,11 +4629,19 @@ void AnimationTrackEditor::_update_tracks() {
}
}
+void AnimationTrackEditor::_sync_animation_change() {
+ bezier_edit->update();
+}
+
void AnimationTrackEditor::_animation_changed() {
if (animation_changing_awaiting_update) {
return; // All will be updated, don't bother with anything.
}
+ if (key_edit) {
+ _update_key_edit();
+ }
+
if (key_edit && key_edit->setting) {
// If editing a key, just update the edited track, makes refresh less costly.
if (key_edit->track < track_edits.size()) {
@@ -5073,13 +5101,12 @@ void AnimationTrackEditor::_insert_key_from_track(float p_ofs, int p_track) {
Variant value;
_find_hint_for_track(p_track, bp, &value);
Array arr;
- arr.resize(6);
+ arr.resize(5);
arr[0] = value;
arr[1] = -0.25;
arr[2] = 0;
arr[3] = 0.25;
arr[4] = 0;
- arr[5] = 0;
undo_redo->create_action(TTR("Add Track Key"));
undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_track, p_ofs, arr);
@@ -5558,6 +5585,13 @@ void AnimationTrackEditor::_bezier_edit(int p_for_track) {
// Search everything within the track and curve - edit it.
}
+void AnimationTrackEditor::_bezier_track_set_key_handle_mode(Animation *p_anim, int p_track, int p_index, Animation::HandleMode p_mode, Animation::HandleSetMode p_set_mode) {
+ if (!p_anim) {
+ return;
+ }
+ p_anim->bezier_track_set_key_handle_mode(p_track, p_index, p_mode, p_set_mode);
+}
+
void AnimationTrackEditor::_anim_duplicate_keys(bool transpose) {
// Duplicait!
if (selection.size() && animation.is_valid() && (!transpose || (_get_track_selected() >= 0 && _get_track_selected() < animation->get_track_count()))) {
@@ -5963,6 +5997,89 @@ void AnimationTrackEditor::_edit_menu_pressed(int p_option) {
#undef NEW_POS
undo_redo->commit_action();
} break;
+
+ case EDIT_EASE_SELECTION: {
+ ease_dialog->popup_centered(Size2(200, 100) * EDSCALE);
+ } break;
+ case EDIT_EASE_CONFIRM: {
+ undo_redo->create_action(TTR("Make Easing Keys"));
+
+ Tween::TransitionType transition_type = static_cast<Tween::TransitionType>(transition_selection->get_selected_id());
+ Tween::EaseType ease_type = static_cast<Tween::EaseType>(ease_selection->get_selected_id());
+ float fps = ease_fps->get_value();
+ double dur_step = 1.0 / fps;
+
+ // Organize track and key.
+ HashMap<int, Vector<int>> keymap;
+ Vector<int> tracks;
+ for (const KeyValue<SelectedKey, KeyInfo> &E : selection) {
+ if (!tracks.has(E.key.track)) {
+ tracks.append(E.key.track);
+ }
+ }
+ for (int i = 0; i < tracks.size(); i++) {
+ switch (animation->track_get_type(tracks[i])) {
+ case Animation::TYPE_VALUE:
+ case Animation::TYPE_POSITION_3D:
+ case Animation::TYPE_ROTATION_3D:
+ case Animation::TYPE_SCALE_3D:
+ case Animation::TYPE_BLEND_SHAPE: {
+ Vector<int> keys;
+ for (const KeyValue<SelectedKey, KeyInfo> &E : selection) {
+ if (E.key.track == tracks[i]) {
+ keys.append(E.key.key);
+ }
+ }
+ keys.sort();
+ keymap.insert(tracks[i], keys);
+ } break;
+ default: {
+ } break;
+ }
+ }
+
+ // Make easing.
+ HashMap<int, Vector<int>>::Iterator E = keymap.begin();
+ while (E) {
+ int track = E->key;
+ Vector<int> keys = E->value;
+ int len = keys.size() - 1;
+
+ // Make insert queue.
+ Vector<Pair<double, Variant>> insert_queue;
+ for (int i = 0; i < len; i++) {
+ // Check neighboring keys.
+ if (keys[i] + 1 == keys[i + 1]) {
+ double from_t = animation->track_get_key_time(track, keys[i]);
+ double to_t = animation->track_get_key_time(track, keys[i + 1]);
+ Variant from_v = animation->track_get_key_value(track, keys[i]);
+ Variant to_v = animation->track_get_key_value(track, keys[i + 1]);
+ Variant delta_v;
+ Variant::sub(to_v, from_v, delta_v);
+ double duration = to_t - from_t;
+ double fixed_duration = duration - 0.01; // Prevent to overwrap keys...
+ for (double delta_t = dur_step; delta_t < fixed_duration; delta_t += dur_step) {
+ Pair<double, Variant> keydata;
+ keydata.first = from_t + delta_t;
+ keydata.second = Tween::interpolate_variant(from_v, delta_v, delta_t, duration, transition_type, ease_type);
+ insert_queue.append(keydata);
+ }
+ }
+ }
+
+ // Do insertion.
+ for (int i = 0; i < insert_queue.size(); i++) {
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, insert_queue[i].first, insert_queue[i].second);
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", track, insert_queue[i].first);
+ }
+
+ ++E;
+ }
+
+ undo_redo->commit_action();
+
+ } break;
+
case EDIT_DUPLICATE_SELECTION: {
if (bezier_edit->is_visible()) {
bezier_edit->duplicate_selection();
@@ -6054,16 +6171,123 @@ void AnimationTrackEditor::_edit_menu_pressed(int p_option) {
} break;
case EDIT_APPLY_RESET: {
AnimationPlayerEditor::get_singleton()->get_player()->apply_reset(true);
+ } break;
+
+ case EDIT_BAKE_ANIMATION: {
+ bake_dialog->popup_centered(Size2(200, 100) * EDSCALE);
+ } break;
+ case EDIT_BAKE_ANIMATION_CONFIRM: {
+ undo_redo->create_action(TTR("Bake Animation as Linear keys."));
+
+ int track_len = animation->get_track_count();
+ bool b_trs = bake_trs->is_pressed();
+ bool b_bs = bake_blendshape->is_pressed();
+ bool b_v = bake_value->is_pressed();
+
+ double anim_len = animation->get_length() + CMP_EPSILON; // For end key.
+ float fps = bake_fps->get_value();
+ double dur_step = 1.0 / fps;
+
+ for (int i = 0; i < track_len; i++) {
+ bool do_bake = false;
+ Animation::TrackType type = animation->track_get_type(i);
+ do_bake |= b_trs && (type == Animation::TYPE_POSITION_3D || type == Animation::TYPE_ROTATION_3D || type == Animation::TYPE_SCALE_3D);
+ do_bake |= b_bs && type == Animation::TYPE_BLEND_SHAPE;
+ do_bake |= b_v && type == Animation::TYPE_VALUE;
+ if (do_bake && !animation->track_is_compressed(i)) {
+ if (animation->track_get_interpolation_type(i) == Animation::INTERPOLATION_NEAREST) {
+ continue; // Nearest interpolation cannot be baked.
+ }
+
+ // Make insert queue.
+ Vector<Pair<double, Variant>> insert_queue;
+
+ switch (type) {
+ case Animation::TYPE_POSITION_3D: {
+ for (double delta_t = 0.0; delta_t <= anim_len; delta_t += dur_step) {
+ Pair<double, Variant> keydata;
+ keydata.first = delta_t;
+ Vector3 v;
+ animation->position_track_interpolate(i, delta_t, &v);
+ keydata.second = v;
+ insert_queue.append(keydata);
+ }
+ } break;
+ case Animation::TYPE_ROTATION_3D: {
+ for (double delta_t = 0.0; delta_t <= anim_len; delta_t += dur_step) {
+ Pair<double, Variant> keydata;
+ keydata.first = delta_t;
+ Quaternion v;
+ animation->rotation_track_interpolate(i, delta_t, &v);
+ keydata.second = v;
+ insert_queue.append(keydata);
+ }
+ } break;
+ case Animation::TYPE_SCALE_3D: {
+ for (double delta_t = 0.0; delta_t <= anim_len; delta_t += dur_step) {
+ Pair<double, Variant> keydata;
+ keydata.first = delta_t;
+ Vector3 v;
+ animation->scale_track_interpolate(i, delta_t, &v);
+ keydata.second = v;
+ insert_queue.append(keydata);
+ }
+ } break;
+ case Animation::TYPE_BLEND_SHAPE: {
+ for (double delta_t = 0.0; delta_t <= anim_len; delta_t += dur_step) {
+ Pair<double, Variant> keydata;
+ keydata.first = delta_t;
+ float v;
+ animation->blend_shape_track_interpolate(i, delta_t, &v);
+ keydata.second = v;
+ insert_queue.append(keydata);
+ }
+ } break;
+ case Animation::TYPE_VALUE: {
+ for (double delta_t = 0.0; delta_t < anim_len; delta_t += dur_step) {
+ Pair<double, Variant> keydata;
+ keydata.first = delta_t;
+ keydata.second = animation->value_track_interpolate(i, delta_t);
+ insert_queue.append(keydata);
+ }
+ } break;
+ default: {
+ } break;
+ }
+
+ // Cleanup keys.
+ int key_len = animation->track_get_key_count(i);
+ for (int j = key_len - 1; j >= 0; j--) {
+ undo_redo->add_do_method(animation.ptr(), "track_remove_key", i, j);
+ }
+
+ // Insert keys.
+ undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_type", i, Animation::INTERPOLATION_LINEAR);
+ for (int j = insert_queue.size() - 1; j >= 0; j--) {
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", i, insert_queue[j].first, insert_queue[j].second);
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key", i, j);
+ }
+
+ // Undo methods.
+ undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", i, animation->track_get_interpolation_type(i));
+ for (int j = key_len - 1; j >= 0; j--) {
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", i, animation->track_get_key_time(i, j), animation->track_get_key_value(i, j), animation->track_get_key_transition(i, j));
+ }
+ }
+ }
+
+ undo_redo->commit_action();
} break;
+
case EDIT_OPTIMIZE_ANIMATION: {
optimize_dialog->popup_centered(Size2(250, 180) * EDSCALE);
} break;
case EDIT_OPTIMIZE_ANIMATION_CONFIRM: {
- animation->optimize(optimize_linear_error->get_value(), optimize_angular_error->get_value(), optimize_max_angle->get_value());
+ animation->optimize(optimize_velocity_error->get_value(), optimize_angular_error->get_value(), optimize_precision_error->get_value());
_update_tracks();
- undo_redo->clear_history();
+ undo_redo->clear_history(true, undo_redo->get_history_for_object(animation.ptr()).id);
} break;
case EDIT_CLEAN_UP_ANIMATION: {
@@ -6131,7 +6355,7 @@ void AnimationTrackEditor::_cleanup_animation(Ref<Animation> p_animation) {
}
}
- undo_redo->clear_history();
+ undo_redo->clear_history(true, undo_redo->get_history_for_object(animation.ptr()).id);
_update_tracks();
}
@@ -6218,15 +6442,17 @@ void AnimationTrackEditor::_select_all_tracks_for_copy() {
}
void AnimationTrackEditor::_bind_methods() {
- ClassDB::bind_method("_animation_update", &AnimationTrackEditor::_animation_update);
- ClassDB::bind_method("_track_grab_focus", &AnimationTrackEditor::_track_grab_focus);
- ClassDB::bind_method("_update_tracks", &AnimationTrackEditor::_update_tracks);
- ClassDB::bind_method("_clear_selection_for_anim", &AnimationTrackEditor::_clear_selection_for_anim);
- ClassDB::bind_method("_select_at_anim", &AnimationTrackEditor::_select_at_anim);
+ ClassDB::bind_method(D_METHOD("_animation_update"), &AnimationTrackEditor::_animation_update);
+ ClassDB::bind_method(D_METHOD("_track_grab_focus"), &AnimationTrackEditor::_track_grab_focus);
+ ClassDB::bind_method(D_METHOD("_update_tracks"), &AnimationTrackEditor::_update_tracks);
+ ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationTrackEditor::_clear_selection_for_anim);
+ ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationTrackEditor::_select_at_anim);
+
+ ClassDB::bind_method(D_METHOD("_key_selected"), &AnimationTrackEditor::_key_selected); // Still used by some connect_compat.
+ ClassDB::bind_method(D_METHOD("_key_deselected"), &AnimationTrackEditor::_key_deselected); // Still used by some connect_compat.
+ ClassDB::bind_method(D_METHOD("_clear_selection"), &AnimationTrackEditor::_clear_selection); // Still used by some connect_compat.
- ClassDB::bind_method("_key_selected", &AnimationTrackEditor::_key_selected); // Still used by some connect_compat.
- ClassDB::bind_method("_key_deselected", &AnimationTrackEditor::_key_deselected); // Still used by some connect_compat.
- ClassDB::bind_method("_clear_selection", &AnimationTrackEditor::_clear_selection); // Still used by some connect_compat.
+ ClassDB::bind_method(D_METHOD("_bezier_track_set_key_handle_mode", "animation", "track_idx", "key_idx", "key_handle_mode", "key_handle_set_mode"), &AnimationTrackEditor::_bezier_track_set_key_handle_mode, DEFVAL(Animation::HANDLE_SET_MODE_NONE));
ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::FLOAT, "position"), PropertyInfo(Variant::BOOL, "drag"), PropertyInfo(Variant::BOOL, "timeline_only")));
ADD_SIGNAL(MethodInfo("keying_changed"));
@@ -6301,7 +6527,7 @@ void AnimationTrackEditor::_pick_track_filter_input(const Ref<InputEvent> &p_ie)
}
AnimationTrackEditor::AnimationTrackEditor() {
- undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ undo_redo = EditorNode::get_undo_redo();
main_panel = memnew(PanelContainer);
main_panel->set_focus_mode(FOCUS_ALL); // Allow panel to have focus so that shortcuts work as expected.
@@ -6463,6 +6689,8 @@ AnimationTrackEditor::AnimationTrackEditor() {
edit->get_popup()->add_item(TTR("Scale Selection"), EDIT_SCALE_SELECTION);
edit->get_popup()->add_item(TTR("Scale From Cursor"), EDIT_SCALE_FROM_CURSOR);
edit->get_popup()->add_separator();
+ edit->get_popup()->add_item(TTR("Make Easing Selection"), EDIT_EASE_SELECTION);
+ edit->get_popup()->add_separator();
edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/duplicate_selection", TTR("Duplicate Selection"), KeyModifierMask::CMD | Key::D), EDIT_DUPLICATE_SELECTION);
edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/duplicate_selection_transposed", TTR("Duplicate Transposed"), KeyModifierMask::SHIFT | KeyModifierMask::CMD | Key::D), EDIT_DUPLICATE_TRANSPOSED);
edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/add_reset_value", TTR("Add RESET Value(s)")));
@@ -6475,6 +6703,7 @@ AnimationTrackEditor::AnimationTrackEditor() {
edit->get_popup()->add_separator();
edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/apply_reset", TTR("Apply Reset")), EDIT_APPLY_RESET);
edit->get_popup()->add_separator();
+ edit->get_popup()->add_item(TTR("Bake Animation"), EDIT_BAKE_ANIMATION);
edit->get_popup()->add_item(TTR("Optimize Animation"), EDIT_OPTIMIZE_ANIMATION);
edit->get_popup()->add_item(TTR("Clean-Up Animation"), EDIT_CLEAN_UP_ANIMATION);
@@ -6536,25 +6765,24 @@ AnimationTrackEditor::AnimationTrackEditor() {
VBoxContainer *optimize_vb = memnew(VBoxContainer);
optimize_dialog->add_child(optimize_vb);
- optimize_linear_error = memnew(SpinBox);
- optimize_linear_error->set_max(1.0);
- optimize_linear_error->set_min(0.001);
- optimize_linear_error->set_step(0.001);
- optimize_linear_error->set_value(0.05);
- optimize_vb->add_margin_child(TTR("Max. Linear Error:"), optimize_linear_error);
+ optimize_velocity_error = memnew(SpinBox);
+ optimize_velocity_error->set_max(1.0);
+ optimize_velocity_error->set_min(0.001);
+ optimize_velocity_error->set_step(0.001);
+ optimize_velocity_error->set_value(0.01);
+ optimize_vb->add_margin_child(TTR("Max. Velocity Error:"), optimize_velocity_error);
optimize_angular_error = memnew(SpinBox);
optimize_angular_error->set_max(1.0);
optimize_angular_error->set_min(0.001);
optimize_angular_error->set_step(0.001);
optimize_angular_error->set_value(0.01);
-
optimize_vb->add_margin_child(TTR("Max. Angular Error:"), optimize_angular_error);
- optimize_max_angle = memnew(SpinBox);
- optimize_vb->add_margin_child(TTR("Max Optimizable Angle:"), optimize_max_angle);
- optimize_max_angle->set_max(360.0);
- optimize_max_angle->set_min(0.0);
- optimize_max_angle->set_step(0.1);
- optimize_max_angle->set_value(22);
+ optimize_precision_error = memnew(SpinBox);
+ optimize_precision_error->set_max(6);
+ optimize_precision_error->set_min(1);
+ optimize_precision_error->set_step(1);
+ optimize_precision_error->set_value(3);
+ optimize_vb->add_margin_child(TTR("Max. Precision Error:"), optimize_precision_error);
optimize_dialog->set_ok_button_text(TTR("Optimize"));
optimize_dialog->connect("confirmed", callable_mp(this, &AnimationTrackEditor::_edit_menu_pressed).bind(EDIT_OPTIMIZE_ANIMATION_CONFIRM));
@@ -6598,6 +6826,88 @@ AnimationTrackEditor::AnimationTrackEditor() {
scale_dialog->connect("confirmed", callable_mp(this, &AnimationTrackEditor::_edit_menu_pressed).bind(EDIT_SCALE_CONFIRM));
add_child(scale_dialog);
+ //
+ ease_dialog = memnew(ConfirmationDialog);
+ ease_dialog->set_title(TTR("Select Transition and Easing"));
+ ease_dialog->connect("confirmed", callable_mp(this, &AnimationTrackEditor::_edit_menu_pressed).bind(EDIT_EASE_CONFIRM));
+ add_child(ease_dialog);
+ GridContainer *ease_grid = memnew(GridContainer);
+ ease_grid->set_columns(2);
+ ease_dialog->add_child(ease_grid);
+ transition_selection = memnew(OptionButton);
+ transition_selection->add_item("Linear", Tween::TRANS_LINEAR);
+ transition_selection->add_item("Sine", Tween::TRANS_SINE);
+ transition_selection->add_item("Quint", Tween::TRANS_QUINT);
+ transition_selection->add_item("Quart", Tween::TRANS_QUART);
+ transition_selection->add_item("Quad", Tween::TRANS_QUAD);
+ transition_selection->add_item("Expo", Tween::TRANS_EXPO);
+ transition_selection->add_item("Elastic", Tween::TRANS_ELASTIC);
+ transition_selection->add_item("Cubic", Tween::TRANS_CUBIC);
+ transition_selection->add_item("Circ", Tween::TRANS_CIRC);
+ transition_selection->add_item("Bounce", Tween::TRANS_BOUNCE);
+ transition_selection->add_item("Back", Tween::TRANS_BACK);
+ transition_selection->select(Tween::TRANS_LINEAR); // Default
+ ease_selection = memnew(OptionButton);
+ ease_selection->add_item("In", Tween::EASE_IN);
+ ease_selection->add_item("Out", Tween::EASE_OUT);
+ ease_selection->add_item("InOut", Tween::EASE_IN_OUT);
+ ease_selection->add_item("OutIn", Tween::EASE_OUT_IN);
+ ease_selection->select(Tween::EASE_IN_OUT); // Default
+ ease_fps = memnew(SpinBox);
+ ease_fps->set_min(1);
+ ease_fps->set_max(999);
+ ease_fps->set_step(1);
+ ease_fps->set_value(30); // Default
+ Label *ease_label1 = memnew(Label);
+ Label *ease_label2 = memnew(Label);
+ Label *ease_label3 = memnew(Label);
+ ease_label1->set_text("Transition Type:");
+ ease_label2->set_text("Ease Type:");
+ ease_label3->set_text("FPS:");
+ ease_grid->add_child(ease_label1);
+ ease_grid->add_child(transition_selection);
+ ease_grid->add_child(ease_label2);
+ ease_grid->add_child(ease_selection);
+ ease_grid->add_child(ease_label3);
+ ease_grid->add_child(ease_fps);
+
+ //
+ bake_dialog = memnew(ConfirmationDialog);
+ bake_dialog->set_title(TTR("Anim. Baker"));
+ bake_dialog->connect("confirmed", callable_mp(this, &AnimationTrackEditor::_edit_menu_pressed).bind(EDIT_BAKE_ANIMATION_CONFIRM));
+ add_child(bake_dialog);
+ GridContainer *bake_grid = memnew(GridContainer);
+ bake_grid->set_columns(2);
+ bake_dialog->add_child(bake_grid);
+ bake_trs = memnew(CheckBox);
+ bake_trs->set_pressed(true);
+ bake_blendshape = memnew(CheckBox);
+ bake_blendshape->set_pressed(true);
+ bake_value = memnew(CheckBox);
+ bake_value->set_pressed(true);
+ bake_fps = memnew(SpinBox);
+ bake_fps->set_min(1);
+ bake_fps->set_max(999);
+ bake_fps->set_step(1);
+ bake_fps->set_value(30); // Default
+ Label *bake_label1 = memnew(Label);
+ Label *bake_label2 = memnew(Label);
+ Label *bake_label3 = memnew(Label);
+ Label *bake_label4 = memnew(Label);
+ bake_label1->set_text("Pos/Rot/Scl3D Track:");
+ bake_label2->set_text("Blendshape Track:");
+ bake_label3->set_text("Value Track:");
+ bake_label4->set_text("FPS:");
+ bake_grid->add_child(bake_label1);
+ bake_grid->add_child(bake_trs);
+ bake_grid->add_child(bake_label2);
+ bake_grid->add_child(bake_blendshape);
+ bake_grid->add_child(bake_label3);
+ bake_grid->add_child(bake_value);
+ bake_grid->add_child(bake_label4);
+ bake_grid->add_child(bake_fps);
+
+ //
track_copy_dialog = memnew(ConfirmationDialog);
add_child(track_copy_dialog);
track_copy_dialog->set_title(TTR("Select Tracks to Copy"));
diff --git a/editor/animation_track_editor.h b/editor/animation_track_editor.h
index b0553c54a5..9cf3269fd0 100644
--- a/editor/animation_track_editor.h
+++ b/editor/animation_track_editor.h
@@ -32,6 +32,7 @@
#define ANIMATION_TRACK_EDITOR_H
#include "editor/editor_data.h"
+#include "editor/editor_properties.h"
#include "editor/editor_spin_slider.h"
#include "editor/property_selector.h"
@@ -78,7 +79,7 @@ class AnimationTimelineEdit : public Range {
void _anim_loop_pressed();
void _play_position_draw();
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Rect2 hsize_rect;
bool editing = false;
@@ -112,7 +113,7 @@ public:
void set_track_edit(AnimationTrackEdit *p_track_edit);
void set_zoom(Range *p_zoom);
Range *get_zoom() const { return zoom; }
- void set_undo_redo(UndoRedo *p_undo_redo);
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void set_play_position(float p_pos);
float get_play_position() const;
@@ -143,6 +144,7 @@ class AnimationTrackEdit : public Control {
MENU_INTERPOLATION_NEAREST,
MENU_INTERPOLATION_LINEAR,
MENU_INTERPOLATION_CUBIC,
+ MENU_INTERPOLATION_CUBIC_IN_TIME,
MENU_LOOP_WRAP,
MENU_LOOP_CLAMP,
MENU_KEY_INSERT,
@@ -152,7 +154,7 @@ class AnimationTrackEdit : public Control {
};
AnimationTimelineEdit *timeline = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Popup *path_popup = nullptr;
LineEdit *path = nullptr;
Node *root = nullptr;
@@ -233,12 +235,12 @@ public:
Ref<Animation> get_animation() const;
AnimationTimelineEdit *get_timeline() const { return timeline; }
AnimationTrackEditor *get_editor() const { return editor; }
- UndoRedo *get_undo_redo() const { return undo_redo; }
+ Ref<EditorUndoRedoManager> get_undo_redo() const;
NodePath get_path() const;
void set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only);
virtual Size2 get_minimum_size() const override;
- void set_undo_redo(UndoRedo *p_undo_redo);
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void set_timeline(AnimationTimelineEdit *p_timeline);
void set_editor(AnimationTrackEditor *p_editor);
void set_root(Node *p_root);
@@ -322,8 +324,9 @@ class AnimationTrackEditor : public VBoxContainer {
Vector<AnimationTrackEditGroup *> groups;
bool animation_changing_awaiting_update = false;
- void _animation_update();
+ void _animation_update(); // Updated by AnimationTrackEditor(this)
int _get_track_selected();
+ void _sync_animation_change();
void _animation_changed();
void _update_tracks();
@@ -333,7 +336,7 @@ class AnimationTrackEditor : public VBoxContainer {
void _animation_track_remove_request(int p_track, Ref<Animation> p_from_animation);
void _track_grab_focus(int p_track);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void _update_scroll(double);
void _update_step(double p_new_step);
@@ -447,13 +450,20 @@ class AnimationTrackEditor : public VBoxContainer {
void _toggle_bezier_edit();
void _cancel_bezier_edit();
void _bezier_edit(int p_for_track);
+ void _bezier_track_set_key_handle_mode(Animation *p_anim, int p_track, int p_index, Animation::HandleMode p_mode, Animation::HandleSetMode p_set_mode = Animation::HANDLE_SET_MODE_NONE);
////////////// edit menu stuff
+ ConfirmationDialog *bake_dialog = nullptr;
+ CheckBox *bake_trs = nullptr;
+ CheckBox *bake_blendshape = nullptr;
+ CheckBox *bake_value = nullptr;
+ SpinBox *bake_fps = nullptr;
+
ConfirmationDialog *optimize_dialog = nullptr;
- SpinBox *optimize_linear_error = nullptr;
+ SpinBox *optimize_velocity_error = nullptr;
SpinBox *optimize_angular_error = nullptr;
- SpinBox *optimize_max_angle = nullptr;
+ SpinBox *optimize_precision_error = nullptr;
ConfirmationDialog *cleanup_dialog = nullptr;
CheckBox *cleanup_keys = nullptr;
@@ -463,6 +473,11 @@ class AnimationTrackEditor : public VBoxContainer {
ConfirmationDialog *scale_dialog = nullptr;
SpinBox *scale = nullptr;
+ ConfirmationDialog *ease_dialog = nullptr;
+ OptionButton *transition_selection = nullptr;
+ OptionButton *ease_selection = nullptr;
+ SpinBox *ease_fps = nullptr;
+
void _select_all_tracks_for_copy();
void _edit_menu_about_to_popup();
@@ -486,9 +501,9 @@ class AnimationTrackEditor : public VBoxContainer {
NodePath full_path;
NodePath base_path;
Animation::TrackType track_type = Animation::TYPE_ANIMATION;
- Animation::InterpolationType interp_type = Animation::INTERPOLATION_CUBIC;
+ Animation::InterpolationType interp_type = Animation::INTERPOLATION_CUBIC_IN_TIME;
Animation::UpdateMode update_mode = Animation::UPDATE_CAPTURE;
- Animation::LoopMode loop_mode = Animation::LOOP_LINEAR;
+ Animation::LoopMode loop_mode = Animation::LOOP_PINGPONG;
bool loop_wrap = false;
bool enabled = false;
@@ -520,6 +535,8 @@ public:
EDIT_SCALE_SELECTION,
EDIT_SCALE_FROM_CURSOR,
EDIT_SCALE_CONFIRM,
+ EDIT_EASE_SELECTION,
+ EDIT_EASE_CONFIRM,
EDIT_DUPLICATE_SELECTION,
EDIT_DUPLICATE_TRANSPOSED,
EDIT_ADD_RESET_KEY,
@@ -528,6 +545,8 @@ public:
EDIT_GOTO_NEXT_STEP_TIMELINE_ONLY, // Next step without updating animation.
EDIT_GOTO_PREV_STEP,
EDIT_APPLY_RESET,
+ EDIT_BAKE_ANIMATION,
+ EDIT_BAKE_ANIMATION_CONFIRM,
EDIT_OPTIMIZE_ANIMATION,
EDIT_OPTIMIZE_ANIMATION_CONFIRM,
EDIT_CLEAN_UP_ANIMATION,
diff --git a/editor/animation_track_editor_plugins.cpp b/editor/animation_track_editor_plugins.cpp
index cd40b53919..ab64aaa24d 100644
--- a/editor/animation_track_editor_plugins.cpp
+++ b/editor/animation_track_editor_plugins.cpp
@@ -33,6 +33,7 @@
#include "editor/audio_stream_preview.h"
#include "editor/editor_resource_preview.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/2d/animated_sprite_2d.h"
#include "scene/2d/sprite_2d.h"
#include "scene/3d/sprite_3d.h"
diff --git a/editor/array_property_edit.cpp b/editor/array_property_edit.cpp
index 58527ee4d1..ab0e801c88 100644
--- a/editor/array_property_edit.cpp
+++ b/editor/array_property_edit.cpp
@@ -32,6 +32,7 @@
#include "core/io/marshalls.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#define ITEMS_PER_PAGE 100
@@ -87,7 +88,7 @@ bool ArrayPropertyEdit::_set(const StringName &p_name, const Variant &p_value) {
return true;
}
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Resize Array"));
ur->add_do_method(this, "_set_size", newsize);
ur->add_undo_method(this, "_set_size", size);
@@ -134,7 +135,7 @@ bool ArrayPropertyEdit::_set(const StringName &p_name, const Variant &p_value) {
Callable::CallError ce;
Variant new_value;
Variant::construct(Variant::Type(type), new_value, nullptr, 0, ce);
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Array Value Type"));
ur->add_do_method(this, "_set_value", idx, new_value);
@@ -150,7 +151,7 @@ bool ArrayPropertyEdit::_set(const StringName &p_name, const Variant &p_value) {
Variant arr = get_array();
Variant value = arr.get(idx);
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Array Value"));
ur->add_do_method(this, "_set_value", idx, p_value);
diff --git a/editor/code_editor.cpp b/editor/code_editor.cpp
index 9e72c8ec10..bdd30dc653 100644
--- a/editor/code_editor.cpp
+++ b/editor/code_editor.cpp
@@ -1789,7 +1789,7 @@ void CodeTextEditor::toggle_bookmark() {
}
void CodeTextEditor::goto_next_bookmark() {
- Array bmarks = text_editor->get_bookmarked_lines();
+ PackedInt32Array bmarks = text_editor->get_bookmarked_lines();
if (bmarks.size() <= 0) {
return;
}
@@ -1813,7 +1813,7 @@ void CodeTextEditor::goto_next_bookmark() {
}
void CodeTextEditor::goto_prev_bookmark() {
- Array bmarks = text_editor->get_bookmarked_lines();
+ PackedInt32Array bmarks = text_editor->get_bookmarked_lines();
if (bmarks.size() <= 0) {
return;
}
diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp
index 7e883ce180..dc8a64d904 100644
--- a/editor/connections_dialog.cpp
+++ b/editor/connections_dialog.cpp
@@ -34,6 +34,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/scene_tree_dock.h"
#include "plugins/script_editor_plugin.h"
@@ -927,6 +928,10 @@ void ConnectionsDock::_bind_methods() {
ClassDB::bind_method("update_tree", &ConnectionsDock::update_tree);
}
+void ConnectionsDock::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
void ConnectionsDock::set_node(Node *p_node) {
selected_node = p_node;
update_tree();
diff --git a/editor/connections_dialog.h b/editor/connections_dialog.h
index 14da06ccb3..352c5c99d6 100644
--- a/editor/connections_dialog.h
+++ b/editor/connections_dialog.h
@@ -31,7 +31,6 @@
#ifndef CONNECTIONS_DIALOG_H
#define CONNECTIONS_DIALOG_H
-#include "core/object/undo_redo.h"
#include "editor/editor_inspector.h"
#include "editor/scene_tree_editor.h"
#include "scene/gui/button.h"
@@ -48,6 +47,7 @@
#include "scene/gui/tree.h"
class ConnectDialogBinds;
+class EditorUndoRedoManager;
class ConnectDialog : public ConfirmationDialog {
GDCLASS(ConnectDialog, ConfirmationDialog);
@@ -195,7 +195,7 @@ class ConnectionsDock : public VBoxContainer {
Button *connect_button = nullptr;
PopupMenu *signal_menu = nullptr;
PopupMenu *slot_menu = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
LineEdit *search_box = nullptr;
HashMap<StringName, HashMap<StringName, String>> descr_cache;
@@ -226,7 +226,7 @@ protected:
static void _bind_methods();
public:
- void set_undoredo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void set_node(Node *p_node);
void update_tree();
diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp
index e6168f4924..c84e8ec48f 100644
--- a/editor/create_dialog.cpp
+++ b/editor/create_dialog.cpp
@@ -38,7 +38,7 @@
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
-void CreateDialog::popup_create(bool p_dont_clear, bool p_replace_mode, const String &p_select_type) {
+void CreateDialog::popup_create(bool p_dont_clear, bool p_replace_mode, const String &p_select_type, const String &p_select_name) {
_fill_type_list();
icon_fallback = search_options->has_theme_icon(base_type, SNAME("EditorIcons")) ? base_type : "Object";
@@ -57,7 +57,11 @@ void CreateDialog::popup_create(bool p_dont_clear, bool p_replace_mode, const St
_update_search();
if (p_replace_mode) {
- set_title(vformat(TTR("Change %s Type"), base_type));
+ if (!p_select_name.is_empty()) {
+ set_title(vformat(TTR("Convert %s from %s"), p_select_name, p_select_type));
+ } else {
+ set_title(vformat(TTR("Convert %s"), p_select_type));
+ }
set_ok_button_text(TTR("Change"));
} else {
set_title(vformat(TTR("Create New %s"), base_type));
diff --git a/editor/create_dialog.h b/editor/create_dialog.h
index 04094108ad..f7731d2726 100644
--- a/editor/create_dialog.h
+++ b/editor/create_dialog.h
@@ -120,7 +120,7 @@ public:
void set_preferred_search_result_type(const String &p_preferred_type) { preferred_search_result_type = p_preferred_type; }
String get_preferred_search_result_type() { return preferred_search_result_type; }
- void popup_create(bool p_dont_clear, bool p_replace_mode = false, const String &p_select_type = "Node");
+ void popup_create(bool p_dont_clear, bool p_replace_mode = false, const String &p_select_type = "Node", const String &p_select_name = "");
CreateDialog();
};
diff --git a/editor/debugger/editor_debugger_inspector.cpp b/editor/debugger/editor_debugger_inspector.cpp
index 58206efc20..6c0ba55ec8 100644
--- a/editor/debugger/editor_debugger_inspector.cpp
+++ b/editor/debugger/editor_debugger_inspector.cpp
@@ -85,6 +85,7 @@ void EditorDebuggerRemoteObject::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_variant"), &EditorDebuggerRemoteObject::get_variant);
ClassDB::bind_method(D_METHOD("clear"), &EditorDebuggerRemoteObject::clear);
ClassDB::bind_method(D_METHOD("get_remote_object_id"), &EditorDebuggerRemoteObject::get_remote_object_id);
+ ClassDB::bind_method(D_METHOD("_is_read_only"), &EditorDebuggerRemoteObject::_is_read_only);
ADD_SIGNAL(MethodInfo("value_edited", PropertyInfo(Variant::INT, "object_id"), PropertyInfo(Variant::STRING, "property"), PropertyInfo("value")));
}
diff --git a/editor/debugger/editor_debugger_inspector.h b/editor/debugger/editor_debugger_inspector.h
index 5aac4dbf11..c595e0acaa 100644
--- a/editor/debugger/editor_debugger_inspector.h
+++ b/editor/debugger/editor_debugger_inspector.h
@@ -50,6 +50,7 @@ public:
HashMap<StringName, Variant> prop_values;
ObjectID get_remote_object_id() { return remote_object_id; };
+ bool _is_read_only() { return true; };
String get_title();
Variant get_variant(const StringName &p_name);
diff --git a/editor/debugger/editor_debugger_node.cpp b/editor/debugger/editor_debugger_node.cpp
index 472e53c0e8..9fd7fa578f 100644
--- a/editor/debugger/editor_debugger_node.cpp
+++ b/editor/debugger/editor_debugger_node.cpp
@@ -30,6 +30,7 @@
#include "editor_debugger_node.h"
+#include "core/object/undo_redo.h"
#include "editor/debugger/editor_debugger_tree.h"
#include "editor/debugger/script_editor_debugger.h"
#include "editor/editor_log.h"
@@ -83,8 +84,6 @@ EditorDebuggerNode::EditorDebuggerNode() {
inspect_edited_object_timeout = EDITOR_DEF("debugger/remote_inspect_refresh_interval", 0.2);
EditorNode *editor = EditorNode::get_singleton();
- editor->get_undo_redo()->set_method_notify_callback(_method_changeds, this);
- editor->get_undo_redo()->set_property_notify_callback(_property_changeds, this);
editor->get_pause_button()->connect("pressed", callable_mp(this, &EditorDebuggerNode::_paused));
}
@@ -181,6 +180,11 @@ void EditorDebuggerNode::_bind_methods() {
ADD_SIGNAL(MethodInfo("breakpoint_toggled", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::INT, "line"), PropertyInfo(Variant::BOOL, "enabled")));
}
+void EditorDebuggerNode::register_undo_redo(UndoRedo *p_undo_redo) {
+ p_undo_redo->set_method_notify_callback(_method_changeds, this);
+ p_undo_redo->set_property_notify_callback(_property_changeds, this);
+}
+
EditorDebuggerRemoteObject *EditorDebuggerNode::get_inspected_remote_object() {
return Object::cast_to<EditorDebuggerRemoteObject>(ObjectDB::get_instance(EditorNode::get_singleton()->get_editor_selection_history()->get_current()));
}
diff --git a/editor/debugger/editor_debugger_node.h b/editor/debugger/editor_debugger_node.h
index 4c9ad49ac4..e79e60b180 100644
--- a/editor/debugger/editor_debugger_node.h
+++ b/editor/debugger/editor_debugger_node.h
@@ -41,6 +41,7 @@ class EditorDebuggerRemoteObject;
class MenuButton;
class ScriptEditorDebugger;
class TabContainer;
+class UndoRedo;
class EditorDebuggerNode : public MarginContainer {
GDCLASS(EditorDebuggerNode, MarginContainer);
@@ -152,6 +153,7 @@ protected:
public:
static EditorDebuggerNode *get_singleton() { return singleton; }
+ void register_undo_redo(UndoRedo *p_undo_redo);
ScriptEditorDebugger *get_current_debugger() const;
ScriptEditorDebugger *get_default_debugger() const;
diff --git a/editor/debugger/script_editor_debugger.cpp b/editor/debugger/script_editor_debugger.cpp
index ac2e958c5b..1bee0513ca 100644
--- a/editor/debugger/script_editor_debugger.cpp
+++ b/editor/debugger/script_editor_debugger.cpp
@@ -1959,15 +1959,18 @@ ScriptEditorDebugger::ScriptEditorDebugger() {
info_left->set_columns(2);
misc->add_child(info_left);
clicked_ctrl = memnew(LineEdit);
+ clicked_ctrl->set_editable(false);
clicked_ctrl->set_h_size_flags(SIZE_EXPAND_FILL);
info_left->add_child(memnew(Label(TTR("Clicked Control:"))));
info_left->add_child(clicked_ctrl);
clicked_ctrl_type = memnew(LineEdit);
+ clicked_ctrl_type->set_editable(false);
info_left->add_child(memnew(Label(TTR("Clicked Control Type:"))));
info_left->add_child(clicked_ctrl_type);
scene_tree = memnew(SceneDebuggerTree);
live_edit_root = memnew(LineEdit);
+ live_edit_root->set_editable(false);
live_edit_root->set_h_size_flags(SIZE_EXPAND_FILL);
{
diff --git a/editor/dictionary_property_edit.cpp b/editor/dictionary_property_edit.cpp
index 630265e268..f16c5402ad 100644
--- a/editor/dictionary_property_edit.cpp
+++ b/editor/dictionary_property_edit.cpp
@@ -30,6 +30,7 @@
#include "dictionary_property_edit.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
void DictionaryPropertyEdit::_notif_change() {
notify_property_list_changed();
@@ -118,7 +119,7 @@ bool DictionaryPropertyEdit::_set(const StringName &p_name, const Variant &p_val
int index = pn.substr(0, slash).to_int();
if (type == "key" && index < keys.size()) {
const Variant &key = keys[index];
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Dictionary Key"));
ur->add_do_method(this, "_set_key", key, p_value);
@@ -130,7 +131,7 @@ bool DictionaryPropertyEdit::_set(const StringName &p_name, const Variant &p_val
const Variant &key = keys[index];
if (dict.has(key)) {
Variant value = dict[key];
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Dictionary Value"));
ur->add_do_method(this, "_set_value", key, p_value);
diff --git a/editor/editor_audio_buses.cpp b/editor/editor_audio_buses.cpp
index b6d7bbc45f..f1add65b7c 100644
--- a/editor/editor_audio_buses.cpp
+++ b/editor/editor_audio_buses.cpp
@@ -38,6 +38,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "filesystem_dock.h"
#include "scene/resources/font.h"
#include "servers/audio_server.h"
@@ -280,7 +281,7 @@ void EditorAudioBus::_name_changed(const String &p_new_name) {
}
updating_bus = true;
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
StringName current = AudioServer::get_singleton()->get_bus_name(get_index());
ur->create_action(TTR("Rename Audio Bus"));
@@ -321,7 +322,7 @@ void EditorAudioBus::_volume_changed(float p_normalized) {
slider->set_value(_scaled_db_to_normalized_volume(Math::round(p_db)));
}
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Audio Bus Volume"), UndoRedo::MERGE_ENDS);
ur->add_do_method(AudioServer::get_singleton(), "set_bus_volume_db", get_index(), p_db);
ur->add_undo_method(AudioServer::get_singleton(), "set_bus_volume_db", get_index(), AudioServer::get_singleton()->get_bus_volume_db(get_index()));
@@ -415,7 +416,7 @@ void EditorAudioBus::_hide_value_preview() {
void EditorAudioBus::_solo_toggled() {
updating_bus = true;
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Toggle Audio Bus Solo"));
ur->add_do_method(AudioServer::get_singleton(), "set_bus_solo", get_index(), solo->is_pressed());
ur->add_undo_method(AudioServer::get_singleton(), "set_bus_solo", get_index(), AudioServer::get_singleton()->is_bus_solo(get_index()));
@@ -429,7 +430,7 @@ void EditorAudioBus::_solo_toggled() {
void EditorAudioBus::_mute_toggled() {
updating_bus = true;
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Toggle Audio Bus Mute"));
ur->add_do_method(AudioServer::get_singleton(), "set_bus_mute", get_index(), mute->is_pressed());
ur->add_undo_method(AudioServer::get_singleton(), "set_bus_mute", get_index(), AudioServer::get_singleton()->is_bus_mute(get_index()));
@@ -443,7 +444,7 @@ void EditorAudioBus::_mute_toggled() {
void EditorAudioBus::_bypass_toggled() {
updating_bus = true;
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Toggle Audio Bus Bypass Effects"));
ur->add_do_method(AudioServer::get_singleton(), "set_bus_bypass_effects", get_index(), bypass->is_pressed());
ur->add_undo_method(AudioServer::get_singleton(), "set_bus_bypass_effects", get_index(), AudioServer::get_singleton()->is_bus_bypassing_effects(get_index()));
@@ -457,7 +458,7 @@ void EditorAudioBus::_bypass_toggled() {
void EditorAudioBus::_send_selected(int p_which) {
updating_bus = true;
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Select Audio Bus Send"));
ur->add_do_method(AudioServer::get_singleton(), "set_bus_send", get_index(), send->get_item_text(p_which));
ur->add_undo_method(AudioServer::get_singleton(), "set_bus_send", get_index(), AudioServer::get_singleton()->get_bus_send(get_index()));
@@ -507,7 +508,7 @@ void EditorAudioBus::_effect_edited() {
int index = effect->get_metadata(0);
updating_bus = true;
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Select Audio Bus Send"));
ur->add_do_method(AudioServer::get_singleton(), "set_bus_effect_enabled", get_index(), index, effect->is_checked(0));
ur->add_undo_method(AudioServer::get_singleton(), "set_bus_effect_enabled", get_index(), index, AudioServer::get_singleton()->is_bus_effect_enabled(get_index(), index));
@@ -534,7 +535,7 @@ void EditorAudioBus::_effect_add(int p_which) {
afxr->set_name(effect_options->get_item_text(p_which));
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Add Audio Bus Effect"));
ur->add_do_method(AudioServer::get_singleton(), "add_bus_effect", get_index(), afxr, -1);
ur->add_undo_method(AudioServer::get_singleton(), "remove_bus_effect", get_index(), AudioServer::get_singleton()->get_bus_effect_count(get_index()));
@@ -688,7 +689,7 @@ void EditorAudioBus::drop_data_fw(const Point2 &p_point, const Variant &p_data,
bool enabled = AudioServer::get_singleton()->is_bus_effect_enabled(bus, effect);
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Move Bus Effect"));
ur->add_do_method(AudioServer::get_singleton(), "remove_bus_effect", bus, effect);
ur->add_do_method(AudioServer::get_singleton(), "add_bus_effect", get_index(), AudioServer::get_singleton()->get_bus_effect(bus, effect), paste_at);
@@ -730,7 +731,7 @@ void EditorAudioBus::_delete_effect_pressed(int p_option) {
int index = item->get_metadata(0);
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Delete Bus Effect"));
ur->add_do_method(AudioServer::get_singleton(), "remove_bus_effect", get_index(), index);
ur->add_undo_method(AudioServer::get_singleton(), "add_bus_effect", get_index(), AudioServer::get_singleton()->get_bus_effect(get_index(), index), index);
@@ -1063,7 +1064,7 @@ void EditorAudioBuses::_notification(int p_what) {
}
void EditorAudioBuses::_add_bus() {
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Add Audio Bus"));
ur->add_do_method(AudioServer::get_singleton(), "set_bus_count", AudioServer::get_singleton()->get_bus_count() + 1);
@@ -1095,7 +1096,7 @@ void EditorAudioBuses::_delete_bus(Object *p_which) {
return;
}
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Delete Audio Bus"));
ur->add_do_method(AudioServer::get_singleton(), "remove_bus", index);
@@ -1117,7 +1118,7 @@ void EditorAudioBuses::_delete_bus(Object *p_which) {
void EditorAudioBuses::_duplicate_bus(int p_which) {
int add_at_pos = p_which + 1;
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Duplicate Audio Bus"));
ur->add_do_method(AudioServer::get_singleton(), "add_bus", add_at_pos);
ur->add_do_method(AudioServer::get_singleton(), "set_bus_name", add_at_pos, AudioServer::get_singleton()->get_bus_name(p_which) + " Copy");
@@ -1140,7 +1141,7 @@ void EditorAudioBuses::_reset_bus_volume(Object *p_which) {
EditorAudioBus *bus = Object::cast_to<EditorAudioBus>(p_which);
int index = bus->get_index();
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Reset Bus Volume"));
ur->add_do_method(AudioServer::get_singleton(), "set_bus_volume_db", index, 0.f);
ur->add_undo_method(AudioServer::get_singleton(), "set_bus_volume_db", index, AudioServer::get_singleton()->get_bus_volume_db(index));
@@ -1160,7 +1161,7 @@ void EditorAudioBuses::_request_drop_end() {
}
void EditorAudioBuses::_drop_at_index(int p_bus, int p_index) {
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Move Audio Bus"));
ur->add_do_method(AudioServer::get_singleton(), "move_bus", p_bus, p_index);
@@ -1219,7 +1220,7 @@ void EditorAudioBuses::_load_default_layout() {
file->set_text(String(TTR("Layout:")) + " " + layout_path.get_file());
AudioServer::get_singleton()->set_bus_layout(state);
_update_buses();
- EditorNode::get_singleton()->get_undo_redo()->clear_history();
+ EditorNode::get_undo_redo()->clear_history(true, EditorUndoRedoManager::GLOBAL_HISTORY);
call_deferred(SNAME("_select_layout"));
}
@@ -1235,7 +1236,7 @@ void EditorAudioBuses::_file_dialog_callback(const String &p_string) {
file->set_text(String(TTR("Layout:")) + " " + p_string.get_file());
AudioServer::get_singleton()->set_bus_layout(state);
_update_buses();
- EditorNode::get_singleton()->get_undo_redo()->clear_history();
+ EditorNode::get_undo_redo()->clear_history(true, EditorUndoRedoManager::GLOBAL_HISTORY);
call_deferred(SNAME("_select_layout"));
} else if (file_dialog->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
@@ -1255,7 +1256,7 @@ void EditorAudioBuses::_file_dialog_callback(const String &p_string) {
edited_path = p_string;
file->set_text(String(TTR("Layout:")) + " " + p_string.get_file());
_update_buses();
- EditorNode::get_singleton()->get_undo_redo()->clear_history();
+ EditorNode::get_undo_redo()->clear_history(true, EditorUndoRedoManager::GLOBAL_HISTORY);
call_deferred(SNAME("_select_layout"));
}
}
@@ -1354,7 +1355,7 @@ void EditorAudioBuses::open_layout(const String &p_path) {
file->set_text(p_path.get_file());
AudioServer::get_singleton()->set_bus_layout(state);
_update_buses();
- EditorNode::get_singleton()->get_undo_redo()->clear_history();
+ EditorNode::get_undo_redo()->clear_history(true, EditorUndoRedoManager::GLOBAL_HISTORY);
call_deferred(SNAME("_select_layout"));
}
diff --git a/editor/editor_autoload_settings.cpp b/editor/editor_autoload_settings.cpp
index ee4955d0a0..120ac5b984 100644
--- a/editor/editor_autoload_settings.cpp
+++ b/editor/editor_autoload_settings.cpp
@@ -35,6 +35,7 @@
#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/filesystem_dock.h"
#include "project_settings_editor.h"
#include "scene/main/window.h"
@@ -193,7 +194,7 @@ void EditorAutoloadSettings::_autoload_edited() {
TreeItem *ti = tree->get_edited();
int column = tree->get_edited_column();
- UndoRedo *undo_redo = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
if (column == 0) {
String name = ti->get_text(0);
@@ -288,7 +289,7 @@ void EditorAutoloadSettings::_autoload_button_pressed(Object *p_item, int p_colu
String name = "autoload/" + ti->get_text(0);
- UndoRedo *undo_redo = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
switch (p_button) {
case BUTTON_OPEN: {
@@ -713,7 +714,7 @@ void EditorAutoloadSettings::drop_data_fw(const Point2 &p_point, const Variant &
orders.sort();
- UndoRedo *undo_redo = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Rearrange Autoloads"));
@@ -757,7 +758,7 @@ bool EditorAutoloadSettings::autoload_add(const String &p_name, const String &p_
name = "autoload/" + name;
- UndoRedo *undo_redo = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Add Autoload"));
// Singleton autoloads are represented with a leading "*" in their path.
@@ -783,7 +784,7 @@ bool EditorAutoloadSettings::autoload_add(const String &p_name, const String &p_
void EditorAutoloadSettings::autoload_remove(const String &p_name) {
String name = "autoload/" + p_name;
- UndoRedo *undo_redo = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
int order = ProjectSettings::get_singleton()->get_order(name);
diff --git a/editor/editor_data.cpp b/editor/editor_data.cpp
index 2d4945db14..231ae198d2 100644
--- a/editor/editor_data.cpp
+++ b/editor/editor_data.cpp
@@ -35,6 +35,7 @@
#include "core/io/resource_loader.h"
#include "editor/editor_node.h"
#include "editor/editor_plugin.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/script_editor_plugin.h"
#include "scene/resources/packed_scene.h"
@@ -364,13 +365,13 @@ void EditorData::restore_editor_global_states() {
void EditorData::paste_object_params(Object *p_object) {
ERR_FAIL_NULL(p_object);
- undo_redo.create_action(TTR("Paste Params"));
+ undo_redo_manager->create_action(TTR("Paste Params"));
for (const PropertyData &E : clipboard) {
String name = E.name;
- undo_redo.add_do_property(p_object, name, E.value);
- undo_redo.add_undo_property(p_object, name, p_object->get(name));
+ undo_redo_manager->add_do_property(p_object, name, E.value);
+ undo_redo_manager->add_undo_property(p_object, name, p_object->get(name));
}
- undo_redo.commit_action();
+ undo_redo_manager->commit_action();
}
bool EditorData::call_build() {
@@ -383,8 +384,49 @@ bool EditorData::call_build() {
return result;
}
-UndoRedo &EditorData::get_undo_redo() {
- return undo_redo;
+void EditorData::set_scene_as_saved(int p_idx) {
+ if (p_idx == -1) {
+ p_idx = current_edited_scene;
+ }
+ ERR_FAIL_INDEX(p_idx, edited_scene.size());
+
+ get_undo_redo()->set_history_as_saved(edited_scene[p_idx].history_id);
+}
+
+bool EditorData::is_scene_changed(int p_idx) {
+ if (p_idx == -1) {
+ p_idx = current_edited_scene;
+ }
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), false);
+
+ uint64_t current_scene_version = get_undo_redo()->get_or_create_history(edited_scene[p_idx].history_id).undo_redo->get_version();
+ bool is_changed = edited_scene[p_idx].last_checked_version != current_scene_version;
+ edited_scene.write[p_idx].last_checked_version = current_scene_version;
+ return is_changed;
+}
+
+int EditorData::get_scene_history_id_from_path(const String &p_path) const {
+ for (const EditedScene &E : edited_scene) {
+ if (E.path == p_path) {
+ return E.history_id;
+ }
+ }
+ return 0;
+}
+
+int EditorData::get_current_edited_scene_history_id() const {
+ if (current_edited_scene != -1) {
+ return edited_scene[current_edited_scene].history_id;
+ }
+ return 0;
+}
+
+int EditorData::get_scene_history_id(int p_idx) const {
+ return edited_scene[p_idx].history_id;
+}
+
+Ref<EditorUndoRedoManager> &EditorData::get_undo_redo() {
+ return undo_redo_manager;
}
void EditorData::add_undo_redo_inspector_hook_callback(Callable p_callable) {
@@ -415,12 +457,12 @@ Callable EditorData::get_move_array_element_function(const StringName &p_class)
}
void EditorData::remove_editor_plugin(EditorPlugin *p_plugin) {
- p_plugin->undo_redo = nullptr;
+ p_plugin->undo_redo = Ref<EditorUndoRedoManager>();
editor_plugins.erase(p_plugin);
}
void EditorData::add_editor_plugin(EditorPlugin *p_plugin) {
- p_plugin->undo_redo = &undo_redo;
+ p_plugin->undo_redo = undo_redo_manager;
editor_plugins.push_back(p_plugin);
}
@@ -505,8 +547,8 @@ int EditorData::add_edited_scene(int p_at_pos) {
es.path = String();
es.file_modified_time = 0;
es.history_current = -1;
- es.version = 0;
es.live_edit_root = NodePath(String("/root"));
+ es.history_id = last_created_scene++;
if (p_at_pos == edited_scene.size()) {
edited_scene.push_back(es);
@@ -547,6 +589,7 @@ void EditorData::remove_scene(int p_idx) {
ScriptEditor::get_singleton()->close_builtin_scripts_from_scene(edited_scene[p_idx].path);
}
+ undo_redo_manager->discard_history(edited_scene[p_idx].history_id);
edited_scene.remove_at(p_idx);
}
@@ -679,26 +722,10 @@ Vector<EditorData::EditedScene> EditorData::get_edited_scenes() const {
return out_edited_scenes_list;
}
-void EditorData::set_edited_scene_version(uint64_t version, int p_scene_idx) {
- ERR_FAIL_INDEX(current_edited_scene, edited_scene.size());
- if (p_scene_idx < 0) {
- edited_scene.write[current_edited_scene].version = version;
- } else {
- ERR_FAIL_INDEX(p_scene_idx, edited_scene.size());
- edited_scene.write[p_scene_idx].version = version;
- }
-}
-
-uint64_t EditorData::get_scene_version(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), 0);
- return edited_scene[p_idx].version;
-}
-
void EditorData::set_scene_modified_time(int p_idx, uint64_t p_time) {
if (p_idx == -1) {
p_idx = current_edited_scene;
}
-
ERR_FAIL_INDEX(p_idx, edited_scene.size());
edited_scene.write[p_idx].file_modified_time = p_time;
@@ -991,6 +1018,7 @@ void EditorData::script_class_load_icon_paths() {
EditorData::EditorData() {
current_edited_scene = -1;
+ undo_redo_manager.instantiate();
script_class_load_icon_paths();
}
@@ -1115,8 +1143,8 @@ void EditorSelection::_emit_change() {
emitted = false;
}
-Array EditorSelection::_get_transformable_selected_nodes() {
- Array ret;
+TypedArray<Node> EditorSelection::_get_transformable_selected_nodes() {
+ TypedArray<Node> ret;
for (const Node *E : selected_node_list) {
ret.push_back(E);
diff --git a/editor/editor_data.h b/editor/editor_data.h
index 351c63f4b9..1da188c546 100644
--- a/editor/editor_data.h
+++ b/editor/editor_data.h
@@ -31,12 +31,12 @@
#ifndef EDITOR_DATA_H
#define EDITOR_DATA_H
-#include "core/object/undo_redo.h"
#include "core/templates/list.h"
#include "scene/resources/texture.h"
class ConfigFile;
class EditorPlugin;
+class EditorUndoRedoManager;
/**
* Stores the history of objects which have been selected for editing in the Editor & the Inspector.
@@ -118,8 +118,9 @@ public:
Vector<EditorSelectionHistory::HistoryElement> history_stored;
int history_current = 0;
Dictionary custom_state;
- uint64_t version = 0;
NodePath live_edit_root;
+ int history_id = 0;
+ uint64_t last_checked_version = 0;
};
private:
@@ -132,12 +133,13 @@ private:
HashMap<String, Vector<CustomType>> custom_types;
List<PropertyData> clipboard;
- UndoRedo undo_redo;
+ Ref<EditorUndoRedoManager> undo_redo_manager;
Vector<Callable> undo_redo_callbacks;
HashMap<StringName, Callable> move_element_functions;
Vector<EditedScene> edited_scene;
- int current_edited_scene;
+ int current_edited_scene = -1;
+ int last_created_scene = 1;
bool _find_updated_instances(Node *p_root, Node *p_node, HashSet<String> &checked_paths);
@@ -166,7 +168,7 @@ public:
int get_editor_plugin_count() const;
EditorPlugin *get_editor_plugin(int p_idx);
- UndoRedo &get_undo_redo();
+ Ref<EditorUndoRedoManager> &get_undo_redo();
void add_undo_redo_inspector_hook_callback(Callable p_callable); // Callbacks should have this signature: void (Object* undo_redo, Object *modified_object, String property, Variant new_value)
void remove_undo_redo_inspector_hook_callback(Callable p_callable);
const Vector<Callable> get_undo_redo_inspector_hook_callback();
@@ -200,7 +202,6 @@ public:
void set_scene_path(int p_idx, const String &p_path);
Ref<Script> get_scene_root_script(int p_idx) const;
void set_edited_scene_version(uint64_t version, int p_scene_idx = -1);
- uint64_t get_scene_version(int p_idx) const;
void set_scene_modified_time(int p_idx, uint64_t p_time);
uint64_t get_scene_modified_time(int p_idx) const;
void clear_edited_scenes();
@@ -210,6 +211,13 @@ public:
void move_edited_scene_to_index(int p_idx);
bool call_build();
+ void set_scene_as_saved(int p_idx);
+ bool is_scene_changed(int p_idx);
+
+ int get_scene_history_id_from_path(const String &p_path) const;
+ int get_current_edited_scene_history_id() const;
+ int get_scene_history_id(int p_idx) const;
+
void set_plugin_window_layout(Ref<ConfigFile> p_layout);
void get_plugin_window_layout(Ref<ConfigFile> p_layout);
@@ -263,7 +271,7 @@ class EditorSelection : public Object {
List<Node *> selected_node_list;
void _update_node_list();
- Array _get_transformable_selected_nodes();
+ TypedArray<Node> _get_transformable_selected_nodes();
void _emit_change();
protected:
diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp
index 1a105c7fe8..bda2e283ef 100644
--- a/editor/editor_file_system.cpp
+++ b/editor/editor_file_system.cpp
@@ -1192,11 +1192,6 @@ void EditorFileSystem::scan_changes() {
void EditorFileSystem::_notification(int p_what) {
switch (p_what) {
- case NOTIFICATION_ENTER_TREE: {
- call_deferred(SNAME("scan")); //this should happen after every editor node entered the tree
-
- } break;
-
case NOTIFICATION_EXIT_TREE: {
Thread &active_thread = thread.is_started() ? thread : thread_sources;
if (use_threads && active_thread.is_started()) {
diff --git a/editor/editor_help.cpp b/editor/editor_help.cpp
index 8d58469684..7fa4303145 100644
--- a/editor/editor_help.cpp
+++ b/editor/editor_help.cpp
@@ -1785,7 +1785,7 @@ static void _add_text_to_rt(const String &p_bbcode, RichTextLabel *p_rt) {
p_rt->add_text("[");
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 ") || tag.begins_with("theme_item ")) {
+ } 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("annotation ") || 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(" ");
diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp
index b4e36d568d..122e6ad021 100644
--- a/editor/editor_inspector.cpp
+++ b/editor/editor_inspector.cpp
@@ -340,6 +340,8 @@ void EditorProperty::_notification(int p_what) {
draw_string(font, Point2(ofs, v_ofs + font->get_ascent(font_size)), label, HORIZONTAL_ALIGNMENT_LEFT, text_limit, font_size, color);
}
+ ofs = size.width;
+
if (keying) {
Ref<Texture2D> key;
@@ -349,7 +351,7 @@ void EditorProperty::_notification(int p_what) {
key = get_theme_icon(SNAME("Key"), SNAME("EditorIcons"));
}
- ofs = size.width - key->get_width() - get_theme_constant(SNAME("hseparator"), SNAME("Tree"));
+ ofs -= key->get_width() + get_theme_constant(SNAME("hseparator"), SNAME("Tree"));
Color color2(1, 1, 1);
if (keying_hover) {
@@ -373,7 +375,7 @@ void EditorProperty::_notification(int p_what) {
close = get_theme_icon(SNAME("Close"), SNAME("EditorIcons"));
- ofs = size.width - close->get_width() - get_theme_constant(SNAME("hseparator"), SNAME("Tree"));
+ ofs -= close->get_width() + get_theme_constant(SNAME("hseparator"), SNAME("Tree"));
Color color2(1, 1, 1);
if (delete_hover) {
@@ -432,11 +434,11 @@ bool EditorProperty::is_read_only() const {
}
Variant EditorPropertyRevert::get_property_revert_value(Object *p_object, const StringName &p_property, bool *r_is_valid) {
- if (p_object->has_method("property_can_revert") && p_object->call("property_can_revert", p_property)) {
+ if (p_object->property_can_revert(p_property)) {
if (r_is_valid) {
*r_is_valid = true;
}
- return p_object->call("property_get_revert", p_property);
+ return p_object->property_get_revert(p_property);
}
return PropertyUtils::get_property_default_value(p_object, p_property, r_is_valid);
@@ -1701,7 +1703,7 @@ void EditorInspectorArray::_move_element(int p_element_index, int p_to_pos) {
// Call the function.
Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name());
if (move_function.is_valid()) {
- Variant args[] = { (Object *)undo_redo, object, array_element_prefix, p_element_index, p_to_pos };
+ Variant args[] = { undo_redo.ptr(), object, array_element_prefix, p_element_index, p_to_pos };
const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] };
Variant return_value;
Callable::CallError call_error;
@@ -1845,7 +1847,7 @@ void EditorInspectorArray::_clear_array() {
// Call the function.
Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name());
if (move_function.is_valid()) {
- Variant args[] = { (Object *)undo_redo, object, array_element_prefix, i, -1 };
+ Variant args[] = { undo_redo.ptr(), object, array_element_prefix, i, -1 };
const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] };
Variant return_value;
Callable::CallError call_error;
@@ -1898,7 +1900,7 @@ void EditorInspectorArray::_resize_array(int p_size) {
// Call the function.
Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name());
if (move_function.is_valid()) {
- Variant args[] = { (Object *)undo_redo, object, array_element_prefix, -1, -1 };
+ Variant args[] = { undo_redo.ptr(), object, array_element_prefix, -1, -1 };
const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] };
Variant return_value;
Callable::CallError call_error;
@@ -1917,7 +1919,7 @@ void EditorInspectorArray::_resize_array(int p_size) {
// Call the function.
Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name());
if (move_function.is_valid()) {
- Variant args[] = { (Object *)undo_redo, object, array_element_prefix, i, -1 };
+ Variant args[] = { undo_redo.ptr(), object, array_element_prefix, i, -1 };
const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] };
Variant return_value;
Callable::CallError call_error;
@@ -2240,7 +2242,7 @@ void EditorInspectorArray::_bind_methods() {
ADD_SIGNAL(MethodInfo("page_change_request"));
}
-void EditorInspectorArray::set_undo_redo(UndoRedo *p_undo_redo) {
+void EditorInspectorArray::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
undo_redo = p_undo_redo;
}
@@ -2502,7 +2504,7 @@ Button *EditorInspector::create_inspector_action_button(const String &p_text) {
return button;
}
-void EditorInspector::set_undo_redo(UndoRedo *p_undo_redo) {
+void EditorInspector::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
undo_redo = p_undo_redo;
}
@@ -2628,15 +2630,28 @@ void EditorInspector::update_tree() {
valid_plugins.push_back(inspector_plugins[i]);
}
- // Decide if properties should be drawn with the warning color (yellow).
+ // Decide if properties should be drawn with the warning color (yellow),
+ // or if the whole object should be considered read-only.
bool draw_warning = false;
+ bool all_read_only = false;
if (is_inside_tree()) {
+ if (object->has_method("_is_read_only")) {
+ all_read_only = object->call("_is_read_only");
+ }
+
Node *nod = Object::cast_to<Node>(object);
Node *es = EditorNode::get_singleton()->get_edited_scene();
if (nod && es != nod && nod->get_owner() != es) {
// Draw in warning color edited nodes that are not in the currently edited scene,
// as changes may be lost in the future.
draw_warning = true;
+ } else {
+ if (!all_read_only) {
+ Resource *res = Object::cast_to<Resource>(object);
+ if (res) {
+ all_read_only = EditorNode::get_singleton()->is_resource_read_only(res);
+ }
+ }
}
}
@@ -3179,7 +3194,6 @@ void EditorInspector::update_tree() {
ep->property_usage = p.usage;
//and set label?
}
-
if (!editors[i].label.is_empty()) {
ep->set_label(editors[i].label);
} else {
@@ -3206,7 +3220,7 @@ void EditorInspector::update_tree() {
ep->set_checkable(checkable);
ep->set_checked(checked);
ep->set_keying(keying);
- ep->set_read_only(property_read_only);
+ ep->set_read_only(property_read_only || all_read_only);
ep->set_deletable(deletable_properties || p.name.begins_with("metadata/"));
}
@@ -3253,6 +3267,9 @@ void EditorInspector::update_tree() {
add_md->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
add_md->connect(SNAME("pressed"), callable_mp(this, &EditorInspector::_show_add_meta_dialog));
main_vbox->add_child(add_md);
+ if (all_read_only) {
+ add_md->set_disabled(true);
+ }
}
// Get the lists of to add at the end.
@@ -3525,7 +3542,7 @@ void EditorInspector::_edit_set(const String &p_name, const Variant &p_value, bo
}
}
- if (!undo_redo || bool(object->call("_dont_undo_redo"))) {
+ if (!undo_redo.is_valid() || bool(object->call("_dont_undo_redo"))) {
object->set(p_name, p_value);
if (p_refresh_all) {
_edit_request_change(object, "");
@@ -3568,7 +3585,7 @@ void EditorInspector::_edit_set(const String &p_name, const Variant &p_value, bo
}
}
- Variant v_undo_redo = (Object *)undo_redo;
+ Variant v_undo_redo = undo_redo;
Variant v_object = object;
Variant v_name = p_name;
for (int i = 0; i < EditorNode::get_singleton()->get_editor_data().get_undo_redo_inspector_hook_callback().size(); i++) {
@@ -3744,7 +3761,7 @@ void EditorInspector::_property_pinned(const String &p_path, bool p_pinned) {
Node *node = Object::cast_to<Node>(object);
ERR_FAIL_COND(!node);
- if (undo_redo) {
+ if (undo_redo.is_valid()) {
undo_redo->create_action(vformat(p_pinned ? TTR("Pinned %s") : TTR("Unpinned %s"), p_path));
undo_redo->add_do_method(node, "_set_property_pinned", p_path, p_pinned);
undo_redo->add_undo_method(node, "_set_property_pinned", p_path, !p_pinned);
@@ -4026,7 +4043,6 @@ void EditorInspector::_bind_methods() {
EditorInspector::EditorInspector() {
object = nullptr;
- undo_redo = nullptr;
main_vbox = memnew(VBoxContainer);
main_vbox->set_h_size_flags(SIZE_EXPAND_FILL);
main_vbox->add_theme_constant_override("separation", 0);
diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h
index baba9ec1f4..905e13b3a9 100644
--- a/editor/editor_inspector.h
+++ b/editor/editor_inspector.h
@@ -31,6 +31,7 @@
#ifndef EDITOR_INSPECTOR_H
#define EDITOR_INSPECTOR_H
+#include "editor/editor_undo_redo_manager.h"
#include "editor_property_name_processor.h"
#include "scene/gui/box_container.h"
#include "scene/gui/button.h"
@@ -42,8 +43,6 @@
#include "scene/gui/spin_box.h"
#include "scene/gui/texture_rect.h"
-class UndoRedo;
-
class EditorPropertyRevert {
public:
static bool get_instantiated_node_original_property(Node *p_node, const StringName &p_prop, Variant &value, bool p_check_class_default = true);
@@ -313,7 +312,7 @@ public:
class EditorInspectorArray : public EditorInspectorSection {
GDCLASS(EditorInspectorArray, EditorInspectorSection);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
enum Mode {
MODE_NONE,
@@ -408,7 +407,7 @@ protected:
static void _bind_methods();
public:
- void set_undo_redo(UndoRedo *p_undo_redo);
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void setup_with_move_element_function(Object *p_object, String p_label, const StringName &p_array_element_prefix, int p_page, const Color &p_bg_color, bool p_foldable, bool p_movable = true, bool p_numbered = false, int p_page_length = 5, const String &p_add_item_text = "");
void setup_with_count_property(Object *p_object, String p_label, const StringName &p_count_property, const StringName &p_array_element_prefix, int p_page, const Color &p_bg_color, bool p_foldable, bool p_movable = true, bool p_numbered = false, int p_page_length = 5, const String &p_add_item_text = "", const String &p_swap_method = "");
@@ -448,7 +447,7 @@ public:
class EditorInspector : public ScrollContainer {
GDCLASS(EditorInspector, ScrollContainer);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
enum {
MAX_PLUGINS = 1024
};
@@ -562,7 +561,7 @@ public:
static EditorProperty *instantiate_property_editor(Object *p_object, const Variant::Type p_type, const String &p_path, const PropertyHint p_hint, const String &p_hint_text, const uint32_t p_usage, const bool p_wide = false);
- void set_undo_redo(UndoRedo *p_undo_redo);
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
String get_selected_path() const;
diff --git a/editor/editor_locale_dialog.cpp b/editor/editor_locale_dialog.cpp
index cd8150d235..0cf7f7df2a 100644
--- a/editor/editor_locale_dialog.cpp
+++ b/editor/editor_locale_dialog.cpp
@@ -33,6 +33,7 @@
#include "core/config/project_settings.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/check_button.h"
#include "scene/gui/line_edit.h"
#include "scene/gui/option_button.h"
diff --git a/editor/editor_locale_dialog.h b/editor/editor_locale_dialog.h
index 7a4828e83a..8ac642a038 100644
--- a/editor/editor_locale_dialog.h
+++ b/editor/editor_locale_dialog.h
@@ -40,7 +40,7 @@ class VBoxContainer;
class LineEdit;
class Tree;
class OptionButton;
-class UndoRedo;
+class EditorUndoRedoManager;
class EditorLocaleDialog : public ConfirmationDialog {
GDCLASS(EditorLocaleDialog, ConfirmationDialog);
@@ -63,7 +63,7 @@ class EditorLocaleDialog : public ConfirmationDialog {
Tree *script_list = nullptr;
Tree *cnt_list = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
bool locale_set = false;
bool updating_lists = false;
diff --git a/editor/editor_log.cpp b/editor/editor_log.cpp
index 8aa099ddff..dc03a1f270 100644
--- a/editor/editor_log.cpp
+++ b/editor/editor_log.cpp
@@ -224,6 +224,10 @@ void EditorLog::set_tool_button(Button *p_tool_button) {
tool_button = p_tool_button;
}
+void EditorLog::register_undo_redo(UndoRedo *p_undo_redo) {
+ p_undo_redo->set_commit_notify_callback(_undo_redo_cbk, this);
+}
+
void EditorLog::_undo_redo_cbk(void *p_self, const String &p_name) {
EditorLog *self = static_cast<EditorLog *>(p_self);
self->add_message(p_name, EditorLog::MSG_TYPE_EDITOR);
@@ -458,8 +462,6 @@ EditorLog::EditorLog() {
add_error_handler(&eh);
current = Thread::get_caller_id();
-
- EditorNode::get_undo_redo()->set_commit_notify_callback(_undo_redo_cbk, this);
}
void EditorLog::deinit() {
diff --git a/editor/editor_log.h b/editor/editor_log.h
index c225e6d8c5..3bdfd936c1 100644
--- a/editor/editor_log.h
+++ b/editor/editor_log.h
@@ -41,6 +41,8 @@
#include "scene/gui/texture_button.h"
#include "scene/gui/texture_rect.h"
+class UndoRedo;
+
class EditorLog : public HBoxContainer {
GDCLASS(EditorLog, HBoxContainer);
@@ -182,6 +184,7 @@ protected:
public:
void add_message(const String &p_msg, MessageType p_type = MSG_TYPE_STD);
void set_tool_button(Button *p_tool_button);
+ void register_undo_redo(UndoRedo *p_undo_redo);
void deinit();
void clear();
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index e7946f56da..4aedd98bd3 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -54,6 +54,7 @@
#include "scene/gui/dialogs.h"
#include "scene/gui/file_dialog.h"
#include "scene/gui/link_button.h"
+#include "scene/gui/menu_bar.h"
#include "scene/gui/menu_button.h"
#include "scene/gui/panel.h"
#include "scene/gui/panel_container.h"
@@ -104,6 +105,7 @@
#include "editor/editor_themes.h"
#include "editor/editor_toaster.h"
#include "editor/editor_translation_parser.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/export/editor_export.h"
#include "editor/export/export_template_manager.h"
#include "editor/export/project_export.h"
@@ -348,8 +350,7 @@ void EditorNode::_update_scene_tabs() {
icon = EditorNode::get_singleton()->get_object_icon(type_node, "Node");
}
- int current = editor_data.get_edited_scene();
- bool unsaved = (i == current) ? saved_version != editor_data.get_undo_redo().get_version() : editor_data.get_scene_version(i) != 0;
+ bool unsaved = get_undo_redo()->is_history_unsaved(editor_data.get_scene_history_id(i));
scene_tabs->add_tab(disambiguated_scene_names[i] + (unsaved ? "(*)" : ""), icon);
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) {
@@ -596,15 +597,15 @@ void EditorNode::_notification(int p_what) {
opening_prev = false;
}
- bool unsaved_cache_changed = false;
- if (unsaved_cache != (saved_version != editor_data.get_undo_redo().get_version())) {
- unsaved_cache = (saved_version != editor_data.get_undo_redo().get_version());
- unsaved_cache_changed = true;
+ bool global_unsaved = get_undo_redo()->is_history_unsaved(EditorUndoRedoManager::GLOBAL_HISTORY);
+ bool scene_or_global_unsaved = global_unsaved || get_undo_redo()->is_history_unsaved(editor_data.get_current_edited_scene_history_id());
+ if (unsaved_cache != scene_or_global_unsaved) {
+ unsaved_cache = scene_or_global_unsaved;
+ _update_title();
}
- if (last_checked_version != editor_data.get_undo_redo().get_version()) {
+ if (editor_data.is_scene_changed(-1)) {
_update_scene_tabs();
- last_checked_version = editor_data.get_undo_redo().get_version();
}
// Update the animation frame of the update spinner.
@@ -630,7 +631,7 @@ void EditorNode::_notification(int p_what) {
ResourceImporterTexture::get_singleton()->update_imports();
- if (settings_changed || unsaved_cache_changed) {
+ if (settings_changed) {
_update_title();
}
@@ -660,6 +661,7 @@ void EditorNode::_notification(int p_what) {
command_palette->register_shortcuts_as_command();
+ MessageQueue::get_singleton()->push_callable(callable_mp(this, &EditorNode::_begin_first_scan));
/* DO NOT LOAD SCENES HERE, WAIT FOR FILE SCANNING AND REIMPORT TO COMPLETE */
} break;
@@ -751,11 +753,7 @@ void EditorNode::_notification(int p_what) {
scene_tabs->add_theme_style_override("tab_selected", gui_base->get_theme_stylebox(SNAME("SceneTabFG"), SNAME("EditorStyles")));
scene_tabs->add_theme_style_override("tab_unselected", gui_base->get_theme_stylebox(SNAME("SceneTabBG"), SNAME("EditorStyles")));
- file_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- project_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- debug_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- settings_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- help_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
+ main_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
}
scene_tabs->set_max_tab_width(int(EDITOR_GET("interface/scene_tabs/maximum_width")) * EDSCALE);
@@ -803,16 +801,15 @@ void EditorNode::_notification(int p_what) {
dock_tab_move_right->set_icon(theme->get_icon(SNAME("Forward"), SNAME("EditorIcons")));
}
- PopupMenu *p = help_menu->get_popup();
- p->set_item_icon(p->get_item_index(HELP_SEARCH), gui_base->get_theme_icon(SNAME("HelpSearch"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_DOCS), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_QA), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_REPORT_A_BUG), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_SUGGEST_A_FEATURE), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_SEND_DOCS_FEEDBACK), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_COMMUNITY), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_ABOUT), gui_base->get_theme_icon(SNAME("Godot"), SNAME("EditorIcons")));
- p->set_item_icon(p->get_item_index(HELP_SUPPORT_GODOT_DEVELOPMENT), gui_base->get_theme_icon(SNAME("Heart"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_SEARCH), gui_base->get_theme_icon(SNAME("HelpSearch"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_DOCS), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_QA), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_REPORT_A_BUG), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_SUGGEST_A_FEATURE), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_SEND_DOCS_FEEDBACK), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_COMMUNITY), gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_ABOUT), gui_base->get_theme_icon(SNAME("Godot"), SNAME("EditorIcons")));
+ help_menu->set_item_icon(help_menu->get_item_index(HELP_SUPPORT_GODOT_DEVELOPMENT), gui_base->get_theme_icon(SNAME("Heart"), SNAME("EditorIcons")));
for (int i = 0; i < main_editor_buttons.size(); i++) {
main_editor_buttons.write[i]->add_theme_font_override("font", gui_base->get_theme_font(SNAME("main_button_font"), SNAME("EditorFonts")));
@@ -1047,6 +1044,8 @@ void EditorNode::_sources_changed(bool p_exist) {
if (waiting_for_first_scan) {
waiting_for_first_scan = false;
+ Engine::get_singleton()->startup_benchmark_end_measure(); // editor_scan_and_reimport
+
// Reload the global shader variables, but this time
// loading textures, as they are now properly imported.
RenderingServer::get_singleton()->global_shader_uniforms_load_settings(true);
@@ -1059,8 +1058,16 @@ void EditorNode::_sources_changed(bool p_exist) {
_load_docks();
if (!defer_load_scene.is_empty()) {
+ Engine::get_singleton()->startup_benchmark_begin_measure("editor_load_scene");
load_scene(defer_load_scene);
defer_load_scene = "";
+ Engine::get_singleton()->startup_benchmark_end_measure();
+
+ if (use_startup_benchmark) {
+ Engine::get_singleton()->startup_dump(startup_benchmark_file);
+ startup_benchmark_file = String();
+ use_startup_benchmark = false;
+ }
}
}
}
@@ -1131,7 +1138,6 @@ void EditorNode::_reload_modified_scenes() {
}
}
- get_undo_redo()->clear_history(false);
set_current_scene(current_idx);
_update_scene_tabs();
disk_changed->hide();
@@ -1244,7 +1250,9 @@ void EditorNode::save_resource_in_path(const Ref<Resource> &p_resource, const St
}
void EditorNode::save_resource(const Ref<Resource> &p_resource) {
- if (p_resource->get_path().is_resource_file()) {
+ // If the resource has been imported, ask the user to use a different path in order to save it.
+ String path = p_resource->get_path();
+ if (path.is_resource_file() && !FileAccess::exists(path + ".import")) {
save_resource_in_path(p_resource, p_resource->get_path());
} else {
save_resource_as(p_resource);
@@ -1254,11 +1262,18 @@ void EditorNode::save_resource(const Ref<Resource> &p_resource) {
void EditorNode::save_resource_as(const Ref<Resource> &p_resource, const String &p_at_path) {
{
String path = p_resource->get_path();
- int srpos = path.find("::");
- if (srpos != -1) {
- String base = path.substr(0, srpos);
- if (!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base) {
- show_warning(TTR("This resource can't be saved because it does not belong to the edited scene. Make it unique first."));
+ if (!path.is_resource_file()) {
+ int srpos = path.find("::");
+ if (srpos != -1) {
+ String base = path.substr(0, srpos);
+ if (!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base) {
+ show_warning(TTR("This resource can't be saved because it does not belong to the edited scene. Make it unique first."));
+ return;
+ }
+ }
+ } else {
+ if (FileAccess::exists(path + ".import")) {
+ show_warning(TTR("This resource can't be saved because it was imported from another file. Make it unique first."));
return;
}
}
@@ -1685,6 +1700,8 @@ int EditorNode::_save_external_resources() {
saved++;
}
+ get_undo_redo()->set_history_as_saved(EditorUndoRedoManager::GLOBAL_HISTORY);
+
return saved;
}
@@ -1766,11 +1783,7 @@ void EditorNode::_save_scene(String p_file, int idx) {
if (err == OK) {
scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(p_file));
- if (idx < 0 || idx == editor_data.get_edited_scene()) {
- set_current_version(editor_data.get_undo_redo().get_version());
- } else {
- editor_data.set_edited_scene_version(0, idx);
- }
+ editor_data.set_scene_as_saved(idx);
editor_data.set_scene_modified_time(idx, FileAccess::get_modified_time(p_file));
editor_folding.save_scene_folding(scene, p_file);
@@ -1815,15 +1828,15 @@ void EditorNode::restart_editor() {
List<String> args;
+ for (const String &a : Main::get_forwardable_cli_arguments(Main::CLI_SCOPE_TOOL)) {
+ args.push_back(a);
+ }
+
args.push_back("--path");
args.push_back(ProjectSettings::get_singleton()->get_resource_path());
args.push_back("-e");
- if (OS::get_singleton()->is_disable_crash_handler()) {
- args.push_back("--disable-crash-handler");
- }
-
if (!to_reopen.is_empty()) {
args.push_back(to_reopen);
}
@@ -1862,12 +1875,9 @@ void EditorNode::_mark_unsaved_scenes() {
}
String path = node->get_scene_file_path();
- if (!(path.is_empty() || FileAccess::exists(path))) {
- if (i == editor_data.get_edited_scene()) {
- set_current_version(-1);
- } else {
- editor_data.set_edited_scene_version(-1, i);
- }
+ if (!path.is_empty() && !FileAccess::exists(path)) {
+ // Mark scene tab as unsaved if the file is gone.
+ get_undo_redo()->set_history_as_unsaved(editor_data.get_scene_history_id(i));
}
}
@@ -1942,6 +1952,21 @@ void EditorNode::_dialog_action(String p_file) {
}
} break;
+ case FILE_SAVE_AND_RUN_MAIN_SCENE: {
+ ProjectSettings::get_singleton()->set("application/run/main_scene", p_file);
+ ProjectSettings::get_singleton()->save();
+
+ if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
+ _save_default_environment();
+ _save_scene_with_preview(p_file);
+ if ((bool)pick_main_scene->get_meta("from_native", false)) {
+ run_native->resume_run_native();
+ } else {
+ _run(false, p_file);
+ }
+ }
+ } break;
+
case FILE_EXPORT_MESH_LIBRARY: {
Ref<MeshLibrary> ml;
if (file_export_lib_merge->is_pressed() && FileAccess::exists(p_file)) {
@@ -2207,7 +2232,14 @@ void EditorNode::_edit_current(bool p_skip_foreign) {
bool stay_in_script_editor_on_node_selected = bool(EDITOR_GET("text_editor/behavior/navigation/stay_in_script_editor_on_node_selected"));
bool skip_main_plugin = false;
- String editable_warning; // None by default.
+ String editable_info; // None by default.
+ bool info_is_warning = false;
+
+ if (current_obj->has_method("_is_read_only")) {
+ if (current_obj->call("_is_read_only")) {
+ editable_info = TTR("This object is marked as read-only, so it's not editable.");
+ }
+ }
if (is_resource) {
Resource *current_res = Object::cast_to<Resource>(current_obj);
@@ -2221,16 +2253,25 @@ void EditorNode::_edit_current(bool p_skip_foreign) {
int subr_idx = current_res->get_path().find("::");
if (subr_idx != -1) {
String base_path = current_res->get_path().substr(0, subr_idx);
- if (FileAccess::exists(base_path + ".import")) {
- editable_warning = TTR("This resource belongs to a scene that was imported, so it's not editable.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
+ if (!base_path.is_resource_file()) {
+ if (FileAccess::exists(base_path + ".import")) {
+ if (get_edited_scene() && get_edited_scene()->get_scene_file_path() == base_path) {
+ info_is_warning = true;
+ }
+ editable_info = TTR("This resource belongs to a scene that was imported, so it's not editable.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
+ } else {
+ if ((!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base_path) && ResourceLoader::get_resource_type(base_path) == "PackedScene") {
+ editable_info = TTR("This resource belongs to a scene that was instantiated or inherited.\nChanges to it must be made inside the original scene.");
+ }
+ }
} else {
- if ((!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base_path) && ResourceLoader::get_resource_type(base_path) == "PackedScene") {
- editable_warning = TTR("This resource belongs to a scene that was instantiated or inherited.\nChanges to it won't be kept when saving the current scene.");
+ if (FileAccess::exists(base_path + ".import")) {
+ editable_info = TTR("This resource belongs to a scene that was imported, so it's not editable.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
}
}
} else if (current_res->get_path().is_resource_file()) {
if (FileAccess::exists(current_res->get_path() + ".import")) {
- editable_warning = TTR("This resource was imported, so it's not editable. Change its settings in the import panel and then re-import.");
+ editable_info = TTR("This resource was imported, so it's not editable. Change its settings in the import panel and then re-import.");
}
}
} else if (is_node) {
@@ -2254,7 +2295,8 @@ void EditorNode::_edit_current(bool p_skip_foreign) {
if (get_edited_scene() && !get_edited_scene()->get_scene_file_path().is_empty()) {
String source_scene = get_edited_scene()->get_scene_file_path();
if (FileAccess::exists(source_scene + ".import")) {
- editable_warning = TTR("This scene was imported, so changes to it won't be kept.\nInstancing it or inheriting will allow making changes to it.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
+ editable_info = TTR("This scene was imported, so changes to it won't be kept.\nInstancing it or inheriting will allow making changes to it.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
+ info_is_warning = true;
}
}
@@ -2262,7 +2304,7 @@ void EditorNode::_edit_current(bool p_skip_foreign) {
Node *selected_node = nullptr;
if (current_obj->is_class("EditorDebuggerRemoteObject")) {
- editable_warning = TTR("This is a remote object, so changes to it won't be kept.\nPlease read the documentation relevant to debugging to better understand this workflow.");
+ editable_info = TTR("This is a remote object, so it's not editable.\nPlease read the documentation relevant to debugging to better understand this workflow.");
disable_folding = true;
} else if (current_obj->is_class("MultiNodeEdit")) {
Node *scene = get_edited_scene();
@@ -2297,7 +2339,10 @@ void EditorNode::_edit_current(bool p_skip_foreign) {
InspectorDock::get_inspector_singleton()->update_tree();
}
- InspectorDock::get_singleton()->set_warning(editable_warning);
+ InspectorDock::get_singleton()->set_info(
+ info_is_warning ? TTR("Changes may be lost!") : TTR("This object is read-only."),
+ editable_info,
+ info_is_warning);
if (InspectorDock::get_inspector_singleton()->is_using_folding() == disable_folding) {
InspectorDock::get_inspector_singleton()->set_use_folding(!disable_folding);
@@ -2396,10 +2441,8 @@ void EditorNode::_run(bool p_current, const String &p_custom) {
}
if (scene->get_scene_file_path().is_empty()) {
- current_menu_option = -1;
- _menu_option(FILE_SAVE_AS_SCENE);
- // Set the option to save and run so when the dialog is accepted, the scene runs.
current_menu_option = FILE_SAVE_AND_RUN;
+ _menu_option_confirm(FILE_SAVE_AS_SCENE, true);
file->set_title(TTR("Save scene before running..."));
return;
}
@@ -2414,6 +2457,7 @@ void EditorNode::_run(bool p_current, const String &p_custom) {
if (!ensure_main_scene(false)) {
return;
}
+ run_filename = GLOBAL_DEF_BASIC("application/run/main_scene", "");
}
if (bool(EDITOR_GET("run/auto_save/save_before_running"))) {
@@ -2711,9 +2755,9 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
if ((int)Input::get_singleton()->get_mouse_button_mask() & 0x7) {
log->add_message(TTR("Can't undo while mouse buttons are pressed."), EditorLog::MSG_TYPE_EDITOR);
} else {
- String action = editor_data.get_undo_redo().get_current_action_name();
+ String action = editor_data.get_undo_redo()->get_current_action_name();
- if (!editor_data.get_undo_redo().undo()) {
+ if (!editor_data.get_undo_redo()->undo()) {
log->add_message(TTR("Nothing to undo."), EditorLog::MSG_TYPE_EDITOR);
} else if (!action.is_empty()) {
log->add_message(vformat(TTR("Undo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
@@ -2724,10 +2768,10 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
if ((int)Input::get_singleton()->get_mouse_button_mask() & 0x7) {
log->add_message(TTR("Can't redo while mouse buttons are pressed."), EditorLog::MSG_TYPE_EDITOR);
} else {
- if (!editor_data.get_undo_redo().redo()) {
+ if (!editor_data.get_undo_redo()->redo()) {
log->add_message(TTR("Nothing to redo."), EditorLog::MSG_TYPE_EDITOR);
} else {
- String action = editor_data.get_undo_redo().get_current_action_name();
+ String action = editor_data.get_undo_redo()->get_current_action_name();
log->add_message(vformat(TTR("Redo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
}
}
@@ -2762,7 +2806,7 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
ERR_PRINT("Failed to load scene");
}
editor_data.move_edited_scene_to_index(cur_idx);
- get_undo_redo()->clear_history(false);
+ get_undo_redo()->clear_history(false, editor_data.get_current_edited_scene_history_id());
scene_tabs->set_current_tab(cur_idx);
} break;
@@ -3075,8 +3119,7 @@ int EditorNode::_next_unsaved_scene(bool p_valid_filename, int p_start) {
if (!editor_data.get_edited_scene_root(i)) {
continue;
}
- int current = editor_data.get_edited_scene();
- bool unsaved = (i == current) ? saved_version != editor_data.get_undo_redo().get_version() : editor_data.get_scene_version(i) != 0;
+ bool unsaved = get_undo_redo()->is_history_unsaved(editor_data.get_scene_history_id(i));
if (unsaved) {
String scene_filename = editor_data.get_edited_scene_root(i)->get_scene_file_path();
if (p_valid_filename && scene_filename.length() == 0) {
@@ -3162,6 +3205,9 @@ void EditorNode::_discard_changes(const String &p_str) {
String exec = OS::get_singleton()->get_executable_path();
List<String> args;
+ for (const String &a : Main::get_forwardable_cli_arguments(Main::CLI_SCOPE_TOOL)) {
+ args.push_back(a);
+ }
args.push_back("--path");
args.push_back(exec.get_base_dir());
args.push_back("--project-manager");
@@ -3181,17 +3227,15 @@ void EditorNode::_update_file_menu_opened() {
Ref<Shortcut> reopen_closed_scene_sc = ED_GET_SHORTCUT("editor/reopen_closed_scene");
reopen_closed_scene_sc->set_name(TTR("Reopen Closed Scene"));
- PopupMenu *pop = file_menu->get_popup();
- pop->set_item_disabled(pop->get_item_index(FILE_OPEN_PREV), previous_scenes.is_empty());
+ file_menu->set_item_disabled(file_menu->get_item_index(FILE_OPEN_PREV), previous_scenes.is_empty());
- const UndoRedo &undo_redo = editor_data.get_undo_redo();
- pop->set_item_disabled(pop->get_item_index(EDIT_UNDO), !undo_redo.has_undo());
- pop->set_item_disabled(pop->get_item_index(EDIT_REDO), !undo_redo.has_redo());
+ Ref<EditorUndoRedoManager> undo_redo = editor_data.get_undo_redo();
+ file_menu->set_item_disabled(file_menu->get_item_index(EDIT_UNDO), !undo_redo->has_undo());
+ file_menu->set_item_disabled(file_menu->get_item_index(EDIT_REDO), !undo_redo->has_redo());
}
void EditorNode::_update_file_menu_closed() {
- PopupMenu *pop = file_menu->get_popup();
- pop->set_item_disabled(pop->get_item_index(FILE_OPEN_PREV), false);
+ file_menu->set_item_disabled(file_menu->get_item_index(FILE_OPEN_PREV), false);
}
Control *EditorNode::get_main_control() {
@@ -3443,7 +3487,6 @@ void EditorNode::_remove_edited_scene(bool p_change_tab) {
_scene_tab_changed(new_index);
}
editor_data.remove_scene(old_index);
- editor_data.get_undo_redo().clear_history(false);
_update_title();
_update_scene_tabs();
}
@@ -3499,7 +3542,6 @@ Dictionary EditorNode::_get_main_scene_state() {
state["main_tab"] = _get_current_main_editor();
state["scene_tree_offset"] = SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->get_value();
state["property_edit_offset"] = InspectorDock::get_inspector_singleton()->get_scroll_offset();
- state["saved_version"] = saved_version;
state["node_filter"] = SceneTreeDock::get_singleton()->get_filter();
return state;
}
@@ -3559,11 +3601,6 @@ void EditorNode::_set_main_scene_state(Dictionary p_state, Node *p_for_scene) {
editor_data.notify_edited_scene_changed();
}
-void EditorNode::set_current_version(uint64_t p_version) {
- saved_version = p_version;
- editor_data.set_edited_scene_version(p_version);
-}
-
bool EditorNode::is_changing_scene() const {
return changing_scene;
}
@@ -3583,7 +3620,7 @@ void EditorNode::set_current_scene(int p_idx) {
editor_folding.load_scene_folding(editor_data.get_edited_scene_root(p_idx), editor_data.get_scene_path(p_idx));
}
- call_deferred(SNAME("_clear_undo_history"));
+ get_undo_redo()->clear_history(false, editor_data.get_scene_history_id(p_idx));
}
changing_scene = true;
@@ -3600,8 +3637,8 @@ void EditorNode::set_current_scene(int p_idx) {
Node *new_scene = editor_data.get_edited_scene_root();
- if (Object::cast_to<Popup>(new_scene)) {
- Object::cast_to<Popup>(new_scene)->show();
+ if (Popup *p = Object::cast_to<Popup>(new_scene)) {
+ p->show();
}
SceneTreeDock::get_singleton()->set_edited_scene(new_scene);
@@ -3619,6 +3656,7 @@ void EditorNode::set_current_scene(int p_idx) {
_edit_current(true);
_update_title();
+ _update_scene_tabs();
call_deferred(SNAME("_set_main_scene_state"), state, get_edited_scene()); // Do after everything else is done setting up.
}
@@ -3777,7 +3815,6 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b
set_edited_scene(new_scene);
_get_scene_metadata(p_scene);
- saved_version = editor_data.get_undo_redo().get_version();
_update_title();
_update_scene_tabs();
_add_to_recent_scenes(lpath);
@@ -3820,6 +3857,37 @@ void EditorNode::edit_foreign_resource(Ref<Resource> p_resource) {
InspectorDock::get_singleton()->call_deferred("edit_resource", p_resource);
}
+bool EditorNode::is_resource_read_only(Ref<Resource> p_resource) {
+ ERR_FAIL_COND_V(p_resource.is_null(), false);
+
+ String path = p_resource->get_path();
+ if (!path.is_resource_file()) {
+ // If the resource name contains '::', that means it is a subresource embedded in another resource.
+ int srpos = path.find("::");
+ if (srpos != -1) {
+ String base = path.substr(0, srpos);
+ // If the base resource is a packed scene, we treat it as read-only if it is not the currently edited scene.
+ if (ResourceLoader::get_resource_type(base) == "PackedScene") {
+ if (!get_tree()->get_edited_scene_root() || get_tree()->get_edited_scene_root()->get_scene_file_path() != base) {
+ return true;
+ }
+ } else {
+ // If a corresponding .import file exists for the base file, we assume it to be imported and should therefore treated as read-only.
+ if (FileAccess::exists(base + ".import")) {
+ return true;
+ }
+ }
+ }
+ } else {
+ // The resource is not a subresource, but if it has an .import file, it's imported so treat it as read only.
+ if (FileAccess::exists(path + ".import")) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
void EditorNode::request_instance_scene(const String &p_path) {
SceneTreeDock::get_singleton()->instantiate(p_path);
}
@@ -3828,6 +3896,10 @@ void EditorNode::request_instantiate_scenes(const Vector<String> &p_files) {
SceneTreeDock::get_singleton()->instantiate_scenes(p_files);
}
+Ref<EditorUndoRedoManager> &EditorNode::get_undo_redo() {
+ return singleton->editor_data.get_undo_redo();
+}
+
void EditorNode::_inherit_request(String p_file) {
current_menu_option = FILE_NEW_INHERITED_SCENE;
_dialog_action(p_file);
@@ -3988,6 +4060,7 @@ void EditorNode::register_editor_types() {
GDREGISTER_CLASS(EditorSpinSlider);
GDREGISTER_CLASS(EditorResourcePicker);
GDREGISTER_CLASS(EditorScriptPicker);
+ GDREGISTER_ABSTRACT_CLASS(EditorUndoRedoManager);
GDREGISTER_ABSTRACT_CLASS(FileSystemDock);
GDREGISTER_VIRTUAL_CLASS(EditorFileSystemImportFormatSupportQuery);
@@ -4102,8 +4175,15 @@ void EditorNode::_pick_main_scene_custom_action(const String &p_custom_action_na
}
pick_main_scene->hide();
- current_menu_option = SETTINGS_PICK_MAIN_SCENE;
- _dialog_action(scene->get_scene_file_path());
+
+ if (!FileAccess::exists(scene->get_scene_file_path())) {
+ current_menu_option = FILE_SAVE_AND_RUN_MAIN_SCENE;
+ _menu_option_confirm(FILE_SAVE_AS_SCENE, true);
+ file->set_title(TTR("Save scene before running..."));
+ } else {
+ current_menu_option = SETTINGS_PICK_MAIN_SCENE;
+ _dialog_action(scene->get_scene_file_path());
+ }
}
}
@@ -4303,6 +4383,15 @@ void EditorNode::_editor_file_dialog_unregister(EditorFileDialog *p_dialog) {
Vector<EditorNodeInitCallback> EditorNode::_init_callbacks;
+void EditorNode::_begin_first_scan() {
+ Engine::get_singleton()->startup_benchmark_begin_measure("editor_scan_and_import");
+ EditorFileSystem::get_singleton()->scan();
+}
+void EditorNode::set_use_startup_benchmark(bool p_use_startup_benchmark, const String &p_startup_benchmark_file) {
+ use_startup_benchmark = p_use_startup_benchmark;
+ startup_benchmark_file = p_startup_benchmark_file;
+}
+
Error EditorNode::export_preset(const String &p_preset, const String &p_path, bool p_debug, bool p_pack_only) {
export_defer.preset = p_preset;
export_defer.path = p_path;
@@ -5113,9 +5202,7 @@ void EditorNode::_scene_tab_closed(int p_tab, int option) {
return;
}
- bool unsaved = (p_tab == editor_data.get_edited_scene())
- ? saved_version != editor_data.get_undo_redo().get_version()
- : editor_data.get_scene_version(p_tab) != 0;
+ bool unsaved = get_undo_redo()->is_history_unsaved(editor_data.get_scene_history_id(p_tab));
if (unsaved) {
save_confirmation->set_ok_button_text(TTR("Save & Close"));
save_confirmation->set_text(vformat(TTR("Save changes to '%s' before closing?"), !scene->get_scene_file_path().is_empty() ? scene->get_scene_file_path() : "unsaved scene"));
@@ -5227,23 +5314,10 @@ void EditorNode::_thumbnail_done(const String &p_path, const Ref<Texture2D> &p_p
void EditorNode::_scene_tab_changed(int p_tab) {
tab_preview_panel->hide();
- bool unsaved = (saved_version != editor_data.get_undo_redo().get_version());
-
if (p_tab == editor_data.get_edited_scene()) {
return; // Pointless.
}
-
- uint64_t next_scene_version = editor_data.get_scene_version(p_tab);
-
- editor_data.get_undo_redo().create_action(TTR("Switch Scene Tab"));
- editor_data.get_undo_redo().add_do_method(this, "set_current_version", unsaved ? saved_version : 0);
- editor_data.get_undo_redo().add_do_method(this, "set_current_scene", p_tab);
- editor_data.get_undo_redo().add_do_method(this, "set_current_version", next_scene_version == 0 ? editor_data.get_undo_redo().get_version() + 1 : next_scene_version);
-
- editor_data.get_undo_redo().add_undo_method(this, "set_current_version", next_scene_version);
- editor_data.get_undo_redo().add_undo_method(this, "set_current_scene", editor_data.get_edited_scene());
- editor_data.get_undo_redo().add_undo_method(this, "set_current_version", saved_version);
- editor_data.get_undo_redo().commit_action();
+ set_current_scene(p_tab);
}
Button *EditorNode::add_bottom_panel_item(String p_text, Control *p_item) {
@@ -5629,7 +5703,7 @@ void EditorNode::reload_scene(const String &p_path) {
if (scene_idx == -1) {
if (get_edited_scene()) {
// Scene is not open, so at it might be instantiated. We'll refresh the whole scene later.
- editor_data.get_undo_redo().clear_history();
+ editor_data.get_undo_redo()->clear_history(false, editor_data.get_current_edited_scene_history_id());
}
return;
}
@@ -5645,7 +5719,7 @@ void EditorNode::reload_scene(const String &p_path) {
// Adjust index so tab is back a the previous position.
editor_data.move_edited_scene_to_index(scene_idx);
- get_undo_redo()->clear_history();
+ get_undo_redo()->clear_history(false, editor_data.get_scene_history_id(scene_idx));
// Recover the tab.
scene_tabs->set_current_tab(current_tab);
@@ -5823,13 +5897,13 @@ void EditorNode::_bind_methods() {
ClassDB::bind_method("set_edited_scene", &EditorNode::set_edited_scene);
ClassDB::bind_method("open_request", &EditorNode::open_request);
ClassDB::bind_method("edit_foreign_resource", &EditorNode::edit_foreign_resource);
+ ClassDB::bind_method("is_resource_read_only", &EditorNode::is_resource_read_only);
ClassDB::bind_method("_close_messages", &EditorNode::_close_messages);
ClassDB::bind_method("_show_messages", &EditorNode::_show_messages);
ClassDB::bind_method("stop_child_process", &EditorNode::stop_child_process);
ClassDB::bind_method("set_current_scene", &EditorNode::set_current_scene);
- ClassDB::bind_method("set_current_version", &EditorNode::set_current_version);
ClassDB::bind_method("_thumbnail_done", &EditorNode::_thumbnail_done);
ClassDB::bind_method("_set_main_scene_state", &EditorNode::_set_main_scene_state);
ClassDB::bind_method("_update_recent_scenes", &EditorNode::_update_recent_scenes);
@@ -6130,7 +6204,7 @@ EditorNode::EditorNode() {
rmp.instantiate();
EditorInspector::add_inspector_plugin(rmp);
- Ref<EditorInspectorShaderModePlugin> smp;
+ Ref<EditorInspectorVisualShaderModePlugin> smp;
smp.instantiate();
EditorInspector::add_inspector_plugin(smp);
}
@@ -6153,6 +6227,7 @@ EditorNode::EditorNode() {
add_child(editor_export);
// Exporters might need the theme.
+ EditorColorMap::create();
theme = create_custom_theme();
register_exporters();
@@ -6450,15 +6525,20 @@ EditorNode::EditorNode() {
main_control->add_theme_constant_override("separation", 0);
scene_root_parent->add_child(main_control);
- HBoxContainer *left_menu_hb = memnew(HBoxContainer);
- menu_hb->add_child(left_menu_hb);
+ bool global_menu = !bool(EDITOR_GET("interface/editor/use_embedded_menu")) && DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU);
+
+ main_menu = memnew(MenuBar);
+ menu_hb->add_child(main_menu);
+ main_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
+ main_menu->set_flat(true);
+ main_menu->set_start_index(0); // Main menu, add to the start of global menu.
+ main_menu->set_prefer_global_menu(global_menu);
+ main_menu->set_switch_on_hover(true);
- file_menu = memnew(MenuButton);
- file_menu->set_flat(false);
- file_menu->set_switch_on_hover(true);
- file_menu->set_text(TTR("Scene"));
- file_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- left_menu_hb->add_child(file_menu);
+ file_menu = memnew(PopupMenu);
+ file_menu->set_name(TTR("Scene"));
+ main_menu->add_child(file_menu);
+ main_menu->set_menu_tooltip(0, TTR("Operations with scene files."));
prev_scene = memnew(Button);
prev_scene->set_flat(true);
@@ -6528,84 +6608,75 @@ EditorNode::EditorNode() {
command_palette->set_title(TTR("Command Palette"));
gui_base->add_child(command_palette);
- PopupMenu *p;
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/new_scene", TTR("New Scene"), KeyModifierMask::CMD + Key::N), FILE_NEW_SCENE);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/new_inherited_scene", TTR("New Inherited Scene..."), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::N), FILE_NEW_INHERITED_SCENE);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/open_scene", TTR("Open Scene..."), KeyModifierMask::CMD + Key::O), FILE_OPEN_SCENE);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/reopen_closed_scene", TTR("Reopen Closed Scene"), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::T), FILE_OPEN_PREV);
+ file_menu->add_submenu_item(TTR("Open Recent"), "RecentScenes", FILE_OPEN_RECENT);
- file_menu->set_tooltip(TTR("Operations with scene files."));
+ file_menu->add_separator();
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_scene", TTR("Save Scene"), KeyModifierMask::CMD + Key::S), FILE_SAVE_SCENE);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_scene_as", TTR("Save Scene As..."), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::S), FILE_SAVE_AS_SCENE);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_all_scenes", TTR("Save All Scenes"), KeyModifierMask::CMD + KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::S), FILE_SAVE_ALL_SCENES);
- p = file_menu->get_popup();
+ file_menu->add_separator();
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/new_scene", TTR("New Scene"), KeyModifierMask::CMD + Key::N), FILE_NEW_SCENE);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/new_inherited_scene", TTR("New Inherited Scene..."), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::N), FILE_NEW_INHERITED_SCENE);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/open_scene", TTR("Open Scene..."), KeyModifierMask::CMD + Key::O), FILE_OPEN_SCENE);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/reopen_closed_scene", TTR("Reopen Closed Scene"), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::T), FILE_OPEN_PREV);
- p->add_submenu_item(TTR("Open Recent"), "RecentScenes", FILE_OPEN_RECENT);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open", TTR("Quick Open..."), KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::O), FILE_QUICK_OPEN);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open_scene", TTR("Quick Open Scene..."), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::O), FILE_QUICK_OPEN_SCENE);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open_script", TTR("Quick Open Script..."), KeyModifierMask::CMD + KeyModifierMask::ALT + Key::O), FILE_QUICK_OPEN_SCRIPT);
- p->add_separator();
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_scene", TTR("Save Scene"), KeyModifierMask::CMD + Key::S), FILE_SAVE_SCENE);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_scene_as", TTR("Save Scene As..."), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::S), FILE_SAVE_AS_SCENE);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_all_scenes", TTR("Save All Scenes"), KeyModifierMask::CMD + KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::S), FILE_SAVE_ALL_SCENES);
-
- p->add_separator();
-
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open", TTR("Quick Open..."), KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::O), FILE_QUICK_OPEN);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open_scene", TTR("Quick Open Scene..."), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::O), FILE_QUICK_OPEN_SCENE);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open_script", TTR("Quick Open Script..."), KeyModifierMask::CMD + KeyModifierMask::ALT + Key::O), FILE_QUICK_OPEN_SCRIPT);
-
- p->add_separator();
+ file_menu->add_separator();
export_as_menu = memnew(PopupMenu);
export_as_menu->set_name("Export");
- p->add_child(export_as_menu);
- p->add_submenu_item(TTR("Export As..."), "Export");
+ file_menu->add_child(export_as_menu);
+ file_menu->add_submenu_item(TTR("Export As..."), "Export");
export_as_menu->add_shortcut(ED_SHORTCUT("editor/export_as_mesh_library", TTR("MeshLibrary...")), FILE_EXPORT_MESH_LIBRARY);
export_as_menu->connect("index_pressed", callable_mp(this, &EditorNode::_export_as_menu_option));
- p->add_separator();
- p->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO, true);
- p->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO, true);
+ file_menu->add_separator();
+ file_menu->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO, true);
+ file_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO, true);
- p->add_separator();
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/reload_saved_scene", TTR("Reload Saved Scene")), EDIT_RELOAD_SAVED_SCENE);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/close_scene", TTR("Close Scene"), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::W), FILE_CLOSE);
+ file_menu->add_separator();
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/reload_saved_scene", TTR("Reload Saved Scene")), EDIT_RELOAD_SAVED_SCENE);
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/close_scene", TTR("Close Scene"), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::W), FILE_CLOSE);
recent_scenes = memnew(PopupMenu);
recent_scenes->set_name("RecentScenes");
- p->add_child(recent_scenes);
+ file_menu->add_child(recent_scenes);
recent_scenes->connect("id_pressed", callable_mp(this, &EditorNode::_open_recent_scene));
- p->add_separator();
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/file_quit", TTR("Quit"), KeyModifierMask::CMD + Key::Q), FILE_QUIT, true);
-
- project_menu = memnew(MenuButton);
- project_menu->set_flat(false);
- project_menu->set_switch_on_hover(true);
- project_menu->set_tooltip(TTR("Miscellaneous project or scene-wide tools."));
- project_menu->set_text(TTR("Project"));
- project_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- left_menu_hb->add_child(project_menu);
+ if (!global_menu || !OS::get_singleton()->has_feature("macos")) {
+ // On macOS "Quit" and "About" options are in the "app" menu.
+ file_menu->add_separator();
+ file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/file_quit", TTR("Quit"), KeyModifierMask::CMD + Key::Q), FILE_QUIT, true);
+ }
- p = project_menu->get_popup();
+ project_menu = memnew(PopupMenu);
+ project_menu->set_name(TTR("Project"));
+ main_menu->add_child(project_menu);
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/project_settings", TTR("Project Settings..."), Key::NONE, TTR("Project Settings")), RUN_SETTINGS);
- p->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
+ project_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/project_settings", TTR("Project Settings..."), Key::NONE, TTR("Project Settings")), RUN_SETTINGS);
+ project_menu->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
vcs_actions_menu = VersionControlEditorPlugin::get_singleton()->get_version_control_actions_panel();
vcs_actions_menu->set_name("Version Control");
vcs_actions_menu->connect("index_pressed", callable_mp(this, &EditorNode::_version_control_menu_option));
- p->add_separator();
- p->add_child(vcs_actions_menu);
- p->add_submenu_item(TTR("Version Control"), "Version Control");
+ project_menu->add_separator();
+ project_menu->add_child(vcs_actions_menu);
+ project_menu->add_submenu_item(TTR("Version Control"), "Version Control");
vcs_actions_menu->add_item(TTR("Create Version Control Metadata"), RUN_VCS_METADATA);
vcs_actions_menu->add_item(TTR("Set Up Version Control"), RUN_VCS_SETTINGS);
vcs_actions_menu->add_item(TTR("Shut Down Version Control"), RUN_VCS_SHUT_DOWN);
- p->add_separator();
- p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/export", TTR("Export..."), Key::NONE, TTR("Export")), FILE_EXPORT_PROJECT);
- p->add_item(TTR("Install Android Build Template..."), FILE_INSTALL_ANDROID_SOURCE);
- p->add_item(TTR("Open User Data Folder"), RUN_USER_DATA_FOLDER);
+ project_menu->add_separator();
+ project_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/export", TTR("Export..."), Key::NONE, TTR("Export")), FILE_EXPORT_PROJECT);
+ project_menu->add_item(TTR("Install Android Build Template..."), FILE_INSTALL_ANDROID_SOURCE);
+ project_menu->add_item(TTR("Open User Data Folder"), RUN_USER_DATA_FOLDER);
- p->add_separator();
- p->add_item(TTR("Customize Engine Build Configuration..."), TOOLS_BUILD_PROFILE_MANAGER);
- p->add_separator();
+ project_menu->add_separator();
+ project_menu->add_item(TTR("Customize Engine Build Configuration..."), TOOLS_BUILD_PROFILE_MANAGER);
+ project_menu->add_separator();
plugin_config_dialog = memnew(PluginConfigDialog);
plugin_config_dialog->connect("plugin_ready", callable_mp(this, &EditorNode::_on_plugin_ready));
@@ -6614,15 +6685,15 @@ EditorNode::EditorNode() {
tool_menu = memnew(PopupMenu);
tool_menu->set_name("Tools");
tool_menu->connect("index_pressed", callable_mp(this, &EditorNode::_tool_menu_option));
- p->add_child(tool_menu);
- p->add_submenu_item(TTR("Tools"), "Tools");
+ project_menu->add_child(tool_menu);
+ project_menu->add_submenu_item(TTR("Tools"), "Tools");
tool_menu->add_item(TTR("Orphan Resource Explorer..."), TOOLS_ORPHAN_RESOURCES);
- p->add_separator();
- p->add_shortcut(ED_SHORTCUT("editor/reload_current_project", TTR("Reload Current Project")), RELOAD_CURRENT_PROJECT);
+ project_menu->add_separator();
+ project_menu->add_shortcut(ED_SHORTCUT("editor/reload_current_project", TTR("Reload Current Project")), RELOAD_CURRENT_PROJECT);
ED_SHORTCUT_AND_COMMAND("editor/quit_to_project_list", TTR("Quit to Project List"), KeyModifierMask::CMD + KeyModifierMask::SHIFT + Key::Q);
ED_SHORTCUT_OVERRIDE("editor/quit_to_project_list", "macos", KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::Q);
- p->add_shortcut(ED_GET_SHORTCUT("editor/quit_to_project_list"), RUN_PROJECT_MANAGER, true);
+ project_menu->add_shortcut(ED_GET_SHORTCUT("editor/quit_to_project_list"), RUN_PROJECT_MANAGER, true);
menu_hb->add_spacer();
@@ -6630,85 +6701,79 @@ EditorNode::EditorNode() {
menu_hb->add_child(main_editor_button_vb);
// Options are added and handled by DebuggerEditorPlugin.
- debug_menu = memnew(MenuButton);
- debug_menu->set_flat(false);
- debug_menu->set_switch_on_hover(true);
- debug_menu->set_text(TTR("Debug"));
- debug_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- left_menu_hb->add_child(debug_menu);
+ debug_menu = memnew(PopupMenu);
+ debug_menu->set_name(TTR("Debug"));
+ main_menu->add_child(debug_menu);
menu_hb->add_spacer();
- settings_menu = memnew(MenuButton);
- settings_menu->set_flat(false);
- settings_menu->set_switch_on_hover(true);
- settings_menu->set_text(TTR("Editor"));
- settings_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- left_menu_hb->add_child(settings_menu);
-
- p = settings_menu->get_popup();
+ settings_menu = memnew(PopupMenu);
+ settings_menu->set_name(TTR("Editor"));
+ main_menu->add_child(settings_menu);
ED_SHORTCUT_AND_COMMAND("editor/editor_settings", TTR("Editor Settings..."));
ED_SHORTCUT_OVERRIDE("editor/editor_settings", "macos", KeyModifierMask::CMD + Key::COMMA);
- p->add_shortcut(ED_GET_SHORTCUT("editor/editor_settings"), SETTINGS_PREFERENCES);
- p->add_shortcut(ED_SHORTCUT("editor/command_palette", TTR("Command Palette..."), KeyModifierMask::CMD | KeyModifierMask::SHIFT | Key::P), HELP_COMMAND_PALETTE);
- p->add_separator();
+ settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/editor_settings"), SETTINGS_PREFERENCES);
+ settings_menu->add_shortcut(ED_SHORTCUT("editor/command_palette", TTR("Command Palette..."), KeyModifierMask::CMD | KeyModifierMask::SHIFT | Key::P), HELP_COMMAND_PALETTE);
+ settings_menu->add_separator();
editor_layouts = memnew(PopupMenu);
editor_layouts->set_name("Layouts");
- p->add_child(editor_layouts);
+ settings_menu->add_child(editor_layouts);
editor_layouts->connect("id_pressed", callable_mp(this, &EditorNode::_layout_menu_option));
- p->add_submenu_item(TTR("Editor Layout"), "Layouts");
- p->add_separator();
+ settings_menu->add_submenu_item(TTR("Editor Layout"), "Layouts");
+ settings_menu->add_separator();
ED_SHORTCUT_AND_COMMAND("editor/take_screenshot", TTR("Take Screenshot"), KeyModifierMask::CTRL | Key::F12);
ED_SHORTCUT_OVERRIDE("editor/take_screenshot", "macos", KeyModifierMask::CMD | Key::F12);
- p->add_shortcut(ED_GET_SHORTCUT("editor/take_screenshot"), EDITOR_SCREENSHOT);
+ settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/take_screenshot"), EDITOR_SCREENSHOT);
- p->set_item_tooltip(-1, TTR("Screenshots are stored in the Editor Data/Settings Folder."));
+ settings_menu->set_item_tooltip(-1, TTR("Screenshots are stored in the Editor Data/Settings Folder."));
ED_SHORTCUT_AND_COMMAND("editor/fullscreen_mode", TTR("Toggle Fullscreen"), KeyModifierMask::SHIFT | Key::F11);
ED_SHORTCUT_OVERRIDE("editor/fullscreen_mode", "macos", KeyModifierMask::CMD | KeyModifierMask::CTRL | Key::F);
- p->add_shortcut(ED_GET_SHORTCUT("editor/fullscreen_mode"), SETTINGS_TOGGLE_FULLSCREEN);
+ settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/fullscreen_mode"), SETTINGS_TOGGLE_FULLSCREEN);
- p->add_separator();
+ settings_menu->add_separator();
if (OS::get_singleton()->get_data_path() == OS::get_singleton()->get_config_path()) {
// Configuration and data folders are located in the same place (Windows/MacOS).
- p->add_item(TTR("Open Editor Data/Settings Folder"), SETTINGS_EDITOR_DATA_FOLDER);
+ settings_menu->add_item(TTR("Open Editor Data/Settings Folder"), SETTINGS_EDITOR_DATA_FOLDER);
} else {
// Separate configuration and data folders (Linux).
- p->add_item(TTR("Open Editor Data Folder"), SETTINGS_EDITOR_DATA_FOLDER);
- p->add_item(TTR("Open Editor Settings Folder"), SETTINGS_EDITOR_CONFIG_FOLDER);
+ settings_menu->add_item(TTR("Open Editor Data Folder"), SETTINGS_EDITOR_DATA_FOLDER);
+ settings_menu->add_item(TTR("Open Editor Settings Folder"), SETTINGS_EDITOR_CONFIG_FOLDER);
}
- p->add_separator();
+ settings_menu->add_separator();
- p->add_item(TTR("Manage Editor Features..."), SETTINGS_MANAGE_FEATURE_PROFILES);
- p->add_item(TTR("Manage Export Templates..."), SETTINGS_MANAGE_EXPORT_TEMPLATES);
+ settings_menu->add_item(TTR("Manage Editor Features..."), SETTINGS_MANAGE_FEATURE_PROFILES);
+ settings_menu->add_item(TTR("Manage Export Templates..."), SETTINGS_MANAGE_EXPORT_TEMPLATES);
- help_menu = memnew(MenuButton);
- help_menu->set_flat(false);
- help_menu->set_switch_on_hover(true);
- help_menu->set_text(TTR("Help"));
- help_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles")));
- left_menu_hb->add_child(help_menu);
+ help_menu = memnew(PopupMenu);
+ help_menu->set_name(TTR("Help"));
+ main_menu->add_child(help_menu);
- p = help_menu->get_popup();
- p->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
+ help_menu->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
ED_SHORTCUT_AND_COMMAND("editor/editor_help", TTR("Search Help"), Key::F1);
ED_SHORTCUT_OVERRIDE("editor/editor_help", "macos", KeyModifierMask::ALT | Key::SPACE);
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("HelpSearch"), SNAME("EditorIcons")), ED_GET_SHORTCUT("editor/editor_help"), HELP_SEARCH);
- p->add_separator();
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/online_docs", TTR("Online Documentation")), HELP_DOCS);
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/q&a", TTR("Questions & Answers")), HELP_QA);
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/report_a_bug", TTR("Report a Bug")), HELP_REPORT_A_BUG);
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/suggest_a_feature", TTR("Suggest a Feature")), HELP_SUGGEST_A_FEATURE);
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/send_docs_feedback", TTR("Send Docs Feedback")), HELP_SEND_DOCS_FEEDBACK);
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/community", TTR("Community")), HELP_COMMUNITY);
- p->add_separator();
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("Godot"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/about", TTR("About Godot")), HELP_ABOUT);
- p->add_icon_shortcut(gui_base->get_theme_icon(SNAME("Heart"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/support_development", TTR("Support Godot Development")), HELP_SUPPORT_GODOT_DEVELOPMENT);
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("HelpSearch"), SNAME("EditorIcons")), ED_GET_SHORTCUT("editor/editor_help"), HELP_SEARCH);
+ help_menu->add_separator();
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/online_docs", TTR("Online Documentation")), HELP_DOCS);
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/q&a", TTR("Questions & Answers")), HELP_QA);
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/report_a_bug", TTR("Report a Bug")), HELP_REPORT_A_BUG);
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/suggest_a_feature", TTR("Suggest a Feature")), HELP_SUGGEST_A_FEATURE);
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/send_docs_feedback", TTR("Send Docs Feedback")), HELP_SEND_DOCS_FEEDBACK);
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("ExternalLink"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/community", TTR("Community")), HELP_COMMUNITY);
+ help_menu->add_separator();
+ if (!global_menu || !OS::get_singleton()->has_feature("macos")) {
+ // On macOS "Quit" and "About" options are in the "app" menu.
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("Godot"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/about", TTR("About Godot")), HELP_ABOUT);
+ }
+ help_menu->add_icon_shortcut(gui_base->get_theme_icon(SNAME("Heart"), SNAME("EditorIcons")), ED_SHORTCUT_AND_COMMAND("editor/support_development", TTR("Support Godot Development")), HELP_SUPPORT_GODOT_DEVELOPMENT);
+
+ Control *right_spacer = memnew(Control);
+ menu_hb->add_child(right_spacer);
HBoxContainer *play_hb = memnew(HBoxContainer);
menu_hb->add_child(play_hb);
@@ -6857,7 +6922,7 @@ EditorNode::EditorNode() {
right_menu_hb->add_child(update_spinner);
update_spinner->set_icon(gui_base->get_theme_icon(SNAME("Progress1"), SNAME("EditorIcons")));
update_spinner->get_popup()->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
- p = update_spinner->get_popup();
+ PopupMenu *p = update_spinner->get_popup();
p->add_radio_check_item(TTR("Update Continuously"), SETTINGS_UPDATE_CONTINUOUSLY);
p->add_radio_check_item(TTR("Update When Changed"), SETTINGS_UPDATE_WHEN_CHANGED);
p->add_separator();
@@ -7077,11 +7142,11 @@ EditorNode::EditorNode() {
gui_base->add_child(file_script);
file_script->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
- file_menu->get_popup()->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
+ file_menu->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
file_menu->connect("about_to_popup", callable_mp(this, &EditorNode::_update_file_menu_opened));
- file_menu->get_popup()->connect("popup_hide", callable_mp(this, &EditorNode::_update_file_menu_closed));
+ file_menu->connect("popup_hide", callable_mp(this, &EditorNode::_update_file_menu_closed));
- settings_menu->get_popup()->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
+ settings_menu->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
file->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
file_templates->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
@@ -7364,11 +7429,14 @@ EditorNode::EditorNode() {
screenshot_timer = memnew(Timer);
screenshot_timer->set_one_shot(true);
- screenshot_timer->set_wait_time(settings_menu->get_popup()->get_submenu_popup_delay() + 0.1f);
+ screenshot_timer->set_wait_time(settings_menu->get_submenu_popup_delay() + 0.1f);
screenshot_timer->connect("timeout", callable_mp(this, &EditorNode::_request_screenshot));
add_child(screenshot_timer);
screenshot_timer->set_owner(get_owner());
+ main_menu->set_custom_minimum_size(Size2(MAX(main_menu->get_minimum_size().x, play_hb->get_minimum_size().x + right_menu_hb->get_minimum_size().x), 0));
+ right_spacer->set_custom_minimum_size(Size2(MAX(0, main_menu->get_minimum_size().x - play_hb->get_minimum_size().x - right_menu_hb->get_minimum_size().x), 0));
+
String exec = OS::get_singleton()->get_executable_path();
// Save editor executable path for third-party tools.
EditorSettings::get_singleton()->set_project_metadata("editor_metadata", "executable_path", exec);
diff --git a/editor/editor_node.h b/editor/editor_node.h
index 0201e84eaf..91c753e480 100644
--- a/editor/editor_node.h
+++ b/editor/editor_node.h
@@ -72,12 +72,14 @@ class EditorRun;
class EditorRunNative;
class EditorSettingsDialog;
class EditorToaster;
+class EditorUndoRedoManager;
class ExportTemplateManager;
class FileDialog;
class FileSystemDock;
class HSplitContainer;
class ImportDock;
class LinkButton;
+class MenuBar;
class MenuButton;
class NodeDock;
class OrphanResourcesDialog;
@@ -141,6 +143,7 @@ private:
FILE_SAVE_AS_SCENE,
FILE_SAVE_ALL_SCENES,
FILE_SAVE_AND_RUN,
+ FILE_SAVE_AND_RUN_MAIN_SCENE,
FILE_SHOW_IN_FILESYSTEM,
FILE_EXPORT_PROJECT,
FILE_EXPORT_MESH_LIBRARY,
@@ -321,11 +324,12 @@ private:
HBoxContainer *menu_hb = nullptr;
Control *main_control = nullptr;
- MenuButton *file_menu = nullptr;
- MenuButton *project_menu = nullptr;
- MenuButton *debug_menu = nullptr;
- MenuButton *settings_menu = nullptr;
- MenuButton *help_menu = nullptr;
+ MenuBar *main_menu = nullptr;
+ PopupMenu *file_menu = nullptr;
+ PopupMenu *project_menu = nullptr;
+ PopupMenu *debug_menu = nullptr;
+ PopupMenu *settings_menu = nullptr;
+ PopupMenu *help_menu = nullptr;
PopupMenu *tool_menu = nullptr;
PopupMenu *export_as_menu = nullptr;
Button *export_button = nullptr;
@@ -468,9 +472,6 @@ private:
String open_navigate;
String run_custom_filename;
- uint64_t saved_version = 1;
- uint64_t last_checked_version = 0;
-
DynamicFontImportSettings *fontdata_import_settings = nullptr;
SceneImportSettings *scene_import_settings = nullptr;
AudioStreamImportSettings *audio_stream_import_settings = nullptr;
@@ -679,6 +680,10 @@ private:
void _bottom_panel_switch(bool p_enable, int p_idx);
void _bottom_panel_raise_toggled(bool);
+ void _begin_first_scan();
+ bool use_startup_benchmark = false;
+ String startup_benchmark_file;
+
protected:
friend class FileSystemDock;
@@ -702,7 +707,7 @@ public:
static EditorLog *get_log() { return singleton->log; }
static EditorData &get_editor_data() { return singleton->editor_data; }
static EditorFolding &get_editor_folding() { return singleton->editor_folding; }
- static UndoRedo *get_undo_redo() { return &singleton->editor_data.get_undo_redo(); }
+ static Ref<EditorUndoRedoManager> &get_undo_redo();
static HBoxContainer *get_menu_hb() { return singleton->menu_hb; }
static VSplitContainer *get_top_split() { return singleton->top_split; }
@@ -771,6 +776,8 @@ public:
void open_request(const String &p_path);
void edit_foreign_resource(Ref<Resource> p_resource);
+ bool is_resource_read_only(Ref<Resource> p_resource);
+
bool is_changing_scene() const;
Control *get_main_control();
@@ -786,7 +793,6 @@ public:
bool is_scene_open(const String &p_path);
- void set_current_version(uint64_t p_version);
void set_current_scene(int p_idx);
void setup_color_picker(ColorPicker *picker);
@@ -813,6 +819,7 @@ public:
void _copy_warning(const String &p_str);
+ void set_use_startup_benchmark(bool p_use_startup_benchmark, const String &p_startup_benchmark_file);
Error export_preset(const String &p_preset, const String &p_path, bool p_debug, bool p_pack_only);
Control *get_gui_base() { return gui_base; }
diff --git a/editor/editor_path.cpp b/editor/editor_path.cpp
index dc77b5fea9..87ebd3e1c1 100644
--- a/editor/editor_path.cpp
+++ b/editor/editor_path.cpp
@@ -72,7 +72,7 @@ void EditorPath::_add_children_to_popup(Object *p_obj, int p_depth) {
int index = sub_objects_menu->get_item_count();
sub_objects_menu->add_icon_item(icon, proper_name, objects.size());
- sub_objects_menu->set_item_horizontal_offset(index, p_depth * 10 * EDSCALE);
+ sub_objects_menu->set_item_indent(index, p_depth);
objects.push_back(obj->get_instance_id());
_add_children_to_popup(obj, p_depth + 1);
diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp
index 566c22f5a9..b0bd500ef8 100644
--- a/editor/editor_plugin.cpp
+++ b/editor/editor_plugin.cpp
@@ -35,6 +35,7 @@
#include "editor/editor_paths.h"
#include "editor/editor_resource_preview.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/export/editor_export.h"
#include "editor/filesystem_dock.h"
#include "editor/plugins/canvas_item_editor_plugin.h"
@@ -47,7 +48,7 @@
#include "scene/gui/popup_menu.h"
#include "servers/rendering_server.h"
-Array EditorInterface::_make_mesh_previews(const Array &p_meshes, int p_preview_size) {
+TypedArray<Texture2D> EditorInterface::_make_mesh_previews(const Array &p_meshes, int p_preview_size) {
Vector<Ref<Mesh>> meshes;
for (int i = 0; i < p_meshes.size(); i++) {
@@ -55,7 +56,7 @@ Array EditorInterface::_make_mesh_previews(const Array &p_meshes, int p_preview_
}
Vector<Ref<Texture2D>> textures = make_mesh_previews(meshes, nullptr, p_preview_size);
- Array ret;
+ TypedArray<Texture2D> ret;
for (int i = 0; i < textures.size(); i++) {
ret.push_back(textures[i]);
}
@@ -215,8 +216,8 @@ Node *EditorInterface::get_edited_scene_root() {
return EditorNode::get_singleton()->get_edited_scene();
}
-Array EditorInterface::get_open_scenes() const {
- Array ret;
+PackedStringArray EditorInterface::get_open_scenes() const {
+ PackedStringArray ret;
Vector<EditorData::EditedScene> scenes = EditorNode::get_editor_data().get_edited_scenes();
int scns_amount = scenes.size();
@@ -312,6 +313,13 @@ void EditorInterface::set_distraction_free_mode(bool p_enter) {
EditorNode::get_singleton()->set_distraction_free_mode(p_enter);
}
+void EditorInterface::restart_editor(bool p_save) {
+ if (p_save) {
+ EditorNode::get_singleton()->save_all_scenes();
+ }
+ EditorNode::get_singleton()->restart_editor();
+}
+
bool EditorInterface::is_distraction_free_mode_enabled() const {
return EditorNode::get_singleton()->is_distraction_free_mode_enabled();
}
@@ -360,6 +368,7 @@ void EditorInterface::_bind_methods() {
ClassDB::bind_method(D_METHOD("save_scene"), &EditorInterface::save_scene);
ClassDB::bind_method(D_METHOD("save_scene_as", "path", "with_preview"), &EditorInterface::save_scene_as, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("restart_editor", "save"), &EditorInterface::restart_editor, DEFVAL(true));
ClassDB::bind_method(D_METHOD("set_main_screen_editor", "name"), &EditorInterface::set_main_screen_editor);
ClassDB::bind_method(D_METHOD("set_distraction_free_mode", "enter"), &EditorInterface::set_distraction_free_mode);
@@ -445,7 +454,7 @@ void EditorPlugin::add_control_to_container(CustomControlContainer p_location, C
CanvasItemEditor::get_singleton()->get_bottom_split()->add_child(p_control);
} break;
- case CONTAINER_PROPERTY_EDITOR_BOTTOM: {
+ case CONTAINER_INSPECTOR_BOTTOM: {
InspectorDock::get_singleton()->get_addon_area()->add_child(p_control);
} break;
@@ -498,7 +507,7 @@ void EditorPlugin::remove_control_from_container(CustomControlContainer p_locati
CanvasItemEditor::get_singleton()->get_bottom_split()->remove_child(p_control);
} break;
- case CONTAINER_PROPERTY_EDITOR_BOTTOM: {
+ case CONTAINER_INSPECTOR_BOTTOM: {
InspectorDock::get_singleton()->get_addon_area()->remove_child(p_control);
} break;
@@ -885,7 +894,7 @@ void EditorPlugin::_bind_methods() {
ClassDB::bind_method(D_METHOD("make_bottom_panel_item_visible", "item"), &EditorPlugin::make_bottom_panel_item_visible);
ClassDB::bind_method(D_METHOD("hide_bottom_panel"), &EditorPlugin::hide_bottom_panel);
- ClassDB::bind_method(D_METHOD("get_undo_redo"), &EditorPlugin::_get_undo_redo);
+ ClassDB::bind_method(D_METHOD("get_undo_redo"), &EditorPlugin::get_undo_redo);
ClassDB::bind_method(D_METHOD("add_undo_redo_inspector_hook_callback", "callable"), &EditorPlugin::add_undo_redo_inspector_hook_callback);
ClassDB::bind_method(D_METHOD("remove_undo_redo_inspector_hook_callback", "callable"), &EditorPlugin::remove_undo_redo_inspector_hook_callback);
ClassDB::bind_method(D_METHOD("queue_save_layout"), &EditorPlugin::queue_save_layout);
@@ -950,7 +959,7 @@ void EditorPlugin::_bind_methods() {
BIND_ENUM_CONSTANT(CONTAINER_CANVAS_EDITOR_SIDE_LEFT);
BIND_ENUM_CONSTANT(CONTAINER_CANVAS_EDITOR_SIDE_RIGHT);
BIND_ENUM_CONSTANT(CONTAINER_CANVAS_EDITOR_BOTTOM);
- BIND_ENUM_CONSTANT(CONTAINER_PROPERTY_EDITOR_BOTTOM);
+ BIND_ENUM_CONSTANT(CONTAINER_INSPECTOR_BOTTOM);
BIND_ENUM_CONSTANT(CONTAINER_PROJECT_SETTING_TAB_LEFT);
BIND_ENUM_CONSTANT(CONTAINER_PROJECT_SETTING_TAB_RIGHT);
@@ -965,6 +974,10 @@ void EditorPlugin::_bind_methods() {
BIND_ENUM_CONSTANT(DOCK_SLOT_MAX);
}
+Ref<EditorUndoRedoManager> EditorPlugin::get_undo_redo() {
+ return undo_redo;
+}
+
EditorPluginCreateFunc EditorPlugins::creation_funcs[MAX_CREATE_FUNCS];
int EditorPlugins::creation_func_count = 0;
diff --git a/editor/editor_plugin.h b/editor/editor_plugin.h
index 84c63d1021..8357f0960a 100644
--- a/editor/editor_plugin.h
+++ b/editor/editor_plugin.h
@@ -53,6 +53,7 @@ class EditorImportPlugin;
class EditorExportPlugin;
class EditorNode3DGizmoPlugin;
class EditorResourcePreview;
+class EditorUndoRedoManager;
class EditorFileSystem;
class EditorToolAddons;
class EditorPaths;
@@ -66,7 +67,7 @@ protected:
static void _bind_methods();
static EditorInterface *singleton;
- Array _make_mesh_previews(const Array &p_meshes, int p_preview_size);
+ TypedArray<Texture2D> _make_mesh_previews(const Array &p_meshes, int p_preview_size);
public:
static EditorInterface *get_singleton() { return singleton; }
@@ -86,7 +87,7 @@ public:
String get_playing_scene() const;
Node *get_edited_scene_root();
- Array get_open_scenes() const;
+ PackedStringArray get_open_scenes() const;
ScriptEditor *get_script_editor();
EditorCommandPalette *get_command_palette() const;
@@ -116,6 +117,7 @@ public:
Error save_scene();
void save_scene_as(const String &p_scene, bool p_with_preview = true);
+ void restart_editor(bool p_save = true);
Vector<Ref<Texture2D>> make_mesh_previews(const Vector<Ref<Mesh>> &p_meshes, Vector<Transform3D> *p_transforms, int p_preview_size);
@@ -129,9 +131,7 @@ public:
class EditorPlugin : public Node {
GDCLASS(EditorPlugin, Node);
friend class EditorData;
- UndoRedo *undo_redo = nullptr;
-
- UndoRedo *_get_undo_redo() { return undo_redo; }
+ Ref<EditorUndoRedoManager> undo_redo;
bool input_event_forwarding_always_enabled = false;
bool force_draw_over_forwarding_enabled = false;
@@ -144,7 +144,7 @@ protected:
void _notification(int p_what);
static void _bind_methods();
- UndoRedo &get_undo_redo() { return *undo_redo; }
+ Ref<EditorUndoRedoManager> get_undo_redo();
void add_custom_type(const String &p_type, const String &p_base, const Ref<Script> &p_script, const Ref<Texture2D> &p_icon);
void remove_custom_type(const String &p_type);
@@ -184,7 +184,7 @@ public:
CONTAINER_CANVAS_EDITOR_SIDE_LEFT,
CONTAINER_CANVAS_EDITOR_SIDE_RIGHT,
CONTAINER_CANVAS_EDITOR_BOTTOM,
- CONTAINER_PROPERTY_EDITOR_BOTTOM,
+ CONTAINER_INSPECTOR_BOTTOM,
CONTAINER_PROJECT_SETTING_TAB_LEFT,
CONTAINER_PROJECT_SETTING_TAB_RIGHT,
};
diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp
index f434df3a1e..84c4c9c877 100644
--- a/editor/editor_properties.cpp
+++ b/editor/editor_properties.cpp
@@ -2613,8 +2613,47 @@ void EditorPropertyQuaternion::_set_read_only(bool p_read_only) {
for (int i = 0; i < 4; i++) {
spin[i]->set_read_only(p_read_only);
}
+ for (int i = 0; i < 3; i++) {
+ euler[i]->set_read_only(p_read_only);
+ }
};
+void EditorPropertyQuaternion::_edit_custom_value() {
+ if (edit_button->is_pressed()) {
+ edit_custom_bc->show();
+ for (int i = 0; i < 3; i++) {
+ euler[i]->grab_focus();
+ }
+ } else {
+ edit_custom_bc->hide();
+ for (int i = 0; i < 4; i++) {
+ spin[i]->grab_focus();
+ }
+ }
+ update_property();
+}
+
+void EditorPropertyQuaternion::_custom_value_changed(double val) {
+ if (setting) {
+ return;
+ }
+
+ edit_euler.x = euler[0]->get_value();
+ edit_euler.y = euler[1]->get_value();
+ edit_euler.z = euler[2]->get_value();
+
+ Vector3 v;
+ v.x = Math::deg2rad(edit_euler.x);
+ v.y = Math::deg2rad(edit_euler.y);
+ v.z = Math::deg2rad(edit_euler.z);
+
+ Quaternion temp_q = Quaternion(v);
+ spin[0]->set_value(temp_q.x);
+ spin[1]->set_value(temp_q.y);
+ spin[2]->set_value(temp_q.z);
+ spin[3]->set_value(temp_q.w);
+}
+
void EditorPropertyQuaternion::_value_changed(double val, const String &p_name) {
if (setting) {
return;
@@ -2625,9 +2664,18 @@ void EditorPropertyQuaternion::_value_changed(double val, const String &p_name)
p.y = spin[1]->get_value();
p.z = spin[2]->get_value();
p.w = spin[3]->get_value();
+
emit_changed(get_edited_property(), p, p_name);
}
+bool EditorPropertyQuaternion::is_grabbing_euler() {
+ bool is_grabbing = false;
+ for (int i = 0; i < 3; i++) {
+ is_grabbing |= euler[i]->is_grabbing();
+ }
+ return is_grabbing;
+}
+
void EditorPropertyQuaternion::update_property() {
Quaternion val = get_edited_object()->get(get_edited_property());
setting = true;
@@ -2635,9 +2683,22 @@ void EditorPropertyQuaternion::update_property() {
spin[1]->set_value(val.y);
spin[2]->set_value(val.z);
spin[3]->set_value(val.w);
+ if (!is_grabbing_euler()) {
+ Vector3 v = val.normalized().get_euler_yxz();
+ edit_euler.x = Math::rad2deg(v.x);
+ edit_euler.y = Math::rad2deg(v.y);
+ edit_euler.z = Math::rad2deg(v.z);
+ euler[0]->set_value(edit_euler.x);
+ euler[1]->set_value(edit_euler.y);
+ euler[2]->set_value(edit_euler.z);
+ }
setting = false;
}
+void EditorPropertyQuaternion::_warning_pressed() {
+ warning_dialog->popup_centered();
+}
+
void EditorPropertyQuaternion::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
@@ -2646,6 +2707,13 @@ void EditorPropertyQuaternion::_notification(int p_what) {
for (int i = 0; i < 4; i++) {
spin[i]->add_theme_color_override("label_color", colors[i]);
}
+ for (int i = 0; i < 3; i++) {
+ euler[i]->add_theme_color_override("label_color", colors[i]);
+ }
+ edit_button->set_icon(get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")));
+ euler_label->add_theme_color_override(SNAME("font_color"), get_theme_color(SNAME("property_color"), SNAME("Editor")));
+ warning->set_icon(get_theme_icon(SNAME("NodeWarning"), SNAME("EditorIcons")));
+ warning->add_theme_color_override(SNAME("font_color"), get_theme_color(SNAME("warning_color"), SNAME("Editor")));
} break;
}
}
@@ -2653,7 +2721,7 @@ void EditorPropertyQuaternion::_notification(int p_what) {
void EditorPropertyQuaternion::_bind_methods() {
}
-void EditorPropertyQuaternion::setup(double p_min, double p_max, double p_step, bool p_no_slider, const String &p_suffix) {
+void EditorPropertyQuaternion::setup(double p_min, double p_max, double p_step, bool p_no_slider, const String &p_suffix, bool p_hide_editor) {
for (int i = 0; i < 4; i++) {
spin[i]->set_min(p_min);
spin[i]->set_max(p_max);
@@ -2665,28 +2733,50 @@ void EditorPropertyQuaternion::setup(double p_min, double p_max, double p_step,
// a generic way to store 4 values, so we'll still respect the suffix.
spin[i]->set_suffix(p_suffix);
}
+
+ for (int i = 0; i < 3; i++) {
+ euler[i]->set_min(-360);
+ euler[i]->set_max(360);
+ euler[i]->set_step(0.1);
+ euler[i]->set_hide_slider(false);
+ euler[i]->set_allow_greater(true);
+ euler[i]->set_allow_lesser(true);
+ euler[i]->set_suffix(U"\u00B0");
+ }
+
+ if (p_hide_editor) {
+ edit_button->hide();
+ }
}
EditorPropertyQuaternion::EditorPropertyQuaternion() {
bool horizontal = EDITOR_GET("interface/inspector/horizontal_vector_types_editing");
- BoxContainer *bc;
-
+ VBoxContainer *bc = memnew(VBoxContainer);
+ edit_custom_bc = memnew(VBoxContainer);
+ BoxContainer *edit_custom_layout;
if (horizontal) {
- bc = memnew(HBoxContainer);
- add_child(bc);
+ default_layout = memnew(HBoxContainer);
+ edit_custom_layout = memnew(HBoxContainer);
set_bottom_editor(bc);
} else {
- bc = memnew(VBoxContainer);
- add_child(bc);
+ default_layout = memnew(VBoxContainer);
+ edit_custom_layout = memnew(VBoxContainer);
}
+ edit_custom_bc->hide();
+ add_child(bc);
+ edit_custom_bc->set_h_size_flags(SIZE_EXPAND_FILL);
+ default_layout->set_h_size_flags(SIZE_EXPAND_FILL);
+ edit_custom_layout->set_h_size_flags(SIZE_EXPAND_FILL);
+ bc->add_child(default_layout);
+ bc->add_child(edit_custom_bc);
static const char *desc[4] = { "x", "y", "z", "w" };
for (int i = 0; i < 4; i++) {
spin[i] = memnew(EditorSpinSlider);
spin[i]->set_flat(true);
spin[i]->set_label(desc[i]);
- bc->add_child(spin[i]);
+ default_layout->add_child(spin[i]);
add_focusable(spin[i]);
spin[i]->connect("value_changed", callable_mp(this, &EditorPropertyQuaternion::_value_changed).bind(desc[i]));
if (horizontal) {
@@ -2694,6 +2784,41 @@ EditorPropertyQuaternion::EditorPropertyQuaternion() {
}
}
+ warning = memnew(Button);
+ warning->set_text(TTR("Temporary Euler may be changed implicitly!"));
+ warning->set_clip_text(true);
+ warning->connect("pressed", callable_mp(this, &EditorPropertyQuaternion::_warning_pressed));
+ warning_dialog = memnew(AcceptDialog);
+ add_child(warning_dialog);
+ warning_dialog->set_text(TTR("Temporary Euler will not be stored in the object with the original value. Instead, it will be stored as Quaternion with irreversible conversion.\nThis is due to the fact that the result of Euler->Quaternion can be determined uniquely, but the result of Quaternion->Euler can be multi-existent."));
+
+ euler_label = memnew(Label);
+ euler_label->set_text("Temporary Euler");
+
+ edit_custom_bc->add_child(warning);
+ edit_custom_bc->add_child(edit_custom_layout);
+ edit_custom_layout->add_child(euler_label);
+
+ for (int i = 0; i < 3; i++) {
+ euler[i] = memnew(EditorSpinSlider);
+ euler[i]->set_flat(true);
+ euler[i]->set_label(desc[i]);
+ edit_custom_layout->add_child(euler[i]);
+ add_focusable(euler[i]);
+ euler[i]->connect("value_changed", callable_mp(this, &EditorPropertyQuaternion::_custom_value_changed));
+ if (horizontal) {
+ euler[i]->set_h_size_flags(SIZE_EXPAND_FILL);
+ }
+ }
+
+ edit_button = memnew(Button);
+ edit_button->set_flat(true);
+ edit_button->set_toggle_mode(true);
+ default_layout->add_child(edit_button);
+ edit_button->connect("pressed", callable_mp(this, &EditorPropertyQuaternion::_edit_custom_value));
+
+ add_focusable(edit_button);
+
if (!horizontal) {
set_label_reference(spin[0]); //show text and buttons around this
}
@@ -3653,20 +3778,24 @@ void EditorPropertyResource::_set_read_only(bool p_read_only) {
resource_picker->set_editable(!p_read_only);
};
-void EditorPropertyResource::_resource_selected(const Ref<Resource> &p_resource, bool p_edit) {
+void EditorPropertyResource::_resource_selected(const Ref<Resource> &p_resource, bool p_inspect) {
if (p_resource->is_built_in() && !p_resource->get_path().is_empty()) {
String parent = p_resource->get_path().get_slice("::", 0);
List<String> extensions;
ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
- if (extensions.find(parent.get_extension()) && (!EditorNode::get_singleton()->get_edited_scene() || EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path() != parent)) {
- // If the resource belongs to another scene, edit it in that scene instead.
- EditorNode::get_singleton()->call_deferred("edit_foreign_resource", p_resource);
- return;
+ if (p_inspect) {
+ if (extensions.find(parent.get_extension()) && (!EditorNode::get_singleton()->get_edited_scene() || EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path() != parent)) {
+ // If the resource belongs to another (non-imported) scene, edit it in that scene instead.
+ if (!FileAccess::exists(parent + ".import")) {
+ EditorNode::get_singleton()->call_deferred("edit_foreign_resource", p_resource);
+ return;
+ }
+ }
}
}
- if (!p_edit && use_sub_inspector) {
+ if (!p_inspect && use_sub_inspector) {
bool unfold = !get_edited_object()->editor_is_section_unfolded(get_edited_property());
get_edited_object()->editor_set_section_unfold(get_edited_property(), unfold);
update_property();
@@ -4357,7 +4486,7 @@ EditorProperty *EditorInspectorDefaultPlugin::get_editor_for_property(Object *p_
case Variant::QUATERNION: {
EditorPropertyQuaternion *editor = memnew(EditorPropertyQuaternion);
EditorPropertyRangeHint hint = _parse_range_hint(p_hint, p_hint_text, default_float_step);
- editor->setup(hint.min, hint.max, hint.step, hint.hide_slider, hint.suffix);
+ editor->setup(hint.min, hint.max, hint.step, hint.hide_slider, hint.suffix, p_hint == PROPERTY_HINT_HIDE_QUATERNION_EDIT);
return editor;
} break;
case Variant::AABB: {
diff --git a/editor/editor_properties.h b/editor/editor_properties.h
index c1dfb5cb1e..6ac3973303 100644
--- a/editor/editor_properties.h
+++ b/editor/editor_properties.h
@@ -625,9 +625,26 @@ public:
class EditorPropertyQuaternion : public EditorProperty {
GDCLASS(EditorPropertyQuaternion, EditorProperty);
+ BoxContainer *default_layout = nullptr;
EditorSpinSlider *spin[4];
bool setting = false;
+
+ Button *warning = nullptr;
+ AcceptDialog *warning_dialog = nullptr;
+
+ Label *euler_label = nullptr;
+ VBoxContainer *edit_custom_bc = nullptr;
+ EditorSpinSlider *euler[3];
+ Button *edit_button = nullptr;
+
+ Vector3 edit_euler = Vector3();
+
void _value_changed(double p_val, const String &p_name);
+ void _edit_custom_value();
+ void _custom_value_changed(double p_val);
+ void _warning_pressed();
+
+ bool is_grabbing_euler();
protected:
virtual void _set_read_only(bool p_read_only) override;
@@ -636,7 +653,7 @@ protected:
public:
virtual void update_property() override;
- void setup(double p_min, double p_max, double p_step, bool p_no_slider, const String &p_suffix = String());
+ void setup(double p_min, double p_max, double p_step, bool p_no_slider, const String &p_suffix = String(), bool p_hide_editor = false);
EditorPropertyQuaternion();
};
@@ -835,7 +852,7 @@ class EditorPropertyResource : public EditorProperty {
bool updating_theme = false;
bool opened_editor = false;
- void _resource_selected(const Ref<Resource> &p_resource, bool p_edit);
+ void _resource_selected(const Ref<Resource> &p_resource, bool p_inspect);
void _resource_changed(const Ref<Resource> &p_resource);
void _viewport_selected(const NodePath &p_path);
diff --git a/editor/editor_resource_picker.cpp b/editor/editor_resource_picker.cpp
index e5c1836205..7e42c45b01 100644
--- a/editor/editor_resource_picker.cpp
+++ b/editor/editor_resource_picker.cpp
@@ -81,6 +81,8 @@ void EditorResourcePicker::_update_resource() {
} else if (edited_resource.is_valid()) {
assign_button->set_tooltip(resource_path + TTR("Type:") + " " + edited_resource->get_class());
}
+
+ assign_button->set_disabled(!editable && !edited_resource.is_valid());
}
void EditorResourcePicker::_update_resource_preview(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, ObjectID p_obj) {
@@ -171,35 +173,50 @@ void EditorResourcePicker::_update_menu_items() {
edit_menu->clear();
// Add options for creating specific subtypes of the base resource type.
- set_create_options(edit_menu);
+ if (is_editable()) {
+ set_create_options(edit_menu);
- // Add an option to load a resource from a file using the QuickOpen dialog.
- edit_menu->add_icon_item(get_theme_icon(SNAME("Load"), SNAME("EditorIcons")), TTR("Quick Load"), OBJ_MENU_QUICKLOAD);
+ // Add an option to load a resource from a file using the QuickOpen dialog.
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Load"), SNAME("EditorIcons")), TTR("Quick Load"), OBJ_MENU_QUICKLOAD);
- // Add an option to load a resource from a file using the regular file dialog.
- edit_menu->add_icon_item(get_theme_icon(SNAME("Load"), SNAME("EditorIcons")), TTR("Load"), OBJ_MENU_LOAD);
+ // Add an option to load a resource from a file using the regular file dialog.
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Load"), SNAME("EditorIcons")), TTR("Load"), OBJ_MENU_LOAD);
+ }
// Add options for changing existing value of the resource.
if (edited_resource.is_valid()) {
- edit_menu->add_icon_item(get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")), TTR("Edit"), OBJ_MENU_EDIT);
- edit_menu->add_icon_item(get_theme_icon(SNAME("Clear"), SNAME("EditorIcons")), TTR("Clear"), OBJ_MENU_CLEAR);
- edit_menu->add_icon_item(get_theme_icon(SNAME("Duplicate"), SNAME("EditorIcons")), TTR("Make Unique"), OBJ_MENU_MAKE_UNIQUE);
-
- // Check whether the resource has subresources.
- List<PropertyInfo> property_list;
- edited_resource->get_property_list(&property_list);
- bool has_subresources = false;
- for (PropertyInfo &p : property_list) {
- if ((p.type == Variant::OBJECT) && (p.hint == PROPERTY_HINT_RESOURCE_TYPE) && (p.name != "script")) {
- has_subresources = true;
- break;
- }
- }
- if (has_subresources) {
- edit_menu->add_icon_item(get_theme_icon(SNAME("Duplicate"), SNAME("EditorIcons")), TTR("Make Unique (Recursive)"), OBJ_MENU_MAKE_UNIQUE_RECURSIVE);
+ // Determine if the edited resource is part of another scene (foreign) which was imported
+ bool is_edited_resource_foreign_import = EditorNode::get_singleton()->is_resource_read_only(edited_resource);
+
+ // If the resource is determined to be foreign and imported, change the menu entry's description to 'inspect' rather than 'edit'
+ // since will only be able to view its properties in read-only mode.
+ if (is_edited_resource_foreign_import) {
+ // The 'Search' icon is a magnifying glass, which seems appropriate, but maybe a bespoke icon is preferred here.
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")), TTR("Inspect"), OBJ_MENU_INSPECT);
+ } else {
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")), TTR("Edit"), OBJ_MENU_INSPECT);
}
- edit_menu->add_icon_item(get_theme_icon(SNAME("Save"), SNAME("EditorIcons")), TTR("Save"), OBJ_MENU_SAVE);
+ if (is_editable()) {
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Clear"), SNAME("EditorIcons")), TTR("Clear"), OBJ_MENU_CLEAR);
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Duplicate"), SNAME("EditorIcons")), TTR("Make Unique"), OBJ_MENU_MAKE_UNIQUE);
+
+ // Check whether the resource has subresources.
+ List<PropertyInfo> property_list;
+ edited_resource->get_property_list(&property_list);
+ bool has_subresources = false;
+ for (PropertyInfo &p : property_list) {
+ if ((p.type == Variant::OBJECT) && (p.hint == PROPERTY_HINT_RESOURCE_TYPE) && (p.name != "script")) {
+ has_subresources = true;
+ break;
+ }
+ }
+ if (has_subresources) {
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Duplicate"), SNAME("EditorIcons")), TTR("Make Unique (Recursive)"), OBJ_MENU_MAKE_UNIQUE_RECURSIVE);
+ }
+
+ edit_menu->add_icon_item(get_theme_icon(SNAME("Save"), SNAME("EditorIcons")), TTR("Save"), OBJ_MENU_SAVE);
+ }
if (edited_resource->get_path().is_resource_file()) {
edit_menu->add_separator();
@@ -210,14 +227,16 @@ void EditorResourcePicker::_update_menu_items() {
// Add options to copy/paste resource.
Ref<Resource> cb = EditorSettings::get_singleton()->get_resource_clipboard();
bool paste_valid = false;
- if (cb.is_valid()) {
- if (base_type.is_empty()) {
- paste_valid = true;
- } else {
- for (int i = 0; i < base_type.get_slice_count(","); i++) {
- if (ClassDB::is_parent_class(cb->get_class(), base_type.get_slice(",", i))) {
- paste_valid = true;
- break;
+ if (is_editable()) {
+ if (cb.is_valid()) {
+ if (base_type.is_empty()) {
+ paste_valid = true;
+ } else {
+ for (int i = 0; i < base_type.get_slice_count(","); i++) {
+ if (ClassDB::is_parent_class(cb->get_class(), base_type.get_slice(",", i))) {
+ paste_valid = true;
+ break;
+ }
}
}
}
@@ -236,7 +255,7 @@ void EditorResourcePicker::_update_menu_items() {
}
// Add options to convert existing resource to another type of resource.
- if (edited_resource.is_valid()) {
+ if (is_editable() && edited_resource.is_valid()) {
Vector<Ref<EditorResourceConversionPlugin>> conversions = EditorNode::get_singleton()->find_resource_conversion_plugin(edited_resource);
if (conversions.size()) {
edit_menu->add_separator();
@@ -295,7 +314,7 @@ void EditorResourcePicker::_edit_menu_cbk(int p_which) {
quick_open->set_title(TTR("Resource"));
} break;
- case OBJ_MENU_EDIT: {
+ case OBJ_MENU_INSPECT: {
if (edited_resource.is_valid()) {
emit_signal(SNAME("resource_selected"), edited_resource, true);
}
@@ -491,20 +510,21 @@ void EditorResourcePicker::_button_draw() {
}
void EditorResourcePicker::_button_input(const Ref<InputEvent> &p_event) {
- if (!editable) {
- return;
- }
-
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
if (mb->is_pressed() && mb->get_button_index() == MouseButton::RIGHT) {
- _update_menu_items();
-
- Vector2 pos = get_screen_position() + mb->get_position();
- edit_menu->reset_size();
- edit_menu->set_position(pos);
- edit_menu->popup();
+ // Only attempt to update and show the menu if we have
+ // a valid resource or the Picker is editable, as
+ // there will otherwise be nothing to display.
+ if (edited_resource.is_valid() || is_editable()) {
+ _update_menu_items();
+
+ Vector2 pos = get_screen_position() + mb->get_position();
+ edit_menu->reset_size();
+ edit_menu->set_position(pos);
+ edit_menu->popup();
+ }
}
}
}
@@ -734,7 +754,7 @@ void EditorResourcePicker::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "toggle_mode"), "set_toggle_mode", "is_toggle_mode");
- ADD_SIGNAL(MethodInfo("resource_selected", PropertyInfo(Variant::OBJECT, "resource", PROPERTY_HINT_RESOURCE_TYPE, "Resource"), PropertyInfo(Variant::BOOL, "edit")));
+ ADD_SIGNAL(MethodInfo("resource_selected", PropertyInfo(Variant::OBJECT, "resource", PROPERTY_HINT_RESOURCE_TYPE, "Resource"), PropertyInfo(Variant::BOOL, "inspect")));
ADD_SIGNAL(MethodInfo("resource_changed", PropertyInfo(Variant::OBJECT, "resource", PROPERTY_HINT_RESOURCE_TYPE, "Resource")));
}
@@ -866,7 +886,7 @@ void EditorResourcePicker::set_toggle_pressed(bool p_pressed) {
void EditorResourcePicker::set_editable(bool p_editable) {
editable = p_editable;
- assign_button->set_disabled(!editable);
+ assign_button->set_disabled(!editable && !edited_resource.is_valid());
edit_button->set_visible(editable);
}
diff --git a/editor/editor_resource_picker.h b/editor/editor_resource_picker.h
index 3a4d5985bd..3d6127e656 100644
--- a/editor/editor_resource_picker.h
+++ b/editor/editor_resource_picker.h
@@ -63,7 +63,7 @@ class EditorResourcePicker : public HBoxContainer {
enum MenuOption {
OBJ_MENU_LOAD,
OBJ_MENU_QUICKLOAD,
- OBJ_MENU_EDIT,
+ OBJ_MENU_INSPECT,
OBJ_MENU_CLEAR,
OBJ_MENU_MAKE_UNIQUE,
OBJ_MENU_MAKE_UNIQUE_RECURSIVE,
diff --git a/editor/editor_run.cpp b/editor/editor_run.cpp
index 6ce8625daa..3b828951e4 100644
--- a/editor/editor_run.cpp
+++ b/editor/editor_run.cpp
@@ -33,6 +33,7 @@
#include "core/config/project_settings.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "main/main.h"
#include "servers/display_server.h"
EditorRun::Status EditorRun::get_status() const {
@@ -46,6 +47,10 @@ String EditorRun::get_running_scene() const {
Error EditorRun::run(const String &p_scene, const String &p_write_movie) {
List<String> args;
+ for (const String &a : Main::get_forwardable_cli_arguments(Main::CLI_SCOPE_PROJECT)) {
+ args.push_back(a);
+ }
+
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
if (!resource_path.is_empty()) {
args.push_back("--path");
@@ -105,10 +110,6 @@ Error EditorRun::run(const String &p_scene, const String &p_write_movie) {
screen -= 3;
}
- if (OS::get_singleton()->is_disable_crash_handler()) {
- args.push_back("--disable-crash-handler");
- }
-
Rect2 screen_rect;
screen_rect.position = DisplayServer::get_singleton()->screen_get_position(screen);
screen_rect.size = DisplayServer::get_singleton()->screen_get_size(screen);
diff --git a/editor/editor_sectioned_inspector.cpp b/editor/editor_sectioned_inspector.cpp
index 801a1a4641..1faefb5af7 100644
--- a/editor/editor_sectioned_inspector.cpp
+++ b/editor/editor_sectioned_inspector.cpp
@@ -113,12 +113,12 @@ class SectionedInspectorFilter : public Object {
}
}
- bool property_can_revert(const String &p_name) {
- return edited->call("property_can_revert", section + "/" + p_name);
+ bool property_can_revert(const StringName &p_name) {
+ return edited->property_can_revert(section + "/" + p_name);
}
- Variant property_get_revert(const String &p_name) {
- return edited->call("property_get_revert", section + "/" + p_name);
+ Variant property_get_revert(const StringName &p_name) {
+ return edited->property_get_revert(section + "/" + p_name);
}
protected:
diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp
index 80e77a1125..4437b1b166 100644
--- a/editor/editor_settings.cpp
+++ b/editor/editor_settings.cpp
@@ -406,6 +406,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
_initial_set("interface/editor/debug/enable_pseudolocalization", false);
set_restart_if_changed("interface/editor/debug/enable_pseudolocalization", true);
// Use pseudolocalization in editor.
+ EDITOR_SETTING_USAGE(Variant::BOOL, PROPERTY_HINT_NONE, "interface/editor/use_embedded_menu", false, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED)
EDITOR_SETTING_USAGE(Variant::FLOAT, PROPERTY_HINT_RANGE, "interface/editor/custom_display_scale", 1.0, "0.5,3,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED)
EDITOR_SETTING(Variant::INT, PROPERTY_HINT_RANGE, "interface/editor/main_font_size", 14, "8,48,1")
@@ -962,8 +963,8 @@ void EditorSettings::save() {
}
}
-Array EditorSettings::get_changed_settings() const {
- Array arr;
+PackedStringArray EditorSettings::get_changed_settings() const {
+ PackedStringArray arr;
for (const String &setting : changed_settings) {
arr.push_back(setting);
}
@@ -1073,24 +1074,25 @@ Variant _EDITOR_GET(const String &p_setting) {
return EditorSettings::get_singleton()->get(p_setting);
}
-bool EditorSettings::property_can_revert(const String &p_setting) {
- if (!props.has(p_setting)) {
+bool EditorSettings::_property_can_revert(const StringName &p_name) const {
+ if (!props.has(p_name)) {
return false;
}
- if (!props[p_setting].has_default_value) {
+ if (!props[p_name].has_default_value) {
return false;
}
- return props[p_setting].initial != props[p_setting].variant;
+ return props[p_name].initial != props[p_name].variant;
}
-Variant EditorSettings::property_get_revert(const String &p_setting) {
- if (!props.has(p_setting) || !props[p_setting].has_default_value) {
- return Variant();
+bool EditorSettings::_property_get_revert(const StringName &p_name, Variant &r_property) const {
+ if (!props.has(p_name) || !props[p_name].has_default_value) {
+ return false;
}
- return props[p_setting].initial;
+ r_property = props[p_name].initial;
+ return true;
}
void EditorSettings::add_property_hint(const PropertyInfo &p_hint) {
@@ -1621,8 +1623,6 @@ void EditorSettings::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_setting", "name"), &EditorSettings::get_setting);
ClassDB::bind_method(D_METHOD("erase", "property"), &EditorSettings::erase);
ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value", "update_current"), &EditorSettings::set_initial_value);
- ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &EditorSettings::property_can_revert);
- ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &EditorSettings::property_get_revert);
ClassDB::bind_method(D_METHOD("add_property_info", "info"), &EditorSettings::_add_property_info_bind);
ClassDB::bind_method(D_METHOD("set_project_metadata", "section", "key", "data"), &EditorSettings::set_project_metadata);
diff --git a/editor/editor_settings.h b/editor/editor_settings.h
index 5faeec88c8..09bc4caa22 100644
--- a/editor/editor_settings.h
+++ b/editor/editor_settings.h
@@ -100,6 +100,8 @@ private:
void _initial_set(const StringName &p_name, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_list) const;
void _add_property_info_bind(const Dictionary &p_info);
+ bool _property_can_revert(const StringName &p_name) const;
+ bool _property_get_revert(const StringName &p_name, Variant &r_property) const;
void _load_defaults(Ref<ConfigFile> p_extra_config = Ref<ConfigFile>());
void _load_godot2_text_editor_theme();
@@ -138,10 +140,8 @@ public:
_set_only(p_setting, p_value);
}
}
- bool property_can_revert(const String &p_setting);
- Variant property_get_revert(const String &p_setting);
void add_property_hint(const PropertyInfo &p_hint);
- Array get_changed_settings() const;
+ PackedStringArray get_changed_settings() const;
bool check_changed_settings_in_group(const String &p_setting_prefix) const;
void mark_setting_changed(const String &p_setting);
diff --git a/editor/editor_settings_dialog.cpp b/editor/editor_settings_dialog.cpp
index 08ff63551f..67c602ad2d 100644
--- a/editor/editor_settings_dialog.cpp
+++ b/editor/editor_settings_dialog.cpp
@@ -40,6 +40,7 @@
#include "editor/editor_property_name_processor.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/margin_container.h"
void EditorSettingsDialog::ok_pressed() {
@@ -124,9 +125,9 @@ void EditorSettingsDialog::_notification(int p_what) {
} break;
case NOTIFICATION_READY: {
- undo_redo->set_method_notify_callback(EditorDebuggerNode::_method_changeds, nullptr);
- undo_redo->set_property_notify_callback(EditorDebuggerNode::_property_changeds, nullptr);
- undo_redo->set_commit_notify_callback(_undo_redo_callback, this);
+ undo_redo->get_or_create_history(EditorUndoRedoManager::GLOBAL_HISTORY).undo_redo->set_method_notify_callback(EditorDebuggerNode::_method_changeds, nullptr);
+ undo_redo->get_or_create_history(EditorUndoRedoManager::GLOBAL_HISTORY).undo_redo->set_property_notify_callback(EditorDebuggerNode::_property_changeds, nullptr);
+ undo_redo->get_or_create_history(EditorUndoRedoManager::GLOBAL_HISTORY).undo_redo->set_commit_notify_callback(_undo_redo_callback, this);
} break;
case NOTIFICATION_ENTER_TREE: {
@@ -680,7 +681,7 @@ void EditorSettingsDialog::_bind_methods() {
EditorSettingsDialog::EditorSettingsDialog() {
set_title(TTR("Editor Settings"));
- undo_redo = memnew(UndoRedo);
+ undo_redo = EditorNode::get_undo_redo();
tabs = memnew(TabContainer);
tabs->set_theme_type_variation("TabContainerOdd");
@@ -776,5 +777,4 @@ EditorSettingsDialog::EditorSettingsDialog() {
}
EditorSettingsDialog::~EditorSettingsDialog() {
- memdelete(undo_redo);
}
diff --git a/editor/editor_settings_dialog.h b/editor/editor_settings_dialog.h
index a1ea54c6fb..87ed6a77eb 100644
--- a/editor/editor_settings_dialog.h
+++ b/editor/editor_settings_dialog.h
@@ -40,6 +40,8 @@
#include "scene/gui/tab_container.h"
#include "scene/gui/texture_rect.h"
+class EditorUndoRedoManager;
+
class EditorSettingsDialog : public AcceptDialog {
GDCLASS(EditorSettingsDialog, AcceptDialog);
@@ -73,7 +75,7 @@ class EditorSettingsDialog : public AcceptDialog {
Timer *timer = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
virtual void cancel_pressed() override;
virtual void ok_pressed() override;
diff --git a/editor/editor_spin_slider.cpp b/editor/editor_spin_slider.cpp
index 20e9d7a3df..5b98460e8e 100644
--- a/editor/editor_spin_slider.cpp
+++ b/editor/editor_spin_slider.cpp
@@ -605,6 +605,10 @@ bool EditorSpinSlider::is_flat() const {
return flat;
}
+bool EditorSpinSlider::is_grabbing() const {
+ return grabbing_grabber || grabbing_spinner;
+}
+
void EditorSpinSlider::_focus_entered() {
_ensure_input_popup();
Rect2 gr = get_screen_rect();
diff --git a/editor/editor_spin_slider.h b/editor/editor_spin_slider.h
index f0adf5b7a1..afcaa3e4b6 100644
--- a/editor/editor_spin_slider.h
+++ b/editor/editor_spin_slider.h
@@ -110,6 +110,8 @@ public:
void set_flat(bool p_enable);
bool is_flat() const;
+ bool is_grabbing() const;
+
void setup_and_show() { _focus_entered(); }
LineEdit *get_line_edit();
diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp
index c58d1263f3..827a657a31 100644
--- a/editor/editor_themes.cpp
+++ b/editor/editor_themes.cpp
@@ -32,7 +32,6 @@
#include "core/error/error_macros.h"
#include "core/io/resource_loader.h"
-#include "core/variant/dictionary.h"
#include "editor/editor_fonts.h"
#include "editor/editor_icons.gen.h"
#include "editor/editor_scale.h"
@@ -43,6 +42,118 @@
#include "modules/svg/image_loader_svg.h"
#endif
+HashMap<Color, Color> EditorColorMap::editor_color_map;
+
+void EditorColorMap::add_color_pair(const String p_from_color, const String p_to_color) {
+ editor_color_map[Color::html(p_from_color)] = Color::html(p_to_color);
+}
+
+void EditorColorMap::create() {
+ // Some of the colors below are listed for completeness sake.
+ // This can be a basis for proper palette validation later.
+
+ // Convert: FROM TO
+ add_color_pair("#478cbf", "#478cbf"); // Godot Blue
+ add_color_pair("#414042", "#414042"); // Godot Gray
+
+ add_color_pair("#ffffff", "#414141"); // Pure white
+ add_color_pair("#000000", "#bfbfbf"); // Pure black
+ // Keep pure RGB colors as is, but list them for explicitly.
+ add_color_pair("#ff0000", "#ff0000"); // Pure red
+ add_color_pair("#00ff00", "#00ff00"); // Pure green
+ add_color_pair("#0000ff", "#0000ff"); // Pure blue
+
+ // GUI Colors
+ add_color_pair("#e0e0e0", "#5a5a5a"); // Common icon color
+ add_color_pair("#fefefe", "#fefefe"); // Forced light color
+ add_color_pair("#808080", "#808080"); // GUI disabled color
+ add_color_pair("#b3b3b3", "#363636"); // GUI disabled light color
+ add_color_pair("#699ce8", "#699ce8"); // GUI highlight color
+ add_color_pair("#f9f9f9", "#606060"); // Scrollbar grabber highlight color
+
+ add_color_pair("#c38ef1", "#a85de9"); // Animation
+ add_color_pair("#fc7f7f", "#cd3838"); // Spatial
+ add_color_pair("#8da5f3", "#3d64dd"); // 2D
+ add_color_pair("#4b70ea", "#1a3eac"); // 2D Dark
+ add_color_pair("#8eef97", "#2fa139"); // Control
+
+ add_color_pair("#5fb2ff", "#0079f0"); // Selection (blue)
+ add_color_pair("#003e7a", "#2b74bb"); // Selection (darker blue)
+ add_color_pair("#f7f5cf", "#615f3a"); // Gizmo (yellow)
+
+ // Rainbow
+ add_color_pair("#ff4545", "#ff2929"); // Red
+ add_color_pair("#ffe345", "#ffe337"); // Yellow
+ add_color_pair("#80ff45", "#74ff34"); // Green
+ add_color_pair("#45ffa2", "#2cff98"); // Aqua
+ add_color_pair("#45d7ff", "#22ccff"); // Blue
+ add_color_pair("#8045ff", "#702aff"); // Purple
+ add_color_pair("#ff4596", "#ff2781"); // Pink
+
+ // Audio gradients
+ add_color_pair("#e1da5b", "#d6cf4b"); // Yellow
+
+ add_color_pair("#62aeff", "#1678e0"); // Frozen gradient top
+ add_color_pair("#75d1e6", "#41acc5"); // Frozen gradient middle
+ add_color_pair("#84ffee", "#49ccba"); // Frozen gradient bottom
+
+ add_color_pair("#f70000", "#c91616"); // Color track red
+ add_color_pair("#eec315", "#d58c0b"); // Color track orange
+ add_color_pair("#dbee15", "#b7d10a"); // Color track yellow
+ add_color_pair("#288027", "#218309"); // Color track green
+
+ // Resource groups
+ add_color_pair("#ffca5f", "#fea900"); // Mesh resource (orange)
+ add_color_pair("#2998ff", "#68b6ff"); // Shape resource (blue)
+ add_color_pair("#a2d2ff", "#4998e3"); // Shape resource (light blue)
+
+ // Animation editor tracks
+ // The property track icon color is set by the common icon color.
+ add_color_pair("#ea7940", "#bd5e2c"); // 3D Position track
+ add_color_pair("#ff2b88", "#bd165f"); // 3D Rotation track
+ add_color_pair("#eac840", "#bd9d1f"); // 3D Scale track
+ add_color_pair("#3cf34e", "#16a827"); // Call Method track
+ add_color_pair("#2877f6", "#236be6"); // Bezier Curve track
+ add_color_pair("#eae440", "#9f9722"); // Audio Playback track
+ add_color_pair("#a448f0", "#9853ce"); // Animation Playback track
+ add_color_pair("#5ad5c4", "#0a9c88"); // Blend Shape track
+
+ // Control layouts
+ add_color_pair("#d6d6d6", "#474747"); // Highlighted part
+ add_color_pair("#474747", "#d6d6d6"); // Background part
+ add_color_pair("#919191", "#6e6e6e"); // Border part
+
+ // TileSet editor icons
+ add_color_pair("#fce00e", "#aa8d24"); // New Single Tile
+ add_color_pair("#0e71fc", "#0350bd"); // New Autotile
+ add_color_pair("#c6ced4", "#828f9b"); // New Atlas
+
+ // Visual script
+ add_color_pair("#41ecad", "#25e3a0"); // VisualScript variant
+ add_color_pair("#6f91f0", "#6d8eeb"); // VisualScript bool
+ add_color_pair("#5abbef", "#4fb2e9"); // VisualScript int
+ add_color_pair("#35d4f4", "#27ccf0"); // VisualScript float
+ add_color_pair("#4593ec", "#4690e7"); // VisualScript String
+ add_color_pair("#ac73f1", "#ad76ee"); // VisualScript Vector2
+ add_color_pair("#f1738f", "#ee758e"); // VisualScript Rect2
+ add_color_pair("#de66f0", "#dc6aed"); // VisualScript Vector3
+ add_color_pair("#b9ec41", "#96ce1a"); // VisualScript Transform2D
+ add_color_pair("#f74949", "#f77070"); // VisualScript Plane
+ add_color_pair("#ec418e", "#ec69a3"); // VisualScript Quat
+ add_color_pair("#ee5677", "#ee7991"); // VisualScript AABB
+ add_color_pair("#e1ec41", "#b2bb19"); // VisualScript Basis
+ add_color_pair("#f68f45", "#f49047"); // VisualScript Transform
+ add_color_pair("#417aec", "#6993ec"); // VisualScript NodePath
+ add_color_pair("#41ec80", "#2ce573"); // VisualScript RID
+ add_color_pair("#55f3e3", "#12d5c3"); // VisualScript Object
+ add_color_pair("#54ed9e", "#57e99f"); // VisualScript Dictionary
+ // Visual shaders
+ add_color_pair("#77ce57", "#67c046"); // Vector funcs
+ add_color_pair("#ea686c", "#d95256"); // Vector transforms
+ add_color_pair("#eac968", "#d9b64f"); // Textures and cubemaps
+ add_color_pair("#cf68ea", "#c050dd"); // Functions and expressions
+}
+
static Ref<StyleBoxTexture> make_stylebox(Ref<Texture2D> p_texture, float p_left, float p_top, float p_right, float p_bottom, float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_bottom = -1, bool p_draw_center = true) {
Ref<StyleBoxTexture> style(memnew(StyleBoxTexture));
style->set_texture(p_texture);
@@ -113,7 +224,7 @@ static Ref<Texture2D> flip_icon(Ref<Texture2D> p_texture, bool p_flip_y = false,
#ifdef MODULE_SVG_ENABLED
// See also `generate_icon()` in `scene/resources/default_theme.cpp`.
-static Ref<ImageTexture> editor_generate_icon(int p_index, bool p_convert_color, float p_scale = EDSCALE, float p_saturation = 1.0, Dictionary p_convert_colors = Dictionary()) {
+static Ref<ImageTexture> editor_generate_icon(int p_index, float p_scale, float p_saturation, const HashMap<Color, Color> &p_convert_colors = HashMap<Color, Color>()) {
Ref<Image> img = memnew(Image);
// Upsample icon generation only if the editor scale isn't an integer multiplier.
@@ -121,8 +232,7 @@ static Ref<ImageTexture> editor_generate_icon(int p_index, bool p_convert_color,
// with integer editor scales.
const bool upsample = !Math::is_equal_approx(Math::round(p_scale), p_scale);
ImageLoaderSVG img_loader;
- img_loader.set_replace_colors(p_convert_colors);
- img_loader.create_image_from_string(img, editor_icons_sources[p_index], p_scale, upsample, p_convert_color);
+ img_loader.create_image_from_string(img, editor_icons_sources[p_index], p_scale, upsample, p_convert_colors);
if (p_saturation != 1.0) {
img->adjust_bcs(1.0, 1.0, p_saturation);
}
@@ -132,126 +242,18 @@ static Ref<ImageTexture> editor_generate_icon(int p_index, bool p_convert_color,
}
#endif
-#ifndef ADD_CONVERT_COLOR
-#define ADD_CONVERT_COLOR(dictionary, old_color, new_color) dictionary[Color::html(old_color)] = Color::html(new_color)
-#endif
-
void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme = true, int p_thumb_size = 32, bool p_only_thumbs = false, float p_icon_saturation = 1.0) {
#ifdef MODULE_SVG_ENABLED
- // The default icon theme is designed to be used for a dark theme.
- // This dictionary stores Color values to convert to other colors
- // for better readability on a light theme.
- // Godot Color values are used to avoid the ambiguity of strings
- // (where "#ffffff", "fff", and "white" are all equivalent).
- Dictionary dark_icon_color_dictionary;
+ HashMap<Color, Color> icon_color_map;
// The names of the icons to never convert, even if one of their colors
// are contained in the dictionary above.
HashSet<StringName> exceptions;
- // Some of the colors below are listed for completeness sake.
- // This can be a basis for proper palette validation later.
if (!p_dark_theme) {
- // Convert color: FROM TO
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#478cbf", "#478cbf"); // Godot Blue
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#414042", "#414042"); // Godot Gray
-
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ffffff", "#414141"); // Pure white
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#000000", "#bfbfbf"); // Pure black
- // Keep pure RGB colors as is, but list them for explicitly.
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ff0000", "#ff0000"); // Pure red
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#00ff00", "#00ff00"); // Pure green
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#0000ff", "#0000ff"); // Pure blue
-
- // GUI Colors
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#e0e0e0", "#5a5a5a"); // Common icon color
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#fefefe", "#fefefe"); // Forced light color
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#808080", "#808080"); // GUI disabled color
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#b3b3b3", "#363636"); // GUI disabled light color
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#699ce8", "#699ce8"); // GUI highlight color
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#f9f9f9", "#606060"); // Scrollbar grabber highlight color
-
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#c38ef1", "#a85de9"); // Animation
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#fc7f7f", "#cd3838"); // Spatial
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#8da5f3", "#3d64dd"); // 2D
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#4b70ea", "#1a3eac"); // 2D Dark
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#8eef97", "#2fa139"); // Control
-
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#5fb2ff", "#0079f0"); // Selection (blue)
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#003e7a", "#2b74bb"); // Selection (darker blue)
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#f7f5cf", "#615f3a"); // Gizmo (yellow)
-
- // Rainbow
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ff4545", "#ff2929"); // Red
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ffe345", "#ffe337"); // Yellow
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#80ff45", "#74ff34"); // Green
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#45ffa2", "#2cff98"); // Aqua
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#45d7ff", "#22ccff"); // Blue
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#8045ff", "#702aff"); // Purple
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ff4596", "#ff2781"); // Pink
-
- // Audio gradients
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#e1da5b", "#d6cf4b"); // Yellow
-
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#62aeff", "#1678e0"); // Frozen gradient top
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#75d1e6", "#41acc5"); // Frozen gradient middle
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#84ffee", "#49ccba"); // Frozen gradient bottom
-
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#f70000", "#c91616"); // Color track red
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#eec315", "#d58c0b"); // Color track orange
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#dbee15", "#b7d10a"); // Color track yellow
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#288027", "#218309"); // Color track green
-
- // Resource groups
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ffca5f", "#fea900"); // Mesh resource (orange)
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#2998ff", "#68b6ff"); // Shape resource (blue)
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#a2d2ff", "#4998e3"); // Shape resource (light blue)
-
- // Animation editor tracks
- // The property track icon color is set by the common icon color.
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ea7940", "#bd5e2c"); // 3D Position track
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ff2b88", "#bd165f"); // 3D Rotation track
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#eac840", "#bd9d1f"); // 3D Scale track
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#3cf34e", "#16a827"); // Call Method track
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#2877f6", "#236be6"); // Bezier Curve track
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#eae440", "#9f9722"); // Audio Playback track
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#a448f0", "#9853ce"); // Animation Playback track
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#5ad5c4", "#0a9c88"); // Blend Shape track
-
- // Control layouts
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#d6d6d6", "#474747"); // Highlighted part
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#474747", "#d6d6d6"); // Background part
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#919191", "#6e6e6e"); // Border part
-
- // TileSet editor icons
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#fce00e", "#aa8d24"); // New Single Tile
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#0e71fc", "#0350bd"); // New Autotile
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#c6ced4", "#828f9b"); // New Atlas
-
- // Visual script
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#41ecad", "#25e3a0"); // VisualScript variant
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#6f91f0", "#6d8eeb"); // VisualScript bool
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#5abbef", "#4fb2e9"); // VisualScript int
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#35d4f4", "#27ccf0"); // VisualScript float
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#4593ec", "#4690e7"); // VisualScript String
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ac73f1", "#ad76ee"); // VisualScript Vector2
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#f1738f", "#ee758e"); // VisualScript Rect2
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#de66f0", "#dc6aed"); // VisualScript Vector3
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#b9ec41", "#96ce1a"); // VisualScript Transform2D
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#f74949", "#f77070"); // VisualScript Plane
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ec418e", "#ec69a3"); // VisualScript Quat
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ee5677", "#ee7991"); // VisualScript AABB
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#e1ec41", "#b2bb19"); // VisualScript Basis
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#f68f45", "#f49047"); // VisualScript Transform
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#417aec", "#6993ec"); // VisualScript NodePath
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#41ec80", "#2ce573"); // VisualScript RID
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#55f3e3", "#12d5c3"); // VisualScript Object
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#54ed9e", "#57e99f"); // VisualScript Dictionary
- // Visual shaders
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#77ce57", "#67c046"); // Vector funcs
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#ea686c", "#d95256"); // Vector transforms
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#eac968", "#d9b64f"); // Textures and cubemaps
- ADD_CONVERT_COLOR(dark_icon_color_dictionary, "#cf68ea", "#c050dd"); // Functions and expressions
+ for (KeyValue<Color, Color> &E : EditorColorMap::get()) {
+ icon_color_map[E.key] = E.value;
+ }
exceptions.insert("EditorPivot");
exceptions.insert("EditorHandle");
@@ -291,18 +293,18 @@ void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme =
const Color error_color = p_theme->get_color(SNAME("error_color"), SNAME("Editor"));
const Color success_color = p_theme->get_color(SNAME("success_color"), SNAME("Editor"));
const Color warning_color = p_theme->get_color(SNAME("warning_color"), SNAME("Editor"));
- dark_icon_color_dictionary[Color::html("#ff5f5f")] = error_color;
- dark_icon_color_dictionary[Color::html("#5fff97")] = success_color;
- dark_icon_color_dictionary[Color::html("#ffdd65")] = warning_color;
+ icon_color_map[Color::html("#ff5f5f")] = error_color;
+ icon_color_map[Color::html("#5fff97")] = success_color;
+ icon_color_map[Color::html("#ffdd65")] = warning_color;
// Use the accent color for some icons (checkbox, radio, toggle, etc.).
- Dictionary accent_color_icon_color_dictionary;
+ HashMap<Color, Color> accent_color_map;
HashSet<StringName> accent_color_icons;
const Color accent_color = p_theme->get_color(SNAME("accent_color"), SNAME("Editor"));
- accent_color_icon_color_dictionary[Color::html("699ce8")] = accent_color;
+ accent_color_map[Color::html("699ce8")] = accent_color;
if (accent_color.get_luminance() > 0.75) {
- accent_color_icon_color_dictionary[Color::html("ffffff")] = Color(0.2, 0.2, 0.2);
+ accent_color_map[Color::html("ffffff")] = Color(0.2, 0.2, 0.2);
}
accent_color_icons.insert("GuiChecked");
@@ -318,7 +320,7 @@ void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme =
Ref<ImageTexture> icon;
if (accent_color_icons.has(editor_icons_names[i])) {
- icon = editor_generate_icon(i, true, EDSCALE, 1.0, accent_color_icon_color_dictionary);
+ icon = editor_generate_icon(i, EDSCALE, 1.0, accent_color_map);
} else {
float saturation = p_icon_saturation;
@@ -327,7 +329,11 @@ void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme =
}
const int is_exception = exceptions.has(editor_icons_names[i]);
- icon = editor_generate_icon(i, !is_exception, EDSCALE, saturation, dark_icon_color_dictionary);
+ if (is_exception) {
+ icon = editor_generate_icon(i, EDSCALE, saturation);
+ } else {
+ icon = editor_generate_icon(i, EDSCALE, saturation, icon_color_map);
+ }
}
p_theme->set_icon(editor_icons_names[i], SNAME("EditorIcons"), icon);
@@ -342,7 +348,13 @@ void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme =
for (int i = 0; i < editor_bg_thumbs_count; i++) {
const int index = editor_bg_thumbs_indices[i];
const int is_exception = exceptions.has(editor_icons_names[index]);
- const Ref<ImageTexture> icon = editor_generate_icon(index, !p_dark_theme && !is_exception, scale, force_filter, dark_icon_color_dictionary);
+
+ Ref<ImageTexture> icon;
+ if (!p_dark_theme && !is_exception) {
+ icon = editor_generate_icon(index, scale, force_filter, icon_color_map);
+ } else {
+ icon = editor_generate_icon(index, scale, force_filter);
+ }
p_theme->set_icon(editor_icons_names[index], SNAME("EditorIcons"), icon);
}
@@ -351,7 +363,13 @@ void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme =
for (int i = 0; i < editor_md_thumbs_count; i++) {
const int index = editor_md_thumbs_indices[i];
const bool is_exception = exceptions.has(editor_icons_names[index]);
- const Ref<ImageTexture> icon = editor_generate_icon(index, !p_dark_theme && !is_exception, scale, force_filter, dark_icon_color_dictionary);
+
+ Ref<ImageTexture> icon;
+ if (!p_dark_theme && !is_exception) {
+ icon = editor_generate_icon(index, scale, force_filter, icon_color_map);
+ } else {
+ icon = editor_generate_icon(index, scale, force_filter);
+ }
p_theme->set_icon(editor_icons_names[index], SNAME("EditorIcons"), icon);
}
@@ -518,8 +536,8 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
Color warning_color = Color(1, 0.87, 0.4);
Color error_color = Color(1, 0.47, 0.42);
Color property_color = font_color.lerp(Color(0.5, 0.5, 0.5), 0.5);
- Color readonly_color = property_color.lerp(dark_theme ? Color(0, 0, 0) : Color(1, 1, 1), 0.5);
- Color readonly_warning_color = error_color.lerp(dark_theme ? Color(0, 0, 0) : Color(1, 1, 1), 0.5);
+ Color readonly_color = property_color.lerp(dark_theme ? Color(0, 0, 0) : Color(1, 1, 1), 0.25);
+ Color readonly_warning_color = error_color.lerp(dark_theme ? Color(0, 0, 0) : Color(1, 1, 1), 0.25);
if (!dark_theme) {
// Darken some colors to be readable on a light background
@@ -788,6 +806,25 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
editor_log_button_pressed->set_border_color(accent_color);
theme->set_stylebox("pressed", "EditorLogFilterButton", editor_log_button_pressed);
+ // MenuBar
+ theme->set_stylebox("normal", "MenuBar", style_widget);
+ theme->set_stylebox("hover", "MenuBar", style_widget_hover);
+ theme->set_stylebox("pressed", "MenuBar", style_widget_pressed);
+ theme->set_stylebox("focus", "MenuBar", style_widget_focus);
+ theme->set_stylebox("disabled", "MenuBar", style_widget_disabled);
+
+ theme->set_color("font_color", "MenuBar", font_color);
+ theme->set_color("font_hover_color", "MenuBar", font_hover_color);
+ theme->set_color("font_focus_color", "MenuBar", font_focus_color);
+ theme->set_color("font_pressed_color", "MenuBar", accent_color);
+ theme->set_color("font_disabled_color", "MenuBar", font_disabled_color);
+
+ theme->set_color("icon_normal_color", "MenuBar", icon_normal_color);
+ theme->set_color("icon_hover_color", "MenuBar", icon_hover_color);
+ theme->set_color("icon_focus_color", "MenuBar", icon_focus_color);
+ theme->set_color("icon_pressed_color", "MenuBar", icon_pressed_color);
+ theme->set_color("icon_disabled_color", "MenuBar", icon_disabled_color);
+
// OptionButton
Ref<StyleBoxFlat> style_option_button_focus = style_widget_focus->duplicate();
Ref<StyleBoxFlat> style_option_button_normal = style_widget->duplicate();
@@ -912,6 +949,9 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
// Always display a border for PopupMenus so they can be distinguished from their background.
style_popup_menu->set_border_width_all(EDSCALE);
style_popup_menu->set_border_color(dark_color_2);
+ // Popups are separate windows by default in the editor. Windows currently don't support per-pixel transparency
+ // in 4.0, and even if it was, it may not always work in practice (e.g. running with compositing disabled).
+ style_popup_menu->set_corner_radius_all(0);
theme->set_stylebox("panel", "PopupMenu", style_popup_menu);
Ref<StyleBoxFlat> style_menu_hover = style_widget_hover->duplicate();
@@ -1460,6 +1500,17 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
// PopupPanel
theme->set_stylebox("panel", "PopupPanel", style_popup);
+ Ref<StyleBoxFlat> control_editor_popup_style = style_popup->duplicate();
+ control_editor_popup_style->set_shadow_size(0);
+ control_editor_popup_style->set_default_margin(SIDE_LEFT, default_margin_size * EDSCALE);
+ control_editor_popup_style->set_default_margin(SIDE_TOP, default_margin_size * EDSCALE);
+ control_editor_popup_style->set_default_margin(SIDE_RIGHT, default_margin_size * EDSCALE);
+ control_editor_popup_style->set_default_margin(SIDE_BOTTOM, default_margin_size * EDSCALE);
+ control_editor_popup_style->set_border_width_all(0);
+
+ theme->set_stylebox("panel", "ControlEditorPopupButton", control_editor_popup_style);
+ theme->set_type_variation("ControlEditorPopupButton", "PopupPanel");
+
// SpinBox
theme->set_icon("updown", "SpinBox", theme->get_icon(SNAME("GuiSpinboxUpdown"), SNAME("EditorIcons")));
theme->set_icon("updown_disabled", "SpinBox", theme->get_icon(SNAME("GuiSpinboxUpdownDisabled"), SNAME("EditorIcons")));
@@ -1816,14 +1867,14 @@ Ref<Theme> create_custom_theme(const Ref<Theme> p_theme) {
return theme;
}
-Ref<ImageTexture> create_unscaled_default_project_icon() {
-#ifdef MODULE_SVG_ENABLED
+/**
+ * Returns the SVG code for the default project icon.
+ */
+String get_default_project_icon() {
for (int i = 0; i < editor_icons_count; i++) {
- // ESCALE should never affect size of the icon
if (strcmp(editor_icons_names[i], "DefaultProjectIcon") == 0) {
- return editor_generate_icon(i, false, 1.0);
+ return String(editor_icons_sources[i]);
}
}
-#endif
- return Ref<ImageTexture>(memnew(ImageTexture));
+ return String();
}
diff --git a/editor/editor_themes.h b/editor/editor_themes.h
index 95184b9d4a..37db8160fa 100644
--- a/editor/editor_themes.h
+++ b/editor/editor_themes.h
@@ -34,10 +34,24 @@
#include "scene/resources/texture.h"
#include "scene/resources/theme.h"
+// The default icon theme is designed to be used for a dark theme. This map stores
+// Color values to convert to other colors for better readability on a light theme.
+class EditorColorMap {
+ // Godot Color values are used to avoid the ambiguity of strings
+ // (where "#ffffff", "fff", and "white" are all equivalent).
+ static HashMap<Color, Color> editor_color_map;
+
+public:
+ static void create();
+ static void add_color_pair(const String p_from_color, const String p_to_color);
+
+ static HashMap<Color, Color> &get() { return editor_color_map; };
+};
+
Ref<Theme> create_editor_theme(Ref<Theme> p_theme = nullptr);
Ref<Theme> create_custom_theme(Ref<Theme> p_theme = nullptr);
-Ref<ImageTexture> create_unscaled_default_project_icon();
+String get_default_project_icon();
#endif // EDITOR_THEMES_H
diff --git a/editor/editor_undo_redo_manager.cpp b/editor/editor_undo_redo_manager.cpp
new file mode 100644
index 0000000000..eca2b3143b
--- /dev/null
+++ b/editor/editor_undo_redo_manager.cpp
@@ -0,0 +1,442 @@
+/*************************************************************************/
+/* editor_undo_redo_manager.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 "editor_undo_redo_manager.h"
+
+#include "core/io/resource.h"
+#include "core/os/os.h"
+#include "core/templates/local_vector.h"
+#include "editor/editor_log.h"
+#include "editor/editor_node.h"
+#include "scene/main/node.h"
+
+EditorUndoRedoManager::History &EditorUndoRedoManager::get_or_create_history(int p_idx) {
+ if (!history_map.has(p_idx)) {
+ History history;
+ history.undo_redo = memnew(UndoRedo);
+ history.id = p_idx;
+ history_map[p_idx] = history;
+
+ EditorNode::get_singleton()->get_log()->register_undo_redo(history.undo_redo);
+ EditorDebuggerNode::get_singleton()->register_undo_redo(history.undo_redo);
+ }
+ return history_map[p_idx];
+}
+
+UndoRedo *EditorUndoRedoManager::get_history_undo_redo(int p_idx) const {
+ ERR_FAIL_COND_V(!history_map.has(p_idx), nullptr);
+ return history_map[p_idx].undo_redo;
+}
+
+int EditorUndoRedoManager::get_history_id_for_object(Object *p_object) const {
+ int history_id = INVALID_HISTORY;
+
+ if (Node *node = Object::cast_to<Node>(p_object)) {
+ Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
+
+ if (edited_scene && (node == edited_scene || edited_scene->is_ancestor_of(node))) {
+ int idx = EditorNode::get_singleton()->get_editor_data().get_current_edited_scene_history_id();
+ if (idx > 0) {
+ history_id = idx;
+ }
+ }
+ }
+
+ if (Resource *res = Object::cast_to<Resource>(p_object)) {
+ if (res->is_built_in()) {
+ if (res->get_path().is_empty()) {
+ int idx = EditorNode::get_singleton()->get_editor_data().get_current_edited_scene_history_id();
+ if (idx > 0) {
+ history_id = idx;
+ }
+ } else {
+ int idx = EditorNode::get_singleton()->get_editor_data().get_scene_history_id_from_path(res->get_path().get_slice("::", 0));
+ if (idx > 0) {
+ history_id = idx;
+ }
+ }
+ }
+ }
+
+ if (history_id == INVALID_HISTORY) {
+ if (pending_action.history_id != INVALID_HISTORY) {
+ history_id = pending_action.history_id;
+ } else {
+ history_id = GLOBAL_HISTORY;
+ }
+ }
+ return history_id;
+}
+
+EditorUndoRedoManager::History &EditorUndoRedoManager::get_history_for_object(Object *p_object) {
+ int history_id = get_history_id_for_object(p_object);
+ ERR_FAIL_COND_V_MSG(pending_action.history_id != INVALID_HISTORY && history_id != pending_action.history_id, get_or_create_history(pending_action.history_id), vformat("UndoRedo history mismatch: expected %d, got %d.", pending_action.history_id, history_id));
+
+ History &history = get_or_create_history(history_id);
+ if (pending_action.history_id == INVALID_HISTORY) {
+ pending_action.history_id = history_id;
+ history.undo_redo->create_action(pending_action.action_name, pending_action.merge_mode);
+ }
+
+ return history;
+}
+
+void EditorUndoRedoManager::create_action_for_history(const String &p_name, int p_history_id, UndoRedo::MergeMode p_mode) {
+ pending_action.action_name = p_name;
+ pending_action.timestamp = OS::get_singleton()->get_unix_time();
+ pending_action.merge_mode = p_mode;
+
+ if (p_history_id != INVALID_HISTORY) {
+ pending_action.history_id = p_history_id;
+ History &history = get_or_create_history(p_history_id);
+ history.undo_redo->create_action(pending_action.action_name, pending_action.merge_mode);
+ }
+}
+
+void EditorUndoRedoManager::create_action(const String &p_name, UndoRedo::MergeMode p_mode, Object *p_custom_context) {
+ create_action_for_history(p_name, INVALID_HISTORY, p_mode);
+
+ if (p_custom_context) {
+ // This assigns context to pending action.
+ get_history_for_object(p_custom_context);
+ }
+}
+
+void EditorUndoRedoManager::add_do_methodp(Object *p_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
+ UndoRedo *undo_redo = get_history_for_object(p_object).undo_redo;
+ undo_redo->add_do_methodp(p_object, p_method, p_args, p_argcount);
+}
+
+void EditorUndoRedoManager::add_undo_methodp(Object *p_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
+ UndoRedo *undo_redo = get_history_for_object(p_object).undo_redo;
+ undo_redo->add_undo_methodp(p_object, p_method, p_args, p_argcount);
+}
+
+void EditorUndoRedoManager::_add_do_method(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
+ if (p_argcount < 2) {
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 0;
+ return;
+ }
+
+ if (p_args[0]->get_type() != Variant::OBJECT) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ return;
+ }
+
+ if (p_args[1]->get_type() != Variant::STRING_NAME && p_args[1]->get_type() != Variant::STRING) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING_NAME;
+ return;
+ }
+
+ r_error.error = Callable::CallError::CALL_OK;
+
+ Object *object = *p_args[0];
+ StringName method = *p_args[1];
+
+ add_do_methodp(object, method, p_args + 2, p_argcount - 2);
+}
+
+void EditorUndoRedoManager::_add_undo_method(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
+ if (p_argcount < 2) {
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 0;
+ return;
+ }
+
+ if (p_args[0]->get_type() != Variant::OBJECT) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ return;
+ }
+
+ if (p_args[1]->get_type() != Variant::STRING_NAME && p_args[1]->get_type() != Variant::STRING) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING_NAME;
+ return;
+ }
+
+ r_error.error = Callable::CallError::CALL_OK;
+
+ Object *object = *p_args[0];
+ StringName method = *p_args[1];
+
+ add_undo_methodp(object, method, p_args + 2, p_argcount - 2);
+}
+
+void EditorUndoRedoManager::add_do_property(Object *p_object, const StringName &p_property, const Variant &p_value) {
+ UndoRedo *undo_redo = get_history_for_object(p_object).undo_redo;
+ undo_redo->add_do_property(p_object, p_property, p_value);
+}
+
+void EditorUndoRedoManager::add_undo_property(Object *p_object, const StringName &p_property, const Variant &p_value) {
+ UndoRedo *undo_redo = get_history_for_object(p_object).undo_redo;
+ undo_redo->add_undo_property(p_object, p_property, p_value);
+}
+
+void EditorUndoRedoManager::add_do_reference(Object *p_object) {
+ UndoRedo *undo_redo = get_history_for_object(p_object).undo_redo;
+ undo_redo->add_do_reference(p_object);
+}
+
+void EditorUndoRedoManager::add_undo_reference(Object *p_object) {
+ UndoRedo *undo_redo = get_history_for_object(p_object).undo_redo;
+ undo_redo->add_undo_reference(p_object);
+}
+
+void EditorUndoRedoManager::commit_action(bool p_execute) {
+ ERR_FAIL_COND(pending_action.history_id == INVALID_HISTORY);
+ is_committing = true;
+
+ History &history = get_or_create_history(pending_action.history_id);
+ history.undo_redo->commit_action(p_execute);
+ history.redo_stack.clear();
+
+ if (!history.undo_stack.is_empty()) {
+ const Action &prev_action = history.undo_stack.back()->get();
+ if (pending_action.merge_mode != UndoRedo::MERGE_DISABLE && pending_action.merge_mode == prev_action.merge_mode && pending_action.action_name == prev_action.action_name) {
+ // Discard action if it should be merged (UndoRedo handles merging internally).
+ pending_action = Action();
+ is_committing = false;
+ return;
+ }
+ }
+
+ history.undo_stack.push_back(pending_action);
+ pending_action = Action();
+ is_committing = false;
+}
+
+bool EditorUndoRedoManager::is_committing_action() const {
+ return is_committing;
+}
+
+bool EditorUndoRedoManager::undo() {
+ if (!has_undo()) {
+ return false;
+ }
+
+ History *selected_history = nullptr;
+ double global_timestamp = 0;
+
+ // Pick the history with greatest last action timestamp (either global or current scene).
+ {
+ History &history = get_or_create_history(GLOBAL_HISTORY);
+ if (!history.undo_stack.is_empty()) {
+ selected_history = &history;
+ global_timestamp = history.undo_stack.back()->get().timestamp;
+ }
+ }
+
+ {
+ History &history = get_or_create_history(EditorNode::get_editor_data().get_current_edited_scene_history_id());
+ if (!history.undo_stack.is_empty() && history.undo_stack.back()->get().timestamp > global_timestamp) {
+ selected_history = &history;
+ }
+ }
+
+ if (selected_history) {
+ Action action = selected_history->undo_stack.back()->get();
+ selected_history->undo_stack.pop_back();
+ selected_history->redo_stack.push_back(action);
+ return selected_history->undo_redo->undo();
+ }
+ return false;
+}
+
+bool EditorUndoRedoManager::redo() {
+ if (!has_redo()) {
+ return false;
+ }
+
+ History *selected_history = nullptr;
+ double global_timestamp = INFINITY;
+
+ // Pick the history with lowest last action timestamp (either global or current scene).
+ {
+ History &history = get_or_create_history(GLOBAL_HISTORY);
+ if (!history.redo_stack.is_empty()) {
+ selected_history = &history;
+ global_timestamp = history.redo_stack.back()->get().timestamp;
+ }
+ }
+
+ {
+ History &history = get_or_create_history(EditorNode::get_editor_data().get_current_edited_scene_history_id());
+ if (!history.redo_stack.is_empty() && history.redo_stack.back()->get().timestamp < global_timestamp) {
+ selected_history = &history;
+ }
+ }
+
+ if (selected_history) {
+ Action action = selected_history->redo_stack.back()->get();
+ selected_history->redo_stack.pop_back();
+ selected_history->undo_stack.push_back(action);
+ return selected_history->undo_redo->redo();
+ }
+ return false;
+}
+
+void EditorUndoRedoManager::set_history_as_saved(int p_id) {
+ History &history = get_or_create_history(p_id);
+ history.saved_version = history.undo_redo->get_version();
+}
+
+void EditorUndoRedoManager::set_history_as_unsaved(int p_id) {
+ History &history = get_or_create_history(p_id);
+ history.saved_version = -1;
+}
+
+bool EditorUndoRedoManager::is_history_unsaved(int p_id) {
+ History &history = get_or_create_history(p_id);
+ return history.undo_redo->get_version() != history.saved_version;
+}
+
+bool EditorUndoRedoManager::has_undo() {
+ for (const KeyValue<int, History> &E : history_map) {
+ if ((E.key == GLOBAL_HISTORY || E.key == EditorNode::get_editor_data().get_current_edited_scene_history_id()) && !E.value.undo_stack.is_empty()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool EditorUndoRedoManager::has_redo() {
+ for (const KeyValue<int, History> &E : history_map) {
+ if ((E.key == GLOBAL_HISTORY || E.key == EditorNode::get_editor_data().get_current_edited_scene_history_id()) && !E.value.redo_stack.is_empty()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+void EditorUndoRedoManager::clear_history(bool p_increase_version, int p_idx) {
+ if (p_idx != INVALID_HISTORY) {
+ get_or_create_history(p_idx).undo_redo->clear_history(p_increase_version);
+ if (!p_increase_version) {
+ set_history_as_saved(p_idx);
+ }
+ return;
+ }
+
+ for (const KeyValue<int, History> &E : history_map) {
+ E.value.undo_redo->clear_history(p_increase_version);
+ set_history_as_saved(E.key);
+ }
+}
+
+String EditorUndoRedoManager::get_current_action_name() {
+ if (has_undo()) {
+ History *selected_history = nullptr;
+ double global_timestamp = 0;
+
+ // Pick the history with greatest last action timestamp (either global or current scene).
+ {
+ History &history = get_or_create_history(GLOBAL_HISTORY);
+ if (!history.undo_stack.is_empty()) {
+ selected_history = &history;
+ global_timestamp = history.undo_stack.back()->get().timestamp;
+ }
+ }
+
+ {
+ History &history = get_or_create_history(EditorNode::get_editor_data().get_current_edited_scene_history_id());
+ if (!history.undo_stack.is_empty() && history.undo_stack.back()->get().timestamp > global_timestamp) {
+ selected_history = &history;
+ }
+ }
+
+ if (selected_history) {
+ return selected_history->undo_redo->get_current_action_name();
+ }
+ }
+ return "";
+}
+
+void EditorUndoRedoManager::discard_history(int p_idx, bool p_erase_from_map) {
+ ERR_FAIL_COND(!history_map.has(p_idx));
+ History &history = history_map[p_idx];
+
+ if (history.undo_redo) {
+ memdelete(history.undo_redo);
+ history.undo_redo = nullptr;
+ }
+
+ if (p_erase_from_map) {
+ history_map.erase(p_idx);
+ }
+}
+
+void EditorUndoRedoManager::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("create_action", "name", "merge_mode", "custom_context"), &EditorUndoRedoManager::create_action, DEFVAL(UndoRedo::MERGE_DISABLE), DEFVAL((Object *)nullptr));
+ ClassDB::bind_method(D_METHOD("commit_action", "execute"), &EditorUndoRedoManager::commit_action, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("is_committing_action"), &EditorUndoRedoManager::is_committing_action);
+
+ {
+ MethodInfo mi;
+ mi.name = "add_do_method";
+ mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
+
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "add_do_method", &EditorUndoRedoManager::_add_do_method, mi, varray(), false);
+ }
+
+ {
+ MethodInfo mi;
+ mi.name = "add_undo_method";
+ mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
+
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "add_undo_method", &EditorUndoRedoManager::_add_undo_method, mi, varray(), false);
+ }
+
+ ClassDB::bind_method(D_METHOD("add_do_property", "object", "property", "value"), &EditorUndoRedoManager::add_do_property);
+ ClassDB::bind_method(D_METHOD("add_undo_property", "object", "property", "value"), &EditorUndoRedoManager::add_undo_property);
+ ClassDB::bind_method(D_METHOD("add_do_reference", "object"), &EditorUndoRedoManager::add_do_reference);
+ ClassDB::bind_method(D_METHOD("add_undo_reference", "object"), &EditorUndoRedoManager::add_undo_reference);
+
+ ClassDB::bind_method(D_METHOD("get_object_history_id", "object"), &EditorUndoRedoManager::get_history_id_for_object);
+ ClassDB::bind_method(D_METHOD("get_history_undo_redo", "id"), &EditorUndoRedoManager::get_history_undo_redo);
+
+ BIND_ENUM_CONSTANT(GLOBAL_HISTORY);
+ BIND_ENUM_CONSTANT(INVALID_HISTORY);
+}
+
+EditorUndoRedoManager::~EditorUndoRedoManager() {
+ for (const KeyValue<int, History> &E : history_map) {
+ discard_history(E.key, false);
+ }
+}
diff --git a/editor/editor_undo_redo_manager.h b/editor/editor_undo_redo_manager.h
new file mode 100644
index 0000000000..c4d85daa22
--- /dev/null
+++ b/editor/editor_undo_redo_manager.h
@@ -0,0 +1,134 @@
+/*************************************************************************/
+/* editor_undo_redo_manager.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 EDITOR_UNDO_REDO_MANAGER_H
+#define EDITOR_UNDO_REDO_MANAGER_H
+
+#include "core/object/class_db.h"
+#include "core/object/ref_counted.h"
+#include "core/object/undo_redo.h"
+
+class EditorUndoRedoManager : public RefCounted {
+ GDCLASS(EditorUndoRedoManager, RefCounted);
+
+public:
+ enum SpecialHistory {
+ GLOBAL_HISTORY = 0,
+ INVALID_HISTORY = -99,
+ };
+
+private:
+ struct Action {
+ int history_id = INVALID_HISTORY;
+ double timestamp = 0;
+ String action_name;
+ UndoRedo::MergeMode merge_mode = UndoRedo::MERGE_DISABLE;
+ };
+
+ struct History {
+ int id = INVALID_HISTORY;
+ UndoRedo *undo_redo = nullptr;
+ uint64_t saved_version = 1;
+ List<Action> undo_stack;
+ List<Action> redo_stack;
+ };
+
+ HashMap<int, History> history_map;
+ Action pending_action;
+
+ bool is_committing = false;
+
+protected:
+ static void _bind_methods();
+
+public:
+ History &get_or_create_history(int p_idx);
+ UndoRedo *get_history_undo_redo(int p_idx) const;
+ int get_history_id_for_object(Object *p_object) const;
+ History &get_history_for_object(Object *p_object);
+
+ void create_action_for_history(const String &p_name, int p_history_id, UndoRedo::MergeMode p_mode = UndoRedo::MERGE_DISABLE);
+ void create_action(const String &p_name = "", UndoRedo::MergeMode p_mode = UndoRedo::MERGE_DISABLE, Object *p_custom_context = nullptr);
+
+ void add_do_methodp(Object *p_object, const StringName &p_method, const Variant **p_args, int p_argcount);
+ void add_undo_methodp(Object *p_object, const StringName &p_method, const Variant **p_args, int p_argcount);
+
+ template <typename... VarArgs>
+ void add_do_method(Object *p_object, const StringName &p_method, VarArgs... p_args) {
+ Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
+ const Variant *argptrs[sizeof...(p_args) + 1];
+ for (uint32_t i = 0; i < sizeof...(p_args); i++) {
+ argptrs[i] = &args[i];
+ }
+
+ add_do_methodp(p_object, p_method, sizeof...(p_args) == 0 ? nullptr : (const Variant **)argptrs, sizeof...(p_args));
+ }
+
+ template <typename... VarArgs>
+ void add_undo_method(Object *p_object, const StringName &p_method, VarArgs... p_args) {
+ Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
+ const Variant *argptrs[sizeof...(p_args) + 1];
+ for (uint32_t i = 0; i < sizeof...(p_args); i++) {
+ argptrs[i] = &args[i];
+ }
+
+ add_undo_methodp(p_object, p_method, sizeof...(p_args) == 0 ? nullptr : (const Variant **)argptrs, sizeof...(p_args));
+ }
+
+ void _add_do_method(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
+ void _add_undo_method(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
+
+ void add_do_property(Object *p_object, const StringName &p_property, const Variant &p_value);
+ void add_undo_property(Object *p_object, const StringName &p_property, const Variant &p_value);
+ void add_do_reference(Object *p_object);
+ void add_undo_reference(Object *p_object);
+
+ void commit_action(bool p_execute = true);
+ bool is_committing_action() const;
+
+ bool undo();
+ bool redo();
+ void clear_history(bool p_increase_version = true, int p_idx = INVALID_HISTORY);
+
+ void set_history_as_saved(int p_idx);
+ void set_history_as_unsaved(int p_idx);
+ bool is_history_unsaved(int p_idx);
+ bool has_undo();
+ bool has_redo();
+
+ String get_current_action_name();
+
+ void discard_history(int p_idx, bool p_erase_from_map = true);
+ ~EditorUndoRedoManager();
+};
+
+VARIANT_ENUM_CAST(EditorUndoRedoManager::SpecialHistory);
+
+#endif // EDITOR_UNDO_REDO_MANAGER_H
diff --git a/editor/editor_vcs_interface.cpp b/editor/editor_vcs_interface.cpp
index 3f2012cc16..cb188f9c3e 100644
--- a/editor/editor_vcs_interface.cpp
+++ b/editor/editor_vcs_interface.cpp
@@ -82,8 +82,8 @@ void EditorVCSInterface::_unstage_file(String p_file_path) {
void EditorVCSInterface::_commit(String p_msg) {
}
-Array EditorVCSInterface::_get_file_diff(String p_file_path) {
- return Array();
+TypedArray<Dictionary> EditorVCSInterface::_get_file_diff(String p_file_path) {
+ return TypedArray<Dictionary>();
}
bool EditorVCSInterface::_shut_down() {
@@ -133,11 +133,11 @@ void EditorVCSInterface::commit(String p_msg) {
}
}
-Array EditorVCSInterface::get_file_diff(String p_file_path) {
+TypedArray<Dictionary> EditorVCSInterface::get_file_diff(String p_file_path) {
if (is_addon_ready()) {
return call("_get_file_diff", p_file_path);
}
- return Array();
+ return TypedArray<Dictionary>();
}
bool EditorVCSInterface::shut_down() {
diff --git a/editor/editor_vcs_interface.h b/editor/editor_vcs_interface.h
index 6a6fca7eba..d6d7ffa0e9 100644
--- a/editor/editor_vcs_interface.h
+++ b/editor/editor_vcs_interface.h
@@ -52,7 +52,7 @@ protected:
virtual void _stage_file(String p_file_path);
virtual void _unstage_file(String p_file_path);
virtual void _commit(String p_msg);
- virtual Array _get_file_diff(String p_file_path);
+ virtual TypedArray<Dictionary> _get_file_diff(String p_file_path);
virtual bool _shut_down();
virtual String _get_project_name();
virtual String _get_vcs_name();
@@ -76,7 +76,7 @@ public:
void stage_file(String p_file_path);
void unstage_file(String p_file_path);
void commit(String p_msg);
- Array get_file_diff(String p_file_path);
+ TypedArray<Dictionary> get_file_diff(String p_file_path);
bool shut_down();
String get_project_name();
String get_vcs_name();
diff --git a/editor/groups_editor.cpp b/editor/groups_editor.cpp
index f16097f109..15add50fd4 100644
--- a/editor/groups_editor.cpp
+++ b/editor/groups_editor.cpp
@@ -32,6 +32,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/scene_tree_dock.h"
#include "editor/scene_tree_editor.h"
#include "scene/gui/box_container.h"
@@ -397,6 +398,10 @@ void GroupDialog::_notification(int p_what) {
}
}
+void GroupDialog::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
void GroupDialog::edit() {
popup_centered();
@@ -696,6 +701,10 @@ void GroupsEditor::update_tree() {
}
}
+void GroupsEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
void GroupsEditor::set_current(Node *p_node) {
node = p_node;
update_tree();
diff --git a/editor/groups_editor.h b/editor/groups_editor.h
index fec8913e31..8bbea4e652 100644
--- a/editor/groups_editor.h
+++ b/editor/groups_editor.h
@@ -31,7 +31,6 @@
#ifndef GROUPS_EDITOR_H
#define GROUPS_EDITOR_H
-#include "core/object/undo_redo.h"
#include "editor/scene_tree_editor.h"
#include "scene/gui/button.h"
#include "scene/gui/dialogs.h"
@@ -40,6 +39,8 @@
#include "scene/gui/popup.h"
#include "scene/gui/tree.h"
+class EditorUndoRedoManager;
+
class GroupDialog : public AcceptDialog {
GDCLASS(GroupDialog, AcceptDialog);
@@ -68,7 +69,7 @@ class GroupDialog : public AcceptDialog {
String selected_group;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void _group_selected();
@@ -103,7 +104,7 @@ public:
};
void edit();
- void set_undo_redo(UndoRedo *p_undoredo) { undo_redo = p_undoredo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
GroupDialog();
};
@@ -119,7 +120,7 @@ class GroupsEditor : public VBoxContainer {
Button *add = nullptr;
Tree *tree = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void update_tree();
void _add_group(const String &p_group = "");
@@ -137,7 +138,7 @@ public:
COPY_GROUP,
};
- void set_undo_redo(UndoRedo *p_undoredo) { undo_redo = p_undoredo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void set_current(Node *p_node);
GroupsEditor();
diff --git a/editor/icons/BezierHandlesBalanced.svg b/editor/icons/BezierHandlesBalanced.svg
index 911029e431..b1778b1a5e 100644
--- a/editor/icons/BezierHandlesBalanced.svg
+++ b/editor/icons/BezierHandlesBalanced.svg
@@ -1 +1 @@
-<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m1.7627119 13.627119s1.2881355-6.847458 6.5762712-8.1355935c5.0847459.9491522 5.9661009 8.1355925 5.9661009 8.1355925" fill="none" stroke="#5fb2ff" stroke-miterlimit="4.9" stroke-width="1.7"/><ellipse cx="1.898304" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><ellipse cx="14.237288" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><path d="m7.4559186 5.1473018-4.7355323 1.5541798" fill="none" stroke="#5fb2ff" stroke-width=".618"/><path d="m10.790357 4.2063094-2.5009748.9433136" fill="none" stroke="#5fb2ff" stroke-width=".614897"/><g fill="#e0e0e0"><ellipse cx="8.271187" cy="4.779661" rx="1.267586" ry="1.199789"/><path d="m1.7157324 5.8754878a1.2675855 1.1997888 0 0 0 -1.26757806 1.1992188 1.2675855 1.1997888 0 0 0 1.26757806 1.1992187 1.2675855 1.1997888 0 0 0 1.2675781-1.1992187 1.2675855 1.1997888 0 0 0 -1.2675781-1.1992188zm.00195.4238282a.84677333.80148375 0 0 1 .8476593.8007812.84677333.80148375 0 0 1 -.8476562.8007812.84677333.80148375 0 0 1 -.84765616-.8007812.84677333.80148375 0 0 1 .84765616-.8007812z"/><path d="m11.909414 2.4642073a1.2836218 1.231838 0 0 0 -1.283614 1.2312528 1.2836218 1.231838 0 0 0 1.283614 1.2312527 1.2836218 1.231838 0 0 0 1.283614-1.2312527 1.2836218 1.231838 0 0 0 -1.283614-1.2312528zm.002.4351497a.85748593.82289328 0 0 1 .858383.8221719.85748593.82289328 0 0 1 -.85838.822172.85748593.82289328 0 0 1 -.858379-.822172.85748593.82289328 0 0 1 .858379-.8221719z"/></g></svg>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m1.7627119 13.627119s1.2881355-6.847458 6.5762712-8.1355935c5.0847459.9491522 5.9661009 8.1355925 5.9661009 8.1355925" fill="none" stroke="#87b1d7" stroke-miterlimit="4.9" stroke-width=".5"/><path d="m2.4962504 7.6963851 10.1811806-3.7166314" fill="none" stroke="#61b2ff" stroke-width="1.5"/><g fill="#e0e0e0"><ellipse cx="1.898304" cy="13.491526" rx="1.267586" ry="1.199789"/><ellipse cx="14.237288" cy="13.491526" rx="1.267586" ry="1.199789"/><ellipse cx="8.338983" cy="5.491526" rx="1.267586" ry="1.199789"/><path d="m1.6910776 6.7273a1.2675855 1.1997888 0 0 0 -1.26757808 1.1992188 1.2675855 1.1997888 0 0 0 1.26757808 1.1992187 1.2675855 1.1997888 0 0 0 1.2675781-1.1992187 1.2675855 1.1997888 0 0 0 -1.2675781-1.1992188zm.00195.4238282a.84677333.80148375 0 0 1 .8476593.8007812.84677333.80148375 0 0 1 -.8476562.8007812.84677333.80148375 0 0 1 -.84765618-.8007812.84677333.80148375 0 0 1 .84765618-.8007812z"/><path d="m13.40948 2.2963899a1.2836218 1.231838 0 0 0 -1.283614 1.2312528 1.2836218 1.231838 0 0 0 1.283614 1.2312526 1.2836218 1.231838 0 0 0 1.283614-1.2312526 1.2836218 1.231838 0 0 0 -1.283614-1.2312528zm.002.4351497a.85748593.82289328 0 0 1 .858383.8221719.85748593.82289328 0 0 1 -.85838.8221719.85748593.82289328 0 0 1 -.858379-.8221719.85748593.82289328 0 0 1 .858379-.8221719z"/></g></svg>
diff --git a/editor/icons/BezierHandlesFree.svg b/editor/icons/BezierHandlesFree.svg
index 6e91288c79..c7bff530ae 100644
--- a/editor/icons/BezierHandlesFree.svg
+++ b/editor/icons/BezierHandlesFree.svg
@@ -1 +1 @@
-<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m1.7627119 13.627119s1.2881355-6.847458 6.5762712-8.1355935c5.0847459.9491522 5.9661009 8.1355925 5.9661009 8.1355925" fill="none" stroke="#5fb2ff" stroke-miterlimit="4.9" stroke-width="1.7"/><ellipse cx="1.898304" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><ellipse cx="14.237288" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><path d="m7.6850253 4.7560401-3.776127.6607599" fill="none" stroke="#5fb2ff" stroke-width=".805138"/><path d="m11.695505 2.3941651-2.999121 2.2935078" fill="none" stroke="#5fb2ff" stroke-width=".730798"/><g fill="#e0e0e0"><ellipse cx="8.271187" cy="4.779661" rx="1.267586" ry="1.199789"/><path d="m2.4961199 4.3976698a1.1997888 1.2675855 80.074672 0 0 -1.0419038 1.3997559 1.1997888 1.2675855 80.074672 0 0 1.4553094.9627848 1.1997888 1.2675855 80.074672 0 0 1.0419037-1.3997558 1.1997888 1.2675855 80.074672 0 0 -1.4553093-.9627849zm.074974.4171488a.80148375.84677333 80.074672 0 1 .9729986.6426896.80148375.84677333 80.074672 0 1 -.6969432.934902.80148375.84677333 80.074672 0 1 -.9729958-.6426902.80148375.84677333 80.074672 0 1 .6969432-.934902z"/><path d="m11.838896.64428913a1.231838 1.2836218 52.593897 0 0 -.271701 1.75779027 1.231838 1.2836218 52.593897 0 0 1.767576.1983008 1.231838 1.2836218 52.593897 0 0 .271701-1.75779027 1.231838 1.2836218 52.593897 0 0 -1.767576-.1983008zm.265925.3444462a.82289328.85748593 52.593897 0 1 1.181294.13165847.82289328.85748593 52.593897 0 1 -.182417 1.1745241.82289328.85748593 52.593897 0 1 -1.181291-.1316609.82289328.85748593 52.593897 0 1 .182417-1.17452347z"/></g></svg>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m1.7627119 13.627119s1.3064631-5.1979735 6.5945988-6.486109c5.0847463.9491522 5.9477733 6.486108 5.9477733 6.486108" fill="none" stroke="#87b1d7" stroke-miterlimit="4.9" stroke-width=".5"/><path d="m2.3554991 8.5165019 6.0018116-1.3754919 2.0717113-4.6377276" fill="none" stroke="#61b3ff" stroke-width="1.5"/><g fill="#e0e0e0"><ellipse cx="1.898304" cy="13.491526" rx="1.267586" ry="1.199789"/><ellipse cx="14.237288" cy="13.491526" rx="1.267586" ry="1.199789"/><ellipse cx="8.35731" cy="7.14101" rx="1.267586" ry="1.199789"/><path d="m1.3048251 7.4400522a1.1997888 1.2675855 80.074672 0 0 -1.04190379 1.3997559 1.1997888 1.2675855 80.074672 0 0 1.45530939.9627848 1.1997888 1.2675855 80.074672 0 0 1.0419037-1.3997558 1.1997888 1.2675855 80.074672 0 0 -1.4553093-.9627849zm.074974.4171488a.80148375.84677333 80.074672 0 1 .9729986.6426896.80148375.84677333 80.074672 0 1 -.6969432.934902.80148375.84677333 80.074672 0 1 -.97299579-.6426902.80148375.84677333 80.074672 0 1 .69694319-.934902z"/><path d="m10.024463.73592688a1.231838 1.2836218 52.593897 0 0 -.2717015 1.75779042 1.231838 1.2836218 52.593897 0 0 1.7675765.1983008 1.231838 1.2836218 52.593897 0 0 .271701-1.75779042 1.231838 1.2836218 52.593897 0 0 -1.767576-.1983008zm.265925.34444622a.82289328.85748593 52.593897 0 1 1.181294.1316585.82289328.85748593 52.593897 0 1 -.182417 1.1745242.82289328.85748593 52.593897 0 1 -1.181291-.1316609.82289328.85748593 52.593897 0 1 .182417-1.1745236z"/></g></svg>
diff --git a/editor/icons/BezierHandlesLinear.svg b/editor/icons/BezierHandlesLinear.svg
new file mode 100644
index 0000000000..2667779dcb
--- /dev/null
+++ b/editor/icons/BezierHandlesLinear.svg
@@ -0,0 +1 @@
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8.2711868 4.7796612-6.3728828 8.7118648z" fill="none" stroke="#87b1d7" stroke-miterlimit="4.9" stroke-width=".5"/><ellipse cx="1.898304" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><path d="m14.237288 13.491526-5.9661012-8.7118648" fill="none" stroke="#87b1d7" stroke-miterlimit="4.9" stroke-width=".5"/><path d="m5.6316733 8.3879317 2.6395135-3.6082705 2.4416832 3.5654122" fill="none" stroke="#61b2ff" stroke-width="1.5"/><g fill="#e0e0e0"><ellipse cx="14.237288" cy="13.491526" rx="1.267586" ry="1.199789"/><ellipse cx="8.271187" cy="4.779661" rx="1.267586" ry="1.199789"/><path d="m5.0847454 7.9363749a1.2675855 1.1997888 0 0 0 -1.2675781 1.1992188 1.2675855 1.1997888 0 0 0 1.2675781 1.1992183 1.2675855 1.1997888 0 0 0 1.2675781-1.1992183 1.2675855 1.1997888 0 0 0 -1.2675781-1.1992188zm.00195.4238282a.84677333.80148375 0 0 1 .8476593.8007812.84677333.80148375 0 0 1 -.8476562.8007812.84677333.80148375 0 0 1 -.8476562-.8007812.84677333.80148375 0 0 1 .8476562-.8007812z"/><path d="m11.254237 7.9043407a1.2836218 1.231838 0 0 0 -1.2836135 1.2312528 1.2836218 1.231838 0 0 0 1.2836135 1.2312525 1.2836218 1.231838 0 0 0 1.283614-1.2312525 1.2836218 1.231838 0 0 0 -1.283614-1.2312528zm.002.4351497a.85748593.82289328 0 0 1 .858383.8221719.85748593.82289328 0 0 1 -.85838.822172.85748593.82289328 0 0 1 -.858379-.822172.85748593.82289328 0 0 1 .858379-.8221719z"/></g></svg>
diff --git a/editor/icons/BezierHandlesMirror.svg b/editor/icons/BezierHandlesMirror.svg
index 9180e31921..07817f7247 100644
--- a/editor/icons/BezierHandlesMirror.svg
+++ b/editor/icons/BezierHandlesMirror.svg
@@ -1 +1 @@
-<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m1.7627119 13.627119s1.2881355-6.847458 6.5762712-8.1355935c5.0847459.9491522 5.9661009 8.1355925 5.9661009 8.1355925" fill="none" stroke="#5fb2ff" stroke-miterlimit="4.9" stroke-width="1.7"/><ellipse cx="1.898304" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><ellipse cx="14.237288" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><path d="m8.2033896 4.6779662h-3.8335021" fill="none" stroke="#5fb2ff" stroke-width=".805138"/><path d="m11.931789 4.6440679h-3.7283994" fill="none" stroke="#5fb2ff" stroke-width=".716709"/><g fill="#e0e0e0"><ellipse cx="8.271187" cy="4.779661" rx="1.267586" ry="1.199789"/><path d="m3.1539157 3.4305762a1.2675855 1.1997888 0 0 0 -1.2675781 1.1992188 1.2675855 1.1997888 0 0 0 1.2675781 1.1992187 1.2675855 1.1997888 0 0 0 1.2675781-1.1992187 1.2675855 1.1997888 0 0 0 -1.2675781-1.1992188zm.00195.4238282a.84677333.80148375 0 0 1 .8476593.8007812.84677333.80148375 0 0 1 -.8476562.8007812.84677333.80148375 0 0 1 -.8476562-.8007812.84677333.80148375 0 0 1 .8476562-.8007812z"/><path d="m13.093969 3.3750567a1.2675855 1.1997888 0 0 0 -1.267578 1.1992188 1.2675855 1.1997888 0 0 0 1.267578 1.1992187 1.2675855 1.1997888 0 0 0 1.267578-1.1992187 1.2675855 1.1997888 0 0 0 -1.267578-1.1992188zm.002.4238282a.84677333.80148375 0 0 1 .847659.8007812.84677333.80148375 0 0 1 -.847656.8007812.84677333.80148375 0 0 1 -.847656-.8007812.84677333.80148375 0 0 1 .847656-.8007812z"/></g></svg>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m1.7627119 13.627119s1.2881355-6.847458 6.5762712-8.1355935c5.0847459.9491522 5.9661009 8.1355925 5.9661009 8.1355925" fill="none" stroke="#87b1d7" stroke-miterlimit="4.9" stroke-width=".5"/><ellipse cx="1.898304" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><ellipse cx="14.237288" cy="13.491526" fill="#e0e0e0" rx="1.267586" ry="1.199789"/><path d="m8.3389831 5.4915255-5.8519685.0395137" fill="none" stroke="#5fb2ff" stroke-width="1.5"/><path d="m13.814033 5.4419288-5.4750499.0156984" fill="none" stroke="#5fb2ff" stroke-width="1.5"/><g fill="#e0e0e0"><ellipse cx="8.40678" cy="5.593221" rx="1.267586" ry="1.199789"/><path d="m1.6400247 4.2441355a1.2675855 1.1997888 0 0 0 -1.26757814 1.1992188 1.2675855 1.1997888 0 0 0 1.26757814 1.1992187 1.2675855 1.1997888 0 0 0 1.2675781-1.1992187 1.2675855 1.1997888 0 0 0 -1.2675781-1.1992188zm.00195.4238282a.84677333.80148375 0 0 1 .8476593.8007812.84677333.80148375 0 0 1 -.8476562.8007812.84677333.80148375 0 0 1 -.84765624-.8007812.84677333.80148375 0 0 1 .84765624-.8007812z"/><path d="m14.659116 4.188616a1.2675855 1.1997888 0 0 0 -1.267578 1.1992188 1.2675855 1.1997888 0 0 0 1.267578 1.1992187 1.2675855 1.1997888 0 0 0 1.267578-1.1992187 1.2675855 1.1997888 0 0 0 -1.267578-1.1992188zm.002.4238282a.84677333.80148375 0 0 1 .847659.8007812.84677333.80148375 0 0 1 -.847656.8007812.84677333.80148375 0 0 1 -.847656-.8007812.84677333.80148375 0 0 1 .847656-.8007812z"/></g></svg>
diff --git a/editor/icons/ContainerLayout.svg b/editor/icons/ContainerLayout.svg
new file mode 100644
index 0000000000..feabc2c350
--- /dev/null
+++ b/editor/icons/ContainerLayout.svg
@@ -0,0 +1 @@
+<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><g fill-rule="nonzero"><path d="m3 1c-1.105 0-2 .895-2 2h2zm2 0v2h2v-2zm4 0v2h2v-2zm4 0v2h2c0-1.105-.895-2-2-2zm-12 4v2h2v-2zm12 0v2h2v-2zm-12 4v2h2v-2zm12 0v2h2v-2zm-12 4c0 1.105.895 2 2 2v-2zm4 0v2h2v-2zm4 0v2h2v-2zm4 0v2c1.105 0 2-.895 2-2z" fill="#8eef97"/><path d="m7 7h4v4h-4z" fill="#d6d6d6"/></g></svg>
diff --git a/editor/icons/ControlLayout.svg b/editor/icons/ControlLayout.svg
index 11dd2554be..8503e3313c 100644
--- a/editor/icons/ControlLayout.svg
+++ b/editor/icons/ControlLayout.svg
@@ -1 +1 @@
-<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m1 1v14h14v-14zm2 2h3v3h-3zm5 0h5v3h-5zm-5 5h3v5h-3zm5 0h5v5h-5z" fill="#8eef97"/></svg>
+<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><g fill-rule="nonzero"><path d="m11.793 8v-2h-3.793v-2.113h-2v2.113h-2.142v2h2.142v3.967h2v-3.967z" fill="#d6d6d6"/><path d="m8 .345c-4.199 0-7.655 3.456-7.655 7.655s3.456 7.655 7.655 7.655 7.655-3.456 7.655-7.655-3.456-7.655-7.655-7.655zm0 1.999c3.103 0 5.656 2.553 5.656 5.656s-2.553 5.656-5.656 5.656-5.656-2.553-5.656-5.656 2.553-5.656 5.656-5.656z" fill="#8eef97"/></g></svg>
diff --git a/editor/icons/CurveIn.svg b/editor/icons/CurveIn.svg
index 2ad44dc654..fefad9ce6c 100644
--- a/editor/icons/CurveIn.svg
+++ b/editor/icons/CurveIn.svg
@@ -1 +1 @@
-<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c5 0 8-3 8-8" fill="none" stroke="#e0e0e0" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
+<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c5 0 8-3 8-8" fill="none" stroke="#80ff45" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
diff --git a/editor/icons/CurveInOut.svg b/editor/icons/CurveInOut.svg
index 292dac4573..f099cb83f1 100644
--- a/editor/icons/CurveInOut.svg
+++ b/editor/icons/CurveInOut.svg
@@ -1 +1 @@
-<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c5 0 3-8 8-8" fill="none" stroke="#e0e0e0" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
+<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c5 0 3-8 8-8" fill="none" stroke="#45d7ff" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
diff --git a/editor/icons/CurveLinear.svg b/editor/icons/CurveLinear.svg
index 3c1fb2a0e2..41d37c9329 100644
--- a/editor/icons/CurveLinear.svg
+++ b/editor/icons/CurveLinear.svg
@@ -1 +1 @@
-<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4 8-8" fill="none" stroke="#e0e0e0" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
+<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4 8-8" fill="none" stroke="#ffe345" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
diff --git a/editor/icons/CurveOut.svg b/editor/icons/CurveOut.svg
index dfa9a26144..19710aa38d 100644
--- a/editor/icons/CurveOut.svg
+++ b/editor/icons/CurveOut.svg
@@ -1 +1 @@
-<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c0-5 3-8 8-8" fill="none" stroke="#e0e0e0" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
+<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c0-5 3-8 8-8" fill="none" stroke="#45ffa2" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
diff --git a/editor/icons/CurveOutIn.svg b/editor/icons/CurveOutIn.svg
index 9a6463d0e9..7f200432bf 100644
--- a/editor/icons/CurveOutIn.svg
+++ b/editor/icons/CurveOutIn.svg
@@ -1 +1 @@
-<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c0-5 8-3 8-8" fill="none" stroke="#e0e0e0" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
+<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4c0-5 8-3 8-8" fill="none" stroke="#ff4596" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
diff --git a/editor/icons/DefaultProjectIcon.svg b/editor/icons/DefaultProjectIcon.svg
index f81ba4d390..adc26df6c2 100644
--- a/editor/icons/DefaultProjectIcon.svg
+++ b/editor/icons/DefaultProjectIcon.svg
@@ -1 +1 @@
-<svg height="64" viewBox="0 0 64 64" width="64" xmlns="http://www.w3.org/2000/svg"><g stroke-linejoin="round"><path d="m8 0c-4.432 0-8 3.568-8 8v48c0 4.432 3.568 8 8 8h48c4.432 0 8-3.568 8-8v-48c0-4.432-3.568-8-8-8z" fill="#355570" stroke-linecap="round" stroke-width="2"/><path d="m8 0c-4.432 0-8 3.568-8 8v48c0 4.432 3.568 8 8 8h48c4.432 0 8-3.568 8-8v-48c0-4.432-3.568-8-8-8zm0 2h48c3.324 0 6 2.676 6 6v48c0 3.324-2.676 6-6 6h-48c-3.324 0-6-2.676-6-6v-48c0-3.324 2.676-6 6-6z" fill-opacity=".19608" stroke-linecap="round" stroke-width="2"/><path d="m27.254 10c-2.1314.47383-4.2401 1.134-6.2168 2.1289.04521 1.7455.15796 3.4164.38672 5.1152-.76768.4919-1.574.91443-2.291 1.4902-.72854.5604-1.4731 1.0965-2.1328 1.752-1.3179-.8716-2.7115-1.691-4.1484-2.4141-1.549 1.667-2.9985 3.4672-4.1816 5.4805.89011 1.4399 1.8209 2.7894 2.8242 4.0703h.027343v9.9453 1.2617 1.1504l-.009765 1.6309h-.001953c.0031.7321.011718 1.5356.011718 1.6953 0 7.1942 9.1264 10.652 20.465 10.691h.013672.013672c11.338-.04 20.461-3.4972 20.461-10.691 0-.1626.010282-.96271.013672-1.6953h-.001953l-.011719-1.6309v-.98633l.003907-.001953v-11.369h.027343c1.0035-1.2809 1.9337-2.6304 2.8242-4.0703-1.1827-2.0133-2.6327-3.8135-4.1816-5.4805-1.4366.7231-2.8325 1.5425-4.1504 2.4141-.65947-.6555-1.4013-1.1916-2.1309-1.752-.71682-.5758-1.5248-.99833-2.291-1.4902.22813-1.6988.3413-3.3697.38672-5.1152-1.977-.99494-4.0863-1.6551-6.2188-2.1289-.85139 1.4309-1.6285 2.9812-2.3066 4.4961-.80409-.1344-1.613-.18571-2.4219-.19531h-.015625-.015625c-.81037.01-1.6176.060513-2.4219.19531-.67768-1.5149-1.4559-3.0652-2.3086-4.4961z" fill="#fff" stroke="#fff" stroke-width="3"/></g><g stroke-width=".32031" transform="matrix(.050279 0 0 .050279 6.2574 1.18)"><path d="m0 0s-.325 1.994-.515 1.976l-36.182-3.491c-2.879-.278-5.115-2.574-5.317-5.459l-.994-14.247-27.992-1.997-1.904 12.912c-.424 2.872-2.932 5.037-5.835 5.037h-38.188c-2.902 0-5.41-2.165-5.834-5.037l-1.905-12.912-27.992 1.997-.994 14.247c-.202 2.886-2.438 5.182-5.317 5.46l-36.2 3.49c-.187.018-.324-1.978-.511-1.978l-.049-7.83 30.658-4.944 1.004-14.374c.203-2.91 2.551-5.263 5.463-5.472l38.551-2.75c.146-.01.29-.016.434-.016 2.897 0 5.401 2.166 5.825 5.038l1.959 13.286h28.005l1.959-13.286c.423-2.871 2.93-5.037 5.831-5.037.142 0 .284.005.423.015l38.556 2.75c2.911.209 5.26 2.562 5.463 5.472l1.003 14.374 30.645 4.966z" fill="#fff" transform="matrix(4.1626 0 0 -4.1626 919.24 771.67)"/><path d="m0 0v-59.041c.108-.001.216-.005.323-.015l36.196-3.49c1.896-.183 3.382-1.709 3.514-3.609l1.116-15.978 31.574-2.253 2.175 14.747c.282 1.912 1.922 3.329 3.856 3.329h38.188c1.933 0 3.573-1.417 3.855-3.329l2.175-14.747 31.575 2.253 1.115 15.978c.133 1.9 1.618 3.425 3.514 3.609l36.182 3.49c.107.01.214.014.322.015v4.711l.015.005v54.325h.134c4.795 6.12 9.232 12.569 13.487 19.449-5.651 9.62-12.575 18.217-19.976 26.182-6.864-3.455-13.531-7.369-19.828-11.534-3.151 3.132-6.7 5.694-10.186 8.372-3.425 2.751-7.285 4.768-10.946 7.118 1.09 8.117 1.629 16.108 1.846 24.448-9.446 4.754-19.519 7.906-29.708 10.17-4.068-6.837-7.788-14.241-11.028-21.479-3.842.642-7.702.88-11.567.926v.006c-.027 0-.052-.006-.075-.006-.024 0-.049.006-.073.006v-.006c-3.872-.046-7.729-.284-11.572-.926-3.238 7.238-6.956 14.642-11.03 21.479-10.184-2.264-20.258-5.416-29.703-10.17.216-8.34.755-16.331 1.848-24.448-3.668-2.35-7.523-4.367-10.949-7.118-3.481-2.678-7.036-5.24-10.188-8.372-6.297 4.165-12.962 8.079-19.828 11.534-7.401-7.965-14.321-16.562-19.974-26.182 4.253-6.88 8.693-13.329 13.487-19.449z" fill="#478cbf" transform="matrix(4.1626 0 0 -4.1626 104.7 525.91)"/><path d="m0 0-1.121-16.063c-.135-1.936-1.675-3.477-3.611-3.616l-38.555-2.751c-.094-.007-.188-.01-.281-.01-1.916 0-3.569 1.406-3.852 3.33l-2.211 14.994h-31.459l-2.211-14.994c-.297-2.018-2.101-3.469-4.133-3.32l-38.555 2.751c-1.936.139-3.476 1.68-3.611 3.616l-1.121 16.063-32.547 3.138c.015-3.498.06-7.33.06-8.093 0-34.374 43.605-50.896 97.781-51.086h.133c54.176.19 97.766 16.712 97.766 51.086 0 .777.047 4.593.063 8.093z" fill="#478cbf" transform="matrix(4.1626 0 0 -4.1626 784.07 817.24)"/><path d="m0 0c0-12.052-9.765-21.815-21.813-21.815-12.042 0-21.81 9.763-21.81 21.815 0 12.044 9.768 21.802 21.81 21.802 12.048 0 21.813-9.758 21.813-21.802" fill="#fff" transform="matrix(4.1626 0 0 -4.1626 389.21 625.67)"/><path d="m0 0c0-7.994-6.479-14.473-14.479-14.473-7.996 0-14.479 6.479-14.479 14.473s6.483 14.479 14.479 14.479c8 0 14.479-6.485 14.479-14.479" fill="#414042" transform="matrix(4.1626 0 0 -4.1626 367.37 631.06)"/><path d="m0 0c-3.878 0-7.021 2.858-7.021 6.381v20.081c0 3.52 3.143 6.381 7.021 6.381s7.028-2.861 7.028-6.381v-20.081c0-3.523-3.15-6.381-7.028-6.381" fill="#fff" transform="matrix(4.1626 0 0 -4.1626 511.99 724.74)"/><path d="m0 0c0-12.052 9.765-21.815 21.815-21.815 12.041 0 21.808 9.763 21.808 21.815 0 12.044-9.767 21.802-21.808 21.802-12.05 0-21.815-9.758-21.815-21.802" fill="#fff" transform="matrix(4.1626 0 0 -4.1626 634.79 625.67)"/><path d="m0 0c0-7.994 6.477-14.473 14.471-14.473 8.002 0 14.479 6.479 14.479 14.473s-6.477 14.479-14.479 14.479c-7.994 0-14.471-6.485-14.471-14.479" fill="#414042" transform="matrix(4.1626 0 0 -4.1626 656.64 631.06)"/></g></svg>
+<svg height="128" width="128" xmlns="http://www.w3.org/2000/svg"><g transform="translate(32 32)"><path d="m-16-32c-8.86 0-16 7.13-16 15.99v95.98c0 8.86 7.13 15.99 16 15.99h96c8.86 0 16-7.13 16-15.99v-95.98c0-8.85-7.14-15.99-16-15.99z" fill="#363d52"/><path d="m-16-32c-8.86 0-16 7.13-16 15.99v95.98c0 8.86 7.13 15.99 16 15.99h96c8.86 0 16-7.13 16-15.99v-95.98c0-8.85-7.14-15.99-16-15.99zm0 4h96c6.64 0 12 5.35 12 11.99v95.98c0 6.64-5.35 11.99-12 11.99h-96c-6.64 0-12-5.35-12-11.99v-95.98c0-6.64 5.36-11.99 12-11.99z" fill-opacity=".4"/></g><g stroke-width="9.92746" transform="matrix(.10073078 0 0 .10073078 12.425923 2.256365)"><path d="m0 0s-.325 1.994-.515 1.976l-36.182-3.491c-2.879-.278-5.115-2.574-5.317-5.459l-.994-14.247-27.992-1.997-1.904 12.912c-.424 2.872-2.932 5.037-5.835 5.037h-38.188c-2.902 0-5.41-2.165-5.834-5.037l-1.905-12.912-27.992 1.997-.994 14.247c-.202 2.886-2.438 5.182-5.317 5.46l-36.2 3.49c-.187.018-.324-1.978-.511-1.978l-.049-7.83 30.658-4.944 1.004-14.374c.203-2.91 2.551-5.263 5.463-5.472l38.551-2.75c.146-.01.29-.016.434-.016 2.897 0 5.401 2.166 5.825 5.038l1.959 13.286h28.005l1.959-13.286c.423-2.871 2.93-5.037 5.831-5.037.142 0 .284.005.423.015l38.556 2.75c2.911.209 5.26 2.562 5.463 5.472l1.003 14.374 30.645 4.966z" fill="#fff" transform="matrix(4.162611 0 0 -4.162611 919.24059 771.67186)"/><path d="m0 0v-47.514-6.035-5.492c.108-.001.216-.005.323-.015l36.196-3.49c1.896-.183 3.382-1.709 3.514-3.609l1.116-15.978 31.574-2.253 2.175 14.747c.282 1.912 1.922 3.329 3.856 3.329h38.188c1.933 0 3.573-1.417 3.855-3.329l2.175-14.747 31.575 2.253 1.115 15.978c.133 1.9 1.618 3.425 3.514 3.609l36.182 3.49c.107.01.214.014.322.015v4.711l.015.005v54.325c5.09692 6.4164715 9.92323 13.494208 13.621 19.449-5.651 9.62-12.575 18.217-19.976 26.182-6.864-3.455-13.531-7.369-19.828-11.534-3.151 3.132-6.7 5.694-10.186 8.372-3.425 2.751-7.285 4.768-10.946 7.118 1.09 8.117 1.629 16.108 1.846 24.448-9.446 4.754-19.519 7.906-29.708 10.17-4.068-6.837-7.788-14.241-11.028-21.479-3.842.642-7.702.88-11.567.926v.006c-.027 0-.052-.006-.075-.006-.024 0-.049.006-.073.006v-.006c-3.872-.046-7.729-.284-11.572-.926-3.238 7.238-6.956 14.642-11.03 21.479-10.184-2.264-20.258-5.416-29.703-10.17.216-8.34.755-16.331 1.848-24.448-3.668-2.35-7.523-4.367-10.949-7.118-3.481-2.678-7.036-5.24-10.188-8.372-6.297 4.165-12.962 8.079-19.828 11.534-7.401-7.965-14.321-16.562-19.974-26.182 4.4426579-6.973692 9.2079702-13.9828876 13.621-19.449z" fill="#478cbf" transform="matrix(4.162611 0 0 -4.162611 104.69892 525.90697)"/><path d="m0 0-1.121-16.063c-.135-1.936-1.675-3.477-3.611-3.616l-38.555-2.751c-.094-.007-.188-.01-.281-.01-1.916 0-3.569 1.406-3.852 3.33l-2.211 14.994h-31.459l-2.211-14.994c-.297-2.018-2.101-3.469-4.133-3.32l-38.555 2.751c-1.936.139-3.476 1.68-3.611 3.616l-1.121 16.063-32.547 3.138c.015-3.498.06-7.33.06-8.093 0-34.374 43.605-50.896 97.781-51.086h.066.067c54.176.19 97.766 16.712 97.766 51.086 0 .777.047 4.593.063 8.093z" fill="#478cbf" transform="matrix(4.162611 0 0 -4.162611 784.07144 817.24284)"/><path d="m0 0c0-12.052-9.765-21.815-21.813-21.815-12.042 0-21.81 9.763-21.81 21.815 0 12.044 9.768 21.802 21.81 21.802 12.048 0 21.813-9.758 21.813-21.802" fill="#fff" transform="matrix(4.162611 0 0 -4.162611 389.21484 625.67104)"/><path d="m0 0c0-7.994-6.479-14.473-14.479-14.473-7.996 0-14.479 6.479-14.479 14.473s6.483 14.479 14.479 14.479c8 0 14.479-6.485 14.479-14.479" fill="#414042" transform="matrix(4.162611 0 0 -4.162611 367.36686 631.05679)"/><path d="m0 0c-3.878 0-7.021 2.858-7.021 6.381v20.081c0 3.52 3.143 6.381 7.021 6.381s7.028-2.861 7.028-6.381v-20.081c0-3.523-3.15-6.381-7.028-6.381" fill="#fff" transform="matrix(4.162611 0 0 -4.162611 511.99336 724.73954)"/><path d="m0 0c0-12.052 9.765-21.815 21.815-21.815 12.041 0 21.808 9.763 21.808 21.815 0 12.044-9.767 21.802-21.808 21.802-12.05 0-21.815-9.758-21.815-21.802" fill="#fff" transform="matrix(4.162611 0 0 -4.162611 634.78706 625.67104)"/><path d="m0 0c0-7.994 6.477-14.473 14.471-14.473 8.002 0 14.479 6.479 14.479 14.473s-6.477 14.479-14.479 14.479c-7.994 0-14.471-6.485-14.471-14.479" fill="#414042" transform="matrix(4.162611 0 0 -4.162611 656.64056 631.05679)"/></g></svg>
diff --git a/editor/icons/InterpCubicInTime.svg b/editor/icons/InterpCubicInTime.svg
new file mode 100644
index 0000000000..81027f798a
--- /dev/null
+++ b/editor/icons/InterpCubicInTime.svg
@@ -0,0 +1 @@
+<svg enable-background="new -595.5 420.5 16 8" height="8" viewBox="-595.5 420.5 16 8" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m-593.5 426.5c1-4 3.5-5.5 6-2s5 2 6-2" fill="none" stroke="#ff92cb" stroke-linecap="round" stroke-width="2"/></svg>
diff --git a/editor/icons/Position2D.svg b/editor/icons/Marker2D.svg
index 191f0b2a03..191f0b2a03 100644
--- a/editor/icons/Position2D.svg
+++ b/editor/icons/Marker2D.svg
diff --git a/editor/icons/Position3D.svg b/editor/icons/Marker3D.svg
index 894b195589..894b195589 100644
--- a/editor/icons/Position3D.svg
+++ b/editor/icons/Marker3D.svg
diff --git a/editor/icons/MenuBar.svg b/editor/icons/MenuBar.svg
new file mode 100644
index 0000000000..0a53f07f85
--- /dev/null
+++ b/editor/icons/MenuBar.svg
@@ -0,0 +1 @@
+<svg height="16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="M2 6a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1Zm1 2h10v2H3Zm0 3h10v2H3ZM1 1v4h6V1Zm1 1h4L4 4Z" fill="#8eef97"/></svg>
diff --git a/editor/icons/NodeInfo.svg b/editor/icons/NodeInfo.svg
new file mode 100644
index 0000000000..4e3f0c42d0
--- /dev/null
+++ b/editor/icons/NodeInfo.svg
@@ -0,0 +1 @@
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1a7 7 0 0 0 -7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0 -7-7zm-1 3h2v2h-2zm0 3h2v5h-2z" fill="#fff"/></svg>
diff --git a/editor/import/editor_import_plugin.cpp b/editor/import/editor_import_plugin.cpp
index e822b4963a..3305f241c0 100644
--- a/editor/import/editor_import_plugin.cpp
+++ b/editor/import/editor_import_plugin.cpp
@@ -115,7 +115,7 @@ void EditorImportPlugin::get_import_options(const String &p_path, List<ResourceI
Array needed;
needed.push_back("name");
needed.push_back("default_value");
- Array options;
+ TypedArray<Dictionary> options;
if (GDVIRTUAL_CALL(_get_import_options, p_path, p_preset, options)) {
for (int i = 0; i < options.size(); i++) {
Dictionary d = options[i];
diff --git a/editor/import/editor_import_plugin.h b/editor/import/editor_import_plugin.h
index 4548513b6f..e9749c240f 100644
--- a/editor/import/editor_import_plugin.h
+++ b/editor/import/editor_import_plugin.h
@@ -32,6 +32,7 @@
#define EDITOR_IMPORT_PLUGIN_H
#include "core/io/resource_importer.h"
+#include "core/variant/typed_array.h"
class EditorImportPlugin : public ResourceImporter {
GDCLASS(EditorImportPlugin, ResourceImporter);
@@ -44,7 +45,7 @@ protected:
GDVIRTUAL0RC(int, _get_preset_count)
GDVIRTUAL1RC(String, _get_preset_name, int)
GDVIRTUAL0RC(Vector<String>, _get_recognized_extensions)
- GDVIRTUAL2RC(Array, _get_import_options, String, int)
+ GDVIRTUAL2RC(TypedArray<Dictionary>, _get_import_options, String, int)
GDVIRTUAL0RC(String, _get_save_extension)
GDVIRTUAL0RC(String, _get_resource_type)
GDVIRTUAL0RC(float, _get_priority)
diff --git a/editor/import/post_import_plugin_skeleton_rest_fixer.cpp b/editor/import/post_import_plugin_skeleton_rest_fixer.cpp
index 4f00bd120a..685cb16eb1 100644
--- a/editor/import/post_import_plugin_skeleton_rest_fixer.cpp
+++ b/editor/import/post_import_plugin_skeleton_rest_fixer.cpp
@@ -38,16 +38,16 @@
void PostImportPluginSkeletonRestFixer::get_internal_import_options(InternalImportCategory p_category, List<ResourceImporter::ImportOption> *r_options) {
if (p_category == INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE) {
+ r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::BOOL, "retarget/rest_fixer/apply_node_transforms"), true));
r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::BOOL, "retarget/rest_fixer/normalize_position_tracks"), true));
r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::BOOL, "retarget/rest_fixer/overwrite_axis"), true));
-
r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::BOOL, "retarget/rest_fixer/fix_silhouette/enable"), false));
- r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::FLOAT, "retarget/rest_fixer/fix_silhouette/threshold"), 15));
-
// TODO: PostImportPlugin need to be implemented such as validate_option(PropertyInfo &property, const Dictionary &p_options).
// get_internal_option_visibility() is not sufficient because it can only retrieve options implemented in the core and can only read option values.
// r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::ARRAY, "retarget/rest_fixer/filter", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::STRING_NAME, PROPERTY_HINT_ENUM, "Hips,Spine,Chest")), Array()));
r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::ARRAY, "retarget/rest_fixer/fix_silhouette/filter", PROPERTY_HINT_ARRAY_TYPE, "StringName"), Array()));
+ r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::FLOAT, "retarget/rest_fixer/fix_silhouette/threshold"), 15));
+ r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::FLOAT, "retarget/rest_fixer/fix_silhouette/base_height_adjustment", PROPERTY_HINT_RANGE, "-1,1,0.01"), 0.0));
}
}
@@ -67,6 +67,7 @@ void PostImportPluginSkeletonRestFixer::internal_process(InternalImportCategory
if (!src_skeleton) {
return;
}
+
bool is_renamed = bool(p_options["retarget/bone_renamer/rename_bones"]);
Array filter = p_options["retarget/rest_fixer/fix_silhouette/filter"];
bool is_rest_changed = false;
@@ -89,44 +90,96 @@ void PostImportPluginSkeletonRestFixer::internal_process(InternalImportCategory
}
}
- // Set motion scale to Skeleton if normalize position tracks.
- if (bool(p_options["retarget/rest_fixer/normalize_position_tracks"])) {
- int src_bone_idx = src_skeleton->find_bone(profile->get_scale_base_bone());
- if (src_bone_idx >= 0) {
- real_t motion_scale = abs(src_skeleton->get_bone_global_rest(src_bone_idx).origin.y);
- if (motion_scale > 0) {
- src_skeleton->set_motion_scale(motion_scale);
+ // Apply node transforms.
+ if (bool(p_options["retarget/rest_fixer/apply_node_transforms"])) {
+ LocalVector<Transform3D> old_skeleton_rest;
+ LocalVector<Transform3D> old_skeleton_global_rest;
+ for (int i = 0; i < src_skeleton->get_bone_count(); i++) {
+ old_skeleton_rest.push_back(src_skeleton->get_bone_rest(i));
+ old_skeleton_global_rest.push_back(src_skeleton->get_bone_global_rest(i));
+ }
+
+ Transform3D global_transform;
+ Node *pr = src_skeleton;
+ while (pr) {
+ Node3D *pr3d = Object::cast_to<Node3D>(pr);
+ if (pr3d) {
+ global_transform = pr3d->get_transform() * global_transform;
+ pr3d->set_transform(Transform3D());
}
+ pr = pr->get_parent();
}
+ Vector3 scl = global_transform.basis.get_scale_local();
- TypedArray<Node> nodes = p_base_scene->find_children("*", "AnimationPlayer");
- while (nodes.size()) {
- AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(nodes.pop_back());
- List<StringName> anims;
- ap->get_animation_list(&anims);
- for (const StringName &name : anims) {
- Ref<Animation> anim = ap->get_animation(name);
- int track_len = anim->get_track_count();
- for (int i = 0; i < track_len; i++) {
- if (anim->track_get_path(i).get_subname_count() != 1 || anim->track_get_type(i) != Animation::TYPE_POSITION_3D) {
- continue;
- }
+ Vector<int> bones_to_process = src_skeleton->get_parentless_bones();
+ for (int i = 0; i < bones_to_process.size(); i++) {
+ src_skeleton->set_bone_rest(bones_to_process[i], global_transform.orthonormalized() * src_skeleton->get_bone_rest(bones_to_process[i]));
+ }
- if (anim->track_is_compressed(i)) {
- continue; // Shouldn't occur in internal_process().
- }
+ while (bones_to_process.size() > 0) {
+ int src_idx = bones_to_process[0];
+ bones_to_process.erase(src_idx);
+ Vector<int> src_children = src_skeleton->get_bone_children(src_idx);
+ for (int i = 0; i < src_children.size(); i++) {
+ bones_to_process.push_back(src_children[i]);
+ }
+ src_skeleton->set_bone_rest(src_idx, Transform3D(src_skeleton->get_bone_rest(src_idx).basis, src_skeleton->get_bone_rest(src_idx).origin * scl));
+ }
- String track_path = String(anim->track_get_path(i).get_concatenated_names());
- Node *node = (ap->get_node(ap->get_root()))->get_node(NodePath(track_path));
- if (node) {
- Skeleton3D *track_skeleton = Object::cast_to<Skeleton3D>(node);
- if (track_skeleton) {
+ // Fix animation.
+ bones_to_process = src_skeleton->get_parentless_bones();
+ {
+ TypedArray<Node> nodes = p_base_scene->find_children("*", "AnimationPlayer");
+ while (nodes.size()) {
+ AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(nodes.pop_back());
+ List<StringName> anims;
+ ap->get_animation_list(&anims);
+ for (const StringName &name : anims) {
+ Ref<Animation> anim = ap->get_animation(name);
+ int track_len = anim->get_track_count();
+ for (int i = 0; i < track_len; i++) {
+ if (anim->track_get_path(i).get_subname_count() != 1 || !(anim->track_get_type(i) == Animation::TYPE_POSITION_3D || anim->track_get_type(i) == Animation::TYPE_ROTATION_3D || anim->track_get_type(i) == Animation::TYPE_SCALE_3D)) {
+ continue;
+ }
+
+ if (anim->track_is_compressed(i)) {
+ continue; // Shouldn't occur in internal_process().
+ }
+
+ String track_path = String(anim->track_get_path(i).get_concatenated_names());
+ Node *node = (ap->get_node(ap->get_root()))->get_node(NodePath(track_path));
+ if (node) {
+ Skeleton3D *track_skeleton = Object::cast_to<Skeleton3D>(node);
if (track_skeleton && track_skeleton == src_skeleton) {
- real_t mlt = 1 / src_skeleton->get_motion_scale();
- int key_len = anim->track_get_key_count(i);
- for (int j = 0; j < key_len; j++) {
- Vector3 pos = static_cast<Vector3>(anim->track_get_key_value(i, j));
- anim->track_set_key_value(i, j, pos * mlt);
+ StringName bn = anim->track_get_path(i).get_subname(0);
+ if (bn) {
+ int bone_idx = src_skeleton->find_bone(bn);
+ int key_len = anim->track_get_key_count(i);
+ if (anim->track_get_type(i) == Animation::TYPE_POSITION_3D) {
+ if (bones_to_process.has(bone_idx)) {
+ for (int j = 0; j < key_len; j++) {
+ Vector3 ps = static_cast<Vector3>(anim->track_get_key_value(i, j));
+ anim->track_set_key_value(i, j, global_transform.basis.xform(ps) + global_transform.origin);
+ }
+ } else {
+ for (int j = 0; j < key_len; j++) {
+ Vector3 ps = static_cast<Vector3>(anim->track_get_key_value(i, j));
+ anim->track_set_key_value(i, j, ps * scl);
+ }
+ }
+ } else if (bones_to_process.has(bone_idx)) {
+ if (anim->track_get_type(i) == Animation::TYPE_ROTATION_3D) {
+ for (int j = 0; j < key_len; j++) {
+ Quaternion qt = static_cast<Quaternion>(anim->track_get_key_value(i, j));
+ anim->track_set_key_value(i, j, global_transform.basis.get_rotation_quaternion() * qt);
+ }
+ } else {
+ for (int j = 0; j < key_len; j++) {
+ Basis sc = Basis().scaled(static_cast<Vector3>(anim->track_get_key_value(i, j)));
+ anim->track_set_key_value(i, j, (global_transform.basis * sc).get_scale());
+ }
+ }
+ }
}
}
}
@@ -134,6 +187,8 @@ void PostImportPluginSkeletonRestFixer::internal_process(InternalImportCategory
}
}
}
+
+ is_rest_changed = true;
}
// Complement Rotation track for compatibility between different rests.
@@ -303,6 +358,52 @@ void PostImportPluginSkeletonRestFixer::internal_process(InternalImportCategory
}
}
+ // Adjust scale base bone height.
+ float base_adjustment = float(p_options["retarget/rest_fixer/fix_silhouette/base_height_adjustment"]);
+ if (!Math::is_zero_approx(base_adjustment)) {
+ StringName scale_base_bone_name = profile->get_scale_base_bone();
+ int src_bone_idx = src_skeleton->find_bone(scale_base_bone_name);
+ Transform3D src_rest = src_skeleton->get_bone_rest(src_bone_idx);
+ src_skeleton->set_bone_rest(src_bone_idx, Transform3D(src_rest.basis, Vector3(src_rest.origin.x, src_rest.origin.y + base_adjustment, src_rest.origin.z)));
+
+ TypedArray<Node> nodes = p_base_scene->find_children("*", "AnimationPlayer");
+ while (nodes.size()) {
+ AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(nodes.pop_back());
+ List<StringName> anims;
+ ap->get_animation_list(&anims);
+ for (const StringName &name : anims) {
+ Ref<Animation> anim = ap->get_animation(name);
+ int track_len = anim->get_track_count();
+ for (int i = 0; i < track_len; i++) {
+ if (anim->track_get_path(i).get_subname_count() != 1 || anim->track_get_type(i) != Animation::TYPE_POSITION_3D) {
+ continue;
+ }
+
+ if (anim->track_is_compressed(i)) {
+ continue; // Shouldn't occur in internal_process().
+ }
+
+ String track_path = String(anim->track_get_path(i).get_concatenated_names());
+ Node *node = (ap->get_node(ap->get_root()))->get_node(NodePath(track_path));
+ if (node) {
+ Skeleton3D *track_skeleton = Object::cast_to<Skeleton3D>(node);
+ if (track_skeleton && track_skeleton == src_skeleton) {
+ StringName bn = anim->track_get_path(i).get_concatenated_subnames();
+ if (bn == scale_base_bone_name) {
+ int key_len = anim->track_get_key_count(i);
+ for (int j = 0; j < key_len; j++) {
+ Vector3 pos = static_cast<Vector3>(anim->track_get_key_value(i, j));
+ pos.y += base_adjustment;
+ anim->track_set_key_value(i, j, pos);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
// For skin modification in overwrite rest.
for (int i = 0; i < src_skeleton->get_bone_count(); i++) {
silhouette_diff_w[i] = old_skeleton_global_rest[i] * src_skeleton->get_bone_global_rest(i).inverse();
@@ -311,6 +412,51 @@ void PostImportPluginSkeletonRestFixer::internal_process(InternalImportCategory
is_rest_changed = true;
}
+ // Set motion scale to Skeleton if normalize position tracks.
+ if (bool(p_options["retarget/rest_fixer/normalize_position_tracks"])) {
+ int src_bone_idx = src_skeleton->find_bone(profile->get_scale_base_bone());
+ if (src_bone_idx >= 0) {
+ real_t motion_scale = abs(src_skeleton->get_bone_global_rest(src_bone_idx).origin.y);
+ if (motion_scale > 0) {
+ src_skeleton->set_motion_scale(motion_scale);
+ }
+ }
+
+ TypedArray<Node> nodes = p_base_scene->find_children("*", "AnimationPlayer");
+ while (nodes.size()) {
+ AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(nodes.pop_back());
+ List<StringName> anims;
+ ap->get_animation_list(&anims);
+ for (const StringName &name : anims) {
+ Ref<Animation> anim = ap->get_animation(name);
+ int track_len = anim->get_track_count();
+ for (int i = 0; i < track_len; i++) {
+ if (anim->track_get_path(i).get_subname_count() != 1 || anim->track_get_type(i) != Animation::TYPE_POSITION_3D) {
+ continue;
+ }
+
+ if (anim->track_is_compressed(i)) {
+ continue; // Shouldn't occur in internal_process().
+ }
+
+ String track_path = String(anim->track_get_path(i).get_concatenated_names());
+ Node *node = (ap->get_node(ap->get_root()))->get_node(NodePath(track_path));
+ if (node) {
+ Skeleton3D *track_skeleton = Object::cast_to<Skeleton3D>(node);
+ if (track_skeleton && track_skeleton == src_skeleton) {
+ real_t mlt = 1 / src_skeleton->get_motion_scale();
+ int key_len = anim->track_get_key_count(i);
+ for (int j = 0; j < key_len; j++) {
+ Vector3 pos = static_cast<Vector3>(anim->track_get_key_value(i, j));
+ anim->track_set_key_value(i, j, pos * mlt);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
// Overwrite axis.
if (bool(p_options["retarget/rest_fixer/overwrite_axis"])) {
LocalVector<Transform3D> old_skeleton_rest;
@@ -367,32 +513,6 @@ void PostImportPluginSkeletonRestFixer::internal_process(InternalImportCategory
src_skeleton->set_bone_rest(src_idx, Transform3D(tgt_rot, diff.xform(src_skeleton->get_bone_rest(src_idx).origin)));
}
- // Fix skin.
- {
- TypedArray<Node> nodes = p_base_scene->find_children("*", "ImporterMeshInstance3D");
- while (nodes.size()) {
- ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(nodes.pop_back());
- Ref<Skin> skin = mi->get_skin();
- if (skin.is_valid()) {
- Node *node = mi->get_node(mi->get_skeleton_path());
- if (node) {
- Skeleton3D *mesh_skeleton = Object::cast_to<Skeleton3D>(node);
- if (mesh_skeleton && node == src_skeleton) {
- int skin_len = skin->get_bind_count();
- for (int i = 0; i < skin_len; i++) {
- StringName bn = skin->get_bind_name(i);
- int bone_idx = src_skeleton->find_bone(bn);
- if (bone_idx >= 0) {
- Transform3D new_rest = silhouette_diff[i] * src_skeleton->get_bone_global_rest(bone_idx);
- skin->set_bind_pose(i, new_rest.inverse());
- }
- }
- }
- }
- }
- }
- }
-
// Fix animation.
{
TypedArray<Node> nodes = p_base_scene->find_children("*", "AnimationPlayer");
@@ -471,8 +591,34 @@ void PostImportPluginSkeletonRestFixer::internal_process(InternalImportCategory
is_rest_changed = true;
}
- // Init skeleton pose to new rest.
if (is_rest_changed) {
+ // Fix skin.
+ {
+ TypedArray<Node> nodes = p_base_scene->find_children("*", "ImporterMeshInstance3D");
+ while (nodes.size()) {
+ ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(nodes.pop_back());
+ Ref<Skin> skin = mi->get_skin();
+ if (skin.is_valid()) {
+ Node *node = mi->get_node(mi->get_skeleton_path());
+ if (node) {
+ Skeleton3D *mesh_skeleton = Object::cast_to<Skeleton3D>(node);
+ if (mesh_skeleton && node == src_skeleton) {
+ int skin_len = skin->get_bind_count();
+ for (int i = 0; i < skin_len; i++) {
+ StringName bn = skin->get_bind_name(i);
+ int bone_idx = src_skeleton->find_bone(bn);
+ if (bone_idx >= 0) {
+ Transform3D new_rest = silhouette_diff[i] * src_skeleton->get_bone_global_rest(bone_idx);
+ skin->set_bind_pose(i, new_rest.inverse());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Init skeleton pose to new rest.
for (int i = 0; i < src_skeleton->get_bone_count(); i++) {
Transform3D fixed_rest = src_skeleton->get_bone_rest(i);
src_skeleton->set_bone_pose_position(i, fixed_rest.origin);
diff --git a/editor/import/resource_importer_layered_texture.cpp b/editor/import/resource_importer_layered_texture.cpp
index b301bbf0f9..ed83535421 100644
--- a/editor/import/resource_importer_layered_texture.cpp
+++ b/editor/import/resource_importer_layered_texture.cpp
@@ -327,7 +327,7 @@ Error ResourceImporterLayeredTexture::import(const String &p_source_file, const
Ref<Image> image;
image.instantiate();
- Error err = ImageLoader::load_image(p_source_file, image, nullptr, false, 1.0);
+ Error err = ImageLoader::load_image(p_source_file, image);
if (err != OK) {
return err;
}
diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp
index 3c0de61d24..85dda24f8e 100644
--- a/editor/import/resource_importer_scene.cpp
+++ b/editor/import/resource_importer_scene.cpp
@@ -850,12 +850,12 @@ Node *ResourceImporterScene::_post_fix_animations(Node *p_node, Node *p_root, co
AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
bool use_optimizer = node_settings["optimizer/enabled"];
- float anim_optimizer_linerr = node_settings["optimizer/max_linear_error"];
+ float anim_optimizer_linerr = node_settings["optimizer/max_velocity_error"];
float anim_optimizer_angerr = node_settings["optimizer/max_angular_error"];
- float anim_optimizer_maxang = node_settings["optimizer/max_angle"];
+ int anim_optimizer_preerr = node_settings["optimizer/max_precision_error"];
if (use_optimizer) {
- _optimize_animations(ap, anim_optimizer_linerr, anim_optimizer_angerr, anim_optimizer_maxang);
+ _optimize_animations(ap, anim_optimizer_linerr, anim_optimizer_angerr, anim_optimizer_preerr);
}
bool use_compression = node_settings["compression/enabled"];
@@ -1386,12 +1386,12 @@ void ResourceImporterScene::_create_clips(AnimationPlayer *anim, const Array &p_
al->remove_animation("default"); // Remove default (no longer needed).
}
-void ResourceImporterScene::_optimize_animations(AnimationPlayer *anim, float p_max_lin_error, float p_max_ang_error, float p_max_angle) {
+void ResourceImporterScene::_optimize_animations(AnimationPlayer *anim, float p_max_vel_error, float p_max_ang_error, int p_prc_error) {
List<StringName> anim_names;
anim->get_animation_list(&anim_names);
for (const StringName &E : anim_names) {
Ref<Animation> a = anim->get_animation(E);
- a->optimize(p_max_lin_error, p_max_ang_error, Math::deg2rad(p_max_angle));
+ a->optimize(p_max_vel_error, p_max_ang_error, p_prc_error);
}
}
@@ -1467,9 +1467,9 @@ void ResourceImporterScene::get_internal_import_options(InternalImportCategory p
case INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE: {
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "import/skip_import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "optimizer/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "optimizer/max_linear_error"), 0.05));
- r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "optimizer/max_angular_error"), 0.01));
- r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "optimizer/max_angle"), 22));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "optimizer/max_velocity_error", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.01));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "optimizer/max_angular_error", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.01));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "optimizer/max_precision_error", PROPERTY_HINT_NONE, "1,6,1"), 3));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compression/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compression/page_size", PROPERTY_HINT_RANGE, "4,512,1,suffix:kb"), 8));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_tracks/position", PROPERTY_HINT_ENUM, "IfPresent,IfPresentForAll,Never"), 1));
diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h
index b336931476..da37893cc5 100644
--- a/editor/import/resource_importer_scene.h
+++ b/editor/import/resource_importer_scene.h
@@ -280,7 +280,7 @@ public:
Ref<Animation> _save_animation_to_file(Ref<Animation> anim, bool p_save_to_file, String p_save_to_path, bool p_keep_custom_tracks);
void _create_clips(AnimationPlayer *anim, const Array &p_clips, bool p_bake_all);
- void _optimize_animations(AnimationPlayer *anim, float p_max_lin_error, float p_max_ang_error, float p_max_angle);
+ void _optimize_animations(AnimationPlayer *anim, float p_max_vel_error, float p_max_ang_error, int p_prc_error);
void _compress_animations(AnimationPlayer *anim, int p_page_size_kb);
Node *pre_import(const String &p_source_file, const HashMap<StringName, Variant> &p_options);
diff --git a/editor/import/resource_importer_texture.cpp b/editor/import/resource_importer_texture.cpp
index 0eed6184c0..17b94ec706 100644
--- a/editor/import/resource_importer_texture.cpp
+++ b/editor/import/resource_importer_texture.cpp
@@ -409,11 +409,26 @@ void ResourceImporterTexture::_save_ctex(const Ref<Image> &p_image, const String
}
Error ResourceImporterTexture::import(const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
+ // Parse import options.
+ int32_t loader_flags = ImageFormatLoader::FLAG_NONE;
+
+ // Compression.
CompressMode compress_mode = CompressMode(int(p_options["compress/mode"]));
const float lossy = p_options["compress/lossy_quality"];
const int pack_channels = p_options["compress/channel_pack"];
+ const int normal = p_options["compress/normal_map"];
+ const int hdr_compression = p_options["compress/hdr_compression"];
+ const int bptc_ldr = p_options["compress/bptc_ldr"];
+
+ // Mipmaps.
const bool mipmaps = p_options["mipmaps/generate"];
const uint32_t mipmap_limit = mipmaps ? uint32_t(p_options["mipmaps/limit"]) : uint32_t(-1);
+
+ // Roughness.
+ const int roughness = p_options["roughness/mode"];
+ const String normal_map = p_options["roughness/src_normal"];
+
+ // Processing.
const bool fix_alpha_border = p_options["process/fix_alpha_border"];
const bool premult_alpha = p_options["process/premult_alpha"];
const bool normal_map_invert_y = p_options["process/normal_map_invert_y"];
@@ -421,29 +436,29 @@ Error ResourceImporterTexture::import(const String &p_source_file, const String
const bool stream = false;
const int size_limit = p_options["process/size_limit"];
const bool hdr_as_srgb = p_options["process/hdr_as_srgb"];
+ if (hdr_as_srgb) {
+ loader_flags |= ImageFormatLoader::FLAG_FORCE_LINEAR;
+ }
const bool hdr_clamp_exposure = p_options["process/hdr_clamp_exposure"];
- const int normal = p_options["compress/normal_map"];
- const int hdr_compression = p_options["compress/hdr_compression"];
- const int bptc_ldr = p_options["compress/bptc_ldr"];
- const int roughness = p_options["roughness/mode"];
- const String normal_map = p_options["roughness/src_normal"];
+
float scale = 1.0;
+ // SVG-specific options.
if (p_options.has("svg/scale")) {
scale = p_options["svg/scale"];
}
Ref<Image> normal_image;
Image::RoughnessChannel roughness_channel = Image::ROUGHNESS_CHANNEL_R;
-
if (mipmaps && roughness > 1 && FileAccess::exists(normal_map)) {
normal_image.instantiate();
if (ImageLoader::load_image(normal_map, normal_image) == OK) {
roughness_channel = Image::RoughnessChannel(roughness - 2);
}
}
+
Ref<Image> image;
image.instantiate();
- Error err = ImageLoader::load_image(p_source_file, image, nullptr, hdr_as_srgb, scale);
+ Error err = ImageLoader::load_image(p_source_file, image, nullptr, loader_flags, scale);
if (err != OK) {
return err;
}
diff --git a/editor/import/resource_importer_texture_atlas.cpp b/editor/import/resource_importer_texture_atlas.cpp
index bae1b903c6..9171f04f42 100644
--- a/editor/import/resource_importer_texture_atlas.cpp
+++ b/editor/import/resource_importer_texture_atlas.cpp
@@ -382,7 +382,6 @@ Error ResourceImporterTextureAtlas::import_group_file(const String &p_group_file
mesh_texture->set_mesh(mesh);
texture = mesh_texture;
- //mesh
}
String save_path = p_base_paths[E.key] + ".res";
diff --git a/editor/inspector_dock.cpp b/editor/inspector_dock.cpp
index 79d94246ad..b0ff678a3e 100644
--- a/editor/inspector_dock.cpp
+++ b/editor/inspector_dock.cpp
@@ -178,7 +178,8 @@ void InspectorDock::_menu_option_confirm(int p_option, bool p_confirmed) {
}
}
- editor_data->get_undo_redo().clear_history();
+ int history_id = editor_data->get_undo_redo()->get_history_for_object(current).id;
+ editor_data->get_undo_redo()->clear_history(true, history_id);
EditorNode::get_singleton()->get_editor_plugins_over()->edit(nullptr);
EditorNode::get_singleton()->get_editor_plugins_over()->edit(current);
@@ -246,7 +247,7 @@ void InspectorDock::_resource_file_selected(String p_file) {
}
if (res.is_null()) {
- warning_dialog->set_text(TTR("Failed to load resource."));
+ info_dialog->set_text(TTR("Failed to load resource."));
return;
};
@@ -408,8 +409,8 @@ void InspectorDock::_menu_expand_revertable() {
inspector->expand_revertable();
}
-void InspectorDock::_warning_pressed() {
- warning_dialog->popup_centered();
+void InspectorDock::_info_pressed() {
+ info_dialog->popup_centered();
}
Container *InspectorDock::get_addon_area() {
@@ -445,8 +446,13 @@ void InspectorDock::_notification(int p_what) {
history_menu->set_icon(get_theme_icon(SNAME("History"), SNAME("EditorIcons")));
object_menu->set_icon(get_theme_icon(SNAME("Tools"), SNAME("EditorIcons")));
search->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
- warning->set_icon(get_theme_icon(SNAME("NodeWarning"), SNAME("EditorIcons")));
- warning->add_theme_color_override("font_color", get_theme_color(SNAME("warning_color"), SNAME("Editor")));
+ if (info_is_warning) {
+ info->set_icon(get_theme_icon(SNAME("NodeWarning"), SNAME("EditorIcons")));
+ info->add_theme_color_override("font_color", get_theme_color(SNAME("warning_color"), SNAME("Editor")));
+ } else {
+ info->set_icon(get_theme_icon(SNAME("NodeInfo"), SNAME("EditorIcons")));
+ info->add_theme_color_override("font_color", get_theme_color(SNAME("font_color"), SNAME("Editor")));
+ }
} break;
}
}
@@ -475,11 +481,22 @@ void InspectorDock::open_resource(const String &p_type) {
_load_resource(p_type);
}
-void InspectorDock::set_warning(const String &p_message) {
- warning->hide();
- if (!p_message.is_empty()) {
- warning->show();
- warning_dialog->set_text(p_message);
+void InspectorDock::set_info(const String &p_button_text, const String &p_message, bool p_is_warning) {
+ info->hide();
+ info_is_warning = p_is_warning;
+
+ if (info_is_warning) {
+ info->set_icon(get_theme_icon(SNAME("NodeWarning"), SNAME("EditorIcons")));
+ info->add_theme_color_override("font_color", get_theme_color(SNAME("warning_color"), SNAME("Editor")));
+ } else {
+ info->set_icon(get_theme_icon(SNAME("NodeInfo"), SNAME("EditorIcons")));
+ info->add_theme_color_override("font_color", get_theme_color(SNAME("font_color"), SNAME("Editor")));
+ }
+
+ if (!p_button_text.is_empty() && !p_message.is_empty()) {
+ info->show();
+ info->set_text(p_button_text);
+ info_dialog->set_text(p_message);
}
}
@@ -514,7 +531,7 @@ void InspectorDock::update(Object *p_object) {
resource_extra_popup->set_item_disabled(resource_extra_popup->get_item_index(RESOURCE_MAKE_BUILT_IN), !is_resource || is_text_file);
if (!is_object || is_text_file) {
- warning->hide();
+ info->hide();
editor_path->clear_path();
return;
}
@@ -706,12 +723,11 @@ InspectorDock::InspectorDock(EditorData &p_editor_data) {
object_menu->get_popup()->connect("about_to_popup", callable_mp(this, &InspectorDock::_prepare_menu));
object_menu->get_popup()->connect("id_pressed", callable_mp(this, &InspectorDock::_menu_option));
- warning = memnew(Button);
- add_child(warning);
- warning->set_text(TTR("Changes may be lost!"));
- warning->set_clip_text(true);
- warning->hide();
- warning->connect("pressed", callable_mp(this, &InspectorDock::_warning_pressed));
+ info = memnew(Button);
+ add_child(info);
+ info->set_clip_text(true);
+ info->hide();
+ info->connect("pressed", callable_mp(this, &InspectorDock::_info_pressed));
unique_resources_confirmation = memnew(ConfirmationDialog);
add_child(unique_resources_confirmation);
@@ -736,8 +752,8 @@ InspectorDock::InspectorDock(EditorData &p_editor_data) {
unique_resources_confirmation->connect("confirmed", callable_mp(this, &InspectorDock::_menu_confirm_current));
- warning_dialog = memnew(AcceptDialog);
- EditorNode::get_singleton()->get_gui_base()->add_child(warning_dialog);
+ info_dialog = memnew(AcceptDialog);
+ EditorNode::get_singleton()->get_gui_base()->add_child(info_dialog);
load_resource_dialog = memnew(EditorFileDialog);
add_child(load_resource_dialog);
@@ -755,7 +771,7 @@ InspectorDock::InspectorDock(EditorData &p_editor_data) {
inspector->set_property_name_style(EditorPropertyNameProcessor::get_default_inspector_style());
inspector->set_use_folding(!bool(EDITOR_GET("interface/inspector/disable_folding")));
inspector->register_text_enter(search);
- inspector->set_undo_redo(&editor_data->get_undo_redo());
+ inspector->set_undo_redo(editor_data->get_undo_redo());
inspector->set_use_filter(true); // TODO: check me
diff --git a/editor/inspector_dock.h b/editor/inspector_dock.h
index e32410151f..5ebcbf70c7 100644
--- a/editor/inspector_dock.h
+++ b/editor/inspector_dock.h
@@ -93,8 +93,9 @@ class InspectorDock : public VBoxContainer {
MenuButton *object_menu = nullptr;
EditorPath *editor_path = nullptr;
- Button *warning = nullptr;
- AcceptDialog *warning_dialog = nullptr;
+ bool info_is_warning = false; // Display in yellow and use warning icon if true.
+ Button *info = nullptr;
+ AcceptDialog *info_dialog = nullptr;
int current_option = -1;
ConfirmationDialog *unique_resources_confirmation = nullptr;
@@ -118,7 +119,7 @@ class InspectorDock : public VBoxContainer {
void _paste_resource();
void _prepare_resource_extra_popup();
- void _warning_pressed();
+ void _info_pressed();
void _resource_created();
void _resource_selected(const Ref<Resource> &p_res, const String &p_property);
void _edit_forward();
@@ -145,7 +146,7 @@ public:
void edit_resource(const Ref<Resource> &p_resource);
void open_resource(const String &p_type);
void clear();
- void set_warning(const String &p_message);
+ void set_info(const String &p_button_text, const String &p_message, bool p_is_warning);
void update(Object *p_object);
Container *get_addon_area();
EditorInspector *get_inspector() { return inspector; }
diff --git a/editor/localization_editor.cpp b/editor/localization_editor.cpp
index e8fb80eb57..77a1700ebf 100644
--- a/editor/localization_editor.cpp
+++ b/editor/localization_editor.cpp
@@ -36,6 +36,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_translation_parser.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/filesystem_dock.h"
#include "editor/pot_generator.h"
#include "scene/gui/control.h"
diff --git a/editor/localization_editor.h b/editor/localization_editor.h
index 10ccdfdc13..ecac171fe3 100644
--- a/editor/localization_editor.h
+++ b/editor/localization_editor.h
@@ -56,7 +56,7 @@ class LocalizationEditor : public VBoxContainer {
EditorFileDialog *pot_file_open_dialog = nullptr;
EditorFileDialog *pot_generate_dialog = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
bool updating_translations = false;
String localization_changed;
diff --git a/editor/multi_node_edit.cpp b/editor/multi_node_edit.cpp
index a694b8d754..70cc54668d 100644
--- a/editor/multi_node_edit.cpp
+++ b/editor/multi_node_edit.cpp
@@ -32,6 +32,7 @@
#include "core/math/math_fieldwise.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
bool MultiNodeEdit::_set(const StringName &p_name, const Variant &p_value) {
return _set_impl(p_name, p_value, "");
@@ -54,7 +55,7 @@ bool MultiNodeEdit::_set_impl(const StringName &p_name, const Variant &p_value,
node_path_target = es->get_node(p_value);
}
- UndoRedo *ur = EditorNode::get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("MultiNode Set") + " " + String(name), UndoRedo::MERGE_ENDS);
for (const NodePath &E : nodes) {
diff --git a/editor/node_dock.cpp b/editor/node_dock.cpp
index 986370f537..55fa2f22dd 100644
--- a/editor/node_dock.cpp
+++ b/editor/node_dock.cpp
@@ -117,7 +117,7 @@ NodeDock::NodeDock() {
groups_button->connect("pressed", callable_mp(this, &NodeDock::show_groups));
connections = memnew(ConnectionsDock);
- connections->set_undoredo(EditorNode::get_undo_redo());
+ connections->set_undo_redo(EditorNode::get_undo_redo());
add_child(connections);
connections->set_v_size_flags(SIZE_EXPAND_FILL);
connections->hide();
diff --git a/editor/plugins/abstract_polygon_2d_editor.cpp b/editor/plugins/abstract_polygon_2d_editor.cpp
index a7d7c0145a..275859f528 100644
--- a/editor/plugins/abstract_polygon_2d_editor.cpp
+++ b/editor/plugins/abstract_polygon_2d_editor.cpp
@@ -36,6 +36,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/separator.h"
bool AbstractPolygon2DEditor::Vertex::operator==(const AbstractPolygon2DEditor::Vertex &p_vertex) const {
diff --git a/editor/plugins/abstract_polygon_2d_editor.h b/editor/plugins/abstract_polygon_2d_editor.h
index 696fd7b637..1fbbe67c8d 100644
--- a/editor/plugins/abstract_polygon_2d_editor.h
+++ b/editor/plugins/abstract_polygon_2d_editor.h
@@ -36,6 +36,7 @@
#include "scene/gui/box_container.h"
class CanvasItemEditor;
+class EditorUndoRedoManager;
class AbstractPolygon2DEditor : public HBoxContainer {
GDCLASS(AbstractPolygon2DEditor, HBoxContainer);
@@ -99,7 +100,7 @@ protected:
int mode = MODE_EDIT;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
virtual void _menu_option(int p_option);
void _wip_changed();
diff --git a/editor/plugins/animation_blend_space_1d_editor.cpp b/editor/plugins/animation_blend_space_1d_editor.cpp
index 32d97c65a9..2578099a9f 100644
--- a/editor/plugins/animation_blend_space_1d_editor.cpp
+++ b/editor/plugins/animation_blend_space_1d_editor.cpp
@@ -35,6 +35,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/animation/animation_blend_tree.h"
StringName AnimationNodeBlendSpace1DEditor::get_blend_position_path() const {
diff --git a/editor/plugins/animation_blend_space_1d_editor.h b/editor/plugins/animation_blend_space_1d_editor.h
index 9b06f3248f..125a3382fa 100644
--- a/editor/plugins/animation_blend_space_1d_editor.h
+++ b/editor/plugins/animation_blend_space_1d_editor.h
@@ -40,6 +40,8 @@
#include "scene/gui/separator.h"
#include "scene/gui/tree.h"
+class EditorUndoRedoManager;
+
class AnimationNodeBlendSpace1DEditor : public AnimationTreeNodeEditorPlugin {
GDCLASS(AnimationNodeBlendSpace1DEditor, AnimationTreeNodeEditorPlugin);
@@ -76,7 +78,7 @@ class AnimationNodeBlendSpace1DEditor : public AnimationTreeNodeEditorPlugin {
bool updating = false;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
static AnimationNodeBlendSpace1DEditor *singleton;
diff --git a/editor/plugins/animation_blend_space_2d_editor.cpp b/editor/plugins/animation_blend_space_2d_editor.cpp
index dc764725dd..c0723cef87 100644
--- a/editor/plugins/animation_blend_space_2d_editor.cpp
+++ b/editor/plugins/animation_blend_space_2d_editor.cpp
@@ -39,6 +39,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/animation/animation_blend_tree.h"
#include "scene/animation/animation_player.h"
#include "scene/gui/menu_button.h"
diff --git a/editor/plugins/animation_blend_space_2d_editor.h b/editor/plugins/animation_blend_space_2d_editor.h
index 26471df051..df2bcf254d 100644
--- a/editor/plugins/animation_blend_space_2d_editor.h
+++ b/editor/plugins/animation_blend_space_2d_editor.h
@@ -40,6 +40,8 @@
#include "scene/gui/separator.h"
#include "scene/gui/tree.h"
+class EditorUndoRedoManager;
+
class AnimationNodeBlendSpace2DEditor : public AnimationTreeNodeEditorPlugin {
GDCLASS(AnimationNodeBlendSpace2DEditor, AnimationTreeNodeEditorPlugin);
@@ -82,7 +84,7 @@ class AnimationNodeBlendSpace2DEditor : public AnimationTreeNodeEditorPlugin {
bool updating;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
static AnimationNodeBlendSpace2DEditor *singleton;
diff --git a/editor/plugins/animation_blend_tree_editor_plugin.cpp b/editor/plugins/animation_blend_tree_editor_plugin.cpp
index 79be2d04b3..e4f5576d66 100644
--- a/editor/plugins/animation_blend_tree_editor_plugin.cpp
+++ b/editor/plugins/animation_blend_tree_editor_plugin.cpp
@@ -39,6 +39,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/animation/animation_player.h"
#include "scene/gui/menu_button.h"
#include "scene/gui/panel.h"
diff --git a/editor/plugins/animation_blend_tree_editor_plugin.h b/editor/plugins/animation_blend_tree_editor_plugin.h
index 18199676b8..af43da6197 100644
--- a/editor/plugins/animation_blend_tree_editor_plugin.h
+++ b/editor/plugins/animation_blend_tree_editor_plugin.h
@@ -41,6 +41,7 @@
class ProgressBar;
class EditorFileDialog;
+class EditorUndoRedoManager;
class AnimationNodeBlendTreeEditor : public AnimationTreeNodeEditorPlugin {
GDCLASS(AnimationNodeBlendTreeEditor, AnimationTreeNodeEditorPlugin);
@@ -54,7 +55,7 @@ class AnimationNodeBlendTreeEditor : public AnimationTreeNodeEditorPlugin {
PanelContainer *error_panel = nullptr;
Label *error_label = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
AcceptDialog *filter_dialog = nullptr;
Tree *filters = nullptr;
diff --git a/editor/plugins/animation_library_editor.cpp b/editor/plugins/animation_library_editor.cpp
index c36ae1c521..f9e5aa799a 100644
--- a/editor/plugins/animation_library_editor.cpp
+++ b/editor/plugins/animation_library_editor.cpp
@@ -32,6 +32,7 @@
#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
void AnimationLibraryEditor::set_animation_player(Object *p_player) {
player = p_player;
@@ -92,7 +93,7 @@ void AnimationLibraryEditor::_add_library_validate(const String &p_name) {
void AnimationLibraryEditor::_add_library_confirm() {
if (adding_animation) {
String anim_name = add_library_name->get_text();
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
Ref<AnimationLibrary> al = player->call("get_animation_library", adding_animation_to_library);
ERR_FAIL_COND(!al.is_valid());
@@ -109,7 +110,7 @@ void AnimationLibraryEditor::_add_library_confirm() {
} else {
String lib_name = add_library_name->get_text();
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
Ref<AnimationLibrary> al;
al.instantiate();
@@ -203,7 +204,7 @@ void AnimationLibraryEditor::_file_popup_selected(int p_id) {
// TODO: should probably make all foreign animations assigned to this library
// unique too.
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Make Animation Library Unique: %s"), lib_name));
undo_redo->add_do_method(player, "remove_animation_library", lib_name);
undo_redo->add_do_method(player, "add_animation_library", lib_name, ald);
@@ -272,7 +273,7 @@ void AnimationLibraryEditor::_file_popup_selected(int p_id) {
Ref<Animation> animd = anim->duplicate();
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Make Animation Unique: %s"), anim_name));
undo_redo->add_do_method(al.ptr(), "remove_animation", anim_name);
undo_redo->add_do_method(al.ptr(), "add_animation", anim_name, animd);
@@ -320,7 +321,7 @@ void AnimationLibraryEditor::_load_file(String p_path) {
name = p_path.get_file().get_basename() + " " + itos(attempt);
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Add Animation Library: %s"), name));
undo_redo->add_do_method(player, "add_animation_library", name, al);
@@ -358,7 +359,7 @@ void AnimationLibraryEditor::_load_file(String p_path) {
name = p_path.get_file().get_basename() + " " + itos(attempt);
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Load Animation into Library: %s"), name));
undo_redo->add_do_method(al.ptr(), "add_animation", name, anim);
@@ -374,7 +375,7 @@ void AnimationLibraryEditor::_load_file(String p_path) {
EditorNode::get_singleton()->save_resource_in_path(al, p_path);
if (al->get_path() != prev_path) { // Save successful.
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Save Animation library to File: %s"), file_dialog_library));
undo_redo->add_do_method(al.ptr(), "set_path", al->get_path());
@@ -395,7 +396,7 @@ void AnimationLibraryEditor::_load_file(String p_path) {
String prev_path = anim->get_path();
EditorNode::get_singleton()->save_resource_in_path(anim, p_path);
if (anim->get_path() != prev_path) { // Save successful.
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Save Animation to File: %s"), file_dialog_animation));
undo_redo->add_do_method(anim.ptr(), "set_path", anim->get_path());
@@ -413,7 +414,7 @@ void AnimationLibraryEditor::_item_renamed() {
String text = ti->get_text(0);
String old_text = ti->get_metadata(0);
bool restore_text = false;
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
if (String(text).contains("/") || String(text).contains(":") || String(text).contains(",") || String(text).contains("[")) {
restore_text = true;
@@ -527,7 +528,7 @@ void AnimationLibraryEditor::_button_pressed(TreeItem *p_item, int p_column, int
name = base_name + " (" + itos(attempt) + ")";
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Add Animation to Library: %s"), name));
undo_redo->add_do_method(al.ptr(), "add_animation", name, anim);
@@ -553,7 +554,7 @@ void AnimationLibraryEditor::_button_pressed(TreeItem *p_item, int p_column, int
file_dialog_library = lib_name;
} break;
case LIB_BUTTON_DELETE: {
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Remove Animation Library: %s"), lib_name));
undo_redo->add_do_method(player, "remove_animation_library", lib_name);
undo_redo->add_undo_method(player, "add_animation_library", lib_name, al);
@@ -594,7 +595,7 @@ void AnimationLibraryEditor::_button_pressed(TreeItem *p_item, int p_column, int
} break;
case ANIM_BUTTON_DELETE: {
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(vformat(TTR("Remove Animation from Library: %s"), anim_name));
undo_redo->add_do_method(al.ptr(), "remove_animation", anim_name);
undo_redo->add_undo_method(al.ptr(), "add_animation", anim_name, anim);
diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp
index 516079673d..f374f48fb2 100644
--- a/editor/plugins/animation_player_editor_plugin.cpp
+++ b/editor/plugins/animation_player_editor_plugin.cpp
@@ -1045,6 +1045,10 @@ void AnimationPlayerEditor::_update_name_dialog_library_dropdown() {
}
}
+void AnimationPlayerEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
void AnimationPlayerEditor::edit(AnimationPlayer *p_player) {
if (player && pin->is_pressed()) {
return; // Ignore, pinned.
@@ -1925,7 +1929,7 @@ void AnimationPlayerEditorPlugin::_update_keying() {
}
void AnimationPlayerEditorPlugin::edit(Object *p_object) {
- anim_editor->set_undo_redo(&get_undo_redo());
+ anim_editor->set_undo_redo(get_undo_redo());
if (!p_object) {
return;
}
diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h
index 3b1de070fa..a37a9debef 100644
--- a/editor/plugins/animation_player_editor_plugin.h
+++ b/editor/plugins/animation_player_editor_plugin.h
@@ -41,6 +41,7 @@
#include "scene/gui/texture_button.h"
#include "scene/gui/tree.h"
+class EditorUndoRedoManager;
class AnimationPlayerEditorPlugin;
class AnimationPlayerEditor : public VBoxContainer {
@@ -100,7 +101,7 @@ class AnimationPlayerEditor : public VBoxContainer {
LineEdit *name = nullptr;
OptionButton *library = nullptr;
Label *name_title = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Ref<Texture2D> autoplay_icon;
Ref<Texture2D> reset_icon;
@@ -233,7 +234,7 @@ public:
void ensure_visibility();
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void edit(AnimationPlayer *p_player);
void forward_force_draw_over_viewport(Control *p_overlay);
diff --git a/editor/plugins/animation_state_machine_editor.cpp b/editor/plugins/animation_state_machine_editor.cpp
index 473450b292..ef4ae3dca4 100644
--- a/editor/plugins/animation_state_machine_editor.cpp
+++ b/editor/plugins/animation_state_machine_editor.cpp
@@ -39,6 +39,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/animation/animation_blend_tree.h"
#include "scene/animation/animation_player.h"
#include "scene/gui/menu_button.h"
diff --git a/editor/plugins/animation_state_machine_editor.h b/editor/plugins/animation_state_machine_editor.h
index 165940e639..fdd1af0f6d 100644
--- a/editor/plugins/animation_state_machine_editor.h
+++ b/editor/plugins/animation_state_machine_editor.h
@@ -40,6 +40,7 @@
#include "scene/gui/tree.h"
class EditorFileDialog;
+class EditorUndoRedoManager;
class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin {
GDCLASS(AnimationNodeStateMachineEditor, AnimationTreeNodeEditorPlugin);
@@ -76,7 +77,7 @@ class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin {
bool updating = false;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
static AnimationNodeStateMachineEditor *singleton;
diff --git a/editor/plugins/audio_stream_randomizer_editor_plugin.cpp b/editor/plugins/audio_stream_randomizer_editor_plugin.cpp
index 9e551ae0ed..d670197c53 100644
--- a/editor/plugins/audio_stream_randomizer_editor_plugin.cpp
+++ b/editor/plugins/audio_stream_randomizer_editor_plugin.cpp
@@ -31,6 +31,7 @@
#include "audio_stream_randomizer_editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
void AudioStreamRandomizerEditorPlugin::edit(Object *p_object) {
}
@@ -43,8 +44,8 @@ void AudioStreamRandomizerEditorPlugin::make_visible(bool p_visible) {
}
void AudioStreamRandomizerEditorPlugin::_move_stream_array_element(Object *p_undo_redo, Object *p_edited, String p_array_prefix, int p_from_index, int p_to_pos) {
- UndoRedo *undo_redo = Object::cast_to<UndoRedo>(p_undo_redo);
- ERR_FAIL_COND(!undo_redo);
+ Ref<EditorUndoRedoManager> undo_redo = Object::cast_to<EditorUndoRedoManager>(p_undo_redo);
+ ERR_FAIL_COND(undo_redo.is_null());
AudioStreamRandomizer *randomizer = Object::cast_to<AudioStreamRandomizer>(p_edited);
if (!randomizer) {
diff --git a/editor/plugins/bone_map_editor_plugin.cpp b/editor/plugins/bone_map_editor_plugin.cpp
index 70775c1ee2..5db9249af1 100644
--- a/editor/plugins/bone_map_editor_plugin.cpp
+++ b/editor/plugins/bone_map_editor_plugin.cpp
@@ -47,6 +47,9 @@ void BoneMapperButton::fetch_textures() {
set_offset(SIDE_TOP, 0);
set_offset(SIDE_BOTTOM, 0);
+ // Hack to avoid handle color darkening...
+ set_modulate(EditorSettings::get_singleton()->is_dark_theme() ? Color(1, 1, 1) : Color(4.25, 4.25, 4.25));
+
circle = memnew(TextureRect);
circle->set_texture(get_theme_icon(SNAME("BoneMapperHandleCircle"), SNAME("EditorIcons")));
add_child(circle);
@@ -98,14 +101,24 @@ BoneMapperButton::~BoneMapperButton() {
}
void BoneMapperItem::create_editor() {
- skeleton_bone_selector = memnew(EditorPropertyTextEnum);
- skeleton_bone_selector->setup(skeleton_bone_names, false, true);
+ HBoxContainer *hbox = memnew(HBoxContainer);
+ add_child(hbox);
+
+ skeleton_bone_selector = memnew(EditorPropertyText);
skeleton_bone_selector->set_label(profile_bone_name);
skeleton_bone_selector->set_selectable(false);
+ skeleton_bone_selector->set_h_size_flags(SIZE_EXPAND_FILL);
skeleton_bone_selector->set_object_and_property(bone_map.ptr(), "bone_map/" + String(profile_bone_name));
skeleton_bone_selector->update_property();
skeleton_bone_selector->connect("property_changed", callable_mp(this, &BoneMapperItem::_value_changed));
- add_child(skeleton_bone_selector);
+ hbox->add_child(skeleton_bone_selector);
+
+ picker_button = memnew(Button);
+ picker_button->set_icon(get_theme_icon(SNAME("ClassList"), SNAME("EditorIcons")));
+ picker_button->connect("pressed", callable_mp(this, &BoneMapperItem::_open_picker));
+ hbox->add_child(picker_button);
+
+ add_child(memnew(HSeparator));
}
void BoneMapperItem::_update_property() {
@@ -114,6 +127,10 @@ void BoneMapperItem::_update_property() {
}
}
+void BoneMapperItem::_open_picker() {
+ emit_signal(SNAME("pick"), profile_bone_name);
+}
+
void BoneMapperItem::_value_changed(const String &p_property, Variant p_value, const String &p_name, bool p_changing) {
bone_map->set(p_property, p_value);
}
@@ -133,25 +150,153 @@ void BoneMapperItem::_notification(int p_what) {
}
void BoneMapperItem::_bind_methods() {
+ ADD_SIGNAL(MethodInfo("pick", PropertyInfo(Variant::STRING_NAME, "profile_bone_name")));
}
-BoneMapperItem::BoneMapperItem(Ref<BoneMap> &p_bone_map, PackedStringArray p_skeleton_bone_names, const StringName &p_profile_bone_name) {
+BoneMapperItem::BoneMapperItem(Ref<BoneMap> &p_bone_map, const StringName &p_profile_bone_name) {
bone_map = p_bone_map;
- skeleton_bone_names = p_skeleton_bone_names;
profile_bone_name = p_profile_bone_name;
}
BoneMapperItem::~BoneMapperItem() {
}
+void BonePicker::create_editors() {
+ set_title(TTR("Bone Picker:"));
+
+ VBoxContainer *vbox = memnew(VBoxContainer);
+ add_child(vbox);
+
+ bones = memnew(Tree);
+ bones->set_select_mode(Tree::SELECT_SINGLE);
+ bones->set_v_size_flags(Control::SIZE_EXPAND_FILL);
+ bones->set_hide_root(true);
+ bones->connect("item_activated", callable_mp(this, &BonePicker::_confirm));
+ vbox->add_child(bones);
+
+ create_bones_tree(skeleton);
+}
+
+void BonePicker::create_bones_tree(Skeleton3D *p_skeleton) {
+ bones->clear();
+
+ if (!p_skeleton) {
+ return;
+ }
+
+ TreeItem *root = bones->create_item();
+
+ HashMap<int, TreeItem *> items;
+
+ items.insert(-1, root);
+
+ Ref<Texture> bone_icon = get_theme_icon(SNAME("BoneAttachment3D"), SNAME("EditorIcons"));
+
+ Vector<int> bones_to_process = p_skeleton->get_parentless_bones();
+ bool is_first = true;
+ while (bones_to_process.size() > 0) {
+ int current_bone_idx = bones_to_process[0];
+ bones_to_process.erase(current_bone_idx);
+
+ Vector<int> current_bone_child_bones = p_skeleton->get_bone_children(current_bone_idx);
+ int child_bone_size = current_bone_child_bones.size();
+ for (int i = 0; i < child_bone_size; i++) {
+ bones_to_process.push_back(current_bone_child_bones[i]);
+ }
+
+ const int parent_idx = p_skeleton->get_bone_parent(current_bone_idx);
+ TreeItem *parent_item = items.find(parent_idx)->value;
+
+ TreeItem *joint_item = bones->create_item(parent_item);
+ items.insert(current_bone_idx, joint_item);
+
+ joint_item->set_text(0, p_skeleton->get_bone_name(current_bone_idx));
+ joint_item->set_icon(0, bone_icon);
+ joint_item->set_selectable(0, true);
+ joint_item->set_metadata(0, "bones/" + itos(current_bone_idx));
+ if (is_first) {
+ is_first = false;
+ } else {
+ joint_item->set_collapsed(true);
+ }
+ }
+}
+
+void BonePicker::_confirm() {
+ _ok_pressed();
+}
+
+void BonePicker::popup_bones_tree(const Size2i &p_minsize) {
+ popup_centered(p_minsize);
+}
+
+bool BonePicker::has_selected_bone() {
+ TreeItem *selected = bones->get_selected();
+ if (!selected) {
+ return false;
+ }
+ return true;
+}
+
+StringName BonePicker::get_selected_bone() {
+ TreeItem *selected = bones->get_selected();
+ if (!selected) {
+ return StringName();
+ }
+ return selected->get_text(0);
+}
+
+void BonePicker::_bind_methods() {
+}
+
+void BonePicker::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ create_editors();
+ } break;
+ }
+}
+
+BonePicker::BonePicker(Skeleton3D *p_skeleton) {
+ skeleton = p_skeleton;
+}
+
+BonePicker::~BonePicker() {
+}
+
void BoneMapper::create_editor() {
+ // Create Bone picker.
+ picker = memnew(BonePicker(skeleton));
+ picker->connect("confirmed", callable_mp(this, &BoneMapper::_apply_picker_selection));
+ add_child(picker, false, INTERNAL_MODE_FRONT);
+
+ profile_selector = memnew(EditorPropertyResource);
+ profile_selector->setup(bone_map.ptr(), "profile", "SkeletonProfile");
+ profile_selector->set_label("Profile");
+ profile_selector->set_selectable(false);
+ profile_selector->set_object_and_property(bone_map.ptr(), "profile");
+ profile_selector->update_property();
+ profile_selector->connect("property_changed", callable_mp(this, &BoneMapper::_profile_changed));
+ add_child(profile_selector);
+ add_child(memnew(HSeparator));
+
+ HBoxContainer *group_hbox = memnew(HBoxContainer);
+ add_child(group_hbox);
+
profile_group_selector = memnew(EditorPropertyEnum);
profile_group_selector->set_label("Group");
profile_group_selector->set_selectable(false);
+ profile_group_selector->set_h_size_flags(SIZE_EXPAND_FILL);
profile_group_selector->set_object_and_property(this, "current_group_idx");
profile_group_selector->update_property();
profile_group_selector->connect("property_changed", callable_mp(this, &BoneMapper::_value_changed));
- add_child(profile_group_selector);
+ group_hbox->add_child(profile_group_selector);
+
+ clear_mapping_button = memnew(Button);
+ clear_mapping_button->set_icon(get_theme_icon(SNAME("Clear"), SNAME("EditorIcons")));
+ clear_mapping_button->set_tooltip(TTR("Clear mappings in current group."));
+ clear_mapping_button->connect("pressed", callable_mp(this, &BoneMapper::_clear_mapping_current_group));
+ group_hbox->add_child(clear_mapping_button);
bone_mapper_field = memnew(AspectRatioContainer);
bone_mapper_field->set_stretch_mode(AspectRatioContainer::STRETCH_FIT);
@@ -175,9 +320,6 @@ void BoneMapper::create_editor() {
mapper_item_vbox = memnew(VBoxContainer);
add_child(mapper_item_vbox);
- separator = memnew(HSeparator);
- add_child(separator);
-
recreate_items();
}
@@ -201,6 +343,18 @@ void BoneMapper::update_group_idx() {
}
}
+void BoneMapper::_pick_bone(const StringName &p_bone_name) {
+ picker_key_name = p_bone_name;
+ picker->popup_bones_tree(Size2(500, 500) * EDSCALE);
+}
+
+void BoneMapper::_apply_picker_selection() {
+ if (!picker->has_selected_bone()) {
+ return;
+ }
+ bone_map->set_skeleton_bone_name(picker_key_name, picker->get_selected_bone());
+}
+
void BoneMapper::set_current_group_idx(int p_group_idx) {
current_group_idx = p_group_idx;
recreate_editor();
@@ -282,6 +436,7 @@ void BoneMapper::clear_items() {
// Clear items.
int len = bone_mapper_items.size();
for (int i = 0; i < len; i++) {
+ bone_mapper_items[i]->disconnect("pick", callable_mp(this, &BoneMapper::_pick_bone));
mapper_item_vbox->remove_child(bone_mapper_items[i]);
memdelete(bone_mapper_items[i]);
}
@@ -293,16 +448,11 @@ void BoneMapper::recreate_items() {
// Create items by profile.
Ref<SkeletonProfile> profile = bone_map->get_profile();
if (profile.is_valid()) {
- PackedStringArray skeleton_bone_names;
- int len = skeleton->get_bone_count();
- for (int i = 0; i < len; i++) {
- skeleton_bone_names.push_back(skeleton->get_bone_name(i));
- }
-
- len = profile->get_bone_size();
+ int len = profile->get_bone_size();
for (int i = 0; i < len; i++) {
StringName bn = profile->get_bone_name(i);
- bone_mapper_items.append(memnew(BoneMapperItem(bone_map, skeleton_bone_names, bn)));
+ bone_mapper_items.append(memnew(BoneMapperItem(bone_map, bn)));
+ bone_mapper_items[i]->connect("pick", callable_mp(this, &BoneMapper::_pick_bone), CONNECT_DEFERRED);
mapper_item_vbox->add_child(bone_mapper_items[i]);
}
}
@@ -363,11 +513,754 @@ void BoneMapper::_update_state() {
}
}
+void BoneMapper::_clear_mapping_current_group() {
+ if (bone_map.is_valid()) {
+ Ref<SkeletonProfile> profile = bone_map->get_profile();
+ if (profile.is_valid() && profile->get_group_size() > 0) {
+ int len = profile->get_bone_size();
+ for (int i = 0; i < len; i++) {
+ if (profile->get_group(i) == profile->get_group_name(current_group_idx)) {
+ bone_map->_set_skeleton_bone_name(profile->get_bone_name(i), StringName());
+ }
+ }
+ recreate_items();
+ }
+ }
+}
+
+#ifdef MODULE_REGEX_ENABLED
+int BoneMapper::search_bone_by_name(Skeleton3D *p_skeleton, Vector<String> p_picklist, BoneSegregation p_segregation, int p_parent, int p_child, int p_children_count) {
+ // There may be multiple candidates hit by existing the subsidiary bone.
+ // The one with the shortest name is probably the original.
+ LocalVector<String> hit_list;
+ String shortest = "";
+
+ for (int word_idx = 0; word_idx < p_picklist.size(); word_idx++) {
+ RegEx re = RegEx(p_picklist[word_idx]);
+ if (p_child == -1) {
+ Vector<int> bones_to_process = p_parent == -1 ? p_skeleton->get_parentless_bones() : p_skeleton->get_bone_children(p_parent);
+ while (bones_to_process.size() > 0) {
+ int idx = bones_to_process[0];
+ bones_to_process.erase(idx);
+ Vector<int> children = p_skeleton->get_bone_children(idx);
+ for (int i = 0; i < children.size(); i++) {
+ bones_to_process.push_back(children[i]);
+ }
+
+ if (p_children_count == 0 && children.size() > 0) {
+ continue;
+ }
+ if (p_children_count > 0 && children.size() < p_children_count) {
+ continue;
+ }
+
+ String bn = skeleton->get_bone_name(idx);
+ if (!re.search(bn.to_lower()).is_null() && guess_bone_segregation(bn) == p_segregation) {
+ hit_list.push_back(bn);
+ }
+ }
+
+ if (hit_list.size() > 0) {
+ shortest = hit_list[0];
+ for (uint32_t i = 0; i < hit_list.size(); i++) {
+ if (hit_list[i].length() < shortest.length()) {
+ shortest = hit_list[i]; // Prioritize parent.
+ }
+ }
+ }
+ } else {
+ int idx = skeleton->get_bone_parent(p_child);
+ while (idx != p_parent && idx >= 0) {
+ Vector<int> children = p_skeleton->get_bone_children(idx);
+ if (p_children_count == 0 && children.size() > 0) {
+ continue;
+ }
+ if (p_children_count > 0 && children.size() < p_children_count) {
+ continue;
+ }
+
+ String bn = skeleton->get_bone_name(idx);
+ if (!re.search(bn.to_lower()).is_null() && guess_bone_segregation(bn) == p_segregation) {
+ hit_list.push_back(bn);
+ }
+ idx = skeleton->get_bone_parent(idx);
+ }
+
+ if (hit_list.size() > 0) {
+ shortest = hit_list[0];
+ for (uint32_t i = 0; i < hit_list.size(); i++) {
+ if (hit_list[i].length() <= shortest.length()) {
+ shortest = hit_list[i]; // Prioritize parent.
+ }
+ }
+ }
+ }
+
+ if (shortest != "") {
+ break;
+ }
+ }
+
+ if (shortest == "") {
+ return -1;
+ }
+
+ return skeleton->find_bone(shortest);
+}
+
+BoneMapper::BoneSegregation BoneMapper::guess_bone_segregation(String p_bone_name) {
+ String fixed_bn = p_bone_name.camelcase_to_underscore().to_lower();
+
+ LocalVector<String> left_words;
+ left_words.push_back("(?<![a-zA-Z])left");
+ left_words.push_back("(?<![a-zA-Z0-9])l(?![a-zA-Z0-9])");
+
+ LocalVector<String> right_words;
+ right_words.push_back("(?<![a-zA-Z])right");
+ right_words.push_back("(?<![a-zA-Z0-9])r(?![a-zA-Z0-9])");
+
+ for (uint32_t i = 0; i < left_words.size(); i++) {
+ RegEx re_l = RegEx(left_words[i]);
+ if (!re_l.search(fixed_bn).is_null()) {
+ return BONE_SEGREGATION_LEFT;
+ }
+ RegEx re_r = RegEx(right_words[i]);
+ if (!re_r.search(fixed_bn).is_null()) {
+ return BONE_SEGREGATION_RIGHT;
+ }
+ }
+
+ return BONE_SEGREGATION_NONE;
+}
+
+void BoneMapper::_run_auto_mapping() {
+ auto_mapping_process(bone_map);
+ recreate_items();
+}
+
+void BoneMapper::auto_mapping_process(Ref<BoneMap> &p_bone_map) {
+ WARN_PRINT("Run auto mapping.");
+
+ int bone_idx = -1;
+ Vector<String> picklist; // Use Vector<String> because match words have priority.
+ Vector<int> search_path;
+
+ // 1. Guess Hips
+ picklist.push_back("hip");
+ picklist.push_back("pelvis");
+ picklist.push_back("waist");
+ picklist.push_back("torso");
+ int hips = search_bone_by_name(skeleton, picklist);
+ if (hips == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess Hips. Abort auto mapping.");
+ return; // If there is no Hips, we cannot guess bone after then.
+ } else {
+ p_bone_map->_set_skeleton_bone_name("Hips", skeleton->get_bone_name(hips));
+ }
+ picklist.clear();
+
+ // 2. Guess Root
+ bone_idx = skeleton->get_bone_parent(hips);
+ while (bone_idx >= 0) {
+ search_path.push_back(bone_idx);
+ bone_idx = skeleton->get_bone_parent(bone_idx);
+ }
+ if (search_path.size() == 0) {
+ bone_idx = -1;
+ } else if (search_path.size() == 1) {
+ bone_idx = search_path[0]; // It is only one bone which can be root.
+ } else {
+ bool found = false;
+ for (int i = 0; i < search_path.size(); i++) {
+ RegEx re = RegEx("root");
+ if (!re.search(skeleton->get_bone_name(search_path[i]).to_lower()).is_null()) {
+ bone_idx = search_path[i]; // Name match is preferred.
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ for (int i = 0; i < search_path.size(); i++) {
+ if (Vector3(0, 0, 0).is_equal_approx(skeleton->get_bone_global_rest(search_path[i]).origin)) {
+ bone_idx = search_path[i]; // The bone existing at the origin is appropriate as a root.
+ found = true;
+ break;
+ }
+ }
+ }
+ if (!found) {
+ bone_idx = search_path[search_path.size() - 1]; // Ambiguous, but most parental bone selected.
+ }
+ }
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess Root."); // Root is not required, so continue.
+ } else {
+ p_bone_map->_set_skeleton_bone_name("Root", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ search_path.clear();
+
+ // 3. Guess Neck
+ picklist.push_back("neck");
+ picklist.push_back("head"); // For no neck model.
+ picklist.push_back("face"); // Same above.
+ int neck = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_NONE, hips);
+ picklist.clear();
+
+ // 4. Guess Head
+ picklist.push_back("head");
+ picklist.push_back("face");
+ int head = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_NONE, neck);
+ if (head == -1) {
+ search_path = skeleton->get_bone_children(neck);
+ if (search_path.size() == 1) {
+ head = search_path[0]; // Maybe only one child of the Neck is Head.
+ }
+ }
+ if (head == -1) {
+ if (neck != -1) {
+ head = neck; // The head animation should have more movement.
+ neck = -1;
+ p_bone_map->_set_skeleton_bone_name("Head", skeleton->get_bone_name(head));
+ } else {
+ WARN_PRINT("Auto Mapping couldn't guess Neck or Head."); // Continued for guessing on the other bones. But abort when guessing spines step.
+ }
+ } else {
+ p_bone_map->_set_skeleton_bone_name("Neck", skeleton->get_bone_name(neck));
+ p_bone_map->_set_skeleton_bone_name("Head", skeleton->get_bone_name(head));
+ }
+ picklist.clear();
+ search_path.clear();
+
+ int neck_or_head = neck != -1 ? neck : (head != -1 ? head : -1);
+ if (neck_or_head != -1) {
+ // 4-1. Guess Eyes
+ picklist.push_back("eye(?!.*(brow|lash|lid))");
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, neck_or_head);
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftEye.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftEye", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, neck_or_head);
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightEye.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightEye", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ picklist.clear();
+
+ // 4-2. Guess Jaw
+ picklist.push_back("jaw");
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_NONE, neck_or_head);
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess Jaw.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("Jaw", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ picklist.clear();
+ }
+
+ // 5. Guess Foots
+ picklist.push_back("foot");
+ picklist.push_back("ankle");
+ int left_foot = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, hips);
+ if (left_foot == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftFoot.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftFoot", skeleton->get_bone_name(left_foot));
+ }
+ int right_foot = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, hips);
+ if (right_foot == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightFoot.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightFoot", skeleton->get_bone_name(right_foot));
+ }
+ picklist.clear();
+
+ // 5-1. Guess LowerLegs
+ picklist.push_back("(low|under).*leg");
+ picklist.push_back("knee");
+ picklist.push_back("shin");
+ picklist.push_back("calf");
+ picklist.push_back("leg");
+ int left_lower_leg = -1;
+ if (left_foot != -1) {
+ left_lower_leg = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, hips, left_foot);
+ }
+ if (left_lower_leg == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftLowerLeg.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftLowerLeg", skeleton->get_bone_name(left_lower_leg));
+ }
+ int right_lower_leg = -1;
+ if (right_foot != -1) {
+ right_lower_leg = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, hips, right_foot);
+ }
+ if (right_lower_leg == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightLowerLeg.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightLowerLeg", skeleton->get_bone_name(right_lower_leg));
+ }
+ picklist.clear();
+
+ // 5-2. Guess UpperLegs
+ picklist.push_back("up.*leg");
+ picklist.push_back("thigh");
+ picklist.push_back("leg");
+ if (left_lower_leg != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, hips, left_lower_leg);
+ }
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftUpperLeg.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftUpperLeg", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ if (right_lower_leg != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, hips, right_lower_leg);
+ }
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightUpperLeg.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightUpperLeg", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ picklist.clear();
+
+ // 5-3. Guess Toes
+ picklist.push_back("toe");
+ picklist.push_back("ball");
+ if (left_foot != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, left_foot);
+ if (bone_idx == -1) {
+ search_path = skeleton->get_bone_children(left_foot);
+ if (search_path.size() == 1) {
+ bone_idx = search_path[0]; // Maybe only one child of the Foot is Toes.
+ }
+ search_path.clear();
+ }
+ }
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftToes.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftToes", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ if (right_foot != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, right_foot);
+ if (bone_idx == -1) {
+ search_path = skeleton->get_bone_children(right_foot);
+ if (search_path.size() == 1) {
+ bone_idx = search_path[0]; // Maybe only one child of the Foot is Toes.
+ }
+ search_path.clear();
+ }
+ }
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightToes.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightToes", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ picklist.clear();
+
+ // 6. Guess Hands
+ picklist.push_back("hand");
+ picklist.push_back("wrist");
+ picklist.push_back("palm");
+ picklist.push_back("fingers");
+ int left_hand_or_palm = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, hips, -1, 5);
+ if (left_hand_or_palm == -1) {
+ // Ambiguous, but try again for fewer finger models.
+ left_hand_or_palm = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, hips);
+ }
+ int left_hand = left_hand_or_palm; // Check for the presence of a wrist, since bones with five children may be palmar.
+ while (left_hand != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, hips, left_hand);
+ if (bone_idx == -1) {
+ break;
+ }
+ left_hand = bone_idx;
+ }
+ if (left_hand == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftHand.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftHand", skeleton->get_bone_name(left_hand));
+ }
+ bone_idx = -1;
+ int right_hand_or_palm = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, hips, -1, 5);
+ if (right_hand_or_palm == -1) {
+ // Ambiguous, but try again for fewer finger models.
+ right_hand_or_palm = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, hips);
+ }
+ int right_hand = right_hand_or_palm;
+ while (right_hand != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, hips, right_hand);
+ if (bone_idx == -1) {
+ break;
+ }
+ right_hand = bone_idx;
+ }
+ if (right_hand == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightHand.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightHand", skeleton->get_bone_name(right_hand));
+ }
+ bone_idx = -1;
+ picklist.clear();
+
+ // 6-1. Guess Finger
+ bool named_finger_is_found = false;
+ LocalVector<String> fingers;
+ fingers.push_back("thumb|pollex");
+ fingers.push_back("index|fore");
+ fingers.push_back("middle");
+ fingers.push_back("ring");
+ fingers.push_back("little|pinkie|pinky");
+ if (left_hand_or_palm != -1) {
+ LocalVector<LocalVector<String>> left_fingers_map;
+ left_fingers_map.resize(5);
+ left_fingers_map[0].push_back("LeftThumbMetacarpal");
+ left_fingers_map[0].push_back("LeftThumbProximal");
+ left_fingers_map[0].push_back("LeftThumbDistal");
+ left_fingers_map[1].push_back("LeftIndexProximal");
+ left_fingers_map[1].push_back("LeftIndexIntermediate");
+ left_fingers_map[1].push_back("LeftIndexDistal");
+ left_fingers_map[2].push_back("LeftMiddleProximal");
+ left_fingers_map[2].push_back("LeftMiddleIntermediate");
+ left_fingers_map[2].push_back("LeftMiddleDistal");
+ left_fingers_map[3].push_back("LeftRingProximal");
+ left_fingers_map[3].push_back("LeftRingIntermediate");
+ left_fingers_map[3].push_back("LeftRingDistal");
+ left_fingers_map[4].push_back("LeftLittleProximal");
+ left_fingers_map[4].push_back("LeftLittleIntermediate");
+ left_fingers_map[4].push_back("LeftLittleDistal");
+ for (int i = 0; i < 5; i++) {
+ picklist.push_back(fingers[i]);
+ int finger = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, left_hand_or_palm, -1, 0);
+ if (finger != -1) {
+ while (finger != left_hand_or_palm && finger >= 0) {
+ search_path.push_back(finger);
+ finger = skeleton->get_bone_parent(finger);
+ }
+ search_path.reverse();
+ if (search_path.size() == 1) {
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ named_finger_is_found = true;
+ } else if (search_path.size() == 2) {
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ named_finger_is_found = true;
+ } else if (search_path.size() >= 3) {
+ search_path = search_path.slice(-3); // Eliminate the possibility of carpal bone.
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][2], skeleton->get_bone_name(search_path[2]));
+ named_finger_is_found = true;
+ }
+ }
+ picklist.clear();
+ search_path.clear();
+ }
+
+ // It is a bit corner case, but possibly the finger names are sequentially numbered...
+ if (!named_finger_is_found) {
+ picklist.push_back("finger");
+ RegEx finger_re = RegEx("finger");
+ search_path = skeleton->get_bone_children(left_hand_or_palm);
+ Vector<String> finger_names;
+ for (int i = 0; i < search_path.size(); i++) {
+ String bn = skeleton->get_bone_name(search_path[i]);
+ if (!finger_re.search(bn.to_lower()).is_null()) {
+ finger_names.push_back(bn);
+ }
+ }
+ finger_names.sort(); // Order by lexicographic, normal use cases never have more than 10 fingers in one hand.
+ search_path.clear();
+ for (int i = 0; i < finger_names.size(); i++) {
+ if (i >= 5) {
+ break;
+ }
+ int finger_root = skeleton->find_bone(finger_names[i]);
+ int finger = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, finger_root, -1, 0);
+ if (finger != -1) {
+ while (finger != finger_root && finger >= 0) {
+ search_path.push_back(finger);
+ finger = skeleton->get_bone_parent(finger);
+ }
+ }
+ search_path.push_back(finger_root);
+ search_path.reverse();
+ if (search_path.size() == 1) {
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ } else if (search_path.size() == 2) {
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ } else if (search_path.size() >= 3) {
+ search_path = search_path.slice(-3); // Eliminate the possibility of carpal bone.
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ p_bone_map->_set_skeleton_bone_name(left_fingers_map[i][2], skeleton->get_bone_name(search_path[2]));
+ }
+ search_path.clear();
+ }
+ picklist.clear();
+ }
+ }
+ named_finger_is_found = false;
+ if (right_hand_or_palm != -1) {
+ LocalVector<LocalVector<String>> right_fingers_map;
+ right_fingers_map.resize(5);
+ right_fingers_map[0].push_back("RightThumbMetacarpal");
+ right_fingers_map[0].push_back("RightThumbProximal");
+ right_fingers_map[0].push_back("RightThumbDistal");
+ right_fingers_map[1].push_back("RightIndexProximal");
+ right_fingers_map[1].push_back("RightIndexIntermediate");
+ right_fingers_map[1].push_back("RightIndexDistal");
+ right_fingers_map[2].push_back("RightMiddleProximal");
+ right_fingers_map[2].push_back("RightMiddleIntermediate");
+ right_fingers_map[2].push_back("RightMiddleDistal");
+ right_fingers_map[3].push_back("RightRingProximal");
+ right_fingers_map[3].push_back("RightRingIntermediate");
+ right_fingers_map[3].push_back("RightRingDistal");
+ right_fingers_map[4].push_back("RightLittleProximal");
+ right_fingers_map[4].push_back("RightLittleIntermediate");
+ right_fingers_map[4].push_back("RightLittleDistal");
+ for (int i = 0; i < 5; i++) {
+ picklist.push_back(fingers[i]);
+ int finger = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, right_hand_or_palm, -1, 0);
+ if (finger != -1) {
+ while (finger != right_hand_or_palm && finger >= 0) {
+ search_path.push_back(finger);
+ finger = skeleton->get_bone_parent(finger);
+ }
+ search_path.reverse();
+ if (search_path.size() == 1) {
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ named_finger_is_found = true;
+ } else if (search_path.size() == 2) {
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ named_finger_is_found = true;
+ } else if (search_path.size() >= 3) {
+ search_path = search_path.slice(-3); // Eliminate the possibility of carpal bone.
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][2], skeleton->get_bone_name(search_path[2]));
+ named_finger_is_found = true;
+ }
+ }
+ picklist.clear();
+ search_path.clear();
+ }
+
+ // It is a bit corner case, but possibly the finger names are sequentially numbered...
+ if (!named_finger_is_found) {
+ picklist.push_back("finger");
+ RegEx finger_re = RegEx("finger");
+ search_path = skeleton->get_bone_children(right_hand_or_palm);
+ Vector<String> finger_names;
+ for (int i = 0; i < search_path.size(); i++) {
+ String bn = skeleton->get_bone_name(search_path[i]);
+ if (!finger_re.search(bn.to_lower()).is_null()) {
+ finger_names.push_back(bn);
+ }
+ }
+ finger_names.sort(); // Order by lexicographic, normal use cases never have more than 10 fingers in one hand.
+ search_path.clear();
+ for (int i = 0; i < finger_names.size(); i++) {
+ if (i >= 5) {
+ break;
+ }
+ int finger_root = skeleton->find_bone(finger_names[i]);
+ int finger = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, finger_root, -1, 0);
+ if (finger != -1) {
+ while (finger != finger_root && finger >= 0) {
+ search_path.push_back(finger);
+ finger = skeleton->get_bone_parent(finger);
+ }
+ }
+ search_path.push_back(finger_root);
+ search_path.reverse();
+ if (search_path.size() == 1) {
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ } else if (search_path.size() == 2) {
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ } else if (search_path.size() >= 3) {
+ search_path = search_path.slice(-3); // Eliminate the possibility of carpal bone.
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][0], skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][1], skeleton->get_bone_name(search_path[1]));
+ p_bone_map->_set_skeleton_bone_name(right_fingers_map[i][2], skeleton->get_bone_name(search_path[2]));
+ }
+ search_path.clear();
+ }
+ picklist.clear();
+ }
+ }
+
+ // 7. Guess Arms
+ picklist.push_back("shoulder");
+ picklist.push_back("clavicle");
+ picklist.push_back("collar");
+ int left_shoulder = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, hips);
+ if (left_shoulder == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftShoulder.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftShoulder", skeleton->get_bone_name(left_shoulder));
+ }
+ int right_shoulder = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, hips);
+ if (right_shoulder == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightShoulder.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightShoulder", skeleton->get_bone_name(right_shoulder));
+ }
+ picklist.clear();
+
+ // 7-1. Guess LowerArms
+ picklist.push_back("(low|fore).*arm");
+ picklist.push_back("elbow");
+ picklist.push_back("arm");
+ int left_lower_arm = -1;
+ if (left_shoulder != -1 && left_hand_or_palm != -1) {
+ left_lower_arm = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, left_shoulder, left_hand_or_palm);
+ }
+ if (left_lower_arm == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftLowerArm.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftLowerArm", skeleton->get_bone_name(left_lower_arm));
+ }
+ int right_lower_arm = -1;
+ if (right_shoulder != -1 && right_hand_or_palm != -1) {
+ right_lower_arm = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, right_shoulder, right_hand_or_palm);
+ }
+ if (right_lower_arm == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightLowerArm.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightLowerArm", skeleton->get_bone_name(right_lower_arm));
+ }
+ picklist.clear();
+
+ // 7-2. Guess UpperArms
+ picklist.push_back("up.*arm");
+ picklist.push_back("arm");
+ if (left_shoulder != -1 && left_lower_arm != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_LEFT, left_shoulder, left_lower_arm);
+ }
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess LeftUpperArm.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("LeftUpperArm", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ if (right_shoulder != -1 && right_lower_arm != -1) {
+ bone_idx = search_bone_by_name(skeleton, picklist, BONE_SEGREGATION_RIGHT, right_shoulder, right_lower_arm);
+ }
+ if (bone_idx == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess RightUpperArm.");
+ } else {
+ p_bone_map->_set_skeleton_bone_name("RightUpperArm", skeleton->get_bone_name(bone_idx));
+ }
+ bone_idx = -1;
+ picklist.clear();
+
+ // 8. Guess UpperChest or Chest
+ if (neck_or_head == -1) {
+ return; // Abort.
+ }
+ int chest_or_upper_chest = skeleton->get_bone_parent(neck_or_head);
+ bool is_appropriate = true;
+ if (left_shoulder != -1) {
+ bone_idx = skeleton->get_bone_parent(left_shoulder);
+ bool detect = false;
+ while (bone_idx != hips && bone_idx >= 0) {
+ if (bone_idx == chest_or_upper_chest) {
+ detect = true;
+ break;
+ }
+ bone_idx = skeleton->get_bone_parent(bone_idx);
+ }
+ if (!detect) {
+ is_appropriate = false;
+ }
+ bone_idx = -1;
+ }
+ if (right_shoulder != -1) {
+ bone_idx = skeleton->get_bone_parent(right_shoulder);
+ bool detect = false;
+ while (bone_idx != hips && bone_idx >= 0) {
+ if (bone_idx == chest_or_upper_chest) {
+ detect = true;
+ break;
+ }
+ bone_idx = skeleton->get_bone_parent(bone_idx);
+ }
+ if (!detect) {
+ is_appropriate = false;
+ }
+ bone_idx = -1;
+ }
+ if (!is_appropriate) {
+ if (skeleton->get_bone_parent(left_shoulder) == skeleton->get_bone_parent(right_shoulder)) {
+ chest_or_upper_chest = skeleton->get_bone_parent(left_shoulder);
+ } else {
+ chest_or_upper_chest = -1;
+ }
+ }
+ if (chest_or_upper_chest == -1) {
+ WARN_PRINT("Auto Mapping couldn't guess Chest or UpperChest. Abort auto mapping.");
+ return; // Will be not able to guess Spines.
+ }
+
+ // 9. Guess Spines
+ bone_idx = skeleton->get_bone_parent(chest_or_upper_chest);
+ while (bone_idx != hips && bone_idx >= 0) {
+ search_path.push_back(bone_idx);
+ bone_idx = skeleton->get_bone_parent(bone_idx);
+ }
+ search_path.reverse();
+ if (search_path.size() == 0) {
+ p_bone_map->_set_skeleton_bone_name("Spine", skeleton->get_bone_name(chest_or_upper_chest)); // Maybe chibi model...?
+ } else if (search_path.size() == 1) {
+ p_bone_map->_set_skeleton_bone_name("Spine", skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name("Chest", skeleton->get_bone_name(chest_or_upper_chest));
+ } else if (search_path.size() >= 2) {
+ p_bone_map->_set_skeleton_bone_name("Spine", skeleton->get_bone_name(search_path[0]));
+ p_bone_map->_set_skeleton_bone_name("Chest", skeleton->get_bone_name(search_path[search_path.size() - 1])); // Probably UppeChest's parent is appropriate.
+ p_bone_map->_set_skeleton_bone_name("UpperChest", skeleton->get_bone_name(chest_or_upper_chest));
+ }
+ bone_idx = -1;
+ search_path.clear();
+
+ WARN_PRINT("Finish auto mapping.");
+}
+#endif // MODULE_REGEX_ENABLED
+
void BoneMapper::_value_changed(const String &p_property, Variant p_value, const String &p_name, bool p_changing) {
set(p_property, p_value);
recreate_editor();
}
+void BoneMapper::_profile_changed(const String &p_property, Variant p_value, const String &p_name, bool p_changing) {
+ bone_map->set(p_property, p_value);
+
+ // Run auto mapping when setting SkeletonProfileHumanoid by GUI Editor.
+ Ref<SkeletonProfile> profile = bone_map->get_profile();
+ if (profile.is_valid()) {
+ SkeletonProfileHumanoid *hmn = Object::cast_to<SkeletonProfileHumanoid>(profile.ptr());
+ if (hmn) {
+#ifdef MODULE_REGEX_ENABLED
+ _run_auto_mapping();
+#endif // MODULE_REGEX_ENABLED
+ }
+ }
+}
+
void BoneMapper::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_current_group_idx", "current_group_idx"), &BoneMapper::set_current_group_idx);
ClassDB::bind_method(D_METHOD("get_current_group_idx"), &BoneMapper::get_current_group_idx);
@@ -444,10 +1337,6 @@ void BoneMapEditor::_notification(int p_what) {
create_editors();
} break;
case NOTIFICATION_EXIT_TREE: {
- if (bone_mapper) {
- remove_child(bone_mapper);
- bone_mapper->queue_delete();
- }
skeleton = nullptr;
} break;
}
diff --git a/editor/plugins/bone_map_editor_plugin.h b/editor/plugins/bone_map_editor_plugin.h
index 339547ea10..0541ce6eac 100644
--- a/editor/plugins/bone_map_editor_plugin.h
+++ b/editor/plugins/bone_map_editor_plugin.h
@@ -34,6 +34,12 @@
#include "editor/editor_node.h"
#include "editor/editor_plugin.h"
#include "editor/editor_properties.h"
+
+#include "modules/modules_enabled.gen.h" // For regex.
+#ifdef MODULE_REGEX_ENABLED
+#include "modules/regex/regex.h"
+#endif
+
#include "scene/3d/skeleton_3d.h"
#include "scene/gui/color_rect.h"
#include "scene/gui/dialogs.h"
@@ -79,12 +85,13 @@ class BoneMapperItem : public VBoxContainer {
int button_id = -1;
StringName profile_bone_name;
- PackedStringArray skeleton_bone_names;
Ref<BoneMap> bone_map;
- EditorPropertyTextEnum *skeleton_bone_selector;
+ EditorPropertyText *skeleton_bone_selector;
+ Button *picker_button;
void _update_property();
+ void _open_picker();
protected:
void _notification(int p_what);
@@ -95,20 +102,49 @@ protected:
public:
void assign_button_id(int p_button_id);
- BoneMapperItem(Ref<BoneMap> &p_bone_map, PackedStringArray p_skeleton_bone_names, const StringName &p_profile_bone_name = StringName());
+ BoneMapperItem(Ref<BoneMap> &p_bone_map, const StringName &p_profile_bone_name = StringName());
~BoneMapperItem();
};
+class BonePicker : public AcceptDialog {
+ GDCLASS(BonePicker, AcceptDialog);
+
+ Skeleton3D *skeleton = nullptr;
+ Tree *bones = nullptr;
+
+public:
+ void popup_bones_tree(const Size2i &p_minsize = Size2i());
+ bool has_selected_bone();
+ StringName get_selected_bone();
+
+protected:
+ void _notification(int p_what);
+ static void _bind_methods();
+
+ void _confirm();
+
+private:
+ void create_editors();
+ void create_bones_tree(Skeleton3D *p_skeleton);
+
+public:
+ BonePicker(Skeleton3D *p_skeleton);
+ ~BonePicker();
+};
+
class BoneMapper : public VBoxContainer {
GDCLASS(BoneMapper, VBoxContainer);
Skeleton3D *skeleton;
Ref<BoneMap> bone_map;
+ EditorPropertyResource *profile_selector;
+
Vector<BoneMapperItem *> bone_mapper_items;
+ Button *clear_mapping_button;
+
VBoxContainer *mapper_item_vbox;
- HSeparator *separator;
int current_group_idx = 0;
int current_bone_idx = -1;
@@ -126,10 +162,31 @@ class BoneMapper : public VBoxContainer {
void update_group_idx();
void _update_state();
+ /* Bone picker */
+ BonePicker *picker = nullptr;
+ StringName picker_key_name;
+ void _pick_bone(const StringName &p_bone_name);
+ void _apply_picker_selection();
+ void _clear_mapping_current_group();
+
+#ifdef MODULE_REGEX_ENABLED
+ /* For auto mapping */
+ enum BoneSegregation {
+ BONE_SEGREGATION_NONE,
+ BONE_SEGREGATION_LEFT,
+ BONE_SEGREGATION_RIGHT
+ };
+ int search_bone_by_name(Skeleton3D *p_skeleton, Vector<String> p_picklist, BoneSegregation p_segregation = BONE_SEGREGATION_NONE, int p_parent = -1, int p_child = -1, int p_children_count = -1);
+ BoneSegregation guess_bone_segregation(String p_bone_name);
+ void auto_mapping_process(Ref<BoneMap> &p_bone_map);
+ void _run_auto_mapping();
+#endif // MODULE_REGEX_ENABLED
+
protected:
void _notification(int p_what);
static void _bind_methods();
virtual void _value_changed(const String &p_property, Variant p_value, const String &p_name, bool p_changing);
+ virtual void _profile_changed(const String &p_property, Variant p_value, const String &p_name, bool p_changing);
public:
void set_current_group_idx(int p_group_idx);
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index fc70ace331..2e83e2041f 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -40,6 +40,7 @@
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
#include "editor/editor_toaster.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/animation_player_editor_plugin.h"
#include "editor/plugins/script_editor_plugin.h"
#include "editor/scene_tree_dock.h"
@@ -2957,6 +2958,9 @@ void CanvasItemEditor::_draw_ruler_tool() {
Point2 corner = Point2(begin.x, end.y);
Vector2 length_vector = (begin - end).abs() / zoom;
+ const real_t horizontal_angle_rad = length_vector.angle();
+ const real_t vertical_angle_rad = Math_PI / 2.0 - horizontal_angle_rad;
+
Ref<Font> font = get_theme_font(SNAME("bold"), SNAME("EditorFonts"));
int font_size = get_theme_font_size(SNAME("bold_size"), SNAME("EditorFonts"));
Color font_color = get_theme_color(SNAME("font_color"), SNAME("Editor"));
@@ -2973,6 +2977,42 @@ void CanvasItemEditor::_draw_ruler_tool() {
text_pos.x = CLAMP(text_pos.x, text_width / 2, viewport->get_rect().size.x - text_width * 1.5);
text_pos.y = CLAMP(text_pos.y, text_height * 1.5, viewport->get_rect().size.y - text_height * 1.5);
+ // Draw lines.
+ viewport->draw_line(begin, end, ruler_primary_color, Math::round(EDSCALE * 3));
+
+ bool draw_secondary_lines = !(Math::is_equal_approx(begin.y, corner.y) || Math::is_equal_approx(end.x, corner.x));
+ if (draw_secondary_lines) {
+ viewport->draw_line(begin, corner, ruler_secondary_color, Math::round(EDSCALE));
+ viewport->draw_line(corner, end, ruler_secondary_color, Math::round(EDSCALE));
+
+ // Angle arcs.
+ int arc_point_count = 8;
+ real_t arc_radius_max_length_percent = 0.1;
+ real_t ruler_length = length_vector.length() * zoom;
+ real_t arc_max_radius = 50.0;
+ real_t arc_line_width = 2.0;
+
+ const Vector2 end_to_begin = (end - begin);
+
+ real_t arc_1_start_angle = end_to_begin.x < 0
+ ? (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 - vertical_angle_rad : Math_PI / 2.0)
+ : (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 : Math_PI / 2.0 - vertical_angle_rad);
+ real_t arc_1_end_angle = arc_1_start_angle + vertical_angle_rad;
+ // Constrain arc to triangle height & max size.
+ real_t arc_1_radius = MIN(MIN(arc_radius_max_length_percent * ruler_length, ABS(end_to_begin.y)), arc_max_radius);
+
+ real_t arc_2_start_angle = end_to_begin.x < 0
+ ? (end_to_begin.y < 0 ? 0.0 : -horizontal_angle_rad)
+ : (end_to_begin.y < 0 ? Math_PI - horizontal_angle_rad : Math_PI);
+ real_t arc_2_end_angle = arc_2_start_angle + horizontal_angle_rad;
+ // Constrain arc to triangle width & max size.
+ real_t arc_2_radius = MIN(MIN(arc_radius_max_length_percent * ruler_length, ABS(end_to_begin.x)), arc_max_radius);
+
+ viewport->draw_arc(begin, arc_1_radius, arc_1_start_angle, arc_1_end_angle, arc_point_count, ruler_primary_color, Math::round(EDSCALE * arc_line_width));
+ viewport->draw_arc(end, arc_2_radius, arc_2_start_angle, arc_2_end_angle, arc_point_count, ruler_primary_color, Math::round(EDSCALE * arc_line_width));
+ }
+
+ // Draw text.
if (begin.is_equal_approx(end)) {
viewport->draw_string_outline(font, text_pos, (String)ruler_tool_origin, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, outline_size, outline_color);
viewport->draw_string(font, text_pos, (String)ruler_tool_origin, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, font_color);
@@ -2984,17 +3024,7 @@ void CanvasItemEditor::_draw_ruler_tool() {
viewport->draw_string_outline(font, text_pos, TS->format_number(vformat("%.1f px", length_vector.length())), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, outline_size, outline_color);
viewport->draw_string(font, text_pos, TS->format_number(vformat("%.1f px", length_vector.length())), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, font_color);
- bool draw_secondary_lines = !(Math::is_equal_approx(begin.y, corner.y) || Math::is_equal_approx(end.x, corner.x));
-
- viewport->draw_line(begin, end, ruler_primary_color, Math::round(EDSCALE * 3));
- if (draw_secondary_lines) {
- viewport->draw_line(begin, corner, ruler_secondary_color, Math::round(EDSCALE));
- viewport->draw_line(corner, end, ruler_secondary_color, Math::round(EDSCALE));
- }
-
if (draw_secondary_lines) {
- const real_t horizontal_angle_rad = length_vector.angle();
- const real_t vertical_angle_rad = Math_PI / 2.0 - horizontal_angle_rad;
const int horizontal_angle = round(180 * horizontal_angle_rad / Math_PI);
const int vertical_angle = round(180 * vertical_angle_rad / Math_PI);
@@ -3031,32 +3061,6 @@ void CanvasItemEditor::_draw_ruler_tool() {
}
viewport->draw_string_outline(font, h_angle_text_pos, TS->format_number(vformat(String::utf8("%d°"), horizontal_angle)), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, outline_size, outline_color);
viewport->draw_string(font, h_angle_text_pos, TS->format_number(vformat(String::utf8("%d°"), horizontal_angle)), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, font_secondary_color);
-
- // Angle arcs
- int arc_point_count = 8;
- real_t arc_radius_max_length_percent = 0.1;
- real_t ruler_length = length_vector.length() * zoom;
- real_t arc_max_radius = 50.0;
- real_t arc_line_width = 2.0;
-
- const Vector2 end_to_begin = (end - begin);
-
- real_t arc_1_start_angle = end_to_begin.x < 0
- ? (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 - vertical_angle_rad : Math_PI / 2.0)
- : (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 : Math_PI / 2.0 - vertical_angle_rad);
- real_t arc_1_end_angle = arc_1_start_angle + vertical_angle_rad;
- // Constrain arc to triangle height & max size
- real_t arc_1_radius = MIN(MIN(arc_radius_max_length_percent * ruler_length, ABS(end_to_begin.y)), arc_max_radius);
-
- real_t arc_2_start_angle = end_to_begin.x < 0
- ? (end_to_begin.y < 0 ? 0.0 : -horizontal_angle_rad)
- : (end_to_begin.y < 0 ? Math_PI - horizontal_angle_rad : Math_PI);
- real_t arc_2_end_angle = arc_2_start_angle + horizontal_angle_rad;
- // Constrain arc to triangle width & max size
- real_t arc_2_radius = MIN(MIN(arc_radius_max_length_percent * ruler_length, ABS(end_to_begin.x)), arc_max_radius);
-
- viewport->draw_arc(begin, arc_1_radius, arc_1_start_angle, arc_1_end_angle, arc_point_count, ruler_primary_color, Math::round(EDSCALE * arc_line_width));
- viewport->draw_arc(end, arc_2_radius, arc_2_start_angle, arc_2_end_angle, arc_point_count, ruler_primary_color, Math::round(EDSCALE * arc_line_width));
}
if (grid_snap_active) {
@@ -3988,6 +3992,10 @@ void CanvasItemEditor::_selection_changed() {
selected_from_canvas = false;
}
+void CanvasItemEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
void CanvasItemEditor::edit(CanvasItem *p_canvas_item) {
Array selection = editor_selection->get_selected_nodes();
if (selection.size() != 1 || Object::cast_to<Node>(selection[0]) != p_canvas_item) {
@@ -5419,7 +5427,7 @@ CanvasItemEditor::CanvasItemEditor() {
CanvasItemEditor *CanvasItemEditor::singleton = nullptr;
void CanvasItemEditorPlugin::edit(Object *p_object) {
- canvas_item_editor->set_undo_redo(&get_undo_redo());
+ canvas_item_editor->set_undo_redo(EditorNode::get_undo_redo());
canvas_item_editor->edit(Object::cast_to<CanvasItem>(p_object));
}
@@ -5572,34 +5580,34 @@ void CanvasItemEditorViewport::_create_nodes(Node *parent, Node *child, String &
Ref<Texture2D> texture = ResourceCache::get_ref(path);
if (parent) {
- editor_data->get_undo_redo().add_do_method(parent, "add_child", child, true);
- editor_data->get_undo_redo().add_do_method(child, "set_owner", EditorNode::get_singleton()->get_edited_scene());
- editor_data->get_undo_redo().add_do_reference(child);
- editor_data->get_undo_redo().add_undo_method(parent, "remove_child", child);
+ editor_data->get_undo_redo()->add_do_method(parent, "add_child", child, true);
+ editor_data->get_undo_redo()->add_do_method(child, "set_owner", EditorNode::get_singleton()->get_edited_scene());
+ editor_data->get_undo_redo()->add_do_reference(child);
+ editor_data->get_undo_redo()->add_undo_method(parent, "remove_child", child);
} else { // If no parent is selected, set as root node of the scene.
- editor_data->get_undo_redo().add_do_method(EditorNode::get_singleton(), "set_edited_scene", child);
- editor_data->get_undo_redo().add_do_method(child, "set_owner", EditorNode::get_singleton()->get_edited_scene());
- editor_data->get_undo_redo().add_do_reference(child);
- editor_data->get_undo_redo().add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
+ editor_data->get_undo_redo()->add_do_method(EditorNode::get_singleton(), "set_edited_scene", child);
+ editor_data->get_undo_redo()->add_do_method(child, "set_owner", EditorNode::get_singleton()->get_edited_scene());
+ editor_data->get_undo_redo()->add_do_reference(child);
+ editor_data->get_undo_redo()->add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
}
if (parent) {
String new_name = parent->validate_child_name(child);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_create_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent), child->get_class(), new_name);
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_create_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent), child->get_class(), new_name);
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
}
if (Object::cast_to<TouchScreenButton>(child) || Object::cast_to<TextureButton>(child)) {
- editor_data->get_undo_redo().add_do_property(child, "texture_normal", texture);
+ editor_data->get_undo_redo()->add_do_property(child, "texture_normal", texture);
} else {
- editor_data->get_undo_redo().add_do_property(child, "texture", texture);
+ editor_data->get_undo_redo()->add_do_property(child, "texture", texture);
}
// make visible for certain node type
if (Object::cast_to<Control>(child)) {
Size2 texture_size = texture->get_size();
- editor_data->get_undo_redo().add_do_property(child, "rect_size", texture_size);
+ editor_data->get_undo_redo()->add_do_property(child, "rect_size", texture_size);
} else if (Object::cast_to<Polygon2D>(child)) {
Size2 texture_size = texture->get_size();
Vector<Vector2> list = {
@@ -5608,7 +5616,7 @@ void CanvasItemEditorViewport::_create_nodes(Node *parent, Node *child, String &
Vector2(texture_size.width, texture_size.height),
Vector2(0, texture_size.height)
};
- editor_data->get_undo_redo().add_do_property(child, "polygon", list);
+ editor_data->get_undo_redo()->add_do_property(child, "polygon", list);
}
// Compute the global position
@@ -5617,7 +5625,7 @@ void CanvasItemEditorViewport::_create_nodes(Node *parent, Node *child, String &
// there's nothing to be used as source position so snapping will work as absolute if enabled
target_position = canvas_item_editor->snap_point(target_position);
- editor_data->get_undo_redo().add_do_method(child, "set_global_position", target_position);
+ editor_data->get_undo_redo()->add_do_method(child, "set_global_position", target_position);
}
bool CanvasItemEditorViewport::_create_instance(Node *parent, String &path, const Point2 &p_point) {
@@ -5642,15 +5650,15 @@ bool CanvasItemEditorViewport::_create_instance(Node *parent, String &path, cons
instantiated_scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(path));
- editor_data->get_undo_redo().add_do_method(parent, "add_child", instantiated_scene, true);
- editor_data->get_undo_redo().add_do_method(instantiated_scene, "set_owner", edited_scene);
- editor_data->get_undo_redo().add_do_reference(instantiated_scene);
- editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instantiated_scene);
+ editor_data->get_undo_redo()->add_do_method(parent, "add_child", instantiated_scene, true);
+ editor_data->get_undo_redo()->add_do_method(instantiated_scene, "set_owner", edited_scene);
+ editor_data->get_undo_redo()->add_do_reference(instantiated_scene);
+ editor_data->get_undo_redo()->add_undo_method(parent, "remove_child", instantiated_scene);
String new_name = parent->validate_child_name(instantiated_scene);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_instance_node", edited_scene->get_path_to(parent), path, new_name);
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name));
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_instance_node", edited_scene->get_path_to(parent), path, new_name);
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name));
CanvasItem *instance_ci = Object::cast_to<CanvasItem>(instantiated_scene);
if (instance_ci) {
@@ -5664,7 +5672,7 @@ bool CanvasItemEditorViewport::_create_instance(Node *parent, String &path, cons
// Preserve instance position of the original scene.
target_pos += instance_ci->_edit_get_position();
- editor_data->get_undo_redo().add_do_method(instantiated_scene, "set_position", target_pos);
+ editor_data->get_undo_redo()->add_do_method(instantiated_scene, "set_position", target_pos);
}
return true;
@@ -5682,7 +5690,7 @@ void CanvasItemEditorViewport::_perform_drop_data() {
Vector<String> error_files;
- editor_data->get_undo_redo().create_action(TTR("Create Node"));
+ editor_data->get_undo_redo()->create_action(TTR("Create Node"));
for (int i = 0; i < selected_files.size(); i++) {
String path = selected_files[i];
@@ -5713,7 +5721,7 @@ void CanvasItemEditorViewport::_perform_drop_data() {
}
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
if (error_files.size() > 0) {
String files_str;
diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h
index 04fd819dec..2ca495e5d6 100644
--- a/editor/plugins/canvas_item_editor_plugin.h
+++ b/editor/plugins/canvas_item_editor_plugin.h
@@ -45,6 +45,7 @@
class EditorData;
class CanvasItemEditorViewport;
class ViewPanner;
+class EditorUndoRedoManager;
class CanvasItemEditorSelectedItem : public Object {
GDCLASS(CanvasItemEditorSelectedItem, Object);
@@ -400,7 +401,7 @@ private:
void _prepare_grid_menu();
void _on_grid_menu_id_pressed(int p_id);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
List<CanvasItem *> _get_edited_canvas_items(bool retrieve_locked = false, bool remove_canvas_item_if_parent_in_selection = true);
Rect2 _get_encompassing_rect_from_list(List<CanvasItem *> p_list);
@@ -547,7 +548,7 @@ public:
Tool get_current_tool() { return tool; }
void set_current_tool(Tool p_tool);
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void edit(CanvasItem *p_canvas_item);
void focus_selection();
diff --git a/editor/plugins/cast_2d_editor_plugin.cpp b/editor/plugins/cast_2d_editor_plugin.cpp
index 18c38e7ab8..a8d255f997 100644
--- a/editor/plugins/cast_2d_editor_plugin.cpp
+++ b/editor/plugins/cast_2d_editor_plugin.cpp
@@ -32,6 +32,7 @@
#include "canvas_item_editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/2d/ray_cast_2d.h"
#include "scene/2d/shape_cast_2d.h"
diff --git a/editor/plugins/cast_2d_editor_plugin.h b/editor/plugins/cast_2d_editor_plugin.h
index d9c0cc4a06..85ff497bc7 100644
--- a/editor/plugins/cast_2d_editor_plugin.h
+++ b/editor/plugins/cast_2d_editor_plugin.h
@@ -35,11 +35,12 @@
#include "scene/2d/node_2d.h"
class CanvasItemEditor;
+class EditorUndoRedoManager;
class Cast2DEditor : public Control {
GDCLASS(Cast2DEditor, Control);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
CanvasItemEditor *canvas_item_editor = nullptr;
Node2D *node;
diff --git a/editor/plugins/collision_shape_2d_editor_plugin.cpp b/editor/plugins/collision_shape_2d_editor_plugin.cpp
index af20064a8d..11992ad10e 100644
--- a/editor/plugins/collision_shape_2d_editor_plugin.cpp
+++ b/editor/plugins/collision_shape_2d_editor_plugin.cpp
@@ -33,6 +33,7 @@
#include "canvas_item_editor_plugin.h"
#include "core/os/keyboard.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/resources/capsule_shape_2d.h"
#include "scene/resources/circle_shape_2d.h"
#include "scene/resources/concave_polygon_shape_2d.h"
diff --git a/editor/plugins/collision_shape_2d_editor_plugin.h b/editor/plugins/collision_shape_2d_editor_plugin.h
index f7de05ddd1..49e0820ae9 100644
--- a/editor/plugins/collision_shape_2d_editor_plugin.h
+++ b/editor/plugins/collision_shape_2d_editor_plugin.h
@@ -35,6 +35,7 @@
#include "scene/2d/collision_shape_2d.h"
class CanvasItemEditor;
+class EditorUndoRedoManager;
class CollisionShape2DEditor : public Control {
GDCLASS(CollisionShape2DEditor, Control);
@@ -61,7 +62,7 @@ class CollisionShape2DEditor : public Control {
Point2(1, -1),
};
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
CanvasItemEditor *canvas_item_editor = nullptr;
CollisionShape2D *node = nullptr;
diff --git a/editor/plugins/control_editor_plugin.cpp b/editor/plugins/control_editor_plugin.cpp
index 2756e45cf4..2a12dc0e89 100644
--- a/editor/plugins/control_editor_plugin.cpp
+++ b/editor/plugins/control_editor_plugin.cpp
@@ -31,10 +31,14 @@
#include "control_editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/canvas_item_editor_plugin.h"
#include "scene/gui/separator.h"
+// Inspector controls.
+
void ControlPositioningWarning::_update_warning() {
if (!control_node) {
title_icon->set_texture(nullptr);
@@ -49,7 +53,7 @@ void ControlPositioningWarning::_update_warning() {
title_label->set_text(TTR("This node doesn't have a control parent."));
hint_label->set_text(TTR("Use the appropriate layout properties depending on where you are going to put it."));
} else if (Object::cast_to<Container>(parent_node)) {
- title_icon->set_texture(get_theme_icon(SNAME("Container"), SNAME("EditorIcons")));
+ title_icon->set_texture(get_theme_icon(SNAME("ContainerLayout"), SNAME("EditorIcons")));
title_label->set_text(TTR("This node is a child of a container."));
hint_label->set_text(TTR("Use container properties for positioning."));
} else {
@@ -448,37 +452,280 @@ bool EditorInspectorPluginControl::parse_property(Object *p_object, const Varian
return false;
}
-void ControlEditorToolbar::_set_anchors_and_offsets_preset(Control::LayoutPreset p_preset) {
+// Toolbars controls.
+
+Size2 ControlEditorPopupButton::get_minimum_size() const {
+ Vector2 base_size = Vector2(26, 26) * EDSCALE;
+
+ if (arrow_icon.is_null()) {
+ return base_size;
+ }
+
+ Vector2 final_size;
+ final_size.x = base_size.x + arrow_icon->get_width();
+ final_size.y = MAX(base_size.y, arrow_icon->get_height());
+
+ return final_size;
+}
+
+void ControlEditorPopupButton::toggled(bool p_pressed) {
+ if (!p_pressed) {
+ return;
+ }
+
+ Size2 size = get_size() * get_viewport()->get_canvas_transform().get_scale();
+
+ popup_panel->set_size(Size2(size.width, 0));
+ Point2 gp = get_screen_position();
+ gp.y += size.y;
+ if (is_layout_rtl()) {
+ gp.x += size.width - popup_panel->get_size().width;
+ }
+ popup_panel->set_position(gp);
+
+ popup_panel->popup();
+}
+
+void ControlEditorPopupButton::_popup_visibility_changed(bool p_visible) {
+ set_pressed(p_visible);
+}
+
+void ControlEditorPopupButton::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE:
+ case NOTIFICATION_THEME_CHANGED: {
+ arrow_icon = get_theme_icon("select_arrow", "Tree");
+ } break;
+
+ case NOTIFICATION_DRAW: {
+ if (arrow_icon.is_valid()) {
+ Vector2 arrow_pos = Point2(26, 0) * EDSCALE;
+ arrow_pos.y = get_size().y / 2 - arrow_icon->get_height() / 2;
+ draw_texture(arrow_icon, arrow_pos);
+ }
+ } break;
+
+ case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: {
+ popup_panel->set_layout_direction((Window::LayoutDirection)get_layout_direction());
+ } break;
+
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ if (!is_visible_in_tree()) {
+ popup_panel->hide();
+ }
+ } break;
+ }
+}
+
+ControlEditorPopupButton::ControlEditorPopupButton() {
+ set_flat(true);
+ set_toggle_mode(true);
+ set_focus_mode(FOCUS_NONE);
+
+ popup_panel = memnew(PopupPanel);
+ popup_panel->set_theme_type_variation("ControlEditorPopupButton");
+ add_child(popup_panel);
+ popup_panel->connect("about_to_popup", callable_mp(this, &ControlEditorPopupButton::_popup_visibility_changed).bind(true));
+ popup_panel->connect("popup_hide", callable_mp(this, &ControlEditorPopupButton::_popup_visibility_changed).bind(false));
+
+ popup_vbox = memnew(VBoxContainer);
+ popup_panel->add_child(popup_vbox);
+}
+
+void ControlEditorPresetPicker::_add_row_button(HBoxContainer *p_row, const int p_preset, const String &p_name) {
+ ERR_FAIL_COND(preset_buttons.has(p_preset));
+
+ Button *b = memnew(Button);
+ b->set_custom_minimum_size(Size2i(36, 36) * EDSCALE);
+ b->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);
+ b->set_tooltip(p_name);
+ b->set_flat(true);
+ p_row->add_child(b);
+ b->connect("pressed", callable_mp(this, &ControlEditorPresetPicker::_preset_button_pressed).bind(p_preset));
+
+ preset_buttons[p_preset] = b;
+}
+
+void ControlEditorPresetPicker::_add_separator(BoxContainer *p_box, Separator *p_separator) {
+ p_separator->add_theme_constant_override("separation", grid_separation);
+ p_separator->set_custom_minimum_size(Size2i(1, 1));
+ p_box->add_child(p_separator);
+}
+
+void AnchorPresetPicker::_preset_button_pressed(const int p_preset) {
+ emit_signal("anchors_preset_selected", p_preset);
+}
+
+void AnchorPresetPicker::_notification(int p_notification) {
+ switch (p_notification) {
+ case NOTIFICATION_ENTER_TREE:
+ case NOTIFICATION_THEME_CHANGED: {
+ preset_buttons[PRESET_TOP_LEFT]->set_icon(get_theme_icon(SNAME("ControlAlignTopLeft"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_CENTER_TOP]->set_icon(get_theme_icon(SNAME("ControlAlignCenterTop"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_TOP_RIGHT]->set_icon(get_theme_icon(SNAME("ControlAlignTopRight"), SNAME("EditorIcons")));
+
+ preset_buttons[PRESET_CENTER_LEFT]->set_icon(get_theme_icon(SNAME("ControlAlignCenterLeft"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_CENTER]->set_icon(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_CENTER_RIGHT]->set_icon(get_theme_icon(SNAME("ControlAlignCenterRight"), SNAME("EditorIcons")));
+
+ preset_buttons[PRESET_BOTTOM_LEFT]->set_icon(get_theme_icon(SNAME("ControlAlignBottomLeft"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_CENTER_BOTTOM]->set_icon(get_theme_icon(SNAME("ControlAlignCenterBottom"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_BOTTOM_RIGHT]->set_icon(get_theme_icon(SNAME("ControlAlignBottomRight"), SNAME("EditorIcons")));
+
+ preset_buttons[PRESET_TOP_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignTopWide"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_HCENTER_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_BOTTOM_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignBottomWide"), SNAME("EditorIcons")));
+
+ preset_buttons[PRESET_LEFT_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignLeftWide"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_VCENTER_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")));
+ preset_buttons[PRESET_RIGHT_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignRightWide"), SNAME("EditorIcons")));
+
+ preset_buttons[PRESET_FULL_RECT]->set_icon(get_theme_icon(SNAME("ControlAlignFullRect"), SNAME("EditorIcons")));
+ } break;
+ }
+}
+
+void AnchorPresetPicker::_bind_methods() {
+ ADD_SIGNAL(MethodInfo("anchors_preset_selected", PropertyInfo(Variant::INT, "preset")));
+}
+
+AnchorPresetPicker::AnchorPresetPicker() {
+ VBoxContainer *main_vb = memnew(VBoxContainer);
+ main_vb->add_theme_constant_override("separation", grid_separation);
+ add_child(main_vb);
+
+ HBoxContainer *top_row = memnew(HBoxContainer);
+ top_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
+ top_row->add_theme_constant_override("separation", grid_separation);
+ main_vb->add_child(top_row);
+
+ _add_row_button(top_row, PRESET_TOP_LEFT, TTR("Top Left"));
+ _add_row_button(top_row, PRESET_CENTER_TOP, TTR("Center Top"));
+ _add_row_button(top_row, PRESET_TOP_RIGHT, TTR("Top Right"));
+ _add_separator(top_row, memnew(VSeparator));
+ _add_row_button(top_row, PRESET_TOP_WIDE, TTR("Top Wide"));
+
+ HBoxContainer *mid_row = memnew(HBoxContainer);
+ mid_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
+ mid_row->add_theme_constant_override("separation", grid_separation);
+ main_vb->add_child(mid_row);
+
+ _add_row_button(mid_row, PRESET_CENTER_LEFT, TTR("Center Left"));
+ _add_row_button(mid_row, PRESET_CENTER, TTR("Center"));
+ _add_row_button(mid_row, PRESET_CENTER_RIGHT, TTR("Center Right"));
+ _add_separator(mid_row, memnew(VSeparator));
+ _add_row_button(mid_row, PRESET_HCENTER_WIDE, TTR("HCenter Wide"));
+
+ HBoxContainer *bot_row = memnew(HBoxContainer);
+ bot_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
+ bot_row->add_theme_constant_override("separation", grid_separation);
+ main_vb->add_child(bot_row);
+
+ _add_row_button(bot_row, PRESET_BOTTOM_LEFT, TTR("Bottom Left"));
+ _add_row_button(bot_row, PRESET_CENTER_BOTTOM, TTR("Center Bottom"));
+ _add_row_button(bot_row, PRESET_BOTTOM_RIGHT, TTR("Bottom Right"));
+ _add_separator(bot_row, memnew(VSeparator));
+ _add_row_button(bot_row, PRESET_BOTTOM_WIDE, TTR("Bottom Wide"));
+
+ _add_separator(main_vb, memnew(HSeparator));
+
+ HBoxContainer *extra_row = memnew(HBoxContainer);
+ extra_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
+ extra_row->add_theme_constant_override("separation", grid_separation);
+ main_vb->add_child(extra_row);
+
+ _add_row_button(extra_row, PRESET_LEFT_WIDE, TTR("Left Wide"));
+ _add_row_button(extra_row, PRESET_VCENTER_WIDE, TTR("VCenter Wide"));
+ _add_row_button(extra_row, PRESET_RIGHT_WIDE, TTR("Right Wide"));
+ _add_separator(extra_row, memnew(VSeparator));
+ _add_row_button(extra_row, PRESET_FULL_RECT, TTR("Full Rect"));
+}
+
+void SizeFlagPresetPicker::_preset_button_pressed(const int p_preset) {
+ int flags = (SizeFlags)p_preset;
+ if (expand_button->is_pressed()) {
+ flags |= SIZE_EXPAND;
+ }
+
+ emit_signal("size_flags_selected", flags);
+}
+
+void SizeFlagPresetPicker::set_allowed_flags(Vector<SizeFlags> &p_flags) {
+ preset_buttons[SIZE_SHRINK_BEGIN]->set_disabled(!p_flags.has(SIZE_SHRINK_BEGIN));
+ preset_buttons[SIZE_SHRINK_CENTER]->set_disabled(!p_flags.has(SIZE_SHRINK_CENTER));
+ preset_buttons[SIZE_SHRINK_END]->set_disabled(!p_flags.has(SIZE_SHRINK_END));
+ preset_buttons[SIZE_FILL]->set_disabled(!p_flags.has(SIZE_FILL));
+
+ expand_button->set_disabled(!p_flags.has(SIZE_EXPAND));
+ if (p_flags.has(SIZE_EXPAND)) {
+ expand_button->set_tooltip(TTR("Enable to also set the Expand flag.\nDisable to only set Shrink/Fill flags."));
+ } else {
+ expand_button->set_pressed(false);
+ expand_button->set_tooltip(TTR("Some parents of the selected nodes do not support the Expand flag."));
+ }
+}
+
+void SizeFlagPresetPicker::_notification(int p_notification) {
+ switch (p_notification) {
+ case NOTIFICATION_ENTER_TREE:
+ case NOTIFICATION_THEME_CHANGED: {
+ if (vertical) {
+ preset_buttons[SIZE_SHRINK_BEGIN]->set_icon(get_theme_icon(SNAME("ControlAlignCenterTop"), SNAME("EditorIcons")));
+ preset_buttons[SIZE_SHRINK_CENTER]->set_icon(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")));
+ preset_buttons[SIZE_SHRINK_END]->set_icon(get_theme_icon(SNAME("ControlAlignCenterBottom"), SNAME("EditorIcons")));
+
+ preset_buttons[SIZE_FILL]->set_icon(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")));
+ } else {
+ preset_buttons[SIZE_SHRINK_BEGIN]->set_icon(get_theme_icon(SNAME("ControlAlignCenterLeft"), SNAME("EditorIcons")));
+ preset_buttons[SIZE_SHRINK_CENTER]->set_icon(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")));
+ preset_buttons[SIZE_SHRINK_END]->set_icon(get_theme_icon(SNAME("ControlAlignCenterRight"), SNAME("EditorIcons")));
+
+ preset_buttons[SIZE_FILL]->set_icon(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")));
+ }
+ } break;
+ }
+}
+
+void SizeFlagPresetPicker::_bind_methods() {
+ ADD_SIGNAL(MethodInfo("size_flags_selected", PropertyInfo(Variant::INT, "size_flags")));
+}
+
+SizeFlagPresetPicker::SizeFlagPresetPicker(bool p_vertical) {
+ vertical = p_vertical;
+
+ VBoxContainer *main_vb = memnew(VBoxContainer);
+ add_child(main_vb);
+
+ HBoxContainer *main_row = memnew(HBoxContainer);
+ main_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
+ main_row->add_theme_constant_override("separation", grid_separation);
+ main_vb->add_child(main_row);
+
+ _add_row_button(main_row, SIZE_SHRINK_BEGIN, TTR("Shrink Begin"));
+ _add_row_button(main_row, SIZE_SHRINK_CENTER, TTR("Shrink Center"));
+ _add_row_button(main_row, SIZE_SHRINK_END, TTR("Shrink End"));
+ _add_separator(main_row, memnew(VSeparator));
+ _add_row_button(main_row, SIZE_FILL, TTR("Fill"));
+
+ expand_button = memnew(CheckBox);
+ expand_button->set_flat(true);
+ expand_button->set_text(TTR("Align with Expand"));
+ expand_button->set_tooltip(TTR("Enable to also set the Expand flag.\nDisable to only set Shrink/Fill flags."));
+ main_vb->add_child(expand_button);
+}
+
+// Toolbar.
+
+void ControlEditorToolbar::_anchors_preset_selected(int p_preset) {
+ LayoutPreset preset = (LayoutPreset)p_preset;
List<Node *> selection = editor_selection->get_selected_node_list();
- undo_redo->create_action(TTR("Change Anchors and Offsets"));
+ undo_redo->create_action(TTR("Change Anchors, Offsets, Grow Direction"));
for (Node *E : selection) {
Control *control = Object::cast_to<Control>(E);
if (control) {
- undo_redo->add_do_method(control, "set_anchors_preset", p_preset);
- switch (p_preset) {
- case PRESET_TOP_LEFT:
- case PRESET_TOP_RIGHT:
- case PRESET_BOTTOM_LEFT:
- case PRESET_BOTTOM_RIGHT:
- case PRESET_CENTER_LEFT:
- case PRESET_CENTER_TOP:
- case PRESET_CENTER_RIGHT:
- case PRESET_CENTER_BOTTOM:
- case PRESET_CENTER:
- undo_redo->add_do_method(control, "set_offsets_preset", p_preset, Control::PRESET_MODE_KEEP_SIZE);
- break;
- case PRESET_LEFT_WIDE:
- case PRESET_TOP_WIDE:
- case PRESET_RIGHT_WIDE:
- case PRESET_BOTTOM_WIDE:
- case PRESET_VCENTER_WIDE:
- case PRESET_HCENTER_WIDE:
- case PRESET_FULL_RECT:
- undo_redo->add_do_method(control, "set_offsets_preset", p_preset, Control::PRESET_MODE_MINSIZE);
- break;
- }
+ undo_redo->add_do_property(control, "anchors_preset", preset);
undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state());
}
}
@@ -489,10 +736,10 @@ void ControlEditorToolbar::_set_anchors_and_offsets_preset(Control::LayoutPreset
anchor_mode_button->set_pressed(anchors_mode);
}
-void ControlEditorToolbar::_set_anchors_and_offsets_to_keep_ratio() {
+void ControlEditorToolbar::_anchors_to_current_ratio() {
List<Node *> selection = editor_selection->get_selected_node_list();
- undo_redo->create_action(TTR("Change Anchors and Offsets"));
+ undo_redo->create_action(TTR("Change Anchors, Offsets (Keep Ratio)"));
for (Node *E : selection) {
Control *control = Object::cast_to<Control>(E);
@@ -521,44 +768,41 @@ void ControlEditorToolbar::_set_anchors_and_offsets_to_keep_ratio() {
undo_redo->commit_action();
}
-void ControlEditorToolbar::_set_anchors_preset(Control::LayoutPreset p_preset) {
- List<Node *> selection = editor_selection->get_selected_node_list();
+void ControlEditorToolbar::_anchor_mode_toggled(bool p_status) {
+ List<Control *> selection = _get_edited_controls();
+ for (Control *E : selection) {
+ if (Object::cast_to<Container>(E->get_parent())) {
+ continue;
+ }
- undo_redo->create_action(TTR("Change Anchors"));
- for (Node *E : selection) {
- Control *control = Object::cast_to<Control>(E);
- if (control) {
- undo_redo->add_do_method(control, "set_anchors_preset", p_preset);
- undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state());
+ if (p_status) {
+ E->set_meta("_edit_use_anchors_", true);
+ } else {
+ E->remove_meta("_edit_use_anchors_");
}
}
- undo_redo->commit_action();
+ anchors_mode = p_status;
+ CanvasItemEditor::get_singleton()->update_viewport();
}
-void ControlEditorToolbar::_set_container_h_preset(Control::SizeFlags p_preset) {
+void ControlEditorToolbar::_container_flags_selected(int p_flags, bool p_vertical) {
List<Node *> selection = editor_selection->get_selected_node_list();
- undo_redo->create_action(TTR("Change Horizontal Size Flags"));
- for (Node *E : selection) {
- Control *control = Object::cast_to<Control>(E);
- if (control) {
- undo_redo->add_do_method(control, "set_h_size_flags", p_preset);
- undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state());
- }
+ if (p_vertical) {
+ undo_redo->create_action(TTR("Change Vertical Size Flags"));
+ } else {
+ undo_redo->create_action(TTR("Change Horizontal Size Flags"));
}
- undo_redo->commit_action();
-}
-
-void ControlEditorToolbar::_set_container_v_preset(Control::SizeFlags p_preset) {
- List<Node *> selection = editor_selection->get_selected_node_list();
-
- undo_redo->create_action(TTR("Change Horizontal Size Flags"));
for (Node *E : selection) {
Control *control = Object::cast_to<Control>(E);
if (control) {
- undo_redo->add_do_method(control, "set_v_size_flags", p_preset);
+ if (p_vertical) {
+ undo_redo->add_do_method(control, "set_v_size_flags", p_flags);
+ } else {
+ undo_redo->add_do_method(control, "set_h_size_flags", p_flags);
+ }
undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state());
}
}
@@ -594,400 +838,205 @@ Vector2 ControlEditorToolbar::_position_to_anchor(const Control *p_control, Vect
return output;
}
-void ControlEditorToolbar::_button_toggle_anchor_mode(bool p_status) {
- List<Control *> selection = _get_edited_controls(false, false);
- for (Control *E : selection) {
- if (Object::cast_to<Container>(E->get_parent())) {
- continue;
- }
-
- if (p_status) {
- E->set_meta("_edit_use_anchors_", true);
- } else {
- E->remove_meta("_edit_use_anchors_");
- }
- }
-
- anchors_mode = p_status;
- CanvasItemEditor::get_singleton()->update_viewport();
-}
-
bool ControlEditorToolbar::_is_node_locked(const Node *p_node) {
return p_node->get_meta("_edit_lock_", false);
}
-List<Control *> ControlEditorToolbar::_get_edited_controls(bool retrieve_locked, bool remove_controls_if_parent_in_selection) {
+List<Control *> ControlEditorToolbar::_get_edited_controls() {
List<Control *> selection;
for (const KeyValue<Node *, Object *> &E : editor_selection->get_selection()) {
Control *control = Object::cast_to<Control>(E.key);
- if (control && control->is_visible_in_tree() && control->get_viewport() == EditorNode::get_singleton()->get_scene_root() && (retrieve_locked || !_is_node_locked(control))) {
+ if (control && control->is_visible_in_tree() && control->get_viewport() == EditorNode::get_singleton()->get_scene_root() && !_is_node_locked(control)) {
selection.push_back(control);
}
}
- if (remove_controls_if_parent_in_selection) {
- List<Control *> filtered_selection;
- for (Control *E : selection) {
- if (!selection.find(E->get_parent())) {
- filtered_selection.push_back(E);
- }
- }
- return filtered_selection;
- }
-
return selection;
}
-void ControlEditorToolbar::_popup_callback(int p_op) {
- switch (p_op) {
- case ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT: {
- _set_anchors_and_offsets_preset(PRESET_TOP_LEFT);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_TOP_RIGHT: {
- _set_anchors_and_offsets_preset(PRESET_TOP_RIGHT);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_BOTTOM_LEFT: {
- _set_anchors_and_offsets_preset(PRESET_BOTTOM_LEFT);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_BOTTOM_RIGHT: {
- _set_anchors_and_offsets_preset(PRESET_BOTTOM_RIGHT);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_CENTER_LEFT: {
- _set_anchors_and_offsets_preset(PRESET_CENTER_LEFT);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_CENTER_RIGHT: {
- _set_anchors_and_offsets_preset(PRESET_CENTER_RIGHT);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_CENTER_TOP: {
- _set_anchors_and_offsets_preset(PRESET_CENTER_TOP);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_CENTER_BOTTOM: {
- _set_anchors_and_offsets_preset(PRESET_CENTER_BOTTOM);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_CENTER: {
- _set_anchors_and_offsets_preset(PRESET_CENTER);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_TOP_WIDE: {
- _set_anchors_and_offsets_preset(PRESET_TOP_WIDE);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_LEFT_WIDE: {
- _set_anchors_and_offsets_preset(PRESET_LEFT_WIDE);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_RIGHT_WIDE: {
- _set_anchors_and_offsets_preset(PRESET_RIGHT_WIDE);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_BOTTOM_WIDE: {
- _set_anchors_and_offsets_preset(PRESET_BOTTOM_WIDE);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_VCENTER_WIDE: {
- _set_anchors_and_offsets_preset(PRESET_VCENTER_WIDE);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_HCENTER_WIDE: {
- _set_anchors_and_offsets_preset(PRESET_HCENTER_WIDE);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_FULL_RECT: {
- _set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
- } break;
- case ANCHORS_AND_OFFSETS_PRESET_KEEP_RATIO: {
- _set_anchors_and_offsets_to_keep_ratio();
- } break;
-
- case ANCHORS_PRESET_TOP_LEFT: {
- _set_anchors_preset(PRESET_TOP_LEFT);
- } break;
- case ANCHORS_PRESET_TOP_RIGHT: {
- _set_anchors_preset(PRESET_TOP_RIGHT);
- } break;
- case ANCHORS_PRESET_BOTTOM_LEFT: {
- _set_anchors_preset(PRESET_BOTTOM_LEFT);
- } break;
- case ANCHORS_PRESET_BOTTOM_RIGHT: {
- _set_anchors_preset(PRESET_BOTTOM_RIGHT);
- } break;
- case ANCHORS_PRESET_CENTER_LEFT: {
- _set_anchors_preset(PRESET_CENTER_LEFT);
- } break;
- case ANCHORS_PRESET_CENTER_RIGHT: {
- _set_anchors_preset(PRESET_CENTER_RIGHT);
- } break;
- case ANCHORS_PRESET_CENTER_TOP: {
- _set_anchors_preset(PRESET_CENTER_TOP);
- } break;
- case ANCHORS_PRESET_CENTER_BOTTOM: {
- _set_anchors_preset(PRESET_CENTER_BOTTOM);
- } break;
- case ANCHORS_PRESET_CENTER: {
- _set_anchors_preset(PRESET_CENTER);
- } break;
- case ANCHORS_PRESET_TOP_WIDE: {
- _set_anchors_preset(PRESET_TOP_WIDE);
- } break;
- case ANCHORS_PRESET_LEFT_WIDE: {
- _set_anchors_preset(PRESET_LEFT_WIDE);
- } break;
- case ANCHORS_PRESET_RIGHT_WIDE: {
- _set_anchors_preset(PRESET_RIGHT_WIDE);
- } break;
- case ANCHORS_PRESET_BOTTOM_WIDE: {
- _set_anchors_preset(PRESET_BOTTOM_WIDE);
- } break;
- case ANCHORS_PRESET_VCENTER_WIDE: {
- _set_anchors_preset(PRESET_VCENTER_WIDE);
- } break;
- case ANCHORS_PRESET_HCENTER_WIDE: {
- _set_anchors_preset(PRESET_HCENTER_WIDE);
- } break;
- case ANCHORS_PRESET_FULL_RECT: {
- _set_anchors_preset(Control::PRESET_FULL_RECT);
- } break;
-
- case CONTAINERS_H_PRESET_FILL: {
- _set_container_h_preset(Control::SIZE_FILL);
- } break;
- case CONTAINERS_H_PRESET_FILL_EXPAND: {
- _set_container_h_preset(Control::SIZE_EXPAND_FILL);
- } break;
- case CONTAINERS_H_PRESET_SHRINK_BEGIN: {
- _set_container_h_preset(Control::SIZE_SHRINK_BEGIN);
- } break;
- case CONTAINERS_H_PRESET_SHRINK_CENTER: {
- _set_container_h_preset(Control::SIZE_SHRINK_CENTER);
- } break;
- case CONTAINERS_H_PRESET_SHRINK_END: {
- _set_container_h_preset(Control::SIZE_SHRINK_END);
- } break;
-
- case CONTAINERS_V_PRESET_FILL: {
- _set_container_v_preset(Control::SIZE_FILL);
- } break;
- case CONTAINERS_V_PRESET_FILL_EXPAND: {
- _set_container_v_preset(Control::SIZE_EXPAND_FILL);
- } break;
- case CONTAINERS_V_PRESET_SHRINK_BEGIN: {
- _set_container_v_preset(Control::SIZE_SHRINK_BEGIN);
- } break;
- case CONTAINERS_V_PRESET_SHRINK_CENTER: {
- _set_container_v_preset(Control::SIZE_SHRINK_CENTER);
- } break;
- case CONTAINERS_V_PRESET_SHRINK_END: {
- _set_container_v_preset(Control::SIZE_SHRINK_END);
- } break;
- }
-}
-
void ControlEditorToolbar::_selection_changed() {
- // Update the anchors_mode.
- int nb_controls = 0;
- int nb_valid_controls = 0;
- int nb_anchors_mode = 0;
+ // Update toolbar visibility.
+ bool has_controls = false;
+ bool has_control_parents = false;
+ bool has_container_parents = false;
+
+ // Also update which size flags can be configured for the selected nodes.
+ Vector<SizeFlags> allowed_h_flags = {
+ SIZE_SHRINK_BEGIN,
+ SIZE_SHRINK_CENTER,
+ SIZE_SHRINK_END,
+ SIZE_FILL,
+ SIZE_EXPAND,
+ };
+ Vector<SizeFlags> allowed_v_flags = {
+ SIZE_SHRINK_BEGIN,
+ SIZE_SHRINK_CENTER,
+ SIZE_SHRINK_END,
+ SIZE_FILL,
+ SIZE_EXPAND,
+ };
- List<Node *> selection = editor_selection->get_selected_node_list();
- for (Node *E : selection) {
- Control *control = Object::cast_to<Control>(E);
+ for (const KeyValue<Node *, Object *> &E : editor_selection->get_selection()) {
+ Control *control = Object::cast_to<Control>(E.key);
if (!control) {
continue;
}
+ has_controls = true;
- nb_controls++;
+ if (Object::cast_to<Control>(control->get_parent())) {
+ has_control_parents = true;
+ }
if (Object::cast_to<Container>(control->get_parent())) {
- continue;
+ has_container_parents = true;
+
+ Container *parent_container = Object::cast_to<Container>(control->get_parent());
+
+ Vector<int> container_h_flags = parent_container->get_allowed_size_flags_horizontal();
+ Vector<SizeFlags> tmp_flags = allowed_h_flags.duplicate();
+ for (int i = 0; i < allowed_h_flags.size(); i++) {
+ if (!container_h_flags.has((int)allowed_h_flags[i])) {
+ tmp_flags.erase(allowed_h_flags[i]);
+ }
+ }
+ allowed_h_flags = tmp_flags;
+
+ Vector<int> container_v_flags = parent_container->get_allowed_size_flags_vertical();
+ tmp_flags = allowed_v_flags.duplicate();
+ for (int i = 0; i < allowed_v_flags.size(); i++) {
+ if (!container_v_flags.has((int)allowed_v_flags[i])) {
+ tmp_flags.erase(allowed_v_flags[i]);
+ }
+ }
+ allowed_v_flags = tmp_flags;
}
+ }
+
+ // Set general toolbar visibility.
+ set_visible(has_controls);
+
+ // Set anchor tools visibility.
+ if (has_controls && (!has_control_parents || !has_container_parents)) {
+ anchors_button->set_visible(true);
+ anchor_mode_button->set_visible(true);
+
+ // Update anchor mode.
+ int nb_valid_controls = 0;
+ int nb_anchors_mode = 0;
- nb_valid_controls++;
- if (control->get_meta("_edit_use_anchors_", false)) {
- nb_anchors_mode++;
+ List<Node *> selection = editor_selection->get_selected_node_list();
+ for (Node *E : selection) {
+ Control *control = Object::cast_to<Control>(E);
+ if (!control) {
+ continue;
+ }
+ if (Object::cast_to<Container>(control->get_parent())) {
+ continue;
+ }
+
+ nb_valid_controls++;
+ if (control->get_meta("_edit_use_anchors_", false)) {
+ nb_anchors_mode++;
+ }
}
+
+ anchors_mode = (nb_valid_controls == nb_anchors_mode);
+ anchor_mode_button->set_pressed(anchors_mode);
+ } else {
+ anchors_button->set_visible(false);
+ anchor_mode_button->set_visible(false);
+ anchor_mode_button->set_pressed(false);
}
- anchors_mode = (nb_valid_controls == nb_anchors_mode);
- anchor_mode_button->set_pressed(anchors_mode);
+ // Set container tools visibility.
+ if (has_controls && (!has_control_parents || has_container_parents)) {
+ containers_button->set_visible(true);
- if (nb_controls > 0) {
- set_physics_process(true);
+ // Update allowed size flags.
+ if (has_container_parents) {
+ container_h_picker->set_allowed_flags(allowed_h_flags);
+ container_v_picker->set_allowed_flags(allowed_v_flags);
+ } else {
+ Vector<SizeFlags> allowed_all_flags = {
+ SIZE_SHRINK_BEGIN,
+ SIZE_SHRINK_CENTER,
+ SIZE_SHRINK_END,
+ SIZE_FILL,
+ SIZE_EXPAND,
+ };
+
+ container_h_picker->set_allowed_flags(allowed_all_flags);
+ container_v_picker->set_allowed_flags(allowed_all_flags);
+ }
} else {
- set_physics_process(false);
- set_visible(false);
+ containers_button->set_visible(false);
}
}
void ControlEditorToolbar::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
- case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
- anchor_presets_menu->set_icon(get_theme_icon(SNAME("ControlLayout"), SNAME("EditorIcons")));
-
- PopupMenu *p = anchor_presets_menu->get_popup();
- p->clear();
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignTopLeft"), SNAME("EditorIcons")), TTR("Top Left"), ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignTopRight"), SNAME("EditorIcons")), TTR("Top Right"), ANCHORS_AND_OFFSETS_PRESET_TOP_RIGHT);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignBottomRight"), SNAME("EditorIcons")), TTR("Bottom Right"), ANCHORS_AND_OFFSETS_PRESET_BOTTOM_RIGHT);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignBottomLeft"), SNAME("EditorIcons")), TTR("Bottom Left"), ANCHORS_AND_OFFSETS_PRESET_BOTTOM_LEFT);
- p->add_separator();
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterLeft"), SNAME("EditorIcons")), TTR("Center Left"), ANCHORS_AND_OFFSETS_PRESET_CENTER_LEFT);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterTop"), SNAME("EditorIcons")), TTR("Center Top"), ANCHORS_AND_OFFSETS_PRESET_CENTER_TOP);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterRight"), SNAME("EditorIcons")), TTR("Center Right"), ANCHORS_AND_OFFSETS_PRESET_CENTER_RIGHT);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterBottom"), SNAME("EditorIcons")), TTR("Center Bottom"), ANCHORS_AND_OFFSETS_PRESET_CENTER_BOTTOM);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")), TTR("Center"), ANCHORS_AND_OFFSETS_PRESET_CENTER);
- p->add_separator();
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignLeftWide"), SNAME("EditorIcons")), TTR("Left Wide"), ANCHORS_AND_OFFSETS_PRESET_LEFT_WIDE);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignTopWide"), SNAME("EditorIcons")), TTR("Top Wide"), ANCHORS_AND_OFFSETS_PRESET_TOP_WIDE);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignRightWide"), SNAME("EditorIcons")), TTR("Right Wide"), ANCHORS_AND_OFFSETS_PRESET_RIGHT_WIDE);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignBottomWide"), SNAME("EditorIcons")), TTR("Bottom Wide"), ANCHORS_AND_OFFSETS_PRESET_BOTTOM_WIDE);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")), TTR("VCenter Wide"), ANCHORS_AND_OFFSETS_PRESET_VCENTER_WIDE);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")), TTR("HCenter Wide"), ANCHORS_AND_OFFSETS_PRESET_HCENTER_WIDE);
- p->add_separator();
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignFullRect"), SNAME("EditorIcons")), TTR("Full Rect"), ANCHORS_AND_OFFSETS_PRESET_FULL_RECT);
- p->add_icon_item(get_theme_icon(SNAME("Anchor"), SNAME("EditorIcons")), TTR("Keep Current Ratio"), ANCHORS_AND_OFFSETS_PRESET_KEEP_RATIO);
- p->set_item_tooltip(19, TTR("Adjust anchors and offsets to match the current rect size."));
-
- p->add_separator();
- p->add_submenu_item(TTR("Anchors only"), "Anchors");
- p->set_item_icon(21, get_theme_icon(SNAME("Anchor"), SNAME("EditorIcons")));
-
- anchors_popup->clear();
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignTopLeft"), SNAME("EditorIcons")), TTR("Top Left"), ANCHORS_PRESET_TOP_LEFT);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignTopRight"), SNAME("EditorIcons")), TTR("Top Right"), ANCHORS_PRESET_TOP_RIGHT);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignBottomRight"), SNAME("EditorIcons")), TTR("Bottom Right"), ANCHORS_PRESET_BOTTOM_RIGHT);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignBottomLeft"), SNAME("EditorIcons")), TTR("Bottom Left"), ANCHORS_PRESET_BOTTOM_LEFT);
- anchors_popup->add_separator();
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterLeft"), SNAME("EditorIcons")), TTR("Center Left"), ANCHORS_PRESET_CENTER_LEFT);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterTop"), SNAME("EditorIcons")), TTR("Center Top"), ANCHORS_PRESET_CENTER_TOP);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterRight"), SNAME("EditorIcons")), TTR("Center Right"), ANCHORS_PRESET_CENTER_RIGHT);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterBottom"), SNAME("EditorIcons")), TTR("Center Bottom"), ANCHORS_PRESET_CENTER_BOTTOM);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")), TTR("Center"), ANCHORS_PRESET_CENTER);
- anchors_popup->add_separator();
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignLeftWide"), SNAME("EditorIcons")), TTR("Left Wide"), ANCHORS_PRESET_LEFT_WIDE);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignTopWide"), SNAME("EditorIcons")), TTR("Top Wide"), ANCHORS_PRESET_TOP_WIDE);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignRightWide"), SNAME("EditorIcons")), TTR("Right Wide"), ANCHORS_PRESET_RIGHT_WIDE);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignBottomWide"), SNAME("EditorIcons")), TTR("Bottom Wide"), ANCHORS_PRESET_BOTTOM_WIDE);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")), TTR("VCenter Wide"), ANCHORS_PRESET_VCENTER_WIDE);
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")), TTR("HCenter Wide"), ANCHORS_PRESET_HCENTER_WIDE);
- anchors_popup->add_separator();
- anchors_popup->add_icon_item(get_theme_icon(SNAME("ControlAlignFullRect"), SNAME("EditorIcons")), TTR("Full Rect"), ANCHORS_PRESET_FULL_RECT);
-
+ case NOTIFICATION_THEME_CHANGED: {
+ anchors_button->set_icon(get_theme_icon(SNAME("ControlLayout"), SNAME("EditorIcons")));
anchor_mode_button->set_icon(get_theme_icon(SNAME("Anchor"), SNAME("EditorIcons")));
-
- container_h_presets_menu->set_icon(get_theme_icon(SNAME("Container"), SNAME("EditorIcons")));
- container_v_presets_menu->set_icon(get_theme_icon(SNAME("Container"), SNAME("EditorIcons")));
-
- p = container_h_presets_menu->get_popup();
- p->clear();
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")), TTR("Fill"), CONTAINERS_H_PRESET_FILL);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")), TTR("Fill & Expand"), CONTAINERS_H_PRESET_FILL_EXPAND);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterLeft"), SNAME("EditorIcons")), TTR("Shrink Begin"), CONTAINERS_H_PRESET_SHRINK_BEGIN);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")), TTR("Shrink Center"), CONTAINERS_H_PRESET_SHRINK_CENTER);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterRight"), SNAME("EditorIcons")), TTR("Shrink End"), CONTAINERS_H_PRESET_SHRINK_END);
-
- p = container_v_presets_menu->get_popup();
- p->clear();
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")), TTR("Fill"), CONTAINERS_V_PRESET_FILL);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")), TTR("Fill & Expand"), CONTAINERS_V_PRESET_FILL_EXPAND);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterTop"), SNAME("EditorIcons")), TTR("Shrink Begin"), CONTAINERS_V_PRESET_SHRINK_BEGIN);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")), TTR("Shrink Center"), CONTAINERS_V_PRESET_SHRINK_CENTER);
- p->add_icon_item(get_theme_icon(SNAME("ControlAlignCenterBottom"), SNAME("EditorIcons")), TTR("Shrink End"), CONTAINERS_V_PRESET_SHRINK_END);
- } break;
-
- case NOTIFICATION_PHYSICS_PROCESS: {
- bool has_control_parents = false;
- bool has_container_parents = false;
-
- // Update the viewport if the canvas_item changes
- List<Control *> selection = _get_edited_controls(true);
- for (Control *control : selection) {
- if (Object::cast_to<Control>(control->get_parent())) {
- has_control_parents = true;
- }
- if (Object::cast_to<Container>(control->get_parent())) {
- has_container_parents = true;
- }
- }
-
- // Show / Hide the control layout buttons.
- if (selection.size() > 0) {
- set_visible(true);
-
- // Toggle anchor and container layout buttons depending on parents of the selected nodes.
- // - If there are no control parents, enable everything.
- // - If there are container parents, then enable only container buttons.
- // - If there are NO container parents, then enable only anchor buttons.
- bool enable_anchors = false;
- bool enable_containers = false;
- if (!has_control_parents) {
- enable_anchors = true;
- enable_containers = true;
- } else if (has_container_parents) {
- enable_containers = true;
- } else {
- enable_anchors = true;
- }
-
- if (enable_anchors) {
- anchor_presets_menu->set_visible(true);
- anchor_mode_button->set_visible(true);
- } else {
- anchor_presets_menu->set_visible(false);
- anchor_mode_button->set_visible(false);
- }
-
- if (enable_containers) {
- container_h_presets_menu->set_visible(true);
- container_v_presets_menu->set_visible(true);
- } else {
- container_h_presets_menu->set_visible(false);
- container_v_presets_menu->set_visible(false);
- }
- } else {
- set_visible(false);
- }
+ containers_button->set_icon(get_theme_icon(SNAME("ContainerLayout"), SNAME("EditorIcons")));
} break;
}
}
ControlEditorToolbar::ControlEditorToolbar() {
- anchor_presets_menu = memnew(MenuButton);
- anchor_presets_menu->set_shortcut_context(this);
- anchor_presets_menu->set_text(TTR("Anchors"));
- anchor_presets_menu->set_tooltip(TTR("Presets for the anchor and offset values of a Control node."));
- add_child(anchor_presets_menu);
- anchor_presets_menu->set_switch_on_hover(true);
+ add_child(memnew(VSeparator));
- PopupMenu *p = anchor_presets_menu->get_popup();
- p->connect("id_pressed", callable_mp(this, &ControlEditorToolbar::_popup_callback));
+ // Anchor and offset tools.
+ anchors_button = memnew(ControlEditorPopupButton);
+ anchors_button->set_tooltip(TTR("Presets for the anchor and offset values of a Control node."));
+ add_child(anchors_button);
- anchors_popup = memnew(PopupMenu);
- p->add_child(anchors_popup);
- anchors_popup->set_name("Anchors");
- anchors_popup->connect("id_pressed", callable_mp(this, &ControlEditorToolbar::_popup_callback));
+ Label *anchors_label = memnew(Label);
+ anchors_label->set_text(TTR("Anchor preset"));
+ anchors_button->get_popup_hbox()->add_child(anchors_label);
+ AnchorPresetPicker *anchors_picker = memnew(AnchorPresetPicker);
+ anchors_picker->set_h_size_flags(SIZE_SHRINK_CENTER);
+ anchors_button->get_popup_hbox()->add_child(anchors_picker);
+ anchors_picker->connect("anchors_preset_selected", callable_mp(this, &ControlEditorToolbar::_anchors_preset_selected));
+
+ anchors_button->get_popup_hbox()->add_child(memnew(HSeparator));
+
+ Button *keep_ratio_button = memnew(Button);
+ keep_ratio_button->set_text_alignment(HORIZONTAL_ALIGNMENT_LEFT);
+ keep_ratio_button->set_text(TTR("Set to Current Ratio"));
+ keep_ratio_button->set_tooltip(TTR("Adjust anchors and offsets to match the current rect size."));
+ anchors_button->get_popup_hbox()->add_child(keep_ratio_button);
+ keep_ratio_button->connect("pressed", callable_mp(this, &ControlEditorToolbar::_anchors_to_current_ratio));
anchor_mode_button = memnew(Button);
anchor_mode_button->set_flat(true);
anchor_mode_button->set_toggle_mode(true);
anchor_mode_button->set_tooltip(TTR("When active, moving Control nodes changes their anchors instead of their offsets."));
add_child(anchor_mode_button);
- anchor_mode_button->connect("toggled", callable_mp(this, &ControlEditorToolbar::_button_toggle_anchor_mode));
-
- add_child(memnew(VSeparator));
-
- container_h_presets_menu = memnew(MenuButton);
- container_h_presets_menu->set_shortcut_context(this);
- container_h_presets_menu->set_text(TTR("Horizontal"));
- container_h_presets_menu->set_tooltip(TTR("Horizontal sizing setting for children of a Container node."));
- add_child(container_h_presets_menu);
- container_h_presets_menu->set_switch_on_hover(true);
-
- p = container_h_presets_menu->get_popup();
- p->connect("id_pressed", callable_mp(this, &ControlEditorToolbar::_popup_callback));
-
- container_v_presets_menu = memnew(MenuButton);
- container_v_presets_menu->set_shortcut_context(this);
- container_v_presets_menu->set_text(TTR("Vertical"));
- container_v_presets_menu->set_tooltip(TTR("Vertical sizing setting for children of a Container node."));
- add_child(container_v_presets_menu);
- container_v_presets_menu->set_switch_on_hover(true);
-
- p = container_v_presets_menu->get_popup();
- p->connect("id_pressed", callable_mp(this, &ControlEditorToolbar::_popup_callback));
-
+ anchor_mode_button->connect("toggled", callable_mp(this, &ControlEditorToolbar::_anchor_mode_toggled));
+
+ // Container tools.
+ containers_button = memnew(ControlEditorPopupButton);
+ containers_button->set_tooltip(TTR("Sizing settings for children of a Container node."));
+ add_child(containers_button);
+
+ Label *container_h_label = memnew(Label);
+ container_h_label->set_text(TTR("Horizontal alignment"));
+ containers_button->get_popup_hbox()->add_child(container_h_label);
+ container_h_picker = memnew(SizeFlagPresetPicker(false));
+ containers_button->get_popup_hbox()->add_child(container_h_picker);
+ container_h_picker->connect("size_flags_selected", callable_mp(this, &ControlEditorToolbar::_container_flags_selected).bind(false));
+
+ containers_button->get_popup_hbox()->add_child(memnew(HSeparator));
+
+ Label *container_v_label = memnew(Label);
+ container_v_label->set_text(TTR("Vertical alignment"));
+ containers_button->get_popup_hbox()->add_child(container_v_label);
+ container_v_picker = memnew(SizeFlagPresetPicker(true));
+ containers_button->get_popup_hbox()->add_child(container_v_picker);
+ container_v_picker->connect("size_flags_selected", callable_mp(this, &ControlEditorToolbar::_container_flags_selected).bind(true));
+
+ // Editor connections.
undo_redo = EditorNode::get_singleton()->get_undo_redo();
editor_selection = EditorNode::get_singleton()->get_editor_selection();
editor_selection->add_editor_plugin(this);
@@ -998,6 +1047,8 @@ ControlEditorToolbar::ControlEditorToolbar() {
ControlEditorToolbar *ControlEditorToolbar::singleton = nullptr;
+// Editor plugin.
+
ControlEditorPlugin::ControlEditorPlugin() {
toolbar = memnew(ControlEditorToolbar);
toolbar->hide();
diff --git a/editor/plugins/control_editor_plugin.h b/editor/plugins/control_editor_plugin.h
index 11389bc095..584d05aab0 100644
--- a/editor/plugins/control_editor_plugin.h
+++ b/editor/plugins/control_editor_plugin.h
@@ -33,14 +33,20 @@
#include "editor/editor_plugin.h"
#include "scene/gui/box_container.h"
+#include "scene/gui/button.h"
#include "scene/gui/check_box.h"
#include "scene/gui/control.h"
#include "scene/gui/label.h"
#include "scene/gui/margin_container.h"
#include "scene/gui/option_button.h"
#include "scene/gui/panel_container.h"
+#include "scene/gui/popup.h"
+#include "scene/gui/separator.h"
#include "scene/gui/texture_rect.h"
+class EditorUndoRedoManager;
+
+// Inspector controls.
class ControlPositioningWarning : public MarginContainer {
GDCLASS(ControlPositioningWarning, MarginContainer);
@@ -125,102 +131,101 @@ public:
virtual bool parse_property(Object *p_object, const Variant::Type p_type, const String &p_path, const PropertyHint p_hint, const String &p_hint_text, const uint32_t p_usage, const bool p_wide = false) override;
};
+// Toolbar controls.
+class ControlEditorPopupButton : public Button {
+ GDCLASS(ControlEditorPopupButton, Button);
+
+ Ref<Texture2D> arrow_icon;
+
+ PopupPanel *popup_panel = nullptr;
+ VBoxContainer *popup_vbox = nullptr;
+
+ void _popup_visibility_changed(bool p_visible);
+
+protected:
+ void _notification(int p_what);
+
+public:
+ virtual Size2 get_minimum_size() const override;
+ virtual void toggled(bool p_pressed) override;
+
+ VBoxContainer *get_popup_hbox() const { return popup_vbox; }
+
+ ControlEditorPopupButton();
+};
+
+class ControlEditorPresetPicker : public MarginContainer {
+ GDCLASS(ControlEditorPresetPicker, MarginContainer);
+
+ virtual void _preset_button_pressed(const int p_preset) {}
+
+protected:
+ static constexpr int grid_separation = 0;
+ HashMap<int, Button *> preset_buttons;
+
+ void _add_row_button(HBoxContainer *p_row, const int p_preset, const String &p_name);
+ void _add_separator(BoxContainer *p_box, Separator *p_separator);
+
+public:
+ ControlEditorPresetPicker() {}
+};
+
+class AnchorPresetPicker : public ControlEditorPresetPicker {
+ GDCLASS(AnchorPresetPicker, ControlEditorPresetPicker);
+
+ virtual void _preset_button_pressed(const int p_preset) override;
+
+protected:
+ void _notification(int p_notification);
+ static void _bind_methods();
+
+public:
+ AnchorPresetPicker();
+};
+
+class SizeFlagPresetPicker : public ControlEditorPresetPicker {
+ GDCLASS(SizeFlagPresetPicker, ControlEditorPresetPicker);
+
+ CheckBox *expand_button;
+
+ bool vertical = false;
+
+ virtual void _preset_button_pressed(const int p_preset) override;
+
+protected:
+ void _notification(int p_notification);
+ static void _bind_methods();
+
+public:
+ void set_allowed_flags(Vector<SizeFlags> &p_flags);
+
+ SizeFlagPresetPicker(bool p_vertical);
+};
+
class ControlEditorToolbar : public HBoxContainer {
GDCLASS(ControlEditorToolbar, HBoxContainer);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
EditorSelection *editor_selection = nullptr;
- enum MenuOption {
- ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT,
- ANCHORS_AND_OFFSETS_PRESET_TOP_RIGHT,
- ANCHORS_AND_OFFSETS_PRESET_BOTTOM_LEFT,
- ANCHORS_AND_OFFSETS_PRESET_BOTTOM_RIGHT,
- ANCHORS_AND_OFFSETS_PRESET_CENTER_LEFT,
- ANCHORS_AND_OFFSETS_PRESET_CENTER_RIGHT,
- ANCHORS_AND_OFFSETS_PRESET_CENTER_TOP,
- ANCHORS_AND_OFFSETS_PRESET_CENTER_BOTTOM,
- ANCHORS_AND_OFFSETS_PRESET_CENTER,
- ANCHORS_AND_OFFSETS_PRESET_TOP_WIDE,
- ANCHORS_AND_OFFSETS_PRESET_LEFT_WIDE,
- ANCHORS_AND_OFFSETS_PRESET_RIGHT_WIDE,
- ANCHORS_AND_OFFSETS_PRESET_BOTTOM_WIDE,
- ANCHORS_AND_OFFSETS_PRESET_VCENTER_WIDE,
- ANCHORS_AND_OFFSETS_PRESET_HCENTER_WIDE,
- ANCHORS_AND_OFFSETS_PRESET_FULL_RECT,
-
- ANCHORS_AND_OFFSETS_PRESET_KEEP_RATIO,
-
- ANCHORS_PRESET_TOP_LEFT,
- ANCHORS_PRESET_TOP_RIGHT,
- ANCHORS_PRESET_BOTTOM_LEFT,
- ANCHORS_PRESET_BOTTOM_RIGHT,
- ANCHORS_PRESET_CENTER_LEFT,
- ANCHORS_PRESET_CENTER_RIGHT,
- ANCHORS_PRESET_CENTER_TOP,
- ANCHORS_PRESET_CENTER_BOTTOM,
- ANCHORS_PRESET_CENTER,
- ANCHORS_PRESET_TOP_WIDE,
- ANCHORS_PRESET_LEFT_WIDE,
- ANCHORS_PRESET_RIGHT_WIDE,
- ANCHORS_PRESET_BOTTOM_WIDE,
- ANCHORS_PRESET_VCENTER_WIDE,
- ANCHORS_PRESET_HCENTER_WIDE,
- ANCHORS_PRESET_FULL_RECT,
-
- // Offsets Presets are not currently in use.
- OFFSETS_PRESET_TOP_LEFT,
- OFFSETS_PRESET_TOP_RIGHT,
- OFFSETS_PRESET_BOTTOM_LEFT,
- OFFSETS_PRESET_BOTTOM_RIGHT,
- OFFSETS_PRESET_CENTER_LEFT,
- OFFSETS_PRESET_CENTER_RIGHT,
- OFFSETS_PRESET_CENTER_TOP,
- OFFSETS_PRESET_CENTER_BOTTOM,
- OFFSETS_PRESET_CENTER,
- OFFSETS_PRESET_TOP_WIDE,
- OFFSETS_PRESET_LEFT_WIDE,
- OFFSETS_PRESET_RIGHT_WIDE,
- OFFSETS_PRESET_BOTTOM_WIDE,
- OFFSETS_PRESET_VCENTER_WIDE,
- OFFSETS_PRESET_HCENTER_WIDE,
- OFFSETS_PRESET_FULL_RECT,
-
- CONTAINERS_H_PRESET_FILL,
- CONTAINERS_H_PRESET_FILL_EXPAND,
- CONTAINERS_H_PRESET_SHRINK_BEGIN,
- CONTAINERS_H_PRESET_SHRINK_CENTER,
- CONTAINERS_H_PRESET_SHRINK_END,
- CONTAINERS_V_PRESET_FILL,
- CONTAINERS_V_PRESET_FILL_EXPAND,
- CONTAINERS_V_PRESET_SHRINK_BEGIN,
- CONTAINERS_V_PRESET_SHRINK_CENTER,
- CONTAINERS_V_PRESET_SHRINK_END,
- };
-
- MenuButton *anchor_presets_menu = nullptr;
- PopupMenu *anchors_popup = nullptr;
- MenuButton *container_h_presets_menu = nullptr;
- MenuButton *container_v_presets_menu = nullptr;
-
+ ControlEditorPopupButton *anchors_button = nullptr;
+ ControlEditorPopupButton *containers_button = nullptr;
Button *anchor_mode_button = nullptr;
+ SizeFlagPresetPicker *container_h_picker = nullptr;
+ SizeFlagPresetPicker *container_v_picker = nullptr;
+
bool anchors_mode = false;
- void _set_anchors_preset(Control::LayoutPreset p_preset);
- void _set_anchors_and_offsets_preset(Control::LayoutPreset p_preset);
- void _set_anchors_and_offsets_to_keep_ratio();
- void _set_container_h_preset(Control::SizeFlags p_preset);
- void _set_container_v_preset(Control::SizeFlags p_preset);
+ void _anchors_preset_selected(int p_preset);
+ void _anchors_to_current_ratio();
+ void _anchor_mode_toggled(bool p_status);
+ void _container_flags_selected(int p_flags, bool p_vertical);
Vector2 _anchor_to_position(const Control *p_control, Vector2 anchor);
Vector2 _position_to_anchor(const Control *p_control, Vector2 position);
-
- void _button_toggle_anchor_mode(bool p_status);
-
bool _is_node_locked(const Node *p_node);
- List<Control *> _get_edited_controls(bool retrieve_locked = false, bool remove_controls_if_parent_in_selection = true);
- void _popup_callback(int p_op);
+ List<Control *> _get_edited_controls();
void _selection_changed();
protected:
@@ -236,6 +241,7 @@ public:
ControlEditorToolbar();
};
+// Editor plugin.
class ControlEditorPlugin : public EditorPlugin {
GDCLASS(ControlEditorPlugin, EditorPlugin);
diff --git a/editor/plugins/cpu_particles_2d_editor_plugin.cpp b/editor/plugins/cpu_particles_2d_editor_plugin.cpp
index a7c3c32120..e20d298195 100644
--- a/editor/plugins/cpu_particles_2d_editor_plugin.cpp
+++ b/editor/plugins/cpu_particles_2d_editor_plugin.cpp
@@ -34,6 +34,7 @@
#include "core/io/image_loader.h"
#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/2d/cpu_particles_2d.h"
#include "scene/gui/separator.h"
#include "scene/resources/particles_material.h"
diff --git a/editor/plugins/cpu_particles_2d_editor_plugin.h b/editor/plugins/cpu_particles_2d_editor_plugin.h
index cc59bc924f..06ca208463 100644
--- a/editor/plugins/cpu_particles_2d_editor_plugin.h
+++ b/editor/plugins/cpu_particles_2d_editor_plugin.h
@@ -39,6 +39,7 @@
class EditorPlugin;
class SpinBox;
class EditorFileDialog;
+class EditorUndoRedoManager;
class CPUParticles2DEditorPlugin : public EditorPlugin {
GDCLASS(CPUParticles2DEditorPlugin, EditorPlugin);
@@ -70,7 +71,7 @@ class CPUParticles2DEditorPlugin : public EditorPlugin {
String source_emission_file;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void _file_selected(const String &p_file);
void _menu_callback(int p_idx);
void _generate_emission_mask();
diff --git a/editor/plugins/curve_editor_plugin.cpp b/editor/plugins/curve_editor_plugin.cpp
index 8aeab684e3..013a9f10a4 100644
--- a/editor/plugins/curve_editor_plugin.cpp
+++ b/editor/plugins/curve_editor_plugin.cpp
@@ -139,14 +139,14 @@ void CurveEditor::gui_input(const Ref<InputEvent> &p_event) {
if (!mb.is_pressed() && _dragging && mb.get_button_index() == MouseButton::LEFT) {
_dragging = false;
if (_has_undo_data) {
- UndoRedo &ur = *EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
- ur.create_action(_selected_tangent == TANGENT_NONE ? TTR("Modify Curve Point") : TTR("Modify Curve Tangent"));
- ur.add_do_method(*_curve_ref, "_set_data", _curve_ref->get_data());
- ur.add_undo_method(*_curve_ref, "_set_data", _undo_data);
+ ur->create_action(_selected_tangent == TANGENT_NONE ? TTR("Modify Curve Point") : TTR("Modify Curve Tangent"));
+ ur->add_do_method(*_curve_ref, "_set_data", _curve_ref->get_data());
+ ur->add_undo_method(*_curve_ref, "_set_data", _undo_data);
// Note: this will trigger one more "changed" signal even if nothing changes,
// but it's ok since it would have fired every frame during the drag anyways
- ur.commit_action();
+ ur->commit_action();
_has_undo_data = false;
}
@@ -301,13 +301,13 @@ void CurveEditor::on_preset_item_selected(int preset_id) {
break;
}
- UndoRedo &ur = *EditorNode::get_singleton()->get_undo_redo();
- ur.create_action(TTR("Load Curve Preset"));
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
+ ur->create_action(TTR("Load Curve Preset"));
- ur.add_do_method(&curve, "_set_data", curve.get_data());
- ur.add_undo_method(&curve, "_set_data", previous_data);
+ ur->add_do_method(&curve, "_set_data", curve.get_data());
+ ur->add_undo_method(&curve, "_set_data", previous_data);
- ur.commit_action();
+ ur->commit_action();
}
void CurveEditor::_curve_changed() {
@@ -435,8 +435,8 @@ CurveEditor::TangentIndex CurveEditor::get_tangent_at(Vector2 pos) const {
void CurveEditor::add_point(Vector2 pos) {
ERR_FAIL_COND(_curve_ref.is_null());
- UndoRedo &ur = *EditorNode::get_singleton()->get_undo_redo();
- ur.create_action(TTR("Remove Curve Point"));
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
+ ur->create_action(TTR("Remove Curve Point"));
Vector2 point_pos = get_world_pos(pos);
if (point_pos.y < 0.0) {
@@ -449,22 +449,22 @@ void CurveEditor::add_point(Vector2 pos) {
int i = _curve_ref->add_point(point_pos);
_curve_ref->remove_point(i);
- ur.add_do_method(*_curve_ref, "add_point", point_pos);
- ur.add_undo_method(*_curve_ref, "remove_point", i);
+ ur->add_do_method(*_curve_ref, "add_point", point_pos);
+ ur->add_undo_method(*_curve_ref, "remove_point", i);
- ur.commit_action();
+ ur->commit_action();
}
void CurveEditor::remove_point(int index) {
ERR_FAIL_COND(_curve_ref.is_null());
- UndoRedo &ur = *EditorNode::get_singleton()->get_undo_redo();
- ur.create_action(TTR("Remove Curve Point"));
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
+ ur->create_action(TTR("Remove Curve Point"));
Curve::Point p = _curve_ref->get_point(index);
- ur.add_do_method(*_curve_ref, "remove_point", index);
- ur.add_undo_method(*_curve_ref, "add_point", p.position, p.left_tangent, p.right_tangent, p.left_mode, p.right_mode);
+ ur->add_do_method(*_curve_ref, "remove_point", index);
+ ur->add_undo_method(*_curve_ref, "add_point", p.position, p.left_tangent, p.right_tangent, p.left_mode, p.right_mode);
if (index == _selected_point) {
set_selected_point(-1);
@@ -474,14 +474,14 @@ void CurveEditor::remove_point(int index) {
set_hover_point_index(-1);
}
- ur.commit_action();
+ ur->commit_action();
}
void CurveEditor::toggle_linear(TangentIndex tangent) {
ERR_FAIL_COND(_curve_ref.is_null());
- UndoRedo &ur = *EditorNode::get_singleton()->get_undo_redo();
- ur.create_action(TTR("Toggle Curve Linear Tangent"));
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
+ ur->create_action(TTR("Toggle Curve Linear Tangent"));
if (tangent == TANGENT_NONE) {
tangent = _selected_tangent;
@@ -493,8 +493,8 @@ void CurveEditor::toggle_linear(TangentIndex tangent) {
Curve::TangentMode prev_mode = _curve_ref->get_point_left_mode(_selected_point);
Curve::TangentMode mode = is_linear ? Curve::TANGENT_FREE : Curve::TANGENT_LINEAR;
- ur.add_do_method(*_curve_ref, "set_point_left_mode", _selected_point, mode);
- ur.add_undo_method(*_curve_ref, "set_point_left_mode", _selected_point, prev_mode);
+ ur->add_do_method(*_curve_ref, "set_point_left_mode", _selected_point, mode);
+ ur->add_undo_method(*_curve_ref, "set_point_left_mode", _selected_point, prev_mode);
} else {
bool is_linear = _curve_ref->get_point_right_mode(_selected_point) == Curve::TANGENT_LINEAR;
@@ -502,11 +502,11 @@ void CurveEditor::toggle_linear(TangentIndex tangent) {
Curve::TangentMode prev_mode = _curve_ref->get_point_right_mode(_selected_point);
Curve::TangentMode mode = is_linear ? Curve::TANGENT_FREE : Curve::TANGENT_LINEAR;
- ur.add_do_method(*_curve_ref, "set_point_right_mode", _selected_point, mode);
- ur.add_undo_method(*_curve_ref, "set_point_right_mode", _selected_point, prev_mode);
+ ur->add_do_method(*_curve_ref, "set_point_right_mode", _selected_point, mode);
+ ur->add_undo_method(*_curve_ref, "set_point_right_mode", _selected_point, prev_mode);
}
- ur.commit_action();
+ ur->commit_action();
}
void CurveEditor::set_selected_point(int index) {
diff --git a/editor/plugins/debugger_editor_plugin.cpp b/editor/plugins/debugger_editor_plugin.cpp
index c572b5b7fe..40e7dfead2 100644
--- a/editor/plugins/debugger_editor_plugin.cpp
+++ b/editor/plugins/debugger_editor_plugin.cpp
@@ -40,7 +40,7 @@
#include "editor/plugins/script_editor_plugin.h"
#include "scene/gui/menu_button.h"
-DebuggerEditorPlugin::DebuggerEditorPlugin(MenuButton *p_debug_menu) {
+DebuggerEditorPlugin::DebuggerEditorPlugin(PopupMenu *p_debug_menu) {
EditorDebuggerServer::initialize();
ED_SHORTCUT("debugger/step_into", TTR("Step Into"), Key::F11);
@@ -61,30 +61,29 @@ DebuggerEditorPlugin::DebuggerEditorPlugin(MenuButton *p_debug_menu) {
// Main editor debug menu.
debug_menu = p_debug_menu;
- PopupMenu *p = debug_menu->get_popup();
- p->set_hide_on_checkable_item_selection(false);
- p->add_check_shortcut(ED_SHORTCUT("editor/deploy_with_remote_debug", TTR("Deploy with Remote Debug")), RUN_DEPLOY_REMOTE_DEBUG);
- p->set_item_tooltip(-1,
+ debug_menu->set_hide_on_checkable_item_selection(false);
+ debug_menu->add_check_shortcut(ED_SHORTCUT("editor/deploy_with_remote_debug", TTR("Deploy with Remote Debug")), RUN_DEPLOY_REMOTE_DEBUG);
+ debug_menu->set_item_tooltip(-1,
TTR("When this option is enabled, using one-click deploy will make the executable attempt to connect to this computer's IP so the running project can be debugged.\nThis option is intended to be used for remote debugging (typically with a mobile device).\nYou don't need to enable it to use the GDScript debugger locally."));
- p->add_check_shortcut(ED_SHORTCUT("editor/small_deploy_with_network_fs", TTR("Small Deploy with Network Filesystem")), RUN_FILE_SERVER);
- p->set_item_tooltip(-1,
+ debug_menu->add_check_shortcut(ED_SHORTCUT("editor/small_deploy_with_network_fs", TTR("Small Deploy with Network Filesystem")), RUN_FILE_SERVER);
+ debug_menu->set_item_tooltip(-1,
TTR("When this option is enabled, using one-click deploy for Android will only export an executable without the project data.\nThe filesystem will be provided from the project by the editor over the network.\nOn Android, deploying will use the USB cable for faster performance. This option speeds up testing for projects with large assets."));
- p->add_separator();
- p->add_check_shortcut(ED_SHORTCUT("editor/visible_collision_shapes", TTR("Visible Collision Shapes")), RUN_DEBUG_COLLISONS);
- p->set_item_tooltip(-1,
+ debug_menu->add_separator();
+ debug_menu->add_check_shortcut(ED_SHORTCUT("editor/visible_collision_shapes", TTR("Visible Collision Shapes")), RUN_DEBUG_COLLISONS);
+ debug_menu->set_item_tooltip(-1,
TTR("When this option is enabled, collision shapes and raycast nodes (for 2D and 3D) will be visible in the running project."));
- p->add_check_shortcut(ED_SHORTCUT("editor/visible_paths", TTR("Visible Paths")), RUN_DEBUG_PATHS);
- p->set_item_tooltip(-1,
+ debug_menu->add_check_shortcut(ED_SHORTCUT("editor/visible_paths", TTR("Visible Paths")), RUN_DEBUG_PATHS);
+ debug_menu->set_item_tooltip(-1,
TTR("When this option is enabled, curve resources used by path nodes will be visible in the running project."));
- p->add_check_shortcut(ED_SHORTCUT("editor/visible_navigation", TTR("Visible Navigation")), RUN_DEBUG_NAVIGATION);
- p->set_item_tooltip(-1,
+ debug_menu->add_check_shortcut(ED_SHORTCUT("editor/visible_navigation", TTR("Visible Navigation")), RUN_DEBUG_NAVIGATION);
+ debug_menu->set_item_tooltip(-1,
TTR("When this option is enabled, navigation meshes and polygons will be visible in the running project."));
- p->add_separator();
- p->add_check_shortcut(ED_SHORTCUT("editor/sync_scene_changes", TTR("Synchronize Scene Changes")), RUN_LIVE_DEBUG);
- p->set_item_tooltip(-1,
+ debug_menu->add_separator();
+ debug_menu->add_check_shortcut(ED_SHORTCUT("editor/sync_scene_changes", TTR("Synchronize Scene Changes")), RUN_LIVE_DEBUG);
+ debug_menu->set_item_tooltip(-1,
TTR("When this option is enabled, any changes made to the scene in the editor will be replicated in the running project.\nWhen used remotely on a device, this is more efficient when the network filesystem option is enabled."));
- p->add_check_shortcut(ED_SHORTCUT("editor/sync_script_changes", TTR("Synchronize Script Changes")), RUN_RELOAD_SCRIPTS);
- p->set_item_tooltip(-1,
+ debug_menu->add_check_shortcut(ED_SHORTCUT("editor/sync_script_changes", TTR("Synchronize Script Changes")), RUN_RELOAD_SCRIPTS);
+ debug_menu->set_item_tooltip(-1,
TTR("When this option is enabled, any script that is saved will be reloaded in the running project.\nWhen used remotely on a device, this is more efficient when the network filesystem option is enabled."));
// Multi-instance, start/stop
@@ -92,9 +91,9 @@ DebuggerEditorPlugin::DebuggerEditorPlugin(MenuButton *p_debug_menu) {
instances_menu->set_name("run_instances");
instances_menu->set_hide_on_checkable_item_selection(false);
- p->add_child(instances_menu);
- p->add_separator();
- p->add_submenu_item(TTR("Run Multiple Instances"), "run_instances");
+ debug_menu->add_child(instances_menu);
+ debug_menu->add_separator();
+ debug_menu->add_submenu_item(TTR("Run Multiple Instances"), "run_instances");
instances_menu->add_radio_check_item(TTR("Run 1 Instance"));
instances_menu->set_item_metadata(0, 1);
@@ -106,7 +105,7 @@ DebuggerEditorPlugin::DebuggerEditorPlugin(MenuButton *p_debug_menu) {
instances_menu->set_item_metadata(3, 4);
instances_menu->set_item_checked(0, true);
instances_menu->connect("index_pressed", callable_mp(this, &DebuggerEditorPlugin::_select_run_count));
- p->connect("id_pressed", callable_mp(this, &DebuggerEditorPlugin::_menu_option));
+ debug_menu->connect("id_pressed", callable_mp(this, &DebuggerEditorPlugin::_menu_option));
}
DebuggerEditorPlugin::~DebuggerEditorPlugin() {
@@ -125,7 +124,7 @@ void DebuggerEditorPlugin::_select_run_count(int p_index) {
void DebuggerEditorPlugin::_menu_option(int p_option) {
switch (p_option) {
case RUN_FILE_SERVER: {
- bool ischecked = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(RUN_FILE_SERVER));
+ bool ischecked = debug_menu->is_item_checked(debug_menu->get_item_index(RUN_FILE_SERVER));
if (ischecked) {
file_server->stop();
@@ -133,45 +132,45 @@ void DebuggerEditorPlugin::_menu_option(int p_option) {
file_server->start();
}
- debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(RUN_FILE_SERVER), !ischecked);
+ debug_menu->set_item_checked(debug_menu->get_item_index(RUN_FILE_SERVER), !ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_file_server", !ischecked);
} break;
case RUN_LIVE_DEBUG: {
- bool ischecked = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(RUN_LIVE_DEBUG));
+ bool ischecked = debug_menu->is_item_checked(debug_menu->get_item_index(RUN_LIVE_DEBUG));
- debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(RUN_LIVE_DEBUG), !ischecked);
+ debug_menu->set_item_checked(debug_menu->get_item_index(RUN_LIVE_DEBUG), !ischecked);
EditorDebuggerNode::get_singleton()->set_live_debugging(!ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_live_debug", !ischecked);
} break;
case RUN_DEPLOY_REMOTE_DEBUG: {
- bool ischecked = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEPLOY_REMOTE_DEBUG));
- debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEPLOY_REMOTE_DEBUG), !ischecked);
+ bool ischecked = debug_menu->is_item_checked(debug_menu->get_item_index(RUN_DEPLOY_REMOTE_DEBUG));
+ debug_menu->set_item_checked(debug_menu->get_item_index(RUN_DEPLOY_REMOTE_DEBUG), !ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_deploy_remote_debug", !ischecked);
} break;
case RUN_DEBUG_COLLISONS: {
- bool ischecked = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEBUG_COLLISONS));
- debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEBUG_COLLISONS), !ischecked);
+ bool ischecked = debug_menu->is_item_checked(debug_menu->get_item_index(RUN_DEBUG_COLLISONS));
+ debug_menu->set_item_checked(debug_menu->get_item_index(RUN_DEBUG_COLLISONS), !ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_debug_collisons", !ischecked);
} break;
case RUN_DEBUG_PATHS: {
- bool ischecked = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEBUG_PATHS));
- debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEBUG_PATHS), !ischecked);
+ bool ischecked = debug_menu->is_item_checked(debug_menu->get_item_index(RUN_DEBUG_PATHS));
+ debug_menu->set_item_checked(debug_menu->get_item_index(RUN_DEBUG_PATHS), !ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_debug_paths", !ischecked);
} break;
case RUN_DEBUG_NAVIGATION: {
- bool ischecked = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEBUG_NAVIGATION));
- debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(RUN_DEBUG_NAVIGATION), !ischecked);
+ bool ischecked = debug_menu->is_item_checked(debug_menu->get_item_index(RUN_DEBUG_NAVIGATION));
+ debug_menu->set_item_checked(debug_menu->get_item_index(RUN_DEBUG_NAVIGATION), !ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_debug_navigation", !ischecked);
} break;
case RUN_RELOAD_SCRIPTS: {
- bool ischecked = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(RUN_RELOAD_SCRIPTS));
- debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(RUN_RELOAD_SCRIPTS), !ischecked);
+ bool ischecked = debug_menu->is_item_checked(debug_menu->get_item_index(RUN_RELOAD_SCRIPTS));
+ debug_menu->set_item_checked(debug_menu->get_item_index(RUN_RELOAD_SCRIPTS), !ischecked);
ScriptEditor::get_singleton()->set_live_auto_reload_running_scripts(!ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_reload_scripts", !ischecked);
diff --git a/editor/plugins/debugger_editor_plugin.h b/editor/plugins/debugger_editor_plugin.h
index fb963385cd..d8871128c3 100644
--- a/editor/plugins/debugger_editor_plugin.h
+++ b/editor/plugins/debugger_editor_plugin.h
@@ -41,7 +41,7 @@ class DebuggerEditorPlugin : public EditorPlugin {
GDCLASS(DebuggerEditorPlugin, EditorPlugin);
private:
- MenuButton *debug_menu = nullptr;
+ PopupMenu *debug_menu = nullptr;
EditorFileServer *file_server = nullptr;
PopupMenu *instances_menu = nullptr;
@@ -64,7 +64,7 @@ public:
virtual String get_name() const override { return "Debugger"; }
bool has_main_screen() const override { return false; }
- DebuggerEditorPlugin(MenuButton *p_menu);
+ DebuggerEditorPlugin(PopupMenu *p_menu);
~DebuggerEditorPlugin();
};
diff --git a/editor/plugins/font_config_plugin.cpp b/editor/plugins/font_config_plugin.cpp
index cadb974345..c7d3e92802 100644
--- a/editor/plugins/font_config_plugin.cpp
+++ b/editor/plugins/font_config_plugin.cpp
@@ -100,11 +100,6 @@ bool EditorPropertyFontOTObject::_get(const StringName &p_name, Variant &r_ret)
return false;
}
-void EditorPropertyFontOTObject::_bind_methods() {
- ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &EditorPropertyFontOTObject::property_can_revert);
- ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &EditorPropertyFontOTObject::property_get_revert);
-}
-
void EditorPropertyFontOTObject::set_dict(const Dictionary &p_dict) {
dict = p_dict;
}
@@ -121,7 +116,7 @@ Dictionary EditorPropertyFontOTObject::get_defaults() {
return defaults_dict;
}
-bool EditorPropertyFontOTObject::property_can_revert(const String &p_name) {
+bool EditorPropertyFontOTObject::_property_can_revert(const StringName &p_name) const {
String name = p_name;
if (name.begins_with("keys")) {
@@ -136,18 +131,19 @@ bool EditorPropertyFontOTObject::property_can_revert(const String &p_name) {
return false;
}
-Variant EditorPropertyFontOTObject::property_get_revert(const String &p_name) {
+bool EditorPropertyFontOTObject::_property_get_revert(const StringName &p_name, Variant &r_property) const {
String name = p_name;
if (name.begins_with("keys")) {
int key = name.get_slicec('/', 1).to_int();
if (defaults_dict.has(key)) {
Vector3i range = defaults_dict[key];
- return range.z;
+ r_property = range.z;
+ return true;
}
}
- return Variant();
+ return false;
}
/*************************************************************************/
diff --git a/editor/plugins/font_config_plugin.h b/editor/plugins/font_config_plugin.h
index 3eaa2fdc17..41dde3cc59 100644
--- a/editor/plugins/font_config_plugin.h
+++ b/editor/plugins/font_config_plugin.h
@@ -66,7 +66,8 @@ class EditorPropertyFontOTObject : public RefCounted {
protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
- static void _bind_methods();
+ bool _property_can_revert(const StringName &p_name) const;
+ bool _property_get_revert(const StringName &p_name, Variant &r_property) const;
public:
void set_dict(const Dictionary &p_dict);
@@ -75,9 +76,6 @@ public:
void set_defaults(const Dictionary &p_dict);
Dictionary get_defaults();
- bool property_can_revert(const String &p_name);
- Variant property_get_revert(const String &p_name);
-
EditorPropertyFontOTObject(){};
};
diff --git a/editor/plugins/gpu_particles_2d_editor_plugin.cpp b/editor/plugins/gpu_particles_2d_editor_plugin.cpp
index 8e6687c836..1487f8b7bc 100644
--- a/editor/plugins/gpu_particles_2d_editor_plugin.cpp
+++ b/editor/plugins/gpu_particles_2d_editor_plugin.cpp
@@ -34,6 +34,7 @@
#include "core/io/image_loader.h"
#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/scene_tree_dock.h"
#include "scene/2d/cpu_particles_2d.h"
#include "scene/gui/separator.h"
@@ -111,7 +112,7 @@ void GPUParticles2DEditorPlugin::_menu_callback(int p_idx) {
cpu_particles->set_process_mode(particles->get_process_mode());
cpu_particles->set_z_index(particles->get_z_index());
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Convert to CPUParticles2D"));
ur->add_do_method(SceneTreeDock::get_singleton(), "replace_node", particles, cpu_particles, true, false);
ur->add_do_reference(cpu_particles);
diff --git a/editor/plugins/gpu_particles_2d_editor_plugin.h b/editor/plugins/gpu_particles_2d_editor_plugin.h
index bf49a82166..0229b57c10 100644
--- a/editor/plugins/gpu_particles_2d_editor_plugin.h
+++ b/editor/plugins/gpu_particles_2d_editor_plugin.h
@@ -38,6 +38,7 @@
#include "scene/gui/spin_box.h"
class EditorFileDialog;
+class EditorUndoRedoManager;
class GPUParticles2DEditorPlugin : public EditorPlugin {
GDCLASS(GPUParticles2DEditorPlugin, EditorPlugin);
@@ -75,7 +76,7 @@ class GPUParticles2DEditorPlugin : public EditorPlugin {
String source_emission_file;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void _file_selected(const String &p_file);
void _menu_callback(int p_idx);
void _generate_visibility_rect();
diff --git a/editor/plugins/gpu_particles_3d_editor_plugin.cpp b/editor/plugins/gpu_particles_3d_editor_plugin.cpp
index 6750f1aa9c..335efd6949 100644
--- a/editor/plugins/gpu_particles_3d_editor_plugin.cpp
+++ b/editor/plugins/gpu_particles_3d_editor_plugin.cpp
@@ -32,6 +32,7 @@
#include "core/io/resource_loader.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/node_3d_editor_plugin.h"
#include "editor/scene_tree_dock.h"
#include "scene/3d/cpu_particles_3d.h"
@@ -271,7 +272,7 @@ void GPUParticles3DEditor::_menu_option(int p_option) {
cpu_particles->set_visible(node->is_visible());
cpu_particles->set_process_mode(node->get_process_mode());
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Convert to CPUParticles3D"));
ur->add_do_method(SceneTreeDock::get_singleton(), "replace_node", node, cpu_particles, true, false);
ur->add_do_reference(cpu_particles);
@@ -321,7 +322,7 @@ void GPUParticles3DEditor::_generate_aabb() {
node->set_emitting(false);
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Generate Visibility AABB"));
ur->add_do_method(node, "set_visibility_aabb", rect);
ur->add_undo_method(node, "set_visibility_aabb", node->get_visibility_aabb());
diff --git a/editor/plugins/gradient_editor_plugin.cpp b/editor/plugins/gradient_editor_plugin.cpp
index 542aee879b..460178490e 100644
--- a/editor/plugins/gradient_editor_plugin.cpp
+++ b/editor/plugins/gradient_editor_plugin.cpp
@@ -34,6 +34,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "node_3d_editor_plugin.h"
Size2 GradientEditor::get_minimum_size() const {
@@ -55,7 +56,7 @@ void GradientEditor::_gradient_changed() {
void GradientEditor::_ramp_changed() {
editing = true;
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Gradient Edited"), UndoRedo::MERGE_ENDS);
undo_redo->add_do_method(gradient.ptr(), "set_offsets", get_offsets());
undo_redo->add_do_method(gradient.ptr(), "set_colors", get_colors());
diff --git a/editor/plugins/gradient_texture_2d_editor_plugin.cpp b/editor/plugins/gradient_texture_2d_editor_plugin.cpp
index df45d6c290..6c463f71cf 100644
--- a/editor/plugins/gradient_texture_2d_editor_plugin.cpp
+++ b/editor/plugins/gradient_texture_2d_editor_plugin.cpp
@@ -32,6 +32,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/box_container.h"
#include "scene/gui/flow_container.h"
#include "scene/gui/separator.h"
@@ -175,7 +176,7 @@ void GradientTexture2DEditorRect::_notification(int p_what) {
}
GradientTexture2DEditorRect::GradientTexture2DEditorRect() {
- undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ undo_redo = EditorNode::get_undo_redo();
checkerboard = memnew(TextureRect);
checkerboard->set_stretch_mode(TextureRect::STRETCH_TILE);
@@ -222,7 +223,7 @@ void GradientTexture2DEditor::_notification(int p_what) {
}
GradientTexture2DEditor::GradientTexture2DEditor() {
- undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ undo_redo = EditorNode::get_undo_redo();
HFlowContainer *toolbar = memnew(HFlowContainer);
add_child(toolbar);
diff --git a/editor/plugins/gradient_texture_2d_editor_plugin.h b/editor/plugins/gradient_texture_2d_editor_plugin.h
index 93c49b1e6f..9faf33152a 100644
--- a/editor/plugins/gradient_texture_2d_editor_plugin.h
+++ b/editor/plugins/gradient_texture_2d_editor_plugin.h
@@ -34,6 +34,8 @@
#include "editor/editor_plugin.h"
#include "editor/editor_spin_slider.h"
+class EditorUndoRedoManager;
+
class GradientTexture2DEditorRect : public Control {
GDCLASS(GradientTexture2DEditorRect, Control);
@@ -44,7 +46,7 @@ class GradientTexture2DEditorRect : public Control {
};
Ref<GradientTexture2D> texture;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
bool snap_enabled = false;
float snap_size = 0;
@@ -74,7 +76,7 @@ class GradientTexture2DEditor : public VBoxContainer {
GDCLASS(GradientTexture2DEditor, VBoxContainer);
Ref<GradientTexture2D> texture;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Button *reverse_button = nullptr;
Button *snap_button = nullptr;
diff --git a/editor/plugins/material_editor_plugin.cpp b/editor/plugins/material_editor_plugin.cpp
index 1b4d98fc3f..5d59f62f05 100644
--- a/editor/plugins/material_editor_plugin.cpp
+++ b/editor/plugins/material_editor_plugin.cpp
@@ -33,6 +33,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/subviewport_container.h"
#include "scene/resources/fog_material.h"
#include "scene/resources/particles_material.h"
@@ -261,10 +262,8 @@ void EditorInspectorPluginMaterial::parse_begin(Object *p_object) {
}
void EditorInspectorPluginMaterial::_undo_redo_inspector_callback(Object *p_undo_redo, Object *p_edited, String p_property, Variant p_new_value) {
- UndoRedo *undo_redo = Object::cast_to<UndoRedo>(p_undo_redo);
- if (!undo_redo) {
- return;
- }
+ Ref<EditorUndoRedoManager> undo_redo = Object::cast_to<EditorUndoRedoManager>(p_undo_redo);
+ ERR_FAIL_COND(!undo_redo.is_valid());
// For BaseMaterial3D, if a roughness or metallic textures is being assigned to an empty slot,
// set the respective metallic or roughness factor to 1.0 as a convenience feature
diff --git a/editor/plugins/mesh_instance_3d_editor_plugin.cpp b/editor/plugins/mesh_instance_3d_editor_plugin.cpp
index 5fb885ad1f..7bd406b869 100644
--- a/editor/plugins/mesh_instance_3d_editor_plugin.cpp
+++ b/editor/plugins/mesh_instance_3d_editor_plugin.cpp
@@ -32,6 +32,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "node_3d_editor_plugin.h"
#include "scene/3d/collision_shape_3d.h"
#include "scene/3d/navigation_region_3d.h"
@@ -60,7 +61,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) {
switch (p_option) {
case MENU_OPTION_CREATE_STATIC_TRIMESH_BODY: {
EditorSelection *editor_selection = EditorNode::get_singleton()->get_editor_selection();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
List<Node *> selection = editor_selection->get_selected_node_list();
@@ -147,7 +148,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) {
Node *owner = get_tree()->get_edited_scene_root();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Create Trimesh Static Shape"));
@@ -177,7 +178,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) {
err_dialog->popup_centered();
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
if (simplify) {
ur->create_action(TTR("Create Simplified Convex Shape"));
@@ -217,7 +218,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) {
err_dialog->popup_centered();
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Create Multiple Convex Shapes"));
@@ -254,7 +255,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) {
Node *owner = get_tree()->get_edited_scene_root();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Create Navigation Mesh"));
ur->add_do_method(node, "add_child", nmi, true);
@@ -311,7 +312,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) {
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Unwrap UV2"));
ur->add_do_method(node, "set_mesh", unwrapped_mesh);
@@ -470,7 +471,7 @@ void MeshInstance3DEditor::_create_outline_mesh() {
mi->set_mesh(mesho);
Node *owner = get_tree()->get_edited_scene_root();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Create Outline"));
diff --git a/editor/plugins/node_3d_editor_gizmos.cpp b/editor/plugins/node_3d_editor_gizmos.cpp
index e8f143a637..043848080f 100644
--- a/editor/plugins/node_3d_editor_gizmos.cpp
+++ b/editor/plugins/node_3d_editor_gizmos.cpp
@@ -35,6 +35,7 @@
#include "core/math/geometry_3d.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/node_3d_editor_plugin.h"
#include "scene/3d/audio_listener_3d.h"
#include "scene/3d/audio_stream_player_3d.h"
@@ -51,10 +52,10 @@
#include "scene/3d/light_3d.h"
#include "scene/3d/lightmap_gi.h"
#include "scene/3d/lightmap_probe.h"
+#include "scene/3d/marker_3d.h"
#include "scene/3d/mesh_instance_3d.h"
#include "scene/3d/navigation_region_3d.h"
#include "scene/3d/occluder_instance_3d.h"
-#include "scene/3d/position_3d.h"
#include "scene/3d/ray_cast_3d.h"
#include "scene/3d/reflection_probe.h"
#include "scene/3d/shape_cast_3d.h"
@@ -1347,13 +1348,13 @@ void Light3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_i
light->set_param(p_id == 0 ? Light3D::PARAM_RANGE : Light3D::PARAM_SPOT_ANGLE, p_restore);
} else if (p_id == 0) {
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Light Radius"));
ur->add_do_method(light, "set_param", Light3D::PARAM_RANGE, light->get_param(Light3D::PARAM_RANGE));
ur->add_undo_method(light, "set_param", Light3D::PARAM_RANGE, p_restore);
ur->commit_action();
} else if (p_id == 1) {
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Light Radius"));
ur->add_do_method(light, "set_param", Light3D::PARAM_SPOT_ANGLE, light->get_param(Light3D::PARAM_SPOT_ANGLE));
ur->add_undo_method(light, "set_param", Light3D::PARAM_SPOT_ANGLE, p_restore);
@@ -1571,7 +1572,7 @@ void AudioStreamPlayer3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gi
player->set_emission_angle(p_restore);
} else {
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change AudioStreamPlayer3D Emission Angle"));
ur->add_do_method(player, "set_emission_angle", player->get_emission_angle());
ur->add_undo_method(player, "set_emission_angle", p_restore);
@@ -1814,7 +1815,7 @@ void Camera3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_
if (p_cancel) {
camera->set("fov", p_restore);
} else {
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Camera FOV"));
ur->add_do_property(camera, "fov", camera->get_fov());
ur->add_undo_property(camera, "fov", p_restore);
@@ -1825,7 +1826,7 @@ void Camera3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_
if (p_cancel) {
camera->set("size", p_restore);
} else {
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Camera Size"));
ur->add_do_property(camera, "size", camera->get_size());
ur->add_undo_property(camera, "size", p_restore);
@@ -2141,7 +2142,7 @@ void OccluderInstance3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_giz
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Sphere Shape Radius"));
ur->add_do_method(so.ptr(), "set_radius", so->get_radius());
ur->add_undo_method(so.ptr(), "set_radius", p_restore);
@@ -2155,7 +2156,7 @@ void OccluderInstance3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_giz
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Box Shape Size"));
ur->add_do_method(bo.ptr(), "set_size", bo->get_size());
ur->add_undo_method(bo.ptr(), "set_size", p_restore);
@@ -2169,7 +2170,7 @@ void OccluderInstance3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_giz
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Box Shape Size"));
ur->add_do_method(qo.ptr(), "set_size", qo->get_size());
ur->add_undo_method(qo.ptr(), "set_size", p_restore);
@@ -2291,7 +2292,7 @@ void Label3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
///
-Position3DGizmoPlugin::Position3DGizmoPlugin() {
+Marker3DGizmoPlugin::Marker3DGizmoPlugin() {
pos3d_mesh = Ref<ArrayMesh>(memnew(ArrayMesh));
cursor_points = Vector<Vector3>();
@@ -2315,7 +2316,7 @@ Position3DGizmoPlugin::Position3DGizmoPlugin() {
// Use the axis color which is brighter for the positive axis.
// Use a darkened axis color for the negative axis.
- // This makes it possible to see in which direction the Position3D node is rotated
+ // This makes it possible to see in which direction the Marker3D node is rotated
// (which can be important depending on how it's used).
const Color color_x = EditorNode::get_singleton()->get_gui_base()->get_theme_color(SNAME("axis_x_color"), SNAME("Editor"));
cursor_colors.push_back(color_x);
@@ -2351,19 +2352,19 @@ Position3DGizmoPlugin::Position3DGizmoPlugin() {
pos3d_mesh->surface_set_material(0, mat);
}
-bool Position3DGizmoPlugin::has_gizmo(Node3D *p_spatial) {
- return Object::cast_to<Position3D>(p_spatial) != nullptr;
+bool Marker3DGizmoPlugin::has_gizmo(Node3D *p_spatial) {
+ return Object::cast_to<Marker3D>(p_spatial) != nullptr;
}
-String Position3DGizmoPlugin::get_gizmo_name() const {
- return "Position3D";
+String Marker3DGizmoPlugin::get_gizmo_name() const {
+ return "Marker3D";
}
-int Position3DGizmoPlugin::get_priority() const {
+int Marker3DGizmoPlugin::get_priority() const {
return -1;
}
-void Position3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
+void Marker3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
p_gizmo->clear();
p_gizmo->add_mesh(pos3d_mesh);
p_gizmo->add_collision_segments(cursor_points);
@@ -2870,7 +2871,7 @@ void VisibleOnScreenNotifier3DGizmoPlugin::commit_handle(const EditorNode3DGizmo
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Notifier AABB"));
ur->add_do_method(notifier, "set_aabb", notifier->get_aabb());
ur->add_undo_method(notifier, "set_aabb", p_restore);
@@ -3061,7 +3062,7 @@ void GPUParticles3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo,
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Particles AABB"));
ur->add_do_method(particles, "set_visibility_aabb", particles->get_visibility_aabb());
ur->add_undo_method(particles, "set_visibility_aabb", p_restore);
@@ -3227,7 +3228,7 @@ void GPUParticlesCollision3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Radius"));
ur->add_do_method(sn, "set_radius", sn->call("get_radius"));
ur->add_undo_method(sn, "set_radius", p_restore);
@@ -3240,7 +3241,7 @@ void GPUParticlesCollision3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Box Shape Extents"));
ur->add_do_method(sn, "set_extents", sn->call("get_extents"));
ur->add_undo_method(sn, "set_extents", p_restore);
@@ -3499,7 +3500,7 @@ void ReflectionProbeGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo,
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Probe Extents"));
ur->add_do_method(probe, "set_extents", probe->get_extents());
ur->add_do_method(probe, "set_origin_offset", probe->get_origin_offset());
@@ -3651,7 +3652,7 @@ void DecalGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_id,
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Decal Extents"));
ur->add_do_method(decal, "set_extents", decal->get_extents());
ur->add_undo_method(decal, "set_extents", restore);
@@ -3791,7 +3792,7 @@ void VoxelGIGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_i
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Probe Extents"));
ur->add_do_method(probe, "set_extents", probe->get_extents());
ur->add_undo_method(probe, "set_extents", restore);
@@ -4406,7 +4407,7 @@ void CollisionShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Sphere Shape Radius"));
ur->add_do_method(ss.ptr(), "set_radius", ss->get_radius());
ur->add_undo_method(ss.ptr(), "set_radius", p_restore);
@@ -4420,7 +4421,7 @@ void CollisionShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Box Shape Size"));
ur->add_do_method(ss.ptr(), "set_size", ss->get_size());
ur->add_undo_method(ss.ptr(), "set_size", p_restore);
@@ -4437,7 +4438,7 @@ void CollisionShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
if (p_id == 0) {
ur->create_action(TTR("Change Capsule Shape Radius"));
ur->add_do_method(ss.ptr(), "set_radius", ss->get_radius());
@@ -4462,7 +4463,7 @@ void CollisionShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
if (p_id == 0) {
ur->create_action(TTR("Change Cylinder Shape Radius"));
ur->add_do_method(ss.ptr(), "set_radius", ss->get_radius());
@@ -4487,7 +4488,7 @@ void CollisionShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Separation Ray Shape Length"));
ur->add_do_method(ss.ptr(), "set_length", ss->get_length());
ur->add_undo_method(ss.ptr(), "set_length", p_restore);
@@ -5745,7 +5746,7 @@ void FogVolumeGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Fog Volume Extents"));
ur->add_do_method(sn, "set_extents", sn->call("get_extents"));
ur->add_undo_method(sn, "set_extents", p_restore);
diff --git a/editor/plugins/node_3d_editor_gizmos.h b/editor/plugins/node_3d_editor_gizmos.h
index 739bf1b929..7dac1bd360 100644
--- a/editor/plugins/node_3d_editor_gizmos.h
+++ b/editor/plugins/node_3d_editor_gizmos.h
@@ -334,8 +334,8 @@ public:
Label3DGizmoPlugin();
};
-class Position3DGizmoPlugin : public EditorNode3DGizmoPlugin {
- GDCLASS(Position3DGizmoPlugin, EditorNode3DGizmoPlugin);
+class Marker3DGizmoPlugin : public EditorNode3DGizmoPlugin {
+ GDCLASS(Marker3DGizmoPlugin, EditorNode3DGizmoPlugin);
Ref<ArrayMesh> pos3d_mesh;
Vector<Vector3> cursor_points;
@@ -346,7 +346,7 @@ public:
int get_priority() const override;
void redraw(EditorNode3DGizmo *p_gizmo) override;
- Position3DGizmoPlugin();
+ Marker3DGizmoPlugin();
};
class PhysicalBone3DGizmoPlugin : public EditorNode3DGizmoPlugin {
diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp
index 6afc6798d0..6add9e2e1e 100644
--- a/editor/plugins/node_3d_editor_plugin.cpp
+++ b/editor/plugins/node_3d_editor_plugin.cpp
@@ -46,6 +46,7 @@
#include "editor/scene_tree_dock.h"
#include "scene/3d/camera_3d.h"
#include "scene/3d/collision_shape_3d.h"
+#include "scene/3d/decal.h"
#include "scene/3d/light_3d.h"
#include "scene/3d/mesh_instance_3d.h"
#include "scene/3d/physics_body_3d.h"
@@ -2972,6 +2973,13 @@ void Node3DEditorViewport::_menu_option(int p_option) {
xform.scale_basis(sp->get_scale());
}
+ if (Object::cast_to<Decal>(E)) {
+ // Adjust rotation to match Decal's default orientation.
+ // This makes the decal "look" in the same direction as the camera,
+ // rather than pointing down relative to the camera orientation.
+ xform.basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
+ }
+
undo_redo->add_do_method(sp, "set_global_transform", xform);
undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
}
@@ -2999,7 +3007,16 @@ void Node3DEditorViewport::_menu_option(int p_option) {
continue;
}
- undo_redo->add_do_method(sp, "set_rotation", camera_transform.basis.get_euler_normalized());
+ Basis basis = camera_transform.basis;
+
+ if (Object::cast_to<Decal>(E)) {
+ // Adjust rotation to match Decal's default orientation.
+ // This makes the decal "look" in the same direction as the camera,
+ // rather than pointing down relative to the camera orientation.
+ basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
+ }
+
+ undo_redo->add_do_method(sp, "set_rotation", basis.get_euler_normalized());
undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
}
undo_redo->commit_action();
@@ -4003,15 +4020,15 @@ bool Node3DEditorViewport::_create_instance(Node *parent, String &path, const Po
instantiated_scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(path));
}
- editor_data->get_undo_redo().add_do_method(parent, "add_child", instantiated_scene, true);
- editor_data->get_undo_redo().add_do_method(instantiated_scene, "set_owner", EditorNode::get_singleton()->get_edited_scene());
- editor_data->get_undo_redo().add_do_reference(instantiated_scene);
- editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instantiated_scene);
+ editor_data->get_undo_redo()->add_do_method(parent, "add_child", instantiated_scene, true);
+ editor_data->get_undo_redo()->add_do_method(instantiated_scene, "set_owner", EditorNode::get_singleton()->get_edited_scene());
+ editor_data->get_undo_redo()->add_do_reference(instantiated_scene);
+ editor_data->get_undo_redo()->add_undo_method(parent, "remove_child", instantiated_scene);
String new_name = parent->validate_child_name(instantiated_scene);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_instance_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent), path, new_name);
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_instance_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent), path, new_name);
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
Node3D *node3d = Object::cast_to<Node3D>(instantiated_scene);
if (node3d) {
@@ -4024,7 +4041,7 @@ bool Node3DEditorViewport::_create_instance(Node *parent, String &path, const Po
global_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point));
global_transform.basis *= node3d->get_transform().basis;
- editor_data->get_undo_redo().add_do_method(instantiated_scene, "set_global_transform", global_transform);
+ editor_data->get_undo_redo()->add_do_method(instantiated_scene, "set_global_transform", global_transform);
}
return true;
@@ -4035,15 +4052,15 @@ void Node3DEditorViewport::_perform_drop_data() {
GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
- editor_data->get_undo_redo().create_action(vformat(TTR("Set Surface %d Override Material"), spatial_editor->get_preview_material_surface()));
- editor_data->get_undo_redo().add_do_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_material());
- editor_data->get_undo_redo().add_undo_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->create_action(vformat(TTR("Set Surface %d Override Material"), spatial_editor->get_preview_material_surface()));
+ editor_data->get_undo_redo()->add_do_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_material());
+ editor_data->get_undo_redo()->add_undo_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
+ editor_data->get_undo_redo()->commit_action();
} else if (geometry_instance) {
- editor_data->get_undo_redo().create_action(TTR("Set Material Override"));
- editor_data->get_undo_redo().add_do_method(geometry_instance, "set_material_override", spatial_editor->get_preview_material());
- editor_data->get_undo_redo().add_undo_method(geometry_instance, "set_material_override", spatial_editor->get_preview_reset_material());
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->create_action(TTR("Set Material Override"));
+ editor_data->get_undo_redo()->add_do_method(geometry_instance, "set_material_override", spatial_editor->get_preview_material());
+ editor_data->get_undo_redo()->add_undo_method(geometry_instance, "set_material_override", spatial_editor->get_preview_reset_material());
+ editor_data->get_undo_redo()->commit_action();
}
_remove_preview_material();
@@ -4054,7 +4071,7 @@ void Node3DEditorViewport::_perform_drop_data() {
Vector<String> error_files;
- editor_data->get_undo_redo().create_action(TTR("Create Node"));
+ editor_data->get_undo_redo()->create_action(TTR("Create Node"));
for (int i = 0; i < selected_files.size(); i++) {
String path = selected_files[i];
@@ -4072,7 +4089,7 @@ void Node3DEditorViewport::_perform_drop_data() {
}
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
if (error_files.size() > 0) {
String files_str;
@@ -4113,6 +4130,7 @@ bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant
continue;
}
Ref<PackedScene> scn = res;
+ Ref<Mesh> mesh = res;
Ref<Material> mat = res;
Ref<Texture2D> tex = res;
if (scn.is_valid()) {
@@ -4131,6 +4149,8 @@ bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant
spatial_editor->set_preview_material(mat);
break;
+ } else if (mesh.is_valid()) {
+ // Let the mesh pass.
} else if (tex.is_valid()) {
Ref<StandardMaterial3D> new_mat = memnew(StandardMaterial3D);
new_mat->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, tex);
@@ -7247,6 +7267,14 @@ Vector<int> Node3DEditor::get_subgizmo_selection() {
return ret;
}
+void Node3DEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
+Ref<EditorUndoRedoManager> Node3DEditor::get_undo_redo() {
+ return undo_redo;
+}
+
void Node3DEditor::add_control_to_menu_panel(Control *p_control) {
context_menu_hbox->add_child(p_control);
}
@@ -7487,7 +7515,7 @@ void Node3DEditor::_register_all_gizmos() {
add_gizmo_plugin(Ref<SoftDynamicBody3DGizmoPlugin>(memnew(SoftDynamicBody3DGizmoPlugin)));
add_gizmo_plugin(Ref<Sprite3DGizmoPlugin>(memnew(Sprite3DGizmoPlugin)));
add_gizmo_plugin(Ref<Label3DGizmoPlugin>(memnew(Label3DGizmoPlugin)));
- add_gizmo_plugin(Ref<Position3DGizmoPlugin>(memnew(Position3DGizmoPlugin)));
+ add_gizmo_plugin(Ref<Marker3DGizmoPlugin>(memnew(Marker3DGizmoPlugin)));
add_gizmo_plugin(Ref<RayCast3DGizmoPlugin>(memnew(RayCast3DGizmoPlugin)));
add_gizmo_plugin(Ref<ShapeCast3DGizmoPlugin>(memnew(ShapeCast3DGizmoPlugin)));
add_gizmo_plugin(Ref<SpringArm3DGizmoPlugin>(memnew(SpringArm3DGizmoPlugin)));
@@ -7607,7 +7635,7 @@ void Node3DEditor::_load_default_preview_settings() {
environ_tonemap_button->set_pressed(true);
environ_ao_button->set_pressed(false);
environ_gi_button->set_pressed(false);
- sun_max_distance->set_value(250);
+ sun_max_distance->set_value(100);
sun_color->set_pick_color(Color(1, 1, 1));
sun_energy->set_value(1.0);
diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h
index 4469271a38..e0298ebd5f 100644
--- a/editor/plugins/node_3d_editor_plugin.h
+++ b/editor/plugins/node_3d_editor_plugin.h
@@ -53,6 +53,7 @@ class Node3DEditorViewport;
class SubViewportContainer;
class DirectionalLight3D;
class WorldEnvironment;
+class EditorUndoRedoManager;
class ViewportRotationControl : public Control {
GDCLASS(ViewportRotationControl, Control);
@@ -201,7 +202,7 @@ private:
EditorData *editor_data = nullptr;
EditorSelection *editor_selection = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
CheckBox *preview_camera = nullptr;
SubViewportContainer *subviewport_container = nullptr;
@@ -682,7 +683,7 @@ private:
HBoxContainer *context_menu_hbox = nullptr;
void _generate_selection_boxes();
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
int camera_override_viewport_id;
@@ -820,13 +821,13 @@ public:
void select_gizmo_highlight_axis(int p_axis);
void set_custom_camera(Node *p_camera) { custom_camera = p_camera; }
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
Dictionary get_state() const;
void set_state(const Dictionary &p_state);
Ref<Environment> get_viewport_environment() { return viewport_environment; }
- UndoRedo *get_undo_redo() { return undo_redo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
+ Ref<EditorUndoRedoManager> get_undo_redo();
void add_control_to_menu_panel(Control *p_control);
void remove_control_from_menu_panel(Control *p_control);
diff --git a/editor/plugins/path_2d_editor_plugin.cpp b/editor/plugins/path_2d_editor_plugin.cpp
index fd331c4127..1d8a3f5c81 100644
--- a/editor/plugins/path_2d_editor_plugin.cpp
+++ b/editor/plugins/path_2d_editor_plugin.cpp
@@ -36,6 +36,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
void Path2DEditor::_notification(int p_what) {
switch (p_what) {
diff --git a/editor/plugins/path_2d_editor_plugin.h b/editor/plugins/path_2d_editor_plugin.h
index 720f5c090f..13eca79010 100644
--- a/editor/plugins/path_2d_editor_plugin.h
+++ b/editor/plugins/path_2d_editor_plugin.h
@@ -36,11 +36,12 @@
#include "scene/gui/separator.h"
class CanvasItemEditor;
+class EditorUndoRedoManager;
class Path2DEditor : public HBoxContainer {
GDCLASS(Path2DEditor, HBoxContainer);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
CanvasItemEditor *canvas_item_editor = nullptr;
Panel *panel = nullptr;
diff --git a/editor/plugins/path_3d_editor_plugin.cpp b/editor/plugins/path_3d_editor_plugin.cpp
index 65b15a6001..084c0c2bb0 100644
--- a/editor/plugins/path_3d_editor_plugin.cpp
+++ b/editor/plugins/path_3d_editor_plugin.cpp
@@ -35,6 +35,7 @@
#include "core/os/keyboard.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "node_3d_editor_plugin.h"
#include "scene/resources/curve.h"
@@ -172,7 +173,7 @@ void Path3DGizmo::commit_handle(int p_id, bool p_secondary, const Variant &p_res
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
if (!p_secondary) {
if (p_cancel) {
@@ -385,7 +386,7 @@ EditorPlugin::AfterGUIInput Path3DEditorPlugin::forward_spatial_gui_input(Camera
}
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
if (closest_seg != -1) {
//subdivide
@@ -427,21 +428,21 @@ EditorPlugin::AfterGUIInput Path3DEditorPlugin::forward_spatial_gui_input(Camera
// Find the offset and point index of the place to break up.
// Also check for the control points.
if (dist_to_p < click_dist) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Path Point"));
ur->add_do_method(c.ptr(), "remove_point", i);
ur->add_undo_method(c.ptr(), "add_point", c->get_point_position(i), c->get_point_in(i), c->get_point_out(i), i);
ur->commit_action();
return EditorPlugin::AFTER_GUI_INPUT_STOP;
} else if (dist_to_p_out < click_dist) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Out-Control Point"));
ur->add_do_method(c.ptr(), "set_point_out", i, Vector3());
ur->add_undo_method(c.ptr(), "set_point_out", i, c->get_point_out(i));
ur->commit_action();
return EditorPlugin::AFTER_GUI_INPUT_STOP;
} else if (dist_to_p_in < click_dist) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove In-Control Point"));
ur->add_do_method(c.ptr(), "set_point_in", i, Vector3());
ur->add_undo_method(c.ptr(), "set_point_in", i, c->get_point_in(i));
@@ -520,7 +521,7 @@ void Path3DEditorPlugin::_close_curve() {
if (c->get_point_position(0) == c->get_point_position(c->get_point_count() - 1)) {
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Close Curve"));
ur->add_do_method(c.ptr(), "add_point", c->get_point_position(0), c->get_point_in(0), c->get_point_out(0), -1);
ur->add_undo_method(c.ptr(), "remove_point", c->get_point_count());
diff --git a/editor/plugins/polygon_3d_editor_plugin.cpp b/editor/plugins/polygon_3d_editor_plugin.cpp
index 83092f990f..2b3a5c3e23 100644
--- a/editor/plugins/polygon_3d_editor_plugin.cpp
+++ b/editor/plugins/polygon_3d_editor_plugin.cpp
@@ -38,6 +38,7 @@
#include "core/os/keyboard.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "node_3d_editor_plugin.h"
#include "scene/3d/camera_3d.h"
diff --git a/editor/plugins/polygon_3d_editor_plugin.h b/editor/plugins/polygon_3d_editor_plugin.h
index e1e1261250..0eb02a39e2 100644
--- a/editor/plugins/polygon_3d_editor_plugin.h
+++ b/editor/plugins/polygon_3d_editor_plugin.h
@@ -37,11 +37,12 @@
#include "scene/resources/immediate_mesh.h"
class CanvasItemEditor;
+class EditorUndoRedoManager;
class Polygon3DEditor : public HBoxContainer {
GDCLASS(Polygon3DEditor, HBoxContainer);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
enum Mode {
MODE_CREATE,
MODE_EDIT,
diff --git a/editor/plugins/resource_preloader_editor_plugin.cpp b/editor/plugins/resource_preloader_editor_plugin.cpp
index 4e528ef066..201a3af539 100644
--- a/editor/plugins/resource_preloader_editor_plugin.cpp
+++ b/editor/plugins/resource_preloader_editor_plugin.cpp
@@ -234,6 +234,10 @@ void ResourcePreloaderEditor::_cell_button_pressed(Object *p_item, int p_column,
}
}
+void ResourcePreloaderEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
void ResourcePreloaderEditor::edit(ResourcePreloader *p_preloader) {
preloader = p_preloader;
@@ -387,7 +391,7 @@ ResourcePreloaderEditor::ResourcePreloaderEditor() {
}
void ResourcePreloaderEditorPlugin::edit(Object *p_object) {
- preloader_editor->set_undo_redo(&get_undo_redo());
+ preloader_editor->set_undo_redo(EditorNode::get_undo_redo());
ResourcePreloader *s = Object::cast_to<ResourcePreloader>(p_object);
if (!s) {
return;
diff --git a/editor/plugins/resource_preloader_editor_plugin.h b/editor/plugins/resource_preloader_editor_plugin.h
index 96cef3de21..ef80283dae 100644
--- a/editor/plugins/resource_preloader_editor_plugin.h
+++ b/editor/plugins/resource_preloader_editor_plugin.h
@@ -37,6 +37,7 @@
#include "scene/main/resource_preloader.h"
class EditorFileDialog;
+class EditorUndoRedoManager;
class ResourcePreloaderEditor : public PanelContainer {
GDCLASS(ResourcePreloaderEditor, PanelContainer);
@@ -66,7 +67,7 @@ class ResourcePreloaderEditor : public PanelContainer {
void _cell_button_pressed(Object *p_item, int p_column, int p_id, MouseButton p_button);
void _item_edited();
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
@@ -78,7 +79,7 @@ protected:
static void _bind_methods();
public:
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void edit(ResourcePreloader *p_preloader);
ResourcePreloaderEditor();
diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp
index c53ac59c11..a0c9ddb14b 100644
--- a/editor/plugins/script_editor_plugin.cpp
+++ b/editor/plugins/script_editor_plugin.cpp
@@ -49,7 +49,6 @@
#include "editor/find_in_files.h"
#include "editor/node_dock.h"
#include "editor/plugins/shader_editor_plugin.h"
-#include "modules/visual_script/editor/visual_script_editor.h"
#include "scene/main/window.h"
#include "scene/scene_string_names.h"
#include "script_text_editor.h"
@@ -66,12 +65,12 @@ String EditorSyntaxHighlighter::_get_name() const {
return "Unnamed";
}
-Array EditorSyntaxHighlighter::_get_supported_languages() const {
- Array ret;
+PackedStringArray EditorSyntaxHighlighter::_get_supported_languages() const {
+ PackedStringArray ret;
if (GDVIRTUAL_CALL(_get_supported_languages, ret)) {
return ret;
}
- return Array();
+ return PackedStringArray();
}
Ref<EditorSyntaxHighlighter> EditorSyntaxHighlighter::_create() const {
@@ -1156,8 +1155,8 @@ Ref<Script> ScriptEditor::_get_current_script() {
}
}
-Array ScriptEditor::_get_open_scripts() const {
- Array ret;
+TypedArray<Script> ScriptEditor::_get_open_scripts() const {
+ TypedArray<Script> ret;
Vector<Ref<Script>> scripts = get_open_scripts();
int scrits_amount = scripts.size();
for (int idx_script = 0; idx_script < scrits_amount; idx_script++) {
@@ -1408,8 +1407,6 @@ void ScriptEditor::_menu_option(int p_option) {
es->set_editor(EditorNode::get_singleton());
es->_run();
-
- EditorNode::get_undo_redo()->clear_history();
} break;
case FILE_CLOSE: {
if (current->is_unsaved()) {
@@ -1734,7 +1731,7 @@ void ScriptEditor::get_breakpoints(List<String> *p_breakpoints) {
continue;
}
- Array bpoints = se->get_breakpoints();
+ PackedInt32Array bpoints = se->get_breakpoints();
for (int j = 0; j < bpoints.size(); j++) {
p_breakpoints->push_back(base + ":" + itos((int)bpoints[j] + 1));
}
@@ -2382,8 +2379,8 @@ bool ScriptEditor::edit(const Ref<Resource> &p_resource, int p_line, int p_col,
se->add_syntax_highlighter(highlighter);
if (script != nullptr && !highlighter_set) {
- Array languages = highlighter->_get_supported_languages();
- if (languages.find(script->get_language()->get_name()) > -1) {
+ PackedStringArray languages = highlighter->_get_supported_languages();
+ if (languages.has(script->get_language()->get_name())) {
se->set_syntax_highlighter(highlighter);
highlighter_set = true;
}
@@ -3448,8 +3445,8 @@ Vector<Ref<Script>> ScriptEditor::get_open_scripts() const {
return out_scripts;
}
-Array ScriptEditor::_get_open_script_editors() const {
- Array script_editors;
+TypedArray<ScriptEditorBase> ScriptEditor::_get_open_script_editors() const {
+ TypedArray<ScriptEditorBase> script_editors;
for (int i = 0; i < tab_container->get_tab_count(); i++) {
ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
if (!se) {
diff --git a/editor/plugins/script_editor_plugin.h b/editor/plugins/script_editor_plugin.h
index 9f088aac49..d1898efb69 100644
--- a/editor/plugins/script_editor_plugin.h
+++ b/editor/plugins/script_editor_plugin.h
@@ -59,11 +59,11 @@ protected:
static void _bind_methods();
GDVIRTUAL0RC(String, _get_name)
- GDVIRTUAL0RC(Array, _get_supported_languages)
+ GDVIRTUAL0RC(PackedStringArray, _get_supported_languages)
public:
virtual String _get_name() const;
- virtual Array _get_supported_languages() const;
+ virtual PackedStringArray _get_supported_languages() const;
void _set_edited_resource(const Ref<Resource> &p_res) { edited_resourse = p_res; }
Ref<RefCounted> _get_edited_resource() { return edited_resourse; }
@@ -156,7 +156,7 @@ public:
virtual void ensure_focus() = 0;
virtual void tag_saved_version() = 0;
virtual void reload(bool p_soft) {}
- virtual Array get_breakpoints() = 0;
+ virtual PackedInt32Array get_breakpoints() = 0;
virtual void set_breakpoint(int p_line, bool p_enabled) = 0;
virtual void clear_breakpoints() = 0;
virtual void add_callback(const String &p_function, PackedStringArray p_args) = 0;
@@ -386,7 +386,7 @@ class ScriptEditor : public PanelContainer {
Array _get_cached_breakpoints_for_script(const String &p_path) const;
ScriptEditorBase *_get_current_editor() const;
- Array _get_open_script_editors() const;
+ TypedArray<ScriptEditorBase> _get_open_script_editors() const;
Ref<ConfigFile> script_editor_cache;
void _save_editor_state(ScriptEditorBase *p_editor);
@@ -452,7 +452,7 @@ class ScriptEditor : public PanelContainer {
void _file_dialog_action(String p_file);
Ref<Script> _get_current_script();
- Array _get_open_scripts() const;
+ TypedArray<Script> _get_open_scripts() const;
HashSet<String> textfile_extensions;
Ref<TextFile> _load_text_file(const String &p_path, Error *r_error) const;
diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp
index 5d5f452390..5e7db17edf 100644
--- a/editor/plugins/script_text_editor.cpp
+++ b/editor/plugins/script_text_editor.cpp
@@ -596,7 +596,7 @@ void ScriptTextEditor::_update_bookmark_list() {
bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT);
bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV);
- Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines();
+ PackedInt32Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines();
if (bookmark_list.size() == 0) {
return;
}
@@ -751,7 +751,7 @@ void ScriptTextEditor::_update_breakpoint_list() {
breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_breakpoint"), DEBUG_GOTO_NEXT_BREAKPOINT);
breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_breakpoint"), DEBUG_GOTO_PREV_BREAKPOINT);
- Array breakpoint_list = code_editor->get_text_editor()->get_breakpointed_lines();
+ PackedInt32Array breakpoint_list = code_editor->get_text_editor()->get_breakpointed_lines();
if (breakpoint_list.size() == 0) {
return;
}
@@ -1264,7 +1264,7 @@ void ScriptTextEditor::_edit_option(int p_op) {
EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), line + 1, dobreak);
} break;
case DEBUG_REMOVE_ALL_BREAKPOINTS: {
- Array bpoints = tx->get_breakpointed_lines();
+ PackedInt32Array bpoints = tx->get_breakpointed_lines();
for (int i = 0; i < bpoints.size(); i++) {
int line = bpoints[i];
@@ -1274,7 +1274,7 @@ void ScriptTextEditor::_edit_option(int p_op) {
}
} break;
case DEBUG_GOTO_NEXT_BREAKPOINT: {
- Array bpoints = tx->get_breakpointed_lines();
+ PackedInt32Array bpoints = tx->get_breakpointed_lines();
if (bpoints.size() <= 0) {
return;
}
@@ -1300,7 +1300,7 @@ void ScriptTextEditor::_edit_option(int p_op) {
} break;
case DEBUG_GOTO_PREV_BREAKPOINT: {
- Array bpoints = tx->get_breakpointed_lines();
+ PackedInt32Array bpoints = tx->get_breakpointed_lines();
if (bpoints.size() <= 0) {
return;
}
@@ -1441,7 +1441,7 @@ void ScriptTextEditor::reload(bool p_soft) {
scr->get_language()->reload_tool_script(scr, soft);
}
-Array ScriptTextEditor::get_breakpoints() {
+PackedInt32Array ScriptTextEditor::get_breakpoints() {
return code_editor->get_text_editor()->get_breakpointed_lines();
}
diff --git a/editor/plugins/script_text_editor.h b/editor/plugins/script_text_editor.h
index fc87c84a2c..8d2fb98721 100644
--- a/editor/plugins/script_text_editor.h
+++ b/editor/plugins/script_text_editor.h
@@ -229,7 +229,7 @@ public:
virtual void clear_executing_line() override;
virtual void reload(bool p_soft) override;
- virtual Array get_breakpoints() override;
+ virtual PackedInt32Array get_breakpoints() override;
virtual void set_breakpoint(int p_line, bool p_enabled) override;
virtual void clear_breakpoints() override;
diff --git a/editor/plugins/shader_editor_plugin.cpp b/editor/plugins/shader_editor_plugin.cpp
index d70c50f72a..4641df3dca 100644
--- a/editor/plugins/shader_editor_plugin.cpp
+++ b/editor/plugins/shader_editor_plugin.cpp
@@ -994,7 +994,7 @@ void ShaderEditor::_update_bookmark_list() {
bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT);
bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV);
- Array bookmark_list = shader_editor->get_text_editor()->get_bookmarked_lines();
+ PackedInt32Array bookmark_list = shader_editor->get_text_editor()->get_bookmarked_lines();
if (bookmark_list.size() == 0) {
return;
}
diff --git a/editor/plugins/skeleton_2d_editor_plugin.cpp b/editor/plugins/skeleton_2d_editor_plugin.cpp
index 5a1505c232..3dc068a72a 100644
--- a/editor/plugins/skeleton_2d_editor_plugin.cpp
+++ b/editor/plugins/skeleton_2d_editor_plugin.cpp
@@ -32,6 +32,7 @@
#include "canvas_item_editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/2d/mesh_instance_2d.h"
#include "scene/gui/box_container.h"
#include "thirdparty/misc/clipper.hpp"
@@ -59,7 +60,7 @@ void Skeleton2DEditor::_menu_option(int p_option) {
err_dialog->popup_centered();
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Rest Pose to Bones"));
for (int i = 0; i < node->get_bone_count(); i++) {
Bone2D *bone = node->get_bone(i);
@@ -75,7 +76,7 @@ void Skeleton2DEditor::_menu_option(int p_option) {
err_dialog->popup_centered();
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Create Rest Pose from Bones"));
for (int i = 0; i < node->get_bone_count(); i++) {
Bone2D *bone = node->get_bone(i);
diff --git a/editor/plugins/skeleton_3d_editor_plugin.cpp b/editor/plugins/skeleton_3d_editor_plugin.cpp
index c453ed26aa..c25f2bb25c 100644
--- a/editor/plugins/skeleton_3d_editor_plugin.cpp
+++ b/editor/plugins/skeleton_3d_editor_plugin.cpp
@@ -31,10 +31,10 @@
#include "skeleton_3d_editor_plugin.h"
#include "core/io/resource_saver.h"
-#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
#include "editor/editor_properties.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/animation_player_editor_plugin.h"
#include "node_3d_editor_plugin.h"
#include "scene/3d/collision_shape_3d.h"
@@ -221,7 +221,7 @@ void Skeleton3DEditor::set_keyable(const bool p_keyable) {
};
void Skeleton3DEditor::set_bone_options_enabled(const bool p_bone_options_enabled) {
- skeleton_options->get_popup()->set_item_disabled(SKELETON_OPTION_INIT_SELECTED_POSES, !p_bone_options_enabled);
+ skeleton_options->get_popup()->set_item_disabled(SKELETON_OPTION_RESET_SELECTED_POSES, !p_bone_options_enabled);
skeleton_options->get_popup()->set_item_disabled(SKELETON_OPTION_SELECTED_POSES_TO_RESTS, !p_bone_options_enabled);
};
@@ -231,12 +231,12 @@ void Skeleton3DEditor::_on_click_skeleton_option(int p_skeleton_option) {
}
switch (p_skeleton_option) {
- case SKELETON_OPTION_INIT_ALL_POSES: {
- init_pose(true);
+ case SKELETON_OPTION_RESET_ALL_POSES: {
+ reset_pose(true);
break;
}
- case SKELETON_OPTION_INIT_SELECTED_POSES: {
- init_pose(false);
+ case SKELETON_OPTION_RESET_SELECTED_POSES: {
+ reset_pose(false);
break;
}
case SKELETON_OPTION_ALL_POSES_TO_RESTS: {
@@ -258,7 +258,7 @@ void Skeleton3DEditor::_on_click_skeleton_option(int p_skeleton_option) {
}
}
-void Skeleton3DEditor::init_pose(const bool p_all_bones) {
+void Skeleton3DEditor::reset_pose(const bool p_all_bones) {
if (!skeleton) {
return;
}
@@ -267,31 +267,25 @@ void Skeleton3DEditor::init_pose(const bool p_all_bones) {
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Bone Transform"), UndoRedo::MERGE_ENDS);
if (p_all_bones) {
for (int i = 0; i < bone_len; i++) {
- Transform3D rest = skeleton->get_bone_rest(i);
- ur->add_do_method(skeleton, "set_bone_pose_position", i, rest.origin);
- ur->add_do_method(skeleton, "set_bone_pose_rotation", i, rest.basis.get_rotation_quaternion());
- ur->add_do_method(skeleton, "set_bone_pose_scale", i, rest.basis.get_scale());
ur->add_undo_method(skeleton, "set_bone_pose_position", i, skeleton->get_bone_pose_position(i));
ur->add_undo_method(skeleton, "set_bone_pose_rotation", i, skeleton->get_bone_pose_rotation(i));
ur->add_undo_method(skeleton, "set_bone_pose_scale", i, skeleton->get_bone_pose_scale(i));
}
+ ur->add_do_method(skeleton, "reset_bone_poses");
} else {
// Todo: Do method with multiple bone selection.
if (selected_bone == -1) {
ur->commit_action();
return;
}
- Transform3D rest = skeleton->get_bone_rest(selected_bone);
- ur->add_do_method(skeleton, "set_bone_pose_position", selected_bone, rest.origin);
- ur->add_do_method(skeleton, "set_bone_pose_rotation", selected_bone, rest.basis.get_rotation_quaternion());
- ur->add_do_method(skeleton, "set_bone_pose_scale", selected_bone, rest.basis.get_scale());
ur->add_undo_method(skeleton, "set_bone_pose_position", selected_bone, skeleton->get_bone_pose_position(selected_bone));
ur->add_undo_method(skeleton, "set_bone_pose_rotation", selected_bone, skeleton->get_bone_pose_rotation(selected_bone));
ur->add_undo_method(skeleton, "set_bone_pose_scale", selected_bone, skeleton->get_bone_pose_scale(selected_bone));
+ ur->add_do_method(skeleton, "reset_bone_pose", selected_bone);
}
ur->commit_action();
}
@@ -340,7 +334,7 @@ void Skeleton3DEditor::pose_to_rest(const bool p_all_bones) {
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Bone Rest"), UndoRedo::MERGE_ENDS);
if (p_all_bones) {
for (int i = 0; i < bone_len; i++) {
@@ -360,7 +354,7 @@ void Skeleton3DEditor::pose_to_rest(const bool p_all_bones) {
}
void Skeleton3DEditor::create_physical_skeleton() {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ERR_FAIL_COND(!get_tree());
Node *owner = get_tree()->get_edited_scene_root();
@@ -593,7 +587,7 @@ void Skeleton3DEditor::move_skeleton_bone(NodePath p_skeleton_path, int32_t p_se
Node *node = get_node_or_null(p_skeleton_path);
Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(node);
ERR_FAIL_NULL(skeleton);
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Bone Parentage"));
// If the target is a child of ourselves, we move only *us* and not our children.
if (skeleton->is_bone_parent_of(p_target_boneidx, p_selected_boneidx)) {
@@ -721,8 +715,8 @@ void Skeleton3DEditor::create_editors() {
// Skeleton options.
PopupMenu *p = skeleton_options->get_popup();
- p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/init_all_poses", TTR("Init all Poses")), SKELETON_OPTION_INIT_ALL_POSES);
- p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/init_selected_poses", TTR("Init selected Poses")), SKELETON_OPTION_INIT_SELECTED_POSES);
+ p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/reset_all_poses", TTR("Reset all bone Poses")), SKELETON_OPTION_RESET_ALL_POSES);
+ p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/reset_selected_poses", TTR("Reset selected Poses")), SKELETON_OPTION_RESET_SELECTED_POSES);
p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/all_poses_to_rests", TTR("Apply all poses to rests")), SKELETON_OPTION_ALL_POSES_TO_RESTS);
p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/selected_poses_to_rests", TTR("Apply selected poses to rests")), SKELETON_OPTION_SELECTED_POSES_TO_RESTS);
p->add_item(TTR("Create physical skeleton"), SKELETON_OPTION_CREATE_PHYSICAL_SKELETON);
@@ -1315,7 +1309,7 @@ void Skeleton3DGizmoPlugin::commit_subgizmos(const EditorNode3DGizmo *p_gizmo, c
Skeleton3DEditor *se = Skeleton3DEditor::get_singleton();
Node3DEditor *ne = Node3DEditor::get_singleton();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Bone Transform"));
if (ne->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || ne->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
for (int i = 0; i < p_ids.size(); i++) {
diff --git a/editor/plugins/skeleton_3d_editor_plugin.h b/editor/plugins/skeleton_3d_editor_plugin.h
index 975b54fa77..9747ed8374 100644
--- a/editor/plugins/skeleton_3d_editor_plugin.h
+++ b/editor/plugins/skeleton_3d_editor_plugin.h
@@ -31,6 +31,7 @@
#ifndef SKELETON_3D_EDITOR_PLUGIN_H
#define SKELETON_3D_EDITOR_PLUGIN_H
+#include "editor/editor_file_dialog.h"
#include "editor/editor_plugin.h"
#include "editor/editor_properties.h"
#include "node_3d_editor_plugin.h"
@@ -40,6 +41,7 @@
#include "scene/resources/immediate_mesh.h"
class EditorInspectorPluginSkeleton;
+class EditorUndoRedoManager;
class Joint;
class PhysicalBone3D;
class Skeleton3DEditorPlugin;
@@ -63,7 +65,7 @@ class BoneTransformEditor : public VBoxContainer {
Skeleton3D *skeleton = nullptr;
// String property;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
bool toggle_enabled = false;
bool updating = false;
@@ -96,8 +98,8 @@ class Skeleton3DEditor : public VBoxContainer {
friend class Skeleton3DEditorPlugin;
enum SkeletonOption {
- SKELETON_OPTION_INIT_ALL_POSES,
- SKELETON_OPTION_INIT_SELECTED_POSES,
+ SKELETON_OPTION_RESET_ALL_POSES,
+ SKELETON_OPTION_RESET_SELECTED_POSES,
SKELETON_OPTION_ALL_POSES_TO_RESTS,
SKELETON_OPTION_SELECTED_POSES_TO_RESTS,
SKELETON_OPTION_CREATE_PHYSICAL_SKELETON,
@@ -148,7 +150,7 @@ class Skeleton3DEditor : public VBoxContainer {
void create_editors();
- void init_pose(const bool p_all_bones);
+ void reset_pose(const bool p_all_bones);
void pose_to_rest(const bool p_all_bones);
void insert_keys(const bool p_all_bones);
diff --git a/editor/plugins/sprite_2d_editor_plugin.cpp b/editor/plugins/sprite_2d_editor_plugin.cpp
index 7d350fd46f..e45c907e86 100644
--- a/editor/plugins/sprite_2d_editor_plugin.cpp
+++ b/editor/plugins/sprite_2d_editor_plugin.cpp
@@ -34,6 +34,7 @@
#include "core/math/geometry_2d.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/scene_tree_dock.h"
#include "scene/2d/collision_polygon_2d.h"
#include "scene/2d/light_occluder_2d.h"
@@ -342,7 +343,7 @@ void Sprite2DEditor::_convert_to_mesh_2d_node() {
MeshInstance2D *mesh_instance = memnew(MeshInstance2D);
mesh_instance->set_mesh(mesh);
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Convert to MeshInstance2D"));
ur->add_do_method(SceneTreeDock::get_singleton(), "replace_node", node, mesh_instance, true, false);
ur->add_do_reference(mesh_instance);
@@ -400,7 +401,7 @@ void Sprite2DEditor::_convert_to_polygon_2d_node() {
polygon_2d_instance->set_polygon(polygon);
polygon_2d_instance->set_polygons(polys);
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Convert to Polygon2D"));
ur->add_do_method(SceneTreeDock::get_singleton(), "replace_node", node, polygon_2d_instance, true, false);
ur->add_do_reference(polygon_2d_instance);
@@ -422,7 +423,7 @@ void Sprite2DEditor::_create_collision_polygon_2d_node() {
CollisionPolygon2D *collision_polygon_2d_instance = memnew(CollisionPolygon2D);
collision_polygon_2d_instance->set_polygon(outline);
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Create CollisionPolygon2D Sibling"));
ur->add_do_method(this, "_add_as_sibling_or_child", node, collision_polygon_2d_instance);
ur->add_do_reference(collision_polygon_2d_instance);
@@ -455,7 +456,7 @@ void Sprite2DEditor::_create_light_occluder_2d_node() {
LightOccluder2D *light_occluder_2d_instance = memnew(LightOccluder2D);
light_occluder_2d_instance->set_occluder_polygon(polygon);
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Create LightOccluder2D Sibling"));
ur->add_do_method(this, "_add_as_sibling_or_child", node, light_occluder_2d_instance);
ur->add_do_reference(light_occluder_2d_instance);
diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp
index a39d24a167..205fed48b4 100644
--- a/editor/plugins/sprite_frames_editor_plugin.cpp
+++ b/editor/plugins/sprite_frames_editor_plugin.cpp
@@ -37,6 +37,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/scene_tree_dock.h"
#include "scene/3d/sprite_3d.h"
#include "scene/gui/center_container.h"
@@ -1010,6 +1011,10 @@ void SpriteFramesEditor::edit(SpriteFrames *p_frames) {
}
}
+void SpriteFramesEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
Variant SpriteFramesEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
if (!frames->has_animation(edited_anim)) {
return false;
@@ -1471,7 +1476,7 @@ SpriteFramesEditor::SpriteFramesEditor() {
}
void SpriteFramesEditorPlugin::edit(Object *p_object) {
- frames_editor->set_undo_redo(&get_undo_redo());
+ frames_editor->set_undo_redo(get_undo_redo());
SpriteFrames *s;
AnimatedSprite2D *animated_sprite = Object::cast_to<AnimatedSprite2D>(p_object);
diff --git a/editor/plugins/sprite_frames_editor_plugin.h b/editor/plugins/sprite_frames_editor_plugin.h
index 6352259b73..f2530b732f 100644
--- a/editor/plugins/sprite_frames_editor_plugin.h
+++ b/editor/plugins/sprite_frames_editor_plugin.h
@@ -45,6 +45,7 @@
#include "scene/gui/tree.h"
class EditorFileDialog;
+class EditorUndoRedoManager;
class SpriteFramesEditor : public HSplitContainer {
GDCLASS(SpriteFramesEditor, HSplitContainer);
@@ -151,7 +152,7 @@ class SpriteFramesEditor : public HSplitContainer {
bool updating;
bool updating_split_settings = false; // Skip SpinBox/Range callback when setting value by code.
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
@@ -176,7 +177,7 @@ protected:
static void _bind_methods();
public:
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void edit(SpriteFrames *p_frames);
SpriteFramesEditor();
diff --git a/editor/plugins/text_editor.cpp b/editor/plugins/text_editor.cpp
index 196d87da36..0900415b04 100644
--- a/editor/plugins/text_editor.cpp
+++ b/editor/plugins/text_editor.cpp
@@ -128,8 +128,8 @@ Control *TextEditor::get_base_editor() const {
return code_editor->get_text_editor();
}
-Array TextEditor::get_breakpoints() {
- return Array();
+PackedInt32Array TextEditor::get_breakpoints() {
+ return PackedInt32Array();
}
void TextEditor::reload_text() {
@@ -165,7 +165,7 @@ void TextEditor::_update_bookmark_list() {
bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT);
bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV);
- Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines();
+ PackedInt32Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines();
if (bookmark_list.size() == 0) {
return;
}
diff --git a/editor/plugins/text_editor.h b/editor/plugins/text_editor.h
index 4f0121da52..15f7c45653 100644
--- a/editor/plugins/text_editor.h
+++ b/editor/plugins/text_editor.h
@@ -118,7 +118,7 @@ public:
virtual Variant get_edit_state() override;
virtual void set_edit_state(const Variant &p_state) override;
virtual Vector<String> get_functions() override;
- virtual Array get_breakpoints() override;
+ virtual PackedInt32Array get_breakpoints() override;
virtual void set_breakpoint(int p_line, bool p_enabled) override{};
virtual void clear_breakpoints() override{};
virtual void goto_line(int p_line, bool p_with_error = false) override;
diff --git a/editor/plugins/texture_region_editor_plugin.cpp b/editor/plugins/texture_region_editor_plugin.cpp
index 0bd8a8a484..772bae6544 100644
--- a/editor/plugins/texture_region_editor_plugin.cpp
+++ b/editor/plugins/texture_region_editor_plugin.cpp
@@ -36,6 +36,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/check_box.h"
#include "scene/gui/separator.h"
#include "scene/gui/view_panner.h"
diff --git a/editor/plugins/texture_region_editor_plugin.h b/editor/plugins/texture_region_editor_plugin.h
index a18c87f153..e3bbaf49fc 100644
--- a/editor/plugins/texture_region_editor_plugin.h
+++ b/editor/plugins/texture_region_editor_plugin.h
@@ -40,6 +40,7 @@
#include "scene/resources/texture.h"
class ViewPanner;
+class EditorUndoRedoManager;
class TextureRegionEditor : public AcceptDialog {
GDCLASS(TextureRegionEditor, AcceptDialog);
@@ -68,7 +69,7 @@ class TextureRegionEditor : public AcceptDialog {
VScrollBar *vscroll = nullptr;
HScrollBar *hscroll = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Vector2 draw_ofs;
float draw_zoom = 0.0;
diff --git a/editor/plugins/theme_editor_plugin.cpp b/editor/plugins/theme_editor_plugin.cpp
index bbc22c8622..af3959d47c 100644
--- a/editor/plugins/theme_editor_plugin.cpp
+++ b/editor/plugins/theme_editor_plugin.cpp
@@ -35,6 +35,7 @@
#include "editor/editor_node.h"
#include "editor/editor_resource_picker.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/progress_dialog.h"
#include "scene/gui/color_picker.h"
@@ -796,7 +797,7 @@ void ThemeItemImportTree::_import_selected() {
ProgressDialog::get_singleton()->end_task("import_theme_items");
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Import Theme Items"));
ur->add_do_method(*edited_theme, "clear");
@@ -1494,7 +1495,7 @@ void ThemeItemEditorDialog::_item_tree_button_pressed(Object *p_item, int p_colu
String item_name = item->get_text(0);
int data_type = item->get_parent()->get_metadata(0);
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Theme Item"));
ur->add_do_method(*edited_theme, "clear_theme_item", (Theme::DataType)data_type, item_name, edited_item_type);
ur->add_undo_method(*edited_theme, "set_theme_item", (Theme::DataType)data_type, item_name, edited_item_type, edited_theme->get_theme_item((Theme::DataType)data_type, item_name, edited_item_type));
@@ -1513,7 +1514,7 @@ void ThemeItemEditorDialog::_add_theme_type(const String &p_new_text) {
const String new_type = edit_add_type_value->get_text().strip_edges();
edit_add_type_value->clear();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Add Theme Type"));
ur->add_do_method(*edited_theme, "add_type", new_type);
@@ -1525,7 +1526,7 @@ void ThemeItemEditorDialog::_add_theme_type(const String &p_new_text) {
}
void ThemeItemEditorDialog::_add_theme_item(Theme::DataType p_data_type, String p_item_name, String p_item_type) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Create Theme Item"));
switch (p_data_type) {
@@ -1570,7 +1571,7 @@ void ThemeItemEditorDialog::_remove_theme_type(const String &p_theme_type) {
Ref<Theme> old_snapshot = edited_theme->duplicate();
Ref<Theme> new_snapshot = edited_theme->duplicate();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Theme Type"));
new_snapshot->remove_type(p_theme_type);
@@ -1593,7 +1594,7 @@ void ThemeItemEditorDialog::_remove_data_type_items(Theme::DataType p_data_type,
Ref<Theme> old_snapshot = edited_theme->duplicate();
Ref<Theme> new_snapshot = edited_theme->duplicate();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Data Type Items From Theme"));
new_snapshot->get_theme_item_list(p_data_type, p_item_type, &names);
@@ -1622,7 +1623,7 @@ void ThemeItemEditorDialog::_remove_class_items() {
Ref<Theme> old_snapshot = edited_theme->duplicate();
Ref<Theme> new_snapshot = edited_theme->duplicate();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Class Items From Theme"));
for (int dt = 0; dt < Theme::DATA_TYPE_MAX; dt++) {
@@ -1658,7 +1659,7 @@ void ThemeItemEditorDialog::_remove_custom_items() {
Ref<Theme> old_snapshot = edited_theme->duplicate();
Ref<Theme> new_snapshot = edited_theme->duplicate();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Custom Items From Theme"));
for (int dt = 0; dt < Theme::DATA_TYPE_MAX; dt++) {
@@ -1694,7 +1695,7 @@ void ThemeItemEditorDialog::_remove_all_items() {
Ref<Theme> old_snapshot = edited_theme->duplicate();
Ref<Theme> new_snapshot = edited_theme->duplicate();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove All Items From Theme"));
for (int dt = 0; dt < Theme::DATA_TYPE_MAX; dt++) {
@@ -1798,7 +1799,7 @@ void ThemeItemEditorDialog::_confirm_edit_theme_item() {
if (item_popup_mode == CREATE_THEME_ITEM) {
_add_theme_item(edit_item_data_type, theme_item_name->get_text(), edited_item_type);
} else if (item_popup_mode == RENAME_THEME_ITEM) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Rename Theme Item"));
ur->add_do_method(*edited_theme, "rename_theme_item", edit_item_data_type, edit_item_old_name, theme_item_name->get_text(), edited_item_type);
@@ -2824,7 +2825,7 @@ void ThemeTypeEditor::_add_default_type_items() {
updating = false;
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Override All Default Theme Items"));
ur->add_do_method(*edited_theme, "merge_with", new_snapshot);
@@ -2844,7 +2845,7 @@ void ThemeTypeEditor::_item_add_cbk(int p_data_type, Control *p_control) {
}
String item_name = le->get_text().strip_edges();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Add Theme Item"));
switch (p_data_type) {
@@ -2889,7 +2890,7 @@ void ThemeTypeEditor::_item_add_lineedit_cbk(String p_value, int p_data_type, Co
}
void ThemeTypeEditor::_item_override_cbk(int p_data_type, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Override Theme Item"));
switch (p_data_type) {
@@ -2928,7 +2929,7 @@ void ThemeTypeEditor::_item_override_cbk(int p_data_type, String p_item_name) {
}
void ThemeTypeEditor::_item_remove_cbk(int p_data_type, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Remove Theme Item"));
switch (p_data_type) {
@@ -3002,7 +3003,7 @@ void ThemeTypeEditor::_item_rename_confirmed(int p_data_type, String p_item_name
return;
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Rename Theme Item"));
switch (p_data_type) {
@@ -3058,7 +3059,7 @@ void ThemeTypeEditor::_item_rename_canceled(int p_data_type, String p_item_name,
}
void ThemeTypeEditor::_color_item_changed(Color p_value, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Color Item in Theme"), UndoRedo::MERGE_ENDS);
ur->add_do_method(*edited_theme, "set_color", p_item_name, edited_type, p_value);
ur->add_undo_method(*edited_theme, "set_color", p_item_name, edited_type, edited_theme->get_color(p_item_name, edited_type));
@@ -3066,7 +3067,7 @@ void ThemeTypeEditor::_color_item_changed(Color p_value, String p_item_name) {
}
void ThemeTypeEditor::_constant_item_changed(float p_value, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Constant Item in Theme"));
ur->add_do_method(*edited_theme, "set_constant", p_item_name, edited_type, p_value);
ur->add_undo_method(*edited_theme, "set_constant", p_item_name, edited_type, edited_theme->get_constant(p_item_name, edited_type));
@@ -3074,7 +3075,7 @@ void ThemeTypeEditor::_constant_item_changed(float p_value, String p_item_name)
}
void ThemeTypeEditor::_font_size_item_changed(float p_value, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Font Size Item in Theme"));
ur->add_do_method(*edited_theme, "set_font_size", p_item_name, edited_type, p_value);
ur->add_undo_method(*edited_theme, "set_font_size", p_item_name, edited_type, edited_theme->get_font_size(p_item_name, edited_type));
@@ -3086,7 +3087,7 @@ void ThemeTypeEditor::_edit_resource_item(Ref<Resource> p_resource, bool p_edit)
}
void ThemeTypeEditor::_font_item_changed(Ref<Font> p_value, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Font Item in Theme"));
ur->add_do_method(*edited_theme, "set_font", p_item_name, edited_type, p_value.is_valid() ? p_value : Ref<Font>());
@@ -3103,7 +3104,7 @@ void ThemeTypeEditor::_font_item_changed(Ref<Font> p_value, String p_item_name)
}
void ThemeTypeEditor::_icon_item_changed(Ref<Texture2D> p_value, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Icon Item in Theme"));
ur->add_do_method(*edited_theme, "set_icon", p_item_name, edited_type, p_value.is_valid() ? p_value : Ref<Texture2D>());
@@ -3120,7 +3121,7 @@ void ThemeTypeEditor::_icon_item_changed(Ref<Texture2D> p_value, String p_item_n
}
void ThemeTypeEditor::_stylebox_item_changed(Ref<StyleBox> p_value, String p_item_name) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Stylebox Item in Theme"));
ur->add_do_method(*edited_theme, "set_stylebox", p_item_name, edited_type, p_value.is_valid() ? p_value : Ref<StyleBox>());
@@ -3163,7 +3164,7 @@ void ThemeTypeEditor::_on_pin_leader_button_pressed(Control *p_editor, String p_
stylebox = Object::cast_to<EditorResourcePicker>(p_editor)->get_edited_resource();
}
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Pin Stylebox"));
ur->add_do_method(this, "_pin_leading_stylebox", p_item_name, stylebox);
@@ -3196,7 +3197,7 @@ void ThemeTypeEditor::_pin_leading_stylebox(String p_item_name, Ref<StyleBox> p_
}
void ThemeTypeEditor::_on_unpin_leader_button_pressed() {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Unpin Stylebox"));
ur->add_do_method(this, "_unpin_leading_stylebox");
ur->add_undo_method(this, "_pin_leading_stylebox", leading_stylebox.item_name, leading_stylebox.stylebox);
@@ -3265,7 +3266,7 @@ void ThemeTypeEditor::_update_stylebox_from_leading() {
}
void ThemeTypeEditor::_type_variation_changed(const String p_value) {
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Set Theme Type Variation"));
if (p_value.is_empty()) {
diff --git a/editor/plugins/tiles/atlas_merging_dialog.cpp b/editor/plugins/tiles/atlas_merging_dialog.cpp
index 3fe6778f48..de4f3f7989 100644
--- a/editor/plugins/tiles/atlas_merging_dialog.cpp
+++ b/editor/plugins/tiles/atlas_merging_dialog.cpp
@@ -33,6 +33,7 @@
#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/control.h"
#include "scene/gui/split_container.h"
diff --git a/editor/plugins/tiles/atlas_merging_dialog.h b/editor/plugins/tiles/atlas_merging_dialog.h
index c54e259594..c7e4635d16 100644
--- a/editor/plugins/tiles/atlas_merging_dialog.h
+++ b/editor/plugins/tiles/atlas_merging_dialog.h
@@ -38,6 +38,7 @@
#include "scene/resources/tile_set.h"
class EditorFileDialog;
+class EditorUndoRedoManager;
class AtlasMergingDialog : public ConfirmationDialog {
GDCLASS(AtlasMergingDialog, ConfirmationDialog);
@@ -49,7 +50,7 @@ private:
LocalVector<HashMap<Vector2i, Vector2i>> merged_mapping;
Ref<TileSet> tile_set;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
// Settings.
int next_line_after_column = 30;
diff --git a/editor/plugins/tiles/tile_atlas_view.cpp b/editor/plugins/tiles/tile_atlas_view.cpp
index f119ada810..54ba28833c 100644
--- a/editor/plugins/tiles/tile_atlas_view.cpp
+++ b/editor/plugins/tiles/tile_atlas_view.cpp
@@ -127,8 +127,8 @@ void TileAtlasView::_update_zoom_and_panning(bool p_zoom_on_mouse_pos) {
}
// Update the backgrounds.
- background_left->update();
- background_right->update();
+ background_left->set_size(base_tiles_root_control->get_custom_minimum_size());
+ background_right->set_size(alternative_tiles_root_control->get_custom_minimum_size());
// Zoom on the position.
if (p_zoom_on_mouse_pos) {
@@ -374,13 +374,11 @@ void TileAtlasView::_draw_alternatives() {
void TileAtlasView::_draw_background_left() {
Ref<Texture2D> texture = get_theme_icon(SNAME("Checkerboard"), SNAME("EditorIcons"));
- background_left->set_size(base_tiles_root_control->get_custom_minimum_size());
background_left->draw_texture_rect(texture, Rect2(Vector2(), background_left->get_size()), true);
}
void TileAtlasView::_draw_background_right() {
Ref<Texture2D> texture = get_theme_icon(SNAME("Checkerboard"), SNAME("EditorIcons"));
- background_right->set_size(alternative_tiles_root_control->get_custom_minimum_size());
background_right->draw_texture_rect(texture, Rect2(Vector2(), background_right->get_size()), true);
}
@@ -405,23 +403,6 @@ void TileAtlasView::set_atlas_source(TileSet *p_tile_set, TileSetAtlasSource *p_
// Update everything.
_update_zoom_and_panning();
- // Change children control size.
- Size2i base_tiles_control_size = _compute_base_tiles_control_size();
- for (int i = 0; i < base_tiles_drawing_root->get_child_count(); i++) {
- Control *control = Object::cast_to<Control>(base_tiles_drawing_root->get_child(i));
- if (control) {
- control->set_size(base_tiles_control_size);
- }
- }
-
- Size2i alternative_control_size = _compute_alternative_tiles_control_size();
- for (int i = 0; i < alternative_tiles_drawing_root->get_child_count(); i++) {
- Control *control = Object::cast_to<Control>(alternative_tiles_drawing_root->get_child(i));
- if (control) {
- control->set_size(alternative_control_size);
- }
- }
-
// Update.
base_tiles_draw->update();
base_tiles_texture_grid->update();
@@ -613,7 +594,7 @@ TileAtlasView::TileAtlasView() {
background_left = memnew(Control);
background_left->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
- background_left->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
+ background_left->set_anchors_and_offsets_preset(Control::PRESET_TOP_LEFT);
background_left->set_texture_repeat(TextureRepeat::TEXTURE_REPEAT_ENABLED);
background_left->connect("draw", callable_mp(this, &TileAtlasView::_draw_background_left));
base_tiles_root_control->add_child(background_left);
@@ -651,23 +632,26 @@ TileAtlasView::TileAtlasView() {
alternative_tiles_root_control = memnew(Control);
alternative_tiles_root_control->set_mouse_filter(Control::MOUSE_FILTER_PASS);
+ alternative_tiles_root_control->set_v_size_flags(Control::SIZE_EXPAND_FILL);
alternative_tiles_root_control->connect("gui_input", callable_mp(this, &TileAtlasView::_alternative_tiles_root_control_gui_input));
right_vbox->add_child(alternative_tiles_root_control);
background_right = memnew(Control);
background_right->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
+ background_right->set_anchors_and_offsets_preset(Control::PRESET_TOP_LEFT);
background_right->set_texture_repeat(TextureRepeat::TEXTURE_REPEAT_ENABLED);
background_right->connect("draw", callable_mp(this, &TileAtlasView::_draw_background_right));
-
alternative_tiles_root_control->add_child(background_right);
alternative_tiles_drawing_root = memnew(Control);
alternative_tiles_drawing_root->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
+ alternative_tiles_drawing_root->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
alternative_tiles_drawing_root->set_texture_filter(TEXTURE_FILTER_NEAREST);
alternative_tiles_root_control->add_child(alternative_tiles_drawing_root);
alternatives_draw = memnew(Control);
alternatives_draw->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
+ alternatives_draw->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
alternatives_draw->connect("draw", callable_mp(this, &TileAtlasView::_draw_alternatives));
alternative_tiles_drawing_root->add_child(alternatives_draw);
}
diff --git a/editor/plugins/tiles/tile_atlas_view.h b/editor/plugins/tiles/tile_atlas_view.h
index 196a642283..1c0b622bb1 100644
--- a/editor/plugins/tiles/tile_atlas_view.h
+++ b/editor/plugins/tiles/tile_atlas_view.h
@@ -136,6 +136,7 @@ public:
} else {
base_tiles_root_control->add_child(p_control);
}
+ p_control->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
p_control->set_mouse_filter(Control::MOUSE_FILTER_PASS);
};
@@ -149,6 +150,7 @@ public:
} else {
alternative_tiles_root_control->add_child(p_control);
}
+ p_control->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
p_control->set_mouse_filter(Control::MOUSE_FILTER_PASS);
};
diff --git a/editor/plugins/tiles/tile_data_editors.cpp b/editor/plugins/tiles/tile_data_editors.cpp
index a00e1ed9e8..b44b6fcc53 100644
--- a/editor/plugins/tiles/tile_data_editors.cpp
+++ b/editor/plugins/tiles/tile_data_editors.cpp
@@ -38,6 +38,7 @@
#include "editor/editor_node.h"
#include "editor/editor_properties.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
void TileDataEditor::_tile_set_changed_plan_update() {
_tile_set_changed_update_needed = true;
@@ -248,7 +249,14 @@ void GenericTilePolygonEditor::_zoom_changed() {
}
void GenericTilePolygonEditor::_advanced_menu_item_pressed(int p_item_pressed) {
- UndoRedo *undo_redo = use_undo_redo ? editor_undo_redo : memnew(UndoRedo);
+ Ref<EditorUndoRedoManager> undo_redo;
+ if (use_undo_redo) {
+ undo_redo = editor_undo_redo;
+ } else {
+ // This nice hack allows for discarding undo actions without making code too complex.
+ undo_redo.instantiate();
+ }
+
switch (p_item_pressed) {
case RESET_TO_DEFAULT_TILE: {
undo_redo->create_action(TTR("Reset Polygons"));
@@ -322,9 +330,6 @@ void GenericTilePolygonEditor::_advanced_menu_item_pressed(int p_item_pressed) {
default:
break;
}
- if (!use_undo_redo) {
- memdelete(undo_redo);
- }
}
void GenericTilePolygonEditor::_grab_polygon_point(Vector2 p_pos, const Transform2D &p_polygon_xform, int &r_polygon_index, int &r_point_index) {
@@ -409,7 +414,14 @@ void GenericTilePolygonEditor::_snap_to_half_pixel(Point2 &r_point) {
}
void GenericTilePolygonEditor::_base_control_gui_input(Ref<InputEvent> p_event) {
- UndoRedo *undo_redo = use_undo_redo ? editor_undo_redo : memnew(UndoRedo);
+ Ref<EditorUndoRedoManager> undo_redo;
+ if (use_undo_redo) {
+ undo_redo = editor_undo_redo;
+ } else {
+ // This nice hack allows for discarding undo actions without making code too complex.
+ undo_redo.instantiate();
+ }
+
real_t grab_threshold = EDITOR_GET("editors/polygon_editor/point_grab_radius");
hovered_polygon_index = -1;
@@ -600,10 +612,6 @@ void GenericTilePolygonEditor::_base_control_gui_input(Ref<InputEvent> p_event)
}
base_control->update();
-
- if (!use_undo_redo) {
- memdelete(undo_redo);
- }
}
void GenericTilePolygonEditor::set_use_undo_redo(bool p_use_undo_redo) {
diff --git a/editor/plugins/tiles/tile_data_editors.h b/editor/plugins/tiles/tile_data_editors.h
index f9b8948d0a..c1560138b2 100644
--- a/editor/plugins/tiles/tile_data_editors.h
+++ b/editor/plugins/tiles/tile_data_editors.h
@@ -39,6 +39,8 @@
#include "scene/gui/control.h"
#include "scene/gui/label.h"
+class EditorUndoRedoManager;
+
class TileDataEditor : public VBoxContainer {
GDCLASS(TileDataEditor, VBoxContainer);
@@ -93,7 +95,7 @@ private:
bool multiple_polygon_mode = false;
bool use_undo_redo = true;
- UndoRedo *editor_undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> editor_undo_redo;
// UI
int hovered_polygon_index = -1;
@@ -214,7 +216,7 @@ private:
protected:
DummyObject *dummy_object = memnew(DummyObject);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
StringName type;
String property;
@@ -279,7 +281,7 @@ private:
virtual void _setup_undo_redo_action(TileSetAtlasSource *p_tile_set_atlas_source, HashMap<TileMapCell, Variant, TileMapCell> p_previous_values, Variant p_new_value) override;
protected:
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
virtual void _tile_set_changed() override;
@@ -314,7 +316,7 @@ class TileDataCollisionEditor : public TileDataDefaultEditor {
virtual void _setup_undo_redo_action(TileSetAtlasSource *p_tile_set_atlas_source, HashMap<TileMapCell, Variant, TileMapCell> p_previous_values, Variant p_new_value) override;
protected:
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
virtual void _tile_set_changed() override;
@@ -366,7 +368,7 @@ protected:
void _notification(int p_what);
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
public:
virtual Control *get_toolbar() override { return toolbar; };
@@ -399,7 +401,7 @@ private:
virtual void _setup_undo_redo_action(TileSetAtlasSource *p_tile_set_atlas_source, HashMap<TileMapCell, Variant, TileMapCell> p_previous_values, Variant p_new_value) override;
protected:
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
virtual void _tile_set_changed() override;
diff --git a/editor/plugins/tiles/tile_map_editor.cpp b/editor/plugins/tiles/tile_map_editor.cpp
index 1bf24a7393..3f355a1ed2 100644
--- a/editor/plugins/tiles/tile_map_editor.cpp
+++ b/editor/plugins/tiles/tile_map_editor.cpp
@@ -35,6 +35,7 @@
#include "editor/editor_node.h"
#include "editor/editor_resource_preview.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/canvas_item_editor_plugin.h"
#include "scene/2d/camera_2d.h"
@@ -3697,8 +3698,8 @@ void TileMapEditor::_update_layers_selection() {
}
void TileMapEditor::_move_tile_map_array_element(Object *p_undo_redo, Object *p_edited, String p_array_prefix, int p_from_index, int p_to_pos) {
- UndoRedo *undo_redo = Object::cast_to<UndoRedo>(p_undo_redo);
- ERR_FAIL_COND(!undo_redo);
+ Ref<EditorUndoRedoManager> undo_redo = Object::cast_to<EditorUndoRedoManager>(p_undo_redo);
+ ERR_FAIL_COND(undo_redo.is_null());
TileMap *tile_map = Object::cast_to<TileMap>(p_edited);
if (!tile_map) {
diff --git a/editor/plugins/tiles/tile_map_editor.h b/editor/plugins/tiles/tile_map_editor.h
index 605fbe4823..9a47d8bbc4 100644
--- a/editor/plugins/tiles/tile_map_editor.h
+++ b/editor/plugins/tiles/tile_map_editor.h
@@ -47,7 +47,7 @@
#include "scene/gui/tab_bar.h"
#include "scene/gui/tree.h"
-class UndoRedo;
+class EditorUndoRedoManager;
class TileMapEditorPlugin : public Object {
public:
@@ -70,7 +70,7 @@ class TileMapEditorTilesPlugin : public TileMapEditorPlugin {
GDCLASS(TileMapEditorTilesPlugin, TileMapEditorPlugin);
private:
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
ObjectID tile_map_id;
int tile_map_layer = -1;
virtual void edit(ObjectID p_tile_map_id, int p_tile_map_layer) override;
@@ -223,7 +223,7 @@ class TileMapEditorTerrainsPlugin : public TileMapEditorPlugin {
GDCLASS(TileMapEditorTerrainsPlugin, TileMapEditorPlugin);
private:
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
ObjectID tile_map_id;
int tile_map_layer = -1;
virtual void edit(ObjectID p_tile_map_id, int p_tile_map_layer) override;
@@ -317,7 +317,7 @@ class TileMapEditor : public VBoxContainer {
GDCLASS(TileMapEditor, VBoxContainer);
private:
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
bool tileset_changed_needs_update = false;
ObjectID tile_map_id;
int tile_map_layer = -1;
diff --git a/editor/plugins/tiles/tile_proxies_manager_dialog.cpp b/editor/plugins/tiles/tile_proxies_manager_dialog.cpp
index 12e1615484..9e4c29fa79 100644
--- a/editor/plugins/tiles/tile_proxies_manager_dialog.cpp
+++ b/editor/plugins/tiles/tile_proxies_manager_dialog.cpp
@@ -32,6 +32,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
void TileProxiesManagerDialog::_right_clicked(int p_item, Vector2 p_local_mouse_pos, Object *p_item_list, MouseButton p_mouse_button_index) {
if (p_mouse_button_index != MouseButton::RIGHT) {
diff --git a/editor/plugins/tiles/tile_proxies_manager_dialog.h b/editor/plugins/tiles/tile_proxies_manager_dialog.h
index 44de708898..511e442a10 100644
--- a/editor/plugins/tiles/tile_proxies_manager_dialog.h
+++ b/editor/plugins/tiles/tile_proxies_manager_dialog.h
@@ -43,7 +43,7 @@ private:
int commited_actions_count = 0;
Ref<TileSet> tile_set;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
TileMapCell from;
TileMapCell to;
diff --git a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp
index 6950f57a00..2c1fad45d9 100644
--- a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp
+++ b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp
@@ -2058,14 +2058,16 @@ void TileSetAtlasSourceEditor::_atlas_source_proxy_object_changed(String p_what)
}
void TileSetAtlasSourceEditor::_undo_redo_inspector_callback(Object *p_undo_redo, Object *p_edited, String p_property, Variant p_new_value) {
- UndoRedo *undo_redo = Object::cast_to<UndoRedo>(p_undo_redo);
- ERR_FAIL_COND(!undo_redo);
+ Ref<EditorUndoRedoManager> undo_redo = Object::cast_to<EditorUndoRedoManager>(p_undo_redo);
+ ERR_FAIL_COND(!undo_redo.is_valid());
#define ADD_UNDO(obj, property) undo_redo->add_undo_property(obj, property, obj->get(property));
- undo_redo->start_force_keep_in_merge_ends();
AtlasTileProxyObject *tile_data_proxy = Object::cast_to<AtlasTileProxyObject>(p_edited);
if (tile_data_proxy) {
+ UndoRedo *internal_undo_redo = undo_redo->get_history_for_object(tile_data_proxy).undo_redo;
+ internal_undo_redo->start_force_keep_in_merge_ends();
+
Vector<String> components = String(p_property).split("/", true, 2);
if (components.size() == 2 && components[1] == "polygons_count") {
int layer_index = components[0].trim_prefix("physics_layer_").to_int();
@@ -2088,6 +2090,7 @@ void TileSetAtlasSourceEditor::_undo_redo_inspector_callback(Object *p_undo_redo
}
}
}
+ internal_undo_redo->end_force_keep_in_merge_ends();
}
TileSetAtlasSourceProxyObject *atlas_source_proxy = Object::cast_to<TileSetAtlasSourceProxyObject>(p_edited);
@@ -2095,6 +2098,9 @@ void TileSetAtlasSourceEditor::_undo_redo_inspector_callback(Object *p_undo_redo
TileSetAtlasSource *atlas_source = atlas_source_proxy->get_edited();
ERR_FAIL_COND(!atlas_source);
+ UndoRedo *internal_undo_redo = undo_redo->get_history_for_object(atlas_source).undo_redo;
+ internal_undo_redo->start_force_keep_in_merge_ends();
+
PackedVector2Array arr;
if (p_property == "texture") {
arr = atlas_source->get_tiles_to_be_removed_on_change(p_new_value, atlas_source->get_margins(), atlas_source->get_separation(), atlas_source->get_texture_region_size());
@@ -2121,8 +2127,8 @@ void TileSetAtlasSourceEditor::_undo_redo_inspector_callback(Object *p_undo_redo
}
}
}
+ internal_undo_redo->end_force_keep_in_merge_ends();
}
- undo_redo->end_force_keep_in_merge_ends();
#undef ADD_UNDO
}
@@ -2518,7 +2524,6 @@ TileSetAtlasSourceEditor::TileSetAtlasSourceEditor() {
tile_atlas_view->add_control_over_atlas_tiles(tile_atlas_control);
tile_atlas_control_unscaled = memnew(Control);
- tile_atlas_control_unscaled->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
tile_atlas_control_unscaled->connect("draw", callable_mp(this, &TileSetAtlasSourceEditor::_tile_atlas_control_unscaled_draw));
tile_atlas_view->add_control_over_atlas_tiles(tile_atlas_control_unscaled, false);
tile_atlas_control_unscaled->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
@@ -2535,7 +2540,6 @@ TileSetAtlasSourceEditor::TileSetAtlasSourceEditor() {
tile_atlas_view->add_control_over_alternative_tiles(alternative_tiles_control);
alternative_tiles_control_unscaled = memnew(Control);
- alternative_tiles_control_unscaled->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
alternative_tiles_control_unscaled->connect("draw", callable_mp(this, &TileSetAtlasSourceEditor::_tile_alternatives_control_unscaled_draw));
tile_atlas_view->add_control_over_alternative_tiles(alternative_tiles_control_unscaled, false);
alternative_tiles_control_unscaled->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
diff --git a/editor/plugins/tiles/tile_set_atlas_source_editor.h b/editor/plugins/tiles/tile_set_atlas_source_editor.h
index 738fe1044d..badb702e29 100644
--- a/editor/plugins/tiles/tile_set_atlas_source_editor.h
+++ b/editor/plugins/tiles/tile_set_atlas_source_editor.h
@@ -114,7 +114,7 @@ private:
TileSetAtlasSource *tile_set_atlas_source = nullptr;
int tile_set_atlas_source_id = TileSet::INVALID_SOURCE;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
bool tile_set_changed_needs_update = false;
diff --git a/editor/plugins/tiles/tile_set_editor.cpp b/editor/plugins/tiles/tile_set_editor.cpp
index 81804710b4..8d04dd3121 100644
--- a/editor/plugins/tiles/tile_set_editor.cpp
+++ b/editor/plugins/tiles/tile_set_editor.cpp
@@ -36,6 +36,7 @@
#include "editor/editor_file_system.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/gui/box_container.h"
#include "scene/gui/control.h"
@@ -405,8 +406,8 @@ void TileSetEditor::_tab_changed(int p_tab_changed) {
}
void TileSetEditor::_move_tile_set_array_element(Object *p_undo_redo, Object *p_edited, String p_array_prefix, int p_from_index, int p_to_pos) {
- UndoRedo *undo_redo = Object::cast_to<UndoRedo>(p_undo_redo);
- ERR_FAIL_COND(!undo_redo);
+ Ref<EditorUndoRedoManager> undo_redo = Object::cast_to<EditorUndoRedoManager>(p_undo_redo);
+ ERR_FAIL_COND(undo_redo.is_null());
TileSet *tile_set = Object::cast_to<TileSet>(p_edited);
if (!tile_set) {
@@ -586,8 +587,8 @@ void TileSetEditor::_move_tile_set_array_element(Object *p_undo_redo, Object *p_
}
void TileSetEditor::_undo_redo_inspector_callback(Object *p_undo_redo, Object *p_edited, String p_property, Variant p_new_value) {
- UndoRedo *undo_redo = Object::cast_to<UndoRedo>(p_undo_redo);
- ERR_FAIL_COND(!undo_redo);
+ Ref<EditorUndoRedoManager> undo_redo = Object::cast_to<EditorUndoRedoManager>(p_undo_redo);
+ ERR_FAIL_COND(undo_redo.is_null());
#define ADD_UNDO(obj, property) undo_redo->add_undo_property(obj, property, obj->get(property));
TileSet *tile_set = Object::cast_to<TileSet>(p_edited);
diff --git a/editor/plugins/tiles/tile_set_editor.h b/editor/plugins/tiles/tile_set_editor.h
index c45240043e..3b9b80dac4 100644
--- a/editor/plugins/tiles/tile_set_editor.h
+++ b/editor/plugins/tiles/tile_set_editor.h
@@ -39,6 +39,8 @@
#include "tile_set_atlas_source_editor.h"
#include "tile_set_scenes_collection_source_editor.h"
+class EditorUndoRedoManager;
+
class TileSetEditor : public VBoxContainer {
GDCLASS(TileSetEditor, VBoxContainer);
@@ -58,7 +60,7 @@ private:
TileSetAtlasSourceEditor *tile_set_atlas_source_editor = nullptr;
TileSetScenesCollectionSourceEditor *tile_set_scenes_collection_source_editor = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void _drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
bool _can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
diff --git a/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h b/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h
index 77a583e522..0284b45c0f 100644
--- a/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h
+++ b/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h
@@ -97,7 +97,7 @@ private:
TileSetScenesCollectionSource *tile_set_scenes_collection_source = nullptr;
int tile_set_source_id = -1;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
bool tile_set_scenes_collection_source_changed_needs_update = false;
diff --git a/editor/plugins/version_control_editor_plugin.cpp b/editor/plugins/version_control_editor_plugin.cpp
index cf55465417..6db499f2c7 100644
--- a/editor/plugins/version_control_editor_plugin.cpp
+++ b/editor/plugins/version_control_editor_plugin.cpp
@@ -242,7 +242,7 @@ void VersionControlEditorPlugin::_view_file_diff() {
}
void VersionControlEditorPlugin::_display_file_diff(String p_file_path) {
- Array diff_content = EditorVCSInterface::get_singleton()->get_file_diff(p_file_path);
+ TypedArray<Dictionary> diff_content = EditorVCSInterface::get_singleton()->get_file_diff(p_file_path);
diff_file_name->set_text(p_file_path);
diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp
index 4a144bc391..e048ee2698 100644
--- a/editor/plugins/visual_shader_editor_plugin.cpp
+++ b/editor/plugins/visual_shader_editor_plugin.cpp
@@ -40,6 +40,7 @@
#include "editor/editor_node.h"
#include "editor/editor_properties.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/curve_editor_plugin.h"
#include "editor/plugins/shader_editor_plugin.h"
#include "scene/animation/animation_player.h"
@@ -4063,7 +4064,7 @@ void VisualShaderEditor::_input_select_item(Ref<VisualShaderNodeInput> p_input,
bool type_changed = next_input_type != prev_input_type;
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Visual Shader Input Type Changed"));
undo_redo->add_do_method(p_input.ptr(), "set_input_name", p_name);
@@ -4132,7 +4133,7 @@ void VisualShaderEditor::_uniform_select_item(Ref<VisualShaderNodeUniformRef> p_
bool type_changed = p_uniform_ref->get_uniform_type_by_name(p_name) != p_uniform_ref->get_uniform_type_by_name(prev_name);
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("UniformRef Name Changed"));
undo_redo->add_do_method(p_uniform_ref.ptr(), "set_uniform_name", p_name);
@@ -4176,7 +4177,7 @@ void VisualShaderEditor::_varying_select_item(Ref<VisualShaderNodeVarying> p_var
bool is_getter = Ref<VisualShaderNodeVaryingGetter>(p_varying.ptr()).is_valid();
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Varying Name Changed"));
undo_redo->add_do_method(p_varying.ptr(), "set_varying_name", p_name);
@@ -4311,6 +4312,9 @@ void VisualShaderEditor::_update_varying_tree() {
case VisualShader::VARYING_TYPE_FLOAT:
item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("float"), SNAME("EditorIcons")));
break;
+ case VisualShader::VARYING_TYPE_INT:
+ item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("int"), SNAME("EditorIcons")));
+ break;
case VisualShader::VARYING_TYPE_VECTOR_2D:
item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Vector2"), SNAME("EditorIcons")));
break;
@@ -4320,8 +4324,8 @@ void VisualShaderEditor::_update_varying_tree() {
case VisualShader::VARYING_TYPE_VECTOR_4D:
item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Vector4"), SNAME("EditorIcons")));
break;
- case VisualShader::VARYING_TYPE_COLOR:
- item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Color"), SNAME("EditorIcons")));
+ case VisualShader::VARYING_TYPE_BOOLEAN:
+ item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("bool"), SNAME("EditorIcons")));
break;
case VisualShader::VARYING_TYPE_TRANSFORM:
item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Transform3D"), SNAME("EditorIcons")));
@@ -4962,10 +4966,11 @@ VisualShaderEditor::VisualShaderEditor() {
varying_type = memnew(OptionButton);
hb->add_child(varying_type);
varying_type->add_item("Float");
+ varying_type->add_item("Int");
varying_type->add_item("Vector2");
varying_type->add_item("Vector3");
varying_type->add_item("Vector4");
- varying_type->add_item("Color");
+ varying_type->add_item("Boolean");
varying_type->add_item("Transform");
varying_name = memnew(LineEdit);
@@ -5668,7 +5673,7 @@ VisualShaderEditor::VisualShaderEditor() {
_update_options_menu();
- undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ undo_redo = EditorNode::get_undo_redo();
Ref<VisualShaderNodePluginDefault> default_plugin;
default_plugin.instantiate();
@@ -5758,10 +5763,11 @@ public:
Ref<Texture2D> type_icon[] = {
EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("float"), SNAME("EditorIcons")),
+ EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("int"), SNAME("EditorIcons")),
EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Vector2"), SNAME("EditorIcons")),
EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Vector3"), SNAME("EditorIcons")),
EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Vector4"), SNAME("EditorIcons")),
- EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Color"), SNAME("EditorIcons")),
+ EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("bool"), SNAME("EditorIcons")),
EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Transform3D"), SNAME("EditorIcons")),
};
@@ -5876,7 +5882,7 @@ public:
return;
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
updating = true;
undo_redo->create_action(TTR("Edit Visual Property:") + " " + p_property, UndoRedo::MERGE_ENDS);
@@ -6063,7 +6069,7 @@ Control *VisualShaderNodePluginDefault::create_editor(const Ref<Resource> &p_par
return editor;
}
-void EditorPropertyShaderMode::_option_selected(int p_which) {
+void EditorPropertyVisualShaderMode::_option_selected(int p_which) {
Ref<VisualShader> visual_shader(Object::cast_to<VisualShader>(get_edited_object()));
if (visual_shader->get_mode() == p_which) {
return;
@@ -6078,7 +6084,7 @@ void EditorPropertyShaderMode::_option_selected(int p_which) {
return;
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Visual Shader Mode Changed"));
//do is easy
undo_redo->add_do_method(visual_shader.ptr(), "set_mode", p_which);
@@ -6149,39 +6155,39 @@ void EditorPropertyShaderMode::_option_selected(int p_which) {
undo_redo->commit_action();
}
-void EditorPropertyShaderMode::update_property() {
+void EditorPropertyVisualShaderMode::update_property() {
int which = get_edited_object()->get(get_edited_property());
options->select(which);
}
-void EditorPropertyShaderMode::setup(const Vector<String> &p_options) {
+void EditorPropertyVisualShaderMode::setup(const Vector<String> &p_options) {
for (int i = 0; i < p_options.size(); i++) {
options->add_item(p_options[i], i);
}
}
-void EditorPropertyShaderMode::set_option_button_clip(bool p_enable) {
+void EditorPropertyVisualShaderMode::set_option_button_clip(bool p_enable) {
options->set_clip_text(p_enable);
}
-void EditorPropertyShaderMode::_bind_methods() {
+void EditorPropertyVisualShaderMode::_bind_methods() {
}
-EditorPropertyShaderMode::EditorPropertyShaderMode() {
+EditorPropertyVisualShaderMode::EditorPropertyVisualShaderMode() {
options = memnew(OptionButton);
options->set_clip_text(true);
add_child(options);
add_focusable(options);
- options->connect("item_selected", callable_mp(this, &EditorPropertyShaderMode::_option_selected));
+ options->connect("item_selected", callable_mp(this, &EditorPropertyVisualShaderMode::_option_selected));
}
-bool EditorInspectorShaderModePlugin::can_handle(Object *p_object) {
+bool EditorInspectorVisualShaderModePlugin::can_handle(Object *p_object) {
return true; // Can handle everything.
}
-bool EditorInspectorShaderModePlugin::parse_property(Object *p_object, const Variant::Type p_type, const String &p_path, const PropertyHint p_hint, const String &p_hint_text, const uint32_t p_usage, const bool p_wide) {
+bool EditorInspectorVisualShaderModePlugin::parse_property(Object *p_object, const Variant::Type p_type, const String &p_path, const PropertyHint p_hint, const String &p_hint_text, const uint32_t p_usage, const bool p_wide) {
if (p_path == "mode" && p_object->is_class("VisualShader") && p_type == Variant::INT) {
- EditorPropertyShaderMode *mode_editor = memnew(EditorPropertyShaderMode);
+ EditorPropertyVisualShaderMode *mode_editor = memnew(EditorPropertyVisualShaderMode);
Vector<String> options = p_hint_text.split(",");
mode_editor->setup(options);
add_property_editor(p_path, mode_editor);
diff --git a/editor/plugins/visual_shader_editor_plugin.h b/editor/plugins/visual_shader_editor_plugin.h
index b846c34f9e..ede6513b83 100644
--- a/editor/plugins/visual_shader_editor_plugin.h
+++ b/editor/plugins/visual_shader_editor_plugin.h
@@ -48,6 +48,7 @@ class TextEdit;
class Tree;
class VisualShaderEditor;
+class EditorUndoRedoManager;
class VisualShaderNodePlugin : public RefCounted {
GDCLASS(VisualShaderNodePlugin, RefCounted);
@@ -192,7 +193,7 @@ class VisualShaderEditor : public VBoxContainer {
PanelContainer *error_panel = nullptr;
Label *error_label = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
Point2 saved_node_pos;
bool saved_node_pos_dirty = false;
@@ -529,8 +530,8 @@ public:
virtual Control *create_editor(const Ref<Resource> &p_parent_resource, const Ref<VisualShaderNode> &p_node) override;
};
-class EditorPropertyShaderMode : public EditorProperty {
- GDCLASS(EditorPropertyShaderMode, EditorProperty);
+class EditorPropertyVisualShaderMode : public EditorProperty {
+ GDCLASS(EditorPropertyVisualShaderMode, EditorProperty);
OptionButton *options = nullptr;
void _option_selected(int p_which);
@@ -542,11 +543,11 @@ public:
void setup(const Vector<String> &p_options);
virtual void update_property() override;
void set_option_button_clip(bool p_enable);
- EditorPropertyShaderMode();
+ EditorPropertyVisualShaderMode();
};
-class EditorInspectorShaderModePlugin : public EditorInspectorPlugin {
- GDCLASS(EditorInspectorShaderModePlugin, EditorInspectorPlugin);
+class EditorInspectorVisualShaderModePlugin : public EditorInspectorPlugin {
+ GDCLASS(EditorInspectorVisualShaderModePlugin, EditorInspectorPlugin);
public:
virtual bool can_handle(Object *p_object) override;
diff --git a/editor/project_converter_3_to_4.cpp b/editor/project_converter_3_to_4.cpp
index 5ce837f862..9e3062d3bc 100644
--- a/editor/project_converter_3_to_4.cpp
+++ b/editor/project_converter_3_to_4.cpp
@@ -206,6 +206,7 @@ static const char *gdscript_function_renames[][2] = {
// { "set_margin", "set_offset" }, // Control broke Shape3D, AtlasTexture
// { "set_mode", "set_mode_file_mode" }, // FileDialog broke Panel, Shader, CSGPolygon, Tilemap
// { "set_normal", "surface_set_normal"}, // ImmediateGeometry broke SurfaceTool, WorldMarginShape2D
+ // { "set_offset", "set_progress" }, // PathFollow2D, PathFollow3D - Too common
// { "set_process_mode", "set_process_callback" }, // AnimationTree broke Node, Tween, Sky
// { "set_refuse_new_network_connections", "set_refuse_new_connections"}, // MultiplayerAPI broke SceneTree
// { "set_uv", "surface_set_uv" }, // ImmediateMesh broke Polygon2D
@@ -371,6 +372,7 @@ static const char *gdscript_function_renames[][2] = {
{ "get_theme_item_types", "get_theme_item_type_list" }, // Theme
{ "get_timer_process_mode", "get_timer_process_callback" }, // Timer
{ "get_translation", "get_position" }, // Node3D broke GLTFNode which is used rarely
+ { "get_unit_offset", "get_progress_ratio" }, // PathFollow2D, PathFollow3D
{ "get_use_in_baked_light", "is_baking_navigation" }, // GridMap
{ "get_used_cells_by_id", "get_used_cells" }, // TileMap
{ "get_v_scrollbar", "get_v_scroll_bar" }, //ScrollContainer
@@ -532,6 +534,7 @@ static const char *gdscript_function_renames[][2] = {
{ "set_timer_process_mode", "set_timer_process_callback" }, // Timer
{ "set_tonemap_auto_exposure", "set_tonemap_auto_exposure_enabled" }, // Environment
{ "set_translation", "set_position" }, // Node3D - this broke GLTFNode which is used rarely
+ { "set_unit_offset", "set_progress_ratio" }, // PathFollow2D, PathFollow3D
{ "set_uv2", "surface_set_uv2" }, // ImmediateMesh broke Surffacetool
{ "set_v_drag_enabled", "set_drag_vertical_enabled" }, // Camera2D
{ "set_valign", "set_vertical_alignment" }, // Label
@@ -612,6 +615,7 @@ static const char *csharp_function_renames[][2] = {
// { "SetMargin", "SetOffset" }, // Control broke Shape3D, AtlasTexture
// { "SetMode", "SetModeFileMode" }, // FileDialog broke Panel, Shader, CSGPolygon, Tilemap
// { "SetNormal", "SurfaceSetNormal"}, // ImmediateGeometry broke SurfaceTool, WorldMarginShape2D
+ // { "SetOffset", "SetProgress" }, // PathFollow2D, PathFollow3D - Too common
// { "SetProcessMode", "SetProcessCallback" }, // AnimationTree broke Node, Tween, Sky
// { "SetRefuseNewNetworkConnections", "SetRefuseNewConnections"}, // MultiplayerAPI broke SceneTree
// { "SetUv", "SurfaceSetUv" }, // ImmediateMesh broke Polygon2D
@@ -767,6 +771,7 @@ static const char *csharp_function_renames[][2] = {
{ "GetThemeItemTypes", "GetThemeItemTypeList" }, // Theme
{ "GetTimerProcessMode", "GetTimerProcessCallback" }, // Timer
{ "GetTranslation", "GetPosition" }, // Node3D broke GLTFNode which is used rarely
+ { "GetUnitOffset", "GetProgressRatio" }, // PathFollow2D, PathFollow3D
{ "GetUseInBakedLight", "IsBakingNavigation" }, // GridMap
{ "GetUsedCellsById", "GetUsedCells" }, // TileMap
{ "GetVScrollbar", "GetVScrollBar" }, //ScrollContainer
@@ -918,6 +923,7 @@ static const char *csharp_function_renames[][2] = {
{ "SetTimerProcessMode", "SetTimerProcessCallback" }, // Timer
{ "SetTonemapAutoExposure", "SetTonemapAutoExposureEnabled" }, // Environment
{ "SetTranslation", "SetPosition" }, // Node3D - this broke GLTFNode which is used rarely
+ { "SetUnitOffset", "SetProgressRatio" }, // PathFollow2D, PathFollow3D
{ "SetUv2", "SurfaceSetUv2" }, // ImmediateMesh broke Surffacetool
{ "SetVDragEnabled", "SetDragVerticalEnabled" }, // Camera2D
{ "SetValign", "SetVerticalAlignment" }, // Label
@@ -969,6 +975,7 @@ static const char *gdscript_properties_renames[][2] = {
// // {"meta","meta_pressed"},// This may broke a lot of comments and user variables
// // {"pause_mode","process_mode"}, // Node - Cyclic rename, look for others
// // {"rotate","rotates"}, // PathFollow2D - probably function exists with same name
+ // // {"offset","progress"}, // PathFollow2D, PathFollow3D - Name is way too vague
// // {"shift","shift_pressed"},// This may broke a lot of comments and user variables
// { "autowrap", "autowrap_mode" }, // Label
// { "cast_to", "target_position" }, // RayCast2D, RayCast3D
@@ -990,6 +997,7 @@ static const char *gdscript_properties_renames[][2] = {
{ "close_h_ofs", "close_h_offset" }, // Theme
{ "close_v_ofs", "close_v_offset" }, // Theme
{ "commentfocus", "comment_focus" }, // Theme
+ { "contacts_reported", "max_contacts_reported" }, // RigidDynamicBody
{ "drag_margin_bottom", "drag_bottom_margin" }, // Camera2D
{ "drag_margin_h_enabled", "drag_horizontal_enabled" }, // Camera2D
{ "drag_margin_left", "drag_left_margin" }, // Camera2D
@@ -1008,6 +1016,7 @@ static const char *gdscript_properties_renames[][2] = {
{ "gravity_vec", "gravity_direction" }, // Area2D
{ "hseparation", "h_separation" }, // Theme
{ "iterations_per_second", "physics_ticks_per_second" }, // Engine
+ { "invert_enable", "invert_enabled" }, // Polygon2D
{ "margin_bottom", "offset_bottom" }, // Control broke NinePatchRect, StyleBox
{ "margin_left", "offset_left" }, // Control broke NinePatchRect, StyleBox
{ "margin_right", "offset_right" }, // Control broke NinePatchRect, StyleBox
@@ -1036,6 +1045,7 @@ static const char *gdscript_properties_renames[][2] = {
{ "table_hseparation", "table_h_separation" }, // Theme
{ "table_vseparation", "table_v_separation" }, // Theme
{ "translation", "position" }, // Node3D - broke GLTFNode
+ { "unit_offset", "progress_ratio" }, // PathFollow2D, PathFollow3D
{ "vseparation", "v_separation" }, // Theme
{ nullptr, nullptr },
@@ -1051,6 +1061,7 @@ static const char *csharp_properties_renames[][2] = {
// // {"Meta","MetaPressed"},// This may broke a lot of comments and user variables
// // {"PauseMode","ProcessMode"}, // Node - Cyclic rename, look for others
// // {"Rotate","Rotates"}, // PathFollow2D - probably function exists with same name
+ // // {"Offset","Progress"}, // PathFollow2D, PathFollow3D - Name is way too vague
// // {"Shift","ShiftPressed"},// This may broke a lot of comments and user variables
// { "Autowrap", "AutowrapMode" }, // Label
// { "CastTo", "TargetPosition" }, // RayCast2D, RayCast3D
@@ -1089,6 +1100,7 @@ static const char *csharp_properties_renames[][2] = {
{ "GravityVec", "GravityDirection" }, // Area2D
{ "Hseparation", "HSeparation" }, // Theme
{ "IterationsPerSecond", "PhysicsTicksPerSecond" }, // Engine
+ { "InvertEnable", "InvertEnabled" }, // Polygon2D
{ "MarginBottom", "OffsetBottom" }, // Control broke NinePatchRect, StyleBox
{ "MarginLeft", "OffsetLeft" }, // Control broke NinePatchRect, StyleBox
{ "MarginRight", "OffsetRight" }, // Control broke NinePatchRect, StyleBox
@@ -1117,6 +1129,7 @@ static const char *csharp_properties_renames[][2] = {
{ "TableHseparation", "TableHSeparation" }, // Theme
{ "TableVseparation", "TableVSeparation" }, // Theme
{ "Translation", "Position" }, // Node3D - broke GLTFNode
+ { "UnitOffset", "ProgressRatio" }, // PathFollow2D, PathFollow3D
{ "Vseparation", "VSeparation" }, // Theme
{ nullptr, nullptr },
@@ -1362,6 +1375,8 @@ static const char *class_renames[][2] = {
{ "PinJoint", "PinJoint3D" },
{ "PlaneShape", "WorldBoundaryShape3D" },
{ "PopupDialog", "Popup" },
+ { "Position2D", "Marker2D" },
+ { "Position3D", "Marker3D" },
{ "ProceduralSky", "Sky" },
{ "RayCast", "RayCast3D" },
{ "RayShape", "SeparationRayShape3D" },
@@ -1381,7 +1396,6 @@ static const char *class_renames[][2] = {
{ "Spatial", "Node3D" },
{ "SpatialGizmo", "Node3DGizmo" },
{ "SpatialMaterial", "StandardMaterial3D" },
- { "SpatialVelocityTracker", "VelocityTracker3D" },
{ "SphereShape", "SphereShape3D" },
{ "SpotLight", "SpotLight3D" },
{ "SpringArm", "SpringArm3D" },
@@ -1607,8 +1621,8 @@ public:
RegEx reg_is_empty = RegEx("\\bempty\\(");
RegEx reg_super = RegEx("([\t ])\\.([a-zA-Z_])");
RegEx reg_json_to = RegEx("\\bto_json\\b");
- RegEx reg_json_parse = RegEx("([\t]{0,})([^\n]+)parse_json\\(([^\n]+)");
- RegEx reg_json_non_new = RegEx("([\t]{0,})([^\n]+)JSON\\.parse\\(([^\n]+)");
+ RegEx reg_json_parse = RegEx("([\t ]{0,})([^\n]+)parse_json\\(([^\n]+)");
+ RegEx reg_json_non_new = RegEx("([\t ]{0,})([^\n]+)JSON\\.parse\\(([^\n]+)");
RegEx reg_export = RegEx("export\\(([a-zA-Z0-9_]+)\\)[ ]+var[ ]+([a-zA-Z0-9_]+)");
RegEx reg_export_advanced = RegEx("export\\(([^)^\n]+)\\)[ ]+var[ ]+([a-zA-Z0-9_]+)([^\n]+)");
RegEx reg_setget_setget = RegEx("var[ ]+([a-zA-Z0-9_]+)([^\n]+)setget[ \t]+([a-zA-Z0-9_]+)[ \t]*,[ \t]*([a-zA-Z0-9_]+)");
@@ -2103,6 +2117,8 @@ bool ProjectConverter3To4::test_conversion(const RegExContainer &reg_container)
valid = valid & test_conversion_single_additional_builtin("(connect(A,B,C) != OK):", "(connect(A,Callable(B,C)) != OK):", &ProjectConverter3To4::rename_gdscript_functions, "custom rename", reg_container, false);
valid = valid & test_conversion_single_additional_builtin("(connect(A,B,C,D) != OK):", "(connect(A,Callable(B,C).bind(D)) != OK):", &ProjectConverter3To4::rename_gdscript_functions, "custom rename", reg_container, false);
valid = valid & test_conversion_single_additional_builtin("(connect(A,B,C,[D]) != OK):", "(connect(A,Callable(B,C).bind(D)) != OK):", &ProjectConverter3To4::rename_gdscript_functions, "custom rename", reg_container, false);
+ valid = valid & test_conversion_single_additional_builtin("(connect(A,B,C,[D,E]) != OK):", "(connect(A,Callable(B,C).bind(D,E)) != OK):", &ProjectConverter3To4::rename_gdscript_functions, "custom rename", reg_container, false);
+ valid = valid & test_conversion_single_additional_builtin("(connect(A,B,C,[D,E],F) != OK):", "(connect(A,Callable(B,C).bind(D,E),F) != OK):", &ProjectConverter3To4::rename_gdscript_functions, "custom rename", reg_container, false);
valid = valid & test_conversion_single_additional_builtin("(connect(A,B,C,D,E) != OK):", "(connect(A,Callable(B,C).bind(D),E) != OK):", &ProjectConverter3To4::rename_gdscript_functions, "custom rename", reg_container, false);
valid = valid & test_conversion_single_additional_builtin("(start(A,B) != OK):", "(start(Callable(A,B)) != OK):", &ProjectConverter3To4::rename_gdscript_functions, "custom rename", reg_container, false);
@@ -2442,6 +2458,21 @@ Vector<String> ProjectConverter3To4::parse_arguments(const String &line) {
}
break;
};
+ case '[': {
+ parts_counter++;
+ if (parts_counter == 1 && !is_inside_string) {
+ start_part = current_index;
+ }
+ break;
+ };
+ case ']': {
+ parts_counter--;
+ if (parts_counter == 0 && !is_inside_string) {
+ parts.append(line.substr(start_part, current_index - start_part));
+ start_part = current_index;
+ }
+ break;
+ };
case ',': {
if (parts_counter == 1 && !is_inside_string) {
parts.append(line.substr(start_part + 1, current_index - start_part - 1));
diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp
index 21891e381b..cce71d9508 100644
--- a/editor/project_manager.cpp
+++ b/editor/project_manager.cpp
@@ -47,6 +47,7 @@
#include "editor/editor_settings.h"
#include "editor/editor_themes.h"
#include "editor/editor_vcs_interface.h"
+#include "main/main.h"
#include "scene/gui/center_container.h"
#include "scene/gui/line_edit.h"
#include "scene/gui/margin_container.h"
@@ -483,12 +484,20 @@ private:
project_features.sort();
initial_settings["application/config/features"] = project_features;
initial_settings["application/config/name"] = project_name->get_text().strip_edges();
- initial_settings["application/config/icon"] = "res://icon.png";
+ initial_settings["application/config/icon"] = "res://icon.svg";
if (ProjectSettings::get_singleton()->save_custom(dir.plus_file("project.godot"), initial_settings, Vector<String>(), false) != OK) {
set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR);
} else {
- ResourceSaver::save(create_unscaled_default_project_icon(), dir.plus_file("icon.png"));
+ // Store default project icon in SVG format.
+ Error err;
+ Ref<FileAccess> fa_icon = FileAccess::open(dir.plus_file("icon.svg"), FileAccess::WRITE, &err);
+ fa_icon->store_string(get_default_project_icon());
+
+ if (err != OK) {
+ set_message(TTR("Couldn't create icon.svg in project path."), MESSAGE_ERROR);
+ }
+
EditorVCSInterface::create_vcs_metadata_files(EditorVCSInterface::VCSMetadata(vcs_metadata_selection->get_selected()), dir);
}
} else if (mode == MODE_INSTALL) {
@@ -1164,6 +1173,12 @@ void ProjectList::load_project_icon(int p_index) {
icon = default_icon;
}
+ // The default project icon is 128×128 to look crisp on hiDPI displays,
+ // but we want the actual displayed size to be 64×64 on loDPI displays.
+ item.control->icon->set_ignore_texture_size(true);
+ item.control->icon->set_custom_minimum_size(Size2(64, 64) * EDSCALE);
+ item.control->icon->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
+
item.control->icon->set_texture(icon);
item.control->icon_needs_reload = false;
}
@@ -2109,27 +2124,15 @@ void ProjectManager::_open_selected_projects() {
List<String> args;
+ for (const String &a : Main::get_forwardable_cli_arguments(Main::CLI_SCOPE_TOOL)) {
+ args.push_back(a);
+ }
+
args.push_back("--path");
args.push_back(path);
args.push_back("--editor");
- if (OS::get_singleton()->is_stdout_debug_enabled()) {
- args.push_back("--debug");
- }
-
- if (OS::get_singleton()->is_stdout_verbose()) {
- args.push_back("--verbose");
- }
-
- if (OS::get_singleton()->is_disable_crash_handler()) {
- args.push_back("--disable-crash-handler");
- }
-
- if (OS::get_singleton()->is_single_window()) {
- args.push_back("--single-window");
- }
-
Error err = OS::get_singleton()->create_instance(args);
ERR_FAIL_COND(err);
}
@@ -2242,13 +2245,13 @@ void ProjectManager::_run_project_confirm() {
List<String> args;
+ for (const String &a : Main::get_forwardable_cli_arguments(Main::CLI_SCOPE_PROJECT)) {
+ args.push_back(a);
+ }
+
args.push_back("--path");
args.push_back(path);
- if (OS::get_singleton()->is_disable_crash_handler()) {
- args.push_back("--disable-crash-handler");
- }
-
Error err = OS::get_singleton()->create_instance(args);
ERR_FAIL_COND(err);
}
diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp
index ca5eeaa787..581315d512 100644
--- a/editor/project_settings_editor.cpp
+++ b/editor/project_settings_editor.cpp
@@ -35,6 +35,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "servers/movie_writer/movie_writer.h"
ProjectSettingsEditor *ProjectSettingsEditor::singleton = nullptr;
@@ -566,7 +567,7 @@ ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) {
set_title(TTR("Project Settings (project.godot)"));
ps = ProjectSettings::get_singleton();
- undo_redo = &p_data->get_undo_redo();
+ undo_redo = p_data->get_undo_redo();
data = p_data;
tab_container = memnew(TabContainer);
@@ -625,7 +626,7 @@ ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) {
custom_properties->add_child(del_button);
general_settings_inspector = memnew(SectionedInspector);
- general_settings_inspector->get_inspector()->set_undo_redo(EditorNode::get_singleton()->get_undo_redo());
+ general_settings_inspector->get_inspector()->set_undo_redo(EditorNode::get_undo_redo());
general_settings_inspector->set_v_size_flags(Control::SIZE_EXPAND_FILL);
general_settings_inspector->register_search_box(search_box);
general_settings_inspector->get_inspector()->set_use_filter(true);
diff --git a/editor/project_settings_editor.h b/editor/project_settings_editor.h
index c2d2c2d8f4..040d992e40 100644
--- a/editor/project_settings_editor.h
+++ b/editor/project_settings_editor.h
@@ -32,7 +32,6 @@
#define PROJECT_SETTINGS_EDITOR_H
#include "core/config/project_settings.h"
-#include "core/object/undo_redo.h"
#include "editor/action_map_editor.h"
#include "editor/editor_autoload_settings.h"
#include "editor/editor_data.h"
@@ -43,6 +42,7 @@
#include "editor/shader_globals_editor.h"
#include "scene/gui/tab_container.h"
+class EditorUndoRedoManager;
class FileSystemDock;
class ProjectSettingsEditor : public AcceptDialog {
@@ -77,7 +77,7 @@ class ProjectSettingsEditor : public AcceptDialog {
ImportDefaultsEditor *import_defaults_editor = nullptr;
EditorData *data = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
void _advanced_toggled(bool p_button_pressed);
void _update_advanced(bool p_is_advanced);
diff --git a/editor/rename_dialog.cpp b/editor/rename_dialog.cpp
index 665aca6a37..84923a94a2 100644
--- a/editor/rename_dialog.cpp
+++ b/editor/rename_dialog.cpp
@@ -38,6 +38,7 @@
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
#include "editor/editor_themes.h"
+#include "editor/editor_undo_redo_manager.h"
#include "modules/regex/regex.h"
#include "plugins/script_editor_plugin.h"
#include "scene/gui/control.h"
@@ -45,7 +46,7 @@
#include "scene/gui/separator.h"
#include "scene/gui/tab_container.h"
-RenameDialog::RenameDialog(SceneTreeEditor *p_scene_tree_editor, UndoRedo *p_undo_redo) {
+RenameDialog::RenameDialog(SceneTreeEditor *p_scene_tree_editor, Ref<EditorUndoRedoManager> p_undo_redo) {
scene_tree_editor = p_scene_tree_editor;
undo_redo = p_undo_redo;
preview_node = nullptr;
@@ -581,7 +582,7 @@ void RenameDialog::rename() {
// Forward recursive as opposed to the actual renaming.
_iterate_scene(root_node, selected_node_list, &global_count);
- if (undo_redo && !to_rename.is_empty()) {
+ if (undo_redo.is_valid() && !to_rename.is_empty()) {
undo_redo->create_action(TTR("Batch Rename"));
// Make sure to iterate reversed so that child nodes will find parents.
diff --git a/editor/rename_dialog.h b/editor/rename_dialog.h
index f3a850045e..dac73b13b8 100644
--- a/editor/rename_dialog.h
+++ b/editor/rename_dialog.h
@@ -34,7 +34,6 @@
#include "modules/modules_enabled.gen.h" // For regex.
#ifdef MODULE_REGEX_ENABLED
-#include "core/object/undo_redo.h"
#include "editor/scene_tree_editor.h"
#include "scene/gui/check_box.h"
#include "scene/gui/check_button.h"
@@ -43,6 +42,8 @@
#include "scene/gui/spin_box.h"
#include "scene/gui/tab_container.h"
+class EditorUndoRedoManager;
+
class RenameDialog : public ConfirmationDialog {
GDCLASS(RenameDialog, ConfirmationDialog);
@@ -63,7 +64,7 @@ class RenameDialog : public ConfirmationDialog {
static void _error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, bool p_editor_notify, ErrorHandlerType p_type);
SceneTreeEditor *scene_tree_editor = nullptr;
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
int global_count = 0;
LineEdit *lne_search = nullptr;
@@ -109,7 +110,7 @@ public:
void reset();
void rename();
- RenameDialog(SceneTreeEditor *p_scene_tree_editor, UndoRedo *p_undo_redo = nullptr);
+ RenameDialog(SceneTreeEditor *p_scene_tree_editor, Ref<EditorUndoRedoManager> p_undo_redo = Ref<EditorUndoRedoManager>());
~RenameDialog() {}
};
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index d19a40599f..9f80119c35 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -222,28 +222,28 @@ void SceneTreeDock::_perform_instantiate_scenes(const Vector<String> &p_files, N
return;
}
- editor_data->get_undo_redo().create_action(TTR("Instance Scene(s)"));
+ editor_data->get_undo_redo()->create_action(TTR("Instance Scene(s)"));
for (int i = 0; i < instances.size(); i++) {
Node *instantiated_scene = instances[i];
- editor_data->get_undo_redo().add_do_method(parent, "add_child", instantiated_scene, true);
+ editor_data->get_undo_redo()->add_do_method(parent, "add_child", instantiated_scene, true);
if (p_pos >= 0) {
- editor_data->get_undo_redo().add_do_method(parent, "move_child", instantiated_scene, p_pos + i);
+ editor_data->get_undo_redo()->add_do_method(parent, "move_child", instantiated_scene, p_pos + i);
}
- editor_data->get_undo_redo().add_do_method(instantiated_scene, "set_owner", edited_scene);
- editor_data->get_undo_redo().add_do_method(editor_selection, "clear");
- editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", instantiated_scene);
- editor_data->get_undo_redo().add_do_reference(instantiated_scene);
- editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instantiated_scene);
+ editor_data->get_undo_redo()->add_do_method(instantiated_scene, "set_owner", edited_scene);
+ editor_data->get_undo_redo()->add_do_method(editor_selection, "clear");
+ editor_data->get_undo_redo()->add_do_method(editor_selection, "add_node", instantiated_scene);
+ editor_data->get_undo_redo()->add_do_reference(instantiated_scene);
+ editor_data->get_undo_redo()->add_undo_method(parent, "remove_child", instantiated_scene);
String new_name = parent->validate_child_name(instantiated_scene);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_instance_node", edited_scene->get_path_to(parent), p_files[i], new_name);
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)).plus_file(new_name)));
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_instance_node", edited_scene->get_path_to(parent), p_files[i], new_name);
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)).plus_file(new_name)));
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
_push_item(instances[instances.size() - 1]);
for (int i = 0; i < instances.size(); i++) {
emit_signal(SNAME("node_created"), instances[i]);
@@ -265,7 +265,7 @@ void SceneTreeDock::_replace_with_branch_scene(const String &p_file, Node *base)
return;
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Replace with Branch Scene"));
Node *parent = base->get_parent();
@@ -510,9 +510,8 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
if (selected) {
- create_dialog->popup_create(false, true, selected->get_class());
+ create_dialog->popup_create(false, true, selected->get_class(), selected->get_name());
}
-
} break;
case TOOL_EXTEND_SCRIPT: {
attach_script_to_selected(true);
@@ -531,23 +530,23 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
return;
}
- editor_data->get_undo_redo().create_action(TTR("Detach Script"));
- editor_data->get_undo_redo().add_do_method(EditorNode::get_singleton(), "push_item", (Script *)nullptr);
+ editor_data->get_undo_redo()->create_action(TTR("Detach Script"), UndoRedo::MERGE_DISABLE, EditorNode::get_singleton()->get_edited_scene());
+ editor_data->get_undo_redo()->add_do_method(EditorNode::get_singleton(), "push_item", (Script *)nullptr);
for (int i = 0; i < selection.size(); i++) {
Node *n = Object::cast_to<Node>(selection[i]);
Ref<Script> existing = n->get_script();
Ref<Script> empty = EditorNode::get_singleton()->get_object_custom_type_base(n);
if (existing != empty) {
- editor_data->get_undo_redo().add_do_method(n, "set_script", empty);
- editor_data->get_undo_redo().add_undo_method(n, "set_script", existing);
+ editor_data->get_undo_redo()->add_do_method(n, "set_script", empty);
+ editor_data->get_undo_redo()->add_undo_method(n, "set_script", existing);
}
}
- editor_data->get_undo_redo().add_do_method(this, "_update_script_button");
- editor_data->get_undo_redo().add_undo_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->add_do_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->add_undo_method(this, "_update_script_button");
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
} break;
case TOOL_MOVE_UP:
case TOOL_MOVE_DOWN: {
@@ -602,10 +601,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
if (selection.size() == 1) {
- editor_data->get_undo_redo().create_action(TTR("Move Node In Parent"));
+ editor_data->get_undo_redo()->create_action(TTR("Move Node In Parent"));
}
if (selection.size() > 1) {
- editor_data->get_undo_redo().create_action(TTR("Move Nodes In Parent"));
+ editor_data->get_undo_redo()->create_action(TTR("Move Nodes In Parent"));
}
for (int i = 0; i < selection.size(); i++) {
@@ -618,11 +617,11 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
int bottom_node_pos = bottom_node->get_index();
int top_node_pos_next = top_node->get_index() + (MOVING_DOWN ? 1 : -1);
- editor_data->get_undo_redo().add_do_method(top_node->get_parent(), "move_child", top_node, top_node_pos_next);
- editor_data->get_undo_redo().add_undo_method(bottom_node->get_parent(), "move_child", bottom_node, bottom_node_pos);
+ editor_data->get_undo_redo()->add_do_method(top_node->get_parent(), "move_child", top_node, top_node_pos_next);
+ editor_data->get_undo_redo()->add_undo_method(bottom_node->get_parent(), "move_child", bottom_node, bottom_node_pos);
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
} break;
case TOOL_DUPLICATE: {
@@ -650,8 +649,8 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
break;
}
- editor_data->get_undo_redo().create_action(TTR("Duplicate Node(s)"));
- editor_data->get_undo_redo().add_do_method(editor_selection, "clear");
+ editor_data->get_undo_redo()->create_action(TTR("Duplicate Node(s)"), UndoRedo::MERGE_DISABLE, selection.front()->get());
+ editor_data->get_undo_redo()->add_do_method(editor_selection, "clear");
Node *dupsingle = nullptr;
@@ -676,28 +675,28 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
dup->set_name(parent->validate_child_name(dup));
- editor_data->get_undo_redo().add_do_method(add_below_node, "add_sibling", dup, true);
+ editor_data->get_undo_redo()->add_do_method(add_below_node, "add_sibling", dup, true);
for (Node *F : owned) {
if (!duplimap.has(F)) {
continue;
}
Node *d = duplimap[F];
- editor_data->get_undo_redo().add_do_method(d, "set_owner", node->get_owner());
+ editor_data->get_undo_redo()->add_do_method(d, "set_owner", node->get_owner());
}
- editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", dup);
- editor_data->get_undo_redo().add_undo_method(parent, "remove_child", dup);
- editor_data->get_undo_redo().add_do_reference(dup);
+ editor_data->get_undo_redo()->add_do_method(editor_selection, "add_node", dup);
+ editor_data->get_undo_redo()->add_undo_method(parent, "remove_child", dup);
+ editor_data->get_undo_redo()->add_do_reference(dup);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_duplicate_node", edited_scene->get_path_to(node), dup->get_name());
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)).plus_file(dup->get_name())));
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_duplicate_node", edited_scene->get_path_to(node), dup->get_name());
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)).plus_file(dup->get_name())));
add_below_node = dup;
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
if (dupsingle) {
_push_item(dupsingle);
@@ -766,29 +765,29 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
return;
}
- editor_data->get_undo_redo().create_action(TTR("Make node as Root"));
- editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node);
- editor_data->get_undo_redo().add_do_method(EditorNode::get_singleton(), "set_edited_scene", node);
- editor_data->get_undo_redo().add_do_method(node, "add_child", root, true);
- editor_data->get_undo_redo().add_do_method(node, "set_scene_file_path", root->get_scene_file_path());
- editor_data->get_undo_redo().add_do_method(root, "set_scene_file_path", String());
- editor_data->get_undo_redo().add_do_method(node, "set_owner", (Object *)nullptr);
- editor_data->get_undo_redo().add_do_method(root, "set_owner", node);
+ editor_data->get_undo_redo()->create_action(TTR("Make node as Root"));
+ editor_data->get_undo_redo()->add_do_method(node->get_parent(), "remove_child", node);
+ editor_data->get_undo_redo()->add_do_method(EditorNode::get_singleton(), "set_edited_scene", node);
+ editor_data->get_undo_redo()->add_do_method(node, "add_child", root, true);
+ editor_data->get_undo_redo()->add_do_method(node, "set_scene_file_path", root->get_scene_file_path());
+ editor_data->get_undo_redo()->add_do_method(root, "set_scene_file_path", String());
+ editor_data->get_undo_redo()->add_do_method(node, "set_owner", (Object *)nullptr);
+ editor_data->get_undo_redo()->add_do_method(root, "set_owner", node);
_node_replace_owner(root, root, node, MODE_DO);
- editor_data->get_undo_redo().add_undo_method(root, "set_scene_file_path", root->get_scene_file_path());
- editor_data->get_undo_redo().add_undo_method(node, "set_scene_file_path", String());
- editor_data->get_undo_redo().add_undo_method(node, "remove_child", root);
- editor_data->get_undo_redo().add_undo_method(EditorNode::get_singleton(), "set_edited_scene", root);
- editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node, true);
- editor_data->get_undo_redo().add_undo_method(node->get_parent(), "move_child", node, node->get_index());
- editor_data->get_undo_redo().add_undo_method(root, "set_owner", (Object *)nullptr);
- editor_data->get_undo_redo().add_undo_method(node, "set_owner", root);
+ editor_data->get_undo_redo()->add_undo_method(root, "set_scene_file_path", root->get_scene_file_path());
+ editor_data->get_undo_redo()->add_undo_method(node, "set_scene_file_path", String());
+ editor_data->get_undo_redo()->add_undo_method(node, "remove_child", root);
+ editor_data->get_undo_redo()->add_undo_method(EditorNode::get_singleton(), "set_edited_scene", root);
+ editor_data->get_undo_redo()->add_undo_method(node->get_parent(), "add_child", node, true);
+ editor_data->get_undo_redo()->add_undo_method(node->get_parent(), "move_child", node, node->get_index());
+ editor_data->get_undo_redo()->add_undo_method(root, "set_owner", (Object *)nullptr);
+ editor_data->get_undo_redo()->add_undo_method(node, "set_owner", root);
_node_replace_owner(root, root, root, MODE_UNDO);
- editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree");
- editor_data->get_undo_redo().add_undo_method(scene_tree, "update_tree");
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->add_do_method(scene_tree, "update_tree");
+ editor_data->get_undo_redo()->add_undo_method(scene_tree, "update_tree");
+ editor_data->get_undo_redo()->commit_action();
} break;
case TOOL_MULTI_EDIT: {
if (!profile_allow_editing) {
@@ -1009,7 +1008,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
Node *node = e->get();
if (node) {
Node *root = EditorNode::get_singleton()->get_edited_scene();
- UndoRedo *undo_redo = &editor_data->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = editor_data->get_undo_redo();
if (!root) {
break;
}
@@ -1072,7 +1071,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
- UndoRedo *undo_redo = &editor_data->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = editor_data->get_undo_redo();
Node *node = e->get();
bool enabled = node->is_unique_name_in_owner();
if (!enabled && get_tree()->get_edited_scene_root()->get_node_or_null(UNIQUE_NODE_PREFIX + String(node->get_name())) != nullptr) {
@@ -1161,19 +1160,19 @@ void SceneTreeDock::_property_selected(int p_idx) {
}
void SceneTreeDock::_perform_property_drop(Node *p_node, String p_property, Ref<Resource> p_res) {
- editor_data->get_undo_redo().create_action(vformat(TTR("Set %s"), p_property));
- editor_data->get_undo_redo().add_do_property(p_node, p_property, p_res);
- editor_data->get_undo_redo().add_undo_property(p_node, p_property, p_node->get(p_property));
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->create_action(vformat(TTR("Set %s"), p_property));
+ editor_data->get_undo_redo()->add_do_property(p_node, p_property, p_res);
+ editor_data->get_undo_redo()->add_undo_property(p_node, p_property, p_node->get(p_property));
+ editor_data->get_undo_redo()->commit_action();
}
void SceneTreeDock::add_root_node(Node *p_node) {
- editor_data->get_undo_redo().create_action(TTR("New Scene Root"));
- editor_data->get_undo_redo().add_do_method(EditorNode::get_singleton(), "set_edited_scene", p_node);
- editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree");
- editor_data->get_undo_redo().add_do_reference(p_node);
- editor_data->get_undo_redo().add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->create_action_for_history(TTR("New Scene Root"), editor_data->get_current_edited_scene_history_id());
+ editor_data->get_undo_redo()->add_do_method(EditorNode::get_singleton(), "set_edited_scene", p_node);
+ editor_data->get_undo_redo()->add_do_method(scene_tree, "update_tree");
+ editor_data->get_undo_redo()->add_do_reference(p_node);
+ editor_data->get_undo_redo()->add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
+ editor_data->get_undo_redo()->commit_action();
}
void SceneTreeDock::_node_collapsed(Object *p_obj) {
@@ -1335,7 +1334,7 @@ void SceneTreeDock::_notification(int p_what) {
void SceneTreeDock::_node_replace_owner(Node *p_base, Node *p_node, Node *p_root, ReplaceOwnerMode p_mode) {
if (p_node->get_owner() == p_base && p_node != p_root) {
- UndoRedo *undo_redo = &editor_data->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = editor_data->get_undo_redo();
switch (p_mode) {
case MODE_BIDI: {
bool disable_unique = p_node->is_unique_name_in_owner() && p_root->get_node_or_null(UNIQUE_NODE_PREFIX + String(p_node->get_name())) != nullptr;
@@ -1568,8 +1567,8 @@ void SceneTreeDock::perform_node_renames(Node *p_base, HashMap<Node *, NodePath>
Variant old_variant = p_base->get(propertyname);
Variant updated_variant = old_variant;
if (_check_node_path_recursive(p_base, updated_variant, p_renames)) {
- editor_data->get_undo_redo().add_do_property(p_base, propertyname, updated_variant);
- editor_data->get_undo_redo().add_undo_property(p_base, propertyname, old_variant);
+ editor_data->get_undo_redo()->add_do_property(p_base, propertyname, updated_variant);
+ editor_data->get_undo_redo()->add_undo_property(p_base, propertyname, old_variant);
p_base->set(propertyname, updated_variant);
}
}
@@ -1627,12 +1626,12 @@ void SceneTreeDock::perform_node_renames(Node *p_base, HashMap<Node *, NodePath>
ERR_FAIL_COND(!EI); //another bug
}
- editor_data->get_undo_redo().add_do_method(anim.ptr(), "remove_track", idx);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(), "add_track", anim->track_get_type(i), idx);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", idx, track_np);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_interpolation_type", idx, anim->track_get_interpolation_type(i));
+ editor_data->get_undo_redo()->add_do_method(anim.ptr(), "remove_track", idx);
+ editor_data->get_undo_redo()->add_undo_method(anim.ptr(), "add_track", anim->track_get_type(i), idx);
+ editor_data->get_undo_redo()->add_undo_method(anim.ptr(), "track_set_path", idx, track_np);
+ editor_data->get_undo_redo()->add_undo_method(anim.ptr(), "track_set_interpolation_type", idx, anim->track_get_interpolation_type(i));
for (int j = 0; j < anim->track_get_key_count(i); j++) {
- editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_insert_key", idx, anim->track_get_key_time(i, j), anim->track_get_key_value(i, j), anim->track_get_key_transition(i, j));
+ editor_data->get_undo_redo()->add_undo_method(anim.ptr(), "track_insert_key", idx, anim->track_get_key_time(i, j), anim->track_get_key_value(i, j), anim->track_get_key_transition(i, j));
}
ran.erase(i); //byebye channel
@@ -1645,8 +1644,8 @@ void SceneTreeDock::perform_node_renames(Node *p_base, HashMap<Node *, NodePath>
if (new_path == track_np) {
continue; //bleh
}
- editor_data->get_undo_redo().add_do_method(anim.ptr(), "track_set_path", i, new_path);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", i, track_np);
+ editor_data->get_undo_redo()->add_do_method(anim.ptr(), "track_set_path", i, new_path);
+ editor_data->get_undo_redo()->add_undo_method(anim.ptr(), "track_set_path", i, track_np);
}
}
}
@@ -1780,7 +1779,7 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V
// Sort by tree order, so re-adding is easy.
p_nodes.sort_custom<Node::Comparator>();
- editor_data->get_undo_redo().create_action(TTR("Reparent Node"));
+ editor_data->get_undo_redo()->create_action(TTR("Reparent Node"));
HashMap<Node *, NodePath> path_renames;
Vector<StringName> former_names;
@@ -1805,11 +1804,11 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V
inc--; // If the child will generate a gap when moved, adjust.
}
- editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node);
- editor_data->get_undo_redo().add_do_method(new_parent, "add_child", node, true);
+ editor_data->get_undo_redo()->add_do_method(node->get_parent(), "remove_child", node);
+ editor_data->get_undo_redo()->add_do_method(new_parent, "add_child", node, true);
if (p_position_in_parent >= 0) {
- editor_data->get_undo_redo().add_do_method(new_parent, "move_child", node, p_position_in_parent + inc);
+ editor_data->get_undo_redo()->add_do_method(new_parent, "move_child", node, p_position_in_parent + inc);
}
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
@@ -1839,29 +1838,29 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V
}
}
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, p_position_in_parent + inc);
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_reparent_node", NodePath(String(edited_scene->get_path_to(new_parent)).plus_file(new_name)), edited_scene->get_path_to(node->get_parent()), node->get_name(), node->get_index());
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, p_position_in_parent + inc);
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_reparent_node", NodePath(String(edited_scene->get_path_to(new_parent)).plus_file(new_name)), edited_scene->get_path_to(node->get_parent()), node->get_name(), node->get_index());
if (p_keep_global_xform) {
if (Object::cast_to<Node2D>(node)) {
- editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Node2D>(node)->get_global_transform());
+ editor_data->get_undo_redo()->add_do_method(node, "set_global_transform", Object::cast_to<Node2D>(node)->get_global_transform());
}
if (Object::cast_to<Node3D>(node)) {
- editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Node3D>(node)->get_global_transform());
+ editor_data->get_undo_redo()->add_do_method(node, "set_global_transform", Object::cast_to<Node3D>(node)->get_global_transform());
}
if (Object::cast_to<Control>(node)) {
- editor_data->get_undo_redo().add_do_method(node, "set_global_position", Object::cast_to<Control>(node)->get_global_position());
+ editor_data->get_undo_redo()->add_do_method(node, "set_global_position", Object::cast_to<Control>(node)->get_global_position());
}
}
- editor_data->get_undo_redo().add_do_method(this, "_set_owners", edited_scene, owners);
+ editor_data->get_undo_redo()->add_do_method(this, "_set_owners", edited_scene, owners);
if (AnimationPlayerEditor::get_singleton()->get_track_editor()->get_root() == node) {
- editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::get_singleton()->get_track_editor(), "set_root", node);
+ editor_data->get_undo_redo()->add_do_method(AnimationPlayerEditor::get_singleton()->get_track_editor(), "set_root", node);
}
- editor_data->get_undo_redo().add_undo_method(new_parent, "remove_child", node);
- editor_data->get_undo_redo().add_undo_method(node, "set_name", former_names[ni]);
+ editor_data->get_undo_redo()->add_undo_method(new_parent, "remove_child", node);
+ editor_data->get_undo_redo()->add_undo_method(node, "set_name", former_names[ni]);
inc++;
}
@@ -1879,29 +1878,29 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V
int child_pos = node->get_index();
- editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node, true);
- editor_data->get_undo_redo().add_undo_method(node->get_parent(), "move_child", node, child_pos);
- editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners);
+ editor_data->get_undo_redo()->add_undo_method(node->get_parent(), "add_child", node, true);
+ editor_data->get_undo_redo()->add_undo_method(node->get_parent(), "move_child", node, child_pos);
+ editor_data->get_undo_redo()->add_undo_method(this, "_set_owners", edited_scene, owners);
if (AnimationPlayerEditor::get_singleton()->get_track_editor()->get_root() == node) {
- editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::get_singleton()->get_track_editor(), "set_root", node);
+ editor_data->get_undo_redo()->add_undo_method(AnimationPlayerEditor::get_singleton()->get_track_editor(), "set_root", node);
}
if (p_keep_global_xform) {
if (Object::cast_to<Node2D>(node)) {
- editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Node2D>(node)->get_transform());
+ editor_data->get_undo_redo()->add_undo_method(node, "set_transform", Object::cast_to<Node2D>(node)->get_transform());
}
if (Object::cast_to<Node3D>(node)) {
- editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Node3D>(node)->get_transform());
+ editor_data->get_undo_redo()->add_undo_method(node, "set_transform", Object::cast_to<Node3D>(node)->get_transform());
}
if (Object::cast_to<Control>(node)) {
- editor_data->get_undo_redo().add_undo_method(node, "set_position", Object::cast_to<Control>(node)->get_position());
+ editor_data->get_undo_redo()->add_undo_method(node, "set_position", Object::cast_to<Control>(node)->get_position());
}
}
}
perform_node_renames(nullptr, &path_renames);
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
}
bool SceneTreeDock::_is_collapsed_recursive(TreeItem *p_item) const {
@@ -1957,30 +1956,30 @@ void SceneTreeDock::_script_created(Ref<Script> p_script) {
Node *node = selected.front()->get();
Ref<Script> existing = node->get_script();
- editor_data->get_undo_redo().create_action(TTR("Attach Script"));
- editor_data->get_undo_redo().add_do_method(InspectorDock::get_singleton(), "store_script_properties", node);
- editor_data->get_undo_redo().add_undo_method(InspectorDock::get_singleton(), "store_script_properties", node);
- editor_data->get_undo_redo().add_do_method(node, "set_script", p_script);
- editor_data->get_undo_redo().add_undo_method(node, "set_script", existing);
- editor_data->get_undo_redo().add_do_method(InspectorDock::get_singleton(), "apply_script_properties", node);
- editor_data->get_undo_redo().add_undo_method(InspectorDock::get_singleton(), "apply_script_properties", node);
- editor_data->get_undo_redo().add_do_method(this, "_update_script_button");
- editor_data->get_undo_redo().add_undo_method(this, "_update_script_button");
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->create_action(TTR("Attach Script"));
+ editor_data->get_undo_redo()->add_do_method(InspectorDock::get_singleton(), "store_script_properties", node);
+ editor_data->get_undo_redo()->add_undo_method(InspectorDock::get_singleton(), "store_script_properties", node);
+ editor_data->get_undo_redo()->add_do_method(node, "set_script", p_script);
+ editor_data->get_undo_redo()->add_undo_method(node, "set_script", existing);
+ editor_data->get_undo_redo()->add_do_method(InspectorDock::get_singleton(), "apply_script_properties", node);
+ editor_data->get_undo_redo()->add_undo_method(InspectorDock::get_singleton(), "apply_script_properties", node);
+ editor_data->get_undo_redo()->add_do_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->add_undo_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->commit_action();
} else {
- editor_data->get_undo_redo().create_action(TTR("Attach Script"));
- for (List<Node *>::Element *E = selected.front(); E; E = E->next()) {
- Ref<Script> existing = E->get()->get_script();
- editor_data->get_undo_redo().add_do_method(InspectorDock::get_singleton(), "store_script_properties", E->get());
- editor_data->get_undo_redo().add_undo_method(InspectorDock::get_singleton(), "store_script_properties", E->get());
- editor_data->get_undo_redo().add_do_method(E->get(), "set_script", p_script);
- editor_data->get_undo_redo().add_undo_method(E->get(), "set_script", existing);
- editor_data->get_undo_redo().add_do_method(InspectorDock::get_singleton(), "apply_script_properties", E->get());
- editor_data->get_undo_redo().add_undo_method(InspectorDock::get_singleton(), "apply_script_properties", E->get());
- editor_data->get_undo_redo().add_do_method(this, "_update_script_button");
- editor_data->get_undo_redo().add_undo_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->create_action(TTR("Attach Script"));
+ for (Node *E : selected) {
+ Ref<Script> existing = E->get_script();
+ editor_data->get_undo_redo()->add_do_method(InspectorDock::get_singleton(), "store_script_properties", E);
+ editor_data->get_undo_redo()->add_undo_method(InspectorDock::get_singleton(), "store_script_properties", E);
+ editor_data->get_undo_redo()->add_do_method(E, "set_script", p_script);
+ editor_data->get_undo_redo()->add_undo_method(E, "set_script", existing);
+ editor_data->get_undo_redo()->add_do_method(InspectorDock::get_singleton(), "apply_script_properties", E);
+ editor_data->get_undo_redo()->add_undo_method(InspectorDock::get_singleton(), "apply_script_properties", E);
+ editor_data->get_undo_redo()->add_do_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->add_undo_method(this, "_update_script_button");
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
}
_push_item(p_script.operator->());
@@ -1994,10 +1993,10 @@ void SceneTreeDock::_shader_created(Ref<Shader> p_shader) {
Ref<Shader> existing = selected_shader_material->get_shader();
- editor_data->get_undo_redo().create_action(TTR("Set Shader"));
- editor_data->get_undo_redo().add_do_method(selected_shader_material.ptr(), "set_shader", p_shader);
- editor_data->get_undo_redo().add_undo_method(selected_shader_material.ptr(), "set_shader", existing);
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->create_action(TTR("Set Shader"));
+ editor_data->get_undo_redo()->add_do_method(selected_shader_material.ptr(), "set_shader", p_shader);
+ editor_data->get_undo_redo()->add_undo_method(selected_shader_material.ptr(), "set_shader", existing);
+ editor_data->get_undo_redo()->commit_action();
}
void SceneTreeDock::_script_creation_closed() {
@@ -2063,9 +2062,9 @@ void SceneTreeDock::_delete_confirm(bool p_cut) {
EditorNode::get_singleton()->get_editor_plugins_over()->make_visible(false);
if (p_cut) {
- editor_data->get_undo_redo().create_action(TTR("Cut Node(s)"));
+ editor_data->get_undo_redo()->create_action(TTR("Cut Node(s)"));
} else {
- editor_data->get_undo_redo().create_action(TTR("Remove Node(s)"));
+ editor_data->get_undo_redo()->create_action(TTR("Remove Node(s)"));
}
bool entire_scene = false;
@@ -2077,11 +2076,11 @@ void SceneTreeDock::_delete_confirm(bool p_cut) {
}
if (entire_scene) {
- editor_data->get_undo_redo().add_do_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
- editor_data->get_undo_redo().add_undo_method(EditorNode::get_singleton(), "set_edited_scene", edited_scene);
- editor_data->get_undo_redo().add_undo_method(edited_scene, "set_owner", edited_scene->get_owner());
- editor_data->get_undo_redo().add_undo_method(scene_tree, "update_tree");
- editor_data->get_undo_redo().add_undo_reference(edited_scene);
+ editor_data->get_undo_redo()->add_do_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
+ editor_data->get_undo_redo()->add_undo_method(EditorNode::get_singleton(), "set_edited_scene", edited_scene);
+ editor_data->get_undo_redo()->add_undo_method(edited_scene, "set_owner", edited_scene->get_owner());
+ editor_data->get_undo_redo()->add_undo_method(scene_tree, "update_tree");
+ editor_data->get_undo_redo()->add_undo_reference(edited_scene);
} else {
remove_list.sort_custom<Node::Comparator>(); //sort nodes to keep positions
@@ -2110,21 +2109,21 @@ void SceneTreeDock::_delete_confirm(bool p_cut) {
owners.push_back(F);
}
- editor_data->get_undo_redo().add_do_method(n->get_parent(), "remove_child", n);
- editor_data->get_undo_redo().add_undo_method(n->get_parent(), "add_child", n, true);
- editor_data->get_undo_redo().add_undo_method(n->get_parent(), "move_child", n, n->get_index());
+ editor_data->get_undo_redo()->add_do_method(n->get_parent(), "remove_child", n);
+ editor_data->get_undo_redo()->add_undo_method(n->get_parent(), "add_child", n, true);
+ editor_data->get_undo_redo()->add_undo_method(n->get_parent(), "move_child", n, n->get_index());
if (AnimationPlayerEditor::get_singleton()->get_track_editor()->get_root() == n) {
- editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::get_singleton()->get_track_editor(), "set_root", n);
+ editor_data->get_undo_redo()->add_undo_method(AnimationPlayerEditor::get_singleton()->get_track_editor(), "set_root", n);
}
- editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners);
- editor_data->get_undo_redo().add_undo_reference(n);
+ editor_data->get_undo_redo()->add_undo_method(this, "_set_owners", edited_scene, owners);
+ editor_data->get_undo_redo()->add_undo_reference(n);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_remove_and_keep_node", edited_scene->get_path_to(n), n->get_instance_id());
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_restore_node", n->get_instance_id(), edited_scene->get_path_to(n->get_parent()), n->get_index());
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_remove_and_keep_node", edited_scene->get_path_to(n), n->get_instance_id());
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_restore_node", n->get_instance_id(), edited_scene->get_path_to(n->get_parent()), n->get_index());
}
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
// hack, force 2d editor viewport to refresh after deletion
if (CanvasItemEditor *editor = CanvasItemEditor::get_singleton()) {
@@ -2190,29 +2189,29 @@ void SceneTreeDock::_do_create(Node *p_parent) {
Node *child = Object::cast_to<Node>(c);
ERR_FAIL_COND(!child);
- editor_data->get_undo_redo().create_action(TTR("Create Node"));
+ editor_data->get_undo_redo()->create_action(TTR("Create Node"));
if (edited_scene) {
- editor_data->get_undo_redo().add_do_method(p_parent, "add_child", child, true);
- editor_data->get_undo_redo().add_do_method(child, "set_owner", edited_scene);
- editor_data->get_undo_redo().add_do_method(editor_selection, "clear");
- editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", child);
- editor_data->get_undo_redo().add_do_reference(child);
- editor_data->get_undo_redo().add_undo_method(p_parent, "remove_child", child);
+ editor_data->get_undo_redo()->add_do_method(p_parent, "add_child", child, true);
+ editor_data->get_undo_redo()->add_do_method(child, "set_owner", edited_scene);
+ editor_data->get_undo_redo()->add_do_method(editor_selection, "clear");
+ editor_data->get_undo_redo()->add_do_method(editor_selection, "add_node", child);
+ editor_data->get_undo_redo()->add_do_reference(child);
+ editor_data->get_undo_redo()->add_undo_method(p_parent, "remove_child", child);
String new_name = p_parent->validate_child_name(child);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
- editor_data->get_undo_redo().add_do_method(ed, "live_debug_create_node", edited_scene->get_path_to(p_parent), child->get_class(), new_name);
- editor_data->get_undo_redo().add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(p_parent)).plus_file(new_name)));
+ editor_data->get_undo_redo()->add_do_method(ed, "live_debug_create_node", edited_scene->get_path_to(p_parent), child->get_class(), new_name);
+ editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(p_parent)).plus_file(new_name)));
} else {
- editor_data->get_undo_redo().add_do_method(EditorNode::get_singleton(), "set_edited_scene", child);
- editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree");
- editor_data->get_undo_redo().add_do_reference(child);
- editor_data->get_undo_redo().add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
+ editor_data->get_undo_redo()->add_do_method(EditorNode::get_singleton(), "set_edited_scene", child);
+ editor_data->get_undo_redo()->add_do_method(scene_tree, "update_tree");
+ editor_data->get_undo_redo()->add_do_reference(child);
+ editor_data->get_undo_redo()->add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
}
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->commit_action();
_push_item(c);
editor_selection->clear();
editor_selection->add_node(child);
@@ -2259,8 +2258,8 @@ void SceneTreeDock::_create() {
List<Node *> selection = editor_selection->get_selected_node_list();
ERR_FAIL_COND(selection.size() <= 0);
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
- ur->create_action(TTR("Change type of node(s)"));
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
+ ur->create_action(TTR("Change type of node(s)"), UndoRedo::MERGE_DISABLE, selection.front()->get());
for (Node *n : selection) {
ERR_FAIL_COND(!n);
@@ -2393,7 +2392,7 @@ void SceneTreeDock::replace_node(Node *p_node, Node *p_by_node, bool p_keep_prop
}
//p_remove_old was added to support undo
if (p_remove_old) {
- editor_data->get_undo_redo().clear_history();
+ editor_data->get_undo_redo()->clear_history();
}
newnode->set_name(newname);
@@ -2607,16 +2606,16 @@ void SceneTreeDock::_script_dropped(String p_file, NodePath p_to) {
Ref<Script> scr = ResourceLoader::load(p_file);
ERR_FAIL_COND(!scr.is_valid());
if (Node *n = get_node(p_to)) {
- editor_data->get_undo_redo().create_action(TTR("Attach Script"));
- editor_data->get_undo_redo().add_do_method(InspectorDock::get_singleton(), "store_script_properties", n);
- editor_data->get_undo_redo().add_undo_method(InspectorDock::get_singleton(), "store_script_properties", n);
- editor_data->get_undo_redo().add_do_method(n, "set_script", scr);
- editor_data->get_undo_redo().add_undo_method(n, "set_script", n->get_script());
- editor_data->get_undo_redo().add_do_method(InspectorDock::get_singleton(), "apply_script_properties", n);
- editor_data->get_undo_redo().add_undo_method(InspectorDock::get_singleton(), "apply_script_properties", n);
- editor_data->get_undo_redo().add_do_method(this, "_update_script_button");
- editor_data->get_undo_redo().add_undo_method(this, "_update_script_button");
- editor_data->get_undo_redo().commit_action();
+ editor_data->get_undo_redo()->create_action(TTR("Attach Script"));
+ editor_data->get_undo_redo()->add_do_method(InspectorDock::get_singleton(), "store_script_properties", n);
+ editor_data->get_undo_redo()->add_undo_method(InspectorDock::get_singleton(), "store_script_properties", n);
+ editor_data->get_undo_redo()->add_do_method(n, "set_script", scr);
+ editor_data->get_undo_redo()->add_undo_method(n, "set_script", n->get_script());
+ editor_data->get_undo_redo()->add_do_method(InspectorDock::get_singleton(), "apply_script_properties", n);
+ editor_data->get_undo_redo()->add_undo_method(InspectorDock::get_singleton(), "apply_script_properties", n);
+ editor_data->get_undo_redo()->add_do_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->add_undo_method(this, "_update_script_button");
+ editor_data->get_undo_redo()->commit_action();
}
}
@@ -2678,7 +2677,7 @@ void SceneTreeDock::_add_children_to_popup(Object *p_obj, int p_depth) {
}
int index = menu_subresources->get_item_count();
menu_subresources->add_icon_item(icon, E.name.capitalize(), EDIT_SUBRESOURCE_BASE + subresources.size());
- menu_subresources->set_item_horizontal_offset(index, p_depth * 10 * EDSCALE);
+ menu_subresources->set_item_indent(index, p_depth);
subresources.push_back(obj->get_instance_id());
_add_children_to_popup(obj, p_depth + 1);
@@ -3064,9 +3063,9 @@ List<Node *> SceneTreeDock::paste_nodes() {
owner = paste_parent;
}
- UndoRedo &ur = editor_data->get_undo_redo();
- ur.create_action(TTR("Paste Node(s)"));
- ur.add_do_method(editor_selection, "clear");
+ Ref<EditorUndoRedoManager> &ur = editor_data->get_undo_redo();
+ ur->create_action(TTR("Paste Node(s)"), UndoRedo::MERGE_DISABLE, EditorNode::get_singleton()->get_edited_scene());
+ ur->add_do_method(editor_selection, "clear");
HashMap<Ref<Resource>, Ref<Resource>> resource_remap;
String target_scene;
@@ -3095,36 +3094,36 @@ List<Node *> SceneTreeDock::paste_nodes() {
if (!paste_parent) {
paste_parent = dup;
owner = dup;
- ur.add_do_method(EditorNode::get_singleton(), "set_edited_scene", dup);
+ ur->add_do_method(EditorNode::get_singleton(), "set_edited_scene", dup);
} else {
- ur.add_do_method(paste_parent, "add_child", dup, true);
+ ur->add_do_method(paste_parent, "add_child", dup, true);
}
for (KeyValue<const Node *, Node *> &E2 : duplimap) {
Node *d = E2.value;
if (d != dup) {
- ur.add_do_method(d, "set_owner", owner);
+ ur->add_do_method(d, "set_owner", owner);
}
}
if (dup != owner) {
- ur.add_do_method(dup, "set_owner", owner);
+ ur->add_do_method(dup, "set_owner", owner);
}
- ur.add_do_method(editor_selection, "add_node", dup);
+ ur->add_do_method(editor_selection, "add_node", dup);
if (dup == paste_parent) {
- ur.add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
+ ur->add_undo_method(EditorNode::get_singleton(), "set_edited_scene", (Object *)nullptr);
} else {
- ur.add_undo_method(paste_parent, "remove_child", dup);
+ ur->add_undo_method(paste_parent, "remove_child", dup);
}
- ur.add_do_reference(dup);
+ ur->add_do_reference(dup);
if (node_clipboard.size() == 1) {
- ur.add_do_method(EditorNode::get_singleton(), "push_item", dup);
+ ur->add_do_method(EditorNode::get_singleton(), "push_item", dup);
}
}
- ur.commit_action();
+ ur->commit_action();
return pasted_nodes;
}
@@ -3492,7 +3491,7 @@ SceneTreeDock::SceneTreeDock(Node *p_scene_root, EditorSelection *p_editor_selec
editor_selection->connect("selection_changed", callable_mp(this, &SceneTreeDock::_selection_changed));
- scene_tree->set_undo_redo(&editor_data->get_undo_redo());
+ scene_tree->set_undo_redo(editor_data->get_undo_redo());
scene_tree->set_editor_selection(editor_selection);
create_dialog = memnew(CreateDialog);
@@ -3502,7 +3501,7 @@ SceneTreeDock::SceneTreeDock(Node *p_scene_root, EditorSelection *p_editor_selec
create_dialog->connect("favorites_updated", callable_mp(this, &SceneTreeDock::_update_create_root_dialog));
#ifdef MODULE_REGEX_ENABLED
- rename_dialog = memnew(RenameDialog(scene_tree, &editor_data->get_undo_redo()));
+ rename_dialog = memnew(RenameDialog(scene_tree, editor_data->get_undo_redo()));
add_child(rename_dialog);
#endif // MODULE_REGEX_ENABLED
diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp
index ad83db9b60..00fd0c3aac 100644
--- a/editor/scene_tree_editor.cpp
+++ b/editor/scene_tree_editor.cpp
@@ -35,6 +35,7 @@
#include "editor/editor_file_system.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/node_dock.h"
#include "editor/plugins/animation_player_editor_plugin.h"
#include "editor/plugins/canvas_item_editor_plugin.h"
@@ -278,7 +279,19 @@ void SceneTreeEditor::_add_nodes(Node *p_node, TreeItem *p_parent) {
warning_icon = SNAME("NodeWarnings4Plus");
}
- item->add_button(0, get_theme_icon(warning_icon, SNAME("EditorIcons")), BUTTON_WARNING, false, TTR("Node configuration warning:") + "\n" + warning);
+ // Improve looks on tooltip, extra spacing on non-bullet point newlines.
+ const String bullet_point = String::utf8("• ");
+ int next_newline = 0;
+ while (next_newline != -1) {
+ next_newline = warning.find("\n", next_newline + 2);
+ if (warning.substr(next_newline + 1, bullet_point.length()) != bullet_point) {
+ warning = warning.insert(next_newline + 1, " ");
+ }
+ }
+
+ String newline = (num_warnings == 1 ? "\n" : "\n\n");
+
+ item->add_button(0, get_theme_icon(warning_icon, SNAME("EditorIcons")), BUTTON_WARNING, false, TTR("Node configuration warning:") + newline + warning);
}
if (p_node->is_unique_name_in_owner()) {
@@ -365,7 +378,7 @@ void SceneTreeEditor::_add_nodes(Node *p_node, TreeItem *p_parent) {
item->set_tooltip(0, tooltip);
}
- if (can_open_instance && undo_redo) { //Show buttons only when necessary(SceneTreeDock) to avoid crashes
+ if (can_open_instance && undo_redo.is_valid()) { //Show buttons only when necessary(SceneTreeDock) to avoid crashes
if (!p_node->is_connected("script_changed", callable_mp(this, &SceneTreeEditor::_node_script_changed))) {
p_node->connect("script_changed", callable_mp(this, &SceneTreeEditor::_node_script_changed).bind(p_node));
@@ -602,7 +615,9 @@ bool SceneTreeEditor::_update_filter(TreeItem *p_parent, bool p_scroll_to_select
}
if (!keep) {
- keep = filter.is_subsequence_ofn(p_parent->get_text(0));
+ StringName node_type = get_node(p_parent->get_metadata(0))->get_class();
+ bool is_kept_by_type = (filter.begins_with("type:") && filter.trim_prefix("type:").is_subsequence_ofn(node_type)) || (filter.begins_with("t:") && filter.trim_prefix("t:").is_subsequence_ofn(node_type));
+ keep = (filter.is_subsequence_ofn(p_parent->get_text(0)) || is_kept_by_type);
}
p_parent->set_visible(keep);
@@ -883,7 +898,7 @@ void SceneTreeEditor::_renamed() {
return;
}
- if (!undo_redo) {
+ if (!undo_redo.is_valid()) {
n->set_name(new_name);
which->set_metadata(0, n->get_path());
emit_signal(SNAME("node_renamed"));
@@ -927,6 +942,10 @@ String SceneTreeEditor::get_filter() const {
return filter;
}
+void SceneTreeEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
+ undo_redo = p_undo_redo;
+}
+
void SceneTreeEditor::set_display_foreign_nodes(bool p_display) {
display_foreign = p_display;
_update_tree();
@@ -1258,7 +1277,6 @@ void SceneTreeEditor::_bind_methods() {
}
SceneTreeEditor::SceneTreeEditor(bool p_label, bool p_can_rename, bool p_can_open_instance) {
- undo_redo = nullptr;
selected = nullptr;
can_rename = p_can_rename;
diff --git a/editor/scene_tree_editor.h b/editor/scene_tree_editor.h
index 31772e55b5..0c13ad96cd 100644
--- a/editor/scene_tree_editor.h
+++ b/editor/scene_tree_editor.h
@@ -31,13 +31,14 @@
#ifndef SCENE_TREE_EDITOR_H
#define SCENE_TREE_EDITOR_H
-#include "core/object/undo_redo.h"
#include "editor/editor_data.h"
#include "editor/editor_settings.h"
#include "scene/gui/button.h"
#include "scene/gui/dialogs.h"
#include "scene/gui/tree.h"
+class EditorUndoRedoManager;
+
class SceneTreeEditor : public Control {
GDCLASS(SceneTreeEditor, Control);
@@ -98,7 +99,7 @@ class SceneTreeEditor : public Control {
bool show_enabled_subscene = false;
void _renamed();
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
HashSet<Node *> marked;
bool marked_selectable = false;
@@ -139,7 +140,7 @@ public:
void set_filter(const String &p_filter);
String get_filter() const;
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; };
+ void set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo);
void set_display_foreign_nodes(bool p_display);
void set_marked(const HashSet<Node *> &p_marked, bool p_selectable = false, bool p_children_selectable = true);
diff --git a/editor/shader_create_dialog.cpp b/editor/shader_create_dialog.cpp
index bd1f2529ca..8c4a231e8a 100644
--- a/editor/shader_create_dialog.cpp
+++ b/editor/shader_create_dialog.cpp
@@ -37,6 +37,13 @@
#include "scene/resources/visual_shader.h"
#include "servers/rendering/shader_types.h"
+enum ShaderType {
+ SHADER_TYPE_TEXT,
+ SHADER_TYPE_VISUAL,
+ SHADER_TYPE_INC,
+ SHADER_TYPE_MAX,
+};
+
void ShaderCreateDialog::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
diff --git a/editor/shader_create_dialog.h b/editor/shader_create_dialog.h
index bf031c3601..9ba655369b 100644
--- a/editor/shader_create_dialog.h
+++ b/editor/shader_create_dialog.h
@@ -44,13 +44,6 @@ class EditorFileDialog;
class ShaderCreateDialog : public ConfirmationDialog {
GDCLASS(ShaderCreateDialog, ConfirmationDialog);
- enum ShaderType {
- SHADER_TYPE_TEXT,
- SHADER_TYPE_VISUAL,
- SHADER_TYPE_INC,
- SHADER_TYPE_MAX,
- };
-
struct ShaderTypeData {
List<String> extensions;
String default_extension;
diff --git a/editor/shader_globals_editor.cpp b/editor/shader_globals_editor.cpp
index 1cd1b4ea00..9058596830 100644
--- a/editor/shader_globals_editor.cpp
+++ b/editor/shader_globals_editor.cpp
@@ -32,6 +32,7 @@
#include "core/config/project_settings.h"
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "servers/rendering/shader_language.h"
static const char *global_var_type_names[RS::GLOBAL_VAR_TYPE_MAX] = {
@@ -85,7 +86,7 @@ protected:
return false;
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Set Shader Global Variable"));
undo_redo->add_do_method(RS::get_singleton(), "global_shader_uniform_set", p_name, p_value);
@@ -393,7 +394,7 @@ void ShaderGlobalsEditor::_variable_added() {
return;
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
Variant value = create_var(RS::GlobalShaderUniformType(variable_type->get_selected()));
@@ -412,7 +413,7 @@ void ShaderGlobalsEditor::_variable_added() {
}
void ShaderGlobalsEditor::_variable_deleted(const String &p_variable) {
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(TTR("Add Shader Global Uniform"));
undo_redo->add_do_method(RS::get_singleton(), "global_shader_uniform_remove", p_variable);
diff --git a/editor/shader_globals_editor.h b/editor/shader_globals_editor.h
index d29052eaee..1e2f1dd828 100644
--- a/editor/shader_globals_editor.h
+++ b/editor/shader_globals_editor.h
@@ -31,7 +31,6 @@
#ifndef SHADER_GLOBALS_EDITOR_H
#define SHADER_GLOBALS_EDITOR_H
-#include "core/object/undo_redo.h"
#include "editor/editor_autoload_settings.h"
#include "editor/editor_data.h"
#include "editor/editor_plugin_settings.h"
diff --git a/gles3_builders.py b/gles3_builders.py
index a9fabd93ce..eafe503dd5 100644
--- a/gles3_builders.py
+++ b/gles3_builders.py
@@ -182,8 +182,8 @@ def include_file_in_gles3_header(filename, header_data, depth):
return header_data
-def build_gles3_header(filename, include, class_suffix, output_attribs):
- header_data = GLES3HeaderStruct()
+def build_gles3_header(filename, include, class_suffix, header_data=None):
+ header_data = header_data or GLES3HeaderStruct()
include_file_in_gles3_header(filename, header_data, 0)
out_file = filename + ".gen.h"
@@ -191,8 +191,6 @@ def build_gles3_header(filename, include, class_suffix, output_attribs):
defspec = 0
defvariant = ""
- enum_constants = []
-
fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
out_file_base = out_file
@@ -552,7 +550,7 @@ def build_gles3_header(filename, include, class_suffix, output_attribs):
def build_gles3_headers(target, source, env):
for x in source:
- build_gles3_header(str(x), include="drivers/gles3/shader_gles3.h", class_suffix="GLES3", output_attribs=True)
+ build_gles3_header(str(x), include="drivers/gles3/shader_gles3.h", class_suffix="GLES3")
if __name__ == "__main__":
diff --git a/glsl_builders.py b/glsl_builders.py
index 0926212e50..8cb5807f21 100644
--- a/glsl_builders.py
+++ b/glsl_builders.py
@@ -3,9 +3,26 @@
All such functions are invoked in a subprocess on Windows to prevent build flakiness.
"""
+import os.path
from platform_methods import subprocess_main
+def generate_inline_code(input_lines, insert_newline=True):
+ """Take header data and generate inline code
+
+ :param: list input_lines: values for shared inline code
+ :return: str - generated inline value
+ """
+ output = []
+ for line in input_lines:
+ if line:
+ output.append(",".join(str(ord(c)) for c in line))
+ if insert_newline:
+ output.append("%s" % ord("\n"))
+ output.append("0")
+ return ",".join(output)
+
+
class RDHeaderStruct:
def __init__(self):
self.vertex_lines = []
@@ -57,10 +74,6 @@ def include_file_in_rd_header(filename, header_data, depth):
while line.find("#include ") != -1:
includeline = line.replace("#include ", "").strip()[1:-1]
- import os.path
-
- included_file = ""
-
if includeline.startswith("thirdparty/"):
included_file = os.path.relpath(includeline)
@@ -82,8 +95,7 @@ def include_file_in_rd_header(filename, header_data, depth):
line = fs.readline()
- line = line.replace("\r", "")
- line = line.replace("\n", "")
+ line = line.replace("\r", "").replace("\n", "")
if header_data.reading == "vertex":
header_data.vertex_lines += [line]
@@ -100,65 +112,53 @@ def include_file_in_rd_header(filename, header_data, depth):
return header_data
-def build_rd_header(filename):
- header_data = RDHeaderStruct()
+def build_rd_header(filename, header_data=None):
+ header_data = header_data or RDHeaderStruct()
include_file_in_rd_header(filename, header_data, 0)
out_file = filename + ".gen.h"
- fd = open(out_file, "w")
-
- fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
-
out_file_base = out_file
out_file_base = out_file_base[out_file_base.rfind("/") + 1 :]
out_file_base = out_file_base[out_file_base.rfind("\\") + 1 :]
out_file_ifdef = out_file_base.replace(".", "_").upper()
- fd.write("#ifndef " + out_file_ifdef + "_RD\n")
- fd.write("#define " + out_file_ifdef + "_RD\n")
-
out_file_class = out_file_base.replace(".glsl.gen.h", "").title().replace("_", "").replace(".", "") + "ShaderRD"
- fd.write("\n")
- fd.write('#include "servers/rendering/renderer_rd/shader_rd.h"\n\n')
- fd.write("class " + out_file_class + " : public ShaderRD {\n\n")
- fd.write("public:\n\n")
- fd.write("\t" + out_file_class + "() {\n\n")
+ if header_data.compute_lines:
+ body_parts = [
+ "static const char _compute_code[] = {\n%s\n\t\t};" % generate_inline_code(header_data.compute_lines),
+ f'setup(nullptr, nullptr, _compute_code, "{out_file_class}");',
+ ]
+ else:
+ body_parts = [
+ "static const char _vertex_code[] = {\n%s\n\t\t};" % generate_inline_code(header_data.vertex_lines),
+ "static const char _fragment_code[] = {\n%s\n\t\t};" % generate_inline_code(header_data.fragment_lines),
+ f'setup(_vertex_code, _fragment_code, nullptr, "{out_file_class}");',
+ ]
- if len(header_data.compute_lines):
+ body_content = "\n\t\t".join(body_parts)
- fd.write("\t\tstatic const char _compute_code[] = {\n")
- for x in header_data.compute_lines:
- for c in x:
- fd.write(str(ord(c)) + ",")
- fd.write(str(ord("\n")) + ",")
- fd.write("\t\t0};\n\n")
+ # Intended curly brackets are doubled so f-string doesn't eat them up.
+ shader_template = f"""/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
+#ifndef {out_file_ifdef}_RD
+#define {out_file_ifdef}_RD
- fd.write('\t\tsetup(nullptr, nullptr, _compute_code, "' + out_file_class + '");\n')
- fd.write("\t}\n")
+#include "servers/rendering/renderer_rd/shader_rd.h"
- else:
+class {out_file_class} : public ShaderRD {{
- fd.write("\t\tstatic const char _vertex_code[] = {\n")
- for x in header_data.vertex_lines:
- for c in x:
- fd.write(str(ord(c)) + ",")
- fd.write(str(ord("\n")) + ",")
- fd.write("\t\t0};\n\n")
+public:
- fd.write("\t\tstatic const char _fragment_code[]={\n")
- for x in header_data.fragment_lines:
- for c in x:
- fd.write(str(ord(c)) + ",")
- fd.write(str(ord("\n")) + ",")
- fd.write("\t\t0};\n\n")
+ {out_file_class}() {{
- fd.write('\t\tsetup(_vertex_code, _fragment_code, nullptr, "' + out_file_class + '");\n')
- fd.write("\t}\n")
+ {body_content}
+ }}
+}};
- fd.write("};\n\n")
+#endif
+"""
- fd.write("#endif\n")
- fd.close()
+ with open(out_file, "w") as fd:
+ fd.write(shader_template)
def build_rd_headers(target, source, env):
@@ -180,8 +180,6 @@ def include_file_in_raw_header(filename, header_data, depth):
while line.find("#include ") != -1:
includeline = line.replace("#include ", "").strip()[1:-1]
- import os.path
-
included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline)
include_file_in_raw_header(included_file, header_data, depth + 1)
@@ -193,28 +191,28 @@ def include_file_in_raw_header(filename, header_data, depth):
fs.close()
-def build_raw_header(filename):
- header_data = RAWHeaderStruct()
+def build_raw_header(filename, header_data=None):
+ header_data = header_data or RAWHeaderStruct()
include_file_in_raw_header(filename, header_data, 0)
out_file = filename + ".gen.h"
- fd = open(out_file, "w")
-
- fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
-
out_file_base = out_file.replace(".glsl.gen.h", "_shader_glsl")
out_file_base = out_file_base[out_file_base.rfind("/") + 1 :]
out_file_base = out_file_base[out_file_base.rfind("\\") + 1 :]
out_file_ifdef = out_file_base.replace(".", "_").upper()
- fd.write("#ifndef " + out_file_ifdef + "_RAW_H\n")
- fd.write("#define " + out_file_ifdef + "_RAW_H\n")
- fd.write("\n")
- fd.write("static const char " + out_file_base + "[] = {\n")
- for c in header_data.code:
- fd.write(str(ord(c)) + ",")
- fd.write("\t\t0};\n\n")
- fd.write("#endif\n")
- fd.close()
+
+ shader_template = f"""/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
+#ifndef {out_file_ifdef}_RAW_H
+#define {out_file_ifdef}_RAW_H
+
+static const char {out_file_base}[] = {{
+ {generate_inline_code(header_data.code, insert_newline=False)}
+}};
+#endif
+"""
+
+ with open(out_file, "w") as f:
+ f.write(shader_template)
def build_raw_headers(target, source, env):
diff --git a/main/main.cpp b/main/main.cpp
index 965fcc66c6..126ac59070 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -143,6 +143,7 @@ static int audio_driver_idx = -1;
// Engine config/tools
+static bool single_window = false;
static bool editor = false;
static bool project_manager = false;
static bool cmdline_tool = false;
@@ -153,7 +154,11 @@ static OS::ProcessID editor_pid = 0;
#ifdef TOOLS_ENABLED
static bool auto_build_solutions = false;
static String debug_server_uri;
+
+HashMap<Main::CLIScope, Vector<String>> forwardable_cli_arguments;
#endif
+bool use_startup_benchmark = false;
+String startup_benchmark_file;
// Display
@@ -161,7 +166,7 @@ static DisplayServer::WindowMode window_mode = DisplayServer::WINDOW_MODE_WINDOW
static DisplayServer::ScreenOrientation window_orientation = DisplayServer::SCREEN_LANDSCAPE;
static DisplayServer::VSyncMode window_vsync_mode = DisplayServer::VSYNC_ENABLED;
static uint32_t window_flags = 0;
-static Size2i window_size = Size2i(1024, 600);
+static Size2i window_size = Size2i(1152, 648);
static int init_screen = -1;
static bool init_fullscreen = false;
@@ -196,6 +201,12 @@ bool Main::is_cmdline_tool() {
return cmdline_tool;
}
+#ifdef TOOLS_ENABLED
+const Vector<String> &Main::get_forwardable_cli_arguments(Main::CLIScope p_scope) {
+ return forwardable_cli_arguments[p_scope];
+}
+#endif
+
static String unescape_cmdline(const String &p_str) {
return p_str.replace("%20", " ");
}
@@ -386,6 +397,8 @@ void Main::print_help(const char *p_binary) {
OS::get_singleton()->print(" --no-docbase Disallow dumping the base types (used with --doctool).\n");
OS::get_singleton()->print(" --build-solutions Build the scripting solutions (e.g. for C# projects). Implies --editor and requires a valid project to edit.\n");
OS::get_singleton()->print(" --dump-extension-api Generate JSON dump of the Godot API for GDExtension bindings named 'extension_api.json' in the current folder.\n");
+ OS::get_singleton()->print(" --startup-benchmark Benchmark the startup time and print it to console.\n");
+ OS::get_singleton()->print(" --startup-benchmark-file <path> Benchmark the startup time and save it to a given file in JSON format.\n");
#ifdef TESTS_ENABLED
OS::get_singleton()->print(" --test [--help] Run unit tests. Use --test --help for more information.\n");
#endif
@@ -594,6 +607,8 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
engine = memnew(Engine);
MAIN_PRINT("Main: Initialize CORE");
+ engine->startup_begin();
+ engine->startup_benchmark_begin_measure("core");
register_core_types();
register_core_driver_types();
@@ -703,6 +718,26 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
List<String>::Element *N = I->next();
+#ifdef TOOLS_ENABLED
+ if (I->get() == "--debug" ||
+ I->get() == "--verbose" ||
+ I->get() == "--disable-crash-handler") {
+ forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->get());
+ forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(I->get());
+ }
+ if (I->get() == "--single-window") {
+ forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->get());
+ }
+ if (I->get() == "--audio-driver" ||
+ I->get() == "--display-driver" ||
+ I->get() == "--rendering-driver") {
+ if (I->next()) {
+ forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->get());
+ forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->next()->get());
+ }
+ }
+#endif
+
if (adding_user_args) {
user_args.push_back(I->get());
} else if (I->get() == "-h" || I->get() == "--help" || I->get() == "/?") { // display help
@@ -881,7 +916,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
}
} else if (I->get() == "--single-window") { // force single window
- OS::get_singleton()->_single_window = true;
+ single_window = true;
} else if (I->get() == "-t" || I->get() == "--always-on-top") { // force always-on-top window
init_always_on_top = true;
@@ -1208,6 +1243,19 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
OS::get_singleton()->print("Missing --xr-mode argument, aborting.\n");
goto error;
}
+
+ } else if (I->get() == "--startup-benchmark") {
+ use_startup_benchmark = true;
+ } else if (I->get() == "--startup-benchmark-file") {
+ if (I->next()) {
+ use_startup_benchmark = true;
+ startup_benchmark_file = I->next()->get();
+ N = I->next()->next();
+ } else {
+ OS::get_singleton()->print("Missing <path> argument for --startup-benchmark-file <path>.\n");
+ goto error;
+ }
+
} else if (I->get() == "--") {
adding_user_args = true;
} else {
@@ -1624,6 +1672,8 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
message_queue = memnew(MessageQueue);
+ engine->startup_benchmark_end_measure(); // core
+
if (p_second_phase) {
return setup2();
}
@@ -1690,6 +1740,8 @@ error:
}
Error Main::setup2(Thread::ID p_main_tid_override) {
+ engine->startup_benchmark_begin_measure("servers");
+
tsman = memnew(TextServerManager);
if (tsman) {
@@ -1997,10 +2049,16 @@ Error Main::setup2(Thread::ID p_main_tid_override) {
GLOBAL_DEF_RST("internationalization/rendering/text_driver", "");
String text_driver_options;
for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
- if (i > 0) {
+ const String driver_name = TextServerManager::get_singleton()->get_interface(i)->get_name();
+ if (driver_name == "Dummy") {
+ // Dummy text driver cannot draw any text, making the editor unusable if selected.
+ continue;
+ }
+ if (!text_driver_options.is_empty() && text_driver_options.find(",") == -1) {
+ // Not the first option; add a comma before it as a separator for the property hint.
text_driver_options += ",";
}
- text_driver_options += TextServerManager::get_singleton()->get_interface(i)->get_name();
+ text_driver_options += driver_name;
}
ProjectSettings::get_singleton()->set_custom_property_info("internationalization/rendering/text_driver", PropertyInfo(Variant::STRING, "internationalization/rendering/text_driver", PROPERTY_HINT_ENUM, text_driver_options));
@@ -2041,8 +2099,12 @@ Error Main::setup2(Thread::ID p_main_tid_override) {
ERR_FAIL_V_MSG(ERR_CANT_CREATE, "TextServer: Unable to create TextServer interface.");
}
+ engine->startup_benchmark_end_measure(); // servers
+
MAIN_PRINT("Main: Load Scene Types");
+ engine->startup_benchmark_begin_measure("scene");
+
register_scene_types();
register_driver_types();
@@ -2118,6 +2180,8 @@ Error Main::setup2(Thread::ID p_main_tid_override) {
print_verbose("EDITOR API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
MAIN_PRINT("Main: Done");
+ engine->startup_benchmark_end_measure(); // scene
+
return OK;
}
@@ -2249,18 +2313,6 @@ bool Main::start() {
ERR_FAIL_COND_V_MSG(da.is_null(), false, "Argument supplied to --doctool must be a valid directory path.");
}
-#ifndef MODULE_MONO_ENABLED
- // Hack to define Mono-specific project settings even on non-Mono builds,
- // so that we don't lose their descriptions and default values in DocData.
- // Default values should be synced with mono_gd/gd_mono.cpp.
- GLOBAL_DEF("mono/debugger_agent/port", 23685);
- GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
- GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
- GLOBAL_DEF("mono/profiler/args", "log:calls,alloc,sample,output=output.mlpd");
- GLOBAL_DEF("mono/profiler/enabled", false);
- GLOBAL_DEF("mono/runtime/unhandled_exception_policy", 0);
-#endif
-
Error err;
DocTools doc;
doc.generate(doc_base);
@@ -2446,7 +2498,7 @@ bool Main::start() {
bool embed_subwindows = GLOBAL_DEF("display/window/subwindows/embed_subwindows", true);
- if (OS::get_singleton()->is_single_window() || (!project_manager && !editor && embed_subwindows) || !DisplayServer::get_singleton()->has_feature(DisplayServer::Feature::FEATURE_SUBWINDOWS)) {
+ if (single_window || (!project_manager && !editor && embed_subwindows) || !DisplayServer::get_singleton()->has_feature(DisplayServer::Feature::FEATURE_SUBWINDOWS)) {
sml->get_root()->set_embedding_subwindows(true);
}
@@ -2456,6 +2508,7 @@ bool Main::start() {
if (!project_manager && !editor) { // game
if (!game_path.is_empty() || !script.is_empty()) {
//autoload
+ Engine::get_singleton()->startup_benchmark_begin_measure("load_autoloads");
HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
//first pass, add the constants so they exist before any script is loaded
@@ -2510,12 +2563,14 @@ bool Main::start() {
for (Node *E : to_add) {
sml->get_root()->add_child(E);
}
+ Engine::get_singleton()->startup_benchmark_end_measure(); // load autoloads
}
}
#ifdef TOOLS_ENABLED
EditorNode *editor_node = nullptr;
if (editor) {
+ Engine::get_singleton()->startup_benchmark_begin_measure("editor");
editor_node = memnew(EditorNode);
sml->get_root()->add_child(editor_node);
@@ -2523,6 +2578,13 @@ bool Main::start() {
editor_node->export_preset(_export_preset, positional_arg, export_debug, export_pack_only);
game_path = ""; // Do not load anything.
}
+
+ Engine::get_singleton()->startup_benchmark_end_measure();
+
+ editor_node->set_use_startup_benchmark(use_startup_benchmark, startup_benchmark_file);
+ // Editor takes over
+ use_startup_benchmark = false;
+ startup_benchmark_file = String();
}
#endif
@@ -2687,6 +2749,8 @@ bool Main::start() {
if (!project_manager && !editor) { // game
+ Engine::get_singleton()->startup_benchmark_begin_measure("game_load");
+
// Load SSL Certificates from Project Settings (or builtin).
Crypto::load_default_certificates(GLOBAL_DEF("network/ssl/certificate_bundle_override", ""));
@@ -2726,16 +2790,20 @@ bool Main::start() {
}
}
}
+
+ Engine::get_singleton()->startup_benchmark_end_measure(); // game_load
}
#ifdef TOOLS_ENABLED
if (project_manager) {
+ Engine::get_singleton()->startup_benchmark_begin_measure("project_manager");
Engine::get_singleton()->set_editor_hint(true);
ProjectManager *pmanager = memnew(ProjectManager);
ProgressDialog *progress_dialog = memnew(ProgressDialog);
pmanager->add_child(progress_dialog);
sml->get_root()->add_child(pmanager);
DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_PROJECTMAN);
+ Engine::get_singleton()->startup_benchmark_end_measure();
}
if (project_manager || editor) {
@@ -2765,6 +2833,11 @@ bool Main::start() {
}
}
+ if (use_startup_benchmark) {
+ Engine::get_singleton()->startup_dump(startup_benchmark_file);
+ startup_benchmark_file = String();
+ }
+
return true;
}
diff --git a/main/main.h b/main/main.h
index d1870ab8df..f0bfe69b34 100644
--- a/main/main.h
+++ b/main/main.h
@@ -35,6 +35,9 @@
#include "core/os/thread.h"
#include "core/typedefs.h"
+template <class T>
+class Vector;
+
class Main {
static void print_help(const char *p_binary);
static uint64_t last_ticks;
@@ -47,6 +50,14 @@ class Main {
public:
static bool is_cmdline_tool();
+#ifdef TOOLS_ENABLED
+ enum CLIScope {
+ CLI_SCOPE_TOOL, // Editor and project manager.
+ CLI_SCOPE_PROJECT,
+ };
+ static const Vector<String> &get_forwardable_cli_arguments(CLIScope p_scope);
+#endif
+
static int test_entrypoint(int argc, char *argv[], bool &tests_need_run);
static Error setup(const char *execpath, int argc, char *argv[], bool p_second_phase = true);
static Error setup2(Thread::ID p_main_tid_override = 0);
diff --git a/main/performance.cpp b/main/performance.cpp
index 0de525134e..bdcd07a216 100644
--- a/main/performance.cpp
+++ b/main/performance.cpp
@@ -32,6 +32,7 @@
#include "core/object/message_queue.h"
#include "core/os/os.h"
+#include "core/variant/typed_array.h"
#include "scene/main/node.h"
#include "scene/main/scene_tree.h"
#include "servers/audio_server.h"
@@ -240,11 +241,11 @@ Variant Performance::get_custom_monitor(const StringName &p_id) {
return return_value;
}
-Array Performance::get_custom_monitor_names() {
+TypedArray<StringName> Performance::get_custom_monitor_names() {
if (!_monitor_map.size()) {
- return Array();
+ return TypedArray<StringName>();
}
- Array return_array;
+ TypedArray<StringName> return_array;
return_array.resize(_monitor_map.size());
int index = 0;
for (KeyValue<StringName, MonitorCall> i : _monitor_map) {
diff --git a/main/performance.h b/main/performance.h
index 2837d8f512..597666b57d 100644
--- a/main/performance.h
+++ b/main/performance.h
@@ -37,6 +37,9 @@
#define PERF_WARN_OFFLINE_FUNCTION
#define PERF_WARN_PROCESS_SYNC
+template <typename T>
+class TypedArray;
+
class Performance : public Object {
GDCLASS(Performance, Object);
@@ -85,7 +88,6 @@ public:
PHYSICS_3D_ACTIVE_OBJECTS,
PHYSICS_3D_COLLISION_PAIRS,
PHYSICS_3D_ISLAND_COUNT,
- //physics
AUDIO_OUTPUT_LATENCY,
MONITOR_MAX
};
@@ -108,7 +110,7 @@ public:
void remove_custom_monitor(const StringName &p_id);
bool has_custom_monitor(const StringName &p_id);
Variant get_custom_monitor(const StringName &p_id);
- Array get_custom_monitor_names();
+ TypedArray<StringName> get_custom_monitor_names();
uint64_t get_monitor_modification_time();
diff --git a/methods.py b/methods.py
index ba7474ea02..9b60d4251f 100644
--- a/methods.py
+++ b/methods.py
@@ -540,7 +540,7 @@ def detect_visual_c_compiler_version(tools_env):
# and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
# the proper vc version that will be called
- # There is no flag to give to visual c compilers to set the architecture, i.e. scons bits argument (32,64,ARM etc)
+ # There is no flag to give to visual c compilers to set the architecture, i.e. scons arch argument (x86_32, x86_64, arm64, etc.).
# There are many different cl.exe files that are run, and each one compiles & links to a different architecture
# As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
# is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
@@ -818,18 +818,21 @@ def generate_vs_project(env, num_jobs):
module_configs = ModuleConfigs()
if env.get("module_mono_enabled"):
- import modules.mono.build_scripts.mono_reg_utils as mono_reg
+ import modules.mono.build_scripts.mono_configure as mono_configure
- mono_root = env.get("mono_prefix") or mono_reg.find_mono_root_dir(env["bits"])
- if mono_root:
+ app_host_dir = mono_configure.find_dotnet_app_host_dir(env)
+ if app_host_dir and os.path.isdir(app_host_dir):
+ mono_defines = [("NETHOST_USE_AS_STATIC",)]
+ if env["tools"]:
+ mono_defines += [("GD_MONO_HOT_RELOAD",)]
module_configs.add_mode(
"mono",
- includes=os.path.join(mono_root, "include", "mono-2.0"),
- cli_args="module_mono_enabled=yes mono_glue=yes",
- defines=[("MONO_GLUE_ENABLED",)],
+ includes=app_host_dir,
+ cli_args="module_mono_enabled=yes",
+ defines=mono_defines,
)
else:
- print("Mono installation directory not found. Generated project will not have build variants for Mono.")
+ print(".NET App Host directory not found. Generated project will not have build variants for .NET.")
env["MSVSBUILDCOM"] = module_configs.build_commandline("scons")
env["MSVSREBUILDCOM"] = module_configs.build_commandline("scons vsproj=yes")
diff --git a/misc/scripts/clang_format.sh b/misc/scripts/clang_format.sh
index 2b7179f5be..b7c577d5fb 100755
--- a/misc/scripts/clang_format.sh
+++ b/misc/scripts/clang_format.sh
@@ -7,7 +7,8 @@ set -uo pipefail
# Loops through all code files tracked by Git.
git ls-files -- '*.c' '*.h' '*.cpp' '*.hpp' '*.cc' '*.hh' '*.cxx' '*.m' '*.mm' '*.inc' '*.java' '*.glsl' \
- ':!:.git/*' ':!:thirdparty/*' ':!:platform/android/java/lib/src/com/google/*' ':!:*-so_wrap.*' |
+ ':!:.git/*' ':!:thirdparty/*' ':!:platform/android/java/lib/src/com/google/*' ':!:*-so_wrap.*' \
+ ':!:tests/python_build/*' |
while read -r f; do
# Run clang-format.
clang-format --Wno-error=unknown -i "$f"
diff --git a/misc/scripts/pytest_builders.sh b/misc/scripts/pytest_builders.sh
new file mode 100755
index 0000000000..eb2ddbcddc
--- /dev/null
+++ b/misc/scripts/pytest_builders.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+set -uo pipefail
+
+echo "Running Python checks for builder system"
+pytest ./tests/python_build
diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp
index 8813c3827a..ae03abca50 100644
--- a/modules/bmp/image_loader_bmp.cpp
+++ b/modules/bmp/image_loader_bmp.cpp
@@ -200,7 +200,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
return err;
}
-Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) {
+Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) {
bmp_header_s bmp_header;
Error err = ERR_INVALID_DATA;
diff --git a/modules/bmp/image_loader_bmp.h b/modules/bmp/image_loader_bmp.h
index 63dee0a969..cf8346ecad 100644
--- a/modules/bmp/image_loader_bmp.h
+++ b/modules/bmp/image_loader_bmp.h
@@ -83,7 +83,7 @@ protected:
const bmp_header_s &p_header);
public:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale);
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderBMP();
};
diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp
index 56be4e65f0..243c23342e 100644
--- a/modules/csg/csg_shape.cpp
+++ b/modules/csg/csg_shape.cpp
@@ -53,6 +53,7 @@ void CSGShape3D::set_use_collision(bool p_enable) {
PhysicsServer3D::get_singleton()->body_attach_object_instance_id(root_collision_instance, get_instance_id());
set_collision_layer(collision_layer);
set_collision_mask(collision_mask);
+ set_collision_priority(collision_priority);
_make_dirty(); //force update
} else {
PhysicsServer3D::get_singleton()->free(root_collision_instance);
@@ -124,6 +125,17 @@ bool CSGShape3D::get_collision_mask_value(int p_layer_number) const {
return get_collision_mask() & (1 << (p_layer_number - 1));
}
+void CSGShape3D::set_collision_priority(real_t p_priority) {
+ collision_priority = p_priority;
+ if (root_collision_instance.is_valid()) {
+ PhysicsServer3D::get_singleton()->body_set_collision_priority(root_collision_instance, p_priority);
+ }
+}
+
+real_t CSGShape3D::get_collision_priority() const {
+ return collision_priority;
+}
+
bool CSGShape3D::is_root_shape() const {
return !parent_shape;
}
@@ -545,6 +557,7 @@ void CSGShape3D::_notification(int p_what) {
PhysicsServer3D::get_singleton()->body_attach_object_instance_id(root_collision_instance, get_instance_id());
set_collision_layer(collision_layer);
set_collision_mask(collision_mask);
+ set_collision_priority(collision_priority);
_update_collision_faces();
}
} break;
@@ -584,15 +597,14 @@ bool CSGShape3D::is_calculating_tangents() const {
return calculate_tangents;
}
-void CSGShape3D::_validate_property(PropertyInfo &property) const {
- bool is_collision_prefixed = property.name.begins_with("collision_");
- if ((is_collision_prefixed || property.name.begins_with("use_collision")) && is_inside_tree() && !is_root_shape()) {
+void CSGShape3D::_validate_property(PropertyInfo &p_property) const {
+ bool is_collision_prefixed = p_property.name.begins_with("collision_");
+ if ((is_collision_prefixed || p_property.name.begins_with("use_collision")) && is_inside_tree() && !is_root_shape()) {
//hide collision if not root
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
} else if (is_collision_prefixed && !bool(get("use_collision"))) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- GeometryInstance3D::_validate_property(property);
}
Array CSGShape3D::get_meshes() const {
@@ -632,6 +644,9 @@ void CSGShape3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_collision_layer_value", "layer_number", "value"), &CSGShape3D::set_collision_layer_value);
ClassDB::bind_method(D_METHOD("get_collision_layer_value", "layer_number"), &CSGShape3D::get_collision_layer_value);
+ ClassDB::bind_method(D_METHOD("set_collision_priority", "priority"), &CSGShape3D::set_collision_priority);
+ ClassDB::bind_method(D_METHOD("get_collision_priority"), &CSGShape3D::get_collision_priority);
+
ClassDB::bind_method(D_METHOD("set_calculate_tangents", "enabled"), &CSGShape3D::set_calculate_tangents);
ClassDB::bind_method(D_METHOD("is_calculating_tangents"), &CSGShape3D::is_calculating_tangents);
@@ -645,6 +660,7 @@ void CSGShape3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_collision"), "set_use_collision", "is_using_collision");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_priority"), "set_collision_priority", "get_collision_priority");
BIND_ENUM_CONSTANT(OPERATION_UNION);
BIND_ENUM_CONSTANT(OPERATION_INTERSECTION);
@@ -2058,18 +2074,16 @@ void CSGPolygon3D::_notification(int p_what) {
}
}
-void CSGPolygon3D::_validate_property(PropertyInfo &property) const {
- if (property.name.begins_with("spin") && mode != MODE_SPIN) {
- property.usage = PROPERTY_USAGE_NONE;
+void CSGPolygon3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name.begins_with("spin") && mode != MODE_SPIN) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("path") && mode != MODE_PATH) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("path") && mode != MODE_PATH) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "depth" && mode != MODE_DEPTH) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "depth" && mode != MODE_DEPTH) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
-
- CSGShape3D::_validate_property(property);
}
void CSGPolygon3D::_path_changed() {
diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h
index 0b49dc4609..7db5477b10 100644
--- a/modules/csg/csg_shape.h
+++ b/modules/csg/csg_shape.h
@@ -65,6 +65,7 @@ private:
bool use_collision = false;
uint32_t collision_layer = 1;
uint32_t collision_mask = 1;
+ real_t collision_priority = 1.0;
Ref<ConcavePolygonShape3D> root_collision_shape;
RID root_collision_instance;
@@ -117,7 +118,7 @@ protected:
friend class CSGCombiner3D;
CSGBrush *_get_brush();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
Array get_meshes() const;
@@ -144,6 +145,9 @@ public:
void set_collision_mask_value(int p_layer_number, bool p_value);
bool get_collision_mask_value(int p_layer_number) const;
+ void set_collision_priority(real_t p_priority);
+ real_t get_collision_priority() const;
+
void set_snap(float p_snap);
float get_snap() const;
@@ -383,7 +387,7 @@ private:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
public:
diff --git a/modules/csg/doc_classes/CSGShape3D.xml b/modules/csg/doc_classes/CSGShape3D.xml
index 4fd4a12a1d..7e92d667b3 100644
--- a/modules/csg/doc_classes/CSGShape3D.xml
+++ b/modules/csg/doc_classes/CSGShape3D.xml
@@ -66,6 +66,8 @@
<member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1">
The physics layers this CSG shape scans for collisions. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</member>
+ <member name="collision_priority" type="float" setter="set_collision_priority" getter="get_collision_priority" default="1.0">
+ </member>
<member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape3D.Operation" default="0">
The operation that is performed on this shape. This is ignored for the first CSG child node as the operation is between this node and the previous child of this nodes parent.
</member>
diff --git a/modules/csg/editor/csg_gizmos.cpp b/modules/csg/editor/csg_gizmos.cpp
index 6442ff71fc..ba9b96db74 100644
--- a/modules/csg/editor/csg_gizmos.cpp
+++ b/modules/csg/editor/csg_gizmos.cpp
@@ -32,7 +32,9 @@
#ifdef TOOLS_ENABLED
+#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/node_3d_editor_plugin.h"
#include "scene/3d/camera_3d.h"
@@ -215,7 +217,7 @@ void CSGShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Sphere Shape Radius"));
ur->add_do_method(s, "set_radius", s->get_radius());
ur->add_undo_method(s, "set_radius", p_restore);
@@ -229,7 +231,7 @@ void CSGShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Change Box Shape Size"));
ur->add_do_method(s, "set_size", s->get_size());
ur->add_undo_method(s, "set_size", p_restore);
@@ -247,7 +249,7 @@ void CSGShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
if (p_id == 0) {
ur->create_action(TTR("Change Cylinder Radius"));
ur->add_do_method(s, "set_radius", s->get_radius());
@@ -272,7 +274,7 @@ void CSGShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int
return;
}
- UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
if (p_id == 0) {
ur->create_action(TTR("Change Torus Inner Radius"));
ur->add_do_method(s, "set_inner_radius", s->get_inner_radius());
diff --git a/modules/denoise/config.py b/modules/denoise/config.py
index 521115dae5..350839651a 100644
--- a/modules/denoise/config.py
+++ b/modules/denoise/config.py
@@ -5,14 +5,7 @@ def can_build(env, platform):
# as doing lightmap generation and denoising on Android or HTML5
# would be a bit far-fetched.
desktop_platforms = ["linuxbsd", "macos", "windows"]
- supported_arch = env["bits"] == "64"
- if env["arch"] == "arm64":
- supported_arch = False
- if env["arch"].startswith("ppc"):
- supported_arch = False
- if env["arch"].startswith("rv"):
- supported_arch = False
- return env["tools"] and platform in desktop_platforms and supported_arch
+ return env["tools"] and platform in desktop_platforms and env["arch"] == "x86_64"
def configure(env):
diff --git a/modules/enet/doc_classes/ENetConnection.xml b/modules/enet/doc_classes/ENetConnection.xml
index c9bf1c65e1..8c84fe87d7 100644
--- a/modules/enet/doc_classes/ENetConnection.xml
+++ b/modules/enet/doc_classes/ENetConnection.xml
@@ -118,7 +118,7 @@
</description>
</method>
<method name="get_peers">
- <return type="Array" />
+ <return type="ENetPacketPeer[]" />
<description>
Returns the list of peers associated with this host.
[b]Note:[/b] This list might include some peers that are not fully connected or are still being disconnected.
diff --git a/modules/enet/enet_connection.cpp b/modules/enet/enet_connection.cpp
index 629974d7c7..6a4bbecf6a 100644
--- a/modules/enet/enet_connection.cpp
+++ b/modules/enet/enet_connection.cpp
@@ -34,6 +34,7 @@
#include "core/io/compression.h"
#include "core/io/ip.h"
+#include "core/variant/typed_array.h"
void ENetConnection::broadcast(enet_uint8 p_channel, ENetPacket *p_packet) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
@@ -263,9 +264,9 @@ void ENetConnection::get_peers(List<Ref<ENetPacketPeer>> &r_peers) {
}
}
-Array ENetConnection::_get_peers() {
+TypedArray<ENetPacketPeer> ENetConnection::_get_peers() {
ERR_FAIL_COND_V_MSG(!host, Array(), "The ENetConnection instance isn't currently active.");
- Array out;
+ TypedArray<ENetPacketPeer> out;
for (const Ref<ENetPacketPeer> &I : peers) {
out.push_back(I);
}
diff --git a/modules/enet/enet_connection.h b/modules/enet/enet_connection.h
index 0c873b6c55..5cd8f6be9a 100644
--- a/modules/enet/enet_connection.h
+++ b/modules/enet/enet_connection.h
@@ -38,6 +38,9 @@
#include <enet/enet.h>
+template <typename T>
+class TypedArray;
+
class ENetConnection : public RefCounted {
GDCLASS(ENetConnection, RefCounted);
@@ -83,7 +86,7 @@ private:
Error _create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth);
Array _service(int p_timeout = 0);
void _broadcast(int p_channel, PackedByteArray p_packet, int p_flags);
- Array _get_peers();
+ TypedArray<ENetPacketPeer> _get_peers();
class Compressor {
private:
diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml
index 4fbf8c6936..a44be04b2d 100644
--- a/modules/gdscript/doc_classes/@GDScript.xml
+++ b/modules/gdscript/doc_classes/@GDScript.xml
@@ -8,6 +8,7 @@
For the list of the global functions and constants see [@GlobalScope].
</description>
<tutorials>
+ <link title="GDScript exports">$DOCS_URL/tutorials/scripting/gdscript/gdscript_exports.html</link>
</tutorials>
<methods>
<method name="Color8">
@@ -267,87 +268,178 @@
<annotation name="@export">
<return type="void" />
<description>
+ Mark the following property as exported (editable in the Inspector dock and saved to disk). To control the type of the exported property use the type hint notation.
+ [codeblock]
+ @export var int_number = 5
+ @export var float_number: float = 5
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_category">
<return type="void" />
<param index="0" name="name" type="String" />
<description>
+ Define a new category for the following exported properties. This helps to organize properties in the Inspector dock.
+ See also [constant PROPERTY_USAGE_CATEGORY].
+ [codeblock]
+ @export_category("My Properties")
+ @export var number = 3
+ @export var string = ""
+ [/codeblock]
+ [b]Note:[/b] Categories in the property list are supposed to indicate different base types, so the use of this annotation is not encouraged. See [annotation @export_group] and [annotation @export_subgroup] instead.
</description>
</annotation>
<annotation name="@export_color_no_alpha">
<return type="void" />
<description>
+ Export a [Color] property without an alpha (fixed as [code]1.0[/code]).
+ See also [constant PROPERTY_HINT_COLOR_NO_ALPHA].
+ [codeblock]
+ @export_color_no_alpha var modulate_color: Color
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_dir">
<return type="void" />
<description>
+ Export a [String] property as a path to a directory. The path will be limited to the project folder and its subfolders. See [annotation @export_global_dir] to allow picking from the entire filesystem.
+ See also [constant PROPERTY_HINT_DIR].
+ [codeblock]
+ @export_dir var sprite_folder: String
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_enum" qualifiers="vararg">
<return type="void" />
<param index="0" name="names" type="String" />
<description>
+ Export a [String] or integer property as an enumerated list of options. If the property is an integer field, then the index of the value is stored, in the same order the values are provided. You can add specific identifiers for allowed values using a colon.
+ See also [constant PROPERTY_HINT_ENUM].
+ [codeblock]
+ @export_enum("Rebecca", "Mary", "Leah") var character_name: String
+ @export_enum("Warrior", "Magician", "Thief") var character_class: int
+ @export_enum("Walking:30", "Running:60", "Riding:200") var character_speed: int
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_exp_easing" qualifiers="vararg">
<return type="void" />
<param index="0" name="hints" type="String" default="&quot;&quot;" />
<description>
+ Export a floating-point property with an easing editor widget. Additional hints can be provided to adjust the behavior of the widget. [code]"attenuation"[/code] flips the curve, which makes it more intuitive for editing attenuation properties. [code]"positive_only"[/code] limits values to only be greater than or equal to zero.
+ See also [constant PROPERTY_HINT_EXP_EASING].
+ [codeblock]
+ @export_exp_easing var transition_speed
+ @export_exp_easing("attenuation") var fading_attenuation
+ @export_exp_easing("positive_only") var effect_power
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_file" qualifiers="vararg">
<return type="void" />
<param index="0" name="filter" type="String" default="&quot;&quot;" />
<description>
+ Export a [String] property as a path to a file. The path will be limited to the project folder and its subfolders. See [annotation @export_global_file] to allow picking from the entire filesystem.
+ If [param filter] is provided, only matching files will be available for picking.
+ See also [constant PROPERTY_HINT_FILE].
+ [codeblock]
+ @export_file var sound_effect_file: String
+ @export_file("*.txt") var notes_file: String
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_flags" qualifiers="vararg">
<return type="void" />
<param index="0" name="names" type="String" />
<description>
+ Export an integer property as a bit flag field. This allows to store several "checked" or [code]true[/code] values with one property, and comfortably select them from the Inspector dock.
+ See also [constant PROPERTY_HINT_FLAGS].
+ [codeblock]
+ @export_flags("Fire", "Water", "Earth", "Wind") var spell_elements = 0
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_flags_2d_navigation">
<return type="void" />
<description>
+ Export an integer property as a bit flag field for 2D navigation layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/2d_navigation/layer_1].
+ See also [constant PROPERTY_HINT_LAYERS_2D_NAVIGATION].
+ [codeblock]
+ @export_flags_2d_navigation var navigation_layers: int
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_flags_2d_physics">
<return type="void" />
<description>
+ Export an integer property as a bit flag field for 2D physics layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/2d_physics/layer_1].
+ See also [constant PROPERTY_HINT_LAYERS_2D_PHYSICS].
+ [codeblock]
+ @export_flags_2d_physics var physics_layers: int
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_flags_2d_render">
<return type="void" />
<description>
+ Export an integer property as a bit flag field for 2D render layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/2d_render/layer_1].
+ See also [constant PROPERTY_HINT_LAYERS_2D_RENDER].
+ [codeblock]
+ @export_flags_2d_render var render_layers: int
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_flags_3d_navigation">
<return type="void" />
<description>
+ Export an integer property as a bit flag field for 3D navigation layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/3d_navigation/layer_1].
+ See also [constant PROPERTY_HINT_LAYERS_3D_NAVIGATION].
+ [codeblock]
+ @export_flags_3d_navigation var navigation_layers: int
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_flags_3d_physics">
<return type="void" />
<description>
+ Export an integer property as a bit flag field for 3D physics layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/3d_physics/layer_1].
+ See also [constant PROPERTY_HINT_LAYERS_3D_PHYSICS].
+ [codeblock]
+ @export_flags_3d_physics var physics_layers: int
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_flags_3d_render">
<return type="void" />
<description>
+ Export an integer property as a bit flag field for 3D render layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/3d_render/layer_1].
+ See also [constant PROPERTY_HINT_LAYERS_3D_RENDER].
+ [codeblock]
+ @export_flags_3d_render var render_layers: int
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_global_dir">
<return type="void" />
<description>
+ Export a [String] property as a path to a directory. The path can be picked from the entire filesystem. See [annotation @export_dir] to limit it to the project folder and its subfolders.
+ See also [constant PROPERTY_HINT_GLOBAL_DIR].
+ [codeblock]
+ @export_global_dir var sprite_folder: String
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_global_file" qualifiers="vararg">
<return type="void" />
<param index="0" name="filter" type="String" default="&quot;&quot;" />
<description>
+ Export a [String] property as a path to a file. The path can be picked from the entire filesystem. See [annotation @export_file] to limit it to the project folder and its subfolders.
+ If [param filter] is provided, only matching files will be available for picking.
+ See also [constant PROPERTY_HINT_GLOBAL_FILE].
+ [codeblock]
+ @export_global_file var sound_effect_file: String
+ @export_global_file("*.txt") var notes_file: String
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_group">
@@ -355,22 +447,54 @@
<param index="0" name="name" type="String" />
<param index="1" name="prefix" type="String" default="&quot;&quot;" />
<description>
+ Define a new group for the following exported properties. This helps to organize properties in the Inspector dock. Groups can be added with an optional [param prefix], which would make group to only consider properties that have this prefix. The grouping will break on the first property that doesn't have a prefix. The prefix is also removed from the property's name in the Inspector dock.
+ If no [param prefix] is provided, the every following property is added to the group. The group ends when then next group or category is defined. You can also force end a group by using this annotation with empty strings for paramters, [code]@export_group("", "")[/code].
+ Groups cannot be nested, use [annotation @export_subgroup] to add subgroups to your groups.
+ See also [constant PROPERTY_USAGE_GROUP].
+ [codeblock]
+ @export_group("My Properties")
+ @export var number = 3
+ @export var string = ""
+
+ @export_group("Prefixed Properties", "prefix_")
+ @export var prefix_number = 3
+ @export var prefix_string = ""
+
+ @export_group("", "")
+ @export var ungrouped_number = 3
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_multiline">
<return type="void" />
<description>
+ Export a [String] property with a large [TextEdit] widget instead of a [LineEdit]. This adds support for multiline content and makes it easier to edit large amount of text stored in the property.
+ See also [constant PROPERTY_HINT_MULTILINE_TEXT].
+ [codeblock]
+ @export_multiline var character_bio
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_node_path" qualifiers="vararg">
<return type="void" />
<param index="0" name="type" type="String" default="&quot;&quot;" />
<description>
+ Export a [NodePath] property with a filter for allowed node types.
+ See also [constant PROPERTY_HINT_NODE_PATH_VALID_TYPES].
+ [codeblock]
+ @export_node_path(Button, TouchScreenButton) var some_button
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_placeholder">
<return type="void" />
+ <param index="0" name="placeholder" type="String" />
<description>
+ Export a [String] property with a placeholder text displayed in the editor widget when no value is present.
+ See also [constant PROPERTY_HINT_PLACEHOLDER_TEXT].
+ [codeblock]
+ @export_placeholder("Name in lowercase") var character_id: String
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_range" qualifiers="vararg">
@@ -380,6 +504,22 @@
<param index="2" name="step" type="float" default="1.0" />
<param index="3" name="extra_hints" type="String" default="&quot;&quot;" />
<description>
+ Export a numeric property as a range value. The range must be defined by [param min] and [param max], as well as an optional [param step] and a variety of extra hints. The [param step] defaults to [code]1[/code] for integer properties. For floating-point numbers this value depends on your [code]EditorSettings.interface/inspector/default_float_step[/code] setting.
+ If hints [code]"or_greater"[/code] and [code]"or_lesser"[/code] are provided, the editor widget will not cap the value at range boundaries. The [code]"exp"[/code] hint will make the edited values on range to change exponentially. The [code]"no_slider"[/code] hint will hide the slider element of the editor widget.
+ Hints also allow to indicate the units for the edited value. Using [code]"radians"[/code] you can specify that the actual value is in radians, but should be displayed in degrees in the Inspector dock. [code]"degrees"[/code] allows to add a degree sign as a unit suffix. Finally, a custom suffix can be provided using [code]"suffix:unit"[/code], where "unit" can be any string.
+ See also [constant PROPERTY_HINT_RANGE].
+ [codeblock]
+ @export_range(0, 20) var number
+ @export_range(-10, 20) var number
+ @export_range(-10, 20, 0.2) var number: float
+
+ @export_range(0, 100, 1, "or_greater") var power_percent
+ @export_range(0, 100, 1, "or_greater", "or_lesser") var health_delta
+
+ @export_range(-3.14, 3.14, 0.001, "radians") var angle_radians
+ @export_range(0, 360, 1, "degrees") var angle_degrees
+ @export_range(-8, 8, 2, "suffix:px") var target_offset
+ [/codeblock]
</description>
</annotation>
<annotation name="@export_subgroup">
@@ -387,17 +527,38 @@
<param index="0" name="name" type="String" />
<param index="1" name="prefix" type="String" default="&quot;&quot;" />
<description>
+ Define a new subgroup for the following exported properties. This helps to organize properties in the Inspector dock. Subgroups work exactly like groups, except they need a parent group to exist. See [annotation @export_group].
+ See also [constant PROPERTY_USAGE_SUBGROUP].
+ [codeblock]
+ @export_group("My Properties")
+ @export var number = 3
+ @export var string = ""
+
+ @export_subgroup("My Prefixed Properties", "prefix_")
+ @export var prefix_number = 3
+ @export var prefix_string = ""
+ [/codeblock]
+ [b]Note:[/b] Subgroups cannot be nested, they only provide one extra level of depth. Just like the next group ends the previous group, so do the subsequent subgroups.
</description>
</annotation>
<annotation name="@icon">
<return type="void" />
<param index="0" name="icon_path" type="String" />
<description>
+ Add a custom icon to the current script. The icon is displayed in the Scene dock for every node that the script is attached to. For named classes the icon is also displayed in various editor dialogs.
+ [codeblock]
+ @icon("res://path/to/class/icon.svg")
+ [/codeblock]
+ [b]Note:[/b] Only the script can have a custom icon. Inner classes are not supported yet.
</description>
</annotation>
<annotation name="@onready">
<return type="void" />
<description>
+ Mark the following property as assigned on [Node]'s ready state change. Values for these properties are no assigned immediately upon the node's creation, and instead are computed and stored right before [method Node._ready].
+ [codeblock]
+ @onready var character_name: Label = $Label
+ [/codeblock]
</description>
</annotation>
<annotation name="@rpc" qualifiers="vararg">
@@ -407,17 +568,34 @@
<param index="2" name="transfer_mode" type="String" default="&quot;&quot;" />
<param index="3" name="transfer_channel" type="int" default="0" />
<description>
+ Mark the following method for remote procedure calls. See [url=$DOCS_URL/tutorials/networking/high_level_multiplayer.html]High-level multiplayer[/url].
+ [codeblock]
+ @rpc()
+ [/codeblock]
</description>
</annotation>
<annotation name="@tool">
<return type="void" />
<description>
+ Mark the current script as a tool script, allowing it to be loaded and executed by the editor. See [url=$DOCS_URL/tutorials/plugins/running_code_in_the_editor.html]Running code in the editor[/url].
+ [codeblock]
+ @tool
+ extends Node
+ [/codeblock]
</description>
</annotation>
<annotation name="@warning_ignore" qualifiers="vararg">
<return type="void" />
<param index="0" name="warning" type="String" />
<description>
+ Mark the following statement to ignore the specified warning. See [url=$DOCS_URL/tutorials/scripting/gdscript/warning_system.html]GDScript warning system[/url].
+ [codeblock]
+ func test():
+ print("hello")
+ return
+ @warning_ignore("unreachable_code")
+ print("unreachable")
+ [/codeblock]
</description>
</annotation>
</annotations>
diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp
index a23f19de85..b9560ea69b 100644
--- a/modules/gdscript/editor/gdscript_highlighter.cpp
+++ b/modules/gdscript/editor/gdscript_highlighter.cpp
@@ -46,6 +46,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
bool prev_is_char = false;
bool prev_is_number = false;
+ bool prev_is_binary_op = false;
bool in_keyword = false;
bool in_word = false;
bool in_function_name = false;
@@ -84,16 +85,17 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
const int line_length = str.length();
Color prev_color;
- if (in_region != -1 && str.length() == 0) {
+ if (in_region != -1 && line_length == 0) {
color_region_cache[p_line] = in_region;
}
- for (int j = 0; j < str.length(); j++) {
+ for (int j = 0; j < line_length; j++) {
Dictionary highlighter_info;
color = font_color;
bool is_char = !is_symbol(str[j]);
bool is_a_symbol = is_symbol(str[j]);
bool is_number = is_digit(str[j]);
+ bool is_binary_op = false;
/* color regions */
if (is_a_symbol || in_region != -1) {
@@ -244,7 +246,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
is_hex_notation = false;
}
- // disallow anything not a 0 or 1
+ // disallow anything not a 0 or 1 in binary notation
if (is_bin_notation && (is_binary_digit(str[j]))) {
is_number = true;
} else if (is_bin_notation) {
@@ -285,7 +287,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
if (!in_keyword && is_char && !prev_is_char) {
int to = j;
- while (to < str.length() && !is_symbol(str[to])) {
+ while (to < line_length && !is_symbol(str[to])) {
to++;
}
@@ -318,12 +320,12 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
in_signal_declaration = true;
} else {
int k = j;
- while (k < str.length() && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
+ while (k < line_length && !is_symbol(str[k]) && !is_whitespace(str[k])) {
k++;
}
// check for space between name and bracket
- while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) {
+ while (k < line_length && is_whitespace(str[k])) {
k++;
}
@@ -336,7 +338,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
// Check for lambda.
if (in_function_name && previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) {
k = j - 1;
- while (k > 0 && (str[k] == '\t' || str[k] == ' ')) {
+ while (k > 0 && is_whitespace(str[k])) {
k--;
}
@@ -349,7 +351,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
if (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) {
int k = j;
- while (k > 0 && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
+ while (k > 0 && !is_symbol(str[k]) && !is_whitespace(str[k])) {
k--;
}
@@ -378,7 +380,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
if (in_variable_declaration || in_function_args) {
int k = j;
// Skip space
- while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) {
+ while (k < line_length && is_whitespace(str[k])) {
k++;
}
@@ -395,13 +397,41 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
in_member_variable = false;
}
- if (!in_node_path && in_region == -1 && (str[j] == '^')) {
+ if (j > 0 && (str[j] == '&' || str[j] == '^' || str[j] == '%' || str[j] == '+' || str[j] == '-' || str[j] == '~')) {
+ int k = j - 1;
+ while (k > 0 && is_whitespace(str[k])) {
+ k--;
+ }
+ if (!is_symbol(str[k]) || str[k] == '"' || str[k] == '\'' || str[k] == ')' || str[k] == ']' || str[k] == '}') {
+ is_binary_op = true;
+ }
+ }
+
+ // Highlight '+' and '-' like numbers when unary
+ if ((str[j] == '+' || str[j] == '-' || str[j] == '~') && !is_binary_op) {
+ is_number = true;
+ is_a_symbol = false;
+ }
+
+ // Keep symbol color for binary '&&'. In the case of '&&&' use StringName color for the last ampersand
+ if (!in_string_name && in_region == -1 && str[j] == '&' && !is_binary_op) {
+ if (j >= 2 && str[j - 1] == '&' && str[j - 2] != '&' && prev_is_binary_op) {
+ is_binary_op = true;
+ } else if (j == 0 || (j > 0 && str[j - 1] != '&') || prev_is_binary_op) {
+ in_string_name = true;
+ }
+ } else if (in_region != -1 || is_a_symbol) {
+ in_string_name = false;
+ }
+
+ // '^^' has no special meaning, so unlike StringName, when binary, use NodePath color for the last caret
+ if (!in_node_path && in_region == -1 && str[j] == '^' && !is_binary_op && (j == 0 || (j > 0 && str[j - 1] != '^') || prev_is_binary_op)) {
in_node_path = true;
- } else if (in_region != -1 || (is_a_symbol && str[j] != '/' && str[j] != '%')) {
+ } else if (in_region != -1 || is_a_symbol) {
in_node_path = false;
}
- if (!in_node_ref && in_region == -1 && (str[j] == '$' || str[j] == '%')) {
+ if (!in_node_ref && in_region == -1 && (str[j] == '$' || (str[j] == '%' && !is_binary_op))) {
in_node_ref = true;
} else if (in_region != -1 || (is_a_symbol && str[j] != '/' && str[j] != '%')) {
in_node_ref = false;
@@ -413,16 +443,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
in_annotation = false;
}
- if (!in_string_name && in_region == -1 && str[j] == '&') {
- in_string_name = true;
- } else if (in_region != -1 || is_a_symbol) {
- in_string_name = false;
- }
-
- if (in_node_path) {
- next_type = NODE_PATH;
- color = node_path_color;
- } else if (in_node_ref) {
+ if (in_node_ref) {
next_type = NODE_REF;
color = node_ref_color;
} else if (in_annotation) {
@@ -431,6 +452,9 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
} else if (in_string_name) {
next_type = STRING_NAME;
color = string_name_color;
+ } else if (in_node_path) {
+ next_type = NODE_PATH;
+ color = node_path_color;
} else if (in_keyword) {
next_type = KEYWORD;
color = keyword_color;
@@ -487,6 +511,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
prev_is_char = is_char;
prev_is_number = is_number;
+ prev_is_binary_op = is_binary_op;
if (color != prev_color) {
prev_color = color;
@@ -501,8 +526,8 @@ String GDScriptSyntaxHighlighter::_get_name() const {
return "GDScript";
}
-Array GDScriptSyntaxHighlighter::_get_supported_languages() const {
- Array languages;
+PackedStringArray GDScriptSyntaxHighlighter::_get_supported_languages() const {
+ PackedStringArray languages;
languages.push_back("GDScript");
return languages;
}
@@ -621,13 +646,13 @@ void GDScriptSyntaxHighlighter::_update_cache() {
node_path_color = Color(0.72, 0.77, 0.49);
node_ref_color = Color(0.39, 0.76, 0.35);
annotation_color = Color(1.0, 0.7, 0.45);
- string_name_color = Color(1.0, 0.66, 0.72);
+ string_name_color = Color(1.0, 0.76, 0.65);
} else {
function_definition_color = Color(0, 0.6, 0.6);
node_path_color = Color(0.18, 0.55, 0);
node_ref_color = Color(0.0, 0.5, 0);
annotation_color = Color(0.8, 0.37, 0);
- string_name_color = Color(0.8, 0.46, 0.52);
+ string_name_color = Color(0.8, 0.56, 0.45);
}
EDITOR_DEF("text_editor/theme/highlighting/gdscript/function_definition_color", function_definition_color);
diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h
index 7987582f07..f434d03a31 100644
--- a/modules/gdscript/editor/gdscript_highlighter.h
+++ b/modules/gdscript/editor/gdscript_highlighter.h
@@ -88,7 +88,7 @@ public:
virtual Dictionary _get_line_syntax_highlighting_impl(int p_line) override;
virtual String _get_name() const override;
- virtual Array _get_supported_languages() const override;
+ virtual PackedStringArray _get_supported_languages() const override;
virtual Ref<EditorSyntaxHighlighter> _create() const override;
};
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index 8a5e93eeff..cf2d6ae9f8 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -1538,6 +1538,47 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const
}
}
+bool GDScriptInstance::property_can_revert(const StringName &p_name) const {
+ Variant name = p_name;
+ const Variant *args[1] = { &name };
+
+ const GDScript *sptr = script.ptr();
+ while (sptr) {
+ HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_can_revert);
+ if (E) {
+ Callable::CallError err;
+ Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
+ if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) {
+ return true;
+ }
+ }
+ sptr = sptr->_base;
+ }
+
+ return false;
+}
+
+bool GDScriptInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
+ Variant name = p_name;
+ const Variant *args[1] = { &name };
+
+ const GDScript *sptr = script.ptr();
+ while (sptr) {
+ HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_get_revert);
+ if (E) {
+ Callable::CallError err;
+ Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err);
+ if (err.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
+ r_ret = ret;
+ return true;
+ }
+ }
+ sptr = sptr->_base;
+ }
+
+ return false;
+}
+
void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
const GDScript *sptr = script.ptr();
while (sptr) {
@@ -2248,6 +2289,8 @@ GDScriptLanguage::GDScriptLanguage() {
strings._set = StaticCString::create("_set");
strings._get = StaticCString::create("_get");
strings._get_property_list = StaticCString::create("_get_property_list");
+ strings._property_can_revert = StaticCString::create("_property_can_revert");
+ strings._property_get_revert = StaticCString::create("_property_get_revert");
strings._script_source = StaticCString::create("script/source");
_debug_parse_err_line = -1;
_debug_parse_err_file = "";
diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h
index 5123cccddd..e4b12d4ddb 100644
--- a/modules/gdscript/gdscript.h
+++ b/modules/gdscript/gdscript.h
@@ -287,6 +287,9 @@ public:
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 bool property_can_revert(const StringName &p_name) const;
+ virtual bool property_get_revert(const StringName &p_name, Variant &r_ret) const;
+
virtual void get_method_list(List<MethodInfo> *p_list) const;
virtual bool has_method(const StringName &p_method) const;
virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);
@@ -423,6 +426,8 @@ public:
StringName _set;
StringName _get;
StringName _get_property_list;
+ StringName _property_can_revert;
+ StringName _property_get_revert;
StringName _script_source;
} strings;
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index 6f5397e1a3..6b6ad427a7 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -127,7 +127,7 @@ GDScriptParser::GDScriptParser() {
register_annotation(MethodInfo("@export_global_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, varray(""), true);
register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>);
register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>);
- register_annotation(MethodInfo("@export_placeholder"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
+ register_annotation(MethodInfo("@export_placeholder", PropertyInfo(Variant::STRING, "placeholder")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
register_annotation(MethodInfo("@export_range", PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"), PropertyInfo(Variant::FLOAT, "step"), PropertyInfo(Variant::STRING, "extra_hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, varray(1.0, ""), true);
register_annotation(MethodInfo("@export_exp_easing", PropertyInfo(Variant::STRING, "hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, varray(""), true);
register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>);
diff --git a/modules/gdscript/gdscript_utility_functions.cpp b/modules/gdscript/gdscript_utility_functions.cpp
index 4b97486cb3..38893a422d 100644
--- a/modules/gdscript/gdscript_utility_functions.cpp
+++ b/modules/gdscript/gdscript_utility_functions.cpp
@@ -36,6 +36,7 @@
#include "core/object/object.h"
#include "core/templates/oa_hash_map.h"
#include "core/templates/vector.h"
+#include "core/variant/typed_array.h"
#include "gdscript.h"
#ifdef DEBUG_ENABLED
@@ -468,12 +469,12 @@ struct GDScriptUtilityFunctionsDefinitions {
static inline void get_stack(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
VALIDATE_ARG_COUNT(0);
if (Thread::get_caller_id() != Thread::get_main_id()) {
- *r_ret = Array();
+ *r_ret = TypedArray<Dictionary>();
return;
}
ScriptLanguage *script = GDScriptLanguage::get_singleton();
- Array ret;
+ TypedArray<Dictionary> ret;
for (int i = 0; i < script->debug_get_stack_level_count(); i++) {
Dictionary frame;
frame["source"] = script->debug_get_stack_level_source(i);
diff --git a/modules/gdscript/gdscript_utility_functions.h b/modules/gdscript/gdscript_utility_functions.h
index 9ca7cf33d8..0f07db857f 100644
--- a/modules/gdscript/gdscript_utility_functions.h
+++ b/modules/gdscript/gdscript_utility_functions.h
@@ -34,6 +34,9 @@
#include "core/string/string_name.h"
#include "core/variant/variant.h"
+template <typename T>
+class TypedArray;
+
class GDScriptUtilityFunctions {
public:
typedef void (*FunctionPtr)(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error);
diff --git a/modules/gltf/doc_classes/GLTFCamera.xml b/modules/gltf/doc_classes/GLTFCamera.xml
index 9b9eff6141..b90abd105d 100644
--- a/modules/gltf/doc_classes/GLTFCamera.xml
+++ b/modules/gltf/doc_classes/GLTFCamera.xml
@@ -1,19 +1,30 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="GLTFCamera" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
<brief_description>
+ Represents a GLTF camera.
</brief_description>
<description>
+ Represents a camera as defined by the base GLTF spec.
</description>
<tutorials>
+ <link title="GLTF camera detailed specification">https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-camera</link>
+ <link title="GLTF camera spec and example file">https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_015_SimpleCameras.md</link>
</tutorials>
<members>
<member name="depth_far" type="float" setter="set_depth_far" getter="get_depth_far" default="4000.0">
+ The distance to the far culling boundary for this camera relative to its local Z axis, in meters. This maps to GLTF's [code]zfar[/code] property.
</member>
<member name="depth_near" type="float" setter="set_depth_near" getter="get_depth_near" default="0.05">
+ The distance to the near culling boundary for this camera relative to its local Z axis, in meters. This maps to GLTF's [code]znear[/code] property.
</member>
- <member name="fov_size" type="float" setter="set_fov_size" getter="get_fov_size" default="75.0">
+ <member name="fov" type="float" setter="set_fov" getter="get_fov" default="1.309">
+ The FOV of the camera. This class and GLTF define the camera FOV in radians, while Godot uses degrees. This maps to GLTF's [code]yfov[/code] property. This value is only used for perspective cameras, when [member perspective] is true.
</member>
<member name="perspective" type="bool" setter="set_perspective" getter="get_perspective" default="true">
+ Whether or not the camera is in perspective mode. If false, the camera is in orthographic/orthogonal mode. This maps to GLTF's camera [code]type[/code] property. See [member Camera3D.projection] and the GLTF spec for more information.
+ </member>
+ <member name="size_mag" type="float" setter="set_size_mag" getter="get_size_mag" default="0.5">
+ The size of the camera. This class and GLTF define the camera size magnitude as a radius in meters, while Godot defines it as a diameter in meters. This maps to GLTF's [code]ymag[/code] property. This value is only used for orthographic/orthogonal cameras, when [member perspective] is false.
</member>
</members>
</class>
diff --git a/modules/gltf/doc_classes/GLTFSkeleton.xml b/modules/gltf/doc_classes/GLTFSkeleton.xml
index e1276d0e21..d6ec09f113 100644
--- a/modules/gltf/doc_classes/GLTFSkeleton.xml
+++ b/modules/gltf/doc_classes/GLTFSkeleton.xml
@@ -29,7 +29,7 @@
</description>
</method>
<method name="get_unique_names">
- <return type="Array" />
+ <return type="String[]" />
<description>
</description>
</method>
@@ -41,7 +41,7 @@
</method>
<method name="set_unique_names">
<return type="void" />
- <param index="0" name="unique_names" type="Array" />
+ <param index="0" name="unique_names" type="String[]" />
<description>
</description>
</method>
diff --git a/modules/gltf/doc_classes/GLTFSkin.xml b/modules/gltf/doc_classes/GLTFSkin.xml
index 5abdf33360..4de32857b5 100644
--- a/modules/gltf/doc_classes/GLTFSkin.xml
+++ b/modules/gltf/doc_classes/GLTFSkin.xml
@@ -8,7 +8,7 @@
</tutorials>
<methods>
<method name="get_inverse_binds">
- <return type="Array" />
+ <return type="Transform3D[]" />
<description>
</description>
</method>
@@ -24,7 +24,7 @@
</method>
<method name="set_inverse_binds">
<return type="void" />
- <param index="0" name="inverse_binds" type="Array" />
+ <param index="0" name="inverse_binds" type="Transform3D[]" />
<description>
</description>
</method>
diff --git a/modules/gltf/doc_classes/GLTFState.xml b/modules/gltf/doc_classes/GLTFState.xml
index adf51ab59e..1dbd89aed8 100644
--- a/modules/gltf/doc_classes/GLTFState.xml
+++ b/modules/gltf/doc_classes/GLTFState.xml
@@ -8,7 +8,7 @@
</tutorials>
<methods>
<method name="get_accessors">
- <return type="Array" />
+ <return type="GLTFAccessor[]" />
<description>
</description>
</method>
@@ -25,42 +25,42 @@
</description>
</method>
<method name="get_animations">
- <return type="Array" />
+ <return type="GLTFAnimation[]" />
<description>
</description>
</method>
<method name="get_buffer_views">
- <return type="Array" />
+ <return type="GLTFBufferView[]" />
<description>
</description>
</method>
<method name="get_cameras">
- <return type="Array" />
+ <return type="GLTFCamera[]" />
<description>
</description>
</method>
<method name="get_images">
- <return type="Array" />
+ <return type="Texture2D[]" />
<description>
</description>
</method>
<method name="get_lights">
- <return type="Array" />
+ <return type="GLTFLight[]" />
<description>
</description>
</method>
<method name="get_materials">
- <return type="Array" />
+ <return type="BaseMaterial3D[]" />
<description>
</description>
</method>
<method name="get_meshes">
- <return type="Array" />
+ <return type="GLTFMesh[]" />
<description>
</description>
</method>
<method name="get_nodes">
- <return type="Array" />
+ <return type="GLTFNode[]" />
<description>
</description>
</method>
@@ -76,81 +76,81 @@
</description>
</method>
<method name="get_skeletons">
- <return type="Array" />
+ <return type="GLTFSkeleton[]" />
<description>
</description>
</method>
<method name="get_skins">
- <return type="Array" />
+ <return type="GLTFSkin[]" />
<description>
</description>
</method>
<method name="get_textures">
- <return type="Array" />
+ <return type="GLTFTexture[]" />
<description>
</description>
</method>
<method name="get_unique_animation_names">
- <return type="Array" />
+ <return type="String[]" />
<description>
</description>
</method>
<method name="get_unique_names">
- <return type="Array" />
+ <return type="String[]" />
<description>
</description>
</method>
<method name="set_accessors">
<return type="void" />
- <param index="0" name="accessors" type="Array" />
+ <param index="0" name="accessors" type="GLTFAccessor[]" />
<description>
</description>
</method>
<method name="set_animations">
<return type="void" />
- <param index="0" name="animations" type="Array" />
+ <param index="0" name="animations" type="GLTFAnimation[]" />
<description>
</description>
</method>
<method name="set_buffer_views">
<return type="void" />
- <param index="0" name="buffer_views" type="Array" />
+ <param index="0" name="buffer_views" type="GLTFBufferView[]" />
<description>
</description>
</method>
<method name="set_cameras">
<return type="void" />
- <param index="0" name="cameras" type="Array" />
+ <param index="0" name="cameras" type="GLTFCamera[]" />
<description>
</description>
</method>
<method name="set_images">
<return type="void" />
- <param index="0" name="images" type="Array" />
+ <param index="0" name="images" type="Texture2D[]" />
<description>
</description>
</method>
<method name="set_lights">
<return type="void" />
- <param index="0" name="lights" type="Array" />
+ <param index="0" name="lights" type="GLTFLight[]" />
<description>
</description>
</method>
<method name="set_materials">
<return type="void" />
- <param index="0" name="materials" type="Array" />
+ <param index="0" name="materials" type="BaseMaterial3D[]" />
<description>
</description>
</method>
<method name="set_meshes">
<return type="void" />
- <param index="0" name="meshes" type="Array" />
+ <param index="0" name="meshes" type="GLTFMesh[]" />
<description>
</description>
</method>
<method name="set_nodes">
<return type="void" />
- <param index="0" name="nodes" type="Array" />
+ <param index="0" name="nodes" type="GLTFNode[]" />
<description>
</description>
</method>
@@ -162,31 +162,31 @@
</method>
<method name="set_skeletons">
<return type="void" />
- <param index="0" name="skeletons" type="Array" />
+ <param index="0" name="skeletons" type="GLTFSkeleton[]" />
<description>
</description>
</method>
<method name="set_skins">
<return type="void" />
- <param index="0" name="skins" type="Array" />
+ <param index="0" name="skins" type="GLTFSkin[]" />
<description>
</description>
</method>
<method name="set_textures">
<return type="void" />
- <param index="0" name="textures" type="Array" />
+ <param index="0" name="textures" type="GLTFTexture[]" />
<description>
</description>
</method>
<method name="set_unique_animation_names">
<return type="void" />
- <param index="0" name="unique_animation_names" type="Array" />
+ <param index="0" name="unique_animation_names" type="String[]" />
<description>
</description>
</method>
<method name="set_unique_names">
<return type="void" />
- <param index="0" name="unique_names" type="Array" />
+ <param index="0" name="unique_names" type="String[]" />
<description>
</description>
</method>
@@ -194,7 +194,7 @@
<members>
<member name="base_path" type="String" setter="set_base_path" getter="get_base_path" default="&quot;&quot;">
</member>
- <member name="buffers" type="Array" setter="set_buffers" getter="get_buffers" default="[]">
+ <member name="buffers" type="PackedByteArray[]" setter="set_buffers" getter="get_buffers" default="[]">
</member>
<member name="create_animations" type="bool" setter="set_create_animations" getter="get_create_animations" default="true">
</member>
@@ -206,7 +206,7 @@
</member>
<member name="minor_version" type="int" setter="set_minor_version" getter="get_minor_version" default="0">
</member>
- <member name="root_nodes" type="Array" setter="set_root_nodes" getter="get_root_nodes" default="[]">
+ <member name="root_nodes" type="PackedInt32Array" setter="set_root_nodes" getter="get_root_nodes" default="PackedInt32Array()">
</member>
<member name="scene_name" type="String" setter="set_scene_name" getter="get_scene_name" default="&quot;&quot;">
</member>
diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp
index d102970932..b913a771e1 100644
--- a/modules/gltf/gltf_document.cpp
+++ b/modules/gltf/gltf_document.cpp
@@ -50,7 +50,6 @@
#include "core/version.h"
#include "drivers/png/png_driver_common.h"
#include "scene/2d/node_2d.h"
-#include "scene/3d/camera_3d.h"
#include "scene/3d/mesh_instance_3d.h"
#include "scene/3d/multimesh_instance_3d.h"
#include "scene/3d/node_3d.h"
@@ -4582,22 +4581,21 @@ Error GLTFDocument::_serialize_cameras(Ref<GLTFState> state) {
Ref<GLTFCamera> camera = state->cameras[i];
- if (camera->get_perspective() == false) {
- Dictionary og;
- og["ymag"] = Math::deg2rad(camera->get_fov_size());
- og["xmag"] = Math::deg2rad(camera->get_fov_size());
- og["zfar"] = camera->get_depth_far();
- og["znear"] = camera->get_depth_near();
- d["orthographic"] = og;
- d["type"] = "orthographic";
- } else if (camera->get_perspective()) {
- Dictionary ppt;
- // GLTF spec is in radians, Godot's camera is in degrees.
- ppt["yfov"] = Math::deg2rad(camera->get_fov_size());
- ppt["zfar"] = camera->get_depth_far();
- ppt["znear"] = camera->get_depth_near();
- d["perspective"] = ppt;
+ if (camera->get_perspective()) {
+ Dictionary persp;
+ persp["yfov"] = camera->get_fov();
+ persp["zfar"] = camera->get_depth_far();
+ persp["znear"] = camera->get_depth_near();
+ d["perspective"] = persp;
d["type"] = "perspective";
+ } else {
+ Dictionary ortho;
+ ortho["ymag"] = camera->get_size_mag();
+ ortho["xmag"] = camera->get_size_mag();
+ ortho["zfar"] = camera->get_depth_far();
+ ortho["znear"] = camera->get_depth_near();
+ d["orthographic"] = ortho;
+ d["type"] = "orthographic";
}
cameras[i] = d;
}
@@ -4680,27 +4678,23 @@ Error GLTFDocument::_parse_cameras(Ref<GLTFState> state) {
camera.instantiate();
ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
const String &type = d["type"];
- if (type == "orthographic") {
- camera->set_perspective(false);
- if (d.has("orthographic")) {
- const Dictionary &og = d["orthographic"];
- // GLTF spec is in radians, Godot's camera is in degrees.
- camera->set_fov_size(Math::rad2deg(real_t(og["ymag"])));
- camera->set_depth_far(og["zfar"]);
- camera->set_depth_near(og["znear"]);
- } else {
- camera->set_fov_size(10);
- }
- } else if (type == "perspective") {
+ if (type == "perspective") {
camera->set_perspective(true);
if (d.has("perspective")) {
- const Dictionary &ppt = d["perspective"];
- // GLTF spec is in radians, Godot's camera is in degrees.
- camera->set_fov_size(Math::rad2deg(real_t(ppt["yfov"])));
- camera->set_depth_far(ppt["zfar"]);
- camera->set_depth_near(ppt["znear"]);
- } else {
- camera->set_fov_size(10);
+ const Dictionary &persp = d["perspective"];
+ camera->set_fov(persp["yfov"]);
+ if (persp.has("zfar")) {
+ camera->set_depth_far(persp["zfar"]);
+ }
+ camera->set_depth_near(persp["znear"]);
+ }
+ } else if (type == "orthographic") {
+ camera->set_perspective(false);
+ if (d.has("orthographic")) {
+ const Dictionary &ortho = d["orthographic"];
+ camera->set_size_mag(ortho["ymag"]);
+ camera->set_depth_far(ortho["zfar"]);
+ camera->set_depth_near(ortho["znear"]);
}
} else {
ERR_FAIL_V_MSG(ERR_PARSE_ERROR, "Camera3D should be in 'orthographic' or 'perspective'");
@@ -5204,12 +5198,13 @@ Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> state, const GLTFNodeInd
print_verbose("glTF: Creating camera for: " + gltf_node->get_name());
Ref<GLTFCamera> c = state->cameras[gltf_node->camera];
- if (c->get_perspective()) {
- camera->set_perspective(c->get_fov_size(), c->get_depth_near(), c->get_depth_far());
- } else {
- camera->set_orthogonal(c->get_fov_size(), c->get_depth_near(), c->get_depth_far());
- }
-
+ camera->set_projection(c->get_perspective() ? Camera3D::PROJECTION_PERSPECTIVE : Camera3D::PROJECTION_ORTHOGONAL);
+ // GLTF spec (yfov) is in radians, Godot's camera (fov) is in degrees.
+ camera->set_fov(Math::rad2deg(c->get_fov()));
+ // GLTF spec (xmag and ymag) is a radius in meters, Godot's camera (size) is a diameter in meters.
+ camera->set_size(c->get_size_mag() * 2.0f);
+ camera->set_near(c->get_depth_near());
+ camera->set_far(c->get_depth_far());
return camera;
}
@@ -5218,11 +5213,11 @@ GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> state, Camera3D *p_
Ref<GLTFCamera> c;
c.instantiate();
-
- if (p_camera->get_projection() == Camera3D::ProjectionType::PROJECTION_PERSPECTIVE) {
- c->set_perspective(true);
- }
- c->set_fov_size(p_camera->get_fov());
+ c->set_perspective(p_camera->get_projection() == Camera3D::ProjectionType::PROJECTION_PERSPECTIVE);
+ // GLTF spec (yfov) is in radians, Godot's camera (fov) is in degrees.
+ c->set_fov(Math::deg2rad(p_camera->get_fov()));
+ // GLTF spec (xmag and ymag) is a radius in meters, Godot's camera (size) is a diameter in meters.
+ c->set_size_mag(p_camera->get_size() * 0.5f);
c->set_depth_far(p_camera->get_far());
c->set_depth_near(p_camera->get_near());
GLTFCameraIndex camera_index = state->cameras.size();
@@ -5442,7 +5437,7 @@ void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex
int32_t cell = p_grid_map->get_cell_item(
Vector3(cell_location.x, cell_location.y, cell_location.z));
Transform3D cell_xform;
- cell_xform.basis.set_orthogonal_index(
+ cell_xform.basis = p_grid_map->get_basis_with_orthogonal_index(
p_grid_map->get_cell_item_orientation(
Vector3(cell_location.x, cell_location.y, cell_location.z)));
cell_xform.basis.scale(Vector3(p_grid_map->get_cell_scale(),
diff --git a/modules/gltf/gltf_state.cpp b/modules/gltf/gltf_state.cpp
index 8212e4c22f..85bac446cc 100644
--- a/modules/gltf/gltf_state.cpp
+++ b/modules/gltf/gltf_state.cpp
@@ -152,51 +152,51 @@ void GLTFState::set_use_named_skin_binds(bool p_use_named_skin_binds) {
use_named_skin_binds = p_use_named_skin_binds;
}
-Array GLTFState::get_nodes() {
+TypedArray<GLTFNode> GLTFState::get_nodes() {
return GLTFTemplateConvert::to_array(nodes);
}
-void GLTFState::set_nodes(Array p_nodes) {
+void GLTFState::set_nodes(TypedArray<GLTFNode> p_nodes) {
GLTFTemplateConvert::set_from_array(nodes, p_nodes);
}
-Array GLTFState::get_buffers() {
+TypedArray<PackedByteArray> GLTFState::get_buffers() {
return GLTFTemplateConvert::to_array(buffers);
}
-void GLTFState::set_buffers(Array p_buffers) {
+void GLTFState::set_buffers(TypedArray<PackedByteArray> p_buffers) {
GLTFTemplateConvert::set_from_array(buffers, p_buffers);
}
-Array GLTFState::get_buffer_views() {
+TypedArray<GLTFBufferView> GLTFState::get_buffer_views() {
return GLTFTemplateConvert::to_array(buffer_views);
}
-void GLTFState::set_buffer_views(Array p_buffer_views) {
+void GLTFState::set_buffer_views(TypedArray<GLTFBufferView> p_buffer_views) {
GLTFTemplateConvert::set_from_array(buffer_views, p_buffer_views);
}
-Array GLTFState::get_accessors() {
+TypedArray<GLTFAccessor> GLTFState::get_accessors() {
return GLTFTemplateConvert::to_array(accessors);
}
-void GLTFState::set_accessors(Array p_accessors) {
+void GLTFState::set_accessors(TypedArray<GLTFAccessor> p_accessors) {
GLTFTemplateConvert::set_from_array(accessors, p_accessors);
}
-Array GLTFState::get_meshes() {
+TypedArray<GLTFMesh> GLTFState::get_meshes() {
return GLTFTemplateConvert::to_array(meshes);
}
-void GLTFState::set_meshes(Array p_meshes) {
+void GLTFState::set_meshes(TypedArray<GLTFMesh> p_meshes) {
GLTFTemplateConvert::set_from_array(meshes, p_meshes);
}
-Array GLTFState::get_materials() {
+TypedArray<BaseMaterial3D> GLTFState::get_materials() {
return GLTFTemplateConvert::to_array(materials);
}
-void GLTFState::set_materials(Array p_materials) {
+void GLTFState::set_materials(TypedArray<BaseMaterial3D> p_materials) {
GLTFTemplateConvert::set_from_array(materials, p_materials);
}
@@ -208,75 +208,75 @@ void GLTFState::set_scene_name(String p_scene_name) {
scene_name = p_scene_name;
}
-Array GLTFState::get_root_nodes() {
- return GLTFTemplateConvert::to_array(root_nodes);
+PackedInt32Array GLTFState::get_root_nodes() {
+ return root_nodes;
}
-void GLTFState::set_root_nodes(Array p_root_nodes) {
- GLTFTemplateConvert::set_from_array(root_nodes, p_root_nodes);
+void GLTFState::set_root_nodes(PackedInt32Array p_root_nodes) {
+ root_nodes = p_root_nodes;
}
-Array GLTFState::get_textures() {
+TypedArray<GLTFTexture> GLTFState::get_textures() {
return GLTFTemplateConvert::to_array(textures);
}
-void GLTFState::set_textures(Array p_textures) {
+void GLTFState::set_textures(TypedArray<GLTFTexture> p_textures) {
GLTFTemplateConvert::set_from_array(textures, p_textures);
}
-Array GLTFState::get_images() {
+TypedArray<Texture2D> GLTFState::get_images() {
return GLTFTemplateConvert::to_array(images);
}
-void GLTFState::set_images(Array p_images) {
+void GLTFState::set_images(TypedArray<Texture2D> p_images) {
GLTFTemplateConvert::set_from_array(images, p_images);
}
-Array GLTFState::get_skins() {
+TypedArray<GLTFSkin> GLTFState::get_skins() {
return GLTFTemplateConvert::to_array(skins);
}
-void GLTFState::set_skins(Array p_skins) {
+void GLTFState::set_skins(TypedArray<GLTFSkin> p_skins) {
GLTFTemplateConvert::set_from_array(skins, p_skins);
}
-Array GLTFState::get_cameras() {
+TypedArray<GLTFCamera> GLTFState::get_cameras() {
return GLTFTemplateConvert::to_array(cameras);
}
-void GLTFState::set_cameras(Array p_cameras) {
+void GLTFState::set_cameras(TypedArray<GLTFCamera> p_cameras) {
GLTFTemplateConvert::set_from_array(cameras, p_cameras);
}
-Array GLTFState::get_lights() {
+TypedArray<GLTFLight> GLTFState::get_lights() {
return GLTFTemplateConvert::to_array(lights);
}
-void GLTFState::set_lights(Array p_lights) {
+void GLTFState::set_lights(TypedArray<GLTFLight> p_lights) {
GLTFTemplateConvert::set_from_array(lights, p_lights);
}
-Array GLTFState::get_unique_names() {
+TypedArray<String> GLTFState::get_unique_names() {
return GLTFTemplateConvert::to_array(unique_names);
}
-void GLTFState::set_unique_names(Array p_unique_names) {
+void GLTFState::set_unique_names(TypedArray<String> p_unique_names) {
GLTFTemplateConvert::set_from_array(unique_names, p_unique_names);
}
-Array GLTFState::get_unique_animation_names() {
+TypedArray<String> GLTFState::get_unique_animation_names() {
return GLTFTemplateConvert::to_array(unique_animation_names);
}
-void GLTFState::set_unique_animation_names(Array p_unique_animation_names) {
+void GLTFState::set_unique_animation_names(TypedArray<String> p_unique_animation_names) {
GLTFTemplateConvert::set_from_array(unique_animation_names, p_unique_animation_names);
}
-Array GLTFState::get_skeletons() {
+TypedArray<GLTFSkeleton> GLTFState::get_skeletons() {
return GLTFTemplateConvert::to_array(skeletons);
}
-void GLTFState::set_skeletons(Array p_skeletons) {
+void GLTFState::set_skeletons(TypedArray<GLTFSkeleton> p_skeletons) {
GLTFTemplateConvert::set_from_array(skeletons, p_skeletons);
}
@@ -296,11 +296,11 @@ void GLTFState::set_create_animations(bool p_create_animations) {
create_animations = p_create_animations;
}
-Array GLTFState::get_animations() {
+TypedArray<GLTFAnimation> GLTFState::get_animations() {
return GLTFTemplateConvert::to_array(animations);
}
-void GLTFState::set_animations(Array p_animations) {
+void GLTFState::set_animations(TypedArray<GLTFAnimation> p_animations) {
GLTFTemplateConvert::set_from_array(animations, p_animations);
}
diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h
index c08132f874..6b2d1ca228 100644
--- a/modules/gltf/gltf_state.h
+++ b/modules/gltf/gltf_state.h
@@ -115,23 +115,23 @@ public:
bool get_discard_meshes_and_materials();
void set_discard_meshes_and_materials(bool p_discard_meshes_and_materials);
- Array get_nodes();
- void set_nodes(Array p_nodes);
+ TypedArray<GLTFNode> get_nodes();
+ void set_nodes(TypedArray<GLTFNode> p_nodes);
- Array get_buffers();
- void set_buffers(Array p_buffers);
+ TypedArray<PackedByteArray> get_buffers();
+ void set_buffers(TypedArray<PackedByteArray> p_buffers);
- Array get_buffer_views();
- void set_buffer_views(Array p_buffer_views);
+ TypedArray<GLTFBufferView> get_buffer_views();
+ void set_buffer_views(TypedArray<GLTFBufferView> p_buffer_views);
- Array get_accessors();
- void set_accessors(Array p_accessors);
+ TypedArray<GLTFAccessor> get_accessors();
+ void set_accessors(TypedArray<GLTFAccessor> p_accessors);
- Array get_meshes();
- void set_meshes(Array p_meshes);
+ TypedArray<GLTFMesh> get_meshes();
+ void set_meshes(TypedArray<GLTFMesh> p_meshes);
- Array get_materials();
- void set_materials(Array p_materials);
+ TypedArray<BaseMaterial3D> get_materials();
+ void set_materials(TypedArray<BaseMaterial3D> p_materials);
String get_scene_name();
void set_scene_name(String p_scene_name);
@@ -139,32 +139,32 @@ public:
String get_base_path();
void set_base_path(String p_base_path);
- Array get_root_nodes();
- void set_root_nodes(Array p_root_nodes);
+ PackedInt32Array get_root_nodes();
+ void set_root_nodes(PackedInt32Array p_root_nodes);
- Array get_textures();
- void set_textures(Array p_textures);
+ TypedArray<GLTFTexture> get_textures();
+ void set_textures(TypedArray<GLTFTexture> p_textures);
- Array get_images();
- void set_images(Array p_images);
+ TypedArray<Texture2D> get_images();
+ void set_images(TypedArray<Texture2D> p_images);
- Array get_skins();
- void set_skins(Array p_skins);
+ TypedArray<GLTFSkin> get_skins();
+ void set_skins(TypedArray<GLTFSkin> p_skins);
- Array get_cameras();
- void set_cameras(Array p_cameras);
+ TypedArray<GLTFCamera> get_cameras();
+ void set_cameras(TypedArray<GLTFCamera> p_cameras);
- Array get_lights();
- void set_lights(Array p_lights);
+ TypedArray<GLTFLight> get_lights();
+ void set_lights(TypedArray<GLTFLight> p_lights);
- Array get_unique_names();
- void set_unique_names(Array p_unique_names);
+ TypedArray<String> get_unique_names();
+ void set_unique_names(TypedArray<String> p_unique_names);
- Array get_unique_animation_names();
- void set_unique_animation_names(Array p_unique_names);
+ TypedArray<String> get_unique_animation_names();
+ void set_unique_animation_names(TypedArray<String> p_unique_names);
- Array get_skeletons();
- void set_skeletons(Array p_skeletons);
+ TypedArray<GLTFSkeleton> get_skeletons();
+ void set_skeletons(TypedArray<GLTFSkeleton> p_skeletons);
Dictionary get_skeleton_to_node();
void set_skeleton_to_node(Dictionary p_skeleton_to_node);
@@ -172,8 +172,8 @@ public:
bool get_create_animations();
void set_create_animations(bool p_create_animations);
- Array get_animations();
- void set_animations(Array p_animations);
+ TypedArray<GLTFAnimation> get_animations();
+ void set_animations(TypedArray<GLTFAnimation> p_animations);
Node *get_scene_node(GLTFNodeIndex idx);
diff --git a/modules/gltf/gltf_template_convert.h b/modules/gltf/gltf_template_convert.h
index c915d3deb0..8a4b595c9f 100644
--- a/modules/gltf/gltf_template_convert.h
+++ b/modules/gltf/gltf_template_convert.h
@@ -46,8 +46,8 @@ static Array to_array(const Vector<T> &p_inp) {
}
template <class T>
-static Array to_array(const HashSet<T> &p_inp) {
- Array ret;
+static TypedArray<T> to_array(const HashSet<T> &p_inp) {
+ TypedArray<T> ret;
typename HashSet<T>::Iterator elem = p_inp.begin();
while (elem) {
ret.push_back(*elem);
@@ -65,7 +65,7 @@ static void set_from_array(Vector<T> &r_out, const Array &p_inp) {
}
template <class T>
-static void set_from_array(HashSet<T> &r_out, const Array &p_inp) {
+static void set_from_array(HashSet<T> &r_out, const TypedArray<T> &p_inp) {
r_out.clear();
for (int i = 0; i < p_inp.size(); i++) {
r_out.insert(p_inp[i]);
diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp
index 1e1204aa57..dbbccc9bcc 100644
--- a/modules/gltf/register_types.cpp
+++ b/modules/gltf/register_types.cpp
@@ -66,17 +66,24 @@ static void _editor_init() {
bool blend_enabled = GLOBAL_GET("filesystem/import/blender/enabled");
// Defined here because EditorSettings doesn't exist in `register_gltf_types` yet.
- EDITOR_DEF_RST("filesystem/import/blender/blender3_path", "");
+ String blender3_path = EDITOR_DEF_RST("filesystem/import/blender/blender3_path", "");
EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING,
"filesystem/import/blender/blender3_path", PROPERTY_HINT_GLOBAL_DIR));
if (blend_enabled) {
- Ref<EditorSceneFormatImporterBlend> importer;
- importer.instantiate();
- ResourceImporterScene::add_importer(importer);
+ Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
+ if (blender3_path.is_empty()) {
+ WARN_PRINT("Blend file import is enabled in the project settings, but no Blender path is configured in the editor settings. Blend files will not be imported.");
+ } else if (!da->dir_exists(blender3_path)) {
+ WARN_PRINT("Blend file import is enabled, but the Blender path doesn't point to an accessible directory. Blend files will not be imported.");
+ } else {
+ Ref<EditorSceneFormatImporterBlend> importer;
+ importer.instantiate();
+ ResourceImporterScene::add_importer(importer);
- Ref<EditorFileSystemImportFormatSupportQueryBlend> blend_import_query;
- blend_import_query.instantiate();
- EditorFileSystem::get_singleton()->add_import_format_support_query(blend_import_query);
+ Ref<EditorFileSystemImportFormatSupportQueryBlend> blend_import_query;
+ blend_import_query.instantiate();
+ EditorFileSystem::get_singleton()->add_import_format_support_query(blend_import_query);
+ }
}
// FBX to glTF importer.
@@ -89,9 +96,9 @@ static void _editor_init() {
if (fbx_enabled) {
Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
if (fbx2gltf_path.is_empty()) {
- WARN_PRINT("FBX file import is enabled, but no FBX2glTF path is configured. FBX files will not be imported.");
+ WARN_PRINT("FBX file import is enabled in the project settings, but no FBX2glTF path is configured in the editor settings. FBX files will not be imported.");
} else if (!da->file_exists(fbx2gltf_path)) {
- WARN_PRINT("FBX file import is enabled, but the FBX2glTF path doesn't point to a valid FBX2glTF executable. FBX files will not be imported.");
+ WARN_PRINT("FBX file import is enabled, but the FBX2glTF path doesn't point to an accessible file. FBX files will not be imported.");
} else {
Ref<EditorSceneFormatImporterFBX> importer;
importer.instantiate();
diff --git a/modules/gltf/structures/gltf_camera.cpp b/modules/gltf/structures/gltf_camera.cpp
index f3ea6a1c4c..c492913ea7 100644
--- a/modules/gltf/structures/gltf_camera.cpp
+++ b/modules/gltf/structures/gltf_camera.cpp
@@ -33,15 +33,18 @@
void GLTFCamera::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_perspective"), &GLTFCamera::get_perspective);
ClassDB::bind_method(D_METHOD("set_perspective", "perspective"), &GLTFCamera::set_perspective);
- ClassDB::bind_method(D_METHOD("get_fov_size"), &GLTFCamera::get_fov_size);
- ClassDB::bind_method(D_METHOD("set_fov_size", "fov_size"), &GLTFCamera::set_fov_size);
+ ClassDB::bind_method(D_METHOD("get_fov"), &GLTFCamera::get_fov);
+ ClassDB::bind_method(D_METHOD("set_fov", "fov"), &GLTFCamera::set_fov);
+ ClassDB::bind_method(D_METHOD("get_size_mag"), &GLTFCamera::get_size_mag);
+ ClassDB::bind_method(D_METHOD("set_size_mag", "size_mag"), &GLTFCamera::set_size_mag);
ClassDB::bind_method(D_METHOD("get_depth_far"), &GLTFCamera::get_depth_far);
ClassDB::bind_method(D_METHOD("set_depth_far", "zdepth_far"), &GLTFCamera::set_depth_far);
ClassDB::bind_method(D_METHOD("get_depth_near"), &GLTFCamera::get_depth_near);
ClassDB::bind_method(D_METHOD("set_depth_near", "zdepth_near"), &GLTFCamera::set_depth_near);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "perspective"), "set_perspective", "get_perspective"); // bool
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov_size"), "set_fov_size", "get_fov_size"); // float
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_far"), "set_depth_far", "get_depth_far"); // float
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_near"), "set_depth_near", "get_depth_near"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "perspective"), "set_perspective", "get_perspective");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov"), "set_fov", "get_fov");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size_mag"), "set_size_mag", "get_size_mag");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_far"), "set_depth_far", "get_depth_far");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_near"), "set_depth_near", "get_depth_near");
}
diff --git a/modules/gltf/structures/gltf_camera.h b/modules/gltf/structures/gltf_camera.h
index b7df741825..714ec21693 100644
--- a/modules/gltf/structures/gltf_camera.h
+++ b/modules/gltf/structures/gltf_camera.h
@@ -32,15 +32,22 @@
#define GLTF_CAMERA_H
#include "core/io/resource.h"
+#include "scene/3d/camera_3d.h"
+
+// Reference and test file:
+// https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_015_SimpleCameras.md
class GLTFCamera : public Resource {
GDCLASS(GLTFCamera, Resource);
private:
+ // GLTF has no default camera values, they should always be specified in
+ // the GLTF file. Here we default to Godot's default camera settings.
bool perspective = true;
- float fov_size = 75.0;
- float depth_far = 4000.0;
- float depth_near = 0.05;
+ real_t fov = Math::deg2rad(75.0);
+ real_t size_mag = 0.5;
+ real_t depth_far = 4000.0;
+ real_t depth_near = 0.05;
protected:
static void _bind_methods();
@@ -48,12 +55,14 @@ protected:
public:
bool get_perspective() const { return perspective; }
void set_perspective(bool p_val) { perspective = p_val; }
- float get_fov_size() const { return fov_size; }
- void set_fov_size(float p_val) { fov_size = p_val; }
- float get_depth_far() const { return depth_far; }
- void set_depth_far(float p_val) { depth_far = p_val; }
- float get_depth_near() const { return depth_near; }
- void set_depth_near(float p_val) { depth_near = p_val; }
+ real_t get_fov() const { return fov; }
+ void set_fov(real_t p_val) { fov = p_val; }
+ real_t get_size_mag() const { return size_mag; }
+ void set_size_mag(real_t p_val) { size_mag = p_val; }
+ real_t get_depth_far() const { return depth_far; }
+ void set_depth_far(real_t p_val) { depth_far = p_val; }
+ real_t get_depth_near() const { return depth_near; }
+ void set_depth_near(real_t p_val) { depth_near = p_val; }
};
#endif // GLTF_CAMERA_H
diff --git a/modules/gltf/structures/gltf_skeleton.cpp b/modules/gltf/structures/gltf_skeleton.cpp
index 90a6b0f50f..0073357eda 100644
--- a/modules/gltf/structures/gltf_skeleton.cpp
+++ b/modules/gltf/structures/gltf_skeleton.cpp
@@ -72,11 +72,11 @@ Skeleton3D *GLTFSkeleton::get_godot_skeleton() {
return godot_skeleton;
}
-Array GLTFSkeleton::get_unique_names() {
+TypedArray<String> GLTFSkeleton::get_unique_names() {
return GLTFTemplateConvert::to_array(unique_names);
}
-void GLTFSkeleton::set_unique_names(Array p_unique_names) {
+void GLTFSkeleton::set_unique_names(TypedArray<String> p_unique_names) {
GLTFTemplateConvert::set_from_array(unique_names, p_unique_names);
}
diff --git a/modules/gltf/structures/gltf_skeleton.h b/modules/gltf/structures/gltf_skeleton.h
index db88623213..0f20b493b6 100644
--- a/modules/gltf/structures/gltf_skeleton.h
+++ b/modules/gltf/structures/gltf_skeleton.h
@@ -75,8 +75,8 @@ public:
// this->godot_skeleton = p_godot_skeleton;
// }
- Array get_unique_names();
- void set_unique_names(Array p_unique_names);
+ TypedArray<String> get_unique_names();
+ void set_unique_names(TypedArray<String> p_unique_names);
//RBMap<int32_t, GLTFNodeIndex> get_godot_bone_node() {
// return this->godot_bone_node;
diff --git a/modules/gltf/structures/gltf_skin.cpp b/modules/gltf/structures/gltf_skin.cpp
index 2e46ee3be2..9717a66048 100644
--- a/modules/gltf/structures/gltf_skin.cpp
+++ b/modules/gltf/structures/gltf_skin.cpp
@@ -31,6 +31,7 @@
#include "gltf_skin.h"
#include "../gltf_template_convert.h"
+#include "core/variant/typed_array.h"
#include "scene/resources/skin.h"
void GLTFSkin::_bind_methods() {
@@ -83,11 +84,11 @@ void GLTFSkin::set_joints_original(Vector<GLTFNodeIndex> p_joints_original) {
joints_original = p_joints_original;
}
-Array GLTFSkin::get_inverse_binds() {
+TypedArray<Transform3D> GLTFSkin::get_inverse_binds() {
return GLTFTemplateConvert::to_array(inverse_binds);
}
-void GLTFSkin::set_inverse_binds(Array p_inverse_binds) {
+void GLTFSkin::set_inverse_binds(TypedArray<Transform3D> p_inverse_binds) {
GLTFTemplateConvert::set_from_array(inverse_binds, p_inverse_binds);
}
diff --git a/modules/gltf/structures/gltf_skin.h b/modules/gltf/structures/gltf_skin.h
index 59b6a300ac..1a4d54b380 100644
--- a/modules/gltf/structures/gltf_skin.h
+++ b/modules/gltf/structures/gltf_skin.h
@@ -34,6 +34,9 @@
#include "../gltf_defines.h"
#include "core/io/resource.h"
+template <typename T>
+class TypedArray;
+
class GLTFSkin : public Resource {
GDCLASS(GLTFSkin, Resource);
friend class GLTFDocument;
@@ -82,8 +85,8 @@ public:
Vector<GLTFNodeIndex> get_joints_original();
void set_joints_original(Vector<GLTFNodeIndex> p_joints_original);
- Array get_inverse_binds();
- void set_inverse_binds(Array p_inverse_binds);
+ TypedArray<Transform3D> get_inverse_binds();
+ void set_inverse_binds(TypedArray<Transform3D> p_inverse_binds);
Vector<GLTFNodeIndex> get_joints();
void set_joints(Vector<GLTFNodeIndex> p_joints);
diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml
index 5552b5b009..6717f23057 100644
--- a/modules/gridmap/doc_classes/GridMap.xml
+++ b/modules/gridmap/doc_classes/GridMap.xml
@@ -39,6 +39,13 @@
Returns an array of [ArrayMesh]es and [Transform3D] references of all bake meshes that exist within the current GridMap.
</description>
</method>
+ <method name="get_basis_with_orthogonal_index" qualifiers="const">
+ <return type="Basis" />
+ <param index="0" name="index" type="int" />
+ <description>
+ Returns one of 24 possible rotations that lie along the vectors (x,y,z) with each component being either -1, 0, or 1. For further details, refer to the Godot source code.
+ </description>
+ </method>
<method name="get_cell_item" qualifiers="const">
<return type="int" />
<param index="0" name="position" type="Vector3i" />
@@ -46,6 +53,13 @@
The [MeshLibrary] item index located at the given grid coordinates. If the cell is empty, [constant INVALID_CELL_ITEM] will be returned.
</description>
</method>
+ <method name="get_cell_item_basis" qualifiers="const">
+ <return type="Basis" />
+ <param index="0" name="position" type="Vector3i" />
+ <description>
+ Returns the basis that gives the specificed cell its orientation.
+ </description>
+ </method>
<method name="get_cell_item_orientation" qualifiers="const">
<return type="int" />
<param index="0" name="position" type="Vector3i" />
@@ -80,14 +94,21 @@
Returns whether or not the specified layer of the [member navigation_layers] bitmask is enabled, given a [code]layer_number[/code] between 1 and 32.
</description>
</method>
+ <method name="get_orthogonal_index_from_basis" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="basis" type="Basis" />
+ <description>
+ This function considers a discretization of rotations into 24 points on unit sphere, lying along the vectors (x,y,z) with each component being either -1, 0, or 1, and returns the index (in the range from 0 to 23) of the point best representing the orientation of the object. For further details, refer to the Godot source code.
+ </description>
+ </method>
<method name="get_used_cells" qualifiers="const">
- <return type="Array" />
+ <return type="Vector3i[]" />
<description>
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" />
+ <return type="Vector3i[]" />
<param index="0" name="item" type="int" />
<description>
Returns an array of all cells with the given item index specified in [code]item[/code].
@@ -121,7 +142,7 @@
<description>
Sets the mesh index for the cell referenced by its grid coordinates.
A negative item index such as [constant INVALID_CELL_ITEM] will clear the cell.
- Optionally, the item's orientation can be passed. For valid orientation values, see [method Basis.get_orthogonal_index].
+ Optionally, the item's orientation can be passed. For valid orientation values, see [method get_orthogonal_index_from_basis].
</description>
</method>
<method name="set_collision_layer_value">
diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp
index 518e2cf97d..17f9832096 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp
@@ -37,6 +37,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/node_3d_editor_plugin.h"
#include "scene/3d/camera_3d.h"
#include "scene/main/window.h"
@@ -94,91 +95,91 @@ void GridMapEditor::_menu_option(int p_option) {
case MENU_OPTION_CURSOR_ROTATE_Y: {
Basis r;
if (input_action == INPUT_PASTE) {
- r.set_orthogonal_index(paste_indicator.orientation);
+ r = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0);
- paste_indicator.orientation = r.get_orthogonal_index();
+ paste_indicator.orientation = node->get_orthogonal_index_from_basis(r);
_update_paste_indicator();
break;
}
- r.set_orthogonal_index(cursor_rot);
+ r = node->get_basis_with_orthogonal_index(cursor_rot);
r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0);
- cursor_rot = r.get_orthogonal_index();
+ cursor_rot = node->get_orthogonal_index_from_basis(r);
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_ROTATE_X: {
Basis r;
if (input_action == INPUT_PASTE) {
- r.set_orthogonal_index(paste_indicator.orientation);
+ r = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0);
- paste_indicator.orientation = r.get_orthogonal_index();
+ paste_indicator.orientation = node->get_orthogonal_index_from_basis(r);
_update_paste_indicator();
break;
}
- r.set_orthogonal_index(cursor_rot);
+ r = node->get_basis_with_orthogonal_index(cursor_rot);
r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0);
- cursor_rot = r.get_orthogonal_index();
+ cursor_rot = node->get_orthogonal_index_from_basis(r);
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_ROTATE_Z: {
Basis r;
if (input_action == INPUT_PASTE) {
- r.set_orthogonal_index(paste_indicator.orientation);
+ r = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0);
- paste_indicator.orientation = r.get_orthogonal_index();
+ paste_indicator.orientation = node->get_orthogonal_index_from_basis(r);
_update_paste_indicator();
break;
}
- r.set_orthogonal_index(cursor_rot);
+ r = node->get_basis_with_orthogonal_index(cursor_rot);
r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0);
- cursor_rot = r.get_orthogonal_index();
+ cursor_rot = node->get_orthogonal_index_from_basis(r);
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_Y: {
Basis r;
if (input_action == INPUT_PASTE) {
- r.set_orthogonal_index(paste_indicator.orientation);
+ r = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 1, 0), Math_PI / 2.0);
- paste_indicator.orientation = r.get_orthogonal_index();
+ paste_indicator.orientation = node->get_orthogonal_index_from_basis(r);
_update_paste_indicator();
break;
}
- r.set_orthogonal_index(cursor_rot);
+ r = node->get_basis_with_orthogonal_index(cursor_rot);
r.rotate(Vector3(0, 1, 0), Math_PI / 2.0);
- cursor_rot = r.get_orthogonal_index();
+ cursor_rot = node->get_orthogonal_index_from_basis(r);
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_X: {
Basis r;
if (input_action == INPUT_PASTE) {
- r.set_orthogonal_index(paste_indicator.orientation);
+ r = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(1, 0, 0), Math_PI / 2.0);
- paste_indicator.orientation = r.get_orthogonal_index();
+ paste_indicator.orientation = node->get_orthogonal_index_from_basis(r);
_update_paste_indicator();
break;
}
- r.set_orthogonal_index(cursor_rot);
+ r = node->get_basis_with_orthogonal_index(cursor_rot);
r.rotate(Vector3(1, 0, 0), Math_PI / 2.0);
- cursor_rot = r.get_orthogonal_index();
+ cursor_rot = node->get_orthogonal_index_from_basis(r);
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_Z: {
Basis r;
if (input_action == INPUT_PASTE) {
- r.set_orthogonal_index(paste_indicator.orientation);
+ r = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 0, 1), Math_PI / 2.0);
- paste_indicator.orientation = r.get_orthogonal_index();
+ paste_indicator.orientation = node->get_orthogonal_index_from_basis(r);
_update_paste_indicator();
break;
}
- r.set_orthogonal_index(cursor_rot);
+ r = node->get_basis_with_orthogonal_index(cursor_rot);
r.rotate(Vector3(0, 0, 1), Math_PI / 2.0);
- cursor_rot = r.get_orthogonal_index();
+ cursor_rot = node->get_orthogonal_index_from_basis(r);
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_CLEAR_ROTATION: {
@@ -242,7 +243,7 @@ void GridMapEditor::_menu_option(int p_option) {
void GridMapEditor::_update_cursor_transform() {
cursor_transform = Transform3D();
cursor_transform.origin = cursor_origin;
- cursor_transform.basis.set_orthogonal_index(cursor_rot);
+ cursor_transform.basis = node->get_basis_with_orthogonal_index(cursor_rot);
cursor_transform.basis *= node->get_cell_scale();
cursor_transform = node->get_global_transform() * cursor_transform;
@@ -543,7 +544,7 @@ void GridMapEditor::_update_paste_indicator() {
xf.scale(scale);
xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size();
Basis rot;
- rot.set_orthogonal_index(paste_indicator.orientation);
+ rot = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
xf.basis = rot * xf.basis;
xf.translate_local((-center * node->get_cell_size()) / scale);
@@ -556,7 +557,7 @@ void GridMapEditor::_update_paste_indicator() {
xf.translate_local(item.grid_offset * node->get_cell_size());
Basis item_rot;
- item_rot.set_orthogonal_index(item.orientation);
+ item_rot = node->get_basis_with_orthogonal_index(item.orientation);
xf.basis = item_rot * xf.basis * node->get_cell_scale();
RenderingServer::get_singleton()->instance_set_transform(item.instance, node->get_global_transform() * xf);
@@ -568,7 +569,7 @@ void GridMapEditor::_do_paste() {
bool reselect = options->get_popup()->is_item_checked(idx);
Basis rot;
- rot.set_orthogonal_index(paste_indicator.orientation);
+ rot = node->get_basis_with_orthogonal_index(paste_indicator.orientation);
Vector3 ofs = paste_indicator.current - paste_indicator.click;
undo_redo->create_action(TTR("GridMap Paste Selection"));
@@ -577,10 +578,10 @@ void GridMapEditor::_do_paste() {
Vector3 position = rot.xform(item.grid_offset) + paste_indicator.begin + ofs;
Basis orm;
- orm.set_orthogonal_index(item.orientation);
+ orm = node->get_basis_with_orthogonal_index(item.orientation);
orm = rot * orm;
- undo_redo->add_do_method(node, "set_cell_item", position, item.cell_item, orm.get_orthogonal_index());
+ undo_redo->add_do_method(node, "set_cell_item", position, item.cell_item, node->get_orthogonal_index_from_basis(orm));
undo_redo->add_undo_method(node, "set_cell_item", position, node->get_cell_item(position), node->get_cell_item_orientation(position));
}
diff --git a/modules/gridmap/editor/grid_map_editor_plugin.h b/modules/gridmap/editor/grid_map_editor_plugin.h
index 3b29397502..a64dc4a80b 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.h
+++ b/modules/gridmap/editor/grid_map_editor_plugin.h
@@ -39,6 +39,7 @@
#include "scene/gui/slider.h"
#include "scene/gui/spin_box.h"
+class EditorUndoRedoManager;
class Node3DEditorPlugin;
class GridMapEditor : public VBoxContainer {
@@ -62,7 +63,7 @@ class GridMapEditor : public VBoxContainer {
DISPLAY_LIST
};
- UndoRedo *undo_redo = nullptr;
+ Ref<EditorUndoRedoManager> undo_redo;
InputAction input_action = INPUT_NONE;
Panel *panel = nullptr;
MenuButton *options = nullptr;
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index 7d80cbef7c..f207d4a741 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -428,6 +428,75 @@ int GridMap::get_cell_item_orientation(const Vector3i &p_position) const {
return cell_map[key].rot;
}
+static const Basis _ortho_bases[24] = {
+ Basis(1, 0, 0, 0, 1, 0, 0, 0, 1),
+ Basis(0, -1, 0, 1, 0, 0, 0, 0, 1),
+ Basis(-1, 0, 0, 0, -1, 0, 0, 0, 1),
+ Basis(0, 1, 0, -1, 0, 0, 0, 0, 1),
+ Basis(1, 0, 0, 0, 0, -1, 0, 1, 0),
+ Basis(0, 0, 1, 1, 0, 0, 0, 1, 0),
+ Basis(-1, 0, 0, 0, 0, 1, 0, 1, 0),
+ Basis(0, 0, -1, -1, 0, 0, 0, 1, 0),
+ Basis(1, 0, 0, 0, -1, 0, 0, 0, -1),
+ Basis(0, 1, 0, 1, 0, 0, 0, 0, -1),
+ Basis(-1, 0, 0, 0, 1, 0, 0, 0, -1),
+ Basis(0, -1, 0, -1, 0, 0, 0, 0, -1),
+ Basis(1, 0, 0, 0, 0, 1, 0, -1, 0),
+ Basis(0, 0, -1, 1, 0, 0, 0, -1, 0),
+ Basis(-1, 0, 0, 0, 0, -1, 0, -1, 0),
+ Basis(0, 0, 1, -1, 0, 0, 0, -1, 0),
+ Basis(0, 0, 1, 0, 1, 0, -1, 0, 0),
+ Basis(0, -1, 0, 0, 0, 1, -1, 0, 0),
+ Basis(0, 0, -1, 0, -1, 0, -1, 0, 0),
+ Basis(0, 1, 0, 0, 0, -1, -1, 0, 0),
+ Basis(0, 0, 1, 0, -1, 0, 1, 0, 0),
+ Basis(0, 1, 0, 0, 0, 1, 1, 0, 0),
+ Basis(0, 0, -1, 0, 1, 0, 1, 0, 0),
+ Basis(0, -1, 0, 0, 0, -1, 1, 0, 0)
+};
+
+Basis GridMap::get_cell_item_basis(const Vector3i &p_position) const {
+ int orientation = get_cell_item_orientation(p_position);
+
+ if (orientation == -1) {
+ return Basis();
+ }
+
+ return get_basis_with_orthogonal_index(orientation);
+}
+
+Basis GridMap::get_basis_with_orthogonal_index(int p_index) const {
+ ERR_FAIL_INDEX_V(p_index, 24, Basis());
+
+ return _ortho_bases[p_index];
+}
+
+int GridMap::get_orthogonal_index_from_basis(const Basis &p_basis) const {
+ Basis orth = p_basis;
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
+ real_t v = orth[i][j];
+ if (v > 0.5) {
+ v = 1.0;
+ } else if (v < -0.5) {
+ v = -1.0;
+ } else {
+ v = 0;
+ }
+
+ orth[i][j] = v;
+ }
+ }
+
+ for (int i = 0; i < 24; i++) {
+ if (_ortho_bases[i] == orth) {
+ return i;
+ }
+ }
+
+ return 0;
+}
+
Vector3i GridMap::world_to_map(const Vector3 &p_world_position) const {
Vector3 map_position = (p_world_position / cell_size).floor();
return Vector3i(map_position);
@@ -529,7 +598,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
Transform3D xform;
- xform.basis.set_orthogonal_index(c.rot);
+ xform.basis = _ortho_bases[c.rot];
xform.set_origin(cellpos * cell_size + ofs);
xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
if (baked_meshes.size() == 0) {
@@ -921,6 +990,9 @@ void GridMap::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_cell_item", "position", "item", "orientation"), &GridMap::set_cell_item, DEFVAL(0));
ClassDB::bind_method(D_METHOD("get_cell_item", "position"), &GridMap::get_cell_item);
ClassDB::bind_method(D_METHOD("get_cell_item_orientation", "position"), &GridMap::get_cell_item_orientation);
+ ClassDB::bind_method(D_METHOD("get_cell_item_basis", "position"), &GridMap::get_cell_item_basis);
+ ClassDB::bind_method(D_METHOD("get_basis_with_orthogonal_index", "index"), &GridMap::get_basis_with_orthogonal_index);
+ ClassDB::bind_method(D_METHOD("get_orthogonal_index_from_basis", "basis"), &GridMap::get_orthogonal_index_from_basis);
ClassDB::bind_method(D_METHOD("world_to_map", "world_position"), &GridMap::world_to_map);
ClassDB::bind_method(D_METHOD("map_to_world", "map_position"), &GridMap::map_to_world);
@@ -977,23 +1049,23 @@ float GridMap::get_cell_scale() const {
return cell_scale;
}
-Array GridMap::get_used_cells() const {
- Array a;
+TypedArray<Vector3i> GridMap::get_used_cells() const {
+ TypedArray<Vector3i> a;
a.resize(cell_map.size());
int i = 0;
for (const KeyValue<IndexKey, Cell> &E : cell_map) {
- Vector3 p(E.key.x, E.key.y, E.key.z);
+ Vector3i p(E.key.x, E.key.y, E.key.z);
a[i++] = p;
}
return a;
}
-Array GridMap::get_used_cells_by_item(int p_item) const {
- Array a;
+TypedArray<Vector3i> GridMap::get_used_cells_by_item(int p_item) const {
+ TypedArray<Vector3i> 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);
+ Vector3i p(E.key.x, E.key.y, E.key.z);
a.push_back(p);
}
}
@@ -1025,7 +1097,7 @@ Array GridMap::get_meshes() const {
Transform3D xform;
- xform.basis.set_orthogonal_index(E.value.rot);
+ xform.basis = _ortho_bases[E.value.rot];
xform.set_origin(cellpos * cell_size + ofs);
xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
@@ -1079,7 +1151,7 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe
Transform3D xform;
- xform.basis.set_orthogonal_index(E.value.rot);
+ xform.basis = _ortho_bases[E.value.rot];
xform.set_origin(cellpos * cell_size + ofs);
xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h
index 078a1d9de5..0ed4695fb9 100644
--- a/modules/gridmap/grid_map.h
+++ b/modules/gridmap/grid_map.h
@@ -263,6 +263,9 @@ public:
void set_cell_item(const Vector3i &p_position, int p_item, int p_rot = 0);
int get_cell_item(const Vector3i &p_position) const;
int get_cell_item_orientation(const Vector3i &p_position) const;
+ Basis get_cell_item_basis(const Vector3i &p_position) const;
+ Basis get_basis_with_orthogonal_index(int p_index) const;
+ int get_orthogonal_index_from_basis(const Basis &p_basis) const;
Vector3i world_to_map(const Vector3 &p_world_position) const;
Vector3 map_to_world(const Vector3i &p_map_position) const;
@@ -270,8 +273,8 @@ public:
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;
+ TypedArray<Vector3i> get_used_cells() const;
+ TypedArray<Vector3i> get_used_cells_by_item(int p_item) const;
Array get_meshes() const;
diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp
index eca689e87a..e7c6fe592d 100644
--- a/modules/hdr/image_loader_hdr.cpp
+++ b/modules/hdr/image_loader_hdr.cpp
@@ -33,7 +33,7 @@
#include "core/os/os.h"
#include "core/string/print_string.h"
-Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) {
+Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) {
String header = f->get_token();
ERR_FAIL_COND_V_MSG(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED, "Unsupported header information in HDR: " + header + ".");
@@ -131,7 +131,7 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_f
ptr[1] * exp / 255.0,
ptr[2] * exp / 255.0);
- if (p_force_linear) {
+ if (p_flags & FLAG_FORCE_LINEAR) {
c = c.srgb_to_linear();
}
diff --git a/modules/hdr/image_loader_hdr.h b/modules/hdr/image_loader_hdr.h
index 16c0816562..1bff05129b 100644
--- a/modules/hdr/image_loader_hdr.h
+++ b/modules/hdr/image_loader_hdr.h
@@ -35,7 +35,7 @@
class ImageLoaderHDR : public ImageFormatLoader {
public:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale);
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderHDR();
};
diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp
index 0e03fa65c8..3e138bf633 100644
--- a/modules/jpg/image_loader_jpegd.cpp
+++ b/modules/jpg/image_loader_jpegd.cpp
@@ -104,7 +104,7 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
return OK;
}
-Error ImageLoaderJPG::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) {
+Error ImageLoaderJPG::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) {
Vector<uint8_t> src_image;
uint64_t src_image_len = f->get_length();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
diff --git a/modules/jpg/image_loader_jpegd.h b/modules/jpg/image_loader_jpegd.h
index 6d631446e7..caa0461d05 100644
--- a/modules/jpg/image_loader_jpegd.h
+++ b/modules/jpg/image_loader_jpegd.h
@@ -35,7 +35,7 @@
class ImageLoaderJPG : public ImageFormatLoader {
public:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale);
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderJPG();
};
diff --git a/modules/mono/.editorconfig b/modules/mono/.editorconfig
index c9dcd7724e..9434d0693c 100644
--- a/modules/mono/.editorconfig
+++ b/modules/mono/.editorconfig
@@ -12,3 +12,32 @@ insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 120
csharp_indent_case_contents_when_block = false
+
+[*.cs]
+# CA1707: Identifiers should not contain underscores
+# TODO:
+# Maybe we could disable this selectively only
+# where it's not desired and for generated code.
+dotnet_diagnostic.CA1707.severity = none
+# CA1711: Identifiers should not have incorrect suffix
+# Disable warning for suffixes like EventHandler, Flags, Enum, etc.
+dotnet_diagnostic.CA1711.severity = none
+# CA1716: Identifiers should not match keywords
+# TODO: We should look into this.
+dotnet_diagnostic.CA1716.severity = warning
+# CA1720: Identifiers should not contain type names
+dotnet_diagnostic.CA1720.severity = none
+# CA1805: Do not initialize unnecessarily
+# Don't tell me what to do.
+dotnet_diagnostic.CA1805.severity = none
+# CA1304: Specify CultureInfo
+# TODO: We should look into this.
+dotnet_diagnostic.CA1304.severity = warning
+# CA1305: Specify IFormatProvider
+# TODO: We should look into this. Disabled for now because it's annoying.
+dotnet_diagnostic.CA1305.severity = none
+# CA1310: Specify StringComparison for correctness
+# TODO: We should look into this. Disabled for now because it's annoying.
+dotnet_diagnostic.CA1310.severity = none
+# Diagnostics to prevent defensive copies of `in` struct parameters
+resharper_possibly_impure_method_call_on_readonly_variable_highlighting = error
diff --git a/modules/mono/Directory.Build.props b/modules/mono/Directory.Build.props
index fbf864b11b..f7c8a825f9 100644
--- a/modules/mono/Directory.Build.props
+++ b/modules/mono/Directory.Build.props
@@ -1,3 +1,6 @@
<Project>
- <Import Project="$(MSBuildThisFileDirectory)\SdkPackageVersions.props" />
+ <PropertyGroup>
+ <GodotSdkPackageVersionsFilePath>$(MSBuildThisFileDirectory)\SdkPackageVersions.props</GodotSdkPackageVersionsFilePath>
+ </PropertyGroup>
+ <Import Project="$(GodotSdkPackageVersionsFilePath)" />
</Project>
diff --git a/modules/mono/Directory.Build.targets b/modules/mono/Directory.Build.targets
new file mode 100644
index 0000000000..98410b93ae
--- /dev/null
+++ b/modules/mono/Directory.Build.targets
@@ -0,0 +1,22 @@
+<Project>
+ <PropertyGroup>
+ <_HasNuGetPackage Condition=" '$(_HasNuGetPackage)' == '' And '$(PackageId)' != '' And '$(GeneratePackageOnBuild.ToLower())' == 'true' ">true</_HasNuGetPackage>
+ <_HasNuGetPackage Condition=" '$(_HasNuGetPackage)' == '' ">false</_HasNuGetPackage>
+ </PropertyGroup>
+ <Target Name="CopyNupkgToSConsOutputDir" AfterTargets="Pack"
+ Condition=" '$(_HasNuGetPackage)' == 'true' ">
+ <PropertyGroup>
+ <GodotSourceRootPath>$(MSBuildThisFileDirectory)\..\..\</GodotSourceRootPath>
+ <GodotOutputDataDir>$(GodotSourceRootPath)\bin\GodotSharp\</GodotOutputDataDir>
+ </PropertyGroup>
+ <Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" />
+ </Target>
+ <Target Name="PushNuGetPackagesToLocalSource" BeforeTargets="Pack"
+ Condition=" '$(_HasNuGetPackage)' == 'true' And '$(PushNuGetToLocalSource)' != '' ">
+ <Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(PushNuGetToLocalSource)\" />
+ </Target>
+ <Target Name="ClearNuGetLocalPackageCache" BeforeTargets="Pack"
+ Condition=" '$(_HasNuGetPackage)' == 'true' And '$(ClearNuGetLocalCache.ToLower())' == 'true' ">
+ <RemoveDir Directories="$(NugetPackageRoot)/$(PackageId.ToLower())/$(PackageVersion)"/>
+ </Target>
+</Project>
diff --git a/modules/mono/README.md b/modules/mono/README.md
new file mode 100644
index 0000000000..ebbc6b0f80
--- /dev/null
+++ b/modules/mono/README.md
@@ -0,0 +1,45 @@
+# How to build and run
+
+1. Build Godot with the module enabled: `module_mono_enabled=yes`.
+2. After building Godot, use it to generate the C# glue code:
+ ```sh
+ <godot_binary> --generate-mono-glue ./modules/mono/glue
+ ```
+3. Build the C# solutions:
+ ```sh
+ ./modules/mono/build_scripts/build_assemblies.py --godot-output-dir ./bin
+ ```
+
+The paths specified in these examples assume the command is being run from
+the Godot source root.
+
+# How to deal with NuGet packages
+
+We distribute the API assemblies, our source generators, and our custom
+MSBuild project SDK as NuGet packages. This is all transparent to the user,
+but it can make things complicated during development.
+
+In order to use Godot with a development of those packages, we must create
+a local NuGet source where MSBuild can find them. This can be done with
+the .NET CLI:
+
+```sh
+dotnet nuget add source ~/MyLocalNugetSource --name MyLocalNugetSource
+```
+
+The Godot NuGet packages must be added to that local source. Additionally,
+we must make sure there are no other versions of the package in the NuGet
+cache, as MSBuild may pick one of those instead.
+
+In order to simplify this process, the `build_assemblies.py` script provides
+the following `--push-nupkgs-local` option:
+
+```sh
+./modules/mono/build_scripts/build_assemblies.py --godot-output-dir ./bin \
+ --push-nupkgs-local ~/MyLocalNugetSource
+```
+
+This option ensures the packages will be added to the specified local NuGet
+source and that conflicting versions of the package are removed from the
+NuGet cache. It's recommended to always use this option when building the
+C# solutions during development to avoid mistakes.
diff --git a/modules/mono/SCsub b/modules/mono/SCsub
index d10ebc7b47..7764ba0b45 100644
--- a/modules/mono/SCsub
+++ b/modules/mono/SCsub
@@ -7,49 +7,14 @@ Import("env_modules")
env_mono = env_modules.Clone()
-if env_mono["tools"]:
- # NOTE: It is safe to generate this file here, since this is still executed serially
- import build_scripts.gen_cs_glue_version as gen_cs_glue_version
-
- gen_cs_glue_version.generate_header("glue/GodotSharp", "glue/cs_glue_version.gen.h")
-
-# Glue sources
-if env_mono["mono_glue"]:
- env_mono.Append(CPPDEFINES=["MONO_GLUE_ENABLED"])
-
- import os.path
-
- if not os.path.isfile("glue/mono_glue.gen.cpp"):
- raise RuntimeError("Mono glue sources not found. Did you forget to run '--generate-mono-glue'?")
-
-if env_mono["tools"] or env_mono["target"] != "release":
- env_mono.Append(CPPDEFINES=["GD_MONO_HOT_RELOAD"])
-
# Configure Mono
mono_configure.configure(env, env_mono)
-if env_mono["tools"] and env_mono["mono_glue"] and env_mono["build_cil"]:
- # Build Godot API solution
- import build_scripts.api_solution_build as api_solution_build
-
- api_sln_cmd = api_solution_build.build(env_mono)
-
- # Build GodotTools
- import build_scripts.godot_tools_build as godot_tools_build
-
- godot_tools_build.build(env_mono, api_sln_cmd)
-
- # Build Godot.NET.Sdk
- import build_scripts.godot_net_sdk_build as godot_net_sdk_build
-
- godot_net_sdk_build.build(env_mono)
-
# Add sources
env_mono.add_source_files(env.modules_sources, "*.cpp")
env_mono.add_source_files(env.modules_sources, "glue/*.cpp")
-env_mono.add_source_files(env.modules_sources, "glue/mono_glue.gen.cpp")
env_mono.add_source_files(env.modules_sources, "mono_gd/*.cpp")
env_mono.add_source_files(env.modules_sources, "utils/*.cpp")
diff --git a/modules/mono/SdkPackageVersions.props b/modules/mono/SdkPackageVersions.props
index bdec051625..65094aa34f 100644
--- a/modules/mono/SdkPackageVersions.props
+++ b/modules/mono/SdkPackageVersions.props
@@ -1,7 +1,8 @@
<Project>
<PropertyGroup>
<PackageFloatingVersion_Godot>4.0.*-*</PackageFloatingVersion_Godot>
- <PackageVersion_Godot_NET_Sdk>4.0.0-dev6</PackageVersion_Godot_NET_Sdk>
- <PackageVersion_Godot_SourceGenerators>4.0.0-dev3</PackageVersion_Godot_SourceGenerators>
+ <PackageVersion_GodotSharp>4.0.0-dev</PackageVersion_GodotSharp>
+ <PackageVersion_Godot_NET_Sdk>4.0.0-dev8</PackageVersion_Godot_NET_Sdk>
+ <PackageVersion_Godot_SourceGenerators>4.0.0-dev8</PackageVersion_Godot_SourceGenerators>
</PropertyGroup>
</Project>
diff --git a/modules/mono/build_scripts/api_solution_build.py b/modules/mono/build_scripts/api_solution_build.py
deleted file mode 100644
index 9abac22df6..0000000000
--- a/modules/mono/build_scripts/api_solution_build.py
+++ /dev/null
@@ -1,80 +0,0 @@
-# Build the Godot API solution
-
-import os
-
-from SCons.Script import Dir
-
-
-def build_api_solution(source, target, env):
- # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str
-
- module_dir = env["module_dir"]
-
- solution_path = os.path.join(module_dir, "glue/GodotSharp/GodotSharp.sln")
-
- build_config = env["solution_build_config"]
-
- extra_msbuild_args = ["/p:NoWarn=1591"] # Ignore missing documentation warnings
-
- from .solution_builder import build_solution
-
- build_solution(env, solution_path, build_config, extra_msbuild_args=extra_msbuild_args)
-
- # Copy targets
-
- core_src_dir = os.path.abspath(os.path.join(solution_path, os.pardir, "GodotSharp", "bin", build_config))
- editor_src_dir = os.path.abspath(os.path.join(solution_path, os.pardir, "GodotSharpEditor", "bin", build_config))
-
- dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir))
-
- if not os.path.isdir(dst_dir):
- assert not os.path.isfile(dst_dir)
- os.makedirs(dst_dir)
-
- def copy_target(target_path):
- from shutil import copy
-
- filename = os.path.basename(target_path)
-
- src_path = os.path.join(core_src_dir, filename)
- if not os.path.isfile(src_path):
- src_path = os.path.join(editor_src_dir, filename)
-
- copy(src_path, target_path)
-
- for scons_target in target:
- copy_target(str(scons_target))
-
-
-def build(env_mono):
- assert env_mono["tools"]
-
- target_filenames = [
- "GodotSharp.dll",
- "GodotSharp.pdb",
- "GodotSharp.xml",
- "GodotSharpEditor.dll",
- "GodotSharpEditor.pdb",
- "GodotSharpEditor.xml",
- ]
-
- depend_cmd = []
-
- for build_config in ["Debug", "Release"]:
- output_dir = Dir("#bin").abspath
- editor_api_dir = os.path.join(output_dir, "GodotSharp", "Api", build_config)
-
- targets = [os.path.join(editor_api_dir, filename) for filename in target_filenames]
-
- cmd = env_mono.CommandNoCache(
- targets, depend_cmd, build_api_solution, module_dir=os.getcwd(), solution_build_config=build_config
- )
- env_mono.AlwaysBuild(cmd)
-
- # Make the Release build of the API solution depend on the Debug build.
- # We do this in order to prevent SCons from building them in parallel,
- # which can freak out MSBuild. In many cases, one of the builds would
- # hang indefinitely requiring a key to be pressed for it to continue.
- depend_cmd = cmd
-
- return depend_cmd
diff --git a/modules/mono/build_scripts/build_assemblies.py b/modules/mono/build_scripts/build_assemblies.py
new file mode 100755
index 0000000000..fa3be684bd
--- /dev/null
+++ b/modules/mono/build_scripts/build_assemblies.py
@@ -0,0 +1,329 @@
+#!/usr/bin/python3
+
+import os
+import os.path
+import shlex
+import subprocess
+from dataclasses import dataclass
+
+
+def find_dotnet_cli():
+ if os.name == "nt":
+ for hint_dir in os.environ["PATH"].split(os.pathsep):
+ hint_dir = hint_dir.strip('"')
+ hint_path = os.path.join(hint_dir, "dotnet")
+ if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
+ return hint_path
+ if os.path.isfile(hint_path + ".exe") and os.access(hint_path + ".exe", os.X_OK):
+ return hint_path + ".exe"
+ else:
+ for hint_dir in os.environ["PATH"].split(os.pathsep):
+ hint_dir = hint_dir.strip('"')
+ hint_path = os.path.join(hint_dir, "dotnet")
+ if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
+ return hint_path
+
+
+def find_msbuild_standalone_windows():
+ msbuild_tools_path = find_msbuild_tools_path_reg()
+
+ if msbuild_tools_path:
+ return os.path.join(msbuild_tools_path, "MSBuild.exe")
+
+ return None
+
+
+def find_msbuild_mono_windows(mono_prefix):
+ assert mono_prefix is not None
+
+ mono_bin_dir = os.path.join(mono_prefix, "bin")
+ msbuild_mono = os.path.join(mono_bin_dir, "msbuild.bat")
+
+ if os.path.isfile(msbuild_mono):
+ return msbuild_mono
+
+ return None
+
+
+def find_msbuild_mono_unix():
+ import sys
+
+ hint_dirs = []
+ if sys.platform == "darwin":
+ hint_dirs[:0] = [
+ "/Library/Frameworks/Mono.framework/Versions/Current/bin",
+ "/usr/local/var/homebrew/linked/mono/bin",
+ ]
+
+ for hint_dir in hint_dirs:
+ hint_path = os.path.join(hint_dir, "msbuild")
+ if os.path.isfile(hint_path):
+ return hint_path
+ elif os.path.isfile(hint_path + ".exe"):
+ return hint_path + ".exe"
+
+ for hint_dir in os.environ["PATH"].split(os.pathsep):
+ hint_dir = hint_dir.strip('"')
+ hint_path = os.path.join(hint_dir, "msbuild")
+ if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
+ return hint_path
+ if os.path.isfile(hint_path + ".exe") and os.access(hint_path + ".exe", os.X_OK):
+ return hint_path + ".exe"
+
+ return None
+
+
+def find_msbuild_tools_path_reg():
+ import subprocess
+
+ program_files = os.getenv("PROGRAMFILES(X86)")
+ if not program_files:
+ program_files = os.getenv("PROGRAMFILES")
+ vswhere = os.path.join(program_files, "Microsoft Visual Studio", "Installer", "vswhere.exe")
+
+ vswhere_args = ["-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild"]
+
+ try:
+ lines = subprocess.check_output([vswhere] + vswhere_args).splitlines()
+
+ for line in lines:
+ parts = line.decode("utf-8").split(":", 1)
+
+ if len(parts) < 2 or parts[0] != "installationPath":
+ continue
+
+ val = parts[1].strip()
+
+ if not val:
+ raise ValueError("Value of `installationPath` entry is empty")
+
+ # Since VS2019, the directory is simply named "Current"
+ msbuild_dir = os.path.join(val, "MSBuild", "Current", "Bin")
+ if os.path.isdir(msbuild_dir):
+ return msbuild_dir
+
+ # Directory name "15.0" is used in VS 2017
+ return os.path.join(val, "MSBuild", "15.0", "Bin")
+
+ raise ValueError("Cannot find `installationPath` entry")
+ except ValueError as e:
+ print("Error reading output from vswhere: " + str(e))
+ except OSError:
+ pass # Fine, vswhere not found
+ except (subprocess.CalledProcessError, OSError):
+ pass
+
+
+@dataclass
+class ToolsLocation:
+ dotnet_cli: str = ""
+ msbuild_standalone: str = ""
+ msbuild_mono: str = ""
+ mono_bin_dir: str = ""
+
+
+def find_any_msbuild_tool(mono_prefix):
+ # Preference order: dotnet CLI > Standalone MSBuild > Mono's MSBuild
+
+ # Find dotnet CLI
+ dotnet_cli = find_dotnet_cli()
+ if dotnet_cli:
+ return ToolsLocation(dotnet_cli=dotnet_cli)
+
+ # Find standalone MSBuild
+ if os.name == "nt":
+ msbuild_standalone = find_msbuild_standalone_windows()
+ if msbuild_standalone:
+ return ToolsLocation(msbuild_standalone=msbuild_standalone)
+
+ if mono_prefix:
+ # Find Mono's MSBuild
+ if os.name == "nt":
+ msbuild_mono = find_msbuild_mono_windows(mono_prefix)
+ if msbuild_mono:
+ return ToolsLocation(msbuild_mono=msbuild_mono)
+ else:
+ msbuild_mono = find_msbuild_mono_unix()
+ if msbuild_mono:
+ return ToolsLocation(msbuild_mono=msbuild_mono)
+
+ return None
+
+
+def run_msbuild(tools: ToolsLocation, sln: str, msbuild_args: [str] = None):
+ if msbuild_args is None:
+ msbuild_args = []
+
+ using_msbuild_mono = False
+
+ # Preference order: dotnet CLI > Standalone MSBuild > Mono's MSBuild
+ if tools.dotnet_cli:
+ args = [tools.dotnet_cli, "msbuild"]
+ elif tools.msbuild_standalone:
+ args = [tools.msbuild_standalone]
+ elif tools.msbuild_mono:
+ args = [tools.msbuild_mono]
+ using_msbuild_mono = True
+ else:
+ raise RuntimeError("Path to MSBuild or dotnet CLI not provided.")
+
+ args += [sln]
+
+ if len(msbuild_args) > 0:
+ args += msbuild_args
+
+ print("Running MSBuild: ", " ".join(shlex.quote(arg) for arg in args), flush=True)
+
+ msbuild_env = os.environ.copy()
+
+ # Needed when running from Developer Command Prompt for VS
+ if "PLATFORM" in msbuild_env:
+ del msbuild_env["PLATFORM"]
+
+ if using_msbuild_mono:
+ # The (Csc/Vbc/Fsc)ToolExe environment variables are required when
+ # building with Mono's MSBuild. They must point to the batch files
+ # in Mono's bin directory to make sure they are executed with Mono.
+ msbuild_env.update(
+ {
+ "CscToolExe": os.path.join(tools.mono_bin_dir, "csc.bat"),
+ "VbcToolExe": os.path.join(tools.mono_bin_dir, "vbc.bat"),
+ "FscToolExe": os.path.join(tools.mono_bin_dir, "fsharpc.bat"),
+ }
+ )
+
+ return subprocess.call(args, env=msbuild_env)
+
+
+def build_godot_api(msbuild_tool, module_dir, output_dir, push_nupkgs_local):
+ target_filenames = [
+ "GodotSharp.dll",
+ "GodotSharp.pdb",
+ "GodotSharp.xml",
+ "GodotSharpEditor.dll",
+ "GodotSharpEditor.pdb",
+ "GodotSharpEditor.xml",
+ "GodotPlugins.dll",
+ "GodotPlugins.pdb",
+ "GodotPlugins.runtimeconfig.json",
+ ]
+
+ for build_config in ["Debug", "Release"]:
+ editor_api_dir = os.path.join(output_dir, "GodotSharp", "Api", build_config)
+
+ targets = [os.path.join(editor_api_dir, filename) for filename in target_filenames]
+
+ args = ["/restore", "/t:Build", "/p:Configuration=" + build_config, "/p:NoWarn=1591"]
+ if push_nupkgs_local:
+ args += ["/p:ClearNuGetLocalCache=true", "/p:PushNuGetToLocalSource=" + push_nupkgs_local]
+
+ sln = os.path.join(module_dir, "glue/GodotSharp/GodotSharp.sln")
+ exit_code = run_msbuild(
+ msbuild_tool,
+ sln=sln,
+ msbuild_args=args,
+ )
+ if exit_code != 0:
+ return exit_code
+
+ # Copy targets
+
+ core_src_dir = os.path.abspath(os.path.join(sln, os.pardir, "GodotSharp", "bin", build_config))
+ editor_src_dir = os.path.abspath(os.path.join(sln, os.pardir, "GodotSharpEditor", "bin", build_config))
+ plugins_src_dir = os.path.abspath(os.path.join(sln, os.pardir, "GodotPlugins", "bin", build_config, "net6.0"))
+
+ if not os.path.isdir(editor_api_dir):
+ assert not os.path.isfile(editor_api_dir)
+ os.makedirs(editor_api_dir)
+
+ def copy_target(target_path):
+ from shutil import copy
+
+ filename = os.path.basename(target_path)
+
+ src_path = os.path.join(core_src_dir, filename)
+ if not os.path.isfile(src_path):
+ src_path = os.path.join(editor_src_dir, filename)
+ if not os.path.isfile(src_path):
+ src_path = os.path.join(plugins_src_dir, filename)
+
+ print(f"Copying assembly to {target_path}...")
+ copy(src_path, target_path)
+
+ for scons_target in targets:
+ copy_target(scons_target)
+
+ return 0
+
+
+def build_all(msbuild_tool, module_dir, output_dir, godot_platform, dev_debug, push_nupkgs_local):
+ # Godot API
+ exit_code = build_godot_api(msbuild_tool, module_dir, output_dir, push_nupkgs_local)
+ if exit_code != 0:
+ return exit_code
+
+ # GodotTools
+ sln = os.path.join(module_dir, "editor/GodotTools/GodotTools.sln")
+ args = ["/restore", "/t:Build", "/p:Configuration=" + ("Debug" if dev_debug else "Release")] + (
+ ["/p:GodotPlatform=" + godot_platform] if godot_platform else []
+ )
+ if push_nupkgs_local:
+ args += ["/p:ClearNuGetLocalCache=true", "/p:PushNuGetToLocalSource=" + push_nupkgs_local]
+ exit_code = run_msbuild(msbuild_tool, sln=sln, msbuild_args=args)
+ if exit_code != 0:
+ return exit_code
+
+ # Godot.NET.Sdk
+ args = ["/restore", "/t:Build", "/p:Configuration=Release"]
+ if push_nupkgs_local:
+ args += ["/p:ClearNuGetLocalCache=true", "/p:PushNuGetToLocalSource=" + push_nupkgs_local]
+ sln = os.path.join(module_dir, "editor/Godot.NET.Sdk/Godot.NET.Sdk.sln")
+ exit_code = run_msbuild(msbuild_tool, sln=sln, msbuild_args=args)
+ if exit_code != 0:
+ return exit_code
+
+ return 0
+
+
+def main():
+ import argparse
+ import sys
+
+ parser = argparse.ArgumentParser(description="Builds all Godot .NET solutions")
+ parser.add_argument("--godot-output-dir", type=str, required=True)
+ parser.add_argument(
+ "--dev-debug",
+ action="store_true",
+ default=False,
+ help="Build GodotTools and Godot.NET.Sdk with 'Configuration=Debug'",
+ )
+ parser.add_argument("--godot-platform", type=str, default="")
+ parser.add_argument("--mono-prefix", type=str, default="")
+ parser.add_argument("--push-nupkgs-local", type=str, default="")
+
+ args = parser.parse_args()
+
+ this_script_dir = os.path.dirname(os.path.realpath(__file__))
+ module_dir = os.path.abspath(os.path.join(this_script_dir, os.pardir))
+
+ output_dir = os.path.abspath(args.godot_output_dir)
+
+ msbuild_tool = find_any_msbuild_tool(args.mono_prefix)
+
+ if msbuild_tool is None:
+ print("Unable to find MSBuild")
+ sys.exit(1)
+
+ exit_code = build_all(
+ msbuild_tool,
+ module_dir,
+ output_dir,
+ args.godot_platform,
+ args.dev_debug,
+ args.push_nupkgs_local,
+ )
+ sys.exit(exit_code)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/modules/mono/build_scripts/gen_cs_glue_version.py b/modules/mono/build_scripts/gen_cs_glue_version.py
deleted file mode 100644
index 98bbb4d9be..0000000000
--- a/modules/mono/build_scripts/gen_cs_glue_version.py
+++ /dev/null
@@ -1,20 +0,0 @@
-def generate_header(solution_dir, version_header_dst):
- import os
-
- latest_mtime = 0
- for root, dirs, files in os.walk(solution_dir, topdown=True):
- dirs[:] = [d for d in dirs if d not in ["Generated"]] # Ignored generated files
- files = [f for f in files if f.endswith(".cs")]
- for file in files:
- filepath = os.path.join(root, file)
- mtime = os.path.getmtime(filepath)
- latest_mtime = mtime if mtime > latest_mtime else latest_mtime
-
- glue_version = int(latest_mtime) # The latest modified time will do for now
-
- with open(version_header_dst, "w") as version_header:
- version_header.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
- version_header.write("#ifndef CS_GLUE_VERSION_H\n")
- version_header.write("#define CS_GLUE_VERSION_H\n\n")
- version_header.write("#define CS_GLUE_VERSION UINT32_C(" + str(glue_version) + ")\n")
- version_header.write("\n#endif // CS_GLUE_VERSION_H\n")
diff --git a/modules/mono/build_scripts/godot_net_sdk_build.py b/modules/mono/build_scripts/godot_net_sdk_build.py
deleted file mode 100644
index 8c5a60d2db..0000000000
--- a/modules/mono/build_scripts/godot_net_sdk_build.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# Build Godot.NET.Sdk solution
-
-import os
-
-from SCons.Script import Dir
-
-
-def build_godot_net_sdk(source, target, env):
- # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str
-
- module_dir = env["module_dir"]
-
- solution_path = os.path.join(module_dir, "editor/Godot.NET.Sdk/Godot.NET.Sdk.sln")
- build_config = "Release"
-
- from .solution_builder import build_solution
-
- extra_msbuild_args = ["/p:GodotPlatform=" + env["platform"]]
-
- build_solution(env, solution_path, build_config, extra_msbuild_args)
- # No need to copy targets. The Godot.NET.Sdk csproj takes care of copying them.
-
-
-def get_nupkgs_versions(props_file):
- import xml.etree.ElementTree as ET
-
- tree = ET.parse(props_file)
- root = tree.getroot()
-
- return {
- "Godot.NET.Sdk": root.find("./PropertyGroup/PackageVersion_Godot_NET_Sdk").text.strip(),
- "Godot.SourceGenerators": root.find("./PropertyGroup/PackageVersion_Godot_SourceGenerators").text.strip(),
- }
-
-
-def build(env_mono):
- assert env_mono["tools"]
-
- output_dir = Dir("#bin").abspath
- editor_tools_dir = os.path.join(output_dir, "GodotSharp", "Tools")
- nupkgs_dir = os.path.join(editor_tools_dir, "nupkgs")
-
- module_dir = os.getcwd()
-
- nupkgs_versions = get_nupkgs_versions(os.path.join(module_dir, "SdkPackageVersions.props"))
-
- target_filenames = [
- "Godot.NET.Sdk.%s.nupkg" % nupkgs_versions["Godot.NET.Sdk"],
- "Godot.SourceGenerators.%s.nupkg" % nupkgs_versions["Godot.SourceGenerators"],
- ]
-
- targets = [os.path.join(nupkgs_dir, filename) for filename in target_filenames]
-
- cmd = env_mono.CommandNoCache(targets, [], build_godot_net_sdk, module_dir=module_dir)
- env_mono.AlwaysBuild(cmd)
diff --git a/modules/mono/build_scripts/godot_tools_build.py b/modules/mono/build_scripts/godot_tools_build.py
deleted file mode 100644
index 3bbbf29d3b..0000000000
--- a/modules/mono/build_scripts/godot_tools_build.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Build GodotTools solution
-
-import os
-
-from SCons.Script import Dir
-
-
-def build_godot_tools(source, target, env):
- # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str
-
- module_dir = env["module_dir"]
-
- solution_path = os.path.join(module_dir, "editor/GodotTools/GodotTools.sln")
- build_config = "Debug" if env["target"] == "debug" else "Release"
-
- from .solution_builder import build_solution
-
- extra_msbuild_args = ["/p:GodotPlatform=" + env["platform"]]
-
- build_solution(env, solution_path, build_config, extra_msbuild_args)
- # No need to copy targets. The GodotTools csproj takes care of copying them.
-
-
-def build(env_mono, api_sln_cmd):
- assert env_mono["tools"]
-
- output_dir = Dir("#bin").abspath
- editor_tools_dir = os.path.join(output_dir, "GodotSharp", "Tools")
-
- target_filenames = ["GodotTools.dll"]
-
- if env_mono["target"] == "debug":
- target_filenames += ["GodotTools.pdb"]
-
- targets = [os.path.join(editor_tools_dir, filename) for filename in target_filenames]
-
- cmd = env_mono.CommandNoCache(targets, api_sln_cmd, build_godot_tools, module_dir=os.getcwd())
- env_mono.AlwaysBuild(cmd)
diff --git a/modules/mono/build_scripts/make_android_mono_config.py b/modules/mono/build_scripts/make_android_mono_config.py
deleted file mode 100644
index 3459244bc2..0000000000
--- a/modules/mono/build_scripts/make_android_mono_config.py
+++ /dev/null
@@ -1,55 +0,0 @@
-def generate_compressed_config(config_src, output_dir):
- import os.path
-
- # Source file
- with open(os.path.join(output_dir, "android_mono_config.gen.cpp"), "w") as cpp:
- with open(config_src, "rb") as f:
- buf = f.read()
- decompr_size = len(buf)
- import zlib
-
- # Use maximum zlib compression level to further reduce file size
- # (at the cost of initial build times).
- buf = zlib.compress(buf, zlib.Z_BEST_COMPRESSION)
- compr_size = len(buf)
-
- bytes_seq_str = ""
- for i, buf_idx in enumerate(range(compr_size)):
- if i > 0:
- bytes_seq_str += ", "
- bytes_seq_str += str(buf[buf_idx])
-
- cpp.write(
- """/* THIS FILE IS GENERATED DO NOT EDIT */
-#include "android_mono_config.h"
-
-#ifdef ANDROID_ENABLED
-
-#include "core/io/compression.h"
-
-
-namespace {
-
-// config
-static const int config_compressed_size = %d;
-static const int config_uncompressed_size = %d;
-static const unsigned char config_compressed_data[] = { %s };
-} // namespace
-
-String get_godot_android_mono_config() {
- Vector<uint8_t> data;
- data.resize(config_uncompressed_size);
- uint8_t* w = data.ptrw();
- Compression::decompress(w, config_uncompressed_size, config_compressed_data,
- config_compressed_size, Compression::MODE_DEFLATE);
- String s;
- if (s.parse_utf8((const char *)w, data.size()) != OK) {
- ERR_FAIL_V(String());
- }
- return s;
-}
-
-#endif // ANDROID_ENABLED
-"""
- % (compr_size, decompr_size, bytes_seq_str)
- )
diff --git a/modules/mono/build_scripts/mono_android_config.xml b/modules/mono/build_scripts/mono_android_config.xml
deleted file mode 100644
index e79670afd2..0000000000
--- a/modules/mono/build_scripts/mono_android_config.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<configuration>
- <dllmap wordsize="32" dll="i:cygwin1.dll" target="/system/lib/libc.so" />
- <dllmap wordsize="64" dll="i:cygwin1.dll" target="/system/lib64/libc.so" />
- <dllmap wordsize="32" dll="libc" target="/system/lib/libc.so" />
- <dllmap wordsize="64" dll="libc" target="/system/lib64/libc.so" />
- <dllmap wordsize="32" dll="intl" target="/system/lib/libc.so" />
- <dllmap wordsize="64" dll="intl" target="/system/lib64/libc.so" />
- <dllmap wordsize="32" dll="libintl" target="/system/lib/libc.so" />
- <dllmap wordsize="64" dll="libintl" target="/system/lib64/libc.so" />
- <dllmap dll="MonoPosixHelper" target="libMonoPosixHelper.so" />
- <dllmap dll="System.Native" target="libmono-native.so" />
- <dllmap wordsize="32" dll="i:msvcrt" target="/system/lib/libc.so" />
- <dllmap wordsize="64" dll="i:msvcrt" target="/system/lib64/libc.so" />
- <dllmap wordsize="32" dll="i:msvcrt.dll" target="/system/lib/libc.so" />
- <dllmap wordsize="64" dll="i:msvcrt.dll" target="/system/lib64/libc.so" />
- <dllmap wordsize="32" dll="sqlite" target="/system/lib/libsqlite.so" />
- <dllmap wordsize="64" dll="sqlite" target="/system/lib64/libsqlite.so" />
- <dllmap wordsize="32" dll="sqlite3" target="/system/lib/libsqlite.so" />
- <dllmap wordsize="64" dll="sqlite3" target="/system/lib64/libsqlite.so" />
- <dllmap wordsize="32" dll="liblog" target="/system/lib/liblog.so" />
- <dllmap wordsize="64" dll="liblog" target="/system/lib64/liblog.so" />
- <dllmap dll="i:kernel32.dll">
- <dllentry dll="__Internal" name="CopyMemory" target="mono_win32_compat_CopyMemory"/>
- <dllentry dll="__Internal" name="FillMemory" target="mono_win32_compat_FillMemory"/>
- <dllentry dll="__Internal" name="MoveMemory" target="mono_win32_compat_MoveMemory"/>
- <dllentry dll="__Internal" name="ZeroMemory" target="mono_win32_compat_ZeroMemory"/>
- </dllmap>
-</configuration>
diff --git a/modules/mono/build_scripts/mono_configure.py b/modules/mono/build_scripts/mono_configure.py
index e69904c54b..3277f9beeb 100644
--- a/modules/mono/build_scripts/mono_configure.py
+++ b/modules/mono/build_scripts/mono_configure.py
@@ -1,574 +1,315 @@
import os
import os.path
-import subprocess
-
-from SCons.Script import Dir, Environment
-
-if os.name == "nt":
- from . import mono_reg_utils as monoreg
-
-
-android_arch_dirs = {
- "armv7": "armeabi-v7a",
- "arm64v8": "arm64-v8a",
- "x86": "x86",
- "x86_64": "x86_64",
-}
-
-
-def get_android_out_dir(env):
- return os.path.join(
- Dir("#platform/android/java/lib/libs").abspath,
- "release" if env["target"] == "release" else "debug",
- android_arch_dirs[env["android_arch"]],
- )
-
-
-def find_name_in_dir_files(directory, names, prefixes=[""], extensions=[""]):
- for extension in extensions:
- if extension and not extension.startswith("."):
- extension = "." + extension
- for prefix in prefixes:
- for curname in names:
- if os.path.isfile(os.path.join(directory, prefix + curname + extension)):
- return curname
- return ""
-
-
-def find_file_in_dir(directory, names, prefixes=[""], extensions=[""]):
- for extension in extensions:
- if extension and not extension.startswith("."):
- extension = "." + extension
- for prefix in prefixes:
- for curname in names:
- filename = prefix + curname + extension
- if os.path.isfile(os.path.join(directory, filename)):
- return filename
- return ""
-
-
-def copy_file(src_dir, dst_dir, src_name, dst_name=""):
- from shutil import copy
-
- src_path = os.path.join(Dir(src_dir).abspath, src_name)
- dst_dir = Dir(dst_dir).abspath
-
- if not os.path.isdir(dst_dir):
- os.makedirs(dst_dir)
-
- if dst_name:
- copy(src_path, os.path.join(dst_dir, dst_name))
- else:
- copy(src_path, dst_dir)
def is_desktop(platform):
- return platform in ["windows", "macos", "linuxbsd", "server", "uwp", "haiku"]
+ return platform in ["windows", "macos", "linuxbsd", "uwp", "haiku"]
def is_unix_like(platform):
- return platform in ["macos", "linuxbsd", "server", "android", "haiku", "ios"]
+ return platform in ["macos", "linuxbsd", "android", "haiku", "ios"]
def module_supports_tools_on(platform):
- return platform not in ["android", "javascript", "ios"]
-
-
-def find_wasm_src_dir(mono_root):
- hint_dirs = [
- os.path.join(mono_root, "src"),
- os.path.join(mono_root, "../src"),
- ]
- for hint_dir in hint_dirs:
- if os.path.isfile(os.path.join(hint_dir, "driver.c")):
- return hint_dir
- return ""
+ return is_desktop(platform)
def configure(env, env_mono):
- bits = env["bits"]
- is_android = env["platform"] == "android"
- is_javascript = env["platform"] == "javascript"
- is_ios = env["platform"] == "ios"
- is_ios_sim = is_ios and env["arch"] in ["x86", "x86_64"]
+ # is_android = env["platform"] == "android"
+ # is_javascript = env["platform"] == "javascript"
+ # is_ios = env["platform"] == "ios"
+ # is_ios_sim = is_ios and env["arch"] in ["x86_32", "x86_64"]
tools_enabled = env["tools"]
- mono_static = env["mono_static"]
- copy_mono_root = env["copy_mono_root"]
-
- mono_prefix = env["mono_prefix"]
- mono_bcl = env["mono_bcl"]
-
- mono_lib_names = ["mono-2.0-sgen", "monosgen-2.0"]
-
- if is_android and not env["android_arch"] in android_arch_dirs:
- raise RuntimeError("This module does not support the specified 'android_arch': " + env["android_arch"])
if tools_enabled and not module_supports_tools_on(env["platform"]):
- # TODO:
- # Android: We have to add the data directory to the apk, concretely the Api and Tools folders.
raise RuntimeError("This module does not currently support building for this platform with tools enabled")
- if is_android and mono_static:
- # FIXME: When static linking and doing something that requires libmono-native, we get a dlopen error as 'libmono-native'
- # seems to depend on 'libmonosgen-2.0'. Could be fixed by re-directing to '__Internal' with a dllmap or in the dlopen hook.
- raise RuntimeError("Statically linking Mono is not currently supported for this platform")
-
- if not mono_static and (is_javascript or is_ios):
- raise RuntimeError("Dynamically linking Mono is not currently supported for this platform")
-
- if not mono_prefix and (os.getenv("MONO32_PREFIX") or os.getenv("MONO64_PREFIX")):
- print(
- "WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the"
- " 'mono_prefix' SCons parameter instead"
- )
-
- # Although we don't support building with tools for any platform where we currently use static AOT,
- # if these are supported in the future, we won't be using static AOT for them as that would be
- # too restrictive for the editor. These builds would probably be made to only use the interpreter.
- mono_aot_static = (is_ios and not is_ios_sim) and not env["tools"]
-
- # Static AOT is only supported on the root domain
- mono_single_appdomain = mono_aot_static
-
- if mono_single_appdomain:
- env_mono.Append(CPPDEFINES=["GD_MONO_SINGLE_APPDOMAIN"])
-
- if (env["tools"] or env["target"] != "release") and not mono_single_appdomain:
+ if env["tools"]:
env_mono.Append(CPPDEFINES=["GD_MONO_HOT_RELOAD"])
- if env["platform"] == "windows":
- mono_root = mono_prefix
-
- if not mono_root and os.name == "nt":
- mono_root = monoreg.find_mono_root_dir(bits)
-
- if not mono_root:
- raise RuntimeError(
- "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
- )
-
- print("Found Mono root directory: " + mono_root)
+ app_host_dir = find_dotnet_app_host_dir(env)
- mono_lib_path = os.path.join(mono_root, "lib")
+ def check_app_host_file_exists(file):
+ file_path = os.path.join(app_host_dir, file)
+ if not os.path.isfile(file_path):
+ raise RuntimeError("File not found: " + file_path)
- env.Append(LIBPATH=mono_lib_path)
- env_mono.Prepend(CPPPATH=os.path.join(mono_root, "include", "mono-2.0"))
+ # TODO:
+ # All libnethost does for us is provide a function to find hostfxr.
+ # If we could handle that logic ourselves we could void linking it.
- lib_suffixes = [".lib"]
+ # nethost file names:
+ # static: libnethost.a/lib
+ # shared: libnethost.a/dylib and nethost.dll
+ check_app_host_file_exists("libnethost.lib" if os.name == "nt" else "libnethost.a")
+ check_app_host_file_exists("nethost.h")
+ check_app_host_file_exists("hostfxr.h")
+ check_app_host_file_exists("coreclr_delegates.h")
- if not env.msvc:
- # MingW supports both '.a' and '.lib'
- lib_suffixes.insert(0, ".a")
+ env_mono.Prepend(CPPPATH=app_host_dir)
- if mono_static:
- if env.msvc:
- mono_static_lib_name = "libmono-static-sgen"
- else:
- mono_static_lib_name = "libmonosgen-2.0"
+ env.Append(LIBPATH=[app_host_dir])
- mono_static_lib_file = find_file_in_dir(mono_lib_path, [mono_static_lib_name], extensions=lib_suffixes)
+ # Only the editor build links nethost, which is needed to find hostfxr.
+ # Exported games don't need this logic as hostfxr is bundled with them.
+ if tools_enabled:
+ libnethost_path = os.path.join(app_host_dir, "libnethost.lib" if os.name == "nt" else "libnethost.a")
- if not mono_static_lib_file:
- raise RuntimeError("Could not find static mono library in: " + mono_lib_path)
+ if env["platform"] == "windows":
+ env_mono.Append(CPPDEFINES=["NETHOST_USE_AS_STATIC"])
if env.msvc:
- env.Append(LINKFLAGS=mono_static_lib_file)
-
- env.Append(LINKFLAGS="Mincore.lib")
- env.Append(LINKFLAGS="msvcrt.lib")
- env.Append(LINKFLAGS="LIBCMT.lib")
- env.Append(LINKFLAGS="Psapi.lib")
+ env.Append(LINKFLAGS="libnethost.lib")
else:
- mono_static_lib_file_path = os.path.join(mono_lib_path, mono_static_lib_file)
- env.Append(LINKFLAGS=["-Wl,-whole-archive", mono_static_lib_file_path, "-Wl,-no-whole-archive"])
-
- env.Append(LIBS=["psapi"])
- env.Append(LIBS=["version"])
+ env.Append(LINKFLAGS=["-Wl,-whole-archive", libnethost_path, "-Wl,-no-whole-archive"])
else:
- mono_lib_file = find_file_in_dir(mono_lib_path, mono_lib_names, extensions=lib_suffixes)
+ is_apple = env["platform"] in ["macos", "ios"]
+ # is_macos = is_apple and not is_ios
- if not mono_lib_file:
- raise RuntimeError("Could not find mono library in: " + mono_lib_path)
+ # if is_ios and not is_ios_sim:
+ # env_mono.Append(CPPDEFINES=["IOS_DEVICE"])
- if env.msvc:
- env.Append(LINKFLAGS=mono_lib_file)
+ if is_apple:
+ env.Append(LINKFLAGS=["-Wl,-force_load," + libnethost_path])
else:
- mono_lib_file_path = os.path.join(mono_lib_path, mono_lib_file)
- env.Append(LINKFLAGS=mono_lib_file_path)
+ env.Append(LINKFLAGS=["-Wl,-whole-archive", libnethost_path, "-Wl,-no-whole-archive"])
- mono_bin_path = os.path.join(mono_root, "bin")
- mono_dll_file = find_file_in_dir(mono_bin_path, mono_lib_names, prefixes=["", "lib"], extensions=[".dll"])
+def find_dotnet_app_host_dir(env):
+ dotnet_version = "6.0"
- if not mono_dll_file:
- raise RuntimeError("Could not find mono shared library in: " + mono_bin_path)
+ dotnet_root = env["dotnet_root"]
- copy_file(mono_bin_path, "#bin", mono_dll_file)
- else:
- is_apple = env["platform"] in ["macos", "ios"]
- is_macos = is_apple and not is_ios
-
- sharedlib_ext = ".dylib" if is_apple else ".so"
-
- mono_root = mono_prefix
- mono_lib_path = ""
- mono_so_file = ""
-
- if not mono_root and (is_android or is_javascript or is_ios):
- raise RuntimeError(
- "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
- )
-
- if not mono_root and is_macos:
- # Try with some known directories under macOS
- hint_dirs = ["/Library/Frameworks/Mono.framework/Versions/Current", "/usr/local/var/homebrew/linked/mono"]
- for hint_dir in hint_dirs:
- if os.path.isdir(hint_dir):
- mono_root = hint_dir
- break
-
- # We can't use pkg-config to link mono statically,
- # but we can still use it to find the mono root directory
- if not mono_root and mono_static:
- mono_root = pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext)
- if not mono_root:
- raise RuntimeError(
- "Building with mono_static=yes, but failed to find the mono prefix with pkg-config; "
- + "specify one manually with the 'mono_prefix' SCons parameter"
- )
-
- if is_ios and not is_ios_sim:
- env_mono.Append(CPPDEFINES=["IOS_DEVICE"])
-
- if mono_root:
- print("Found Mono root directory: " + mono_root)
-
- mono_lib_path = os.path.join(mono_root, "lib")
-
- env.Append(LIBPATH=[mono_lib_path])
- env_mono.Prepend(CPPPATH=os.path.join(mono_root, "include", "mono-2.0"))
-
- mono_lib = find_name_in_dir_files(mono_lib_path, mono_lib_names, prefixes=["lib"], extensions=[".a"])
-
- if not mono_lib:
- raise RuntimeError("Could not find mono library in: " + mono_lib_path)
-
- env_mono.Append(CPPDEFINES=["_REENTRANT"])
-
- if mono_static:
- if not is_javascript:
- env.Append(LINKFLAGS=["-rdynamic"])
-
- mono_lib_file = os.path.join(mono_lib_path, "lib" + mono_lib + ".a")
-
- if is_apple:
- if is_macos:
- env.Append(LINKFLAGS=["-Wl,-force_load," + mono_lib_file])
- else:
- arch = env["arch"]
-
- def copy_mono_lib(libname_wo_ext):
- copy_file(
- mono_lib_path, "#bin", libname_wo_ext + ".a", "%s.ios.%s.a" % (libname_wo_ext, arch)
- )
-
- # Copy Mono libraries to the output folder. These are meant to be bundled with
- # the export templates and added to the Xcode project when exporting a game.
- copy_mono_lib("lib" + mono_lib)
- copy_mono_lib("libmono-native")
- copy_mono_lib("libmono-profiler-log")
-
- if not is_ios_sim:
- copy_mono_lib("libmono-ee-interp")
- copy_mono_lib("libmono-icall-table")
- copy_mono_lib("libmono-ilgen")
- else:
- assert is_desktop(env["platform"]) or is_android or is_javascript
- env.Append(LINKFLAGS=["-Wl,-whole-archive", mono_lib_file, "-Wl,-no-whole-archive"])
-
- if is_javascript:
- env.Append(LIBS=["mono-icall-table", "mono-native", "mono-ilgen", "mono-ee-interp"])
-
- wasm_src_dir = os.path.join(mono_root, "src")
- if not os.path.isdir(wasm_src_dir):
- raise RuntimeError("Could not find mono wasm src directory")
-
- # Ideally this should be defined only for 'driver.c', but I can't fight scons for another 2 hours
- env_mono.Append(CPPDEFINES=["CORE_BINDINGS"])
-
- env_mono.add_source_files(
- env.modules_sources,
- [
- os.path.join(wasm_src_dir, "driver.c"),
- os.path.join(wasm_src_dir, "zlib-helper.c"),
- os.path.join(wasm_src_dir, "corebindings.c"),
- ],
- )
-
- env.Append(
- LINKFLAGS=[
- "--js-library",
- os.path.join(wasm_src_dir, "library_mono.js"),
- "--js-library",
- os.path.join(wasm_src_dir, "binding_support.js"),
- "--js-library",
- os.path.join(wasm_src_dir, "dotnet_support.js"),
- ]
- )
- else:
- env.Append(LIBS=[mono_lib])
-
- if is_macos:
- env.Append(LIBS=["iconv", "pthread"])
- elif is_android:
- pass # Nothing
- elif is_ios:
- pass # Nothing, linking is delegated to the exported Xcode project
- elif is_javascript:
- env.Append(LIBS=["m", "rt", "dl", "pthread"])
- else:
- env.Append(LIBS=["m", "rt", "dl", "pthread"])
+ if not dotnet_root:
+ dotnet_cmd = find_dotnet_executable(env["arch"])
+ if dotnet_cmd:
+ sdk_path = find_dotnet_sdk(dotnet_cmd, dotnet_version)
+ if sdk_path:
+ dotnet_root = os.path.abspath(os.path.join(sdk_path, os.pardir))
- if not mono_static:
- mono_so_file = find_file_in_dir(
- mono_lib_path, mono_lib_names, prefixes=["lib"], extensions=[sharedlib_ext]
- )
+ if not dotnet_root:
+ raise RuntimeError("Cannot find .NET Core Sdk")
- if not mono_so_file:
- raise RuntimeError("Could not find mono shared library in: " + mono_lib_path)
- else:
- assert not mono_static
+ print("Found .NET Core Sdk root directory: " + dotnet_root)
- # TODO: Add option to force using pkg-config
- print("Mono root directory not found. Using pkg-config instead")
+ dotnet_cmd = os.path.join(dotnet_root, "dotnet.exe" if os.name == "nt" else "dotnet")
- env.ParseConfig("pkg-config monosgen-2 --libs")
- env_mono.ParseConfig("pkg-config monosgen-2 --cflags")
+ runtime_identifier = determine_runtime_identifier(env)
- tmpenv = Environment()
- tmpenv.AppendENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
- tmpenv.ParseConfig("pkg-config monosgen-2 --libs-only-L")
+ # TODO: In the future, if it can't be found this way, we want to obtain it
+ # from the runtime.{runtime_identifier}.Microsoft.NETCore.DotNetAppHost NuGet package.
+ app_host_version = find_app_host_version(dotnet_cmd, dotnet_version)
+ if not app_host_version:
+ raise RuntimeError("Cannot find .NET app host for version: " + dotnet_version)
- for hint_dir in tmpenv["LIBPATH"]:
- file_found = find_file_in_dir(hint_dir, mono_lib_names, prefixes=["lib"], extensions=[sharedlib_ext])
- if file_found:
- mono_lib_path = hint_dir
- mono_so_file = file_found
- break
+ def get_runtime_path():
+ return os.path.join(
+ dotnet_root,
+ "packs",
+ "Microsoft.NETCore.App.Host." + runtime_identifier,
+ app_host_version,
+ "runtimes",
+ runtime_identifier,
+ "native",
+ )
- if not mono_so_file:
- raise RuntimeError("Could not find mono shared library in: " + str(tmpenv["LIBPATH"]))
+ app_host_dir = get_runtime_path()
+
+ # Some Linux distros use their distro name as the RID in these paths.
+ # If the initial generic path doesn't exist, try to get the RID from `dotnet --info`.
+ # The generic RID should still be the first choice. Some platforms like Windows 10
+ # define the RID as `win10-x64` but still use the generic `win-x64` for directory names.
+ if not app_host_dir or not os.path.isdir(app_host_dir):
+ runtime_identifier = find_dotnet_cli_rid(dotnet_cmd)
+ app_host_dir = get_runtime_path()
+
+ return app_host_dir
+
+
+def determine_runtime_identifier(env):
+ # The keys are Godot's names, the values are the Microsoft's names.
+ # List: https://docs.microsoft.com/en-us/dotnet/core/rid-catalog
+ names_map = {
+ "windows": "win",
+ "macos": "osx",
+ "linuxbsd": "linux",
+ }
+ arch_map = {
+ "x86_64": "x64",
+ "x86_32": "x86",
+ "arm64": "arm64",
+ "arm32": "arm",
+ }
+ platform = env["platform"]
+ if is_desktop(platform):
+ return "%s-%s" % (names_map[platform], arch_map[env["arch"]])
+ else:
+ raise NotImplementedError()
- if not mono_static:
- libs_output_dir = get_android_out_dir(env) if is_android else "#bin"
- copy_file(mono_lib_path, libs_output_dir, mono_so_file)
- if not tools_enabled:
- if is_desktop(env["platform"]):
- if not mono_root:
- mono_root = (
- subprocess.check_output(["pkg-config", "mono-2", "--variable=prefix"]).decode("utf8").strip()
- )
+def find_app_host_version(dotnet_cmd, search_version_str):
+ import subprocess
+ from distutils.version import LooseVersion
- make_template_dir(env, mono_root)
- elif is_android:
- # Compress Android Mono Config
- from . import make_android_mono_config
+ search_version = LooseVersion(search_version_str)
- module_dir = os.getcwd()
- config_file_path = os.path.join(module_dir, "build_scripts", "mono_android_config.xml")
- make_android_mono_config.generate_compressed_config(config_file_path, "mono_gd/")
+ try:
+ env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US")
+ lines = subprocess.check_output([dotnet_cmd, "--list-runtimes"], env=env).splitlines()
- # Copy the required shared libraries
- copy_mono_shared_libs(env, mono_root, None)
- elif is_javascript:
- pass # No data directory for this platform
- elif is_ios:
- pass # No data directory for this platform
+ for line_bytes in lines:
+ line = line_bytes.decode("utf-8")
+ if not line.startswith("Microsoft.NETCore.App "):
+ continue
- if copy_mono_root:
- if not mono_root:
- mono_root = subprocess.check_output(["pkg-config", "mono-2", "--variable=prefix"]).decode("utf8").strip()
+ parts = line.split(" ", 2)
+ if len(parts) < 3:
+ continue
- if tools_enabled:
- # Only supported for editor builds.
- copy_mono_root_files(env, mono_root, mono_bcl)
+ version_str = parts[1]
+ version = LooseVersion(version_str)
-def make_template_dir(env, mono_root):
- from shutil import rmtree
+ if version >= search_version:
+ return version_str
+ except (subprocess.CalledProcessError, OSError) as e:
+ import sys
- platform = env["platform"]
- target = env["target"]
+ print(e, file=sys.stderr)
- template_dir_name = ""
+ return ""
- assert is_desktop(platform)
- template_dir_name = "data.mono.%s.%s.%s" % (platform, env["bits"], target)
+def find_dotnet_arch(dotnet_cmd):
+ import subprocess
- output_dir = Dir("#bin").abspath
- template_dir = os.path.join(output_dir, template_dir_name)
+ try:
+ env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US")
+ lines = subprocess.check_output([dotnet_cmd, "--info"], env=env).splitlines()
- template_mono_root_dir = os.path.join(template_dir, "Mono")
+ for line_bytes in lines:
+ line = line_bytes.decode("utf-8")
- if os.path.isdir(template_mono_root_dir):
- rmtree(template_mono_root_dir) # Clean first
+ parts = line.split(":", 1)
+ if len(parts) < 2:
+ continue
- # Copy etc/mono/
+ arch_str = parts[0].strip()
+ if arch_str != "Architecture":
+ continue
- template_mono_config_dir = os.path.join(template_mono_root_dir, "etc", "mono")
- copy_mono_etc_dir(mono_root, template_mono_config_dir, platform)
+ arch_value = parts[1].strip()
+ arch_map = {"x64": "x86_64", "x86": "x86_32", "arm64": "arm64", "arm32": "arm32"}
+ return arch_map[arch_value]
+ except (subprocess.CalledProcessError, OSError) as e:
+ import sys
- # Copy the required shared libraries
+ print(e, file=sys.stderr)
- copy_mono_shared_libs(env, mono_root, template_mono_root_dir)
+ return ""
-def copy_mono_root_files(env, mono_root, mono_bcl):
- from glob import glob
- from shutil import copy
- from shutil import rmtree
+def find_dotnet_sdk(dotnet_cmd, search_version_str):
+ import subprocess
+ from distutils.version import LooseVersion
- if not mono_root:
- raise RuntimeError("Mono installation directory not found")
+ search_version = LooseVersion(search_version_str)
- output_dir = Dir("#bin").abspath
- editor_mono_root_dir = os.path.join(output_dir, "GodotSharp", "Mono")
+ try:
+ env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US")
+ lines = subprocess.check_output([dotnet_cmd, "--list-sdks"], env=env).splitlines()
- if os.path.isdir(editor_mono_root_dir):
- rmtree(editor_mono_root_dir) # Clean first
+ for line_bytes in lines:
+ line = line_bytes.decode("utf-8")
- # Copy etc/mono/
+ parts = line.split(" ", 1)
+ if len(parts) < 2:
+ continue
- editor_mono_config_dir = os.path.join(editor_mono_root_dir, "etc", "mono")
- copy_mono_etc_dir(mono_root, editor_mono_config_dir, env["platform"])
+ version_str = parts[0]
- # Copy the required shared libraries
+ version = LooseVersion(version_str)
- copy_mono_shared_libs(env, mono_root, editor_mono_root_dir)
+ if version < search_version:
+ continue
- # Copy framework assemblies
+ path_part = parts[1]
+ return path_part[1 : path_part.find("]")]
+ except (subprocess.CalledProcessError, OSError) as e:
+ import sys
- mono_framework_dir = mono_bcl or os.path.join(mono_root, "lib", "mono", "4.5")
- mono_framework_facades_dir = os.path.join(mono_framework_dir, "Facades")
+ print(e, file=sys.stderr)
- editor_mono_framework_dir = os.path.join(editor_mono_root_dir, "lib", "mono", "4.5")
- editor_mono_framework_facades_dir = os.path.join(editor_mono_framework_dir, "Facades")
+ return ""
- if not os.path.isdir(editor_mono_framework_dir):
- os.makedirs(editor_mono_framework_dir)
- if not os.path.isdir(editor_mono_framework_facades_dir):
- os.makedirs(editor_mono_framework_facades_dir)
- for assembly in glob(os.path.join(mono_framework_dir, "*.dll")):
- copy(assembly, editor_mono_framework_dir)
- for assembly in glob(os.path.join(mono_framework_facades_dir, "*.dll")):
- copy(assembly, editor_mono_framework_facades_dir)
+def find_dotnet_cli_rid(dotnet_cmd):
+ import subprocess
+ try:
+ env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US")
+ lines = subprocess.check_output([dotnet_cmd, "--info"], env=env).splitlines()
-def copy_mono_etc_dir(mono_root, target_mono_config_dir, platform):
- from distutils.dir_util import copy_tree
- from glob import glob
- from shutil import copy
+ for line_bytes in lines:
+ line = line_bytes.decode("utf-8")
+ if not line.startswith(" RID:"):
+ continue
- if not os.path.isdir(target_mono_config_dir):
- os.makedirs(target_mono_config_dir)
+ parts = line.split()
+ if len(parts) < 2:
+ continue
- mono_etc_dir = os.path.join(mono_root, "etc", "mono")
- if not os.path.isdir(mono_etc_dir):
- mono_etc_dir = ""
- etc_hint_dirs = []
- if platform != "windows":
- etc_hint_dirs += ["/etc/mono", "/usr/local/etc/mono"]
- if "MONO_CFG_DIR" in os.environ:
- etc_hint_dirs += [os.path.join(os.environ["MONO_CFG_DIR"], "mono")]
- for etc_hint_dir in etc_hint_dirs:
- if os.path.isdir(etc_hint_dir):
- mono_etc_dir = etc_hint_dir
- break
- if not mono_etc_dir:
- raise RuntimeError("Mono installation etc directory not found")
+ return parts[1]
+ except (subprocess.CalledProcessError, OSError) as e:
+ import sys
- copy_tree(os.path.join(mono_etc_dir, "2.0"), os.path.join(target_mono_config_dir, "2.0"))
- copy_tree(os.path.join(mono_etc_dir, "4.0"), os.path.join(target_mono_config_dir, "4.0"))
- copy_tree(os.path.join(mono_etc_dir, "4.5"), os.path.join(target_mono_config_dir, "4.5"))
- if os.path.isdir(os.path.join(mono_etc_dir, "mconfig")):
- copy_tree(os.path.join(mono_etc_dir, "mconfig"), os.path.join(target_mono_config_dir, "mconfig"))
+ print(e, file=sys.stderr)
- for file in glob(os.path.join(mono_etc_dir, "*")):
- if os.path.isfile(file):
- copy(file, target_mono_config_dir)
+ return ""
-def copy_mono_shared_libs(env, mono_root, target_mono_root_dir):
- from shutil import copy
+ENV_PATH_SEP = ";" if os.name == "nt" else ":"
- def copy_if_exists(src, dst):
- if os.path.isfile(src):
- copy(src, dst)
- platform = env["platform"]
+def find_dotnet_executable(arch):
+ is_windows = os.name == "nt"
+ windows_exts = os.environ["PATHEXT"].split(ENV_PATH_SEP) if is_windows else None
+ path_dirs = os.environ["PATH"].split(ENV_PATH_SEP)
- if platform == "windows":
- src_mono_bin_dir = os.path.join(mono_root, "bin")
- target_mono_bin_dir = os.path.join(target_mono_root_dir, "bin")
+ search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list
- if not os.path.isdir(target_mono_bin_dir):
- os.makedirs(target_mono_bin_dir)
+ for dir in path_dirs:
+ search_dirs += [
+ os.path.join(dir, "x64"),
+ os.path.join(dir, "x86"),
+ os.path.join(dir, "arm64"),
+ os.path.join(dir, "arm32"),
+ ] # search subfolders for cross compiling
- mono_posix_helper_file = find_file_in_dir(
- src_mono_bin_dir, ["MonoPosixHelper"], prefixes=["", "lib"], extensions=[".dll"]
- )
- copy(
- os.path.join(src_mono_bin_dir, mono_posix_helper_file),
- os.path.join(target_mono_bin_dir, "MonoPosixHelper.dll"),
- )
+ # `dotnet --info` may not specify architecture. In such cases,
+ # we fallback to the first one we find without architecture.
+ sdk_path_unknown_arch = ""
- # For newer versions
- btls_dll_path = os.path.join(src_mono_bin_dir, "libmono-btls-shared.dll")
- if os.path.isfile(btls_dll_path):
- copy(btls_dll_path, target_mono_bin_dir)
- else:
- target_mono_lib_dir = (
- get_android_out_dir(env) if platform == "android" else os.path.join(target_mono_root_dir, "lib")
- )
+ for dir in search_dirs:
+ path = os.path.join(dir, "dotnet")
- if not os.path.isdir(target_mono_lib_dir):
- os.makedirs(target_mono_lib_dir)
-
- lib_file_names = []
- if platform == "macos":
- lib_file_names = [
- lib_name + ".dylib"
- for lib_name in ["libmono-btls-shared", "libmono-native-compat", "libMonoPosixHelper"]
- ]
- elif is_unix_like(platform):
- lib_file_names = [
- lib_name + ".so"
- for lib_name in [
- "libmono-btls-shared",
- "libmono-ee-interp",
- "libmono-native",
- "libMonoPosixHelper",
- "libmono-profiler-aot",
- "libmono-profiler-coverage",
- "libmono-profiler-log",
- "libMonoSupportW",
- ]
- ]
-
- for lib_file_name in lib_file_names:
- copy_if_exists(os.path.join(mono_root, "lib", lib_file_name), target_mono_lib_dir)
-
-
-def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext):
- tmpenv = Environment()
- tmpenv.AppendENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
- tmpenv.ParseConfig("pkg-config monosgen-2 --libs-only-L")
- for hint_dir in tmpenv["LIBPATH"]:
- name_found = find_name_in_dir_files(hint_dir, mono_lib_names, prefixes=["lib"], extensions=[sharedlib_ext])
- if name_found and os.path.isdir(os.path.join(hint_dir, "..", "include", "mono-2.0")):
- return os.path.join(hint_dir, "..")
- return ""
+ if is_windows:
+ for extension in windows_exts:
+ path_with_ext = path + extension
+
+ if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK):
+ sdk_arch = find_dotnet_arch(path_with_ext)
+ if sdk_arch == arch or arch == "":
+ return path_with_ext
+ elif sdk_arch == "":
+ sdk_path_unknown_arch = path_with_ext
+ else:
+ if os.path.isfile(path) and os.access(path, os.X_OK):
+ sdk_arch = find_dotnet_arch(path)
+ if sdk_arch == arch or arch == "":
+ return path
+ elif sdk_arch == "":
+ sdk_path_unknown_arch = path
+
+ return sdk_path_unknown_arch
diff --git a/modules/mono/build_scripts/mono_reg_utils.py b/modules/mono/build_scripts/mono_reg_utils.py
deleted file mode 100644
index 43c1ec8f8a..0000000000
--- a/modules/mono/build_scripts/mono_reg_utils.py
+++ /dev/null
@@ -1,112 +0,0 @@
-import os
-import platform
-
-if os.name == "nt":
- import winreg
-
-
-def _reg_open_key(key, subkey):
- try:
- return winreg.OpenKey(key, subkey)
- except OSError:
- if platform.architecture()[0] == "32bit":
- bitness_sam = winreg.KEY_WOW64_64KEY
- else:
- bitness_sam = winreg.KEY_WOW64_32KEY
- return winreg.OpenKey(key, subkey, 0, winreg.KEY_READ | bitness_sam)
-
-
-def _reg_open_key_bits(key, subkey, bits):
- sam = winreg.KEY_READ
-
- if platform.architecture()[0] == "32bit":
- if bits == "64":
- # Force 32bit process to search in 64bit registry
- sam |= winreg.KEY_WOW64_64KEY
- else:
- if bits == "32":
- # Force 64bit process to search in 32bit registry
- sam |= winreg.KEY_WOW64_32KEY
-
- return winreg.OpenKey(key, subkey, 0, sam)
-
-
-def _find_mono_in_reg(subkey, bits):
- try:
- with _reg_open_key_bits(winreg.HKEY_LOCAL_MACHINE, subkey, bits) as hKey:
- value = winreg.QueryValueEx(hKey, "SdkInstallRoot")[0]
- return value
- except OSError:
- return None
-
-
-def _find_mono_in_reg_old(subkey, bits):
- try:
- with _reg_open_key_bits(winreg.HKEY_LOCAL_MACHINE, subkey, bits) as hKey:
- default_clr = winreg.QueryValueEx(hKey, "DefaultCLR")[0]
- if default_clr:
- return _find_mono_in_reg(subkey + "\\" + default_clr, bits)
- return None
- except OSError:
- return None
-
-
-def find_mono_root_dir(bits):
- root_dir = _find_mono_in_reg(r"SOFTWARE\Mono", bits)
- if root_dir is not None:
- return str(root_dir)
- root_dir = _find_mono_in_reg_old(r"SOFTWARE\Novell\Mono", bits)
- if root_dir is not None:
- return str(root_dir)
- return ""
-
-
-def find_msbuild_tools_path_reg():
- import subprocess
-
- vswhere = os.getenv("PROGRAMFILES(X86)")
- if not vswhere:
- vswhere = os.getenv("PROGRAMFILES")
- vswhere += r"\Microsoft Visual Studio\Installer\vswhere.exe"
-
- vswhere_args = ["-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild"]
-
- try:
- lines = subprocess.check_output([vswhere] + vswhere_args).splitlines()
-
- for line in lines:
- parts = line.decode("utf-8").split(":", 1)
-
- if len(parts) < 2 or parts[0] != "installationPath":
- continue
-
- val = parts[1].strip()
-
- if not val:
- raise ValueError("Value of `installationPath` entry is empty")
-
- # Since VS2019, the directory is simply named "Current"
- msbuild_dir = os.path.join(val, "MSBuild\\Current\\Bin")
- if os.path.isdir(msbuild_dir):
- return msbuild_dir
-
- # Directory name "15.0" is used in VS 2017
- return os.path.join(val, "MSBuild\\15.0\\Bin")
-
- raise ValueError("Cannot find `installationPath` entry")
- except ValueError as e:
- print("Error reading output from vswhere: " + e.message)
- except subprocess.CalledProcessError as e:
- print(e.output)
- except OSError as e:
- print(e)
-
- # Try to find 14.0 in the Registry
-
- try:
- subkey = r"SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0"
- with _reg_open_key(winreg.HKEY_LOCAL_MACHINE, subkey) as hKey:
- value = winreg.QueryValueEx(hKey, "MSBuildToolsPath")[0]
- return value
- except OSError:
- return ""
diff --git a/modules/mono/build_scripts/solution_builder.py b/modules/mono/build_scripts/solution_builder.py
deleted file mode 100644
index 6a621c3c8b..0000000000
--- a/modules/mono/build_scripts/solution_builder.py
+++ /dev/null
@@ -1,145 +0,0 @@
-import os
-
-
-verbose = False
-
-
-def find_dotnet_cli():
- import os.path
-
- if os.name == "nt":
- for hint_dir in os.environ["PATH"].split(os.pathsep):
- hint_dir = hint_dir.strip('"')
- hint_path = os.path.join(hint_dir, "dotnet")
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
- if os.path.isfile(hint_path + ".exe") and os.access(hint_path + ".exe", os.X_OK):
- return hint_path + ".exe"
- else:
- for hint_dir in os.environ["PATH"].split(os.pathsep):
- hint_dir = hint_dir.strip('"')
- hint_path = os.path.join(hint_dir, "dotnet")
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
-
-
-def find_msbuild_unix():
- import os.path
- import sys
-
- hint_dirs = []
- if sys.platform == "darwin":
- hint_dirs[:0] = [
- "/Library/Frameworks/Mono.framework/Versions/Current/bin",
- "/usr/local/var/homebrew/linked/mono/bin",
- ]
-
- for hint_dir in hint_dirs:
- hint_path = os.path.join(hint_dir, "msbuild")
- if os.path.isfile(hint_path):
- return hint_path
- elif os.path.isfile(hint_path + ".exe"):
- return hint_path + ".exe"
-
- for hint_dir in os.environ["PATH"].split(os.pathsep):
- hint_dir = hint_dir.strip('"')
- hint_path = os.path.join(hint_dir, "msbuild")
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
- if os.path.isfile(hint_path + ".exe") and os.access(hint_path + ".exe", os.X_OK):
- return hint_path + ".exe"
-
- return None
-
-
-def find_msbuild_windows(env):
- from .mono_reg_utils import find_mono_root_dir, find_msbuild_tools_path_reg
-
- mono_root = env["mono_prefix"] or find_mono_root_dir(env["bits"])
-
- if not mono_root:
- raise RuntimeError("Cannot find mono root directory")
-
- mono_bin_dir = os.path.join(mono_root, "bin")
- msbuild_mono = os.path.join(mono_bin_dir, "msbuild.bat")
-
- msbuild_tools_path = find_msbuild_tools_path_reg()
-
- if msbuild_tools_path:
- return (os.path.join(msbuild_tools_path, "MSBuild.exe"), {})
-
- if os.path.isfile(msbuild_mono):
- # The (Csc/Vbc/Fsc)ToolExe environment variables are required when
- # building with Mono's MSBuild. They must point to the batch files
- # in Mono's bin directory to make sure they are executed with Mono.
- mono_msbuild_env = {
- "CscToolExe": os.path.join(mono_bin_dir, "csc.bat"),
- "VbcToolExe": os.path.join(mono_bin_dir, "vbc.bat"),
- "FscToolExe": os.path.join(mono_bin_dir, "fsharpc.bat"),
- }
- return (msbuild_mono, mono_msbuild_env)
-
- return None
-
-
-def run_command(command, args, env_override=None, name=None):
- def cmd_args_to_str(cmd_args):
- return " ".join([arg if not " " in arg else '"%s"' % arg for arg in cmd_args])
-
- args = [command] + args
-
- if name is None:
- name = os.path.basename(command)
-
- if verbose:
- print("Running '%s': %s" % (name, cmd_args_to_str(args)))
-
- import subprocess
-
- try:
- if env_override is None:
- subprocess.check_call(args)
- else:
- subprocess.check_call(args, env=env_override)
- except subprocess.CalledProcessError as e:
- raise RuntimeError("'%s' exited with error code: %s" % (name, e.returncode))
-
-
-def build_solution(env, solution_path, build_config, extra_msbuild_args=[]):
- global verbose
- verbose = env["verbose"]
-
- msbuild_env = os.environ.copy()
-
- # Needed when running from Developer Command Prompt for VS
- if "PLATFORM" in msbuild_env:
- del msbuild_env["PLATFORM"]
-
- msbuild_args = []
-
- dotnet_cli = find_dotnet_cli()
-
- if dotnet_cli:
- msbuild_path = dotnet_cli
- msbuild_args += ["msbuild"] # `dotnet msbuild` command
- else:
- # Find MSBuild
- if os.name == "nt":
- msbuild_info = find_msbuild_windows(env)
- if msbuild_info is None:
- raise RuntimeError("Cannot find MSBuild executable")
- msbuild_path = msbuild_info[0]
- msbuild_env.update(msbuild_info[1])
- else:
- msbuild_path = find_msbuild_unix()
- if msbuild_path is None:
- raise RuntimeError("Cannot find MSBuild executable")
-
- print("MSBuild path: " + msbuild_path)
-
- # Build solution
-
- msbuild_args += [solution_path, "/restore", "/t:Build", "/p:Configuration=" + build_config]
- msbuild_args += extra_msbuild_args
-
- run_command(msbuild_path, msbuild_args, env_override=msbuild_env, name="msbuild")
diff --git a/modules/mono/config.py b/modules/mono/config.py
index d895d2d92d..b599414a2c 100644
--- a/modules/mono/config.py
+++ b/modules/mono/config.py
@@ -1,4 +1,6 @@
-supported_platforms = ["windows", "macos", "linuxbsd", "server", "android", "haiku", "javascript", "ios"]
+# Prior to .NET Core, we supported these: ["windows", "macos", "linuxbsd", "android", "haiku", "javascript", "ios"]
+# Eventually support for each them should be added back (except Haiku if not supported by .NET Core)
+supported_platforms = ["windows", "macos", "linuxbsd"]
def can_build(env, platform):
@@ -13,26 +15,11 @@ def get_opts(platform):
return [
PathVariable(
- "mono_prefix",
- "Path to the Mono installation directory for the target platform and architecture",
+ "dotnet_root",
+ "Path to the .NET Sdk installation directory for the target platform and architecture",
"",
PathVariable.PathAccept,
),
- PathVariable(
- "mono_bcl",
- "Path to a custom Mono BCL (Base Class Library) directory for the target platform",
- "",
- PathVariable.PathAccept,
- ),
- BoolVariable("mono_static", "Statically link Mono", default_mono_static),
- BoolVariable("mono_glue", "Build with the Mono glue sources", True),
- BoolVariable("build_cil", "Build C# solutions", True),
- BoolVariable(
- "copy_mono_root", "Make a copy of the Mono installation directory to bundle with the editor", True
- ),
- BoolVariable(
- "mono_bundles_zlib", "Specify if the Mono runtime was built with bundled zlib", default_mono_bundles_zlib
- ),
]
@@ -44,13 +31,6 @@ def configure(env):
env.add_module_version_string("mono")
- if env["mono_bundles_zlib"]:
- # Mono may come with zlib bundled for WASM or on newer version when built with MinGW.
- print("This Mono runtime comes with zlib bundled. Disabling 'builtin_zlib'...")
- env["builtin_zlib"] = False
- thirdparty_zlib_dir = "#thirdparty/zlib/"
- env.Prepend(CPPPATH=[thirdparty_zlib_dir])
-
def get_doc_classes():
return [
diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp
index 475b483d6c..8b135051c5 100644
--- a/modules/mono/csharp_script.cpp
+++ b/modules/mono/csharp_script.cpp
@@ -30,8 +30,6 @@
#include "csharp_script.h"
-#include <mono/metadata/threads.h>
-#include <mono/metadata/tokentype.h>
#include <stdint.h>
#include "core/config/project_settings.h"
@@ -57,10 +55,8 @@
#endif
#include "godotsharp_dirs.h"
+#include "managed_callable.h"
#include "mono_gd/gd_mono_cache.h"
-#include "mono_gd/gd_mono_class.h"
-#include "mono_gd/gd_mono_marshal.h"
-#include "mono_gd/gd_mono_utils.h"
#include "signal_awaiter_utils.h"
#include "utils/macros.h"
#include "utils/string_utils.h"
@@ -69,17 +65,8 @@
#ifdef TOOLS_ENABLED
static bool _create_project_solution_if_needed() {
- String sln_path = GodotSharpDirs::get_project_sln_path();
- String csproj_path = GodotSharpDirs::get_project_csproj_path();
-
- if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
- // A solution does not yet exist, create a new one
-
- CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
- return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution");
- }
-
- return true;
+ CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
+ return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolutionIfNeeded");
}
#endif
@@ -118,26 +105,21 @@ void CSharpLanguage::init() {
}
#endif
- gdmono = memnew(GDMono);
- gdmono->initialize();
-
#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
- // Generate bindings here, before loading assemblies. 'initialize_load_assemblies' aborts
- // the applications if the api assemblies or the main tools assembly is missing, but this
- // is not a problem for BindingsGenerator as it only needs the tools project editor assembly.
+ // Generate the bindings here, before loading assemblies. The Godot assemblies
+ // may be missing if the glue wasn't generated yet in order to build them.
List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
BindingsGenerator::handle_cmdline_args(cmdline_args);
#endif
-#ifndef MONO_GLUE_ENABLED
- print_line("Run this binary with '--generate-mono-glue path/to/modules/mono/glue'");
-#endif
+ gdmono = memnew(GDMono);
+ gdmono->initialize();
+#ifdef TOOLS_ENABLED
if (gdmono->is_runtime_initialized()) {
gdmono->initialize_load_assemblies();
}
-#ifdef TOOLS_ENABLED
EditorNode::add_init_callback(&_editor_init_callback);
#endif
}
@@ -596,23 +578,19 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info()
return Vector<StackInfo>();
}
_recursion_flag_ = true;
- SCOPE_EXIT { _recursion_flag_ = false; };
-
- GD_MONO_SCOPE_THREAD_ATTACH;
+ SCOPE_EXIT {
+ _recursion_flag_ = false;
+ };
- if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoCache::cached_data.corlib_cache_updated) {
+ if (!gdmono->is_runtime_initialized()) {
return Vector<StackInfo>();
}
- MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());
-
- MonoBoolean need_file_info = true;
- void *ctor_args[1] = { &need_file_info };
-
- CACHED_METHOD(System_Diagnostics_StackTrace, ctor_bool)->invoke_raw(stack_trace, ctor_args);
-
Vector<StackInfo> si;
- si = stack_trace_get_info(stack_trace);
+
+ if (GDMonoCache::godot_api_cache_updated) {
+ GDMonoCache::managed_callbacks.DebuggingUtils_GetCurrentStackInfo(&si);
+ }
return si;
#else
@@ -620,63 +598,6 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info()
#endif
}
-#ifdef DEBUG_ENABLED
-Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
- // Printing an error here will result in endless recursion, so we must be careful
- static thread_local bool _recursion_flag_ = false;
- if (_recursion_flag_) {
- return Vector<StackInfo>();
- }
- _recursion_flag_ = true;
- SCOPE_EXIT { _recursion_flag_ = false; };
-
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- MonoException *exc = nullptr;
-
- MonoArray *frames = CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames).invoke(p_stack_trace, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- return Vector<StackInfo>();
- }
-
- int frame_count = mono_array_length(frames);
-
- if (frame_count <= 0) {
- return Vector<StackInfo>();
- }
-
- Vector<StackInfo> si;
- si.resize(frame_count);
-
- for (int i = 0; i < frame_count; i++) {
- StackInfo &sif = si.write[i];
- MonoObject *frame = mono_array_get(frames, MonoObject *, i);
-
- MonoString *file_name;
- int file_line_num;
- MonoString *method_decl;
- CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo).invoke(frame, &file_name, &file_line_num, &method_decl, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- return Vector<StackInfo>();
- }
-
- // TODO
- // what if the StackFrame method is null (method_decl is empty). should we skip this frame?
- // can reproduce with a MissingMethodException on internal calls
-
- sif.file = GDMonoMarshal::mono_string_to_godot(file_name);
- sif.line = file_line_num;
- sif.func = GDMonoMarshal::mono_string_to_godot(method_decl);
- }
-
- return si;
-}
-#endif
-
void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
#ifdef DEBUG_ENABLED
MutexLock lock(unsafe_object_references_lock);
@@ -698,48 +619,36 @@ void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
}
void CSharpLanguage::frame() {
- if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != nullptr) {
- const Ref<MonoGCHandleRef> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle;
-
- if (task_scheduler_handle.is_valid()) {
- MonoObject *task_scheduler = task_scheduler_handle->get_target();
-
- if (task_scheduler) {
- MonoException *exc = nullptr;
- CACHED_METHOD_THUNK(GodotTaskScheduler, Activate).invoke(task_scheduler, &exc);
-
- if (exc) {
- GDMonoUtils::debug_unhandled_exception(exc);
- }
- }
- }
+ if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_FrameCallback();
}
}
struct CSharpScriptDepSort {
- // must support sorting so inheritance works properly (parent must be reloaded first)
+ // Must support sorting so inheritance works properly (parent must be reloaded first)
bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
if (A == B) {
- return false; // shouldn't happen but..
+ // Shouldn't happen but just in case...
+ return false;
}
- GDMonoClass *I = B->base;
+ const Script *I = B->get_base_script().ptr();
while (I) {
- if (I == A->script_class) {
+ if (I == A.ptr()) {
// A is a base of B
return true;
}
- I = I->get_parent_class();
+ I = I->get_base_script().ptr();
}
- return false; // not a base
+ // A isn't a base of B
+ return false;
}
};
void CSharpLanguage::reload_all_scripts() {
#ifdef GD_MONO_HOT_RELOAD
if (is_assembly_reloading_needed()) {
- GD_MONO_SCOPE_THREAD_ATTACH;
reload_assemblies(false);
}
#endif
@@ -756,7 +665,6 @@ void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft
#ifdef GD_MONO_HOT_RELOAD
if (is_assembly_reloading_needed()) {
- GD_MONO_SCOPE_THREAD_ATTACH;
reload_assemblies(p_soft_reload);
}
#endif
@@ -768,28 +676,28 @@ bool CSharpLanguage::is_assembly_reloading_needed() {
return false;
}
- GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
-
- String appname_safe = ProjectSettings::get_singleton()->get_safe_project_name();
-
- appname_safe += ".dll";
+ String assembly_path = gdmono->get_project_assembly_path();
- if (proj_assembly) {
- String proj_asm_path = proj_assembly->get_path();
-
- if (!FileAccess::exists(proj_asm_path)) {
- // Maybe it wasn't loaded from the default path, so check this as well
- proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe);
- if (!FileAccess::exists(proj_asm_path)) {
- return false; // No assembly to load
- }
+ if (!assembly_path.is_empty()) {
+ if (!FileAccess::exists(assembly_path)) {
+ return false; // No assembly to load
}
- if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time()) {
+ if (FileAccess::get_modified_time(assembly_path) <= gdmono->get_project_assembly_modified_time()) {
return false; // Already up to date
}
} else {
- if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe))) {
+ String assembly_name = ProjectSettings::get_singleton()->get_setting("dotnet/project/assembly_name");
+
+ if (assembly_name.is_empty()) {
+ assembly_name = ProjectSettings::get_singleton()->get_safe_project_name();
+ }
+
+ assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir()
+ .plus_file(assembly_name + ".dll");
+ assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
+
+ if (!FileAccess::exists(assembly_path)) {
return false; // No assembly to load
}
}
@@ -802,6 +710,12 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
return;
}
+ // TODO:
+ // Currently, this reloads all scripts, including those whose class is not part of the
+ // assembly load context being unloaded. As such, we unnecessarily reload GodotTools.
+
+ print_verbose(".NET: Reloading assemblies...");
+
// There is no soft reloading with Mono. It's always hard reloading.
List<Ref<CSharpScript>> scripts;
@@ -824,18 +738,12 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
ManagedCallable *managed_callable = elem->self();
- MonoDelegate *delegate = (MonoDelegate *)managed_callable->delegate_handle.get_target();
+ ERR_CONTINUE(managed_callable->delegate_handle.value == nullptr);
Array serialized_data;
- MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
- MonoException *exc = nullptr;
- bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TrySerializeDelegate).invoke(delegate, managed_serialized_data, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- continue;
- }
+ bool success = GDMonoCache::managed_callbacks.DelegateUtils_TrySerializeDelegateWithGCHandle(
+ managed_callable->delegate_handle, &serialized_data);
if (success) {
ManagedCallable::instances_pending_reload.insert(managed_callable, serialized_data);
@@ -864,17 +772,12 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
// If someone removes a script from a node, deletes the script, builds, adds a script to the
// same node, then builds again, the script might have no path and also no script_class. In
// that case, we can't (and don't need to) reload it.
- if (script->get_path().is_empty() && !script->script_class) {
+ if (script->get_path().is_empty() && !script->valid) {
continue;
}
to_reload.push_back(script);
- if (script->get_path().is_empty()) {
- script->tied_class_name_for_reload = script->script_class->get_name_for_lookup();
- script->tied_class_namespace_for_reload = script->script_class->get_namespace();
- }
-
// Script::instances are deleted during managed object disposal, which happens on domain finalize.
// Only placeholders are kept. Therefore we need to keep a copy before that happens.
@@ -907,17 +810,20 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
- // Call OnBeforeSerialize
- if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener))) {
- obj->get_script_instance()->call(string_names.on_before_serialize);
- }
+ // Call OnBeforeSerialize and save instance info
- // Save instance info
CSharpScript::StateBackup state;
- // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
- csi->get_properties_state_for_reloading(state.properties);
- csi->get_event_signals_state_for_reloading(state.event_signals);
+ Dictionary properties;
+
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_SerializeState(
+ csi->get_gchandle_intptr(), &properties, &state.event_signals);
+
+ for (const Variant *s = properties.next(nullptr); s != nullptr; s = properties.next(s)) {
+ StringName name = *s;
+ Variant value = properties[*s];
+ state.properties.push_back(Pair<StringName, Variant>(name, value));
+ }
owners_map[obj->get_instance_id()] = state;
}
@@ -934,7 +840,7 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
}
// Do domain reload
- if (gdmono->reload_scripts_domain() != OK) {
+ if (gdmono->reload_project_assemblies() != OK) {
// Failed to reload the scripts domain
// Make sure to add the scripts back to their owners before returning
for (Ref<CSharpScript> &scr : to_reload) {
@@ -965,6 +871,9 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
scr->pending_reload_state.erase(obj_id);
}
+
+ scr->pending_reload_instances.clear();
+ scr->pending_reload_state.clear();
}
return;
@@ -976,53 +885,27 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
#ifdef TOOLS_ENABLED
script->exports_invalidated = true;
#endif
- script->signals_invalidated = true;
if (!script->get_path().is_empty()) {
script->reload(p_soft_reload);
if (!script->valid) {
script->pending_reload_instances.clear();
+ script->pending_reload_state.clear();
continue;
}
} else {
- const StringName &class_namespace = script->tied_class_namespace_for_reload;
- const StringName &class_name = script->tied_class_name_for_reload;
- GDMonoAssembly *project_assembly = gdmono->get_project_assembly();
-
- // Search in project and tools assemblies first as those are the most likely to have the class
- GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : nullptr);
-
-#ifdef TOOLS_ENABLED
- if (!script_class) {
- GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly();
- script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : nullptr);
- }
-#endif
+ bool success = GDMonoCache::managed_callbacks.ScriptManagerBridge_TryReloadRegisteredScriptWithClass(script.ptr());
- if (!script_class) {
- script_class = gdmono->get_class(class_namespace, class_name);
- }
-
- if (!script_class) {
- // The class was removed, can't reload
- script->pending_reload_instances.clear();
- continue;
- }
-
- bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(script_class);
- if (!obj_type) {
- // The class no longer inherits Godot.Object, can't reload
+ if (!success) {
+ // Couldn't reload
script->pending_reload_instances.clear();
+ script->pending_reload_state.clear();
continue;
}
-
- GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class);
-
- CSharpScript::initialize_for_managed_type(script, script_class, native);
}
- StringName native_name = NATIVE_GDMONOCLASS_NAME(script->native);
+ StringName native_name = script->get_instance_base_type();
{
for (const ObjectID &obj_id : script->pending_reload_instances) {
@@ -1087,57 +970,25 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
ERR_CONTINUE(!obj->get_script_instance());
- // TODO: Restore serialized state
-
CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
- for (const Pair<StringName, Variant> &G : state_backup.properties) {
- obj->get_script_instance()->set(G.first, G.second);
- }
-
CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
if (csi) {
- for (const Pair<StringName, Array> &G : state_backup.event_signals) {
- const StringName &name = G.first;
- const Array &serialized_data = G.second;
-
- HashMap<StringName, CSharpScript::EventSignal>::Iterator match = script->event_signals.find(name);
+ Dictionary properties;
- if (!match) {
- // The event or its signal attribute were removed
- continue;
- }
-
- const CSharpScript::EventSignal &event_signal = match->value;
-
- MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
- MonoDelegate *delegate = nullptr;
-
- MonoException *exc = nullptr;
- bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TryDeserializeDelegate).invoke(managed_serialized_data, &delegate, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- continue;
- }
-
- if (success) {
- ERR_CONTINUE(delegate == nullptr);
- event_signal.field->set_value(csi->get_mono_object(), (MonoObject *)delegate);
- } else if (OS::get_singleton()->is_stdout_verbose()) {
- OS::get_singleton()->print("Failed to deserialize event signal delegate\n");
- }
+ for (const Pair<StringName, Variant> &G : state_backup.properties) {
+ properties[G.first] = G.second;
}
- // Call OnAfterDeserialization
- if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener))) {
- obj->get_script_instance()->call(string_names.on_after_deserialize);
- }
+ // Restore serialized state and call OnAfterDeserialization
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_DeserializeState(
+ csi->get_gchandle_intptr(), &properties, &state_backup.event_signals);
}
}
script->pending_reload_instances.clear();
+ script->pending_reload_state.clear();
}
// Deserialize managed callables
@@ -1148,20 +999,14 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
ManagedCallable *managed_callable = elem.key;
const Array &serialized_data = elem.value;
- MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
- MonoDelegate *delegate = nullptr;
-
- MonoException *exc = nullptr;
- bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TryDeserializeDelegate).invoke(managed_serialized_data, &delegate, &exc);
+ GCHandleIntPtr delegate = { nullptr };
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- continue;
- }
+ bool success = GDMonoCache::managed_callbacks.DelegateUtils_TryDeserializeDelegateWithGCHandle(
+ &serialized_data, &delegate);
if (success) {
- ERR_CONTINUE(delegate == nullptr);
- managed_callable->set_delegate(delegate);
+ ERR_CONTINUE(delegate.value == nullptr);
+ managed_callable->delegate_handle = delegate;
} else if (OS::get_singleton()->is_stdout_verbose()) {
OS::get_singleton()->print("Failed to deserialize delegate\n");
}
@@ -1180,60 +1025,6 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
}
#endif
-void CSharpLanguage::lookup_script_for_class(GDMonoClass *p_class) {
- if (!p_class->has_attribute(CACHED_CLASS(ScriptPathAttribute))) {
- return;
- }
-
- MonoObject *attr = p_class->get_attribute(CACHED_CLASS(ScriptPathAttribute));
- String path = CACHED_FIELD(ScriptPathAttribute, path)->get_string_value(attr);
-
- dotnet_script_lookup_map[path] = DotNetScriptLookupInfo(
- p_class->get_namespace(), p_class->get_name(), p_class);
-}
-
-void CSharpLanguage::lookup_scripts_in_assembly(GDMonoAssembly *p_assembly) {
- if (p_assembly->has_attribute(CACHED_CLASS(AssemblyHasScriptsAttribute))) {
- MonoObject *attr = p_assembly->get_attribute(CACHED_CLASS(AssemblyHasScriptsAttribute));
- bool requires_lookup = CACHED_FIELD(AssemblyHasScriptsAttribute, requiresLookup)->get_bool_value(attr);
-
- if (requires_lookup) {
- // This is supported for scenarios where specifying all types would be cumbersome,
- // such as when disabling C# source generators (for whatever reason) or when using a
- // language other than C# that has nothing similar to source generators to automate it.
- MonoImage *image = p_assembly->get_image();
-
- int rows = mono_image_get_table_rows(image, MONO_TABLE_TYPEDEF);
-
- for (int i = 1; i < rows; i++) {
- // We don't search inner classes, only top-level.
- MonoClass *mono_class = mono_class_get(image, (i + 1) | MONO_TOKEN_TYPE_DEF);
-
- if (!mono_class_is_assignable_from(CACHED_CLASS_RAW(GodotObject), mono_class)) {
- continue;
- }
-
- GDMonoClass *current = p_assembly->get_class(mono_class);
- if (current) {
- lookup_script_for_class(current);
- }
- }
- } else {
- // This is the most likely scenario as we use C# source generators
- MonoArray *script_types = (MonoArray *)CACHED_FIELD(AssemblyHasScriptsAttribute, scriptTypes)->get_value(attr);
-
- int length = mono_array_length(script_types);
-
- for (int i = 0; i < length; i++) {
- MonoReflectionType *reftype = mono_array_get(script_types, MonoReflectionType *, i);
- ManagedType type = ManagedType::from_reftype(reftype);
- ERR_CONTINUE(!type.type_class);
- lookup_script_for_class(type.type_class);
- }
- }
- }
-}
-
void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("cs");
}
@@ -1248,22 +1039,6 @@ bool CSharpLanguage::overrides_external_editor() {
}
#endif
-void CSharpLanguage::thread_enter() {
-#if 0
- if (gdmono->is_runtime_initialized()) {
- GDMonoUtils::attach_current_thread();
- }
-#endif
-}
-
-void CSharpLanguage::thread_exit() {
-#if 0
- if (gdmono->is_runtime_initialized()) {
- GDMonoUtils::detach_current_thread();
- }
-#endif
-}
-
bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
// Not a parser error in our case, but it's still used for other type of errors
if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
@@ -1289,49 +1064,35 @@ bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
}
}
-void CSharpLanguage::_on_scripts_domain_unloaded() {
- for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
- CSharpScriptBinding &script_binding = E.value;
- script_binding.gchandle.release();
- script_binding.inited = false;
- }
-
+void CSharpLanguage::_on_scripts_domain_about_to_unload() {
#ifdef GD_MONO_HOT_RELOAD
{
MutexLock lock(ManagedCallable::instances_mutex);
for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
ManagedCallable *managed_callable = elem->self();
- managed_callable->delegate_handle.release();
- managed_callable->delegate_invoke = nullptr;
+ managed_callable->release_delegate_handle();
}
}
#endif
-
- dotnet_script_lookup_map.clear();
}
#ifdef TOOLS_ENABLED
void CSharpLanguage::_editor_init_callback() {
- register_editor_internal_calls();
-
- // Initialize GodotSharpEditor
-
- GDMonoClass *editor_klass = GDMono::get_singleton()->get_tools_assembly()->get_class("GodotTools", "GodotSharpEditor");
- CRASH_COND(editor_klass == nullptr);
+ // Load GodotTools and initialize GodotSharpEditor
- MonoObject *mono_object = mono_object_new(mono_domain_get(), editor_klass->get_mono_ptr());
- CRASH_COND(mono_object == nullptr);
+ int32_t interop_funcs_size = 0;
+ const void **interop_funcs = godotsharp::get_editor_interop_funcs(interop_funcs_size);
- MonoException *exc = nullptr;
- GDMonoUtils::runtime_object_init(mono_object, editor_klass, &exc);
- UNHANDLED_EXCEPTION(exc);
+ Object *editor_plugin_obj = GDMono::get_singleton()->get_plugin_callbacks().LoadToolsAssemblyCallback(
+ GodotSharpDirs::get_data_editor_tools_dir().plus_file("GodotTools.dll").utf16(),
+ interop_funcs, interop_funcs_size);
+ CRASH_COND(editor_plugin_obj == nullptr);
- EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(
- GDMonoMarshal::mono_object_to_variant(mono_object).operator Object *());
+ EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(editor_plugin_obj);
CRASH_COND(godotsharp_editor == nullptr);
- // Enable it as a plugin
+ // Add plugin to EditorNode and enable it
EditorNode::add_editor_plugin(godotsharp_editor);
ED_SHORTCUT("mono/build_solution", TTR("Build Solution"), KeyModifierMask::ALT | Key::B);
godotsharp_editor->enable_plugin();
@@ -1352,24 +1113,24 @@ void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
}
}
-void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, MonoGCHandleData &p_gchandle) {
- uint32_t pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(p_expected_obj); // We might lock after this, so pin it
-
- if (!p_gchandle.is_released()) { // Do not lock unnecessarily
+void CSharpLanguage::release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle) {
+ if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
MutexLock lock(get_singleton()->script_gchandle_release_mutex);
-
- MonoObject *target = p_gchandle.get_target();
-
- // We release the gchandle if it points to the MonoObject* we expect (otherwise it was
- // already released and could have been replaced) or if we can't get its target MonoObject*
- // (which doesn't necessarily mean it was released, and we want it released in order to
- // avoid locking other threads unnecessarily).
- if (target == p_expected_obj || target == nullptr) {
- p_gchandle.release();
+ if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) {
+ r_gchandle.release();
}
}
+}
- GDMonoUtils::free_gchandle(pinned_gchandle);
+void CSharpLanguage::release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding) {
+ MonoGCHandleData &gchandle = r_script_binding.gchandle;
+ if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
+ MutexLock lock(get_singleton()->script_gchandle_release_mutex);
+ if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) {
+ gchandle.release();
+ r_script_binding.inited = false; // Here too, to be thread safe
+ }
+ }
}
CSharpLanguage::CSharpLanguage() {
@@ -1401,18 +1162,23 @@ bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_b
ERR_FAIL_NULL_V(classinfo, false);
type_name = classinfo->name;
- GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
+ bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), type_name);
+ ERR_FAIL_COND_V_MSG(!parent_is_object_class, false,
+ "Type inherits from native type '" + type_name + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'.");
- ERR_FAIL_NULL_V(type_class, false);
+#ifdef DEBUG_ENABLED
+ CRASH_COND(!r_script_binding.gchandle.is_released());
+#endif
- MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
+ GCHandleIntPtr strong_gchandle =
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectBinding(
+ &type_name, p_object);
- ERR_FAIL_NULL_V(mono_object, false);
+ ERR_FAIL_NULL_V(strong_gchandle.value, false);
r_script_binding.inited = true;
r_script_binding.type_name = type_name;
- r_script_binding.wrapper_class = type_class; // cache
- r_script_binding.gchandle = MonoGCHandleData::new_strong_handle(mono_object);
+ r_script_binding.gchandle = MonoGCHandleData(strong_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
r_script_binding.owner = p_object;
// Tie managed to unmanaged
@@ -1455,7 +1221,7 @@ void CSharpLanguage::_instance_binding_free_callback(void *, void *, void *p_bin
if (GDMono::get_singleton() == nullptr) {
#ifdef DEBUG_ENABLED
- CRASH_COND(!csharp_lang->script_bindings.is_empty());
+ CRASH_COND(csharp_lang && !csharp_lang->script_bindings.is_empty());
#endif
// Mono runtime finalized, all the gchandle bindings were already released
return;
@@ -1465,8 +1231,6 @@ void CSharpLanguage::_instance_binding_free_callback(void *, void *, void *p_bin
return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
}
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
{
MutexLock lock(csharp_lang->language_bind_mutex);
@@ -1477,11 +1241,11 @@ void CSharpLanguage::_instance_binding_free_callback(void *, void *, void *p_bin
if (script_binding.inited) {
// Set the native instance field to IntPtr.Zero, if not yet garbage collected.
// This is done to avoid trying to dispose the native instance from Dispose(bool).
- MonoObject *mono_object = script_binding.gchandle.get_target();
- if (mono_object) {
- CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, nullptr);
- }
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_SetGodotObjectPtr(
+ script_binding.gchandle.get_intptr(), nullptr);
+
script_binding.gchandle.release();
+ script_binding.inited = false;
}
csharp_lang->script_bindings.erase(data);
@@ -1510,41 +1274,49 @@ GDNativeBool CSharpLanguage::_instance_binding_reference_callback(void *p_token,
if (p_reference) {
// Refcount incremented
if (refcount > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
- GD_MONO_SCOPE_THREAD_ATTACH;
-
// The reference count was increased after the managed side was the only one referencing our owner.
// This means the owner is being referenced again by the unmanaged side,
// so the owner must hold the managed side alive again to avoid it from being GCed.
- MonoObject *target = gchandle.get_target();
- if (!target) {
+ // Release the current weak handle and replace it with a strong handle.
+
+ GCHandleIntPtr old_gchandle = gchandle.get_intptr();
+ gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
+
+ GCHandleIntPtr new_gchandle = { nullptr };
+ bool create_weak = false;
+ bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
+ old_gchandle, &new_gchandle, create_weak);
+
+ if (!target_alive) {
return false; // Called after the managed side was collected, so nothing to do here
}
- // Release the current weak handle and replace it with a strong handle.
- MonoGCHandleData strong_gchandle = MonoGCHandleData::new_strong_handle(target);
- gchandle.release();
- gchandle = strong_gchandle;
+ gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
}
return false;
} else {
// Refcount decremented
if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
- GD_MONO_SCOPE_THREAD_ATTACH;
-
// If owner owner is no longer referenced by the unmanaged side,
// the managed instance takes responsibility of deleting the owner when GCed.
- MonoObject *target = gchandle.get_target();
- if (!target) {
+ // Release the current strong handle and replace it with a weak handle.
+
+ GCHandleIntPtr old_gchandle = gchandle.get_intptr();
+ gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
+
+ GCHandleIntPtr new_gchandle = { nullptr };
+ bool create_weak = true;
+ bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
+ old_gchandle, &new_gchandle, create_weak);
+
+ if (!target_alive) {
return refcount == 0; // Called after the managed side was collected, so nothing to do here
}
- // Release the current strong handle and replace it with a weak handle.
- MonoGCHandleData weak_gchandle = MonoGCHandleData::new_weak_handle(target);
- gchandle.release();
- gchandle = weak_gchandle;
+ gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
return false;
}
@@ -1589,214 +1361,160 @@ void CSharpLanguage::set_instance_binding(Object *p_object, void *p_binding) {
bool CSharpLanguage::has_instance_binding(Object *p_object) {
return p_object->has_instance_binding(get_singleton());
}
+void CSharpLanguage::tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted) {
+ // This method should not fail
-CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
- CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));
-
- RefCounted *rc = Object::cast_to<RefCounted>(p_owner);
+ CRASH_COND(!p_unmanaged);
- instance->base_ref_counted = rc != nullptr;
- instance->owner = p_owner;
- instance->gchandle = p_gchandle;
+ // All mono objects created from the managed world (e.g.: 'new Player()')
+ // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
- if (instance->base_ref_counted) {
- instance->_reference_owner_unsafe();
- }
+ RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
- p_script->instances.insert(p_owner);
+ CRASH_COND(p_ref_counted != (bool)rc);
- return instance;
-}
+ MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
+ p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
-MonoObject *CSharpInstance::get_mono_object() const {
- ERR_FAIL_COND_V(gchandle.is_released(), nullptr);
- return gchandle.get_target();
-}
+ // If it's just a wrapper Godot class and not a custom inheriting class, then attach a
+ // script binding instead. One of the advantages of this is that if a script is attached
+ // later and it's not a C# script, then the managed object won't have to be disposed.
+ // Another reason for doing this is that this instance could outlive CSharpLanguage, which would
+ // be problematic when using a script. See: https://github.com/godotengine/godot/issues/25621
-Object *CSharpInstance::get_owner() {
- return owner;
-}
-
-bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
- ERR_FAIL_COND_V(!script.is_valid(), false);
-
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- MonoObject *mono_object = get_mono_object();
- ERR_FAIL_NULL_V(mono_object, false);
+ CSharpScriptBinding script_binding;
- GDMonoClass *top = script->script_class;
+ script_binding.inited = true;
+ script_binding.type_name = *p_native_name;
+ script_binding.gchandle = gchandle;
+ script_binding.owner = p_unmanaged;
- while (top && top != script->native) {
- GDMonoField *field = top->get_field(p_name);
+ if (p_ref_counted) {
+ // Unsafe refcount increment. The managed instance also counts as a reference.
+ // This way if the unmanaged world has no references to our owner
+ // but the managed instance is alive, the refcount will be 1 instead of 0.
+ // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
- if (field) {
- field->set_value_from_variant(mono_object, p_value);
- return true;
+ // May not me referenced yet, so we must use init_ref() instead of reference()
+ if (rc->init_ref()) {
+ CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
}
+ }
- GDMonoProperty *property = top->get_property(p_name);
-
- if (property) {
- property->set_value_from_variant(mono_object, p_value);
- return true;
- }
+ // The object was just created, no script instance binding should have been attached
+ CRASH_COND(CSharpLanguage::has_instance_binding(p_unmanaged));
- top = top->get_parent_class();
+ void *data;
+ {
+ MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
+ data = (void *)CSharpLanguage::get_singleton()->insert_script_binding(p_unmanaged, script_binding);
}
- // Call _set
+ // Should be thread safe because the object was just created and nothing else should be referencing it
+ CSharpLanguage::set_instance_binding(p_unmanaged, data);
+}
- top = script->script_class;
+void CSharpLanguage::tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted) {
+ // This method should not fail
- while (top && top != script->native) {
- GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
+ Ref<CSharpScript> script = *p_script;
+ // We take care of destructing this reference here, so the managed code won't need to do another P/Invoke call
+ p_script->~Ref();
- if (method) {
- Variant name = p_name;
- const Variant *args[2] = { &name, &p_value };
+ CRASH_COND(!p_unmanaged);
- MonoObject *ret = method->invoke(mono_object, args);
+ // All mono objects created from the managed world (e.g.: 'new Player()')
+ // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
- if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret)) {
- return true;
- }
+ RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
- break;
- }
+ CRASH_COND(p_ref_counted != (bool)rc);
- top = top->get_parent_class();
- }
+ MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
+ p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
- return false;
-}
+ CRASH_COND(script.is_null());
-bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
- ERR_FAIL_COND_V(!script.is_valid(), false);
-
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- MonoObject *mono_object = get_mono_object();
- ERR_FAIL_NULL_V(mono_object, false);
+ CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(p_unmanaged, script.ptr(), gchandle);
- GDMonoClass *top = script->script_class;
+ p_unmanaged->set_script_and_instance(script, csharp_instance);
- while (top && top != script->native) {
- GDMonoField *field = top->get_field(p_name);
+ csharp_instance->connect_event_signals();
+}
- if (field) {
- MonoObject *value = field->get_value(mono_object);
- r_ret = GDMonoMarshal::mono_object_to_variant(value);
- return true;
- }
+void CSharpLanguage::tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged) {
+ // This method should not fail
- GDMonoProperty *property = top->get_property(p_name);
+ CRASH_COND(!p_unmanaged);
- if (property) {
- MonoException *exc = nullptr;
- MonoObject *value = property->get_value(mono_object, &exc);
- if (exc) {
- r_ret = Variant();
- GDMonoUtils::set_pending_exception(exc);
- } else {
- r_ret = GDMonoMarshal::mono_object_to_variant(value);
- }
- return true;
- }
+ CSharpInstance *instance = CAST_CSHARP_INSTANCE(p_unmanaged->get_script_instance());
- top = top->get_parent_class();
+ if (!instance) {
+ // Native bindings don't need post-setup
+ return;
}
- // Call _get
+ CRASH_COND(!instance->gchandle.is_released());
- top = script->script_class;
-
- while (top && top != script->native) {
- GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
-
- if (method) {
- Variant name = p_name;
- const Variant *args[1] = { &name };
-
- MonoObject *ret = method->invoke(mono_object, args);
-
- if (ret) {
- r_ret = GDMonoMarshal::mono_object_to_variant(ret);
- return true;
- }
+ // Tie managed to unmanaged
+ instance->gchandle = MonoGCHandleData(p_gchandle_intptr, gdmono::GCHandleType::STRONG_HANDLE);
- break;
- }
+ if (instance->base_ref_counted) {
+ instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
+ }
- top = top->get_parent_class();
+ {
+ MutexLock lock(CSharpLanguage::get_singleton()->get_script_instances_mutex());
+ // instances is a set, so it's safe to insert multiple times (e.g.: from _internal_new_managed)
+ instance->script->instances.insert(instance->owner);
}
- return false;
+ instance->connect_event_signals();
}
-void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant>> &r_state) {
- List<PropertyInfo> property_list;
- get_property_list(&property_list);
-
- for (const PropertyInfo &prop_info : property_list) {
- Pair<StringName, Variant> state_pair;
- state_pair.first = prop_info.name;
+CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
+ CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));
- ManagedType managedType;
+ RefCounted *rc = Object::cast_to<RefCounted>(p_owner);
- GDMonoField *field = nullptr;
- GDMonoClass *top = script->script_class;
- while (top && top != script->native) {
- field = top->get_field(state_pair.first);
- if (field) {
- break;
- }
+ instance->base_ref_counted = rc != nullptr;
+ instance->owner = p_owner;
+ instance->gchandle = p_gchandle;
- top = top->get_parent_class();
- }
- if (!field) {
- continue; // Properties ignored. We get the property baking fields instead.
- }
+ if (instance->base_ref_counted) {
+ instance->_reference_owner_unsafe();
+ }
- managedType = field->get_type();
+ p_script->instances.insert(p_owner);
- if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it
- if (get(state_pair.first, state_pair.second)) {
- r_state.push_back(state_pair);
- }
- }
- }
+ return instance;
}
-void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName, Array>> &r_state) {
- MonoObject *owner_managed = get_mono_object();
- ERR_FAIL_NULL(owner_managed);
+Object *CSharpInstance::get_owner() {
+ return owner;
+}
- for (const KeyValue<StringName, CSharpScript::EventSignal> &E : script->event_signals) {
- const CSharpScript::EventSignal &event_signal = E.value;
+bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
+ ERR_FAIL_COND_V(!script.is_valid(), false);
- MonoDelegate *delegate_field_value = (MonoDelegate *)event_signal.field->get_value(owner_managed);
- if (!delegate_field_value) {
- continue; // Empty
- }
+ return GDMonoCache::managed_callbacks.CSharpInstanceBridge_Set(
+ gchandle.get_intptr(), &p_name, &p_value);
+}
- Array serialized_data;
- MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
+bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
+ ERR_FAIL_COND_V(!script.is_valid(), false);
- MonoException *exc = nullptr;
- bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TrySerializeDelegate).invoke(delegate_field_value, managed_serialized_data, &exc);
+ Variant ret_value;
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- continue;
- }
+ bool ret = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Get(
+ gchandle.get_intptr(), &p_name, &ret_value);
- if (success) {
- r_state.push_back(Pair<StringName, Array>(event_signal.field->get_name(), serialized_data));
- } else if (OS::get_singleton()->is_stdout_verbose()) {
- OS::get_singleton()->print("Failed to serialize event signal delegate\n");
- }
+ if (ret) {
+ r_ret = ret_value;
+ return true;
}
+
+ return false;
}
void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
@@ -1807,30 +1525,25 @@ void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
ERR_FAIL_COND(!script.is_valid());
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- MonoObject *mono_object = get_mono_object();
- ERR_FAIL_NULL(mono_object);
-
- GDMonoClass *top = script->script_class;
+ StringName method = SNAME("_get_property_list");
- while (top && top != script->native) {
- GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get_property_list), 0);
+ Variant ret;
+ Callable::CallError call_error;
+ bool ok = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
+ gchandle.get_intptr(), &method, nullptr, 0, &call_error, &ret);
- if (method) {
- MonoObject *ret = method->invoke(mono_object);
-
- if (ret) {
- Array array = Array(GDMonoMarshal::mono_object_to_variant(ret));
- for (int i = 0, size = array.size(); i < size; i++) {
- props.push_back(PropertyInfo::from_dict(array.get(i)));
- }
+ // CALL_ERROR_INVALID_METHOD would simply mean it was not overridden
+ if (call_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD) {
+ if (call_error.error != Callable::CallError::CALL_OK) {
+ ERR_PRINT("Error calling '_get_property_list': " + Variant::get_call_error_text(method, nullptr, 0, call_error));
+ } else if (!ok) {
+ ERR_PRINT("Unexpected error calling '_get_property_list'");
+ } else {
+ Array array = ret;
+ for (int i = 0, size = array.size(); i < size; i++) {
+ p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
}
-
- break;
}
-
- top = top->get_parent_class();
}
for (const PropertyInfo &prop : props) {
@@ -1853,84 +1566,79 @@ Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *
return Variant::NIL;
}
-void CSharpInstance::get_method_list(List<MethodInfo> *p_list) const {
- if (!script->is_valid() || !script->script_class) {
- return;
- }
-
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- // TODO: We're filtering out constructors but there may be other methods unsuitable for explicit calls.
- GDMonoClass *top = script->script_class;
+bool CSharpInstance::property_can_revert(const StringName &p_name) const {
+ ERR_FAIL_COND_V(!script.is_valid(), false);
- while (top && top != script->native) {
- const Vector<GDMonoMethod *> &methods = top->get_all_methods();
- for (int i = 0; i < methods.size(); ++i) {
- MethodInfo minfo = methods[i]->get_method_info();
- if (minfo.name != CACHED_STRING_NAME(dotctor)) {
- p_list->push_back(minfo);
- }
- }
+ Variant name_arg = p_name;
+ const Variant *args[1] = { &name_arg };
- top = top->get_parent_class();
- }
-}
+ Variant ret;
+ Callable::CallError call_error;
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
+ gchandle.get_intptr(), &CACHED_STRING_NAME(_property_can_revert), args, 1, &call_error, &ret);
-bool CSharpInstance::has_method(const StringName &p_method) const {
- if (!script.is_valid()) {
+ if (call_error.error != Callable::CallError::CALL_OK) {
return false;
}
- GD_MONO_SCOPE_THREAD_ATTACH;
+ return (bool)ret;
+}
- GDMonoClass *top = script->script_class;
+bool CSharpInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
+ ERR_FAIL_COND_V(!script.is_valid(), false);
- while (top && top != script->native) {
- if (top->has_fetched_method_unknown_params(p_method)) {
- return true;
- }
+ Variant name_arg = p_name;
+ const Variant *args[1] = { &name_arg };
+
+ Variant ret;
+ Callable::CallError call_error;
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
+ gchandle.get_intptr(), &CACHED_STRING_NAME(_property_get_revert), args, 1, &call_error, &ret);
- top = top->get_parent_class();
+ if (call_error.error != Callable::CallError::CALL_OK) {
+ return false;
}
- return false;
+ r_ret = ret;
+ return true;
}
-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;
-
- MonoObject *mono_object = get_mono_object();
-
- if (!mono_object) {
- r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
- ERR_FAIL_V(Variant());
+void CSharpInstance::get_method_list(List<MethodInfo> *p_list) const {
+ if (!script->is_valid() || !script->valid) {
+ return;
}
- GDMonoClass *top = script->script_class;
+ const CSharpScript *top = script.ptr();
+ while (top != nullptr) {
+ for (const CSharpScript::CSharpMethodInfo &E : top->methods) {
+ p_list->push_back(E.method_info);
+ }
- while (top && top != script->native) {
- GDMonoMethod *method = top->get_method(p_method, p_argcount);
+ top = top->base_script.ptr();
+ }
+}
- if (method) {
- MonoObject *return_value = method->invoke(mono_object, p_args);
+bool CSharpInstance::has_method(const StringName &p_method) const {
+ if (!script.is_valid()) {
+ return false;
+ }
- r_error.error = Callable::CallError::CALL_OK;
+ if (!GDMonoCache::godot_api_cache_updated) {
+ return false;
+ }
- if (return_value) {
- return GDMonoMarshal::mono_object_to_variant(return_value);
- } else {
- return Variant();
- }
- }
+ return GDMonoCache::managed_callbacks.CSharpInstanceBridge_HasMethodUnknownParams(
+ gchandle.get_intptr(), &p_method);
+}
- top = top->get_parent_class();
- }
+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());
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
+ Variant ret;
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
+ gchandle.get_intptr(), &p_method, p_args, p_argcount, &r_error, &ret);
- return Variant();
+ return ret;
}
bool CSharpInstance::_reference_owner_unsafe() {
@@ -1976,48 +1684,29 @@ bool CSharpInstance::_unreference_owner_unsafe() {
return static_cast<RefCounted *>(owner)->unreference();
}
-MonoObject *CSharpInstance::_internal_new_managed() {
- // Search the constructor first, to fail with an error if it's not found before allocating anything else.
- GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
- ERR_FAIL_NULL_V_MSG(ctor, nullptr,
- "Cannot create script instance because the class does not define a parameterless constructor: '" + script->get_path() + "'.");
-
+bool CSharpInstance::_internal_new_managed() {
CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
- ERR_FAIL_NULL_V(owner, nullptr);
- ERR_FAIL_COND_V(script.is_null(), nullptr);
+ ERR_FAIL_NULL_V(owner, false);
+ ERR_FAIL_COND_V(script.is_null(), false);
- MonoObject *mono_object = mono_object_new(mono_domain_get(), script->script_class->get_mono_ptr());
+ bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
+ script.ptr(), owner, nullptr, 0);
- if (!mono_object) {
+ if (!ok) {
// Important to clear this before destroying the script instance here
script = Ref<CSharpScript>();
-
- bool die = _unreference_owner_unsafe();
- // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
- CRASH_COND(die);
-
owner = nullptr;
- ERR_FAIL_V_MSG(nullptr, "Failed to allocate memory for the object.");
- }
-
- // Tie managed to unmanaged
- gchandle = MonoGCHandleData::new_strong_handle(mono_object);
-
- if (base_ref_counted) {
- _reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
+ return false;
}
- CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);
-
- // Construct
- ctor->invoke_raw(mono_object, nullptr);
+ CRASH_COND(gchandle.is_released());
- return mono_object;
+ return true;
}
-void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
+void CSharpInstance::mono_object_disposed(GCHandleIntPtr p_gchandle_to_free) {
// Must make sure event signals are not left dangling
disconnect_event_signals();
@@ -2025,10 +1714,10 @@ void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
CRASH_COND(base_ref_counted);
CRASH_COND(gchandle.is_released());
#endif
- CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
+ CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
}
-void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
+void CSharpInstance::mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
#ifdef DEBUG_ENABLED
CRASH_COND(!base_ref_counted);
CRASH_COND(gchandle.is_released());
@@ -2044,20 +1733,20 @@ void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_f
r_delete_owner = true;
} else {
r_delete_owner = false;
- CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
+ CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
if (!p_is_finalizer) {
// If the native instance is still alive and Dispose() was called
// (instead of the finalizer), then we remove the script instance.
r_remove_script_instance = true;
+ // TODO: Last usage of 'is_finalizing_scripts_domain'. It should be replaced with a check to determine if the load context is being unloaded.
} else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
// If the native instance is still alive and this is called from the finalizer,
// then it was referenced from another thread before the finalizer could
// unreference and delete it, so we want to keep it.
// GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
// could have already been collected. Instead we will create a new managed instance here.
- MonoObject *new_managed = _internal_new_managed();
- if (!new_managed) {
+ if (!_internal_new_managed()) {
r_remove_script_instance = true;
}
}
@@ -2065,17 +1754,20 @@ void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_f
}
void CSharpInstance::connect_event_signals() {
- for (const KeyValue<StringName, CSharpScript::EventSignal> &E : script->event_signals) {
- const CSharpScript::EventSignal &event_signal = E.value;
+ CSharpScript *top = script.ptr();
+ while (top != nullptr) {
+ for (CSharpScript::EventSignalInfo &signal : top->get_script_event_signals()) {
+ String signal_name = signal.name;
- StringName signal_name = event_signal.field->get_name();
+ // TODO: Use pooling for ManagedCallable instances.
+ EventSignalCallable *event_signal_callable = memnew(EventSignalCallable(owner, signal_name));
- // TODO: Use pooling for ManagedCallable instances.
- EventSignalCallable *event_signal_callable = memnew(EventSignalCallable(owner, &event_signal));
+ Callable callable(event_signal_callable);
+ connected_event_signals.push_back(callable);
+ owner->connect(signal_name, callable);
+ }
- Callable callable(event_signal_callable);
- connected_event_signals.push_back(callable);
- owner->connect(signal_name, callable);
+ top = top->base_script.ptr();
}
}
@@ -2097,16 +1789,25 @@ void CSharpInstance::refcount_incremented() {
RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
if (rc_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
- GD_MONO_SCOPE_THREAD_ATTACH;
-
// The reference count was increased after the managed side was the only one referencing our owner.
// This means the owner is being referenced again by the unmanaged side,
// so the owner must hold the managed side alive again to avoid it from being GCed.
// Release the current weak handle and replace it with a strong handle.
- MonoGCHandleData strong_gchandle = MonoGCHandleData::new_strong_handle(gchandle.get_target());
- gchandle.release();
- gchandle = strong_gchandle;
+
+ GCHandleIntPtr old_gchandle = gchandle.get_intptr();
+ gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
+
+ GCHandleIntPtr new_gchandle = { nullptr };
+ bool create_weak = false;
+ bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
+ old_gchandle, &new_gchandle, create_weak);
+
+ if (!target_alive) {
+ return; // Called after the managed side was collected, so nothing to do here
+ }
+
+ gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
}
}
@@ -2121,15 +1822,24 @@ bool CSharpInstance::refcount_decremented() {
int refcount = rc_owner->reference_get_count();
if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
- GD_MONO_SCOPE_THREAD_ATTACH;
-
// If owner owner is no longer referenced by the unmanaged side,
// the managed instance takes responsibility of deleting the owner when GCed.
// Release the current strong handle and replace it with a weak handle.
- MonoGCHandleData weak_gchandle = MonoGCHandleData::new_weak_handle(gchandle.get_target());
- gchandle.release();
- gchandle = weak_gchandle;
+
+ GCHandleIntPtr old_gchandle = gchandle.get_intptr();
+ gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
+
+ GCHandleIntPtr new_gchandle = { nullptr };
+ bool create_weak = true;
+ bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
+ old_gchandle, &new_gchandle, create_weak);
+
+ if (!target_alive) {
+ return refcount == 0; // Called after the managed side was collected, so nothing to do here
+ }
+
+ gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
return false;
}
@@ -2144,8 +1854,6 @@ const Variant CSharpInstance::get_rpc_config() const {
}
void CSharpInstance::notification(int p_notification) {
- GD_MONO_SCOPE_THREAD_ATTACH;
-
if (p_notification == Object::NOTIFICATION_PREDELETE) {
// When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
// It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
@@ -2165,15 +1873,8 @@ void CSharpInstance::notification(int p_notification) {
_call_notification(p_notification);
- MonoObject *mono_object = get_mono_object();
- ERR_FAIL_NULL(mono_object);
-
- MonoException *exc = nullptr;
- GDMonoUtils::dispose(mono_object, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- }
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
+ gchandle.get_intptr(), /* okIfNull */ false);
return;
}
@@ -2182,62 +1883,29 @@ void CSharpInstance::notification(int p_notification) {
}
void CSharpInstance::_call_notification(int p_notification) {
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
- MonoObject *mono_object = get_mono_object();
- ERR_FAIL_NULL(mono_object);
-
- // Custom version of _call_multilevel, optimized for _notification
+ Variant arg = p_notification;
+ const Variant *args[1] = { &arg };
+ StringName method_name = SNAME("_notification");
- int32_t arg = p_notification;
- void *args[1] = { &arg };
- StringName method_name = CACHED_STRING_NAME(_notification);
+ Callable::CallError call_error;
- GDMonoClass *top = script->script_class;
-
- while (top && top != script->native) {
- GDMonoMethod *method = top->get_method(method_name, 1);
-
- if (method) {
- method->invoke_raw(mono_object, args);
- return;
- }
-
- top = top->get_parent_class();
- }
+ Variant ret;
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
+ gchandle.get_intptr(), &method_name, args, 1, &call_error, &ret);
}
String CSharpInstance::to_string(bool *r_valid) {
- GD_MONO_SCOPE_THREAD_ATTACH;
+ String res;
+ bool valid;
- MonoObject *mono_object = get_mono_object();
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallToString(
+ gchandle.get_intptr(), &res, &valid);
- if (mono_object == nullptr) {
- if (r_valid) {
- *r_valid = false;
- }
- return String();
- }
-
- MonoException *exc = nullptr;
- MonoString *result = GDMonoUtils::object_to_string(mono_object, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- if (r_valid) {
- *r_valid = false;
- }
- return String();
- }
-
- if (result == nullptr) {
- if (r_valid) {
- *r_valid = false;
- }
- return String();
+ if (r_valid) {
+ *r_valid = valid;
}
- return GDMonoMarshal::mono_string_to_godot(result);
+ return res;
}
Ref<Script> CSharpInstance::get_script() const {
@@ -2253,8 +1921,6 @@ CSharpInstance::CSharpInstance(const Ref<CSharpScript> &p_script) :
}
CSharpInstance::~CSharpInstance() {
- GD_MONO_SCOPE_THREAD_ATTACH;
-
destructing_script_instance = true;
// Must make sure event signals are not left dangling
@@ -2268,16 +1934,8 @@ CSharpInstance::~CSharpInstance() {
// we must call Dispose here, because Dispose calls owner->set_script_instance(nullptr)
// and that would mess up with the new script instance if called later.
- MonoObject *mono_object = gchandle.get_target();
-
- if (mono_object) {
- MonoException *exc = nullptr;
- GDMonoUtils::dispose(mono_object, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- }
- }
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
+ gchandle.get_intptr(), /* okIfNull */ true);
}
gchandle.release(); // Make sure the gchandle is released
@@ -2341,63 +1999,8 @@ void CSharpScript::_update_exports_values(HashMap<StringName, Variant> &values,
propnames.push_back(prop_info);
}
- if (base_cache.is_valid()) {
- base_cache->_update_exports_values(values, propnames);
- }
-}
-
-void CSharpScript::_update_member_info_no_exports() {
- if (exports_invalidated) {
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
- exports_invalidated = false;
-
- member_info.clear();
-
- GDMonoClass *top = script_class;
- List<PropertyInfo> props;
-
- while (top && top != native) {
- PropertyInfo prop_info;
- bool exported;
-
- const Vector<GDMonoField *> &fields = top->get_all_fields();
-
- for (int i = fields.size() - 1; i >= 0; i--) {
- GDMonoField *field = fields[i];
-
- if (_get_member_export(field, /* inspect export: */ false, prop_info, exported)) {
- StringName member_name = field->get_name();
-
- member_info[member_name] = prop_info;
- props.push_front(prop_info);
- exported_members_defval_cache[member_name] = Variant();
- }
- }
-
- const Vector<GDMonoProperty *> &properties = top->get_all_properties();
-
- for (int i = properties.size() - 1; i >= 0; i--) {
- GDMonoProperty *property = properties[i];
-
- if (_get_member_export(property, /* inspect export: */ false, prop_info, exported)) {
- StringName member_name = property->get_name();
-
- member_info[member_name] = prop_info;
- props.push_front(prop_info);
- exported_members_defval_cache[member_name] = Variant();
- }
- }
-
- exported_members_cache.push_back(PropertyInfo(Variant::NIL, top->get_name(), PROPERTY_HINT_NONE, get_path(), PROPERTY_USAGE_CATEGORY));
- for (const PropertyInfo &E : props) {
- exported_members_cache.push_back(E);
- }
-
- props.clear();
-
- top = top->get_parent_class();
- }
+ if (base_script.is_valid()) {
+ base_script->_update_exports_values(values, propnames);
}
}
#endif
@@ -2419,166 +2022,65 @@ bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_upda
if (exports_invalidated)
#endif
{
- GD_MONO_SCOPE_THREAD_ATTACH;
+#ifdef TOOLS_ENABLED
+ exports_invalidated = false;
+#endif
changed = true;
member_info.clear();
#ifdef TOOLS_ENABLED
- MonoObject *tmp_object = nullptr;
- Object *tmp_native = nullptr;
- uint32_t tmp_pinned_gchandle = 0;
-
- if (is_editor) {
- exports_invalidated = false;
-
- exported_members_cache.clear();
- exported_members_defval_cache.clear();
-
- // Here we create a temporary managed instance of the class to get the initial values
- tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
-
- if (!tmp_object) {
- ERR_PRINT("Failed to allocate temporary MonoObject.");
- return false;
- }
-
- tmp_pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(tmp_object); // pin it (not sure if needed)
-
- GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
-
- ERR_FAIL_NULL_V_MSG(ctor, false,
- "Cannot construct temporary MonoObject because the class does not define a parameterless constructor: '" + get_path() + "'.");
-
- MonoException *ctor_exc = nullptr;
- ctor->invoke(tmp_object, nullptr, &ctor_exc);
-
- tmp_native = GDMonoMarshal::unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(tmp_object));
-
- if (ctor_exc) {
- // TODO: Should we free 'tmp_native' if the exception was thrown after its creation?
-
- GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
- tmp_object = nullptr;
-
- ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
- GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
- return false;
- }
- }
+ exported_members_cache.clear();
+ exported_members_defval_cache.clear();
#endif
- GDMonoClass *top = script_class;
- List<PropertyInfo> props;
-
- while (top && top != native) {
- PropertyInfo prop_info;
- bool exported;
-
- const Vector<GDMonoField *> &fields = top->get_all_fields();
-
- for (int i = fields.size() - 1; i >= 0; i--) {
- GDMonoField *field = fields[i];
-
- if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) {
- StringName member_name = field->get_name();
-
- member_info[member_name] = prop_info;
-
- if (exported) {
+ if (GDMonoCache::godot_api_cache_updated) {
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyInfoList(this,
+ [](CSharpScript *p_script, const String *p_current_class_name, GDMonoCache::godotsharp_property_info *p_props, int32_t p_count) {
#ifdef TOOLS_ENABLED
- if (is_editor) {
- props.push_front(prop_info);
-
- if (tmp_object) {
- exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
- }
- }
+ p_script->exported_members_cache.push_back(PropertyInfo(
+ Variant::NIL, *p_current_class_name, PROPERTY_HINT_NONE,
+ p_script->get_path(), PROPERTY_USAGE_CATEGORY));
#endif
-#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
- exported_members_names.insert(member_name);
-#endif
- }
- }
- }
+ for (int i = 0; i < p_count; i++) {
+ const GDMonoCache::godotsharp_property_info &prop = p_props[i];
- const Vector<GDMonoProperty *> &properties = top->get_all_properties();
+ StringName name = *reinterpret_cast<const StringName *>(&prop.name);
+ String hint_string = *reinterpret_cast<const String *>(&prop.hint_string);
- for (int i = properties.size() - 1; i >= 0; i--) {
- GDMonoProperty *property = properties[i];
+ PropertyInfo pinfo(prop.type, name, prop.hint, hint_string, prop.usage);
- if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) {
- StringName member_name = property->get_name();
+ p_script->member_info[name] = pinfo;
- member_info[member_name] = prop_info;
+ if (prop.exported) {
- if (exported) {
#ifdef TOOLS_ENABLED
- if (is_editor) {
- props.push_front(prop_info);
- if (tmp_object) {
- MonoException *exc = nullptr;
- MonoObject *ret = property->get_value(tmp_object, &exc);
- if (exc) {
- exported_members_defval_cache[member_name] = Variant();
- GDMonoUtils::debug_print_unhandled_exception(exc);
- } else {
- exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
- }
- }
- }
+ p_script->exported_members_cache.push_back(pinfo);
#endif
#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
- exported_members_names.insert(member_name);
+ p_script->exported_members_names.insert(name);
#endif
- }
- }
- }
-
-#ifdef TOOLS_ENABLED
- exported_members_cache.push_back(PropertyInfo(Variant::NIL, top->get_name(), PROPERTY_HINT_NONE, get_path(), PROPERTY_USAGE_CATEGORY));
-
- for (const PropertyInfo &E : props) {
- exported_members_cache.push_back(E);
- }
-
- props.clear();
-#endif // TOOLS_ENABLED
-
- top = top->get_parent_class();
- }
+ }
+ }
+ });
#ifdef TOOLS_ENABLED
- if (is_editor) {
- // Need to check this here, before disposal
- bool base_ref_counted = Object::cast_to<RefCounted>(tmp_native) != nullptr;
-
- // Dispose the temporary managed instance
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyDefaultValues(this,
+ [](CSharpScript *p_script, GDMonoCache::godotsharp_property_def_val_pair *p_def_vals, int32_t p_count) {
+ for (int i = 0; i < p_count; i++) {
+ const GDMonoCache::godotsharp_property_def_val_pair &def_val_pair = p_def_vals[i];
- MonoException *exc = nullptr;
- GDMonoUtils::dispose(tmp_object, &exc);
+ StringName name = *reinterpret_cast<const StringName *>(&def_val_pair.name);
+ Variant value = *reinterpret_cast<const Variant *>(&def_val_pair.value);
- if (exc) {
- ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
- GDMonoUtils::debug_print_unhandled_exception(exc);
- }
-
- GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
- tmp_object = nullptr;
-
- if (tmp_native && !base_ref_counted) {
- Node *node = Object::cast_to<Node>(tmp_native);
- if (node && node->is_inside_tree()) {
- ERR_PRINT("Temporary instance was added to the scene tree.");
- } else {
- memdelete(tmp_native);
- }
- }
- }
+ p_script->exported_members_defval_cache[name] = value;
+ }
+ });
#endif
+ }
}
#ifdef TOOLS_ENABLED
@@ -2605,374 +2107,6 @@ bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_upda
return changed;
}
-void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
- // no need to load the script's signals more than once
- if (!signals_invalidated) {
- return;
- }
-
- // make sure this classes signals are empty when loading for the first time
- _signals.clear();
- event_signals.clear();
-
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- GDMonoClass *top = p_class;
- while (top && top != p_native_class) {
- const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
- for (int i = delegates.size() - 1; i >= 0; --i) {
- GDMonoClass *delegate = delegates[i];
-
- if (!delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
- continue;
- }
-
- // Arguments are accessibles as arguments of .Invoke method
- GDMonoMethod *invoke_method = delegate->get_method(mono_get_delegate_invoke(delegate->get_mono_ptr()));
-
- Vector<SignalParameter> parameters;
- if (_get_signal(top, invoke_method, parameters)) {
- _signals[delegate->get_name()] = parameters;
- }
- }
-
- List<StringName> found_event_signals;
-
- void *iter = nullptr;
- MonoEvent *raw_event = nullptr;
- while ((raw_event = mono_class_get_events(top->get_mono_ptr(), &iter)) != nullptr) {
- MonoCustomAttrInfo *event_attrs = mono_custom_attrs_from_event(top->get_mono_ptr(), raw_event);
- if (event_attrs) {
- if (mono_custom_attrs_has_attr(event_attrs, CACHED_CLASS(SignalAttribute)->get_mono_ptr())) {
- String event_name = String::utf8(mono_event_get_name(raw_event));
- found_event_signals.push_back(StringName(event_name));
- }
-
- mono_custom_attrs_free(event_attrs);
- }
- }
-
- const Vector<GDMonoField *> &fields = top->get_all_fields();
- for (int i = 0; i < fields.size(); i++) {
- GDMonoField *field = fields[i];
-
- GDMonoClass *field_class = field->get_type().type_class;
-
- if (!mono_class_is_delegate(field_class->get_mono_ptr())) {
- continue;
- }
-
- if (!found_event_signals.find(field->get_name())) {
- continue;
- }
-
- GDMonoMethod *invoke_method = field_class->get_method(mono_get_delegate_invoke(field_class->get_mono_ptr()));
-
- Vector<SignalParameter> parameters;
- if (_get_signal(top, invoke_method, parameters)) {
- event_signals[field->get_name()] = { field, invoke_method, parameters };
- }
- }
-
- top = top->get_parent_class();
- }
-
- signals_invalidated = false;
-}
-
-bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoMethod *p_delegate_invoke, Vector<SignalParameter> &params) {
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
- Vector<StringName> names;
- Vector<ManagedType> types;
- p_delegate_invoke->get_parameter_names(names);
- p_delegate_invoke->get_parameter_types(types);
-
- for (int i = 0; i < names.size(); ++i) {
- SignalParameter arg;
- arg.name = names[i];
-
- bool nil_is_variant = false;
- arg.type = GDMonoMarshal::managed_to_variant_type(types[i], &nil_is_variant);
-
- if (arg.type == Variant::NIL) {
- if (nil_is_variant) {
- arg.nil_is_variant = true;
- } else {
- ERR_PRINT("Unknown type of signal parameter: '" + arg.name + "' in '" + p_class->get_full_name() + "'.");
- return false;
- }
- }
-
- params.push_back(arg);
- }
-
- return true;
-}
-
-/**
- * Returns false if there was an error, otherwise true.
- * If there was an error, r_prop_info and r_exported are not assigned any value.
- */
-bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) {
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
- // Goddammit, C++. All I wanted was some nested functions.
-#define MEMBER_FULL_QUALIFIED_NAME(m_member) \
- (m_member->get_enclosing_class()->get_full_name() + "." + (String)m_member->get_name())
-
- if (p_member->is_static()) {
-#ifdef TOOLS_ENABLED
- if (p_member->has_attribute(CACHED_CLASS(ExportAttribute))) {
- ERR_PRINT("Cannot export member because it is static: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
- }
-#endif
- return false;
- }
-
- if (member_info.has(p_member->get_name())) {
- return false;
- }
-
- ManagedType type;
-
- if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_FIELD) {
- type = static_cast<GDMonoField *>(p_member)->get_type();
- } else if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
- type = static_cast<GDMonoProperty *>(p_member)->get_type();
- } else {
- CRASH_NOW();
- }
-
- bool exported = p_member->has_attribute(CACHED_CLASS(ExportAttribute));
-
- if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
- GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
- if (!property->has_getter()) {
-#ifdef TOOLS_ENABLED
- if (exported) {
- ERR_PRINT("Cannot export a property without a getter: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
- }
-#endif
- return false;
- }
- if (!property->has_setter()) {
-#ifdef TOOLS_ENABLED
- if (exported) {
- ERR_PRINT("Cannot export a property without a setter: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
- }
-#endif
- return false;
- }
- }
-
- bool nil_is_variant = false;
- Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type, &nil_is_variant);
-
- if (!p_inspect_export || !exported) {
- r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
- r_exported = false;
- return true;
- }
-
-#ifdef TOOLS_ENABLED
- MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
-#endif
-
- PropertyHint hint = PROPERTY_HINT_NONE;
- String hint_string;
-
- if (variant_type == Variant::NIL && !nil_is_variant) {
-#ifdef TOOLS_ENABLED
- ERR_PRINT("Unknown exported member type: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
-#endif
- return false;
- }
-
-#ifdef TOOLS_ENABLED
- int hint_res = _try_get_member_export_hint(p_member, type, variant_type, /* allow_generics: */ true, hint, hint_string);
-
- ERR_FAIL_COND_V_MSG(hint_res == -1, false,
- "Error while trying to determine information about the exported member: '" +
- MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
-
- if (hint_res == 0) {
- hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
- hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
- }
-#endif
-
- uint32_t prop_usage = PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE;
-
- if (variant_type == Variant::NIL) {
- // System.Object (Variant)
- prop_usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- }
-
- r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), hint, hint_string, prop_usage);
- r_exported = true;
-
- return true;
-
-#undef MEMBER_FULL_QUALIFIED_NAME
-}
-
-#ifdef TOOLS_ENABLED
-int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string) {
- if (p_variant_type == Variant::NIL) {
- // System.Object (Variant)
- return 1;
- }
-
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
- if (p_variant_type == Variant::INT && p_type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(p_type.type_class->get_mono_ptr())) {
- MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type());
- r_hint = GDMonoUtils::Marshal::type_has_flags_attribute(reftype) ? PROPERTY_HINT_FLAGS : PROPERTY_HINT_ENUM;
-
- Vector<MonoClassField *> fields = p_type.type_class->get_enum_fields();
-
- MonoType *enum_basetype = mono_class_enum_basetype(p_type.type_class->get_mono_ptr());
-
- String name_only_hint_string;
-
- // True: enum Foo { Bar, Baz, Quux }
- // True: enum Foo { Bar = 0, Baz = 1, Quux = 2 }
- // False: enum Foo { Bar = 0, Baz = 7, Quux = 5 }
- bool uses_default_values = true;
-
- for (int i = 0; i < fields.size(); i++) {
- MonoClassField *field = fields[i];
-
- if (i > 0) {
- r_hint_string += ",";
- name_only_hint_string += ",";
- }
-
- String enum_field_name = String::utf8(mono_field_get_name(field));
- r_hint_string += enum_field_name;
- name_only_hint_string += enum_field_name;
-
- // TODO:
- // Instead of using mono_field_get_value_object, we can do this without boxing. Check the
- // internal mono functions: ves_icall_System_Enum_GetEnumValuesAndNames and the get_enum_field.
-
- MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, nullptr);
-
- ERR_FAIL_NULL_V_MSG(val_obj, -1, "Failed to get '" + enum_field_name + "' constant enum value.");
-
- bool r_error;
- uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error);
- ERR_FAIL_COND_V_MSG(r_error, -1, "Failed to unbox '" + enum_field_name + "' constant enum value.");
-
- unsigned int expected_val = r_hint == PROPERTY_HINT_FLAGS ? 1 << i : i;
- if (val != expected_val) {
- uses_default_values = false;
- }
-
- r_hint_string += ":";
- r_hint_string += String::num_uint64(val);
- }
-
- if (uses_default_values) {
- // If we use the format NAME:VAL, that's what the editor displays.
- // That's annoying if the user is not using custom values for the enum constants.
- // This may not be needed in the future if the editor is changed to not display values.
- r_hint_string = name_only_hint_string;
- }
- } else if (p_variant_type == Variant::OBJECT && CACHED_CLASS(GodotResource)->is_assignable_from(p_type.type_class)) {
- GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(p_type.type_class);
- CRASH_COND(field_native_class == nullptr);
-
- r_hint = PROPERTY_HINT_RESOURCE_TYPE;
- r_hint_string = String(NATIVE_GDMONOCLASS_NAME(field_native_class));
- } else if (p_variant_type == Variant::OBJECT && CACHED_CLASS(Node)->is_assignable_from(p_type.type_class)) {
- GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(p_type.type_class);
- CRASH_COND(field_native_class == nullptr);
-
- r_hint = PROPERTY_HINT_NODE_TYPE;
- r_hint_string = String(NATIVE_GDMONOCLASS_NAME(field_native_class));
- } else if (p_allow_generics && p_variant_type == Variant::ARRAY) {
- // Nested arrays are not supported in the inspector
-
- ManagedType elem_type;
-
- if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type)) {
- return 0;
- }
-
- Variant::Type elem_variant_type = GDMonoMarshal::managed_to_variant_type(elem_type);
-
- PropertyHint elem_hint = PROPERTY_HINT_NONE;
- String elem_hint_string;
-
- ERR_FAIL_COND_V_MSG(elem_variant_type == Variant::NIL, -1, "Unknown array element type.");
-
- bool preset_hint = false;
- if (elem_variant_type == Variant::STRING) {
- MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
- if (PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr)) == PROPERTY_HINT_ENUM) {
- r_hint_string = itos(elem_variant_type) + "/" + itos(PROPERTY_HINT_ENUM) + ":" + CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
- preset_hint = true;
- }
- }
-
- if (!preset_hint) {
- int hint_res = _try_get_member_export_hint(p_member, elem_type, elem_variant_type, /* allow_generics: */ false, elem_hint, elem_hint_string);
-
- ERR_FAIL_COND_V_MSG(hint_res == -1, -1, "Error while trying to determine information about the array element type.");
-
- // Format: type/hint:hint_string
- r_hint_string = itos(elem_variant_type) + "/" + itos(elem_hint) + ":" + elem_hint_string;
- }
-
- r_hint = PROPERTY_HINT_TYPE_STRING;
-
- } else if (p_allow_generics && p_variant_type == Variant::DICTIONARY) {
- // TODO: Dictionaries are not supported in the inspector
- } else {
- return 0;
- }
-
- return 1;
-}
-#endif
-
-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;
- return Variant();
- }
-
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- GDMonoClass *top = script_class;
-
- while (top && top != native) {
- GDMonoMethod *method = top->get_method(p_method, p_argcount);
-
- if (method && method->is_static()) {
- MonoObject *result = method->invoke(nullptr, p_args);
-
- if (result) {
- return GDMonoMarshal::mono_object_to_variant(result);
- } else {
- return Variant();
- }
- }
-
- top = top->get_parent_class();
- }
-
- // No static method found. Try regular instance calls
- return Script::callp(p_method, p_args, p_argcount, r_error);
-}
-
-void CSharpScript::_resource_path_changed() {
- _update_name();
-}
-
bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
if (p_name == CSharpLanguage::singleton->string_names._script_source) {
r_ret = get_source_code();
@@ -3000,107 +2134,107 @@ void CSharpScript::_bind_methods() {
ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
}
-Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
- // This method should not fail, only assertions allowed
-
- CRASH_COND(p_class == nullptr);
+void CSharpScript::reload_registered_script(Ref<CSharpScript> p_script) {
+ // IMPORTANT:
+ // This method must be called only after the CSharpScript and its associated type
+ // have been added to the script bridge map in the ScriptManagerBridge C# class.
+ // Other than that, it's the same as `CSharpScript::reload`.
- // TODO OPTIMIZE: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
- Ref<CSharpScript> script = memnew(CSharpScript);
+ // This method should not fail, only assertions allowed.
- initialize_for_managed_type(script, p_class, p_native);
-
- return script;
-}
-
-void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native) {
- // This method should not fail, only assertions allowed
-
- CRASH_COND(p_class == nullptr);
-
- p_script->name = p_class->get_name();
- p_script->script_class = p_class;
- p_script->native = p_native;
-
- CRASH_COND(p_script->native == nullptr);
+ // Unlike `reload`, we print an error rather than silently returning,
+ // as we can assert this won't be called a second time until invalidated.
+ ERR_FAIL_COND(!p_script->reload_invalidated);
p_script->valid = true;
p_script->reload_invalidated = false;
update_script_class_info(p_script);
-#ifdef TOOLS_ENABLED
- p_script->_update_member_info_no_exports();
-#endif
+ p_script->_update_exports();
}
// Extract information about the script using the mono class.
void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) {
- GDMonoClass *base = p_script->script_class->get_parent_class();
+ bool tool = false;
- // `base` should only be set if the script is a user defined type.
- if (base != p_script->native) {
- p_script->base = base;
- }
+ // TODO: Use GDNative godot_dictionary
+ Array methods_array;
+ methods_array.~Array();
+ Dictionary rpc_functions_dict;
+ rpc_functions_dict.~Dictionary();
+ Dictionary signals_dict;
+ signals_dict.~Dictionary();
- p_script->tool = p_script->script_class->has_attribute(CACHED_CLASS(ToolAttribute));
+ Ref<CSharpScript> base_script;
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_UpdateScriptClassInfo(
+ p_script.ptr(), &tool, &methods_array, &rpc_functions_dict, &signals_dict, &base_script);
- if (!p_script->tool) {
- GDMonoClass *nesting_class = p_script->script_class->get_nesting_class();
- p_script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
- }
+ p_script->tool = tool;
-#ifdef TOOLS_ENABLED
- if (!p_script->tool) {
- p_script->tool = p_script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
- }
-#endif
+ p_script->rpc_config.clear();
+ p_script->rpc_config = rpc_functions_dict;
-#ifdef DEBUG_ENABLED
- // For debug builds, we must fetch from all native base methods as well.
- // Native base methods must be fetched before the current class.
- // Not needed if the script class itself is a native class.
+ // Methods
- if (p_script->script_class != p_script->native) {
- GDMonoClass *native_top = p_script->native;
- while (native_top) {
- native_top->fetch_methods_with_godot_api_checks(p_script->native);
+ p_script->methods.clear();
- if (native_top == CACHED_CLASS(GodotObject)) {
- break;
- }
+ p_script->methods.resize(methods_array.size());
+ int push_index = 0;
+
+ for (int i = 0; i < methods_array.size(); i++) {
+ Dictionary method_info_dict = methods_array[i];
- native_top = native_top->get_parent_class();
+ StringName name = method_info_dict["name"];
+
+ MethodInfo mi;
+ mi.name = name;
+
+ Array params = method_info_dict["params"];
+
+ for (int j = 0; j < params.size(); j++) {
+ Dictionary param = params[j];
+
+ Variant::Type param_type = (Variant::Type)(int)param["type"];
+ PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
+ arg_info.usage = (uint32_t)param["usage"];
+ mi.arguments.push_back(arg_info);
}
+
+ p_script->methods.set(push_index++, CSharpMethodInfo{ name, mi });
}
-#endif
- p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native);
+ // Event signals
- p_script->rpc_config.clear();
+ // Performance is not critical here as this will be replaced with source generators.
- GDMonoClass *top = p_script->script_class;
- while (top && top != p_script->native) {
- // Fetch methods from base classes as well
- top->fetch_methods_with_godot_api_checks(p_script->native);
+ p_script->event_signals.clear();
- // Update RPC info
- {
- Vector<GDMonoMethod *> methods = top->get_all_methods();
- for (int i = 0; i < methods.size(); i++) {
- if (!methods[i]->is_static()) {
- const Variant rpc_config = p_script->_member_get_rpc_config(methods[i]);
- if (rpc_config.get_type() != Variant::NIL) {
- p_script->rpc_config[methods[i]->get_name()] = rpc_config;
- }
- }
- }
+ // Sigh... can't we just have capacity?
+ p_script->event_signals.resize(signals_dict.size());
+ push_index = 0;
+
+ for (const Variant *s = signals_dict.next(nullptr); s != nullptr; s = signals_dict.next(s)) {
+ StringName name = *s;
+
+ MethodInfo mi;
+ mi.name = name;
+
+ Array params = signals_dict[*s];
+
+ for (int i = 0; i < params.size(); i++) {
+ Dictionary param = params[i];
+
+ Variant::Type param_type = (Variant::Type)(int)param["type"];
+ PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
+ arg_info.usage = (uint32_t)param["usage"];
+ mi.arguments.push_back(arg_info);
}
- top = top->get_parent_class();
+ p_script->event_signals.set(push_index++, EventSignalInfo{ name, mi });
}
- p_script->load_script_signals(p_script->script_class, p_script->native);
+ p_script->base_script = base_script;
}
bool CSharpScript::can_instantiate() const {
@@ -3113,43 +2247,22 @@ bool CSharpScript::can_instantiate() const {
// FIXME Need to think this through better.
// For tool scripts, this will never fire if the class is not found. That's because we
// don't know if it's a tool script if we can't find the class to access the attributes.
- if (extra_cond && !script_class) {
- if (GDMono::get_singleton()->get_project_assembly() == nullptr) {
- // The project assembly is not loaded
- ERR_FAIL_V_MSG(false, "Cannot instance script because the project assembly is not loaded. Script: '" + get_path() + "'.");
- } else {
- // The project assembly is loaded, but the class could not found
- ERR_FAIL_V_MSG(false, "Cannot instance script because the class '" + name + "' could not be found. Script: '" + get_path() + "'.");
- }
+ if (extra_cond && !valid) {
+ ERR_FAIL_V_MSG(false, "Cannot instance script because the associated class could not be found. Script: '" + get_path() + "'.");
}
return valid && extra_cond;
}
StringName CSharpScript::get_instance_base_type() const {
- if (native) {
- return native->get_name();
- } else {
- return StringName();
- }
+ StringName native_name;
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
+ return native_name;
}
CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) {
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
/* STEP 1, CREATE */
- // Search the constructor first, to fail with an error if it's not found before allocating anything else.
- GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
- if (ctor == nullptr) {
- ERR_FAIL_COND_V_MSG(p_argcount == 0, nullptr,
- "Cannot create script instance. The class '" + script_class->get_full_name() +
- "' does not define a parameterless constructor." +
- (get_path().is_empty() ? String() : " Path: '" + get_path() + "'."));
-
- ERR_FAIL_V_MSG(nullptr, "Constructor not found.");
- }
-
Ref<RefCounted> ref;
if (p_is_ref_counted) {
// Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
@@ -3163,15 +2276,8 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
if (script_binding.inited && !script_binding.gchandle.is_released()) {
- MonoObject *mono_object = script_binding.gchandle.get_target();
- if (mono_object) {
- MonoException *exc = nullptr;
- GDMonoUtils::dispose(mono_object, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- }
- }
+ GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
+ script_binding.gchandle.get_intptr(), /* okIfNull */ true);
script_binding.gchandle.release(); // Just in case
script_binding.inited = false;
@@ -3185,38 +2291,19 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
/* STEP 2, INITIALIZE AND CONSTRUCT */
- MonoObject *mono_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
+ bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
+ this, p_owner, p_args, p_argcount);
- if (!mono_object) {
+ if (!ok) {
// Important to clear this before destroying the script instance here
instance->script = Ref<CSharpScript>();
instance->owner = nullptr;
-
- bool die = instance->_unreference_owner_unsafe();
- // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
- CRASH_COND(die);
-
p_owner->set_script_instance(nullptr);
- r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
- ERR_FAIL_V_MSG(nullptr, "Failed to allocate memory for the object.");
- }
-
- // Tie managed to unmanaged
- instance->gchandle = MonoGCHandleData::new_strong_handle(mono_object);
- if (instance->base_ref_counted) {
- instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
- }
-
- {
- MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
- instances.insert(instance->owner);
+ return nullptr;
}
- CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
-
- // Construct
- ctor->invoke(mono_object, p_args);
+ CRASH_COND(instance->gchandle.is_released());
/* STEP 3, PARTY */
@@ -3232,11 +2319,12 @@ Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::Cal
r_error.error = Callable::CallError::CALL_OK;
- ERR_FAIL_NULL_V(native, Variant());
+ StringName native_name;
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
- GD_MONO_SCOPE_THREAD_ATTACH;
+ ERR_FAIL_COND_V(native_name == StringName(), Variant());
- Object *owner = ClassDB::instantiate(NATIVE_GDMONOCLASS_NAME(native));
+ Object *owner = ClassDB::instantiate(native_name);
Ref<RefCounted> ref;
RefCounted *r = Object::cast_to<RefCounted>(owner);
@@ -3264,18 +2352,18 @@ ScriptInstance *CSharpScript::instance_create(Object *p_this) {
CRASH_COND(!valid);
#endif
- GD_MONO_SCOPE_THREAD_ATTACH;
+ StringName native_name;
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
- if (native) {
- StringName native_name = NATIVE_GDMONOCLASS_NAME(native);
- if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
- if (EngineDebugger::is_active()) {
- CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0,
- "Script inherits from native type '" + String(native_name) +
- "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'");
- }
- ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'.");
+ ERR_FAIL_COND_V(native_name == StringName(), nullptr);
+
+ if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
+ if (EngineDebugger::is_active()) {
+ CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0,
+ "Script inherits from native type '" + String(native_name) +
+ "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'");
}
+ ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'.");
}
Callable::CallError unchecked_error;
@@ -3317,54 +2405,43 @@ void CSharpScript::set_source_code(const String &p_code) {
}
void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
- if (!script_class) {
+ if (!valid) {
return;
}
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- // TODO: We're filtering out constructors but there may be other methods unsuitable for explicit calls.
- GDMonoClass *top = script_class;
-
- while (top && top != native) {
- const Vector<GDMonoMethod *> &methods = top->get_all_methods();
- for (int i = 0; i < methods.size(); ++i) {
- MethodInfo minfo = methods[i]->get_method_info();
- if (minfo.name != CACHED_STRING_NAME(dotctor)) {
- p_list->push_back(methods[i]->get_method_info());
- }
+ const CSharpScript *top = this;
+ while (top != nullptr) {
+ for (const CSharpMethodInfo &E : top->methods) {
+ p_list->push_back(E.method_info);
}
- top = top->get_parent_class();
+ top = top->base_script.ptr();
}
}
bool CSharpScript::has_method(const StringName &p_method) const {
- if (!script_class) {
+ if (!valid) {
return false;
}
- GD_MONO_SCOPE_THREAD_ATTACH;
+ for (const CSharpMethodInfo &E : methods) {
+ if (E.name == p_method) {
+ return true;
+ }
+ }
- return script_class->has_fetched_method_unknown_params(p_method);
+ return false;
}
MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
- if (!script_class) {
+ if (!valid) {
return MethodInfo();
}
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- GDMonoClass *top = script_class;
-
- while (top && top != native) {
- GDMonoMethod *params = top->get_fetched_method_unknown_params(p_method);
- if (params) {
- return params->get_method_info();
+ for (const CSharpMethodInfo &E : methods) {
+ if (E.name == p_method) {
+ return E.method_info;
}
-
- top = top->get_parent_class();
}
return MethodInfo();
@@ -3379,30 +2456,15 @@ Error CSharpScript::reload(bool p_keep_state) {
// That's done separately via domain reloading.
reload_invalidated = false;
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- const DotNetScriptLookupInfo *lookup_info =
- CSharpLanguage::get_singleton()->lookup_dotnet_script(get_path());
-
- if (lookup_info) {
- GDMonoClass *klass = lookup_info->script_class;
- if (klass) {
- ERR_FAIL_COND_V(!CACHED_CLASS(GodotObject)->is_assignable_from(klass), FAILED);
- script_class = klass;
- }
- }
+ String script_path = get_path();
- valid = script_class != nullptr;
+ valid = GDMonoCache::managed_callbacks.ScriptManagerBridge_AddScriptBridge(this, &script_path);
- if (script_class) {
+ if (valid) {
#ifdef DEBUG_ENABLED
- print_verbose("Found class " + script_class->get_full_name() + " for script " + get_path());
+ print_verbose("Found class for script " + get_path());
#endif
- native = GDMonoUtils::get_class_native_base(script_class);
-
- CRASH_COND(native == nullptr);
-
update_script_class_info(this);
_update_exports();
@@ -3424,8 +2486,8 @@ bool CSharpScript::get_property_default_value(const StringName &p_property, Vari
return true;
}
- if (base_cache.is_valid()) {
- return base_cache->get_property_default_value(p_property, r_value);
+ if (base_script.is_valid()) {
+ return base_script->get_property_default_value(p_property, r_value);
}
#endif
@@ -3439,48 +2501,39 @@ void CSharpScript::update_exports() {
}
bool CSharpScript::has_script_signal(const StringName &p_signal) const {
- return event_signals.has(p_signal) || _signals.has(p_signal);
-}
-
-void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
- for (const KeyValue<StringName, Vector<SignalParameter>> &E : _signals) {
- MethodInfo mi;
- mi.name = E.key;
-
- const Vector<SignalParameter> &params = E.value;
- for (int i = 0; i < params.size(); i++) {
- const SignalParameter &param = params[i];
+ if (!valid) {
+ return false;
+ }
- PropertyInfo arg_info = PropertyInfo(param.type, param.name);
- if (param.type == Variant::NIL && param.nil_is_variant) {
- arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- }
+ if (!GDMonoCache::godot_api_cache_updated) {
+ return false;
+ }
- mi.arguments.push_back(arg_info);
+ for (const EventSignalInfo &signal : event_signals) {
+ if (signal.name == p_signal) {
+ return true;
}
-
- r_signals->push_back(mi);
}
- for (const KeyValue<StringName, EventSignal> &E : event_signals) {
- MethodInfo mi;
- mi.name = E.key;
-
- const EventSignal &event_signal = E.value;
- const Vector<SignalParameter> &params = event_signal.parameters;
- for (int i = 0; i < params.size(); i++) {
- const SignalParameter &param = params[i];
+ return false;
+}
- PropertyInfo arg_info = PropertyInfo(param.type, param.name);
- if (param.type == Variant::NIL && param.nil_is_variant) {
- arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- }
+void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
+ if (!valid) {
+ return;
+ }
- mi.arguments.push_back(arg_info);
- }
+ for (const EventSignalInfo &signal : get_script_event_signals()) {
+ r_signals->push_back(signal.method_info);
+ }
+}
- r_signals->push_back(mi);
+Vector<CSharpScript::EventSignalInfo> CSharpScript::get_script_event_signals() const {
+ if (!valid) {
+ return Vector<EventSignalInfo>();
}
+
+ return event_signals;
}
bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
@@ -3489,38 +2542,47 @@ bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
return false;
}
- if (script_class == nullptr || cs->script_class == nullptr) {
+ if (!valid || !cs->valid) {
return false;
}
- if (script_class == cs->script_class) {
- return true;
+ if (!GDMonoCache::godot_api_cache_updated) {
+ return false;
}
- return cs->script_class->is_assignable_from(script_class);
+ return GDMonoCache::managed_callbacks.ScriptManagerBridge_ScriptIsOrInherits(this, cs.ptr());
}
Ref<Script> CSharpScript::get_base_script() const {
- // TODO search in metadata file once we have it, not important any way?
- return Ref<Script>();
+ return base_script;
}
void CSharpScript::get_script_property_list(List<PropertyInfo> *r_list) const {
- List<PropertyInfo> props;
-
#ifdef TOOLS_ENABLED
- for (const PropertyInfo &E : exported_members_cache) {
- props.push_back(E);
+ const CSharpScript *top = this;
+ while (top != nullptr) {
+ for (const PropertyInfo &E : top->exported_members_cache) {
+ r_list->push_back(E);
+ }
+
+ top = top->base_script.ptr();
}
#else
- for (const KeyValue<StringName, PropertyInfo> &E : member_info) {
- props.push_front(E.value);
- }
-#endif // TOOLS_ENABLED
+ const CSharpScript *top = this;
+ while (top != nullptr) {
+ List<PropertyInfo> props;
- for (const PropertyInfo &prop : props) {
- r_list->push_back(prop);
+ for (const KeyValue<StringName, PropertyInfo> &E : top->member_info) {
+ props.push_front(E.value);
+ }
+
+ for (const PropertyInfo &prop : props) {
+ r_list->push_back(prop);
+ }
+
+ top = top->base_script.ptr();
}
+#endif
}
int CSharpScript::get_member_line(const StringName &p_member) const {
@@ -3528,22 +2590,6 @@ int CSharpScript::get_member_line(const StringName &p_member) const {
return -1;
}
-Variant CSharpScript::_member_get_rpc_config(IMonoClassMember *p_member) const {
- Variant out;
-
- MonoObject *rpc_attribute = p_member->get_attribute(CACHED_CLASS(RPCAttribute));
- if (rpc_attribute != nullptr) {
- Dictionary rpc_config;
- rpc_config["rpc_mode"] = CACHED_PROPERTY(RPCAttribute, Mode)->get_int_value(rpc_attribute);
- rpc_config["call_local"] = CACHED_PROPERTY(RPCAttribute, CallLocal)->get_bool_value(rpc_attribute);
- rpc_config["transfer_mode"] = CACHED_PROPERTY(RPCAttribute, TransferMode)->get_int_value(rpc_attribute);
- rpc_config["channel"] = CACHED_PROPERTY(RPCAttribute, TransferChannel)->get_int_value(rpc_attribute);
- out = rpc_config;
- }
-
- return out;
-}
-
const Variant CSharpScript::get_rpc_config() const {
return rpc_config;
}
@@ -3564,29 +2610,15 @@ Error CSharpScript::load_source_code(const String &p_path) {
return OK;
}
-void CSharpScript::_update_name() {
- String path = get_path();
-
- if (!path.is_empty()) {
- name = get_path().get_file().get_basename();
- }
-}
-
void CSharpScript::_clear() {
tool = false;
valid = false;
reload_invalidated = true;
-
- base = nullptr;
- native = nullptr;
- script_class = nullptr;
}
CSharpScript::CSharpScript() {
_clear();
- _update_name();
-
#ifdef DEBUG_ENABLED
{
MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
@@ -3600,6 +2632,10 @@ CSharpScript::~CSharpScript() {
MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
#endif
+
+ if (GDMonoCache::godot_api_cache_updated) {
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_RemoveScriptBridge(this);
+ }
}
void CSharpScript::get_members(HashSet<StringName> *p_members) {
@@ -3621,9 +2657,13 @@ Ref<Resource> ResourceFormatLoaderCSharpScript::load(const String &p_path, const
// TODO ignore anything inside bin/ and obj/ in tools builds?
- CSharpScript *script = memnew(CSharpScript);
+ Ref<CSharpScript> script;
- Ref<CSharpScript> scriptres(script);
+ if (GDMonoCache::godot_api_cache_updated) {
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_GetOrCreateScriptBridgeForPath(&p_path, &script);
+ } else {
+ script = Ref<CSharpScript>(memnew(CSharpScript));
+ }
#if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
Error err = script->load_source_code(p_path);
@@ -3638,7 +2678,7 @@ Ref<Resource> ResourceFormatLoaderCSharpScript::load(const String &p_path, const
*r_error = OK;
}
- return scriptres;
+ return script;
}
void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
@@ -3701,14 +2741,7 @@ bool ResourceFormatSaverCSharpScript::recognize(const Ref<Resource> &p_resource)
}
CSharpLanguage::StringNameCache::StringNameCache() {
- _signal_callback = StaticCString::create("_signal_callback");
- _set = StaticCString::create("_set");
- _get = StaticCString::create("_get");
- _get_property_list = StaticCString::create("_get_property_list");
- _notification = StaticCString::create("_notification");
+ _property_can_revert = StaticCString::create("_property_can_revert");
+ _property_get_revert = StaticCString::create("_property_get_revert");
_script_source = StaticCString::create("script/source");
- on_before_serialize = StaticCString::create("OnBeforeSerialize");
- on_after_deserialize = StaticCString::create("OnAfterDeserialize");
- dotctor = StaticCString::create(".ctor");
- delegate_invoke_method_name = StaticCString::create("Invoke");
}
diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h
index 48129e69cb..3509a5c87d 100644
--- a/modules/mono/csharp_script.h
+++ b/modules/mono/csharp_script.h
@@ -39,8 +39,6 @@
#include "mono_gc_handle.h"
#include "mono_gd/gd_mono.h"
-#include "mono_gd/gd_mono_header.h"
-#include "mono_gd/gd_mono_internals.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_plugin.h"
@@ -67,48 +65,17 @@ TScriptInstance *cast_script_instance(ScriptInstance *p_inst) {
#define CAST_CSHARP_INSTANCE(m_inst) (cast_script_instance<CSharpInstance, CSharpLanguage>(m_inst))
-struct DotNetScriptLookupInfo {
- String class_namespace;
- String class_name;
- GDMonoClass *script_class = nullptr;
-
- DotNetScriptLookupInfo() {} // Required by HashMap...
-
- DotNetScriptLookupInfo(const String &p_class_namespace, const String &p_class_name, GDMonoClass *p_script_class) :
- class_namespace(p_class_namespace), class_name(p_class_name), script_class(p_script_class) {
- }
-};
-
class CSharpScript : public Script {
GDCLASS(CSharpScript, Script);
-public:
- struct SignalParameter {
- String name;
- Variant::Type type;
- bool nil_is_variant = false;
- };
-
- struct EventSignal {
- GDMonoField *field = nullptr;
- GDMonoMethod *invoke_method = nullptr;
- Vector<SignalParameter> parameters;
- };
-
-private:
friend class CSharpInstance;
friend class CSharpLanguage;
- friend struct CSharpScriptDepSort;
bool tool = false;
bool valid = false;
bool reload_invalidated = false;
- GDMonoClass *base = nullptr;
- GDMonoClass *native = nullptr;
- GDMonoClass *script_class = nullptr;
-
- Ref<CSharpScript> base_cache; // TODO what's this for?
+ Ref<CSharpScript> base_script;
HashSet<Object *> instances;
@@ -118,26 +85,32 @@ private:
// Replace with buffer containing the serialized state of managed scripts.
// Keep variant state backup to use only with script instance placeholders.
List<Pair<StringName, Variant>> properties;
- List<Pair<StringName, Array>> event_signals;
+ Dictionary event_signals;
};
HashSet<ObjectID> pending_reload_instances;
RBMap<ObjectID, StateBackup> pending_reload_state;
- StringName tied_class_name_for_reload;
- StringName tied_class_namespace_for_reload;
#endif
String source;
- StringName name;
SelfList<CSharpScript> script_list = this;
- HashMap<StringName, Vector<SignalParameter>> _signals;
- HashMap<StringName, EventSignal> event_signals;
- bool signals_invalidated = true;
-
Dictionary rpc_config;
+ struct EventSignalInfo {
+ StringName name; // MethodInfo stores a string...
+ MethodInfo method_info;
+ };
+
+ struct CSharpMethodInfo {
+ StringName name; // MethodInfo stores a string...
+ MethodInfo method_info;
+ };
+
+ Vector<EventSignalInfo> event_signals;
+ Vector<CSharpMethodInfo> methods;
+
#ifdef TOOLS_ENABLED
List<PropertyInfo> exported_members_cache; // members_cache
HashMap<StringName, Variant> exported_members_defval_cache; // member_default_values_cache
@@ -146,7 +119,6 @@ private:
bool placeholder_fallback_enabled = false;
bool exports_invalidated = true;
void _update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames);
- void _update_member_info_no_exports();
void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
#endif
@@ -158,39 +130,24 @@ private:
void _clear();
- void _update_name();
-
- void load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class);
- bool _get_signal(GDMonoClass *p_class, GDMonoMethod *p_delegate_invoke, Vector<SignalParameter> &params);
-
bool _update_exports(PlaceHolderScriptInstance *p_instance_to_update = nullptr);
- bool _get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported);
-#ifdef TOOLS_ENABLED
- static int _try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string);
-#endif
-
CSharpInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error);
Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
// Do not use unless you know what you are doing
- friend void GDMonoInternals::tie_managed_to_unmanaged(MonoObject *, Object *);
- static Ref<CSharpScript> create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native);
static void update_script_class_info(Ref<CSharpScript> p_script);
- static void initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native);
-
- Variant _member_get_rpc_config(IMonoClassMember *p_member) const;
protected:
static void _bind_methods();
- 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);
void _get_property_list(List<PropertyInfo> *p_properties) const;
public:
+ static void reload_registered_script(Ref<CSharpScript> p_script);
+
bool can_instantiate() const override;
StringName get_instance_base_type() const override;
ScriptInstance *instance_create(Object *p_this) override;
@@ -214,14 +171,20 @@ public:
bool has_script_signal(const StringName &p_signal) const override;
void get_script_signal_list(List<MethodInfo> *r_signals) const override;
+ Vector<EventSignalInfo> get_script_event_signals() const;
+
bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
void get_script_property_list(List<PropertyInfo> *r_list) const override;
void update_exports() override;
void get_members(HashSet<StringName> *p_members) override;
- bool is_tool() const override { return tool; }
- bool is_valid() const override { return valid; }
+ bool is_tool() const override {
+ return tool;
+ }
+ bool is_valid() const override {
+ return valid;
+ }
bool inherits_script(const Ref<Script> &p_script) const override;
@@ -237,7 +200,9 @@ public:
const Variant get_rpc_config() const override;
#ifdef TOOLS_ENABLED
- bool is_placeholder_fallback_enabled() const override { return placeholder_fallback_enabled; }
+ bool is_placeholder_fallback_enabled() const override {
+ return placeholder_fallback_enabled;
+ }
#endif
Error load_source_code(const String &p_path);
@@ -270,22 +235,18 @@ class CSharpInstance : public ScriptInstance {
bool _unreference_owner_unsafe();
/*
- * If nullptr is returned, the caller must destroy the script instance by removing it from its owner.
+ * If false is returned, the caller must destroy the script instance by removing it from its owner.
*/
- MonoObject *_internal_new_managed();
+ bool _internal_new_managed();
// Do not use unless you know what you are doing
- friend void GDMonoInternals::tie_managed_to_unmanaged(MonoObject *, Object *);
static CSharpInstance *create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle);
- void get_properties_state_for_reloading(List<Pair<StringName, Variant>> &r_state);
- void get_event_signals_state_for_reloading(List<Pair<StringName, Array>> &r_state);
-
public:
- MonoObject *get_mono_object() const;
-
_FORCE_INLINE_ bool is_destructing_script_instance() { return destructing_script_instance; }
+ _FORCE_INLINE_ GCHandleIntPtr get_gchandle_intptr() { return gchandle.get_intptr(); }
+
Object *get_owner() override;
bool set(const StringName &p_name, const Variant &p_value) override;
@@ -293,17 +254,20 @@ public:
void get_property_list(List<PropertyInfo> *p_properties) const override;
Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override;
+ bool property_can_revert(const StringName &p_name) const override;
+ bool property_get_revert(const StringName &p_name, Variant &r_ret) const override;
+
void get_method_list(List<MethodInfo> *p_list) const override;
bool has_method(const StringName &p_method) const 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);
+ void mono_object_disposed(GCHandleIntPtr p_gchandle_to_free);
/*
* If 'r_delete_owner' is set to true, the caller must memdelete the script instance's owner. Otherwise, if
* 'r_remove_script_instance' is set to true, the caller must destroy the script instance by removing it from its owner.
*/
- void mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance);
+ void mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance);
void connect_event_signals();
void disconnect_event_signals();
@@ -329,7 +293,6 @@ public:
struct CSharpScriptBinding {
bool inited = false;
StringName type_name;
- GDMonoClass *wrapper_class = nullptr;
MonoGCHandleData gchandle;
Object *owner = nullptr;
@@ -367,33 +330,22 @@ class CSharpLanguage : public ScriptLanguage {
ManagedCallableMiddleman *managed_callable_middleman = memnew(ManagedCallableMiddleman);
struct StringNameCache {
- StringName _signal_callback;
- StringName _set;
- StringName _get;
- StringName _get_property_list;
- StringName _notification;
+ StringName _property_can_revert;
+ StringName _property_get_revert;
StringName _script_source;
- StringName dotctor; // .ctor
- StringName on_before_serialize; // OnBeforeSerialize
- StringName on_after_deserialize; // OnAfterDeserialize
- StringName delegate_invoke_method_name;
StringNameCache();
};
int lang_idx = -1;
- HashMap<String, DotNetScriptLookupInfo> dotnet_script_lookup_map;
-
- void lookup_script_for_class(GDMonoClass *p_class);
-
// For debug_break and debug_break_parse
int _debug_parse_err_line = -1;
String _debug_parse_err_file;
String _debug_error;
friend class GDMono;
- void _on_scripts_domain_unloaded();
+ void _on_scripts_domain_about_to_unload();
#ifdef TOOLS_ENABLED
EditorPlugin *godotsharp_editor = nullptr;
@@ -415,21 +367,35 @@ public:
StringNameCache string_names;
- const Mutex &get_language_bind_mutex() { return language_bind_mutex; }
+ const Mutex &get_language_bind_mutex() {
+ return language_bind_mutex;
+ }
+ const Mutex &get_script_instances_mutex() {
+ return script_instances_mutex;
+ }
- _FORCE_INLINE_ int get_language_index() { return lang_idx; }
+ _FORCE_INLINE_ int get_language_index() {
+ return lang_idx;
+ }
void set_language_index(int p_idx);
- _FORCE_INLINE_ const StringNameCache &get_string_names() { return string_names; }
+ _FORCE_INLINE_ const StringNameCache &get_string_names() {
+ return string_names;
+ }
- _FORCE_INLINE_ static CSharpLanguage *get_singleton() { return singleton; }
+ _FORCE_INLINE_ static CSharpLanguage *get_singleton() {
+ return singleton;
+ }
#ifdef TOOLS_ENABLED
- _FORCE_INLINE_ EditorPlugin *get_godotsharp_editor() const { return godotsharp_editor; }
+ _FORCE_INLINE_ EditorPlugin *get_godotsharp_editor() const {
+ return godotsharp_editor;
+ }
#endif
static void release_script_gchandle(MonoGCHandleData &p_gchandle);
- static void release_script_gchandle(MonoObject *p_expected_obj, MonoGCHandleData &p_gchandle);
+ static void release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle);
+ static void release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding);
bool debug_break(const String &p_error, bool p_allow_continue = true);
bool debug_break_parse(const String &p_file, int p_line, const String &p_error);
@@ -439,12 +405,8 @@ public:
void reload_assemblies(bool p_soft_reload);
#endif
- _FORCE_INLINE_ ManagedCallableMiddleman *get_managed_callable_middleman() const { return managed_callable_middleman; }
-
- void lookup_scripts_in_assembly(GDMonoAssembly *p_assembly);
-
- const DotNetScriptLookupInfo *lookup_dotnet_script(const String &p_script_path) const {
- return dotnet_script_lookup_map.getptr(p_script_path);
+ _FORCE_INLINE_ ManagedCallableMiddleman *get_managed_callable_middleman() const {
+ return managed_callable_middleman;
}
String get_name() const override;
@@ -474,7 +436,9 @@ public:
Script *create_script() const override;
bool has_named_classes() const override;
bool supports_builtin_mode() const override;
- /* TODO? */ int find_function(const String &p_function, const String &p_code) const override { return -1; }
+ /* TODO? */ int find_function(const String &p_function, const String &p_code) const override {
+ return -1;
+ }
String make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const override;
virtual String _get_indentation() const;
/* TODO? */ void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const override {}
@@ -489,14 +453,20 @@ public:
/* TODO */ 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) override {}
/* TODO */ 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) override {}
/* TODO */ void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
- /* TODO */ String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) override { return ""; }
+ /* TODO */ String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) override {
+ return "";
+ }
Vector<StackInfo> debug_get_current_stack_info() override;
/* PROFILING FUNCTIONS */
/* TODO */ void profiling_start() override {}
/* TODO */ void profiling_stop() override {}
- /* TODO */ int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) override { return 0; }
- /* TODO */ int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) override { return 0; }
+ /* TODO */ int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) override {
+ return 0;
+ }
+ /* TODO */ int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) override {
+ return 0;
+ }
void frame() override;
@@ -515,16 +485,12 @@ public:
bool overrides_external_editor() override;
#endif
- /* THREAD ATTACHING */
- void thread_enter() override;
- void thread_exit() override;
-
RBMap<Object *, CSharpScriptBinding>::Element *insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding);
bool setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object);
-#ifdef DEBUG_ENABLED
- Vector<StackInfo> stack_trace_get_info(MonoObject *p_stack_trace);
-#endif
+ static void tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted);
+ static void tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted);
+ static void tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged);
void post_unsafe_reference(Object *p_obj);
void pre_unsafe_unreference(Object *p_obj);
diff --git a/modules/mono/doc_classes/GodotSharp.xml b/modules/mono/doc_classes/GodotSharp.xml
index b981542801..faf3512da7 100644
--- a/modules/mono/doc_classes/GodotSharp.xml
+++ b/modules/mono/doc_classes/GodotSharp.xml
@@ -10,55 +10,10 @@
<tutorials>
</tutorials>
<methods>
- <method name="attach_thread">
- <return type="void" />
- <description>
- Attaches the current thread to the Mono runtime.
- </description>
- </method>
- <method name="detach_thread">
- <return type="void" />
- <description>
- Detaches the current thread from the Mono runtime.
- </description>
- </method>
- <method name="get_domain_id">
- <return type="int" />
- <description>
- Returns the current MonoDomain ID.
- [b]Note:[/b] The Mono runtime must be initialized for this method to work (use [method is_runtime_initialized] to check). If the Mono runtime isn't initialized at the time this method is called, the engine will crash.
- </description>
- </method>
- <method name="get_scripts_domain_id">
- <return type="int" />
- <description>
- Returns the scripts MonoDomain's ID. This will be the same MonoDomain ID as [method get_domain_id], unless the scripts domain isn't loaded.
- [b]Note:[/b] The Mono runtime must be initialized for this method to work (use [method is_runtime_initialized] to check). If the Mono runtime isn't initialized at the time this method is called, the engine will crash.
- </description>
- </method>
- <method name="is_domain_finalizing_for_unload">
- <return type="bool" />
- <param index="0" name="domain_id" type="int" />
- <description>
- Returns [code]true[/code] if the domain is being finalized, [code]false[/code] otherwise.
- </description>
- </method>
<method name="is_runtime_initialized">
<return type="bool" />
<description>
- Returns [code]true[/code] if the Mono runtime is initialized, [code]false[/code] otherwise.
- </description>
- </method>
- <method name="is_runtime_shutting_down">
- <return type="bool" />
- <description>
- Returns [code]true[/code] if the Mono runtime is shutting down, [code]false[/code] otherwise.
- </description>
- </method>
- <method name="is_scripts_domain_loaded">
- <return type="bool" />
- <description>
- Returns [code]true[/code] if the scripts domain is loaded, [code]false[/code] otherwise.
+ Returns [code]true[/code] if the .NET runtime is initialized, [code]false[/code] otherwise.
</description>
</method>
</methods>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln
index d1868f52ef..03a7dc453c 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln
@@ -1,4 +1,4 @@
-
+
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Godot.NET.Sdk", "Godot.NET.Sdk\Godot.NET.Sdk.csproj", "{31B00BFA-DEA1-42FA-A472-9E54A92A8A5F}"
EndProject
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj
index 4e9e7184da..013b210ff4 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj
@@ -26,16 +26,8 @@
<None Include="Sdk\Sdk.props" Pack="true" PackagePath="Sdk" />
<None Include="Sdk\Sdk.targets" Pack="true" PackagePath="Sdk" />
<!-- SdkPackageVersions.props -->
- <None Include="..\..\..\SdkPackageVersions.props" Pack="true" PackagePath="Sdk">
+ <None Include="$(GodotSdkPackageVersionsFilePath)" Pack="true" PackagePath="Sdk">
<Link>Sdk\SdkPackageVersions.props</Link>
</None>
</ItemGroup>
-
- <Target Name="CopyNupkgToSConsOutputDir" AfterTargets="Pack">
- <PropertyGroup>
- <GodotSourceRootPath>$(SolutionDir)\..\..\..\..\</GodotSourceRootPath>
- <GodotOutputDataDir>$(GodotSourceRootPath)\bin\GodotSharp\</GodotOutputDataDir>
- </PropertyGroup>
- <Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" />
- </Target>
</Project>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props
index 5a499742e9..ad41ab04d5 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props
@@ -77,7 +77,6 @@
<GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'windows' ">GODOT_WINDOWS;GODOT_PC</GodotPlatformConstants>
<GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'linuxbsd' ">GODOT_LINUXBSD;GODOT_PC</GodotPlatformConstants>
<GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'macos' ">GODOT_OSX;GODOT_MACOS;GODOT_PC</GodotPlatformConstants>
- <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'server' ">GODOT_SERVER;GODOT_PC</GodotPlatformConstants>
<GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'uwp' ">GODOT_UWP;GODOT_PC</GodotPlatformConstants>
<GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'haiku' ">GODOT_HAIKU;GODOT_PC</GodotPlatformConstants>
<GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'android' ">GODOT_ANDROID;GODOT_MOBILE</GodotPlatformConstants>
@@ -95,21 +94,4 @@
<DefineConstants>$(GodotDefineConstants);$(DefineConstants)</DefineConstants>
</PropertyGroup>
-
- <!-- Godot API references -->
- <ItemGroup>
- <!--
- TODO:
- We should consider a nuget package for reference assemblies. This is difficult because the
- Godot scripting API is continuaslly breaking backwards compatibility even in patch releases.
- -->
- <Reference Include="GodotSharp">
- <Private>false</Private>
- <HintPath>$(GodotProjectDir).godot\mono\assemblies\$(GodotApiConfiguration)\GodotSharp.dll</HintPath>
- </Reference>
- <Reference Include="GodotSharpEditor" Condition=" '$(Configuration)' == 'Debug' ">
- <Private>false</Private>
- <HintPath>$(GodotProjectDir).godot\mono\assemblies\$(GodotApiConfiguration)\GodotSharpEditor.dll</HintPath>
- </Reference>
- </ItemGroup>
</Project>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets
index 397ede9644..aad4ea4553 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets
@@ -19,4 +19,10 @@
<ItemGroup Condition=" '$(DisableImplicitGodotGeneratorReferences)' != 'true' ">
<PackageReference Include="Godot.SourceGenerators" Version="$(PackageFloatingVersion_Godot)" />
</ItemGroup>
+
+ <!-- Godot API references -->
+ <ItemGroup Condition=" '$(DisableImplicitGodotSharpReferences)' != 'true' ">
+ <PackageReference Include="GodotSharp" Version="$(PackageVersion_GodotSharp)" />
+ <PackageReference Include="GodotSharpEditor" Version="$(PackageVersion_GodotSharp)" Condition=" '$(Configuration)' == 'Debug' " />
+ </ItemGroup>
</Project>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/EventSignals.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/EventSignals.cs
new file mode 100644
index 0000000000..764ba8f121
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/EventSignals.cs
@@ -0,0 +1,7 @@
+namespace Godot.SourceGenerators.Sample;
+
+public partial class EventSignals : Godot.Object
+{
+ [Signal]
+ public delegate void MySignalEventHandler(string str, int num);
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs
new file mode 100644
index 0000000000..ac9f59aa99
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs
@@ -0,0 +1,109 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+
+#pragma warning disable CS0169
+#pragma warning disable CS0414
+
+namespace Godot.SourceGenerators.Sample
+{
+ [SuppressMessage("ReSharper", "BuiltInTypeReferenceStyle")]
+ [SuppressMessage("ReSharper", "RedundantNameQualifier")]
+ [SuppressMessage("ReSharper", "ArrangeObjectCreationWhenTypeEvident")]
+ [SuppressMessage("ReSharper", "InconsistentNaming")]
+ public partial class ExportedFields : Godot.Object
+ {
+ [Export] private Boolean field_Boolean = true;
+ [Export] private Char field_Char = 'f';
+ [Export] private SByte field_SByte = 10;
+ [Export] private Int16 field_Int16 = 10;
+ [Export] private Int32 field_Int32 = 10;
+ [Export] private Int64 field_Int64 = 10;
+ [Export] private Byte field_Byte = 10;
+ [Export] private UInt16 field_UInt16 = 10;
+ [Export] private UInt32 field_UInt32 = 10;
+ [Export] private UInt64 field_UInt64 = 10;
+ [Export] private Single field_Single = 10;
+ [Export] private Double field_Double = 10;
+ [Export] private String field_String = "foo";
+
+ // Godot structs
+ [Export] private Vector2 field_Vector2 = new(10f, 10f);
+ [Export] private Vector2i field_Vector2i = Vector2i.Up;
+ [Export] private Rect2 field_Rect2 = new(new Vector2(10f, 10f), new Vector2(10f, 10f));
+ [Export] private Rect2i field_Rect2i = new(new Vector2i(10, 10), new Vector2i(10, 10));
+ [Export] private Transform2D field_Transform2D = Transform2D.Identity;
+ [Export] private Vector3 field_Vector3 = new(10f, 10f, 10f);
+ [Export] private Vector3i field_Vector3i = Vector3i.Back;
+ [Export] private Basis field_Basis = new Basis(Quaternion.Identity);
+ [Export] private Quaternion field_Quaternion = new Quaternion(Basis.Identity);
+ [Export] private Transform3D field_Transform3D = Transform3D.Identity;
+ [Export] private Vector4 field_Vector4 = new(10f, 10f, 10f, 10f);
+ [Export] private Vector4i field_Vector4i = Vector4i.One;
+ [Export] private Projection field_Projection = Projection.Identity;
+ [Export] private AABB field_AABB = new AABB(10f, 10f, 10f, new Vector3(1f, 1f, 1f));
+ [Export] private Color field_Color = Colors.Aquamarine;
+ [Export] private Plane field_Plane = Plane.PlaneXZ;
+ [Export] private Callable field_Callable = new Callable(Engine.GetMainLoop(), "_process");
+ [Export] private SignalInfo field_SignalInfo = new SignalInfo(Engine.GetMainLoop(), "property_list_changed");
+
+ // Enums
+ [SuppressMessage("ReSharper", "UnusedMember.Local")]
+ enum MyEnum
+ {
+ A,
+ B,
+ C
+ }
+
+ [Export] private MyEnum field_Enum = MyEnum.C;
+
+ [Flags]
+ [SuppressMessage("ReSharper", "UnusedMember.Local")]
+ enum MyFlagsEnum
+ {
+ A,
+ B,
+ C
+ }
+
+ [Export] private MyFlagsEnum field_FlagsEnum = MyFlagsEnum.C;
+
+ // Arrays
+ [Export] private Byte[] field_ByteArray = { 0, 1, 2, 3, 4, 5, 6 };
+ [Export] private Int32[] field_Int32Array = { 0, 1, 2, 3, 4, 5, 6 };
+ [Export] private Int64[] field_Int64Array = { 0, 1, 2, 3, 4, 5, 6 };
+ [Export] private Single[] field_SingleArray = { 0f, 1f, 2f, 3f, 4f, 5f, 6f };
+ [Export] private Double[] field_DoubleArray = { 0d, 1d, 2d, 3d, 4d, 5d, 6d };
+ [Export] private String[] field_StringArray = { "foo", "bar" };
+ [Export(PropertyHint.Enum, "A,B,C")] private String[] field_StringArrayEnum = { "foo", "bar" };
+ [Export] private Vector2[] field_Vector2Array = { Vector2.Up, Vector2.Down, Vector2.Left, Vector2.Right };
+ [Export] private Vector3[] field_Vector3Array = { Vector3.Up, Vector3.Down, Vector3.Left, Vector3.Right };
+ [Export] private Color[] field_ColorArray = { Colors.Aqua, Colors.Aquamarine, Colors.Azure, Colors.Beige };
+ [Export] private Godot.Object[] field_GodotObjectOrDerivedArray = { null };
+ [Export] private StringName[] field_StringNameArray = { "foo", "bar" };
+ [Export] private NodePath[] field_NodePathArray = { "foo", "bar" };
+ [Export] private RID[] field_RIDArray = { default, default, default };
+
+ // Variant
+ [Export] private Variant field_Variant = "foo";
+
+ // Classes
+ [Export] private Godot.Object field_GodotObjectOrDerived;
+ [Export] private Godot.Texture field_GodotResourceTexture;
+ [Export] private StringName field_StringName = new StringName("foo");
+ [Export] private NodePath field_NodePath = new NodePath("foo");
+ [Export] private RID field_RID;
+
+ [Export] private Godot.Collections.Dictionary field_GodotDictionary =
+ new() { { "foo", 10 }, { Vector2.Up, Colors.Chocolate } };
+
+ [Export] private Godot.Collections.Array field_GodotArray =
+ new() { "foo", 10, Vector2.Up, Colors.Chocolate };
+
+ [Export] private Godot.Collections.Dictionary<string, bool> field_GodotGenericDictionary =
+ new() { { "foo", true }, { "bar", false } };
+
+ [Export] private Godot.Collections.Array<int> field_GodotGenericArray =
+ new() { 0, 1, 2, 3, 4, 5, 6 };
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs
new file mode 100644
index 0000000000..4a0e8075f0
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs
@@ -0,0 +1,109 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+
+#pragma warning disable CS0169
+#pragma warning disable CS0414
+
+namespace Godot.SourceGenerators.Sample
+{
+ [SuppressMessage("ReSharper", "BuiltInTypeReferenceStyle")]
+ [SuppressMessage("ReSharper", "RedundantNameQualifier")]
+ [SuppressMessage("ReSharper", "ArrangeObjectCreationWhenTypeEvident")]
+ [SuppressMessage("ReSharper", "InconsistentNaming")]
+ public partial class ExportedProperties : Godot.Object
+ {
+ [Export] private Boolean property_Boolean { get; set; } = true;
+ [Export] private Char property_Char { get; set; } = 'f';
+ [Export] private SByte property_SByte { get; set; } = 10;
+ [Export] private Int16 property_Int16 { get; set; } = 10;
+ [Export] private Int32 property_Int32 { get; set; } = 10;
+ [Export] private Int64 property_Int64 { get; set; } = 10;
+ [Export] private Byte property_Byte { get; set; } = 10;
+ [Export] private UInt16 property_UInt16 { get; set; } = 10;
+ [Export] private UInt32 property_UInt32 { get; set; } = 10;
+ [Export] private UInt64 property_UInt64 { get; set; } = 10;
+ [Export] private Single property_Single { get; set; } = 10;
+ [Export] private Double property_Double { get; set; } = 10;
+ [Export] private String property_String { get; set; } = "foo";
+
+ // Godot structs
+ [Export] private Vector2 property_Vector2 { get; set; } = new(10f, 10f);
+ [Export] private Vector2i property_Vector2i { get; set; } = Vector2i.Up;
+ [Export] private Rect2 property_Rect2 { get; set; } = new(new Vector2(10f, 10f), new Vector2(10f, 10f));
+ [Export] private Rect2i property_Rect2i { get; set; } = new(new Vector2i(10, 10), new Vector2i(10, 10));
+ [Export] private Transform2D property_Transform2D { get; set; } = Transform2D.Identity;
+ [Export] private Vector3 property_Vector3 { get; set; } = new(10f, 10f, 10f);
+ [Export] private Vector3i property_Vector3i { get; set; } = Vector3i.Back;
+ [Export] private Basis property_Basis { get; set; } = new Basis(Quaternion.Identity);
+ [Export] private Quaternion property_Quaternion { get; set; } = new Quaternion(Basis.Identity);
+ [Export] private Transform3D property_Transform3D { get; set; } = Transform3D.Identity;
+ [Export] private Vector4 property_Vector4 { get; set; } = new(10f, 10f, 10f, 10f);
+ [Export] private Vector4i property_Vector4i { get; set; } = Vector4i.One;
+ [Export] private Projection property_Projection { get; set; } = Projection.Identity;
+ [Export] private AABB property_AABB { get; set; } = new AABB(10f, 10f, 10f, new Vector3(1f, 1f, 1f));
+ [Export] private Color property_Color { get; set; } = Colors.Aquamarine;
+ [Export] private Plane property_Plane { get; set; } = Plane.PlaneXZ;
+ [Export] private Callable property_Callable { get; set; } = new Callable(Engine.GetMainLoop(), "_process");
+ [Export] private SignalInfo property_SignalInfo { get; set; } = new SignalInfo(Engine.GetMainLoop(), "property_list_changed");
+
+ // Enums
+ [SuppressMessage("ReSharper", "UnusedMember.Local")]
+ enum MyEnum
+ {
+ A,
+ B,
+ C
+ }
+
+ [Export] private MyEnum property_Enum { get; set; } = MyEnum.C;
+
+ [Flags]
+ [SuppressMessage("ReSharper", "UnusedMember.Local")]
+ enum MyFlagsEnum
+ {
+ A,
+ B,
+ C
+ }
+
+ [Export] private MyFlagsEnum property_FlagsEnum { get; set; } = MyFlagsEnum.C;
+
+ // Arrays
+ [Export] private Byte[] property_ByteArray { get; set; } = { 0, 1, 2, 3, 4, 5, 6 };
+ [Export] private Int32[] property_Int32Array { get; set; } = { 0, 1, 2, 3, 4, 5, 6 };
+ [Export] private Int64[] property_Int64Array { get; set; } = { 0, 1, 2, 3, 4, 5, 6 };
+ [Export] private Single[] property_SingleArray { get; set; } = { 0f, 1f, 2f, 3f, 4f, 5f, 6f };
+ [Export] private Double[] property_DoubleArray { get; set; } = { 0d, 1d, 2d, 3d, 4d, 5d, 6d };
+ [Export] private String[] property_StringArray { get; set; } = { "foo", "bar" };
+ [Export(PropertyHint.Enum, "A,B,C")] private String[] property_StringArrayEnum { get; set; } = { "foo", "bar" };
+ [Export] private Vector2[] property_Vector2Array { get; set; } = { Vector2.Up, Vector2.Down, Vector2.Left, Vector2.Right };
+ [Export] private Vector3[] property_Vector3Array { get; set; } = { Vector3.Up, Vector3.Down, Vector3.Left, Vector3.Right };
+ [Export] private Color[] property_ColorArray { get; set; } = { Colors.Aqua, Colors.Aquamarine, Colors.Azure, Colors.Beige };
+ [Export] private Godot.Object[] property_GodotObjectOrDerivedArray { get; set; } = { null };
+ [Export] private StringName[] field_StringNameArray { get; set; } = { "foo", "bar" };
+ [Export] private NodePath[] field_NodePathArray { get; set; } = { "foo", "bar" };
+ [Export] private RID[] field_RIDArray { get; set; } = { default, default, default };
+
+ // Variant
+ [Export] private Variant property_Variant { get; set; } = "foo";
+
+ // Classes
+ [Export] private Godot.Object property_GodotObjectOrDerived { get; set; }
+ [Export] private Godot.Texture property_GodotResourceTexture { get; set; }
+ [Export] private StringName property_StringName { get; set; } = new StringName("foo");
+ [Export] private NodePath property_NodePath { get; set; } = new NodePath("foo");
+ [Export] private RID property_RID { get; set; }
+
+ [Export] private Godot.Collections.Dictionary property_GodotDictionary { get; set; } =
+ new() { { "foo", 10 }, { Vector2.Up, Colors.Chocolate } };
+
+ [Export] private Godot.Collections.Array property_GodotArray { get; set; } =
+ new() { "foo", 10, Vector2.Up, Colors.Chocolate };
+
+ [Export] private Godot.Collections.Dictionary<string, bool> property_GodotGenericDictionary { get; set; } =
+ new() { { "foo", true }, { "bar", false } };
+
+ [Export] private Godot.Collections.Array<int> property_GodotGenericArray { get; set; } =
+ new() { 0, 1, 2, 3, 4, 5, 6 };
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Generic.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Generic.cs
index 2ddb8880c2..b21b035b4d 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Generic.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Generic.cs
@@ -1,16 +1,21 @@
+#pragma warning disable CS0169
+
namespace Godot.SourceGenerators.Sample
{
partial class Generic<T> : Godot.Object
{
+ private int _field;
}
// Generic again but different generic parameters
partial class Generic<T, R> : Godot.Object
{
+ private int _field;
}
// Generic again but without generic parameters
partial class Generic : Godot.Object
{
+ private int _field;
}
}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Godot.SourceGenerators.Sample.csproj b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Godot.SourceGenerators.Sample.csproj
index 24f7909861..8e78e0385d 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Godot.SourceGenerators.Sample.csproj
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Godot.SourceGenerators.Sample.csproj
@@ -1,12 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netstandard2.1</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<!-- $(GodotProjectDir) would normally be defined by the Godot.NET.Sdk -->
<GodotProjectDir>$(MSBuildProjectDirectory)</GodotProjectDir>
+ <!-- For compiling GetGodotPropertyDefaultValues. -->
+ <DefineConstants>$(DefineConstants);TOOLS</DefineConstants>
</PropertyGroup>
<PropertyGroup>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Methods.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Methods.cs
new file mode 100644
index 0000000000..618ba24abc
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/Methods.cs
@@ -0,0 +1,31 @@
+using System.Diagnostics.CodeAnalysis;
+
+namespace Godot.SourceGenerators.Sample;
+
+[SuppressMessage("ReSharper", "RedundantNameQualifier")]
+public partial class Methods : Godot.Object
+{
+ private void MethodWithOverload()
+ {
+ }
+
+ private void MethodWithOverload(int a)
+ {
+ }
+
+ private void MethodWithOverload(int a, int b)
+ {
+ }
+
+ // Should be ignored. The previous one is picked.
+ // ReSharper disable once UnusedMember.Local
+ private void MethodWithOverload(float a, float b)
+ {
+ }
+
+ // Generic methods should be ignored.
+ // ReSharper disable once UnusedMember.Local
+ private void GenericMethod<T>(T t)
+ {
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs
new file mode 100644
index 0000000000..a1667dbb8f
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs
@@ -0,0 +1,36 @@
+#pragma warning disable CS0169
+
+namespace Godot.SourceGenerators.Sample
+{
+ public partial class ScriptBoilerplate : Node
+ {
+ private NodePath _nodePath;
+ private int _velocity;
+
+ public override void _Process(float delta)
+ {
+ _ = delta;
+
+ base._Process(delta);
+ }
+
+ public int Bazz(StringName name)
+ {
+ _ = name;
+ return 1;
+ }
+
+ public void IgnoreThisMethodWithByRefParams(ref int a)
+ {
+ _ = a;
+ }
+ }
+
+ partial struct OuterClass
+ {
+ public partial class NesterClass : RefCounted
+ {
+ public override Variant _Get(StringName property) => default;
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Common.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Common.cs
index 4867c986e6..3dfa8000ba 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Common.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Common.cs
@@ -1,5 +1,7 @@
+using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Diagnostics;
namespace Godot.SourceGenerators
{
@@ -14,12 +16,11 @@ namespace Godot.SourceGenerators
"Missing partial modifier on declaration of type '" +
$"{symbol.FullQualifiedName()}' which is a subclass of '{GodotClasses.Object}'";
- string description = $"{message}. Subclasses of '{GodotClasses.Object}' must be " +
- "declared with the partial modifier or annotated with the " +
- $"attribute '{GodotClasses.DisableGodotGeneratorsAttr}'.";
+ string description = $"{message}. Subclasses of '{GodotClasses.Object}' " +
+ "must be declared with the partial modifier.";
context.ReportDiagnostic(Diagnostic.Create(
- new DiagnosticDescriptor(id: "GODOT-G0001",
+ new DiagnosticDescriptor(id: "GD0001",
title: message,
messageFormat: message,
category: "Usage",
@@ -29,5 +30,307 @@ namespace Godot.SourceGenerators
cds.GetLocation(),
cds.SyntaxTree.FilePath));
}
+
+ public static void ReportNonPartialGodotScriptOuterClass(
+ GeneratorExecutionContext context,
+ TypeDeclarationSyntax outerTypeDeclSyntax
+ )
+ {
+ var outerSymbol = context.Compilation
+ .GetSemanticModel(outerTypeDeclSyntax.SyntaxTree)
+ .GetDeclaredSymbol(outerTypeDeclSyntax);
+
+ string fullQualifiedName = outerSymbol is INamedTypeSymbol namedTypeSymbol ?
+ namedTypeSymbol.FullQualifiedName() :
+ "type not found";
+
+ string message =
+ $"Missing partial modifier on declaration of type '{fullQualifiedName}', " +
+ $"which contains one or more subclasses of '{GodotClasses.Object}'";
+
+ string description = $"{message}. Subclasses of '{GodotClasses.Object}' and their " +
+ "containing types must be declared with the partial modifier.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0002",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ outerTypeDeclSyntax.GetLocation(),
+ outerTypeDeclSyntax.SyntaxTree.FilePath));
+ }
+
+ public static void ReportExportedMemberIsStatic(
+ GeneratorExecutionContext context,
+ ISymbol exportedMemberSymbol
+ )
+ {
+ var locations = exportedMemberSymbol.Locations;
+ var location = locations.FirstOrDefault(l => l.SourceTree != null) ?? locations.FirstOrDefault();
+ bool isField = exportedMemberSymbol is IFieldSymbol;
+
+ string message = $"Attempted to export static {(isField ? "field" : "property")}: " +
+ $"'{exportedMemberSymbol.ToDisplayString()}'";
+
+ string description = $"{message}. Only instance fields and properties can be exported." +
+ " Remove the 'static' modifier or the '[Export]' attribute.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0101",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ location,
+ location?.SourceTree?.FilePath));
+ }
+
+ public static void ReportExportedMemberTypeNotSupported(
+ GeneratorExecutionContext context,
+ ISymbol exportedMemberSymbol
+ )
+ {
+ var locations = exportedMemberSymbol.Locations;
+ var location = locations.FirstOrDefault(l => l.SourceTree != null) ?? locations.FirstOrDefault();
+ bool isField = exportedMemberSymbol is IFieldSymbol;
+
+ string message = $"The type of the exported {(isField ? "field" : "property")} " +
+ $"is not supported: '{exportedMemberSymbol.ToDisplayString()}'";
+
+ string description = $"{message}. Use a supported type or remove the '[Export]' attribute.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0102",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ location,
+ location?.SourceTree?.FilePath));
+ }
+
+ public static void ReportExportedMemberIsReadOnly(
+ GeneratorExecutionContext context,
+ ISymbol exportedMemberSymbol
+ )
+ {
+ var locations = exportedMemberSymbol.Locations;
+ var location = locations.FirstOrDefault(l => l.SourceTree != null) ?? locations.FirstOrDefault();
+ bool isField = exportedMemberSymbol is IFieldSymbol;
+
+ string message = $"The exported {(isField ? "field" : "property")} " +
+ $"is read-only: '{exportedMemberSymbol.ToDisplayString()}'";
+
+ string description = isField ?
+ $"{message}. Exported fields cannot be read-only." :
+ $"{message}. Exported properties must be writable.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0103",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ location,
+ location?.SourceTree?.FilePath));
+ }
+
+ public static void ReportExportedMemberIsWriteOnly(
+ GeneratorExecutionContext context,
+ ISymbol exportedMemberSymbol
+ )
+ {
+ var locations = exportedMemberSymbol.Locations;
+ var location = locations.FirstOrDefault(l => l.SourceTree != null) ?? locations.FirstOrDefault();
+
+ string message = $"The exported property is write-only: '{exportedMemberSymbol.ToDisplayString()}'";
+
+ string description = $"{message}. Exported properties must be readable.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0104",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ location,
+ location?.SourceTree?.FilePath));
+ }
+
+ public static void ReportSignalDelegateMissingSuffix(
+ GeneratorExecutionContext context,
+ INamedTypeSymbol delegateSymbol)
+ {
+ var locations = delegateSymbol.Locations;
+ var location = locations.FirstOrDefault(l => l.SourceTree != null) ?? locations.FirstOrDefault();
+
+ string message = "The name of the delegate must end with 'EventHandler': " +
+ delegateSymbol.ToDisplayString() +
+ $". Did you mean '{delegateSymbol.Name}EventHandler'?";
+
+ string description = $"{message}. Rename the delegate accordingly or remove the '[Signal]' attribute.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0201",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ location,
+ location?.SourceTree?.FilePath));
+ }
+
+ public static void ReportSignalParameterTypeNotSupported(
+ GeneratorExecutionContext context,
+ IParameterSymbol parameterSymbol)
+ {
+ var locations = parameterSymbol.Locations;
+ var location = locations.FirstOrDefault(l => l.SourceTree != null) ?? locations.FirstOrDefault();
+
+ string message = "The parameter of the delegate signature of the signal " +
+ $"is not supported: '{parameterSymbol.ToDisplayString()}'";
+
+ string description = $"{message}. Use supported types only or remove the '[Signal]' attribute.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0202",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ location,
+ location?.SourceTree?.FilePath));
+ }
+
+ public static void ReportSignalDelegateSignatureMustReturnVoid(
+ GeneratorExecutionContext context,
+ INamedTypeSymbol delegateSymbol)
+ {
+ var locations = delegateSymbol.Locations;
+ var location = locations.FirstOrDefault(l => l.SourceTree != null) ?? locations.FirstOrDefault();
+
+ string message = "The delegate signature of the signal " +
+ $"must return void: '{delegateSymbol.ToDisplayString()}'";
+
+ string description = $"{message}. Return void or remove the '[Signal]' attribute.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0203",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ location,
+ location?.SourceTree?.FilePath));
+ }
+
+ public static readonly DiagnosticDescriptor GenericTypeArgumentMustBeVariantRule =
+ new DiagnosticDescriptor(id: "GD0301",
+ title: "The generic type argument must be a Variant compatible type",
+ messageFormat: "The generic type argument must be a Variant compatible type: {0}",
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ "The generic type argument must be a Variant compatible type. Use a Variant compatible type as the generic type argument.");
+
+ public static void ReportGenericTypeArgumentMustBeVariant(
+ SyntaxNodeAnalysisContext context,
+ SyntaxNode typeArgumentSyntax,
+ ISymbol typeArgumentSymbol)
+ {
+ string message = "The generic type argument " +
+ $"must be a Variant compatible type: '{typeArgumentSymbol.ToDisplayString()}'";
+
+ string description = $"{message}. Use a Variant compatible type as the generic type argument.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0301",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ typeArgumentSyntax.GetLocation(),
+ typeArgumentSyntax.SyntaxTree.FilePath));
+ }
+
+ public static readonly DiagnosticDescriptor GenericTypeParameterMustBeVariantAnnotatedRule =
+ new DiagnosticDescriptor(id: "GD0302",
+ title: "The generic type parameter must be annotated with the MustBeVariant attribute",
+ messageFormat: "The generic type argument must be a Variant type: {0}",
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ "The generic type argument must be a Variant type. Use a Variant type as the generic type argument.");
+
+ public static void ReportGenericTypeParameterMustBeVariantAnnotated(
+ SyntaxNodeAnalysisContext context,
+ SyntaxNode typeArgumentSyntax,
+ ISymbol typeArgumentSymbol)
+ {
+ string message = "The generic type parameter must be annotated with the MustBeVariant attribute";
+
+ string description = $"{message}. Add the MustBeVariant attribute to the generic type parameter.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0302",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ typeArgumentSyntax.GetLocation(),
+ typeArgumentSyntax.SyntaxTree.FilePath));
+ }
+
+ public static readonly DiagnosticDescriptor TypeArgumentParentSymbolUnhandledRule =
+ new DiagnosticDescriptor(id: "GD0303",
+ title: "The generic type parameter must be annotated with the MustBeVariant attribute",
+ messageFormat: "The generic type argument must be a Variant type: {0}",
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ "The generic type argument must be a Variant type. Use a Variant type as the generic type argument.");
+
+ public static void ReportTypeArgumentParentSymbolUnhandled(
+ SyntaxNodeAnalysisContext context,
+ SyntaxNode typeArgumentSyntax,
+ ISymbol parentSymbol)
+ {
+ string message = $"Symbol '{parentSymbol.ToDisplayString()}' parent of a type argument " +
+ "that must be Variant compatible was not handled.";
+
+ string description = $"{message}. Handle type arguments that are children of the unhandled symbol type.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GD0303",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ typeArgumentSyntax.GetLocation(),
+ typeArgumentSyntax.SyntaxTree.FilePath));
+ }
}
}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs
index e16f72f43a..de3b6c862a 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs
@@ -1,4 +1,6 @@
+using System;
using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
@@ -13,30 +15,65 @@ namespace Godot.SourceGenerators
) => context.AnalyzerConfigOptions.GlobalOptions
.TryGetValue("build_property." + property, out value);
- private static bool InheritsFrom(this INamedTypeSymbol? symbol, string baseName)
- {
- if (symbol == null)
- return false;
+ public static bool AreGodotSourceGeneratorsDisabled(this GeneratorExecutionContext context)
+ => context.TryGetGlobalAnalyzerProperty("GodotSourceGenerators", out string? toggle) &&
+ toggle != null &&
+ toggle.Equals("disabled", StringComparison.OrdinalIgnoreCase);
+
+ public static bool IsGodotToolsProject(this GeneratorExecutionContext context)
+ => context.TryGetGlobalAnalyzerProperty("IsGodotToolsProject", out string? toggle) &&
+ toggle != null &&
+ toggle.Equals("true", StringComparison.OrdinalIgnoreCase);
- while (true)
+ public static bool InheritsFrom(this INamedTypeSymbol? symbol, string assemblyName, string typeFullName)
+ {
+ while (symbol != null)
{
- if (symbol.ToString() == baseName)
+ if (symbol.ContainingAssembly.Name == assemblyName &&
+ symbol.ToString() == typeFullName)
{
return true;
}
- if (symbol.BaseType != null)
- {
- symbol = symbol.BaseType;
- continue;
- }
-
- break;
+ symbol = symbol.BaseType;
}
return false;
}
+ public static INamedTypeSymbol? GetGodotScriptNativeClass(this INamedTypeSymbol classTypeSymbol)
+ {
+ var symbol = classTypeSymbol;
+
+ while (symbol != null)
+ {
+ if (symbol.ContainingAssembly.Name == "GodotSharp")
+ return symbol;
+
+ symbol = symbol.BaseType;
+ }
+
+ return null;
+ }
+
+ public static string? GetGodotScriptNativeClassName(this INamedTypeSymbol classTypeSymbol)
+ {
+ var nativeType = classTypeSymbol.GetGodotScriptNativeClass();
+
+ if (nativeType == null)
+ return null;
+
+ var godotClassNameAttr = nativeType.GetAttributes()
+ .FirstOrDefault(a => a.AttributeClass?.IsGodotClassNameAttribute() ?? false);
+
+ string? godotClassName = null;
+
+ if (godotClassNameAttr is { ConstructorArguments: { Length: > 0 } })
+ godotClassName = godotClassNameAttr.ConstructorArguments[0].Value?.ToString();
+
+ return godotClassName ?? nativeType.Name;
+ }
+
private static bool IsGodotScriptClass(
this ClassDeclarationSyntax cds, Compilation compilation,
out INamedTypeSymbol? symbol
@@ -47,7 +84,7 @@ namespace Godot.SourceGenerators
var classTypeSymbol = sm.GetDeclaredSymbol(cds);
if (classTypeSymbol?.BaseType == null
- || !classTypeSymbol.BaseType.InheritsFrom(GodotClasses.Object))
+ || !classTypeSymbol.BaseType.InheritsFrom("GodotSharp", GodotClasses.Object))
{
symbol = null;
return false;
@@ -69,21 +106,182 @@ namespace Godot.SourceGenerators
}
}
- public static bool IsPartial(this ClassDeclarationSyntax cds)
+ public static bool IsNested(this TypeDeclarationSyntax cds)
+ => cds.Parent is TypeDeclarationSyntax;
+
+ public static bool IsPartial(this TypeDeclarationSyntax cds)
=> cds.Modifiers.Any(SyntaxKind.PartialKeyword);
- public static bool HasDisableGeneratorsAttribute(this INamedTypeSymbol symbol)
- => symbol.GetAttributes().Any(attr =>
- attr.AttributeClass?.ToString() == GodotClasses.DisableGodotGeneratorsAttr);
+ public static bool AreAllOuterTypesPartial(
+ this TypeDeclarationSyntax cds,
+ out TypeDeclarationSyntax? typeMissingPartial
+ )
+ {
+ SyntaxNode? outerSyntaxNode = cds.Parent;
+
+ while (outerSyntaxNode is TypeDeclarationSyntax outerTypeDeclSyntax)
+ {
+ if (!outerTypeDeclSyntax.IsPartial())
+ {
+ typeMissingPartial = outerTypeDeclSyntax;
+ return false;
+ }
+
+ outerSyntaxNode = outerSyntaxNode.Parent;
+ }
+
+ typeMissingPartial = null;
+ return true;
+ }
+
+ public static string GetDeclarationKeyword(this INamedTypeSymbol namedTypeSymbol)
+ {
+ string? keyword = namedTypeSymbol.DeclaringSyntaxReferences
+ .OfType<TypeDeclarationSyntax>().FirstOrDefault()?
+ .Keyword.Text;
+
+ return keyword ?? namedTypeSymbol.TypeKind switch
+ {
+ TypeKind.Interface => "interface",
+ TypeKind.Struct => "struct",
+ _ => "class"
+ };
+ }
private static SymbolDisplayFormat FullyQualifiedFormatOmitGlobal { get; } =
SymbolDisplayFormat.FullyQualifiedFormat
.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
- public static string FullQualifiedName(this INamedTypeSymbol symbol)
+ public static string FullQualifiedName(this ITypeSymbol symbol)
=> symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatOmitGlobal);
+ public static string NameWithTypeParameters(this INamedTypeSymbol symbol)
+ {
+ return symbol.IsGenericType ?
+ string.Concat(symbol.Name, "<", string.Join(", ", symbol.TypeParameters), ">") :
+ symbol.Name;
+ }
+
public static string FullQualifiedName(this INamespaceSymbol namespaceSymbol)
=> namespaceSymbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
+
+ public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
+ => qualifiedName
+ // AddSource() doesn't support angle brackets
+ .Replace("<", "(Of ")
+ .Replace(">", ")");
+
+ public static bool IsGodotExportAttribute(this INamedTypeSymbol symbol)
+ => symbol.ToString() == GodotClasses.ExportAttr;
+
+ public static bool IsGodotSignalAttribute(this INamedTypeSymbol symbol)
+ => symbol.ToString() == GodotClasses.SignalAttr;
+
+ public static bool IsGodotMustBeVariantAttribute(this INamedTypeSymbol symbol)
+ => symbol.ToString() == GodotClasses.MustBeVariantAttr;
+
+ public static bool IsGodotClassNameAttribute(this INamedTypeSymbol symbol)
+ => symbol.ToString() == GodotClasses.GodotClassNameAttr;
+
+ public static bool IsSystemFlagsAttribute(this INamedTypeSymbol symbol)
+ => symbol.ToString() == GodotClasses.SystemFlagsAttr;
+
+ public static GodotMethodData? HasGodotCompatibleSignature(
+ this IMethodSymbol method,
+ MarshalUtils.TypeCache typeCache
+ )
+ {
+ if (method.IsGenericMethod)
+ return null;
+
+ var retSymbol = method.ReturnType;
+ var retType = method.ReturnsVoid ?
+ null :
+ MarshalUtils.ConvertManagedTypeToMarshalType(method.ReturnType, typeCache);
+
+ if (retType == null && !method.ReturnsVoid)
+ return null;
+
+ var parameters = method.Parameters;
+
+ var paramTypes = parameters
+ // Currently we don't support `ref`, `out`, `in`, `ref readonly` parameters (and we never may)
+ .Where(p => p.RefKind == RefKind.None)
+ // Attempt to determine the variant type
+ .Select(p => MarshalUtils.ConvertManagedTypeToMarshalType(p.Type, typeCache))
+ // Discard parameter types that couldn't be determined (null entries)
+ .Where(t => t != null).Cast<MarshalType>().ToImmutableArray();
+
+ // If any parameter type was incompatible, it was discarded so the length won't match
+ if (parameters.Length > paramTypes.Length)
+ return null; // Ignore incompatible method
+
+ return new GodotMethodData(method, paramTypes, parameters
+ .Select(p => p.Type).ToImmutableArray(), retType, retSymbol);
+ }
+
+ public static IEnumerable<GodotMethodData> WhereHasGodotCompatibleSignature(
+ this IEnumerable<IMethodSymbol> methods,
+ MarshalUtils.TypeCache typeCache
+ )
+ {
+ foreach (var method in methods)
+ {
+ var methodData = HasGodotCompatibleSignature(method, typeCache);
+
+ if (methodData != null)
+ yield return methodData.Value;
+ }
+ }
+
+ public static IEnumerable<GodotPropertyData> WhereIsGodotCompatibleType(
+ this IEnumerable<IPropertySymbol> properties,
+ MarshalUtils.TypeCache typeCache
+ )
+ {
+ foreach (var property in properties)
+ {
+ // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
+ // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
+ if (property.IsWriteOnly || property.IsReadOnly)
+ continue;
+
+ var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(property.Type, typeCache);
+
+ if (marshalType == null)
+ continue;
+
+ yield return new GodotPropertyData(property, marshalType.Value);
+ }
+ }
+
+ public static IEnumerable<GodotFieldData> WhereIsGodotCompatibleType(
+ this IEnumerable<IFieldSymbol> fields,
+ MarshalUtils.TypeCache typeCache
+ )
+ {
+ foreach (var field in fields)
+ {
+ // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
+ // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
+ if (field.IsReadOnly)
+ continue;
+
+ var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(field.Type, typeCache);
+
+ if (marshalType == null)
+ continue;
+
+ yield return new GodotFieldData(field, marshalType.Value);
+ }
+ }
+
+ public static string Path(this Location location)
+ => location.SourceTree?.GetLineSpan(location.SourceSpan).Path
+ ?? location.GetLineSpan().Path;
+
+ public static int StartLine(this Location location)
+ => location.SourceTree?.GetLineSpan(location.SourceSpan).StartLinePosition.Line
+ ?? location.GetLineSpan().StartLinePosition.Line;
}
}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj
index 11d8e0f72b..f51b5970c3 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
- <LangVersion>8.0</LangVersion>
+ <LangVersion>9.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
@@ -21,21 +21,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" />
- <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.1" PrivateAssets="all" />
+ <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<!-- Package the generator in the analyzer directory of the nuget package -->
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<!-- Package the props file -->
- <None Include="Godot.SourceGenerators.props" Pack="true" PackagePath="build" Visible="false" />
+ <None Include="Godot.SourceGenerators.props" Pack="true" PackagePath="build" Visible="true" />
</ItemGroup>
-
- <Target Name="CopyNupkgToSConsOutputDir" AfterTargets="Pack">
- <PropertyGroup>
- <GodotSourceRootPath>$(SolutionDir)\..\..\..\..\</GodotSourceRootPath>
- <GodotOutputDataDir>$(GodotSourceRootPath)\bin\GodotSharp\</GodotOutputDataDir>
- </PropertyGroup>
- <Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" />
- </Target>
</Project>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.props b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.props
index f9b47ad5b1..7881ed0a8c 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.props
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.props
@@ -2,6 +2,7 @@
<ItemGroup>
<!-- $(GodotProjectDir) is defined by Godot.NET.Sdk -->
<CompilerVisibleProperty Include="GodotProjectDir" />
- <CompilerVisibleProperty Include="GodotScriptPathAttributeGenerator" />
+ <CompilerVisibleProperty Include="GodotSourceGenerators" />
+ <CompilerVisibleProperty Include="IsGodotToolsProject" />
</ItemGroup>
</Project>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotClasses.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotClasses.cs
index 29e41d155a..1d8ddbabf2 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotClasses.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotClasses.cs
@@ -3,7 +3,14 @@ namespace Godot.SourceGenerators
public static class GodotClasses
{
public const string Object = "Godot.Object";
- public const string DisableGodotGeneratorsAttr = "Godot.DisableGodotGeneratorsAttribute";
public const string AssemblyHasScriptsAttr = "Godot.AssemblyHasScriptsAttribute";
+ public const string ExportAttr = "Godot.ExportAttribute";
+ public const string ExportCategoryAttr = "Godot.ExportCategoryAttribute";
+ public const string ExportGroupAttr = "Godot.ExportGroupAttribute";
+ public const string ExportSubgroupAttr = "Godot.ExportSubgroupAttribute";
+ public const string SignalAttr = "Godot.SignalAttribute";
+ public const string MustBeVariantAttr = "Godot.MustBeVariantAttribute";
+ public const string GodotClassNameAttr = "Godot.GodotClassName";
+ public const string SystemFlagsAttr = "System.FlagsAttribute";
}
}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotEnums.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotEnums.cs
new file mode 100644
index 0000000000..1a25d684a0
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotEnums.cs
@@ -0,0 +1,148 @@
+using System;
+
+namespace Godot.SourceGenerators
+{
+ // TODO: May need to think about compatibility here. Could Godot change these values between minor versions?
+
+ internal enum VariantType
+ {
+ Nil = 0,
+ Bool = 1,
+ Int = 2,
+ Float = 3,
+ String = 4,
+ Vector2 = 5,
+ Vector2i = 6,
+ Rect2 = 7,
+ Rect2i = 8,
+ Vector3 = 9,
+ Vector3i = 10,
+ Transform2d = 11,
+ Vector4 = 12,
+ Vector4i = 13,
+ Plane = 14,
+ Quaternion = 15,
+ Aabb = 16,
+ Basis = 17,
+ Transform3d = 18,
+ Projection = 19,
+ Color = 20,
+ StringName = 21,
+ NodePath = 22,
+ Rid = 23,
+ Object = 24,
+ Callable = 25,
+ Signal = 26,
+ Dictionary = 27,
+ Array = 28,
+ PackedByteArray = 29,
+ PackedInt32Array = 30,
+ PackedInt64Array = 31,
+ PackedFloat32Array = 32,
+ PackedFloat64Array = 33,
+ PackedStringArray = 34,
+ PackedVector2Array = 35,
+ PackedVector3Array = 36,
+ PackedColorArray = 37,
+ Max = 38
+ }
+
+ internal enum PropertyHint
+ {
+ None = 0,
+ Range = 1,
+ Enum = 2,
+ EnumSuggestion = 3,
+ ExpEasing = 4,
+ Link = 5,
+ Flags = 6,
+ Layers2dRender = 7,
+ Layers2dPhysics = 8,
+ Layers2dNavigation = 9,
+ Layers3dRender = 10,
+ Layers3dPhysics = 11,
+ Layers3dNavigation = 12,
+ File = 13,
+ Dir = 14,
+ GlobalFile = 15,
+ GlobalDir = 16,
+ ResourceType = 17,
+ MultilineText = 18,
+ Expression = 19,
+ PlaceholderText = 20,
+ ColorNoAlpha = 21,
+ ImageCompressLossy = 22,
+ ImageCompressLossless = 23,
+ ObjectId = 24,
+ TypeString = 25,
+ NodePathToEditedNode = 26,
+ MethodOfVariantType = 27,
+ MethodOfBaseType = 28,
+ MethodOfInstance = 29,
+ MethodOfScript = 30,
+ PropertyOfVariantType = 31,
+ PropertyOfBaseType = 32,
+ PropertyOfInstance = 33,
+ PropertyOfScript = 34,
+ ObjectTooBig = 35,
+ NodePathValidTypes = 36,
+ SaveFile = 37,
+ GlobalSaveFile = 38,
+ IntIsObjectid = 39,
+ IntIsPointer = 41,
+ ArrayType = 40,
+ LocaleId = 42,
+ LocalizableString = 43,
+ NodeType = 44,
+ Max = 45
+ }
+
+ [Flags]
+ internal enum PropertyUsageFlags
+ {
+ None = 0,
+ Storage = 2,
+ Editor = 4,
+ Checkable = 8,
+ Checked = 16,
+ Internationalized = 32,
+ Group = 64,
+ Category = 128,
+ Subgroup = 256,
+ ClassIsBitfield = 512,
+ NoInstanceState = 1024,
+ RestartIfChanged = 2048,
+ ScriptVariable = 4096,
+ StoreIfNull = 8192,
+ AnimateAsTrigger = 16384,
+ UpdateAllIfModified = 32768,
+ ScriptDefaultValue = 65536,
+ ClassIsEnum = 131072,
+ NilIsVariant = 262144,
+ Internal = 524288,
+ DoNotShareOnDuplicate = 1048576,
+ HighEndGfx = 2097152,
+ NodePathFromSceneRoot = 4194304,
+ ResourceNotPersistent = 8388608,
+ KeyingIncrements = 16777216,
+ DeferredSetResource = 33554432,
+ EditorInstantiateObject = 67108864,
+ EditorBasicSetting = 134217728,
+ Array = 536870912,
+ Default = 6,
+ DefaultIntl = 38,
+ NoEditor = 2
+ }
+
+ public enum MethodFlags
+ {
+ Normal = 1,
+ Editor = 2,
+ Const = 4,
+ Virtual = 8,
+ Vararg = 16,
+ Static = 32,
+ ObjectCore = 64,
+ Default = 1
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotMemberData.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotMemberData.cs
new file mode 100644
index 0000000000..db395e21cb
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotMemberData.cs
@@ -0,0 +1,84 @@
+using System.Collections.Immutable;
+using Microsoft.CodeAnalysis;
+
+namespace Godot.SourceGenerators
+{
+ public struct GodotMethodData
+ {
+ public GodotMethodData(IMethodSymbol method, ImmutableArray<MarshalType> paramTypes,
+ ImmutableArray<ITypeSymbol> paramTypeSymbols, MarshalType? retType, ITypeSymbol? retSymbol)
+ {
+ Method = method;
+ ParamTypes = paramTypes;
+ ParamTypeSymbols = paramTypeSymbols;
+ RetType = retType;
+ RetSymbol = retSymbol;
+ }
+
+ public IMethodSymbol Method { get; }
+ public ImmutableArray<MarshalType> ParamTypes { get; }
+ public ImmutableArray<ITypeSymbol> ParamTypeSymbols { get; }
+ public MarshalType? RetType { get; }
+ public ITypeSymbol? RetSymbol { get; }
+ }
+
+ public struct GodotSignalDelegateData
+ {
+ public GodotSignalDelegateData(string name, INamedTypeSymbol delegateSymbol, GodotMethodData invokeMethodData)
+ {
+ Name = name;
+ DelegateSymbol = delegateSymbol;
+ InvokeMethodData = invokeMethodData;
+ }
+
+ public string Name { get; }
+ public INamedTypeSymbol DelegateSymbol { get; }
+ public GodotMethodData InvokeMethodData { get; }
+ }
+
+ public struct GodotPropertyData
+ {
+ public GodotPropertyData(IPropertySymbol propertySymbol, MarshalType type)
+ {
+ PropertySymbol = propertySymbol;
+ Type = type;
+ }
+
+ public IPropertySymbol PropertySymbol { get; }
+ public MarshalType Type { get; }
+ }
+
+ public struct GodotFieldData
+ {
+ public GodotFieldData(IFieldSymbol fieldSymbol, MarshalType type)
+ {
+ FieldSymbol = fieldSymbol;
+ Type = type;
+ }
+
+ public IFieldSymbol FieldSymbol { get; }
+ public MarshalType Type { get; }
+ }
+
+ public struct GodotPropertyOrFieldData
+ {
+ public GodotPropertyOrFieldData(ISymbol symbol, MarshalType type)
+ {
+ Symbol = symbol;
+ Type = type;
+ }
+
+ public GodotPropertyOrFieldData(GodotPropertyData propertyData)
+ : this(propertyData.PropertySymbol, propertyData.Type)
+ {
+ }
+
+ public GodotPropertyOrFieldData(GodotFieldData fieldData)
+ : this(fieldData.FieldSymbol, fieldData.Type)
+ {
+ }
+
+ public ISymbol Symbol { get; }
+ public MarshalType Type { get; }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs
new file mode 100644
index 0000000000..54da6218f3
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs
@@ -0,0 +1,60 @@
+using System.Text;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Text;
+
+namespace Godot.SourceGenerators
+{
+ [Generator]
+ public class GodotPluginsInitializerGenerator : ISourceGenerator
+ {
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ if (context.IsGodotToolsProject())
+ return;
+
+ string source =
+ @"using System;
+using System.Runtime.InteropServices;
+using Godot.Bridge;
+using Godot.NativeInterop;
+
+namespace GodotPlugins.Game
+{
+ internal static partial class Main
+ {
+ [UnmanagedCallersOnly(EntryPoint = ""godotsharp_game_main_init"")]
+ private static godot_bool InitializeFromGameProject(IntPtr godotDllHandle, IntPtr outManagedCallbacks)
+ {
+ try
+ {
+ DllImportResolver dllImportResolver = new GodotDllImportResolver(godotDllHandle).OnResolveDllImport;
+
+ var coreApiAssembly = typeof(Godot.Object).Assembly;
+
+ NativeLibrary.SetDllImportResolver(coreApiAssembly, dllImportResolver);
+
+ ManagedCallbacks.Create(outManagedCallbacks);
+
+ ScriptManagerBridge.LookupScriptsInAssembly(typeof(GodotPlugins.Game.Main).Assembly);
+
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine(e);
+ return false.ToGodotBool();
+ }
+ }
+ }
+}
+";
+
+ context.AddSource("GodotPlugins.Game_Generated",
+ SourceText.From(source, Encoding.UTF8));
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs
new file mode 100644
index 0000000000..15f5803bf0
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs
@@ -0,0 +1,73 @@
+using System.Diagnostics.CodeAnalysis;
+
+namespace Godot.SourceGenerators
+{
+ [SuppressMessage("ReSharper", "InconsistentNaming")]
+ public enum MarshalType
+ {
+ Boolean,
+ Char,
+ SByte,
+ Int16,
+ Int32,
+ Int64,
+ Byte,
+ UInt16,
+ UInt32,
+ UInt64,
+ Single,
+ Double,
+ String,
+
+ // Godot structs
+ Vector2,
+ Vector2i,
+ Rect2,
+ Rect2i,
+ Transform2D,
+ Vector3,
+ Vector3i,
+ Basis,
+ Quaternion,
+ Transform3D,
+ Vector4,
+ Vector4i,
+ Projection,
+ AABB,
+ Color,
+ Plane,
+ Callable,
+ SignalInfo,
+
+ // Enums
+ Enum,
+
+ // Arrays
+ ByteArray,
+ Int32Array,
+ Int64Array,
+ Float32Array,
+ Float64Array,
+ StringArray,
+ Vector2Array,
+ Vector3Array,
+ ColorArray,
+ GodotObjectOrDerivedArray,
+ SystemArrayOfStringName,
+ SystemArrayOfNodePath,
+ SystemArrayOfRID,
+
+ // Variant
+ Variant,
+
+ // Classes
+ GodotObjectOrDerived,
+ StringName,
+ NodePath,
+ RID,
+ GodotDictionary,
+ GodotArray,
+ GodotGenericDictionary,
+ GodotGenericArray,
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs
new file mode 100644
index 0000000000..831ac3bdeb
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs
@@ -0,0 +1,678 @@
+using System;
+using System.Linq;
+using System.Text;
+using Microsoft.CodeAnalysis;
+
+namespace Godot.SourceGenerators
+{
+ internal static class MarshalUtils
+ {
+ public class TypeCache
+ {
+ public INamedTypeSymbol GodotObjectType { get; }
+
+ public TypeCache(Compilation compilation)
+ {
+ INamedTypeSymbol GetTypeByMetadataNameOrThrow(string fullyQualifiedMetadataName)
+ {
+ return compilation.GetTypeByMetadataName(fullyQualifiedMetadataName) ??
+ throw new InvalidOperationException("Type not found: " + fullyQualifiedMetadataName);
+ }
+
+ GodotObjectType = GetTypeByMetadataNameOrThrow("Godot.Object");
+ }
+ }
+
+ public static VariantType? ConvertMarshalTypeToVariantType(MarshalType marshalType)
+ => marshalType switch
+ {
+ MarshalType.Boolean => VariantType.Bool,
+ MarshalType.Char => VariantType.Int,
+ MarshalType.SByte => VariantType.Int,
+ MarshalType.Int16 => VariantType.Int,
+ MarshalType.Int32 => VariantType.Int,
+ MarshalType.Int64 => VariantType.Int,
+ MarshalType.Byte => VariantType.Int,
+ MarshalType.UInt16 => VariantType.Int,
+ MarshalType.UInt32 => VariantType.Int,
+ MarshalType.UInt64 => VariantType.Int,
+ MarshalType.Single => VariantType.Float,
+ MarshalType.Double => VariantType.Float,
+ MarshalType.String => VariantType.String,
+ MarshalType.Vector2 => VariantType.Vector2,
+ MarshalType.Vector2i => VariantType.Vector2i,
+ MarshalType.Rect2 => VariantType.Rect2,
+ MarshalType.Rect2i => VariantType.Rect2i,
+ MarshalType.Transform2D => VariantType.Transform2d,
+ MarshalType.Vector3 => VariantType.Vector3,
+ MarshalType.Vector3i => VariantType.Vector3i,
+ MarshalType.Basis => VariantType.Basis,
+ MarshalType.Quaternion => VariantType.Quaternion,
+ MarshalType.Transform3D => VariantType.Transform3d,
+ MarshalType.Vector4 => VariantType.Vector4,
+ MarshalType.Vector4i => VariantType.Vector4i,
+ MarshalType.Projection => VariantType.Projection,
+ MarshalType.AABB => VariantType.Aabb,
+ MarshalType.Color => VariantType.Color,
+ MarshalType.Plane => VariantType.Plane,
+ MarshalType.Callable => VariantType.Callable,
+ MarshalType.SignalInfo => VariantType.Signal,
+ MarshalType.Enum => VariantType.Int,
+ MarshalType.ByteArray => VariantType.PackedByteArray,
+ MarshalType.Int32Array => VariantType.PackedInt32Array,
+ MarshalType.Int64Array => VariantType.PackedInt64Array,
+ MarshalType.Float32Array => VariantType.PackedFloat32Array,
+ MarshalType.Float64Array => VariantType.PackedFloat64Array,
+ MarshalType.StringArray => VariantType.PackedStringArray,
+ MarshalType.Vector2Array => VariantType.PackedVector2Array,
+ MarshalType.Vector3Array => VariantType.PackedVector3Array,
+ MarshalType.ColorArray => VariantType.PackedColorArray,
+ MarshalType.GodotObjectOrDerivedArray => VariantType.Array,
+ MarshalType.SystemArrayOfStringName => VariantType.Array,
+ MarshalType.SystemArrayOfNodePath => VariantType.Array,
+ MarshalType.SystemArrayOfRID => VariantType.Array,
+ MarshalType.Variant => VariantType.Nil,
+ MarshalType.GodotObjectOrDerived => VariantType.Object,
+ MarshalType.StringName => VariantType.StringName,
+ MarshalType.NodePath => VariantType.NodePath,
+ MarshalType.RID => VariantType.Rid,
+ MarshalType.GodotDictionary => VariantType.Dictionary,
+ MarshalType.GodotArray => VariantType.Array,
+ MarshalType.GodotGenericDictionary => VariantType.Dictionary,
+ MarshalType.GodotGenericArray => VariantType.Array,
+ _ => null
+ };
+
+ public static MarshalType? ConvertManagedTypeToMarshalType(ITypeSymbol type, TypeCache typeCache)
+ {
+ var specialType = type.SpecialType;
+
+ switch (specialType)
+ {
+ case SpecialType.System_Boolean:
+ return MarshalType.Boolean;
+ case SpecialType.System_Char:
+ return MarshalType.Char;
+ case SpecialType.System_SByte:
+ return MarshalType.SByte;
+ case SpecialType.System_Int16:
+ return MarshalType.Int16;
+ case SpecialType.System_Int32:
+ return MarshalType.Int32;
+ case SpecialType.System_Int64:
+ return MarshalType.Int64;
+ case SpecialType.System_Byte:
+ return MarshalType.Byte;
+ case SpecialType.System_UInt16:
+ return MarshalType.UInt16;
+ case SpecialType.System_UInt32:
+ return MarshalType.UInt32;
+ case SpecialType.System_UInt64:
+ return MarshalType.UInt64;
+ case SpecialType.System_Single:
+ return MarshalType.Single;
+ case SpecialType.System_Double:
+ return MarshalType.Double;
+ case SpecialType.System_String:
+ return MarshalType.String;
+ default:
+ {
+ var typeKind = type.TypeKind;
+
+ if (typeKind == TypeKind.Enum)
+ return MarshalType.Enum;
+
+ if (typeKind == TypeKind.Struct)
+ {
+ if (type.ContainingAssembly.Name == "GodotSharp" &&
+ type.ContainingNamespace.Name == "Godot")
+ {
+ return type switch
+ {
+ { Name: "Vector2" } => MarshalType.Vector2,
+ { Name: "Vector2i" } => MarshalType.Vector2i,
+ { Name: "Rect2" } => MarshalType.Rect2,
+ { Name: "Rect2i" } => MarshalType.Rect2i,
+ { Name: "Transform2D" } => MarshalType.Transform2D,
+ { Name: "Vector3" } => MarshalType.Vector3,
+ { Name: "Vector3i" } => MarshalType.Vector3i,
+ { Name: "Basis" } => MarshalType.Basis,
+ { Name: "Quaternion" } => MarshalType.Quaternion,
+ { Name: "Transform3D" } => MarshalType.Transform3D,
+ { Name: "Vector4" } => MarshalType.Vector4,
+ { Name: "Vector4i" } => MarshalType.Vector4i,
+ { Name: "Projection" } => MarshalType.Projection,
+ { Name: "AABB" } => MarshalType.AABB,
+ { Name: "Color" } => MarshalType.Color,
+ { Name: "Plane" } => MarshalType.Plane,
+ { Name: "RID" } => MarshalType.RID,
+ { Name: "Callable" } => MarshalType.Callable,
+ { Name: "SignalInfo" } => MarshalType.SignalInfo,
+ { Name: "Variant" } => MarshalType.Variant,
+ _ => null
+ };
+ }
+ }
+ else if (typeKind == TypeKind.Array)
+ {
+ var arrayType = (IArrayTypeSymbol)type;
+ var elementType = arrayType.ElementType;
+
+ switch (elementType.SpecialType)
+ {
+ case SpecialType.System_Byte:
+ return MarshalType.ByteArray;
+ case SpecialType.System_Int32:
+ return MarshalType.Int32Array;
+ case SpecialType.System_Int64:
+ return MarshalType.Int64Array;
+ case SpecialType.System_Single:
+ return MarshalType.Float32Array;
+ case SpecialType.System_Double:
+ return MarshalType.Float64Array;
+ case SpecialType.System_String:
+ return MarshalType.StringArray;
+ }
+
+ if (elementType.SimpleDerivesFrom(typeCache.GodotObjectType))
+ return MarshalType.GodotObjectOrDerivedArray;
+
+ if (elementType.ContainingAssembly.Name == "GodotSharp" &&
+ elementType.ContainingNamespace.Name == "Godot")
+ {
+ switch (elementType)
+ {
+ case { Name: "Vector2" }:
+ return MarshalType.Vector2Array;
+ case { Name: "Vector3" }:
+ return MarshalType.Vector3Array;
+ case { Name: "Color" }:
+ return MarshalType.ColorArray;
+ case { Name: "StringName" }:
+ return MarshalType.SystemArrayOfStringName;
+ case { Name: "NodePath" }:
+ return MarshalType.SystemArrayOfNodePath;
+ case { Name: "RID" }:
+ return MarshalType.SystemArrayOfRID;
+ }
+ }
+
+ return null;
+ }
+ else
+ {
+ if (type.SimpleDerivesFrom(typeCache.GodotObjectType))
+ return MarshalType.GodotObjectOrDerived;
+
+ if (type.ContainingAssembly.Name == "GodotSharp")
+ {
+ switch (type.ContainingNamespace.Name)
+ {
+ case "Godot":
+ return type switch
+ {
+ { Name: "StringName" } => MarshalType.StringName,
+ { Name: "NodePath" } => MarshalType.NodePath,
+ _ => null
+ };
+ case "Collections"
+ when type.ContainingNamespace.FullQualifiedName() == "Godot.Collections":
+ return type switch
+ {
+ { Name: "Dictionary" } =>
+ type is INamedTypeSymbol { IsGenericType: false } ?
+ MarshalType.GodotDictionary :
+ MarshalType.GodotGenericDictionary,
+ { Name: "Array" } =>
+ type is INamedTypeSymbol { IsGenericType: false } ?
+ MarshalType.GodotArray :
+ MarshalType.GodotGenericArray,
+ _ => null
+ };
+ }
+ }
+ }
+
+ break;
+ }
+ }
+
+ return null;
+ }
+
+ private static bool SimpleDerivesFrom(this ITypeSymbol? type, ITypeSymbol candidateBaseType)
+ {
+ while (type != null)
+ {
+ if (SymbolEqualityComparer.Default.Equals(type, candidateBaseType))
+ return true;
+
+ type = type.BaseType;
+ }
+
+ return false;
+ }
+
+ public static ITypeSymbol? GetArrayElementType(ITypeSymbol typeSymbol)
+ {
+ if (typeSymbol.TypeKind == TypeKind.Array)
+ {
+ var arrayType = (IArrayTypeSymbol)typeSymbol;
+ return arrayType.ElementType;
+ }
+
+ if (typeSymbol is INamedTypeSymbol { IsGenericType: true } genericType)
+ return genericType.TypeArguments.FirstOrDefault();
+
+ return null;
+ }
+
+ private static StringBuilder Append(this StringBuilder source, string a, string b)
+ => source.Append(a).Append(b);
+
+ private static StringBuilder Append(this StringBuilder source, string a, string b, string c)
+ => source.Append(a).Append(b).Append(c);
+
+ private static StringBuilder Append(this StringBuilder source, string a, string b,
+ string c, string d)
+ => source.Append(a).Append(b).Append(c).Append(d);
+
+ private static StringBuilder Append(this StringBuilder source, string a, string b,
+ string c, string d, string e)
+ => source.Append(a).Append(b).Append(c).Append(d).Append(e);
+
+ private static StringBuilder Append(this StringBuilder source, string a, string b,
+ string c, string d, string e, string f)
+ => source.Append(a).Append(b).Append(c).Append(d).Append(e).Append(f);
+
+ private static StringBuilder Append(this StringBuilder source, string a, string b,
+ string c, string d, string e, string f, string g)
+ => source.Append(a).Append(b).Append(c).Append(d).Append(e).Append(f).Append(g);
+
+ private static StringBuilder Append(this StringBuilder source, string a, string b,
+ string c, string d, string e, string f, string g, string h)
+ => source.Append(a).Append(b).Append(c).Append(d).Append(e).Append(f).Append(g).Append(h);
+
+ private const string VariantUtils = "global::Godot.NativeInterop.VariantUtils";
+
+ public static StringBuilder AppendNativeVariantToManagedExpr(this StringBuilder source,
+ string inputExpr, ITypeSymbol typeSymbol, MarshalType marshalType)
+ {
+ return marshalType switch
+ {
+ MarshalType.Boolean =>
+ source.Append(VariantUtils, ".ConvertToBool(", inputExpr, ")"),
+ MarshalType.Char =>
+ source.Append("(char)", VariantUtils, ".ConvertToUInt16(", inputExpr, ")"),
+ MarshalType.SByte =>
+ source.Append(VariantUtils, ".ConvertToInt8(", inputExpr, ")"),
+ MarshalType.Int16 =>
+ source.Append(VariantUtils, ".ConvertToInt16(", inputExpr, ")"),
+ MarshalType.Int32 =>
+ source.Append(VariantUtils, ".ConvertToInt32(", inputExpr, ")"),
+ MarshalType.Int64 =>
+ source.Append(VariantUtils, ".ConvertToInt64(", inputExpr, ")"),
+ MarshalType.Byte =>
+ source.Append(VariantUtils, ".ConvertToUInt8(", inputExpr, ")"),
+ MarshalType.UInt16 =>
+ source.Append(VariantUtils, ".ConvertToUInt16(", inputExpr, ")"),
+ MarshalType.UInt32 =>
+ source.Append(VariantUtils, ".ConvertToUInt32(", inputExpr, ")"),
+ MarshalType.UInt64 =>
+ source.Append(VariantUtils, ".ConvertToUInt64(", inputExpr, ")"),
+ MarshalType.Single =>
+ source.Append(VariantUtils, ".ConvertToFloat32(", inputExpr, ")"),
+ MarshalType.Double =>
+ source.Append(VariantUtils, ".ConvertToFloat64(", inputExpr, ")"),
+ MarshalType.String =>
+ source.Append(VariantUtils, ".ConvertToStringObject(", inputExpr, ")"),
+ MarshalType.Vector2 =>
+ source.Append(VariantUtils, ".ConvertToVector2(", inputExpr, ")"),
+ MarshalType.Vector2i =>
+ source.Append(VariantUtils, ".ConvertToVector2i(", inputExpr, ")"),
+ MarshalType.Rect2 =>
+ source.Append(VariantUtils, ".ConvertToRect2(", inputExpr, ")"),
+ MarshalType.Rect2i =>
+ source.Append(VariantUtils, ".ConvertToRect2i(", inputExpr, ")"),
+ MarshalType.Transform2D =>
+ source.Append(VariantUtils, ".ConvertToTransform2D(", inputExpr, ")"),
+ MarshalType.Vector3 =>
+ source.Append(VariantUtils, ".ConvertToVector3(", inputExpr, ")"),
+ MarshalType.Vector3i =>
+ source.Append(VariantUtils, ".ConvertToVector3i(", inputExpr, ")"),
+ MarshalType.Basis =>
+ source.Append(VariantUtils, ".ConvertToBasis(", inputExpr, ")"),
+ MarshalType.Quaternion =>
+ source.Append(VariantUtils, ".ConvertToQuaternion(", inputExpr, ")"),
+ MarshalType.Transform3D =>
+ source.Append(VariantUtils, ".ConvertToTransform3D(", inputExpr, ")"),
+ MarshalType.Vector4 =>
+ source.Append(VariantUtils, ".ConvertToVector4(", inputExpr, ")"),
+ MarshalType.Vector4i =>
+ source.Append(VariantUtils, ".ConvertToVector4i(", inputExpr, ")"),
+ MarshalType.Projection =>
+ source.Append(VariantUtils, ".ConvertToProjection(", inputExpr, ")"),
+ MarshalType.AABB =>
+ source.Append(VariantUtils, ".ConvertToAABB(", inputExpr, ")"),
+ MarshalType.Color =>
+ source.Append(VariantUtils, ".ConvertToColor(", inputExpr, ")"),
+ MarshalType.Plane =>
+ source.Append(VariantUtils, ".ConvertToPlane(", inputExpr, ")"),
+ MarshalType.Callable =>
+ source.Append(VariantUtils, ".ConvertToCallableManaged(", inputExpr, ")"),
+ MarshalType.SignalInfo =>
+ source.Append(VariantUtils, ".ConvertToSignalInfo(", inputExpr, ")"),
+ MarshalType.Enum =>
+ source.Append("(", typeSymbol.FullQualifiedName(),
+ ")", VariantUtils, ".ConvertToInt32(", inputExpr, ")"),
+ MarshalType.ByteArray =>
+ source.Append(VariantUtils, ".ConvertAsPackedByteArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.Int32Array =>
+ source.Append(VariantUtils, ".ConvertAsPackedInt32ArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.Int64Array =>
+ source.Append(VariantUtils, ".ConvertAsPackedInt64ArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.Float32Array =>
+ source.Append(VariantUtils, ".ConvertAsPackedFloat32ArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.Float64Array =>
+ source.Append(VariantUtils, ".ConvertAsPackedFloat64ArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.StringArray =>
+ source.Append(VariantUtils, ".ConvertAsPackedStringArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.Vector2Array =>
+ source.Append(VariantUtils, ".ConvertAsPackedVector2ArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.Vector3Array =>
+ source.Append(VariantUtils, ".ConvertAsPackedVector3ArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.ColorArray =>
+ source.Append(VariantUtils, ".ConvertAsPackedColorArrayToSystemArray(", inputExpr, ")"),
+ MarshalType.GodotObjectOrDerivedArray =>
+ source.Append(VariantUtils, ".ConvertToSystemArrayOfGodotObject<",
+ ((IArrayTypeSymbol)typeSymbol).ElementType.FullQualifiedName(), ">(", inputExpr, ")"),
+ MarshalType.SystemArrayOfStringName =>
+ source.Append(VariantUtils, ".ConvertToSystemArrayOfStringName(", inputExpr, ")"),
+ MarshalType.SystemArrayOfNodePath =>
+ source.Append(VariantUtils, ".ConvertToSystemArrayOfNodePath(", inputExpr, ")"),
+ MarshalType.SystemArrayOfRID =>
+ source.Append(VariantUtils, ".ConvertToSystemArrayOfRID(", inputExpr, ")"),
+ MarshalType.Variant =>
+ source.Append("global::Godot.Variant.CreateCopyingBorrowed(", inputExpr, ")"),
+ MarshalType.GodotObjectOrDerived =>
+ source.Append("(", typeSymbol.FullQualifiedName(),
+ ")", VariantUtils, ".ConvertToGodotObject(", inputExpr, ")"),
+ MarshalType.StringName =>
+ source.Append(VariantUtils, ".ConvertToStringNameObject(", inputExpr, ")"),
+ MarshalType.NodePath =>
+ source.Append(VariantUtils, ".ConvertToNodePathObject(", inputExpr, ")"),
+ MarshalType.RID =>
+ source.Append(VariantUtils, ".ConvertToRID(", inputExpr, ")"),
+ MarshalType.GodotDictionary =>
+ source.Append(VariantUtils, ".ConvertToDictionaryObject(", inputExpr, ")"),
+ MarshalType.GodotArray =>
+ source.Append(VariantUtils, ".ConvertToArrayObject(", inputExpr, ")"),
+ MarshalType.GodotGenericDictionary =>
+ source.Append(VariantUtils, ".ConvertToDictionaryObject<",
+ ((INamedTypeSymbol)typeSymbol).TypeArguments[0].FullQualifiedName(), ", ",
+ ((INamedTypeSymbol)typeSymbol).TypeArguments[1].FullQualifiedName(), ">(", inputExpr, ")"),
+ MarshalType.GodotGenericArray =>
+ source.Append(VariantUtils, ".ConvertToArrayObject<",
+ ((INamedTypeSymbol)typeSymbol).TypeArguments[0].FullQualifiedName(), ">(", inputExpr, ")"),
+ _ => throw new ArgumentOutOfRangeException(nameof(marshalType), marshalType,
+ "Received unexpected marshal type")
+ };
+ }
+
+ public static StringBuilder AppendManagedToNativeVariantExpr(
+ this StringBuilder source, string inputExpr, MarshalType marshalType)
+ {
+ return marshalType switch
+ {
+ MarshalType.Boolean =>
+ source.Append(VariantUtils, ".CreateFromBool(", inputExpr, ")"),
+ MarshalType.Char =>
+ source.Append(VariantUtils, ".CreateFromInt((ushort)", inputExpr, ")"),
+ MarshalType.SByte =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.Int16 =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.Int32 =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.Int64 =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.Byte =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.UInt16 =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.UInt32 =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.UInt64 =>
+ source.Append(VariantUtils, ".CreateFromInt(", inputExpr, ")"),
+ MarshalType.Single =>
+ source.Append(VariantUtils, ".CreateFromFloat(", inputExpr, ")"),
+ MarshalType.Double =>
+ source.Append(VariantUtils, ".CreateFromFloat(", inputExpr, ")"),
+ MarshalType.String =>
+ source.Append(VariantUtils, ".CreateFromString(", inputExpr, ")"),
+ MarshalType.Vector2 =>
+ source.Append(VariantUtils, ".CreateFromVector2(", inputExpr, ")"),
+ MarshalType.Vector2i =>
+ source.Append(VariantUtils, ".CreateFromVector2i(", inputExpr, ")"),
+ MarshalType.Rect2 =>
+ source.Append(VariantUtils, ".CreateFromRect2(", inputExpr, ")"),
+ MarshalType.Rect2i =>
+ source.Append(VariantUtils, ".CreateFromRect2i(", inputExpr, ")"),
+ MarshalType.Transform2D =>
+ source.Append(VariantUtils, ".CreateFromTransform2D(", inputExpr, ")"),
+ MarshalType.Vector3 =>
+ source.Append(VariantUtils, ".CreateFromVector3(", inputExpr, ")"),
+ MarshalType.Vector3i =>
+ source.Append(VariantUtils, ".CreateFromVector3i(", inputExpr, ")"),
+ MarshalType.Basis =>
+ source.Append(VariantUtils, ".CreateFromBasis(", inputExpr, ")"),
+ MarshalType.Quaternion =>
+ source.Append(VariantUtils, ".CreateFromQuaternion(", inputExpr, ")"),
+ MarshalType.Transform3D =>
+ source.Append(VariantUtils, ".CreateFromTransform3D(", inputExpr, ")"),
+ MarshalType.Vector4 =>
+ source.Append(VariantUtils, ".CreateFromVector4(", inputExpr, ")"),
+ MarshalType.Vector4i =>
+ source.Append(VariantUtils, ".CreateFromVector4i(", inputExpr, ")"),
+ MarshalType.Projection =>
+ source.Append(VariantUtils, ".CreateFromProjection(", inputExpr, ")"),
+ MarshalType.AABB =>
+ source.Append(VariantUtils, ".CreateFromAABB(", inputExpr, ")"),
+ MarshalType.Color =>
+ source.Append(VariantUtils, ".CreateFromColor(", inputExpr, ")"),
+ MarshalType.Plane =>
+ source.Append(VariantUtils, ".CreateFromPlane(", inputExpr, ")"),
+ MarshalType.Callable =>
+ source.Append(VariantUtils, ".CreateFromCallable(", inputExpr, ")"),
+ MarshalType.SignalInfo =>
+ source.Append(VariantUtils, ".CreateFromSignalInfo(", inputExpr, ")"),
+ MarshalType.Enum =>
+ source.Append(VariantUtils, ".CreateFromInt((int)", inputExpr, ")"),
+ MarshalType.ByteArray =>
+ source.Append(VariantUtils, ".CreateFromPackedByteArray(", inputExpr, ")"),
+ MarshalType.Int32Array =>
+ source.Append(VariantUtils, ".CreateFromPackedInt32Array(", inputExpr, ")"),
+ MarshalType.Int64Array =>
+ source.Append(VariantUtils, ".CreateFromPackedInt64Array(", inputExpr, ")"),
+ MarshalType.Float32Array =>
+ source.Append(VariantUtils, ".CreateFromPackedFloat32Array(", inputExpr, ")"),
+ MarshalType.Float64Array =>
+ source.Append(VariantUtils, ".CreateFromPackedFloat64Array(", inputExpr, ")"),
+ MarshalType.StringArray =>
+ source.Append(VariantUtils, ".CreateFromPackedStringArray(", inputExpr, ")"),
+ MarshalType.Vector2Array =>
+ source.Append(VariantUtils, ".CreateFromPackedVector2Array(", inputExpr, ")"),
+ MarshalType.Vector3Array =>
+ source.Append(VariantUtils, ".CreateFromPackedVector3Array(", inputExpr, ")"),
+ MarshalType.ColorArray =>
+ source.Append(VariantUtils, ".CreateFromPackedColorArray(", inputExpr, ")"),
+ MarshalType.GodotObjectOrDerivedArray =>
+ source.Append(VariantUtils, ".CreateFromSystemArrayOfGodotObject(", inputExpr, ")"),
+ MarshalType.SystemArrayOfStringName =>
+ source.Append(VariantUtils, ".CreateFromSystemArrayOfStringName(", inputExpr, ")"),
+ MarshalType.SystemArrayOfNodePath =>
+ source.Append(VariantUtils, ".CreateFromSystemArrayOfNodePath(", inputExpr, ")"),
+ MarshalType.SystemArrayOfRID =>
+ source.Append(VariantUtils, ".CreateFromSystemArrayOfRID(", inputExpr, ")"),
+ MarshalType.Variant =>
+ source.Append(inputExpr, ".CopyNativeVariant()"),
+ MarshalType.GodotObjectOrDerived =>
+ source.Append(VariantUtils, ".CreateFromGodotObject(", inputExpr, ")"),
+ MarshalType.StringName =>
+ source.Append(VariantUtils, ".CreateFromStringName(", inputExpr, ")"),
+ MarshalType.NodePath =>
+ source.Append(VariantUtils, ".CreateFromNodePath(", inputExpr, ")"),
+ MarshalType.RID =>
+ source.Append(VariantUtils, ".CreateFromRID(", inputExpr, ")"),
+ MarshalType.GodotDictionary =>
+ source.Append(VariantUtils, ".CreateFromDictionary(", inputExpr, ")"),
+ MarshalType.GodotArray =>
+ source.Append(VariantUtils, ".CreateFromArray(", inputExpr, ")"),
+ MarshalType.GodotGenericDictionary =>
+ source.Append(VariantUtils, ".CreateFromDictionary(", inputExpr, ")"),
+ MarshalType.GodotGenericArray =>
+ source.Append(VariantUtils, ".CreateFromArray(", inputExpr, ")"),
+ _ => throw new ArgumentOutOfRangeException(nameof(marshalType), marshalType,
+ "Received unexpected marshal type")
+ };
+ }
+
+ public static StringBuilder AppendVariantToManagedExpr(this StringBuilder source,
+ string inputExpr, ITypeSymbol typeSymbol, MarshalType marshalType)
+ {
+ return marshalType switch
+ {
+ MarshalType.Boolean => source.Append(inputExpr, ".AsBool()"),
+ MarshalType.Char => source.Append(inputExpr, ".AsChar()"),
+ MarshalType.SByte => source.Append(inputExpr, ".AsSByte()"),
+ MarshalType.Int16 => source.Append(inputExpr, ".AsInt16()"),
+ MarshalType.Int32 => source.Append(inputExpr, ".AsInt32()"),
+ MarshalType.Int64 => source.Append(inputExpr, ".AsInt64()"),
+ MarshalType.Byte => source.Append(inputExpr, ".AsByte()"),
+ MarshalType.UInt16 => source.Append(inputExpr, ".AsUInt16()"),
+ MarshalType.UInt32 => source.Append(inputExpr, ".AsUInt32()"),
+ MarshalType.UInt64 => source.Append(inputExpr, ".AsUInt64()"),
+ MarshalType.Single => source.Append(inputExpr, ".AsSingle()"),
+ MarshalType.Double => source.Append(inputExpr, ".AsDouble()"),
+ MarshalType.String => source.Append(inputExpr, ".AsString()"),
+ MarshalType.Vector2 => source.Append(inputExpr, ".AsVector2()"),
+ MarshalType.Vector2i => source.Append(inputExpr, ".AsVector2i()"),
+ MarshalType.Rect2 => source.Append(inputExpr, ".AsRect2()"),
+ MarshalType.Rect2i => source.Append(inputExpr, ".AsRect2i()"),
+ MarshalType.Transform2D => source.Append(inputExpr, ".AsTransform2D()"),
+ MarshalType.Vector3 => source.Append(inputExpr, ".AsVector3()"),
+ MarshalType.Vector3i => source.Append(inputExpr, ".AsVector3i()"),
+ MarshalType.Basis => source.Append(inputExpr, ".AsBasis()"),
+ MarshalType.Quaternion => source.Append(inputExpr, ".AsQuaternion()"),
+ MarshalType.Transform3D => source.Append(inputExpr, ".AsTransform3D()"),
+ MarshalType.Vector4 => source.Append(inputExpr, ".AsVector4()"),
+ MarshalType.Vector4i => source.Append(inputExpr, ".AsVector4i()"),
+ MarshalType.Projection => source.Append(inputExpr, ".AsProjection()"),
+ MarshalType.AABB => source.Append(inputExpr, ".AsAABB()"),
+ MarshalType.Color => source.Append(inputExpr, ".AsColor()"),
+ MarshalType.Plane => source.Append(inputExpr, ".AsPlane()"),
+ MarshalType.Callable => source.Append(inputExpr, ".AsCallable()"),
+ MarshalType.SignalInfo => source.Append(inputExpr, ".AsSignalInfo()"),
+ MarshalType.Enum =>
+ source.Append("(", typeSymbol.FullQualifiedName(), ")", inputExpr, ".AsInt64()"),
+ MarshalType.ByteArray => source.Append(inputExpr, ".AsByteArray()"),
+ MarshalType.Int32Array => source.Append(inputExpr, ".AsInt32Array()"),
+ MarshalType.Int64Array => source.Append(inputExpr, ".AsInt64Array()"),
+ MarshalType.Float32Array => source.Append(inputExpr, ".AsFloat32Array()"),
+ MarshalType.Float64Array => source.Append(inputExpr, ".AsFloat64Array()"),
+ MarshalType.StringArray => source.Append(inputExpr, ".AsStringArray()"),
+ MarshalType.Vector2Array => source.Append(inputExpr, ".AsVector2Array()"),
+ MarshalType.Vector3Array => source.Append(inputExpr, ".AsVector3Array()"),
+ MarshalType.ColorArray => source.Append(inputExpr, ".AsColorArray()"),
+ MarshalType.GodotObjectOrDerivedArray => source.Append(inputExpr, ".AsGodotObjectArray<",
+ ((IArrayTypeSymbol)typeSymbol).ElementType.FullQualifiedName(), ">()"),
+ MarshalType.SystemArrayOfStringName => source.Append(inputExpr, ".AsSystemArrayOfStringName()"),
+ MarshalType.SystemArrayOfNodePath => source.Append(inputExpr, ".AsSystemArrayOfNodePath()"),
+ MarshalType.SystemArrayOfRID => source.Append(inputExpr, ".AsSystemArrayOfRID()"),
+ MarshalType.Variant => source.Append(inputExpr),
+ MarshalType.GodotObjectOrDerived => source.Append("(",
+ typeSymbol.FullQualifiedName(), ")", inputExpr, ".AsGodotObject()"),
+ MarshalType.StringName => source.Append(inputExpr, ".AsStringName()"),
+ MarshalType.NodePath => source.Append(inputExpr, ".AsNodePath()"),
+ MarshalType.RID => source.Append(inputExpr, ".AsRID()"),
+ MarshalType.GodotDictionary => source.Append(inputExpr, ".AsGodotDictionary()"),
+ MarshalType.GodotArray => source.Append(inputExpr, ".AsGodotArray()"),
+ MarshalType.GodotGenericDictionary => source.Append(inputExpr, ".AsGodotDictionary<",
+ ((INamedTypeSymbol)typeSymbol).TypeArguments[0].FullQualifiedName(), ", ",
+ ((INamedTypeSymbol)typeSymbol).TypeArguments[1].FullQualifiedName(), ">()"),
+ MarshalType.GodotGenericArray => source.Append(inputExpr, ".AsGodotArray<",
+ ((INamedTypeSymbol)typeSymbol).TypeArguments[0].FullQualifiedName(), ">()"),
+ _ => throw new ArgumentOutOfRangeException(nameof(marshalType), marshalType,
+ "Received unexpected marshal type")
+ };
+ }
+
+ public static StringBuilder AppendManagedToVariantExpr(this StringBuilder source,
+ string inputExpr, MarshalType marshalType)
+ {
+ switch (marshalType)
+ {
+ case MarshalType.Boolean:
+ case MarshalType.Char:
+ case MarshalType.SByte:
+ case MarshalType.Int16:
+ case MarshalType.Int32:
+ case MarshalType.Int64:
+ case MarshalType.Byte:
+ case MarshalType.UInt16:
+ case MarshalType.UInt32:
+ case MarshalType.UInt64:
+ case MarshalType.Single:
+ case MarshalType.Double:
+ case MarshalType.String:
+ case MarshalType.Vector2:
+ case MarshalType.Vector2i:
+ case MarshalType.Rect2:
+ case MarshalType.Rect2i:
+ case MarshalType.Transform2D:
+ case MarshalType.Vector3:
+ case MarshalType.Vector3i:
+ case MarshalType.Basis:
+ case MarshalType.Quaternion:
+ case MarshalType.Transform3D:
+ case MarshalType.Vector4:
+ case MarshalType.Vector4i:
+ case MarshalType.Projection:
+ case MarshalType.AABB:
+ case MarshalType.Color:
+ case MarshalType.Plane:
+ case MarshalType.Callable:
+ case MarshalType.SignalInfo:
+ case MarshalType.ByteArray:
+ case MarshalType.Int32Array:
+ case MarshalType.Int64Array:
+ case MarshalType.Float32Array:
+ case MarshalType.Float64Array:
+ case MarshalType.StringArray:
+ case MarshalType.Vector2Array:
+ case MarshalType.Vector3Array:
+ case MarshalType.ColorArray:
+ case MarshalType.GodotObjectOrDerivedArray:
+ case MarshalType.SystemArrayOfStringName:
+ case MarshalType.SystemArrayOfNodePath:
+ case MarshalType.SystemArrayOfRID:
+ case MarshalType.GodotObjectOrDerived:
+ case MarshalType.StringName:
+ case MarshalType.NodePath:
+ case MarshalType.RID:
+ case MarshalType.GodotDictionary:
+ case MarshalType.GodotArray:
+ case MarshalType.GodotGenericDictionary:
+ case MarshalType.GodotGenericArray:
+ return source.Append("Variant.CreateFrom(", inputExpr, ")");
+ case MarshalType.Enum:
+ return source.Append("Variant.CreateFrom((long)", inputExpr, ")");
+ case MarshalType.Variant:
+ return source.Append(inputExpr);
+ default:
+ throw new ArgumentOutOfRangeException(nameof(marshalType), marshalType,
+ "Received unexpected marshal type");
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MethodInfo.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MethodInfo.cs
new file mode 100644
index 0000000000..81c6f2b7d5
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MethodInfo.cs
@@ -0,0 +1,24 @@
+using System.Collections.Generic;
+
+namespace Godot.SourceGenerators
+{
+ internal struct MethodInfo
+ {
+ public MethodInfo(string name, PropertyInfo returnVal, MethodFlags flags,
+ List<PropertyInfo>? arguments,
+ List<string?>? defaultArguments)
+ {
+ Name = name;
+ ReturnVal = returnVal;
+ Flags = flags;
+ Arguments = arguments;
+ DefaultArguments = defaultArguments;
+ }
+
+ public string Name { get; }
+ public PropertyInfo ReturnVal { get; }
+ public MethodFlags Flags { get; }
+ public List<PropertyInfo>? Arguments { get; }
+ public List<string?>? DefaultArguments { get; }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MustBeVariantAnalyzer.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MustBeVariantAnalyzer.cs
new file mode 100644
index 0000000000..7aaadb27be
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MustBeVariantAnalyzer.cs
@@ -0,0 +1,100 @@
+using System.Collections.Immutable;
+using System.Diagnostics;
+using System.Linq;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Diagnostics;
+
+namespace Godot.SourceGenerators
+{
+ [DiagnosticAnalyzer(LanguageNames.CSharp)]
+ public class MustBeVariantAnalyzer : DiagnosticAnalyzer
+ {
+ public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
+ => ImmutableArray.Create(
+ Common.GenericTypeArgumentMustBeVariantRule,
+ Common.GenericTypeParameterMustBeVariantAnnotatedRule,
+ Common.TypeArgumentParentSymbolUnhandledRule);
+
+ public override void Initialize(AnalysisContext context)
+ {
+ context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+ context.EnableConcurrentExecution();
+ context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.TypeArgumentList);
+ }
+
+ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ {
+ var typeArgListSyntax = (TypeArgumentListSyntax)context.Node;
+
+ // Method invocation or variable declaration that contained the type arguments
+ var parentSyntax = context.Node.Parent;
+ Debug.Assert(parentSyntax != null);
+
+ var sm = context.SemanticModel;
+
+ var typeCache = new MarshalUtils.TypeCache(context.Compilation);
+
+ for (int i = 0; i < typeArgListSyntax.Arguments.Count; i++)
+ {
+ var typeSyntax = typeArgListSyntax.Arguments[i];
+ var typeSymbol = sm.GetSymbolInfo(typeSyntax).Symbol as ITypeSymbol;
+ Debug.Assert(typeSymbol != null);
+
+ var parentSymbol = sm.GetSymbolInfo(parentSyntax).Symbol;
+
+ if (!ShouldCheckTypeArgument(context, parentSyntax, parentSymbol, typeSyntax, typeSymbol, i))
+ {
+ return;
+ }
+
+ if (typeSymbol is ITypeParameterSymbol typeParamSymbol)
+ {
+ if (!typeParamSymbol.GetAttributes().Any(a => a.AttributeClass?.IsGodotMustBeVariantAttribute() ?? false))
+ {
+ Common.ReportGenericTypeParameterMustBeVariantAnnotated(context, typeSyntax, typeSymbol);
+ }
+ continue;
+ }
+
+ var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(typeSymbol, typeCache);
+
+ if (marshalType == null)
+ {
+ Common.ReportGenericTypeArgumentMustBeVariant(context, typeSyntax, typeSymbol);
+ continue;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Check if the given type argument is being used in a type parameter that contains
+ /// the <c>MustBeVariantAttribute</c>; otherwise, we ignore the attribute.
+ /// </summary>
+ /// <param name="context">Context for a syntax node action.</param>
+ /// <param name="parentSyntax">The parent node syntax that contains the type node syntax.</param>
+ /// <param name="parentSymbol">The symbol retrieved for the parent node syntax.</param>
+ /// <param name="typeArgumentSyntax">The type node syntax of the argument type to check.</param>
+ /// <param name="typeArgumentSymbol">The symbol retrieved for the type node syntax.</param>
+ /// <returns><see langword="true"/> if the type must be variant and must be analyzed.</returns>
+ private bool ShouldCheckTypeArgument(SyntaxNodeAnalysisContext context, SyntaxNode parentSyntax, ISymbol parentSymbol, TypeSyntax typeArgumentSyntax, ITypeSymbol typeArgumentSymbol, int typeArgumentIndex)
+ {
+ var typeParamSymbol = parentSymbol switch
+ {
+ IMethodSymbol methodSymbol => methodSymbol.TypeParameters[typeArgumentIndex],
+ INamedTypeSymbol typeSymbol => typeSymbol.TypeParameters[typeArgumentIndex],
+ _ => null,
+ };
+
+ if (typeParamSymbol == null)
+ {
+ Common.ReportTypeArgumentParentSymbolUnhandled(context, typeArgumentSyntax, parentSymbol);
+ return false;
+ }
+
+ return typeParamSymbol.GetAttributes()
+ .Any(a => a.AttributeClass?.IsGodotMustBeVariantAttribute() ?? false);
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/PropertyInfo.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/PropertyInfo.cs
new file mode 100644
index 0000000000..b345f5f84d
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/PropertyInfo.cs
@@ -0,0 +1,23 @@
+namespace Godot.SourceGenerators
+{
+ internal struct PropertyInfo
+ {
+ public PropertyInfo(VariantType type, string name, PropertyHint hint,
+ string? hintString, PropertyUsageFlags usage, bool exported)
+ {
+ Type = type;
+ Name = name;
+ Hint = hint;
+ HintString = hintString;
+ Usage = usage;
+ Exported = exported;
+ }
+
+ public VariantType Type { get; }
+ public string Name { get; }
+ public PropertyHint Hint { get; }
+ public string? HintString { get; }
+ public PropertyUsageFlags Usage { get; }
+ public bool Exported { get; }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs
new file mode 100644
index 0000000000..5ac4f4a47e
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs
@@ -0,0 +1,408 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Text;
+
+namespace Godot.SourceGenerators
+{
+ [Generator]
+ public class ScriptMethodsGenerator : ISourceGenerator
+ {
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ if (context.AreGodotSourceGeneratorsDisabled())
+ return;
+
+ INamedTypeSymbol[] godotClasses = context
+ .Compilation.SyntaxTrees
+ .SelectMany(tree =>
+ tree.GetRoot().DescendantNodes()
+ .OfType<ClassDeclarationSyntax>()
+ .SelectGodotScriptClasses(context.Compilation)
+ // Report and skip non-partial classes
+ .Where(x =>
+ {
+ if (x.cds.IsPartial())
+ {
+ if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
+ {
+ Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
+ return false;
+ }
+
+ return true;
+ }
+
+ Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
+ return false;
+ })
+ .Select(x => x.symbol)
+ )
+ .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
+ .ToArray();
+
+ if (godotClasses.Length > 0)
+ {
+ var typeCache = new MarshalUtils.TypeCache(context.Compilation);
+
+ foreach (var godotClass in godotClasses)
+ {
+ VisitGodotScriptClass(context, typeCache, godotClass);
+ }
+ }
+ }
+
+ private class MethodOverloadEqualityComparer : IEqualityComparer<GodotMethodData>
+ {
+ public bool Equals(GodotMethodData x, GodotMethodData y)
+ => x.ParamTypes.Length == y.ParamTypes.Length && x.Method.Name == y.Method.Name;
+
+ public int GetHashCode(GodotMethodData obj)
+ {
+ unchecked
+ {
+ return (obj.ParamTypes.Length.GetHashCode() * 397) ^ obj.Method.Name.GetHashCode();
+ }
+ }
+ }
+
+ private static void VisitGodotScriptClass(
+ GeneratorExecutionContext context,
+ MarshalUtils.TypeCache typeCache,
+ INamedTypeSymbol symbol
+ )
+ {
+ INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
+ string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
+ namespaceSymbol.FullQualifiedName() :
+ string.Empty;
+ bool hasNamespace = classNs.Length != 0;
+
+ bool isInnerClass = symbol.ContainingType != null;
+
+ string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
+ + "_ScriptMethods_Generated";
+
+ var source = new StringBuilder();
+
+ source.Append("using Godot;\n");
+ source.Append("using Godot.NativeInterop;\n");
+ source.Append("\n");
+
+ if (hasNamespace)
+ {
+ source.Append("namespace ");
+ source.Append(classNs);
+ source.Append(" {\n\n");
+ }
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("partial ");
+ source.Append(containingType.GetDeclarationKeyword());
+ source.Append(" ");
+ source.Append(containingType.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ source.Append("partial class ");
+ source.Append(symbol.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ var members = symbol.GetMembers();
+
+ var methodSymbols = members
+ .Where(s => !s.IsStatic && s.Kind == SymbolKind.Method && !s.IsImplicitlyDeclared)
+ .Cast<IMethodSymbol>()
+ .Where(m => m.MethodKind == MethodKind.Ordinary);
+
+ var godotClassMethods = methodSymbols.WhereHasGodotCompatibleSignature(typeCache)
+ .Distinct(new MethodOverloadEqualityComparer())
+ .ToArray();
+
+ source.Append(" private partial class GodotInternal {\n");
+
+ // Generate cached StringNames for methods and properties, for fast lookup
+
+ var distinctMethodNames = godotClassMethods
+ .Select(m => m.Method.Name)
+ .Distinct()
+ .ToArray();
+
+ foreach (string methodName in distinctMethodNames)
+ {
+ source.Append(" public static readonly StringName MethodName_");
+ source.Append(methodName);
+ source.Append(" = \"");
+ source.Append(methodName);
+ source.Append("\";\n");
+ }
+
+ source.Append(" }\n"); // class GodotInternal
+
+ // Generate GetGodotMethodList
+
+ if (godotClassMethods.Length > 0)
+ {
+ source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
+
+ const string listType = "System.Collections.Generic.List<global::Godot.Bridge.MethodInfo>";
+
+ source.Append(" internal new static ")
+ .Append(listType)
+ .Append(" GetGodotMethodList()\n {\n");
+
+ source.Append(" var methods = new ")
+ .Append(listType)
+ .Append("(")
+ .Append(godotClassMethods.Length)
+ .Append(");\n");
+
+ foreach (var method in godotClassMethods)
+ {
+ var methodInfo = DetermineMethodInfo(method);
+ AppendMethodInfo(source, methodInfo);
+ }
+
+ source.Append(" return methods;\n");
+ source.Append(" }\n");
+
+ source.Append("#pragma warning restore CS0109\n");
+ }
+
+ // Generate InvokeGodotClassMethod
+
+ if (godotClassMethods.Length > 0)
+ {
+ source.Append(" protected override bool InvokeGodotClassMethod(in godot_string_name method, ");
+ source.Append("NativeVariantPtrArgs args, int argCount, out godot_variant ret)\n {\n");
+
+ foreach (var method in godotClassMethods)
+ {
+ GenerateMethodInvoker(method, source);
+ }
+
+ source.Append(" return base.InvokeGodotClassMethod(method, args, argCount, out ret);\n");
+
+ source.Append(" }\n");
+ }
+
+ // Generate HasGodotClassMethod
+
+ if (distinctMethodNames.Length > 0)
+ {
+ source.Append(" protected override bool HasGodotClassMethod(in godot_string_name method)\n {\n");
+
+ bool isFirstEntry = true;
+ foreach (string methodName in distinctMethodNames)
+ {
+ GenerateHasMethodEntry(methodName, source, isFirstEntry);
+ isFirstEntry = false;
+ }
+
+ source.Append(" return base.HasGodotClassMethod(method);\n");
+
+ source.Append(" }\n");
+ }
+
+ source.Append("}\n"); // partial class
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("}\n"); // outer class
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ if (hasNamespace)
+ {
+ source.Append("\n}\n");
+ }
+
+ context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
+ }
+
+ private static void AppendMethodInfo(StringBuilder source, MethodInfo methodInfo)
+ {
+ source.Append(" methods.Add(new(name: GodotInternal.MethodName_")
+ .Append(methodInfo.Name)
+ .Append(", returnVal: ");
+
+ AppendPropertyInfo(source, methodInfo.ReturnVal);
+
+ source.Append(", flags: (Godot.MethodFlags)")
+ .Append((int)methodInfo.Flags)
+ .Append(", arguments: ");
+
+ if (methodInfo.Arguments is { Count: > 0 })
+ {
+ source.Append("new() { ");
+
+ foreach (var param in methodInfo.Arguments)
+ {
+ AppendPropertyInfo(source, param);
+
+ // C# allows colon after the last element
+ source.Append(", ");
+ }
+
+ source.Append(" }");
+ }
+ else
+ {
+ source.Append("null");
+ }
+
+ source.Append(", defaultArguments: null));\n");
+ }
+
+ private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
+ {
+ source.Append("new(type: (Godot.Variant.Type)")
+ .Append((int)propertyInfo.Type)
+ .Append(", name: \"")
+ .Append(propertyInfo.Name)
+ .Append("\", hint: (Godot.PropertyHint)")
+ .Append((int)propertyInfo.Hint)
+ .Append(", hintString: \"")
+ .Append(propertyInfo.HintString)
+ .Append("\", usage: (Godot.PropertyUsageFlags)")
+ .Append((int)propertyInfo.Usage)
+ .Append(", exported: ")
+ .Append(propertyInfo.Exported ? "true" : "false")
+ .Append(")");
+ }
+
+ private static MethodInfo DetermineMethodInfo(GodotMethodData method)
+ {
+ PropertyInfo returnVal;
+
+ if (method.RetType != null)
+ {
+ returnVal = DeterminePropertyInfo(method.RetType.Value, name: string.Empty);
+ }
+ else
+ {
+ returnVal = new PropertyInfo(VariantType.Nil, string.Empty, PropertyHint.None,
+ hintString: null, PropertyUsageFlags.Default, exported: false);
+ }
+
+ int paramCount = method.ParamTypes.Length;
+
+ List<PropertyInfo>? arguments;
+
+ if (paramCount > 0)
+ {
+ arguments = new(capacity: paramCount);
+
+ for (int i = 0; i < paramCount; i++)
+ {
+ arguments.Add(DeterminePropertyInfo(method.ParamTypes[i],
+ name: method.Method.Parameters[i].Name));
+ }
+ }
+ else
+ {
+ arguments = null;
+ }
+
+ return new MethodInfo(method.Method.Name, returnVal, MethodFlags.Default, arguments,
+ defaultArguments: null);
+ }
+
+ private static PropertyInfo DeterminePropertyInfo(MarshalType marshalType, string name)
+ {
+ var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
+
+ var propUsage = PropertyUsageFlags.Default;
+
+ if (memberVariantType == VariantType.Nil)
+ propUsage |= PropertyUsageFlags.NilIsVariant;
+
+ return new PropertyInfo(memberVariantType, name,
+ PropertyHint.None, string.Empty, propUsage, exported: false);
+ }
+
+ private static void GenerateHasMethodEntry(
+ string methodName,
+ StringBuilder source,
+ bool isFirstEntry
+ )
+ {
+ source.Append(" ");
+ if (!isFirstEntry)
+ source.Append("else ");
+ source.Append("if (method == GodotInternal.MethodName_");
+ source.Append(methodName);
+ source.Append(") {\n return true;\n }\n");
+ }
+
+ private static void GenerateMethodInvoker(
+ GodotMethodData method,
+ StringBuilder source
+ )
+ {
+ string methodName = method.Method.Name;
+
+ source.Append(" if (method == GodotInternal.MethodName_");
+ source.Append(methodName);
+ source.Append(" && argCount == ");
+ source.Append(method.ParamTypes.Length);
+ source.Append(") {\n");
+
+ if (method.RetType != null)
+ source.Append(" var callRet = ");
+ else
+ source.Append(" ");
+
+ source.Append(methodName);
+ source.Append("(");
+
+ for (int i = 0; i < method.ParamTypes.Length; i++)
+ {
+ if (i != 0)
+ source.Append(", ");
+
+ source.AppendNativeVariantToManagedExpr(string.Concat("args[", i.ToString(), "]"),
+ method.ParamTypeSymbols[i], method.ParamTypes[i]);
+ }
+
+ source.Append(");\n");
+
+ if (method.RetType != null)
+ {
+ source.Append(" ret = ");
+
+ source.AppendManagedToNativeVariantExpr("callRet", method.RetType.Value);
+ source.Append(";\n");
+
+ source.Append(" return true;\n");
+ }
+ else
+ {
+ source.Append(" ret = default;\n");
+ source.Append(" return true;\n");
+ }
+
+ source.Append(" }\n");
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs
index fa65595290..e8a9e28d0c 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs
@@ -14,13 +14,13 @@ namespace Godot.SourceGenerators
{
public void Execute(GeneratorExecutionContext context)
{
- if (context.TryGetGlobalAnalyzerProperty("GodotScriptPathAttributeGenerator", out string? toggle)
- && toggle == "disabled")
- {
+ if (context.AreGodotSourceGeneratorsDisabled())
+ return;
+
+ if (context.IsGodotToolsProject())
return;
- }
- // NOTE: IsNullOrEmpty doesn't work well with nullable checks
+ // NOTE: NotNullWhen diagnostics don't work on projects targeting .NET Standard 2.0
// ReSharper disable once ReplaceWithStringIsNullOrEmpty
if (!context.TryGetGlobalAnalyzerProperty("GodotProjectDir", out string? godotProjectDir)
|| godotProjectDir!.Length == 0)
@@ -28,17 +28,18 @@ namespace Godot.SourceGenerators
throw new InvalidOperationException("Property 'GodotProjectDir' is null or empty.");
}
- var godotClasses = context.Compilation.SyntaxTrees
+ Dictionary<INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>> godotClasses = context
+ .Compilation.SyntaxTrees
.SelectMany(tree =>
tree.GetRoot().DescendantNodes()
.OfType<ClassDeclarationSyntax>()
// Ignore inner classes
- .Where(cds => !(cds.Parent is ClassDeclarationSyntax))
+ .Where(cds => !cds.IsNested())
.SelectGodotScriptClasses(context.Compilation)
// Report and skip non-partial classes
.Where(x =>
{
- if (x.cds.IsPartial() || x.symbol.HasDisableGeneratorsAttribute())
+ if (x.cds.IsPartial())
return true;
Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
return false;
@@ -89,21 +90,14 @@ namespace Godot.SourceGenerators
attributes.Append(@""")]");
}
- string className = symbol.Name;
-
INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
namespaceSymbol.FullQualifiedName() :
string.Empty;
bool hasNamespace = classNs.Length != 0;
- var uniqueName = new StringBuilder();
- if (hasNamespace)
- uniqueName.Append($"{classNs}.");
- uniqueName.Append(className);
- if (symbol.IsGenericType)
- uniqueName.Append($"Of{string.Join(string.Empty, symbol.TypeParameters)}");
- uniqueName.Append("_ScriptPath_Generated");
+ var uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
+ + "_ScriptPath_Generated";
var source = new StringBuilder();
@@ -123,10 +117,8 @@ namespace Godot.SourceGenerators
}
source.Append(attributes);
- source.Append("\n partial class ");
- source.Append(className);
- if (symbol.IsGenericType)
- source.Append($"<{string.Join(", ", symbol.TypeParameters)}>");
+ source.Append("\npartial class ");
+ source.Append(symbol.NameWithTypeParameters());
source.Append("\n{\n}\n");
if (hasNamespace)
@@ -134,7 +126,7 @@ namespace Godot.SourceGenerators
source.Append("\n}\n");
}
- context.AddSource(uniqueName.ToString(), SourceText.From(source.ToString(), Encoding.UTF8));
+ context.AddSource(uniqueHint.ToString(), SourceText.From(source.ToString(), Encoding.UTF8));
}
private static void AddScriptTypesAssemblyAttr(GeneratorExecutionContext context,
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs
new file mode 100644
index 0000000000..7629595b3a
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs
@@ -0,0 +1,657 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Text;
+
+namespace Godot.SourceGenerators
+{
+ [Generator]
+ public class ScriptPropertiesGenerator : ISourceGenerator
+ {
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ if (context.AreGodotSourceGeneratorsDisabled())
+ return;
+
+ INamedTypeSymbol[] godotClasses = context
+ .Compilation.SyntaxTrees
+ .SelectMany(tree =>
+ tree.GetRoot().DescendantNodes()
+ .OfType<ClassDeclarationSyntax>()
+ .SelectGodotScriptClasses(context.Compilation)
+ // Report and skip non-partial classes
+ .Where(x =>
+ {
+ if (x.cds.IsPartial())
+ {
+ if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
+ {
+ Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
+ return false;
+ }
+
+ return true;
+ }
+
+ Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
+ return false;
+ })
+ .Select(x => x.symbol)
+ )
+ .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
+ .ToArray();
+
+ if (godotClasses.Length > 0)
+ {
+ var typeCache = new MarshalUtils.TypeCache(context.Compilation);
+
+ foreach (var godotClass in godotClasses)
+ {
+ VisitGodotScriptClass(context, typeCache, godotClass);
+ }
+ }
+ }
+
+ private static void VisitGodotScriptClass(
+ GeneratorExecutionContext context,
+ MarshalUtils.TypeCache typeCache,
+ INamedTypeSymbol symbol
+ )
+ {
+ INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
+ string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
+ namespaceSymbol.FullQualifiedName() :
+ string.Empty;
+ bool hasNamespace = classNs.Length != 0;
+
+ bool isInnerClass = symbol.ContainingType != null;
+
+ string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
+ + "_ScriptProperties_Generated";
+
+ var source = new StringBuilder();
+
+ source.Append("using Godot;\n");
+ source.Append("using Godot.NativeInterop;\n");
+ source.Append("\n");
+
+ if (hasNamespace)
+ {
+ source.Append("namespace ");
+ source.Append(classNs);
+ source.Append(" {\n\n");
+ }
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("partial ");
+ source.Append(containingType.GetDeclarationKeyword());
+ source.Append(" ");
+ source.Append(containingType.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ source.Append("partial class ");
+ source.Append(symbol.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ var members = symbol.GetMembers();
+
+ var propertySymbols = members
+ .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
+ .Cast<IPropertySymbol>();
+
+ var fieldSymbols = members
+ .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
+ .Cast<IFieldSymbol>();
+
+ var godotClassProperties = propertySymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
+ var godotClassFields = fieldSymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
+
+ source.Append(" private partial class GodotInternal {\n");
+
+ // Generate cached StringNames for methods and properties, for fast lookup
+
+ foreach (var property in godotClassProperties)
+ {
+ string propertyName = property.PropertySymbol.Name;
+ source.Append(" public static readonly StringName PropName_");
+ source.Append(propertyName);
+ source.Append(" = \"");
+ source.Append(propertyName);
+ source.Append("\";\n");
+ }
+
+ foreach (var field in godotClassFields)
+ {
+ string fieldName = field.FieldSymbol.Name;
+ source.Append(" public static readonly StringName PropName_");
+ source.Append(fieldName);
+ source.Append(" = \"");
+ source.Append(fieldName);
+ source.Append("\";\n");
+ }
+
+ source.Append(" }\n"); // class GodotInternal
+
+ if (godotClassProperties.Length > 0 || godotClassFields.Length > 0)
+ {
+ bool isFirstEntry;
+
+ // Generate SetGodotClassPropertyValue
+
+ bool allPropertiesAreReadOnly = godotClassFields.All(fi => fi.FieldSymbol.IsReadOnly) &&
+ godotClassProperties.All(pi => pi.PropertySymbol.IsReadOnly);
+
+ if (!allPropertiesAreReadOnly)
+ {
+ source.Append(" protected override bool SetGodotClassPropertyValue(in godot_string_name name, ");
+ source.Append("in godot_variant value)\n {\n");
+
+ isFirstEntry = true;
+ foreach (var property in godotClassProperties)
+ {
+ if (property.PropertySymbol.IsReadOnly)
+ continue;
+
+ GeneratePropertySetter(property.PropertySymbol.Name,
+ property.PropertySymbol.Type, property.Type, source, isFirstEntry);
+ isFirstEntry = false;
+ }
+
+ foreach (var field in godotClassFields)
+ {
+ if (field.FieldSymbol.IsReadOnly)
+ continue;
+
+ GeneratePropertySetter(field.FieldSymbol.Name,
+ field.FieldSymbol.Type, field.Type, source, isFirstEntry);
+ isFirstEntry = false;
+ }
+
+ source.Append(" return base.SetGodotClassPropertyValue(name, value);\n");
+
+ source.Append(" }\n");
+ }
+
+ // Generate GetGodotClassPropertyValue
+
+ source.Append(" protected override bool GetGodotClassPropertyValue(in godot_string_name name, ");
+ source.Append("out godot_variant value)\n {\n");
+
+ isFirstEntry = true;
+ foreach (var property in godotClassProperties)
+ {
+ GeneratePropertyGetter(property.PropertySymbol.Name,
+ property.Type, source, isFirstEntry);
+ isFirstEntry = false;
+ }
+
+ foreach (var field in godotClassFields)
+ {
+ GeneratePropertyGetter(field.FieldSymbol.Name,
+ field.Type, source, isFirstEntry);
+ isFirstEntry = false;
+ }
+
+ source.Append(" return base.GetGodotClassPropertyValue(name, out value);\n");
+
+ source.Append(" }\n");
+
+ // Generate GetGodotPropertyList
+
+ source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
+
+ string dictionaryType = "System.Collections.Generic.List<global::Godot.Bridge.PropertyInfo>";
+
+ source.Append(" internal new static ")
+ .Append(dictionaryType)
+ .Append(" GetGodotPropertyList()\n {\n");
+
+ source.Append(" var properties = new ")
+ .Append(dictionaryType)
+ .Append("();\n");
+
+ // To retain the definition order (and display categories correctly), we want to
+ // iterate over fields and properties at the same time, sorted by line number.
+ var godotClassPropertiesAndFields = Enumerable.Empty<GodotPropertyOrFieldData>()
+ .Concat(godotClassProperties.Select(propertyData => new GodotPropertyOrFieldData(propertyData)))
+ .Concat(godotClassFields.Select(fieldData => new GodotPropertyOrFieldData(fieldData)))
+ .OrderBy(data => data.Symbol.Locations[0].Path())
+ .ThenBy(data => data.Symbol.Locations[0].StartLine());
+
+ foreach (var member in godotClassPropertiesAndFields)
+ {
+ foreach (var groupingInfo in DetermineGroupingPropertyInfo(member.Symbol))
+ AppendGroupingPropertyInfo(source, groupingInfo);
+
+ var propertyInfo = DeterminePropertyInfo(context, typeCache,
+ member.Symbol, member.Type);
+
+ if (propertyInfo == null)
+ continue;
+
+ AppendPropertyInfo(source, propertyInfo.Value);
+ }
+
+ source.Append(" return properties;\n");
+ source.Append(" }\n");
+
+ source.Append("#pragma warning restore CS0109\n");
+ }
+
+ source.Append("}\n"); // partial class
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("}\n"); // outer class
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ if (hasNamespace)
+ {
+ source.Append("\n}\n");
+ }
+
+ context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
+ }
+
+ private static void GeneratePropertySetter(
+ string propertyMemberName,
+ ITypeSymbol propertyTypeSymbol,
+ MarshalType propertyMarshalType,
+ StringBuilder source,
+ bool isFirstEntry
+ )
+ {
+ source.Append(" ");
+
+ if (!isFirstEntry)
+ source.Append("else ");
+
+ source.Append("if (name == GodotInternal.PropName_")
+ .Append(propertyMemberName)
+ .Append(") {\n")
+ .Append(" ")
+ .Append(propertyMemberName)
+ .Append(" = ")
+ .AppendNativeVariantToManagedExpr("value", propertyTypeSymbol, propertyMarshalType)
+ .Append(";\n")
+ .Append(" return true;\n")
+ .Append(" }\n");
+ }
+
+ private static void GeneratePropertyGetter(
+ string propertyMemberName,
+ MarshalType propertyMarshalType,
+ StringBuilder source,
+ bool isFirstEntry
+ )
+ {
+ source.Append(" ");
+
+ if (!isFirstEntry)
+ source.Append("else ");
+
+ source.Append("if (name == GodotInternal.PropName_")
+ .Append(propertyMemberName)
+ .Append(") {\n")
+ .Append(" value = ")
+ .AppendManagedToNativeVariantExpr(propertyMemberName, propertyMarshalType)
+ .Append(";\n")
+ .Append(" return true;\n")
+ .Append(" }\n");
+ }
+
+ private static void AppendGroupingPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
+ {
+ source.Append(" properties.Add(new(type: (Godot.Variant.Type)")
+ .Append((int)VariantType.Nil)
+ .Append(", name: \"")
+ .Append(propertyInfo.Name)
+ .Append("\", hint: (Godot.PropertyHint)")
+ .Append((int)PropertyHint.None)
+ .Append(", hintString: \"")
+ .Append(propertyInfo.HintString)
+ .Append("\", usage: (Godot.PropertyUsageFlags)")
+ .Append((int)propertyInfo.Usage)
+ .Append(", exported: true));\n");
+ }
+
+ private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
+ {
+ source.Append(" properties.Add(new(type: (Godot.Variant.Type)")
+ .Append((int)propertyInfo.Type)
+ .Append(", name: GodotInternal.PropName_")
+ .Append(propertyInfo.Name)
+ .Append(", hint: (Godot.PropertyHint)")
+ .Append((int)propertyInfo.Hint)
+ .Append(", hintString: \"")
+ .Append(propertyInfo.HintString)
+ .Append("\", usage: (Godot.PropertyUsageFlags)")
+ .Append((int)propertyInfo.Usage)
+ .Append(", exported: ")
+ .Append(propertyInfo.Exported ? "true" : "false")
+ .Append("));\n");
+ }
+
+ private static IEnumerable<PropertyInfo> DetermineGroupingPropertyInfo(ISymbol memberSymbol)
+ {
+ foreach (var attr in memberSymbol.GetAttributes())
+ {
+ PropertyUsageFlags? propertyUsage = attr.AttributeClass?.ToString() switch
+ {
+ GodotClasses.ExportCategoryAttr => PropertyUsageFlags.Category,
+ GodotClasses.ExportGroupAttr => PropertyUsageFlags.Group,
+ GodotClasses.ExportSubgroupAttr => PropertyUsageFlags.Subgroup,
+ _ => null
+ };
+
+ if (propertyUsage is null)
+ continue;
+
+ if (attr.ConstructorArguments.Length > 0 && attr.ConstructorArguments[0].Value is string name)
+ {
+ string? hintString = null;
+ if (propertyUsage != PropertyUsageFlags.Category && attr.ConstructorArguments.Length > 1)
+ hintString = attr.ConstructorArguments[1].Value?.ToString();
+
+ yield return new PropertyInfo(VariantType.Nil, name, PropertyHint.None, hintString, propertyUsage.Value, true);
+ }
+ }
+ }
+
+ private static PropertyInfo? DeterminePropertyInfo(
+ GeneratorExecutionContext context,
+ MarshalUtils.TypeCache typeCache,
+ ISymbol memberSymbol,
+ MarshalType marshalType
+ )
+ {
+ var exportAttr = memberSymbol.GetAttributes()
+ .FirstOrDefault(a => a.AttributeClass?.IsGodotExportAttribute() ?? false);
+
+ var propertySymbol = memberSymbol as IPropertySymbol;
+ var fieldSymbol = memberSymbol as IFieldSymbol;
+
+ if (exportAttr != null && propertySymbol != null)
+ {
+ if (propertySymbol.GetMethod == null)
+ {
+ // This should never happen, as we filtered WriteOnly properties, but just in case.
+ Common.ReportExportedMemberIsWriteOnly(context, propertySymbol);
+ return null;
+ }
+
+ if (propertySymbol.SetMethod == null)
+ {
+ // This should never happen, as we filtered ReadOnly properties, but just in case.
+ Common.ReportExportedMemberIsReadOnly(context, propertySymbol);
+ return null;
+ }
+ }
+
+ var memberType = propertySymbol?.Type ?? fieldSymbol!.Type;
+
+ var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
+ string memberName = memberSymbol.Name;
+
+ if (exportAttr == null)
+ {
+ return new PropertyInfo(memberVariantType, memberName, PropertyHint.None,
+ hintString: null, PropertyUsageFlags.ScriptVariable, exported: false);
+ }
+
+ if (!TryGetMemberExportHint(typeCache, memberType, exportAttr, memberVariantType,
+ isTypeArgument: false, out var hint, out var hintString))
+ {
+ var constructorArguments = exportAttr.ConstructorArguments;
+
+ if (constructorArguments.Length > 0)
+ {
+ var hintValue = exportAttr.ConstructorArguments[0].Value;
+
+ hint = hintValue switch
+ {
+ null => PropertyHint.None,
+ int intValue => (PropertyHint)intValue,
+ _ => (PropertyHint)(long)hintValue
+ };
+
+ hintString = constructorArguments.Length > 1 ?
+ exportAttr.ConstructorArguments[1].Value?.ToString() :
+ null;
+ }
+ else
+ {
+ hint = PropertyHint.None;
+ }
+ }
+
+ var propUsage = PropertyUsageFlags.Default | PropertyUsageFlags.ScriptVariable;
+
+ if (memberVariantType == VariantType.Nil)
+ propUsage |= PropertyUsageFlags.NilIsVariant;
+
+ return new PropertyInfo(memberVariantType, memberName,
+ hint, hintString, propUsage, exported: true);
+ }
+
+ private static bool TryGetMemberExportHint(
+ MarshalUtils.TypeCache typeCache,
+ ITypeSymbol type, AttributeData exportAttr,
+ VariantType variantType, bool isTypeArgument,
+ out PropertyHint hint, out string? hintString
+ )
+ {
+ hint = PropertyHint.None;
+ hintString = null;
+
+ if (variantType == VariantType.Nil)
+ return true; // Variant, no export hint
+
+ if (variantType == VariantType.Int &&
+ type.IsValueType && type.TypeKind == TypeKind.Enum)
+ {
+ bool hasFlagsAttr = type.GetAttributes()
+ .Any(a => a.AttributeClass?.IsSystemFlagsAttribute() ?? false);
+
+ hint = hasFlagsAttr ? PropertyHint.Flags : PropertyHint.Enum;
+
+ var members = type.GetMembers();
+
+ var enumFields = members
+ .Where(s => s.Kind == SymbolKind.Field && s.IsStatic &&
+ s.DeclaredAccessibility == Accessibility.Public &&
+ !s.IsImplicitlyDeclared)
+ .Cast<IFieldSymbol>().ToArray();
+
+ var hintStringBuilder = new StringBuilder();
+ var nameOnlyHintStringBuilder = new StringBuilder();
+
+ // True: enum Foo { Bar, Baz, Qux }
+ // True: enum Foo { Bar = 0, Baz = 1, Qux = 2 }
+ // False: enum Foo { Bar = 0, Baz = 7, Qux = 5 }
+ bool usesDefaultValues = true;
+
+ for (int i = 0; i < enumFields.Length; i++)
+ {
+ var enumField = enumFields[i];
+
+ if (i > 0)
+ {
+ hintStringBuilder.Append(",");
+ nameOnlyHintStringBuilder.Append(",");
+ }
+
+ string enumFieldName = enumField.Name;
+ hintStringBuilder.Append(enumFieldName);
+ nameOnlyHintStringBuilder.Append(enumFieldName);
+
+ long val = enumField.ConstantValue switch
+ {
+ sbyte v => v,
+ short v => v,
+ int v => v,
+ long v => v,
+ byte v => v,
+ ushort v => v,
+ uint v => v,
+ ulong v => (long)v,
+ _ => 0
+ };
+
+ uint expectedVal = (uint)(hint == PropertyHint.Flags ? 1 << i : i);
+ if (val != expectedVal)
+ usesDefaultValues = false;
+
+ hintStringBuilder.Append(":");
+ hintStringBuilder.Append(val);
+ }
+
+ hintString = !usesDefaultValues ?
+ hintStringBuilder.ToString() :
+ // If we use the format NAME:VAL, that's what the editor displays.
+ // That's annoying if the user is not using custom values for the enum constants.
+ // This may not be needed in the future if the editor is changed to not display values.
+ nameOnlyHintStringBuilder.ToString();
+
+ return true;
+ }
+
+ if (variantType == VariantType.Object && type is INamedTypeSymbol memberNamedType)
+ {
+ if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Resource"))
+ {
+ string nativeTypeName = memberNamedType.GetGodotScriptNativeClassName()!;
+
+ hint = PropertyHint.ResourceType;
+ hintString = nativeTypeName;
+
+ return true;
+ }
+
+ if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Node"))
+ {
+ string nativeTypeName = memberNamedType.GetGodotScriptNativeClassName()!;
+
+ hint = PropertyHint.NodeType;
+ hintString = nativeTypeName;
+
+ return true;
+ }
+ }
+
+ static bool GetStringArrayEnumHint(VariantType elementVariantType,
+ AttributeData exportAttr, out string? hintString)
+ {
+ var constructorArguments = exportAttr.ConstructorArguments;
+
+ if (constructorArguments.Length > 0)
+ {
+ var presetHintValue = exportAttr.ConstructorArguments[0].Value;
+
+ PropertyHint presetHint = presetHintValue switch
+ {
+ null => PropertyHint.None,
+ int intValue => (PropertyHint)intValue,
+ _ => (PropertyHint)(long)presetHintValue
+ };
+
+ if (presetHint == PropertyHint.Enum)
+ {
+ string? presetHintString = constructorArguments.Length > 1 ?
+ exportAttr.ConstructorArguments[1].Value?.ToString() :
+ null;
+
+ hintString = (int)elementVariantType + "/" + (int)PropertyHint.Enum + ":";
+
+ if (presetHintString != null)
+ hintString += presetHintString;
+
+ return true;
+ }
+ }
+
+ hintString = null;
+ return false;
+ }
+
+ if (!isTypeArgument && variantType == VariantType.Array)
+ {
+ var elementType = MarshalUtils.GetArrayElementType(type);
+
+ if (elementType == null)
+ return false; // Non-generic Array, so there's no hint to add
+
+ var elementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementType, typeCache)!.Value;
+ var elementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(elementMarshalType)!.Value;
+
+ bool isPresetHint = false;
+
+ if (elementVariantType == VariantType.String)
+ isPresetHint = GetStringArrayEnumHint(elementVariantType, exportAttr, out hintString);
+
+ if (!isPresetHint)
+ {
+ bool hintRes = TryGetMemberExportHint(typeCache, elementType,
+ exportAttr, elementVariantType, isTypeArgument: true,
+ out var elementHint, out var elementHintString);
+
+ // Format: type/hint:hint_string
+ if (hintRes)
+ {
+ hintString = (int)elementVariantType + "/" + (int)elementHint + ":";
+
+ if (elementHintString != null)
+ hintString += elementHintString;
+ }
+ else
+ {
+ hintString = (int)elementVariantType + "/" + (int)PropertyHint.None + ":";
+ }
+ }
+
+ hint = PropertyHint.TypeString;
+
+ return hintString != null;
+ }
+
+ if (!isTypeArgument && variantType == VariantType.PackedStringArray)
+ {
+ if (GetStringArrayEnumHint(VariantType.String, exportAttr, out hintString))
+ {
+ hint = PropertyHint.TypeString;
+ return true;
+ }
+ }
+
+ if (!isTypeArgument && variantType == VariantType.Dictionary)
+ {
+ // TODO: Dictionaries are not supported in the inspector
+ return false;
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs
new file mode 100644
index 0000000000..85fadaa52e
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs
@@ -0,0 +1,293 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Text;
+
+namespace Godot.SourceGenerators
+{
+ [Generator]
+ public class ScriptPropertyDefValGenerator : ISourceGenerator
+ {
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ if (context.AreGodotSourceGeneratorsDisabled())
+ return;
+
+ INamedTypeSymbol[] godotClasses = context
+ .Compilation.SyntaxTrees
+ .SelectMany(tree =>
+ tree.GetRoot().DescendantNodes()
+ .OfType<ClassDeclarationSyntax>()
+ .SelectGodotScriptClasses(context.Compilation)
+ // Report and skip non-partial classes
+ .Where(x =>
+ {
+ if (x.cds.IsPartial())
+ {
+ if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
+ {
+ Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
+ return false;
+ }
+
+ return true;
+ }
+
+ Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
+ return false;
+ })
+ .Select(x => x.symbol)
+ )
+ .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
+ .ToArray();
+
+ if (godotClasses.Length > 0)
+ {
+ var typeCache = new MarshalUtils.TypeCache(context.Compilation);
+
+ foreach (var godotClass in godotClasses)
+ {
+ VisitGodotScriptClass(context, typeCache, godotClass);
+ }
+ }
+ }
+
+ private static void VisitGodotScriptClass(
+ GeneratorExecutionContext context,
+ MarshalUtils.TypeCache typeCache,
+ INamedTypeSymbol symbol
+ )
+ {
+ INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
+ string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
+ namespaceSymbol.FullQualifiedName() :
+ string.Empty;
+ bool hasNamespace = classNs.Length != 0;
+
+ bool isInnerClass = symbol.ContainingType != null;
+
+ string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
+ + "_ScriptPropertyDefVal_Generated";
+
+ var source = new StringBuilder();
+
+ source.Append("using Godot;\n");
+ source.Append("using Godot.NativeInterop;\n");
+ source.Append("\n");
+
+ if (hasNamespace)
+ {
+ source.Append("namespace ");
+ source.Append(classNs);
+ source.Append(" {\n\n");
+ }
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("partial ");
+ source.Append(containingType.GetDeclarationKeyword());
+ source.Append(" ");
+ source.Append(containingType.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ source.Append("partial class ");
+ source.Append(symbol.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ var exportedMembers = new List<ExportedPropertyMetadata>();
+
+ var members = symbol.GetMembers();
+
+ var exportedProperties = members
+ .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
+ .Cast<IPropertySymbol>()
+ .Where(s => s.GetAttributes()
+ .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
+ .ToArray();
+
+ var exportedFields = members
+ .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
+ .Cast<IFieldSymbol>()
+ .Where(s => s.GetAttributes()
+ .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
+ .ToArray();
+
+ foreach (var property in exportedProperties)
+ {
+ if (property.IsStatic)
+ {
+ Common.ReportExportedMemberIsStatic(context, property);
+ continue;
+ }
+
+ // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
+ // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
+ if (property.IsWriteOnly)
+ {
+ Common.ReportExportedMemberIsWriteOnly(context, property);
+ continue;
+ }
+
+ if (property.IsReadOnly)
+ {
+ Common.ReportExportedMemberIsReadOnly(context, property);
+ continue;
+ }
+
+
+ var propertyType = property.Type;
+ var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(propertyType, typeCache);
+
+ if (marshalType == null)
+ {
+ Common.ReportExportedMemberTypeNotSupported(context, property);
+ continue;
+ }
+
+ // TODO: Detect default value from simple property getters (currently we only detect from initializers)
+
+ EqualsValueClauseSyntax? initializer = property.DeclaringSyntaxReferences
+ .Select(r => r.GetSyntax() as PropertyDeclarationSyntax)
+ .Select(s => s?.Initializer ?? null)
+ .FirstOrDefault();
+
+ string? value = initializer?.Value.ToString();
+
+ exportedMembers.Add(new ExportedPropertyMetadata(
+ property.Name, marshalType.Value, propertyType, value));
+ }
+
+ foreach (var field in exportedFields)
+ {
+ if (field.IsStatic)
+ {
+ Common.ReportExportedMemberIsStatic(context, field);
+ continue;
+ }
+
+ // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
+ // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
+ if (field.IsReadOnly)
+ {
+ Common.ReportExportedMemberIsReadOnly(context, field);
+ continue;
+ }
+
+ var fieldType = field.Type;
+ var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
+
+ if (marshalType == null)
+ {
+ Common.ReportExportedMemberTypeNotSupported(context, field);
+ continue;
+ }
+
+ EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
+ .Select(r => r.GetSyntax())
+ .OfType<VariableDeclaratorSyntax>()
+ .Select(s => s.Initializer)
+ .FirstOrDefault(i => i != null);
+
+ string? value = initializer?.Value.ToString();
+
+ exportedMembers.Add(new ExportedPropertyMetadata(
+ field.Name, marshalType.Value, fieldType, value));
+ }
+
+ // Generate GetGodotExportedProperties
+
+ if (exportedMembers.Count > 0)
+ {
+ source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
+
+ string dictionaryType = "System.Collections.Generic.Dictionary<StringName, object>";
+
+ source.Append("#if TOOLS\n");
+ source.Append(" internal new static ");
+ source.Append(dictionaryType);
+ source.Append(" GetGodotPropertyDefaultValues()\n {\n");
+
+ source.Append(" var values = new ");
+ source.Append(dictionaryType);
+ source.Append("(");
+ source.Append(exportedMembers.Count);
+ source.Append(");\n");
+
+ foreach (var exportedMember in exportedMembers)
+ {
+ string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
+
+ source.Append(" ");
+ source.Append(exportedMember.TypeSymbol.FullQualifiedName());
+ source.Append(" ");
+ source.Append(defaultValueLocalName);
+ source.Append(" = ");
+ source.Append(exportedMember.Value ?? "default");
+ source.Append(";\n");
+ source.Append(" values.Add(GodotInternal.PropName_");
+ source.Append(exportedMember.Name);
+ source.Append(", ");
+ source.Append(defaultValueLocalName);
+ source.Append(");\n");
+ }
+
+ source.Append(" return values;\n");
+ source.Append(" }\n");
+ source.Append("#endif\n");
+
+ source.Append("#pragma warning restore CS0109\n");
+ }
+
+ source.Append("}\n"); // partial class
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("}\n"); // outer class
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ if (hasNamespace)
+ {
+ source.Append("\n}\n");
+ }
+
+ context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
+ }
+
+ private struct ExportedPropertyMetadata
+ {
+ public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
+ {
+ Name = name;
+ Type = type;
+ TypeSymbol = typeSymbol;
+ Value = value;
+ }
+
+ public string Name { get; }
+ public MarshalType Type { get; }
+ public ITypeSymbol TypeSymbol { get; }
+ public string? Value { get; }
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptRegistrarGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptRegistrarGenerator.cs
new file mode 100644
index 0000000000..ec04a319e2
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptRegistrarGenerator.cs
@@ -0,0 +1,19 @@
+using Microsoft.CodeAnalysis;
+
+namespace Godot.SourceGenerators
+{
+ // Placeholder. Once we switch to native extensions this will act as the registrar for all
+ // user Godot classes in the assembly. Think of it as something similar to `register_types`.
+ public class ScriptRegistrarGenerator : ISourceGenerator
+ {
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ throw new System.NotImplementedException();
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ throw new System.NotImplementedException();
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs
new file mode 100644
index 0000000000..5a84122c4c
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs
@@ -0,0 +1,283 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Text;
+
+namespace Godot.SourceGenerators
+{
+ [Generator]
+ public class ScriptSerializationGenerator : ISourceGenerator
+ {
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ if (context.AreGodotSourceGeneratorsDisabled())
+ return;
+
+ INamedTypeSymbol[] godotClasses = context
+ .Compilation.SyntaxTrees
+ .SelectMany(tree =>
+ tree.GetRoot().DescendantNodes()
+ .OfType<ClassDeclarationSyntax>()
+ .SelectGodotScriptClasses(context.Compilation)
+ // Report and skip non-partial classes
+ .Where(x =>
+ {
+ if (x.cds.IsPartial())
+ {
+ if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
+ {
+ Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
+ return false;
+ }
+
+ return true;
+ }
+
+ Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
+ return false;
+ })
+ .Select(x => x.symbol)
+ )
+ .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
+ .ToArray();
+
+ if (godotClasses.Length > 0)
+ {
+ var typeCache = new MarshalUtils.TypeCache(context.Compilation);
+
+ foreach (var godotClass in godotClasses)
+ {
+ VisitGodotScriptClass(context, typeCache, godotClass);
+ }
+ }
+ }
+
+ private static void VisitGodotScriptClass(
+ GeneratorExecutionContext context,
+ MarshalUtils.TypeCache typeCache,
+ INamedTypeSymbol symbol
+ )
+ {
+ INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
+ string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
+ namespaceSymbol.FullQualifiedName() :
+ string.Empty;
+ bool hasNamespace = classNs.Length != 0;
+
+ bool isInnerClass = symbol.ContainingType != null;
+
+ string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
+ + "_ScriptSerialization_Generated";
+
+ var source = new StringBuilder();
+
+ source.Append("using Godot;\n");
+ source.Append("using Godot.NativeInterop;\n");
+ source.Append("\n");
+
+ if (hasNamespace)
+ {
+ source.Append("namespace ");
+ source.Append(classNs);
+ source.Append(" {\n\n");
+ }
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("partial ");
+ source.Append(containingType.GetDeclarationKeyword());
+ source.Append(" ");
+ source.Append(containingType.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ source.Append("partial class ");
+ source.Append(symbol.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ var members = symbol.GetMembers();
+
+ var propertySymbols = members
+ .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
+ .Cast<IPropertySymbol>();
+
+ var fieldSymbols = members
+ .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
+ .Cast<IFieldSymbol>();
+
+ var godotClassProperties = propertySymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
+ var godotClassFields = fieldSymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
+
+ var signalDelegateSymbols = members
+ .Where(s => s.Kind == SymbolKind.NamedType)
+ .Cast<INamedTypeSymbol>()
+ .Where(namedTypeSymbol => namedTypeSymbol.TypeKind == TypeKind.Delegate)
+ .Where(s => s.GetAttributes()
+ .Any(a => a.AttributeClass?.IsGodotSignalAttribute() ?? false));
+
+ List<GodotSignalDelegateData> godotSignalDelegates = new();
+
+ foreach (var signalDelegateSymbol in signalDelegateSymbols)
+ {
+ if (!signalDelegateSymbol.Name.EndsWith(ScriptSignalsGenerator.SignalDelegateSuffix))
+ continue;
+
+ string signalName = signalDelegateSymbol.Name;
+ signalName = signalName.Substring(0,
+ signalName.Length - ScriptSignalsGenerator.SignalDelegateSuffix.Length);
+
+ var invokeMethodData = signalDelegateSymbol
+ .DelegateInvokeMethod?.HasGodotCompatibleSignature(typeCache);
+
+ if (invokeMethodData == null)
+ continue;
+
+ godotSignalDelegates.Add(new(signalName, signalDelegateSymbol, invokeMethodData.Value));
+ }
+
+ source.Append(
+ " protected override void SaveGodotObjectData(global::Godot.Bridge.GodotSerializationInfo info)\n {\n");
+ source.Append(" base.SaveGodotObjectData(info);\n");
+
+ // Save properties
+
+ foreach (var property in godotClassProperties)
+ {
+ string propertyName = property.PropertySymbol.Name;
+
+ source.Append(" info.AddProperty(GodotInternal.PropName_")
+ .Append(propertyName)
+ .Append(", ")
+ .AppendManagedToVariantExpr(string.Concat("this.", propertyName), property.Type)
+ .Append(");\n");
+ }
+
+ // Save fields
+
+ foreach (var field in godotClassFields)
+ {
+ string fieldName = field.FieldSymbol.Name;
+
+ source.Append(" info.AddProperty(GodotInternal.PropName_")
+ .Append(fieldName)
+ .Append(", ")
+ .AppendManagedToVariantExpr(string.Concat("this.", fieldName), field.Type)
+ .Append(");\n");
+ }
+
+ // Save signal events
+
+ foreach (var signalDelegate in godotSignalDelegates)
+ {
+ string signalName = signalDelegate.Name;
+
+ source.Append(" info.AddSignalEventDelegate(GodotInternal.SignalName_")
+ .Append(signalName)
+ .Append(", this.backing_")
+ .Append(signalName)
+ .Append(");\n");
+ }
+
+ source.Append(" }\n");
+
+ source.Append(
+ " protected override void RestoreGodotObjectData(global::Godot.Bridge.GodotSerializationInfo info)\n {\n");
+ source.Append(" base.RestoreGodotObjectData(info);\n");
+
+ // Restore properties
+
+ foreach (var property in godotClassProperties)
+ {
+ string propertyName = property.PropertySymbol.Name;
+
+ source.Append(" if (info.TryGetProperty(GodotInternal.PropName_")
+ .Append(propertyName)
+ .Append(", out var _value_")
+ .Append(propertyName)
+ .Append("))\n")
+ .Append(" this.")
+ .Append(propertyName)
+ .Append(" = ")
+ .AppendVariantToManagedExpr(string.Concat("_value_", propertyName),
+ property.PropertySymbol.Type, property.Type)
+ .Append(";\n");
+ }
+
+ // Restore fields
+
+ foreach (var field in godotClassFields)
+ {
+ string fieldName = field.FieldSymbol.Name;
+
+ source.Append(" if (info.TryGetProperty(GodotInternal.PropName_")
+ .Append(fieldName)
+ .Append(", out var _value_")
+ .Append(fieldName)
+ .Append("))\n")
+ .Append(" this.")
+ .Append(fieldName)
+ .Append(" = ")
+ .AppendVariantToManagedExpr(string.Concat("_value_", fieldName),
+ field.FieldSymbol.Type, field.Type)
+ .Append(";\n");
+ }
+
+ // Restore signal events
+
+ foreach (var signalDelegate in godotSignalDelegates)
+ {
+ string signalName = signalDelegate.Name;
+ string signalDelegateQualifiedName = signalDelegate.DelegateSymbol.FullQualifiedName();
+
+ source.Append(" if (info.TryGetSignalEventDelegate<")
+ .Append(signalDelegateQualifiedName)
+ .Append(">(GodotInternal.SignalName_")
+ .Append(signalName)
+ .Append(", out var _value_")
+ .Append(signalName)
+ .Append("))\n")
+ .Append(" this.backing_")
+ .Append(signalName)
+ .Append(" = _value_")
+ .Append(signalName)
+ .Append(";\n");
+ }
+
+ source.Append(" }\n");
+
+ source.Append("}\n"); // partial class
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("}\n"); // outer class
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ if (hasNamespace)
+ {
+ source.Append("\n}\n");
+ }
+
+ context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
+ }
+ }
+}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs
new file mode 100644
index 0000000000..161834a4be
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs
@@ -0,0 +1,432 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Text;
+
+// TODO:
+// Determine a proper way to emit the signal.
+// 'Emit(nameof(TheEvent))' creates a StringName everytime and has the overhead of string marshaling.
+// I haven't decided on the best option yet. Some possibilities:
+// - Expose the generated StringName fields to the user, for use with 'Emit(...)'.
+// - Generate a 'EmitSignalName' method for each event signal.
+
+namespace Godot.SourceGenerators
+{
+ [Generator]
+ public class ScriptSignalsGenerator : ISourceGenerator
+ {
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ if (context.AreGodotSourceGeneratorsDisabled())
+ return;
+
+ INamedTypeSymbol[] godotClasses = context
+ .Compilation.SyntaxTrees
+ .SelectMany(tree =>
+ tree.GetRoot().DescendantNodes()
+ .OfType<ClassDeclarationSyntax>()
+ .SelectGodotScriptClasses(context.Compilation)
+ // Report and skip non-partial classes
+ .Where(x =>
+ {
+ if (x.cds.IsPartial())
+ {
+ if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
+ {
+ Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
+ return false;
+ }
+
+ return true;
+ }
+
+ Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
+ return false;
+ })
+ .Select(x => x.symbol)
+ )
+ .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
+ .ToArray();
+
+ if (godotClasses.Length > 0)
+ {
+ var typeCache = new MarshalUtils.TypeCache(context.Compilation);
+
+ foreach (var godotClass in godotClasses)
+ {
+ VisitGodotScriptClass(context, typeCache, godotClass);
+ }
+ }
+ }
+
+ internal static string SignalDelegateSuffix = "EventHandler";
+
+ private static void VisitGodotScriptClass(
+ GeneratorExecutionContext context,
+ MarshalUtils.TypeCache typeCache,
+ INamedTypeSymbol symbol
+ )
+ {
+ INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
+ string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
+ namespaceSymbol.FullQualifiedName() :
+ string.Empty;
+ bool hasNamespace = classNs.Length != 0;
+
+ bool isInnerClass = symbol.ContainingType != null;
+
+ string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
+ + "_ScriptSignals_Generated";
+
+ var source = new StringBuilder();
+
+ source.Append("using Godot;\n");
+ source.Append("using Godot.NativeInterop;\n");
+ source.Append("\n");
+
+ if (hasNamespace)
+ {
+ source.Append("namespace ");
+ source.Append(classNs);
+ source.Append(" {\n\n");
+ }
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("partial ");
+ source.Append(containingType.GetDeclarationKeyword());
+ source.Append(" ");
+ source.Append(containingType.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ source.Append("partial class ");
+ source.Append(symbol.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ // TODO:
+ // The delegate name already needs to end with 'Signal' to avoid collision with the event name.
+ // Requiring SignalAttribute is redundant. Should we remove it to make declaration shorter?
+
+ var members = symbol.GetMembers();
+
+ var signalDelegateSymbols = members
+ .Where(s => s.Kind == SymbolKind.NamedType)
+ .Cast<INamedTypeSymbol>()
+ .Where(namedTypeSymbol => namedTypeSymbol.TypeKind == TypeKind.Delegate)
+ .Where(s => s.GetAttributes()
+ .Any(a => a.AttributeClass?.IsGodotSignalAttribute() ?? false));
+
+ List<GodotSignalDelegateData> godotSignalDelegates = new();
+
+ foreach (var signalDelegateSymbol in signalDelegateSymbols)
+ {
+ if (!signalDelegateSymbol.Name.EndsWith(SignalDelegateSuffix))
+ {
+ Common.ReportSignalDelegateMissingSuffix(context, signalDelegateSymbol);
+ continue;
+ }
+
+ string signalName = signalDelegateSymbol.Name;
+ signalName = signalName.Substring(0, signalName.Length - SignalDelegateSuffix.Length);
+
+ var invokeMethodData = signalDelegateSymbol
+ .DelegateInvokeMethod?.HasGodotCompatibleSignature(typeCache);
+
+ if (invokeMethodData == null)
+ {
+ if (signalDelegateSymbol.DelegateInvokeMethod is IMethodSymbol methodSymbol)
+ {
+ foreach (var parameter in methodSymbol.Parameters)
+ {
+ if (parameter.RefKind != RefKind.None)
+ {
+ Common.ReportSignalParameterTypeNotSupported(context, parameter);
+ continue;
+ }
+
+ var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(parameter.Type, typeCache);
+
+ if (marshalType == null)
+ {
+ Common.ReportSignalParameterTypeNotSupported(context, parameter);
+ }
+ }
+
+ if (!methodSymbol.ReturnsVoid)
+ {
+ Common.ReportSignalDelegateSignatureMustReturnVoid(context, signalDelegateSymbol);
+ }
+ }
+ continue;
+ }
+
+ godotSignalDelegates.Add(new(signalName, signalDelegateSymbol, invokeMethodData.Value));
+ }
+
+ source.Append(" private partial class GodotInternal {\n");
+
+ // Generate cached StringNames for methods and properties, for fast lookup
+
+ foreach (var signalDelegate in godotSignalDelegates)
+ {
+ string signalName = signalDelegate.Name;
+ source.Append(" public static readonly StringName SignalName_");
+ source.Append(signalName);
+ source.Append(" = \"");
+ source.Append(signalName);
+ source.Append("\";\n");
+ }
+
+ source.Append(" }\n"); // class GodotInternal
+
+ // Generate GetGodotSignalList
+
+ if (godotSignalDelegates.Count > 0)
+ {
+ source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
+
+ const string listType = "System.Collections.Generic.List<global::Godot.Bridge.MethodInfo>";
+
+ source.Append(" internal new static ")
+ .Append(listType)
+ .Append(" GetGodotSignalList()\n {\n");
+
+ source.Append(" var signals = new ")
+ .Append(listType)
+ .Append("(")
+ .Append(godotSignalDelegates.Count)
+ .Append(");\n");
+
+ foreach (var signalDelegateData in godotSignalDelegates)
+ {
+ var methodInfo = DetermineMethodInfo(signalDelegateData);
+ AppendMethodInfo(source, methodInfo);
+ }
+
+ source.Append(" return signals;\n");
+ source.Append(" }\n");
+
+ source.Append("#pragma warning restore CS0109\n");
+ }
+
+ // Generate signal event
+
+ foreach (var signalDelegate in godotSignalDelegates)
+ {
+ string signalName = signalDelegate.Name;
+
+ // TODO: Hide backing event from code-completion and debugger
+ // The reason we have a backing field is to hide the invoke method from the event,
+ // as it doesn't emit the signal, only the event delegates. This can confuse users.
+ // Maybe we should directly connect the delegates, as we do with native signals?
+ source.Append(" private ")
+ .Append(signalDelegate.DelegateSymbol.FullQualifiedName())
+ .Append(" backing_")
+ .Append(signalName)
+ .Append(";\n");
+
+ source.Append(" public event ")
+ .Append(signalDelegate.DelegateSymbol.FullQualifiedName())
+ .Append(" ")
+ .Append(signalName)
+ .Append(" {\n")
+ .Append(" add => backing_")
+ .Append(signalName)
+ .Append(" += value;\n")
+ .Append(" remove => backing_")
+ .Append(signalName)
+ .Append(" -= value;\n")
+ .Append("}\n");
+ }
+
+ // Generate RaiseGodotClassSignalCallbacks
+
+ if (godotSignalDelegates.Count > 0)
+ {
+ source.Append(
+ " protected override void RaiseGodotClassSignalCallbacks(in godot_string_name signal, ");
+ source.Append("NativeVariantPtrArgs args, int argCount)\n {\n");
+
+ foreach (var signal in godotSignalDelegates)
+ {
+ GenerateSignalEventInvoker(signal, source);
+ }
+
+ source.Append(" base.RaiseGodotClassSignalCallbacks(signal, args, argCount);\n");
+
+ source.Append(" }\n");
+ }
+
+ source.Append("}\n"); // partial class
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("}\n"); // outer class
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ if (hasNamespace)
+ {
+ source.Append("\n}\n");
+ }
+
+ context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
+ }
+
+ private static void AppendMethodInfo(StringBuilder source, MethodInfo methodInfo)
+ {
+ source.Append(" signals.Add(new(name: GodotInternal.SignalName_")
+ .Append(methodInfo.Name)
+ .Append(", returnVal: ");
+
+ AppendPropertyInfo(source, methodInfo.ReturnVal);
+
+ source.Append(", flags: (Godot.MethodFlags)")
+ .Append((int)methodInfo.Flags)
+ .Append(", arguments: ");
+
+ if (methodInfo.Arguments is { Count: > 0 })
+ {
+ source.Append("new() { ");
+
+ foreach (var param in methodInfo.Arguments)
+ {
+ AppendPropertyInfo(source, param);
+
+ // C# allows colon after the last element
+ source.Append(", ");
+ }
+
+ source.Append(" }");
+ }
+ else
+ {
+ source.Append("null");
+ }
+
+ source.Append(", defaultArguments: null));\n");
+ }
+
+ private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
+ {
+ source.Append("new(type: (Godot.Variant.Type)")
+ .Append((int)propertyInfo.Type)
+ .Append(", name: \"")
+ .Append(propertyInfo.Name)
+ .Append("\", hint: (Godot.PropertyHint)")
+ .Append((int)propertyInfo.Hint)
+ .Append(", hintString: \"")
+ .Append(propertyInfo.HintString)
+ .Append("\", usage: (Godot.PropertyUsageFlags)")
+ .Append((int)propertyInfo.Usage)
+ .Append(", exported: ")
+ .Append(propertyInfo.Exported ? "true" : "false")
+ .Append(")");
+ }
+
+ private static MethodInfo DetermineMethodInfo(GodotSignalDelegateData signalDelegateData)
+ {
+ var invokeMethodData = signalDelegateData.InvokeMethodData;
+
+ PropertyInfo returnVal;
+
+ if (invokeMethodData.RetType != null)
+ {
+ returnVal = DeterminePropertyInfo(invokeMethodData.RetType.Value, name: string.Empty);
+ }
+ else
+ {
+ returnVal = new PropertyInfo(VariantType.Nil, string.Empty, PropertyHint.None,
+ hintString: null, PropertyUsageFlags.Default, exported: false);
+ }
+
+ int paramCount = invokeMethodData.ParamTypes.Length;
+
+ List<PropertyInfo>? arguments;
+
+ if (paramCount > 0)
+ {
+ arguments = new(capacity: paramCount);
+
+ for (int i = 0; i < paramCount; i++)
+ {
+ arguments.Add(DeterminePropertyInfo(invokeMethodData.ParamTypes[i],
+ name: invokeMethodData.Method.Parameters[i].Name));
+ }
+ }
+ else
+ {
+ arguments = null;
+ }
+
+ return new MethodInfo(signalDelegateData.Name, returnVal, MethodFlags.Default, arguments,
+ defaultArguments: null);
+ }
+
+ private static PropertyInfo DeterminePropertyInfo(MarshalType marshalType, string name)
+ {
+ var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
+
+ var propUsage = PropertyUsageFlags.Default;
+
+ if (memberVariantType == VariantType.Nil)
+ propUsage |= PropertyUsageFlags.NilIsVariant;
+
+ return new PropertyInfo(memberVariantType, name,
+ PropertyHint.None, string.Empty, propUsage, exported: false);
+ }
+
+ private static void GenerateSignalEventInvoker(
+ GodotSignalDelegateData signal,
+ StringBuilder source
+ )
+ {
+ string signalName = signal.Name;
+ var invokeMethodData = signal.InvokeMethodData;
+
+ source.Append(" if (signal == GodotInternal.SignalName_");
+ source.Append(signalName);
+ source.Append(" && argCount == ");
+ source.Append(invokeMethodData.ParamTypes.Length);
+ source.Append(") {\n");
+ source.Append(" backing_");
+ source.Append(signalName);
+ source.Append("?.Invoke(");
+
+ for (int i = 0; i < invokeMethodData.ParamTypes.Length; i++)
+ {
+ if (i != 0)
+ source.Append(", ");
+
+ source.AppendNativeVariantToManagedExpr(string.Concat("args[", i.ToString(), "]"),
+ invokeMethodData.ParamTypeSymbols[i], invokeMethodData.ParamTypes[i]);
+ }
+
+ source.Append(");\n");
+
+ source.Append(" return;\n");
+
+ source.Append(" }\n");
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
index 2bf1cb7a18..01aa65bfc3 100644
--- a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
@@ -7,8 +7,6 @@ namespace GodotTools.BuildLogger
{
public class GodotBuildLogger : ILogger
{
- public static readonly string AssemblyPath = Path.GetFullPath(typeof(GodotBuildLogger).Assembly.Location);
-
public string Parameters { get; set; }
public LoggerVerbosity Verbosity { get; set; }
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
index 0afec970c6..9e36497b06 100644
--- a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
@@ -5,6 +5,6 @@
<LangVersion>7.2</LangVersion>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Build.Framework" Version="16.5.0" />
+ <PackageReference Include="Microsoft.Build.Framework" Version="15.1.548" ExcludeAssets="runtime" />
</ItemGroup>
</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
index d6d8962f90..cfd5c88a58 100644
--- a/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ProjectGuid>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</ProjectGuid>
- <TargetFramework>netstandard2.0</TargetFramework>
- <LangVersion>7.2</LangVersion>
+ <TargetFramework>net6.0</TargetFramework>
+ <LangVersion>10</LangVersion>
</PropertyGroup>
</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj
index 303ca3a293..d2132115f3 100644
--- a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj
@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ProjectGuid>{B06C2951-C8E3-4F28-80B2-717CF327EB19}</ProjectGuid>
<OutputType>Exe</OutputType>
diff --git a/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj b/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj
index 5b3ed0b1b7..c05096bdcc 100644
--- a/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj
@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ProjectGuid>{EAFFF236-FA96-4A4D-BD23-0E51EF988277}</ProjectGuid>
<OutputType>Exe</OutputType>
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
index 37123ba2b2..bde14b2b40 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
@@ -1,32 +1,16 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ProjectGuid>{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}</ProjectGuid>
- <TargetFramework>net472</TargetFramework>
- <LangVersion>7.2</LangVersion>
+ <TargetFramework>net6.0</TargetFramework>
+ <LangVersion>10</LangVersion>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Build" Version="16.5.0" />
+ <PackageReference Include="Microsoft.Build" Version="15.1.548" ExcludeAssets="runtime" />
+ <PackageReference Include="Microsoft.Build.Locator" Version="1.2.6" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj" />
<ProjectReference Include="..\GodotTools.Shared\GodotTools.Shared.csproj" />
</ItemGroup>
- <!--
- The Microsoft.Build.Runtime package is too problematic so we create a MSBuild.exe stub. The workaround described
- here doesn't work with Microsoft.NETFramework.ReferenceAssemblies: https://github.com/microsoft/msbuild/issues/3486
- We need a MSBuild.exe file as there's an issue in Microsoft.Build where it executes platform dependent code when
- searching for MSBuild.exe before the fallback to not using it. A stub is fine as it should never be executed.
- -->
- <ItemGroup>
- <None Include="MSBuild.exe" CopyToOutputDirectory="Always" />
- </ItemGroup>
- <Target Name="CopyMSBuildStubWindows" AfterTargets="Build" Condition=" '$(GodotPlatform)' == 'windows' Or ( '$(GodotPlatform)' == '' And '$(OS)' == 'Windows_NT' ) ">
- <PropertyGroup>
- <GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath>
- <GodotOutputDataDir>$(GodotSourceRootPath)/bin/GodotSharp</GodotOutputDataDir>
- </PropertyGroup>
- <!-- Need to copy it here as well on Windows -->
- <Copy SourceFiles="MSBuild.exe" DestinationFiles="$(GodotOutputDataDir)\Mono\lib\mono\v4.0\MSBuild.exe" />
- </Target>
</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe
deleted file mode 100644
index e69de29bb2..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe
+++ /dev/null
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
index 7d49d251dd..fb6d2a707b 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.Build.Construction;
@@ -21,7 +22,8 @@ namespace GodotTools.ProjectEditor
root.Sdk = GodotSdkAttrValue;
var mainGroup = root.AddPropertyGroup();
- mainGroup.AddProperty("TargetFramework", "netstandard2.1");
+ mainGroup.AddProperty("TargetFramework", "net6.0");
+ mainGroup.AddProperty("EnableDynamicLoading", "true");
string sanitizedName = IdentifierUtils.SanitizeQualifiedIdentifier(name, allowEmptyIdentifiers: true);
@@ -44,7 +46,7 @@ namespace GodotTools.ProjectEditor
// Save (without BOM)
root.Save(path, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
- return Guid.NewGuid().ToString().ToUpper();
+ return Guid.NewGuid().ToString().ToUpperInvariant();
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
index cdac9acb25..7b1d5c228a 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
@@ -19,6 +19,16 @@ namespace GodotTools.ProjectEditor
public static class ProjectUtils
{
+ public static void MSBuildLocatorRegisterDefaults(out Version version, out string path)
+ {
+ var instance = Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults();
+ version = instance.Version;
+ path = instance.MSBuildPath;
+ }
+
+ public static void MSBuildLocatorRegisterMSBuildPath(string msbuildPath)
+ => Microsoft.Build.Locator.MSBuildLocator.RegisterMSBuildPath(msbuildPath);
+
public static MSBuildProject Open(string path)
{
var root = ProjectRootElement.Open(path);
@@ -42,7 +52,8 @@ namespace GodotTools.ProjectEditor
var root = project.Root;
string godotSdkAttrValue = ProjectGenerator.GodotSdkAttrValue;
- if (!string.IsNullOrEmpty(root.Sdk) && root.Sdk.Trim().Equals(godotSdkAttrValue, StringComparison.OrdinalIgnoreCase))
+ if (!string.IsNullOrEmpty(root.Sdk) &&
+ root.Sdk.Trim().Equals(godotSdkAttrValue, StringComparison.OrdinalIgnoreCase))
return;
root.Sdk = godotSdkAttrValue;
diff --git a/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets
index aab2d73bdd..4baae77b34 100644
--- a/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets
+++ b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets
@@ -8,8 +8,8 @@
</Target>
<Target Name="GenerateGodotNupkgsVersionsFile"
- DependsOnTargets="PrepareForBuild;_GenerateGodotNupkgsVersionsFile"
- BeforeTargets="BeforeCompile;CoreCompile">
+ DependsOnTargets="_GenerateGodotNupkgsVersionsFile"
+ BeforeTargets="PrepareForBuild;CompileDesignTime;BeforeCompile;CoreCompile">
<ItemGroup>
<Compile Include="$(GeneratedGodotNupkgsVersionsFile)" />
<FileWrites Include="$(GeneratedGodotNupkgsVersionsFile)" />
diff --git a/modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj b/modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj
index 3bc1698c15..d60e6343ea 100644
--- a/modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj
@@ -1,6 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
+ <!-- Specify compile items manually to avoid including dangling generated items. -->
+ <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<Import Project="GenerateGodotNupkgsVersions.targets" />
</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.sln b/modules/mono/editor/GodotTools/GodotTools.sln
index d3107a69db..564775635d 100644
--- a/modules/mono/editor/GodotTools/GodotTools.sln
+++ b/modules/mono/editor/GodotTools/GodotTools.sln
@@ -1,4 +1,4 @@
-
+
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.ProjectEditor", "GodotTools.ProjectEditor\GodotTools.ProjectEditor.csproj", "{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}"
@@ -15,6 +15,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.OpenVisualStudio
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.Shared", "GodotTools.Shared\GodotTools.Shared.csproj", "{2758FFAF-8237-4CF2-B569-66BF8B3587BB}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Godot.SourceGenerators", "..\Godot.NET.Sdk\Godot.SourceGenerators\Godot.SourceGenerators.csproj", "{D8C421B2-8911-41EB-B983-F675C7141EB7}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Godot.SourceGenerators.Internal", "..\..\glue\GodotSharp\Godot.SourceGenerators.Internal\Godot.SourceGenerators.Internal.csproj", "{55666071-BEC1-4A52-8A98-9A4A7A947DBF}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -49,5 +53,13 @@ Global
{2758FFAF-8237-4CF2-B569-66BF8B3587BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2758FFAF-8237-4CF2-B569-66BF8B3587BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2758FFAF-8237-4CF2-B569-66BF8B3587BB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D8C421B2-8911-41EB-B983-F675C7141EB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D8C421B2-8911-41EB-B983-F675C7141EB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D8C421B2-8911-41EB-B983-F675C7141EB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D8C421B2-8911-41EB-B983-F675C7141EB7}.Release|Any CPU.Build.0 = Release|Any CPU
+ {55666071-BEC1-4A52-8A98-9A4A7A947DBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {55666071-BEC1-4A52-8A98-9A4A7A947DBF}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {55666071-BEC1-4A52-8A98-9A4A7A947DBF}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {55666071-BEC1-4A52-8A98-9A4A7A947DBF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs
index 28bf57dc21..3c5b897719 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs
@@ -4,26 +4,36 @@ using Godot.Collections;
using GodotTools.Internals;
using Path = System.IO.Path;
+#nullable enable
+
namespace GodotTools.Build
{
[Serializable]
- public sealed class BuildInfo : RefCounted // TODO Remove RefCounted once we have proper serialization
+ public sealed partial class BuildInfo : RefCounted // TODO Remove RefCounted once we have proper serialization
{
- public string Solution { get; }
- public string[] Targets { get; }
- public string Configuration { get; }
- public bool Restore { get; }
+ public string Solution { get; private set; }
+ public string Configuration { get; private set; }
+ public string? RuntimeIdentifier { get; private set; }
+ public string? PublishOutputDir { get; private set; }
+ public bool Restore { get; private set; }
+ public bool Rebuild { get; private set; }
+ public bool OnlyClean { get; private set; }
+
// TODO Use List once we have proper serialization
- public Array<string> CustomProperties { get; } = new Array<string>();
+ public Godot.Collections.Array CustomProperties { get; private set; } = new();
- public string LogsDirPath => Path.Combine(GodotSharpDirs.BuildLogsDirs, $"{Solution.MD5Text()}_{Configuration}");
+ public string LogsDirPath =>
+ Path.Combine(GodotSharpDirs.BuildLogsDirs, $"{Solution.MD5Text()}_{Configuration}");
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (obj is BuildInfo other)
- return other.Solution == Solution && other.Targets == Targets &&
- other.Configuration == Configuration && other.Restore == Restore &&
- other.CustomProperties == CustomProperties && other.LogsDirPath == LogsDirPath;
+ return other.Solution == Solution &&
+ other.Configuration == Configuration && other.RuntimeIdentifier == RuntimeIdentifier &&
+ other.PublishOutputDir == PublishOutputDir && other.Restore == Restore &&
+ other.Rebuild == Rebuild && other.OnlyClean == OnlyClean &&
+ other.CustomProperties == CustomProperties &&
+ other.LogsDirPath == LogsDirPath;
return false;
}
@@ -34,25 +44,44 @@ namespace GodotTools.Build
{
int hash = 17;
hash = (hash * 29) + Solution.GetHashCode();
- hash = (hash * 29) + Targets.GetHashCode();
hash = (hash * 29) + Configuration.GetHashCode();
+ hash = (hash * 29) + (RuntimeIdentifier?.GetHashCode() ?? 0);
+ hash = (hash * 29) + (PublishOutputDir?.GetHashCode() ?? 0);
hash = (hash * 29) + Restore.GetHashCode();
+ hash = (hash * 29) + Rebuild.GetHashCode();
+ hash = (hash * 29) + OnlyClean.GetHashCode();
hash = (hash * 29) + CustomProperties.GetHashCode();
hash = (hash * 29) + LogsDirPath.GetHashCode();
return hash;
}
}
+ // Needed for instantiation from Godot, after reloading assemblies
private BuildInfo()
{
+ Solution = string.Empty;
+ Configuration = string.Empty;
+ }
+
+ public BuildInfo(string solution, string configuration, bool restore, bool rebuild, bool onlyClean)
+ {
+ Solution = solution;
+ Configuration = configuration;
+ Restore = restore;
+ Rebuild = rebuild;
+ OnlyClean = onlyClean;
}
- public BuildInfo(string solution, string[] targets, string configuration, bool restore)
+ public BuildInfo(string solution, string configuration, string runtimeIdentifier,
+ string publishOutputDir, bool restore, bool rebuild, bool onlyClean)
{
Solution = solution;
- Targets = targets;
Configuration = configuration;
+ RuntimeIdentifier = runtimeIdentifier;
+ PublishOutputDir = publishOutputDir;
Restore = restore;
+ Rebuild = rebuild;
+ OnlyClean = onlyClean;
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs
index 21bff70b15..43256953f5 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs
@@ -1,12 +1,10 @@
using System;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
-using GodotTools.Ides.Rider;
+using Godot;
using GodotTools.Internals;
-using JetBrains.Annotations;
-using static GodotTools.Internals.Globals;
using File = GodotTools.Utils.File;
-using OS = GodotTools.Utils.OS;
namespace GodotTools.Build
{
@@ -14,13 +12,8 @@ namespace GodotTools.Build
{
private static BuildInfo _buildInProgress;
- public const string PropNameMSBuildMono = "MSBuild (Mono)";
- public const string PropNameMSBuildVs = "MSBuild (VS Build Tools)";
- public const string PropNameMSBuildJetBrains = "MSBuild (JetBrains Rider)";
- public const string PropNameDotnetCli = "dotnet CLI";
-
public const string MsBuildIssuesFileName = "msbuild_issues.csv";
- public const string MsBuildLogFileName = "msbuild_log.txt";
+ private const string MsBuildLogFileName = "msbuild_log.txt";
public delegate void BuildLaunchFailedEventHandler(BuildInfo buildInfo, string reason);
@@ -62,11 +55,11 @@ namespace GodotTools.Build
private static void PrintVerbose(string text)
{
- if (Godot.OS.IsStdoutVerbose())
- Godot.GD.Print(text);
+ if (OS.IsStdoutVerbose())
+ GD.Print(text);
}
- public static bool Build(BuildInfo buildInfo)
+ private static bool Build(BuildInfo buildInfo)
{
if (_buildInProgress != null)
throw new InvalidOperationException("A build is already in progress");
@@ -103,7 +96,8 @@ namespace GodotTools.Build
}
catch (Exception e)
{
- BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
+ BuildLaunchFailed?.Invoke(buildInfo,
+ $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
Console.Error.WriteLine(e);
return false;
}
@@ -148,7 +142,8 @@ namespace GodotTools.Build
}
catch (Exception e)
{
- BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
+ BuildLaunchFailed?.Invoke(buildInfo,
+ $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
Console.Error.WriteLine(e);
return false;
}
@@ -159,18 +154,54 @@ namespace GodotTools.Build
}
}
- public static bool BuildProjectBlocking(string config, [CanBeNull] string[] targets = null, [CanBeNull] string platform = null)
+ private static bool Publish(BuildInfo buildInfo)
{
- var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, targets ?? new[] {"Build"}, config, restore: true);
+ if (_buildInProgress != null)
+ throw new InvalidOperationException("A build is already in progress");
- // If a platform was not specified, try determining the current one. If that fails, let MSBuild auto-detect it.
- if (platform != null || OS.PlatformNameMap.TryGetValue(Godot.OS.GetName(), out platform))
- buildInfo.CustomProperties.Add($"GodotTargetPlatform={platform}");
+ _buildInProgress = buildInfo;
- if (Internal.GodotIsRealTDouble())
- buildInfo.CustomProperties.Add("GodotRealTIsDouble=true");
+ try
+ {
+ BuildStarted?.Invoke(buildInfo);
+
+ // Required in order to update the build tasks list
+ Internal.GodotMainIteration();
+
+ try
+ {
+ RemoveOldIssuesFile(buildInfo);
+ }
+ catch (IOException e)
+ {
+ BuildLaunchFailed?.Invoke(buildInfo, $"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}");
+ Console.Error.WriteLine(e);
+ }
+
+ try
+ {
+ int exitCode = BuildSystem.Publish(buildInfo, StdOutputReceived, StdErrorReceived);
+
+ if (exitCode != 0)
+ PrintVerbose(
+ $"dotnet publish exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}");
- return BuildProjectBlocking(buildInfo);
+ BuildFinished?.Invoke(exitCode == 0 ? BuildResult.Success : BuildResult.Error);
+
+ return exitCode == 0;
+ }
+ catch (Exception e)
+ {
+ BuildLaunchFailed?.Invoke(buildInfo,
+ $"The publish method threw an exception.\n{e.GetType().FullName}: {e.Message}");
+ Console.Error.WriteLine(e);
+ return false;
+ }
+ }
+ finally
+ {
+ _buildInProgress = null;
+ }
}
private static bool BuildProjectBlocking(BuildInfo buildInfo)
@@ -178,31 +209,109 @@ namespace GodotTools.Build
if (!File.Exists(buildInfo.Solution))
return true; // No solution to build
- // Make sure the API assemblies are up to date before building the project.
- // We may not have had the chance to update the release API assemblies, and the debug ones
- // may have been deleted by the user at some point after they were loaded by the Godot editor.
- string apiAssembliesUpdateError = Internal.UpdateApiAssembliesFromPrebuilt(buildInfo.Configuration == "ExportRelease" ? "Release" : "Debug");
+ using var pr = new EditorProgress("dotnet_build_project", "Building .NET project...", 1);
+
+ pr.Step("Building project solution", 0);
- if (!string.IsNullOrEmpty(apiAssembliesUpdateError))
+ if (!Build(buildInfo))
{
- ShowBuildErrorDialog("Failed to update the Godot API assemblies");
+ ShowBuildErrorDialog("Failed to build project solution");
return false;
}
- using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1))
+ return true;
+ }
+
+ private static bool CleanProjectBlocking(BuildInfo buildInfo)
+ {
+ if (!File.Exists(buildInfo.Solution))
+ return true; // No solution to clean
+
+ using var pr = new EditorProgress("dotnet_clean_project", "Cleaning .NET project...", 1);
+
+ pr.Step("Cleaning project solution", 0);
+
+ if (!Build(buildInfo))
{
- pr.Step("Building project solution", 0);
+ ShowBuildErrorDialog("Failed to clean project solution");
+ return false;
+ }
- if (!Build(buildInfo))
- {
- ShowBuildErrorDialog("Failed to build project solution");
- return false;
- }
+ return true;
+ }
+
+ private static bool PublishProjectBlocking(BuildInfo buildInfo)
+ {
+ using var pr = new EditorProgress("dotnet_publish_project", "Publishing .NET project...", 1);
+
+ pr.Step("Running dotnet publish", 0);
+
+ if (!Publish(buildInfo))
+ {
+ ShowBuildErrorDialog("Failed to publish .NET project");
+ return false;
}
return true;
}
+ private static BuildInfo CreateBuildInfo(
+ [DisallowNull] string configuration,
+ [AllowNull] string platform = null,
+ bool rebuild = false,
+ bool onlyClean = false
+ )
+ {
+ var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, configuration,
+ restore: true, rebuild, onlyClean);
+
+ // If a platform was not specified, try determining the current one. If that fails, let MSBuild auto-detect it.
+ if (platform != null || Utils.OS.PlatformNameMap.TryGetValue(OS.GetName(), out platform))
+ buildInfo.CustomProperties.Add($"GodotTargetPlatform={platform}");
+
+ if (Internal.GodotIsRealTDouble())
+ buildInfo.CustomProperties.Add("GodotRealTIsDouble=true");
+
+ return buildInfo;
+ }
+
+ private static BuildInfo CreatePublishBuildInfo(
+ [DisallowNull] string configuration,
+ [DisallowNull] string platform,
+ [DisallowNull] string runtimeIdentifier,
+ [DisallowNull] string publishOutputDir
+ )
+ {
+ var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, configuration,
+ runtimeIdentifier, publishOutputDir, restore: true, rebuild: false, onlyClean: false);
+
+ buildInfo.CustomProperties.Add($"GodotTargetPlatform={platform}");
+
+ if (Internal.GodotIsRealTDouble())
+ buildInfo.CustomProperties.Add("GodotRealTIsDouble=true");
+
+ return buildInfo;
+ }
+
+ public static bool BuildProjectBlocking(
+ [DisallowNull] string configuration,
+ [AllowNull] string platform = null,
+ bool rebuild = false
+ ) => BuildProjectBlocking(CreateBuildInfo(configuration, platform, rebuild));
+
+ public static bool CleanProjectBlocking(
+ [DisallowNull] string configuration,
+ [AllowNull] string platform = null
+ ) => CleanProjectBlocking(CreateBuildInfo(configuration, platform, rebuild: false));
+
+ public static bool PublishProjectBlocking(
+ [DisallowNull] string configuration,
+ [DisallowNull] string platform,
+ [DisallowNull] string runtimeIdentifier,
+ string publishOutputDir
+ ) => PublishProjectBlocking(CreatePublishBuildInfo(configuration,
+ platform, runtimeIdentifier, publishOutputDir));
+
public static bool EditorBuildCallback()
{
if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
@@ -215,7 +324,7 @@ namespace GodotTools.Build
}
catch (Exception e)
{
- Godot.GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message);
+ GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message);
}
if (GodotSharpEditor.Instance.SkipBuildBeforePlaying)
@@ -226,47 +335,6 @@ namespace GodotTools.Build
public static void Initialize()
{
- // Build tool settings
- var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
-
- BuildTool msbuildDefault;
-
- if (OS.IsWindows)
- {
- if (RiderPathManager.IsExternalEditorSetToRider(editorSettings))
- msbuildDefault = BuildTool.JetBrainsMsBuild;
- else
- msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildVs;
- }
- else
- {
- msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildMono;
- }
-
- EditorDef("mono/builds/build_tool", msbuildDefault);
-
- string hintString;
-
- if (OS.IsWindows)
- {
- hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," +
- $"{PropNameMSBuildVs}:{(int)BuildTool.MsBuildVs}," +
- $"{PropNameMSBuildJetBrains}:{(int)BuildTool.JetBrainsMsBuild}," +
- $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}";
- }
- else
- {
- hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," +
- $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}";
- }
-
- editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary
- {
- ["type"] = Godot.Variant.Type.Int,
- ["name"] = "mono/builds/build_tool",
- ["hint"] = Godot.PropertyHint.Enum,
- ["hint_string"] = hintString
- });
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs
index ebdaca0ce8..96d1fc28bf 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs
@@ -1,17 +1,16 @@
using Godot;
using System;
-using Godot.Collections;
+using System.Diagnostics.CodeAnalysis;
using GodotTools.Internals;
-using JetBrains.Annotations;
using File = GodotTools.Utils.File;
using Path = System.IO.Path;
namespace GodotTools.Build
{
- public class BuildOutputView : VBoxContainer, ISerializationListener
+ public partial class BuildOutputView : VBoxContainer, ISerializationListener
{
[Serializable]
- private class BuildIssue : RefCounted // TODO Remove RefCounted once we have proper serialization
+ private partial class BuildIssue : RefCounted // TODO Remove RefCounted once we have proper serialization
{
public bool Warning { get; set; }
public string File { get; set; }
@@ -22,7 +21,8 @@ namespace GodotTools.Build
public string ProjectFile { get; set; }
}
- [Signal] public event Action BuildStateChanged;
+ [Signal]
+ public delegate void BuildStateChangedEventHandler();
public bool HasBuildExited { get; private set; } = false;
@@ -58,7 +58,7 @@ namespace GodotTools.Build
}
// TODO Use List once we have proper serialization.
- private readonly Array<BuildIssue> _issues = new Array<BuildIssue>();
+ private Godot.Collections.Array<BuildIssue> _issues = new();
private ItemList _issuesList;
private PopupMenu _issuesListContextMenu;
private TextEdit _buildLog;
@@ -123,7 +123,7 @@ namespace GodotTools.Build
throw new IndexOutOfRangeException("Item list index out of range");
// Get correct issue idx from issue list
- int issueIndex = (int)(long)_issuesList.GetItemMetadata(idx);
+ int issueIndex = (int)_issuesList.GetItemMetadata(idx);
if (issueIndex < 0 || issueIndex >= _issues.Count)
throw new IndexOutOfRangeException("Issue index out of range");
@@ -133,7 +133,9 @@ namespace GodotTools.Build
if (string.IsNullOrEmpty(issue.ProjectFile) && string.IsNullOrEmpty(issue.File))
return;
- string projectDir = issue.ProjectFile.Length > 0 ? issue.ProjectFile.GetBaseDir() : _buildInfo.Solution.GetBaseDir();
+ string projectDir = !string.IsNullOrEmpty(issue.ProjectFile) ?
+ issue.ProjectFile.GetBaseDir() :
+ _buildInfo.Solution.GetBaseDir();
string file = Path.Combine(projectDir.SimplifyGodotPath(), issue.File.SimplifyGodotPath());
@@ -412,6 +414,16 @@ namespace GodotTools.Build
{
// In case it didn't update yet. We don't want to have to serialize any pending output.
UpdateBuildLogText();
+
+ // NOTE:
+ // Currently, GodotTools is loaded in its own load context. This load context is not reloaded, but the script still are.
+ // Until that changes, we need workarounds like this one because events keep strong references to disposed objects.
+ BuildManager.BuildLaunchFailed -= BuildLaunchFailed;
+ BuildManager.BuildStarted -= BuildStarted;
+ BuildManager.BuildFinished -= BuildFinished;
+ // StdOutput/Error can be received from different threads, so we need to use CallDeferred
+ BuildManager.StdOutputReceived -= StdOutputReceived;
+ BuildManager.StdErrorReceived -= StdErrorReceived;
}
public void OnAfterDeserialize()
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
index 02e9d98647..655be0ab5e 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
@@ -1,61 +1,93 @@
-using GodotTools.Core;
using System;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
+using System.Linq;
+using System.Text;
using System.Threading.Tasks;
using GodotTools.BuildLogger;
-using GodotTools.Internals;
using GodotTools.Utils;
-using Directory = System.IO.Directory;
namespace GodotTools.Build
{
public static class BuildSystem
{
- private static string MonoWindowsBinDir
+ private static Process LaunchBuild(BuildInfo buildInfo, Action<string> stdOutHandler,
+ Action<string> stdErrHandler)
{
- get
- {
- string monoWinBinDir = Path.Combine(Internal.MonoWindowsInstallRoot, "bin");
+ string dotnetPath = DotNetFinder.FindDotNetExe();
- if (!Directory.Exists(monoWinBinDir))
- throw new FileNotFoundException("Cannot find the Windows Mono install bin directory.");
+ if (dotnetPath == null)
+ throw new FileNotFoundException("Cannot find the dotnet executable.");
- return monoWinBinDir;
- }
+ var startInfo = new ProcessStartInfo(dotnetPath);
+
+ BuildArguments(buildInfo, startInfo.ArgumentList);
+
+ string launchMessage = startInfo.GetCommandLineDisplay(new StringBuilder("Running: ")).ToString();
+ stdOutHandler?.Invoke(launchMessage);
+ if (Godot.OS.IsStdoutVerbose())
+ Console.WriteLine(launchMessage);
+
+ startInfo.RedirectStandardOutput = true;
+ startInfo.RedirectStandardError = true;
+ startInfo.UseShellExecute = false;
+ startInfo.CreateNoWindow = true;
+
+ // Needed when running from Developer Command Prompt for VS
+ RemovePlatformVariable(startInfo.EnvironmentVariables);
+
+ var process = new Process { StartInfo = startInfo };
+
+ if (stdOutHandler != null)
+ process.OutputDataReceived += (_, e) => stdOutHandler.Invoke(e.Data);
+ if (stdErrHandler != null)
+ process.ErrorDataReceived += (_, e) => stdErrHandler.Invoke(e.Data);
+
+ process.Start();
+
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+
+ return process;
}
- private static Godot.EditorSettings EditorSettings =>
- GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
+ public static int Build(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
+ {
+ using (var process = LaunchBuild(buildInfo, stdOutHandler, stdErrHandler))
+ {
+ process.WaitForExit();
+
+ return process.ExitCode;
+ }
+ }
- private static bool UsingMonoMsBuildOnWindows
+ public static async Task<int> BuildAsync(BuildInfo buildInfo, Action<string> stdOutHandler,
+ Action<string> stdErrHandler)
{
- get
+ using (var process = LaunchBuild(buildInfo, stdOutHandler, stdErrHandler))
{
- if (OS.IsWindows)
- {
- return (BuildTool)EditorSettings.GetSetting("mono/builds/build_tool")
- == BuildTool.MsBuildMono;
- }
+ await process.WaitForExitAsync();
- return false;
+ return process.ExitCode;
}
}
- private static Process LaunchBuild(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
+ private static Process LaunchPublish(BuildInfo buildInfo, Action<string> stdOutHandler,
+ Action<string> stdErrHandler)
{
- (string msbuildPath, BuildTool buildTool) = MsBuildFinder.FindMsBuild();
+ string dotnetPath = DotNetFinder.FindDotNetExe();
- if (msbuildPath == null)
- throw new FileNotFoundException("Cannot find the MSBuild executable.");
+ if (dotnetPath == null)
+ throw new FileNotFoundException("Cannot find the dotnet executable.");
- string compilerArgs = BuildArguments(buildTool, buildInfo);
+ var startInfo = new ProcessStartInfo(dotnetPath);
- var startInfo = new ProcessStartInfo(msbuildPath, compilerArgs);
+ BuildPublishArguments(buildInfo, startInfo.ArgumentList);
- string launchMessage = $"Running: \"{startInfo.FileName}\" {startInfo.Arguments}";
+ string launchMessage = startInfo.GetCommandLineDisplay(new StringBuilder("Running: ")).ToString();
stdOutHandler?.Invoke(launchMessage);
if (Godot.OS.IsStdoutVerbose())
Console.WriteLine(launchMessage);
@@ -63,27 +95,16 @@ namespace GodotTools.Build
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
- startInfo.CreateNoWindow = true;
-
- if (UsingMonoMsBuildOnWindows)
- {
- // These environment variables are required for Mono's MSBuild to find the compilers.
- // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono.
- string monoWinBinDir = MonoWindowsBinDir;
- startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat"));
- startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat"));
- startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat"));
- }
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
- var process = new Process {StartInfo = startInfo};
+ var process = new Process { StartInfo = startInfo };
if (stdOutHandler != null)
- process.OutputDataReceived += (s, e) => stdOutHandler.Invoke(e.Data);
+ process.OutputDataReceived += (_, e) => stdOutHandler.Invoke(e.Data);
if (stdErrHandler != null)
- process.ErrorDataReceived += (s, e) => stdErrHandler.Invoke(e.Data);
+ process.ErrorDataReceived += (_, e) => stdErrHandler.Invoke(e.Data);
process.Start();
@@ -93,9 +114,9 @@ namespace GodotTools.Build
return process;
}
- public static int Build(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
+ public static int Publish(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
{
- using (var process = LaunchBuild(buildInfo, stdOutHandler, stdErrHandler))
+ using (var process = LaunchPublish(buildInfo, stdOutHandler, stdErrHandler))
{
process.WaitForExit();
@@ -103,38 +124,101 @@ namespace GodotTools.Build
}
}
- public static async Task<int> BuildAsync(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
+ private static void BuildArguments(BuildInfo buildInfo, Collection<string> arguments)
{
- using (var process = LaunchBuild(buildInfo, stdOutHandler, stdErrHandler))
+ // `dotnet clean` / `dotnet build` commands
+ arguments.Add(buildInfo.OnlyClean ? "clean" : "build");
+
+ // Solution
+ arguments.Add(buildInfo.Solution);
+
+ // `dotnet clean` doesn't recognize these options
+ if (!buildInfo.OnlyClean)
{
- await process.WaitForExitAsync();
+ // Restore
+ // `dotnet build` restores by default, unless requested not to
+ if (!buildInfo.Restore)
+ arguments.Add("--no-restore");
+
+ // Incremental or rebuild
+ if (buildInfo.Rebuild)
+ arguments.Add("--no-incremental");
+ }
- return process.ExitCode;
+ // Configuration
+ arguments.Add("-c");
+ arguments.Add(buildInfo.Configuration);
+
+ // Verbosity
+ arguments.Add("-v");
+ arguments.Add("normal");
+
+ // Logger
+ AddLoggerArgument(buildInfo, arguments);
+
+ // Custom properties
+ foreach (var customProperty in buildInfo.CustomProperties)
+ {
+ arguments.Add("-p:" + (string)customProperty);
}
}
- private static string BuildArguments(BuildTool buildTool, BuildInfo buildInfo)
+ private static void BuildPublishArguments(BuildInfo buildInfo, Collection<string> arguments)
{
- string arguments = string.Empty;
+ arguments.Add("publish"); // `dotnet publish` command
+
+ // Solution
+ arguments.Add(buildInfo.Solution);
+
+ // Restore
+ // `dotnet publish` restores by default, unless requested not to
+ if (!buildInfo.Restore)
+ arguments.Add("--no-restore");
- if (buildTool == BuildTool.DotnetCli)
- arguments += "msbuild"; // `dotnet msbuild` command
+ // Incremental or rebuild
+ if (buildInfo.Rebuild)
+ arguments.Add("--no-incremental");
- arguments += $@" ""{buildInfo.Solution}""";
+ // Configuration
+ arguments.Add("-c");
+ arguments.Add(buildInfo.Configuration);
- if (buildInfo.Restore)
- arguments += " /restore";
+ // Runtime Identifier
+ arguments.Add("-r");
+ arguments.Add(buildInfo.RuntimeIdentifier!);
- arguments += $@" /t:{string.Join(",", buildInfo.Targets)} " +
- $@"""/p:{"Configuration=" + buildInfo.Configuration}"" /v:normal " +
- $@"""/l:{typeof(GodotBuildLogger).FullName},{GodotBuildLogger.AssemblyPath};{buildInfo.LogsDirPath}""";
+ // Self-published
+ arguments.Add("--self-contained");
+ arguments.Add("true");
- foreach (string customProperty in buildInfo.CustomProperties)
+ // Verbosity
+ arguments.Add("-v");
+ arguments.Add("normal");
+
+ // Logger
+ AddLoggerArgument(buildInfo, arguments);
+
+ // Custom properties
+ foreach (var customProperty in buildInfo.CustomProperties)
+ {
+ arguments.Add("-p:" + (string)customProperty);
+ }
+
+ // Publish output directory
+ if (buildInfo.PublishOutputDir != null)
{
- arguments += " /p:" + customProperty;
+ arguments.Add("-o");
+ arguments.Add(buildInfo.PublishOutputDir);
}
+ }
+
+ private static void AddLoggerArgument(BuildInfo buildInfo, Collection<string> arguments)
+ {
+ string buildLoggerPath = Path.Combine(Internals.GodotSharpDirs.DataEditorToolsDir,
+ "GodotTools.BuildLogger.dll");
- return arguments;
+ arguments.Add(
+ $"-l:{typeof(GodotBuildLogger).FullName},{buildLoggerPath};{buildInfo.LogsDirPath}");
}
private static void RemovePlatformVariable(StringDictionary environmentVariables)
@@ -145,7 +229,7 @@ namespace GodotTools.Build
foreach (string env in environmentVariables.Keys)
{
- if (env.ToUpper() == "PLATFORM")
+ if (env.ToUpperInvariant() == "PLATFORM")
platformEnvironmentVariables.Add(env);
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildTool.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildTool.cs
deleted file mode 100644
index 837c8adddb..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildTool.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace GodotTools.Build
-{
- public enum BuildTool : long
- {
- MsBuildMono,
- MsBuildVs,
- JetBrainsMsBuild,
- DotnetCli
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs b/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs
new file mode 100644
index 0000000000..7bce53308c
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs
@@ -0,0 +1,99 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using JetBrains.Annotations;
+using OS = GodotTools.Utils.OS;
+
+namespace GodotTools.Build
+{
+ public static class DotNetFinder
+ {
+ [CanBeNull]
+ public static string FindDotNetExe()
+ {
+ // In the future, this method may do more than just search in PATH. We could look in
+ // known locations or use Godot's linked nethost to search from the hostfxr location.
+
+ return OS.PathWhich("dotnet");
+ }
+
+ public static bool TryFindDotNetSdk(
+ Version expectedVersion,
+ [NotNullWhen(true)] out Version version,
+ [NotNullWhen(true)] out string path
+ )
+ {
+ version = null;
+ path = null;
+
+ string dotNetExe = FindDotNetExe();
+
+ if (string.IsNullOrEmpty(dotNetExe))
+ return false;
+
+ using Process process = new Process();
+ process.StartInfo = new ProcessStartInfo(dotNetExe, "--list-sdks")
+ {
+ UseShellExecute = false,
+ RedirectStandardOutput = true
+ };
+
+ process.StartInfo.EnvironmentVariables["DOTNET_CLI_UI_LANGUAGE"] = "en-US";
+
+ var lines = new List<string>();
+
+ process.OutputDataReceived += (_, e) =>
+ {
+ if (!string.IsNullOrWhiteSpace(e.Data))
+ lines.Add(e.Data);
+ };
+
+ try
+ {
+ process.Start();
+ }
+ catch
+ {
+ return false;
+ }
+
+ process.BeginOutputReadLine();
+ process.WaitForExit();
+
+ Version latestVersionMatch = null;
+ string matchPath = null;
+
+ foreach (var line in lines)
+ {
+ string[] sdkLineParts = line.Trim()
+ .Split(' ', 2, StringSplitOptions.TrimEntries);
+
+ if (sdkLineParts.Length < 2)
+ continue;
+
+ if (!Version.TryParse(sdkLineParts[0], out var lineVersion))
+ continue;
+
+ // We're looking for the exact same major version
+ if (lineVersion.Major != expectedVersion.Major)
+ continue;
+
+ if (latestVersionMatch != null && lineVersion < latestVersionMatch)
+ continue;
+
+ latestVersionMatch = lineVersion;
+ matchPath = sdkLineParts[1].TrimStart('[').TrimEnd(']');
+ }
+
+ if (latestVersionMatch == null)
+ return false;
+
+ version = latestVersionMatch;
+ path = Path.Combine(matchPath!, version.ToString());
+
+ return true;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs
index 3c020a2589..6dae0a3a0e 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs
@@ -1,13 +1,12 @@
using System;
using Godot;
using GodotTools.Internals;
-using JetBrains.Annotations;
using static GodotTools.Internals.Globals;
using File = GodotTools.Utils.File;
namespace GodotTools.Build
{
- public class MSBuildPanel : VBoxContainer
+ public partial class MSBuildPanel : VBoxContainer
{
public BuildOutputView BuildOutputView { get; private set; }
@@ -28,7 +27,6 @@ namespace GodotTools.Build
BuildOutputView.UpdateIssuesList();
}
- [UsedImplicitly]
public void BuildSolution()
{
if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
@@ -57,7 +55,6 @@ namespace GodotTools.Build
Internal.ReloadAssemblies(softReload: false);
}
- [UsedImplicitly]
private void RebuildSolution()
{
if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
@@ -73,7 +70,7 @@ namespace GodotTools.Build
GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message);
}
- if (!BuildManager.BuildProjectBlocking("Debug", targets: new[] { "Rebuild" }))
+ if (!BuildManager.BuildProjectBlocking("Debug", rebuild: true))
return; // Build failed
// Notify running game for hot-reload
@@ -86,13 +83,12 @@ namespace GodotTools.Build
Internal.ReloadAssemblies(softReload: false);
}
- [UsedImplicitly]
private void CleanSolution()
{
if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
return; // No solution to build
- BuildManager.BuildProjectBlocking("Debug", targets: new[] { "Clean" });
+ _ = BuildManager.CleanProjectBlocking("Debug");
}
private void ViewLogToggled(bool pressed) => BuildOutputView.LogVisible = pressed;
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs
deleted file mode 100644
index a859c6f717..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs
+++ /dev/null
@@ -1,233 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using Godot;
-using GodotTools.Ides.Rider;
-using GodotTools.Internals;
-using Directory = System.IO.Directory;
-using Environment = System.Environment;
-using File = System.IO.File;
-using Path = System.IO.Path;
-using OS = GodotTools.Utils.OS;
-
-namespace GodotTools.Build
-{
- public static class MsBuildFinder
- {
- private static string _msbuildToolsPath = string.Empty;
- private static string _msbuildUnixPath = string.Empty;
-
- public static (string, BuildTool) FindMsBuild()
- {
- var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
- var buildTool = (BuildTool)editorSettings.GetSetting("mono/builds/build_tool");
-
- if (OS.IsWindows)
- {
- switch (buildTool)
- {
- case BuildTool.DotnetCli:
- {
- string dotnetCliPath = OS.PathWhich("dotnet");
- if (!string.IsNullOrEmpty(dotnetCliPath))
- return (dotnetCliPath, BuildTool.DotnetCli);
- GD.PushError($"Cannot find executable for '{BuildManager.PropNameDotnetCli}'. Fallback to MSBuild from Visual Studio.");
- goto case BuildTool.MsBuildVs;
- }
- case BuildTool.MsBuildVs:
- {
- if (string.IsNullOrEmpty(_msbuildToolsPath) || !File.Exists(_msbuildToolsPath))
- {
- // Try to search it again if it wasn't found last time or if it was removed from its location
- _msbuildToolsPath = FindMsBuildToolsPathOnWindows();
-
- if (string.IsNullOrEmpty(_msbuildToolsPath))
- throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMSBuildVs}'.");
- }
-
- if (!_msbuildToolsPath.EndsWith("\\"))
- _msbuildToolsPath += "\\";
-
- return (Path.Combine(_msbuildToolsPath, "MSBuild.exe"), BuildTool.MsBuildVs);
- }
- case BuildTool.MsBuildMono:
- {
- string msbuildPath = Path.Combine(Internal.MonoWindowsInstallRoot, "bin", "msbuild.bat");
-
- if (!File.Exists(msbuildPath))
- throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMSBuildMono}'. Tried with path: {msbuildPath}");
-
- return (msbuildPath, BuildTool.MsBuildMono);
- }
- case BuildTool.JetBrainsMsBuild:
- {
- string editorPath = (string)editorSettings.GetSetting(RiderPathManager.EditorPathSettingName);
-
- if (!File.Exists(editorPath))
- throw new FileNotFoundException($"Cannot find Rider executable. Tried with path: {editorPath}");
-
- var riderDir = new FileInfo(editorPath).Directory?.Parent;
-
- string msbuildPath = Path.Combine(riderDir.FullName, @"tools\MSBuild\Current\Bin\MSBuild.exe");
-
- if (!File.Exists(msbuildPath))
- throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMSBuildJetBrains}'. Tried with path: {msbuildPath}");
-
- return (msbuildPath, BuildTool.JetBrainsMsBuild);
- }
- default:
- throw new IndexOutOfRangeException("Invalid build tool in editor settings");
- }
- }
-
- if (OS.IsUnixLike)
- {
- switch (buildTool)
- {
- case BuildTool.DotnetCli:
- {
- string dotnetCliPath = FindBuildEngineOnUnix("dotnet");
- if (!string.IsNullOrEmpty(dotnetCliPath))
- return (dotnetCliPath, BuildTool.DotnetCli);
- GD.PushError($"Cannot find executable for '{BuildManager.PropNameDotnetCli}'. Fallback to MSBuild from Mono.");
- goto case BuildTool.MsBuildMono;
- }
- case BuildTool.MsBuildMono:
- {
- if (string.IsNullOrEmpty(_msbuildUnixPath) || !File.Exists(_msbuildUnixPath))
- {
- // Try to search it again if it wasn't found last time or if it was removed from its location
- _msbuildUnixPath = FindBuildEngineOnUnix("msbuild");
- }
-
- if (string.IsNullOrEmpty(_msbuildUnixPath))
- throw new FileNotFoundException($"Cannot find binary for '{BuildManager.PropNameMSBuildMono}'");
-
- return (_msbuildUnixPath, BuildTool.MsBuildMono);
- }
- default:
- throw new IndexOutOfRangeException("Invalid build tool in editor settings");
- }
- }
-
- throw new PlatformNotSupportedException();
- }
-
- private static IEnumerable<string> MsBuildHintDirs
- {
- get
- {
- var result = new List<string>();
-
- if (OS.IsMacOS)
- {
- result.Add("/Library/Frameworks/Mono.framework/Versions/Current/bin/");
- result.Add("/opt/local/bin/");
- result.Add("/usr/local/var/homebrew/linked/mono/bin/");
- result.Add("/usr/local/bin/");
- result.Add("/usr/local/bin/dotnet/");
- result.Add("/usr/local/share/dotnet/");
- }
-
- result.Add("/opt/novell/mono/bin/");
-
- return result;
- }
- }
-
- private static string FindBuildEngineOnUnix(string name)
- {
- string ret = OS.PathWhich(name);
-
- if (!string.IsNullOrEmpty(ret))
- return ret;
-
- string retFallback = OS.PathWhich($"{name}.exe");
-
- if (!string.IsNullOrEmpty(retFallback))
- return retFallback;
-
- foreach (string hintDir in MsBuildHintDirs)
- {
- string hintPath = Path.Combine(hintDir, name);
-
- if (File.Exists(hintPath))
- return hintPath;
- }
-
- return string.Empty;
- }
-
- private static string FindMsBuildToolsPathOnWindows()
- {
- if (!OS.IsWindows)
- throw new PlatformNotSupportedException();
-
- // Try to find 15.0 with vswhere
-
- string[] envNames = Internal.GodotIs32Bits() ?
- envNames = new[] { "ProgramFiles", "ProgramW6432" } :
- envNames = new[] { "ProgramFiles(x86)", "ProgramFiles" };
-
- string vsWherePath = null;
- foreach (var envName in envNames)
- {
- vsWherePath = Environment.GetEnvironmentVariable(envName);
- if (!string.IsNullOrEmpty(vsWherePath))
- {
- vsWherePath += "\\Microsoft Visual Studio\\Installer\\vswhere.exe";
- if (File.Exists(vsWherePath))
- break;
- }
-
- vsWherePath = null;
- }
-
- var vsWhereArgs = new[] {"-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild"};
-
- var outputArray = new Godot.Collections.Array<string>();
- int exitCode = Godot.OS.Execute(vsWherePath, vsWhereArgs,
- output: (Godot.Collections.Array)outputArray);
-
- if (exitCode != 0)
- return string.Empty;
-
- if (outputArray.Count == 0)
- return string.Empty;
-
- var lines = outputArray[0].Split('\n');
-
- foreach (string line in lines)
- {
- int sepIdx = line.IndexOf(':');
-
- if (sepIdx <= 0)
- continue;
-
- string key = line.Substring(0, sepIdx); // No need to trim
-
- if (key != "installationPath")
- continue;
-
- string value = line.Substring(sepIdx + 1).StripEdges();
-
- if (string.IsNullOrEmpty(value))
- throw new FormatException("installationPath value is empty");
-
- if (!value.EndsWith("\\"))
- value += "\\";
-
- // Since VS2019, the directory is simply named "Current"
- string msbuildDir = Path.Combine(value, "MSBuild\\Current\\Bin");
-
- if (Directory.Exists(msbuildDir))
- return msbuildDir;
-
- // Directory name "15.0" is used in VS 2017
- return Path.Combine(value, "MSBuild\\15.0\\Bin");
- }
-
- return string.Empty;
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs
index 63b97e981e..fdb86c8f34 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
@@ -39,7 +40,8 @@ namespace GodotTools.Build
// Since this can be considered pretty much a new NuGet.Config, add the default nuget.org source as well
XmlElement nugetOrgSourceEntry = xmlDoc.CreateElement("add");
nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("key")).Value = "nuget.org";
- nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value = "https://api.nuget.org/v3/index.json";
+ nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value =
+ "https://api.nuget.org/v3/index.json";
nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("protocolVersion")).Value = "3";
rootNode.AppendChild(xmlDoc.CreateElement("packageSources")).AppendChild(nugetOrgSourceEntry);
}
@@ -181,8 +183,8 @@ namespace GodotTools.Build
// - The sha512 of the nupkg is base64 encoded.
// - We can get the nuspec from the nupkg which is a Zip file.
- string packageIdLower = packageId.ToLower();
- string packageVersionLower = packageVersion.ToLower();
+ string packageIdLower = packageId.ToLowerInvariant();
+ string packageVersionLower = packageVersion.ToLowerInvariant();
string destDir = Path.Combine(fallbackFolder, packageIdLower, packageVersionLower);
string nupkgDestPath = Path.Combine(destDir, $"{packageIdLower}.{packageVersionLower}.nupkg");
@@ -227,9 +229,11 @@ namespace GodotTools.Build
var nuspecEntry = archive.GetEntry(packageId + ".nuspec");
if (nuspecEntry == null)
- throw new InvalidOperationException($"Failed to extract package {packageId}.{packageVersion}. Could not find the nuspec file.");
+ throw new InvalidOperationException(
+ $"Failed to extract package {packageId}.{packageVersion}. Could not find the nuspec file.");
- nuspecEntry.ExtractToFile(Path.Combine(destDir, nuspecEntry.Name.ToLower().SimplifyGodotPath()));
+ nuspecEntry.ExtractToFile(Path.Combine(destDir, nuspecEntry.Name
+ .ToLowerInvariant().SimplifyGodotPath()));
// Extract the other package files
diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs
index e9718cc82c..fc325fc25b 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs
@@ -75,8 +75,17 @@ namespace GodotTools.Export
}
else
{
- string bits = features.Contains("64") ? "64" : features.Contains("32") ? "32" : null;
- CompileAssembliesForDesktop(exporter, platform, isDebug, bits, aotOpts, aotTempDir, outputDataDir, assembliesPrepared, bclDir);
+ string arch = "";
+ if (features.Contains("x86_64")) {
+ arch = "x86_64";
+ } else if (features.Contains("x86_32")) {
+ arch = "x86_32";
+ } else if (features.Contains("arm64")) {
+ arch = "arm64";
+ } else if (features.Contains("arm32")) {
+ arch = "arm32";
+ }
+ CompileAssembliesForDesktop(exporter, platform, isDebug, arch, aotOpts, aotTempDir, outputDataDir, assembliesPrepared, bclDir);
}
}
@@ -112,7 +121,7 @@ namespace GodotTools.Export
}
}
- public static void CompileAssembliesForDesktop(ExportPlugin exporter, string platform, bool isDebug, string bits, AotOptions aotOpts, string aotTempDir, string outputDataDir, IDictionary<string, string> assemblies, string bclDir)
+ public static void CompileAssembliesForDesktop(ExportPlugin exporter, string platform, bool isDebug, string arch, AotOptions aotOpts, string aotTempDir, string outputDataDir, IDictionary<string, string> assemblies, string bclDir)
{
foreach (var assembly in assemblies)
{
@@ -126,9 +135,9 @@ namespace GodotTools.Export
string outputFileName = assemblyName + ".dll" + outputFileExtension;
string tempOutputFilePath = Path.Combine(aotTempDir, outputFileName);
- var compilerArgs = GetAotCompilerArgs(platform, isDebug, bits, aotOpts, assemblyPath, tempOutputFilePath);
+ var compilerArgs = GetAotCompilerArgs(platform, isDebug, arch, aotOpts, assemblyPath, tempOutputFilePath);
- string compilerDirPath = GetMonoCrossDesktopDirName(platform, bits);
+ string compilerDirPath = GetMonoCrossDesktopDirName(platform, arch);
ExecuteCompiler(FindCrossCompiler(compilerDirPath), compilerArgs, bclDir);
@@ -289,7 +298,7 @@ MONO_AOT_MODE_LAST = 1000,
// Archive the AOT object files into a static library
var arFilePathsForAllArchs = new List<string>();
- string projectAssemblyName = GodotSharpEditor.ProjectAssemblyName;
+ string projectAssemblyName = GodotSharpDirs.ProjectAssemblyName;
foreach (var archPathsPair in objFilePathsForiOSArch)
{
@@ -432,9 +441,9 @@ MONO_AOT_MODE_LAST = 1000,
var androidToolPrefixes = new Dictionary<string, string>
{
- ["armeabi-v7a"] = "arm-linux-androideabi-",
- ["arm64-v8a"] = "aarch64-linux-android-",
- ["x86"] = "i686-linux-android-",
+ ["arm32"] = "arm-linux-androideabi-",
+ ["arm64"] = "aarch64-linux-android-",
+ ["x86_32"] = "i686-linux-android-",
["x86_64"] = "x86_64-linux-android-"
};
@@ -547,9 +556,9 @@ MONO_AOT_MODE_LAST = 1000,
{
var androidAbis = new[]
{
- "armeabi-v7a",
- "arm64-v8a",
- "x86",
+ "arm32",
+ "arm64",
+ "x86_32",
"x86_64"
};
@@ -560,9 +569,9 @@ MONO_AOT_MODE_LAST = 1000,
{
var abiArchs = new Dictionary<string, string>
{
- ["armeabi-v7a"] = "armv7",
- ["arm64-v8a"] = "aarch64-v8a",
- ["x86"] = "i686",
+ ["arm32"] = "armv7",
+ ["arm64"] = "aarch64-v8a",
+ ["x86_32"] = "i686",
["x86_64"] = "x86_64"
};
@@ -571,31 +580,25 @@ MONO_AOT_MODE_LAST = 1000,
return $"{arch}-linux-android";
}
- private static string GetMonoCrossDesktopDirName(string platform, string bits)
+ private static string GetMonoCrossDesktopDirName(string platform, string arch)
{
switch (platform)
{
case OS.Platforms.Windows:
case OS.Platforms.UWP:
{
- string arch = bits == "64" ? "x86_64" : "i686";
return $"windows-{arch}";
}
case OS.Platforms.MacOS:
{
- Debug.Assert(bits == null || bits == "64");
- string arch = "x86_64";
return $"{platform}-{arch}";
}
case OS.Platforms.LinuxBSD:
- case OS.Platforms.Server:
{
- string arch = bits == "64" ? "x86_64" : "i686";
return $"linux-{arch}";
}
case OS.Platforms.Haiku:
{
- string arch = bits == "64" ? "x86_64" : "i686";
return $"{platform}-{arch}";
}
default:
diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
index cca18a2a1f..e1b5530b93 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
@@ -4,11 +4,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
-using System.Runtime.CompilerServices;
using GodotTools.Build;
using GodotTools.Core;
using GodotTools.Internals;
-using JetBrains.Annotations;
using static GodotTools.Internals.Globals;
using Directory = GodotTools.Utils.Directory;
using File = GodotTools.Utils.File;
@@ -17,61 +15,13 @@ using Path = System.IO.Path;
namespace GodotTools.Export
{
- public class ExportPlugin : EditorExportPlugin
+ public partial class ExportPlugin : EditorExportPlugin
{
- [Flags]
- private enum I18NCodesets : long
- {
- None = 0,
- CJK = 1,
- MidEast = 2,
- Other = 4,
- Rare = 8,
- West = 16,
- All = CJK | MidEast | Other | Rare | West
- }
-
- private string _maybeLastExportError;
-
- private void AddI18NAssemblies(Godot.Collections.Dictionary<string, string> assemblies, string bclDir)
- {
- var codesets = (I18NCodesets)ProjectSettings.GetSetting("mono/export/i18n_codesets");
-
- if (codesets == I18NCodesets.None)
- return;
-
- void AddI18NAssembly(string name) => assemblies.Add(name, Path.Combine(bclDir, $"{name}.dll"));
-
- AddI18NAssembly("I18N");
-
- if ((codesets & I18NCodesets.CJK) != 0)
- AddI18NAssembly("I18N.CJK");
- if ((codesets & I18NCodesets.MidEast) != 0)
- AddI18NAssembly("I18N.MidEast");
- if ((codesets & I18NCodesets.Other) != 0)
- AddI18NAssembly("I18N.Other");
- if ((codesets & I18NCodesets.Rare) != 0)
- AddI18NAssembly("I18N.Rare");
- if ((codesets & I18NCodesets.West) != 0)
- AddI18NAssembly("I18N.West");
- }
-
public void RegisterExportSettings()
{
// TODO: These would be better as export preset options, but that doesn't seem to be supported yet
GlobalDef("mono/export/include_scripts_content", false);
- GlobalDef("mono/export/export_assemblies_inside_pck", true);
-
- GlobalDef("mono/export/i18n_codesets", I18NCodesets.All);
-
- ProjectSettings.AddPropertyInfo(new Godot.Collections.Dictionary
- {
- ["type"] = Variant.Type.Int,
- ["name"] = "mono/export/i18n_codesets",
- ["hint"] = PropertyHint.Flags,
- ["hint_string"] = "CJK,MidEast,Other,Rare,West"
- });
GlobalDef("mono/export/aot/enabled", false);
GlobalDef("mono/export/aot/full_aot", false);
@@ -85,11 +35,7 @@ namespace GodotTools.Export
GlobalDef("mono/export/aot/android_toolchain_path", "");
}
- private void AddFile(string srcPath, string dstPath, bool remap = false)
- {
- // Add file to the PCK
- AddFile(dstPath.Replace("\\", "/"), File.ReadAllBytes(srcPath), remap);
- }
+ private string _maybeLastExportError;
// With this method we can override how a file is exported in the PCK
public override void _ExportFile(string path, string type, string[] features)
@@ -100,7 +46,9 @@ namespace GodotTools.Export
return;
if (Path.GetExtension(path) != Internal.CSharpLanguageExtension)
- throw new ArgumentException($"Resource of type {Internal.CSharpLanguageType} has an invalid file extension: {path}", nameof(path));
+ throw new ArgumentException(
+ $"Resource of type {Internal.CSharpLanguageType} has an invalid file extension: {path}",
+ nameof(path));
// TODO What if the source file is not part of the game's C# project
@@ -152,159 +100,93 @@ namespace GodotTools.Export
if (!DeterminePlatformFromFeatures(features, out string platform))
throw new NotSupportedException("Target platform not supported");
+ if (!new[] { OS.Platforms.Windows, OS.Platforms.LinuxBSD, OS.Platforms.MacOS }
+ .Contains(platform))
+ {
+ throw new NotImplementedException("Target platform not yet implemented");
+ }
+
string outputDir = new FileInfo(path).Directory?.FullName ??
- throw new FileNotFoundException("Base directory not found");
+ throw new FileNotFoundException("Output base directory not found");
string buildConfig = isDebug ? "ExportDebug" : "ExportRelease";
- if (!BuildManager.BuildProjectBlocking(buildConfig, platform: platform))
- throw new Exception("Failed to build project");
+ // TODO: This works for now, as we only implemented support for x86 family desktop so far, but it needs to be fixed
+ string arch = features.Contains("64") ? "x86_64" : "x86";
- // Add dependency assemblies
+ string ridOS = DetermineRuntimeIdentifierOS(platform);
+ string ridArch = DetermineRuntimeIdentifierArch(arch);
+ string runtimeIdentifier = $"{ridOS}-{ridArch}";
- var assemblies = new Godot.Collections.Dictionary<string, string>();
+ // Create temporary publish output directory
- string projectDllName = GodotSharpEditor.ProjectAssemblyName;
- string projectDllSrcDir = Path.Combine(GodotSharpDirs.ResTempAssembliesBaseDir, buildConfig);
- string projectDllSrcPath = Path.Combine(projectDllSrcDir, $"{projectDllName}.dll");
+ string publishOutputTempDir = Path.Combine(Path.GetTempPath(), "godot-publish-dotnet",
+ $"{Process.GetCurrentProcess().Id}-{buildConfig}-{runtimeIdentifier}");
- assemblies[projectDllName] = projectDllSrcPath;
+ if (!Directory.Exists(publishOutputTempDir))
+ Directory.CreateDirectory(publishOutputTempDir);
- string bclDir = DeterminePlatformBclDir(platform);
+ // Execute dotnet publish
- if (platform == OS.Platforms.Android)
+ if (!BuildManager.PublishProjectBlocking(buildConfig, platform,
+ runtimeIdentifier, publishOutputTempDir))
{
- string godotAndroidExtProfileDir = GetBclProfileDir("godot_android_ext");
- string monoAndroidAssemblyPath = Path.Combine(godotAndroidExtProfileDir, "Mono.Android.dll");
+ throw new Exception("Failed to build project");
+ }
- if (!File.Exists(monoAndroidAssemblyPath))
- throw new FileNotFoundException("Assembly not found: 'Mono.Android'", monoAndroidAssemblyPath);
+ string soExt = ridOS switch
+ {
+ OS.DotNetOS.Win or OS.DotNetOS.Win10 => "dll",
+ OS.DotNetOS.OSX or OS.DotNetOS.iOS => "dylib",
+ _ => "so"
+ };
- assemblies["Mono.Android"] = monoAndroidAssemblyPath;
- }
- else if (platform == OS.Platforms.HTML5)
+ if (!File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.dll"))
+ // NativeAOT shared library output
+ && !File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.{soExt}")))
{
- // Ideally these would be added automatically since they're referenced by the wasm BCL assemblies.
- // However, at least in the case of 'WebAssembly.Net.Http' for some reason the BCL assemblies
- // reference a different version even though the assembly is the same, for some weird reason.
-
- var wasmFrameworkAssemblies = new[] { "WebAssembly.Bindings", "WebAssembly.Net.WebSockets" };
-
- foreach (string thisWasmFrameworkAssemblyName in wasmFrameworkAssemblies)
- {
- string thisWasmFrameworkAssemblyPath = Path.Combine(bclDir, thisWasmFrameworkAssemblyName + ".dll");
- if (!File.Exists(thisWasmFrameworkAssemblyPath))
- throw new FileNotFoundException($"Assembly not found: '{thisWasmFrameworkAssemblyName}'", thisWasmFrameworkAssemblyPath);
- assemblies[thisWasmFrameworkAssemblyName] = thisWasmFrameworkAssemblyPath;
- }
-
- // Assemblies that can have a different name in a newer version. Newer version must come first and it has priority.
- (string newName, string oldName)[] wasmFrameworkAssembliesOneOf = new[]
- {
- ("System.Net.Http.WebAssemblyHttpHandler", "WebAssembly.Net.Http")
- };
-
- foreach (var thisWasmFrameworkAssemblyName in wasmFrameworkAssembliesOneOf)
- {
- string thisWasmFrameworkAssemblyPath = Path.Combine(bclDir, thisWasmFrameworkAssemblyName.newName + ".dll");
- if (File.Exists(thisWasmFrameworkAssemblyPath))
- {
- assemblies[thisWasmFrameworkAssemblyName.newName] = thisWasmFrameworkAssemblyPath;
- }
- else
- {
- thisWasmFrameworkAssemblyPath = Path.Combine(bclDir, thisWasmFrameworkAssemblyName.oldName + ".dll");
- if (!File.Exists(thisWasmFrameworkAssemblyPath))
- {
- throw new FileNotFoundException("Expected one of the following assemblies but none were found: " +
- $"'{thisWasmFrameworkAssemblyName.newName}' / '{thisWasmFrameworkAssemblyName.oldName}'",
- thisWasmFrameworkAssemblyPath);
- }
-
- assemblies[thisWasmFrameworkAssemblyName.oldName] = thisWasmFrameworkAssemblyPath;
- }
- }
+ throw new NotSupportedException(
+ "Publish succeeded but project assembly not found in the output directory");
}
- var initialAssemblies = assemblies.Duplicate();
- internal_GetExportedAssemblyDependencies(initialAssemblies, buildConfig, bclDir, assemblies);
-
- AddI18NAssemblies(assemblies, bclDir);
-
- string outputDataDir = null;
+ // Copy all files from the dotnet publish output directory to
+ // a data directory next to the Godot output executable.
- if (PlatformHasTemplateDir(platform))
- outputDataDir = ExportDataDirectory(features, platform, isDebug, outputDir);
+ string outputDataDir = Path.Combine(outputDir, DetermineDataDirNameForProject());
- string apiConfig = isDebug ? "Debug" : "Release";
- string resAssembliesDir = Path.Combine(GodotSharpDirs.ResAssembliesBaseDir, apiConfig);
+ if (Directory.Exists(outputDataDir))
+ Directory.Delete(outputDataDir, recursive: true); // Clean first
- bool assembliesInsidePck = (bool)ProjectSettings.GetSetting("mono/export/export_assemblies_inside_pck") || outputDataDir == null;
+ Directory.CreateDirectory(outputDataDir);
- if (!assembliesInsidePck)
+ foreach (string dir in Directory.GetDirectories(publishOutputTempDir, "*", SearchOption.AllDirectories))
{
- string outputDataGameAssembliesDir = Path.Combine(outputDataDir, "Assemblies");
- if (!Directory.Exists(outputDataGameAssembliesDir))
- Directory.CreateDirectory(outputDataGameAssembliesDir);
+ Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(publishOutputTempDir.Length + 1)));
}
- foreach (var assembly in assemblies)
+ foreach (string file in Directory.GetFiles(publishOutputTempDir, "*", SearchOption.AllDirectories))
{
- void AddToAssembliesDir(string fileSrcPath)
- {
- if (assembliesInsidePck)
- {
- string fileDstPath = Path.Combine(resAssembliesDir, fileSrcPath.GetFile());
- AddFile(fileSrcPath, fileDstPath);
- }
- else
- {
- Debug.Assert(outputDataDir != null);
- string fileDstPath = Path.Combine(outputDataDir, "Assemblies", fileSrcPath.GetFile());
- File.Copy(fileSrcPath, fileDstPath);
- }
- }
-
- string assemblySrcPath = assembly.Value;
-
- string assemblyPathWithoutExtension = Path.ChangeExtension(assemblySrcPath, null);
- string pdbSrcPath = assemblyPathWithoutExtension + ".pdb";
-
- AddToAssembliesDir(assemblySrcPath);
-
- if (File.Exists(pdbSrcPath))
- AddToAssembliesDir(pdbSrcPath);
+ File.Copy(file, Path.Combine(outputDataDir, file.Substring(publishOutputTempDir.Length + 1)));
}
+ }
- // AOT compilation
- bool aotEnabled = platform == OS.Platforms.iOS || (bool)ProjectSettings.GetSetting("mono/export/aot/enabled");
+ private string DetermineRuntimeIdentifierOS(string platform)
+ => OS.DotNetOSPlatformMap[platform];
- if (aotEnabled)
+ private string DetermineRuntimeIdentifierArch(string arch)
+ {
+ return arch switch
{
- string aotToolchainPath = null;
-
- if (platform == OS.Platforms.Android)
- aotToolchainPath = (string)ProjectSettings.GetSetting("mono/export/aot/android_toolchain_path");
-
- if (aotToolchainPath == string.Empty)
- aotToolchainPath = null; // Don't risk it being used as current working dir
-
- // TODO: LLVM settings are hard-coded and disabled for now
- var aotOpts = new AotOptions
- {
- EnableLLVM = false,
- LLVMOnly = false,
- LLVMPath = "",
- LLVMOutputPath = "",
- FullAot = platform == OS.Platforms.iOS || (bool)(ProjectSettings.GetSetting("mono/export/aot/full_aot") ?? false),
- UseInterpreter = (bool)ProjectSettings.GetSetting("mono/export/aot/use_interpreter"),
- ExtraAotOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_aot_options") ?? Array.Empty<string>(),
- ExtraOptimizerOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_optimizer_options") ?? Array.Empty<string>(),
- ToolchainPath = aotToolchainPath
- };
-
- AotBuilder.CompileAssemblies(this, aotOpts, features, platform, isDebug, bclDir, outputDir, outputDataDir, assemblies);
- }
+ "x86" => "x86",
+ "x86_32" => "x86",
+ "x64" => "x64",
+ "x86_64" => "x64",
+ "armeabi-v7a" => "arm",
+ "arm64-v8a" => "arm64",
+ "armv7" => "arm",
+ "arm64" => "arm64",
+ _ => throw new ArgumentOutOfRangeException(nameof(arch), arch, "Unexpected architecture")
+ };
}
public override void _ExportEnd()
@@ -316,8 +198,10 @@ namespace GodotTools.Export
if (Directory.Exists(aotTempDir))
Directory.Delete(aotTempDir, recursive: true);
- // TODO: Just a workaround until the export plugins can be made to abort with errors
- if (!string.IsNullOrEmpty(_maybeLastExportError)) // Check empty as well, because it's set to empty after hot-reloading
+ // TODO: The following is just a workaround until the export plugins can be made to abort with errors
+
+ // We check for empty as well, because it's set to empty after hot-reloading
+ if (!string.IsNullOrEmpty(_maybeLastExportError))
{
string lastExportError = _maybeLastExportError;
_maybeLastExportError = null;
@@ -326,69 +210,11 @@ namespace GodotTools.Export
}
}
- [NotNull]
- private static string ExportDataDirectory(string[] features, string platform, bool isDebug, string outputDir)
- {
- string target = isDebug ? "release_debug" : "release";
-
- // NOTE: Bits is ok for now as all platforms with a data directory only have one or two architectures.
- // However, this may change in the future if we add arm linux or windows desktop templates.
- string bits = features.Contains("64") ? "64" : "32";
-
- string TemplateDirName() => $"data.mono.{platform}.{bits}.{target}";
-
- string templateDirPath = Path.Combine(Internal.FullExportTemplatesDir, TemplateDirName());
- bool validTemplatePathFound = true;
-
- if (!Directory.Exists(templateDirPath))
- {
- validTemplatePathFound = false;
-
- if (isDebug)
- {
- target = "debug"; // Support both 'release_debug' and 'debug' for the template data directory name
- templateDirPath = Path.Combine(Internal.FullExportTemplatesDir, TemplateDirName());
- validTemplatePathFound = true;
-
- if (!Directory.Exists(templateDirPath))
- validTemplatePathFound = false;
- }
- }
-
- if (!validTemplatePathFound)
- throw new FileNotFoundException("Data template directory not found", templateDirPath);
-
- string outputDataDir = Path.Combine(outputDir, DetermineDataDirNameForProject());
-
- if (Directory.Exists(outputDataDir))
- Directory.Delete(outputDataDir, recursive: true); // Clean first
-
- Directory.CreateDirectory(outputDataDir);
-
- foreach (string dir in Directory.GetDirectories(templateDirPath, "*", SearchOption.AllDirectories))
- {
- Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(templateDirPath.Length + 1)));
- }
-
- foreach (string file in Directory.GetFiles(templateDirPath, "*", SearchOption.AllDirectories))
- {
- File.Copy(file, Path.Combine(outputDataDir, file.Substring(templateDirPath.Length + 1)));
- }
-
- return outputDataDir;
- }
-
- private static bool PlatformHasTemplateDir(string platform)
- {
- // macOS export templates are contained in a zip, so we place our custom template inside it and let Godot do the rest.
- return !new[] { OS.Platforms.MacOS, OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5 }.Contains(platform);
- }
-
private static bool DeterminePlatformFromFeatures(IEnumerable<string> features, out string platform)
{
foreach (var feature in features)
{
- if (OS.PlatformNameMap.TryGetValue(feature, out platform))
+ if (OS.PlatformFeatureMap.TryGetValue(feature, out platform))
return true;
}
@@ -396,87 +222,11 @@ namespace GodotTools.Export
return false;
}
- private static string GetBclProfileDir(string profile)
- {
- string templatesDir = Internal.FullExportTemplatesDir;
- return Path.Combine(templatesDir, "bcl", profile);
- }
-
- private static string DeterminePlatformBclDir(string platform)
- {
- string templatesDir = Internal.FullExportTemplatesDir;
- string platformBclDir = Path.Combine(templatesDir, "bcl", platform);
-
- if (!File.Exists(Path.Combine(platformBclDir, "mscorlib.dll")))
- {
- string profile = DeterminePlatformBclProfile(platform);
- platformBclDir = Path.Combine(templatesDir, "bcl", profile);
-
- if (!File.Exists(Path.Combine(platformBclDir, "mscorlib.dll")))
- {
- if (PlatformRequiresCustomBcl(platform))
- throw new FileNotFoundException($"Missing BCL (Base Class Library) for platform: {platform}");
-
- platformBclDir = typeof(object).Assembly.Location.GetBaseDir(); // Use the one we're running on
- }
- }
-
- return platformBclDir;
- }
-
- /// <summary>
- /// Determines whether the BCL bundled with the Godot editor can be used for the target platform,
- /// or if it requires a custom BCL that must be distributed with the export templates.
- /// </summary>
- private static bool PlatformRequiresCustomBcl(string platform)
- {
- if (new[] { OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5 }.Contains(platform))
- return true;
-
- // The 'net_4_x' BCL is not compatible between Windows and the other platforms.
- // We use the names 'net_4_x_win' and 'net_4_x' to differentiate between the two.
-
- bool isWinOrUwp = new[]
- {
- OS.Platforms.Windows,
- OS.Platforms.UWP
- }.Contains(platform);
-
- return OS.IsWindows ? !isWinOrUwp : isWinOrUwp;
- }
-
- private static string DeterminePlatformBclProfile(string platform)
- {
- switch (platform)
- {
- case OS.Platforms.Windows:
- case OS.Platforms.UWP:
- return "net_4_x_win";
- case OS.Platforms.MacOS:
- case OS.Platforms.LinuxBSD:
- case OS.Platforms.Server:
- case OS.Platforms.Haiku:
- return "net_4_x";
- case OS.Platforms.Android:
- return "monodroid";
- case OS.Platforms.iOS:
- return "monotouch";
- case OS.Platforms.HTML5:
- return "wasm";
- default:
- throw new NotSupportedException($"Platform not supported: {platform}");
- }
- }
-
private static string DetermineDataDirNameForProject()
{
string appName = (string)ProjectSettings.GetSetting("application/config/name");
string appNameSafe = appName.ToSafeDirName();
return $"data_{appNameSafe}";
}
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_GetExportedAssemblyDependencies(Godot.Collections.Dictionary<string, string> initialAssemblies,
- string buildConfig, string customBclDir, Godot.Collections.Dictionary<string, string> dependencyAssemblies);
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
index b39c3d1c0d..0aca60dad4 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
@@ -13,13 +13,14 @@ using GodotTools.Internals;
using GodotTools.ProjectEditor;
using JetBrains.Annotations;
using static GodotTools.Internals.Globals;
+using Environment = System.Environment;
using File = GodotTools.Utils.File;
using OS = GodotTools.Utils.OS;
using Path = System.IO.Path;
namespace GodotTools
{
- public class GodotSharpEditor : EditorPlugin, ISerializationListener
+ public partial class GodotSharpEditor : EditorPlugin, ISerializationListener
{
private EditorSettings _editorSettings;
@@ -39,28 +40,27 @@ namespace GodotTools
public bool SkipBuildBeforePlaying { get; set; } = false;
- public static string ProjectAssemblyName
+ [UsedImplicitly]
+ private bool CreateProjectSolutionIfNeeded()
{
- get
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath) || !File.Exists(GodotSharpDirs.ProjectCsProjPath))
{
- string projectAssemblyName = (string)ProjectSettings.GetSetting("application/config/name");
- projectAssemblyName = projectAssemblyName.ToSafeDirName();
- if (string.IsNullOrEmpty(projectAssemblyName))
- projectAssemblyName = "UnnamedProject";
- return projectAssemblyName;
+ return CreateProjectSolution();
}
+
+ return true;
}
private bool CreateProjectSolution()
{
- using (var pr = new EditorProgress("create_csharp_solution", "Generating solution...".TTR(), 3))
+ using (var pr = new EditorProgress("create_csharp_solution", "Generating solution...".TTR(), 2))
{
pr.Step("Generating C# project...".TTR());
string resourceDir = ProjectSettings.GlobalizePath("res://");
string path = resourceDir;
- string name = ProjectAssemblyName;
+ string name = GodotSharpDirs.ProjectAssemblyName;
string guid = CsProjOperations.GenerateGameProject(path, name);
@@ -75,7 +75,7 @@ namespace GodotTools
{
Guid = guid,
PathRelativeToSolution = name + ".csproj",
- Configs = new List<string> {"Debug", "ExportDebug", "ExportRelease"}
+ Configs = new List<string> { "Debug", "ExportDebug", "ExportRelease" }
};
solution.AddNewProject(name, projectInfo);
@@ -90,24 +90,6 @@ namespace GodotTools
return false;
}
- pr.Step("Updating Godot API assemblies...".TTR());
-
- string debugApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Debug");
-
- if (!string.IsNullOrEmpty(debugApiAssembliesError))
- {
- ShowErrorDialog("Failed to update the Godot API assemblies: " + debugApiAssembliesError);
- return false;
- }
-
- string releaseApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Release");
-
- if (!string.IsNullOrEmpty(releaseApiAssembliesError))
- {
- ShowErrorDialog("Failed to update the Godot API assemblies: " + releaseApiAssembliesError);
- return false;
- }
-
pr.Step("Done".TTR());
// Here, after all calls to progress_task_step
@@ -141,7 +123,8 @@ namespace GodotTools
try
{
string fallbackFolder = NuGetUtils.GodotFallbackFolderPath;
- NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, fallbackFolder);
+ NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName,
+ fallbackFolder);
NuGetUtils.AddBundledPackagesToFallbackFolder(fallbackFolder);
}
catch (Exception e)
@@ -167,13 +150,6 @@ namespace GodotTools
Instance.MSBuildPanel.BuildSolution();
}
- public override void _Ready()
- {
- base._Ready();
-
- MSBuildPanel.BuildOutputView.BuildStateChanged += BuildStateChanged;
- }
-
private enum MenuOptions
{
CreateSln,
@@ -197,7 +173,7 @@ namespace GodotTools
[UsedImplicitly]
public Error OpenInExternalEditor(Script script, int line, int col)
{
- var editorId = (ExternalEditorId)_editorSettings.GetSetting("mono/editor/external_editor");
+ var editorId = (ExternalEditorId)(int)_editorSettings.GetSetting("mono/editor/external_editor");
switch (editorId)
{
@@ -219,13 +195,15 @@ namespace GodotTools
try
{
if (Godot.OS.IsStdoutVerbose())
- Console.WriteLine($"Running: \"{command}\" {string.Join(" ", args.Select(a => $"\"{a}\""))}");
+ Console.WriteLine(
+ $"Running: \"{command}\" {string.Join(" ", args.Select(a => $"\"{a}\""))}");
OS.RunProcess(command, args);
}
catch (Exception e)
{
- GD.PushError($"Error when trying to run code editor: VisualStudio. Exception message: '{e.Message}'");
+ GD.PushError(
+ $"Error when trying to run code editor: VisualStudio. Exception message: '{e.Message}'");
}
break;
@@ -347,7 +325,8 @@ namespace GodotTools
[UsedImplicitly]
public bool OverridesExternalEditor()
{
- return (ExternalEditorId)_editorSettings.GetSetting("mono/editor/external_editor") != ExternalEditorId.None;
+ return (ExternalEditorId)(int)_editorSettings.GetSetting("mono/editor/external_editor") !=
+ ExternalEditorId.None;
}
public override bool _Build()
@@ -368,7 +347,7 @@ namespace GodotTools
// NOTE: The order in which changes are made to the project is important
// Migrate to MSBuild project Sdks style if using the old style
- ProjectUtils.MigrateToProjectSdksStyle(msbuildProject, ProjectAssemblyName);
+ ProjectUtils.MigrateToProjectSdksStyle(msbuildProject, GodotSharpDirs.ProjectAssemblyName);
ProjectUtils.EnsureGodotSdkIsUpToDate(msbuildProject);
@@ -400,18 +379,49 @@ namespace GodotTools
throw new InvalidOperationException();
Instance = this;
+ var dotNetSdkSearchVersion = Environment.Version;
+
+ // First we try to find the .NET Sdk ourselves to make sure we get the
+ // correct version first (`RegisterDefaults` always picks the latest).
+ if (DotNetFinder.TryFindDotNetSdk(dotNetSdkSearchVersion, out var sdkVersion, out string sdkPath))
+ {
+ if (Godot.OS.IsStdoutVerbose())
+ Console.WriteLine($"Found .NET Sdk version '{sdkVersion}': {sdkPath}");
+
+ ProjectUtils.MSBuildLocatorRegisterMSBuildPath(sdkPath);
+ }
+ else
+ {
+ try
+ {
+ ProjectUtils.MSBuildLocatorRegisterDefaults(out sdkVersion, out sdkPath);
+ if (Godot.OS.IsStdoutVerbose())
+ Console.WriteLine($"Found .NET Sdk version '{sdkVersion}': {sdkPath}");
+ }
+ catch (InvalidOperationException e)
+ {
+ if (Godot.OS.IsStdoutVerbose())
+ GD.PrintErr(e.ToString());
+ GD.PushError($".NET Sdk not found. The required version is '{dotNetSdkSearchVersion}'.");
+ }
+ }
+
var editorInterface = GetEditorInterface();
var editorBaseControl = editorInterface.GetBaseControl();
_editorSettings = editorInterface.GetEditorSettings();
+ GodotSharpDirs.RegisterProjectSettings();
+
_errorDialog = new AcceptDialog();
editorBaseControl.AddChild(_errorDialog);
MSBuildPanel = new MSBuildPanel();
+ MSBuildPanel.Ready += () =>
+ MSBuildPanel.BuildOutputView.BuildStateChanged += BuildStateChanged;
_bottomPanelBtn = AddControlToBottomPanel(MSBuildPanel, "MSBuild".TTR());
- AddChild(new HotReloadAssemblyWatcher {Name = "HotReloadAssemblyWatcher"});
+ AddChild(new HotReloadAssemblyWatcher { Name = "HotReloadAssemblyWatcher" });
_menuPopup = new PopupMenu();
_menuPopup.Hide();
@@ -472,9 +482,9 @@ namespace GodotTools
_editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary
{
- ["type"] = Variant.Type.Int,
+ ["type"] = (int)Variant.Type.Int,
["name"] = "mono/editor/external_editor",
- ["hint"] = PropertyHint.Enum,
+ ["hint"] = (int)PropertyHint.Enum,
["hint_string"] = settingsHintStr
});
@@ -487,7 +497,8 @@ namespace GodotTools
try
{
// At startup we make sure NuGet.Config files have our Godot NuGet fallback folder included
- NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, NuGetUtils.GodotFallbackFolderPath);
+ NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName,
+ NuGetUtils.GodotFallbackFolderPath);
}
catch (Exception e)
{
@@ -503,20 +514,23 @@ namespace GodotTools
protected override void Dispose(bool disposing)
{
- base.Dispose(disposing);
-
- if (_exportPluginWeak != null)
+ if (disposing)
{
- // We need to dispose our export plugin before the editor destroys EditorSettings.
- // Otherwise, if the GC disposes it at a later time, EditorExportPlatformAndroid
- // will be freed after EditorSettings already was, and its device polling thread
- // will try to access the EditorSettings singleton, resulting in null dereferencing.
- (_exportPluginWeak.GetRef() as ExportPlugin)?.Dispose();
+ if (IsInstanceValid(_exportPluginWeak))
+ {
+ // We need to dispose our export plugin before the editor destroys EditorSettings.
+ // Otherwise, if the GC disposes it at a later time, EditorExportPlatformAndroid
+ // will be freed after EditorSettings already was, and its device polling thread
+ // will try to access the EditorSettings singleton, resulting in null dereferencing.
+ (_exportPluginWeak.GetRef().AsGodotObject() as ExportPlugin)?.Dispose();
+
+ _exportPluginWeak.Dispose();
+ }
- _exportPluginWeak.Dispose();
+ GodotIdeManager?.Dispose();
}
- GodotIdeManager?.Dispose();
+ base.Dispose(disposing);
}
public void OnBeforeSerialize()
@@ -533,8 +547,10 @@ namespace GodotTools
public static GodotSharpEditor Instance { get; private set; }
[UsedImplicitly]
- private GodotSharpEditor()
+ private static IntPtr InternalCreateInstance(IntPtr unmanagedCallbacks, int unmanagedCallbacksSize)
{
+ Internal.Initialize(unmanagedCallbacks, unmanagedCallbacksSize);
+ return new GodotSharpEditor().NativeInstance;
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
index f1d45463c5..30525ba04a 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
@@ -1,14 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ProjectGuid>{27B00618-A6F2-4828-B922-05CAEB08C286}</ProjectGuid>
- <TargetFramework>net472</TargetFramework>
- <LangVersion>7.2</LangVersion>
+ <TargetFramework>net6.0</TargetFramework>
+ <EnableDynamicLoading>true</EnableDynamicLoading>
+ <LangVersion>10</LangVersion>
<!-- The Godot editor uses the Debug Godot API assemblies -->
<GodotApiConfiguration>Debug</GodotApiConfiguration>
<GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath>
<GodotOutputDataDir>$(GodotSourceRootPath)/bin/GodotSharp</GodotOutputDataDir>
<GodotApiAssembliesDir>$(GodotOutputDataDir)/Api/$(GodotApiConfiguration)</GodotApiAssembliesDir>
+ <ProduceReferenceAssembly>false</ProduceReferenceAssembly>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
+ <!-- Needed for our source generators to work despite this not being a Godot game project -->
+ <PropertyGroup>
+ <IsGodotToolsProject>true</IsGodotToolsProject>
+ </PropertyGroup>
+ <ItemGroup>
+ <CompilerVisibleProperty Include="IsGodotToolsProject" />
+ </ItemGroup>
<PropertyGroup Condition=" Exists('$(GodotApiAssembliesDir)/GodotSharp.dll') ">
<!-- The project is part of the Godot source tree -->
<!-- Use the Godot source tree output folder instead of '$(ProjectDir)/bin' -->
@@ -20,6 +30,8 @@
<PackageReference Include="JetBrains.Annotations" Version="2019.1.3.0" ExcludeAssets="runtime" PrivateAssets="all" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
+ <!-- For RiderPathLocator -->
+ <PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
<Reference Include="GodotSharp">
<HintPath>$(GodotApiAssembliesDir)/GodotSharp.dll</HintPath>
<Private>False</Private>
@@ -30,6 +42,10 @@
</Reference>
</ItemGroup>
<ItemGroup>
+ <ProjectReference Include="..\..\Godot.NET.Sdk\Godot.SourceGenerators\Godot.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
+ <ProjectReference Include="..\..\..\glue\GodotSharp\Godot.SourceGenerators.Internal\Godot.SourceGenerators.Internal.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
+ </ItemGroup>
+ <ItemGroup>
<ProjectReference Include="..\GodotTools.BuildLogger\GodotTools.BuildLogger.csproj" />
<ProjectReference Include="..\GodotTools.IdeMessaging\GodotTools.IdeMessaging.csproj" />
<ProjectReference Include="..\GodotTools.ProjectEditor\GodotTools.ProjectEditor.csproj" />
diff --git a/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
index dd05f28af0..260d13a714 100644
--- a/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
@@ -1,10 +1,11 @@
using Godot;
using GodotTools.Internals;
+using JetBrains.Annotations;
using static GodotTools.Internals.Globals;
namespace GodotTools
{
- public class HotReloadAssemblyWatcher : Node
+ public partial class HotReloadAssemblyWatcher : Node
{
private Timer _watchTimer;
@@ -25,6 +26,7 @@ namespace GodotTools
Internal.ReloadAssemblies(softReload: false);
}
+ [UsedImplicitly]
public void RestartTimer()
{
_watchTimer.Stop();
@@ -38,7 +40,7 @@ namespace GodotTools
_watchTimer = new Timer
{
OneShot = false,
- WaitTime = (float)EditorDef("mono/assembly_watch_interval_sec", 0.5)
+ WaitTime = 0.5f
};
_watchTimer.Timeout += TimerTimeout;
AddChild(_watchTimer);
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs
index 23339fe50b..95b60aded1 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs
@@ -8,7 +8,7 @@ using GodotTools.Internals;
namespace GodotTools.Ides
{
- public sealed class GodotIdeManager : Node, ISerializationListener
+ public sealed partial class GodotIdeManager : Node, ISerializationListener
{
private MessagingServer _messagingServer;
@@ -76,7 +76,7 @@ namespace GodotTools.Ides
public async Task<EditorPick?> LaunchIdeAsync(int millisecondsTimeout = 10000)
{
- var editorId = (ExternalEditorId)GodotSharpEditor.Instance.GetEditorInterface()
+ var editorId = (ExternalEditorId)(int)GodotSharpEditor.Instance.GetEditorInterface()
.GetEditorSettings().GetSetting("mono/editor/external_editor");
string editorIdentity = GetExternalEditorIdentity(editorId);
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs
index 71055f0125..4caab035de 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs
@@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
+using System.Runtime.Versioning;
using Godot;
-using JetBrains.Annotations;
using Microsoft.Win32;
using Newtonsoft.Json;
using Directory = System.IO.Directory;
@@ -113,6 +114,7 @@ namespace GodotTools.Ides.Rider
return installInfos.ToArray();
}
+ [SupportedOSPlatform("windows")]
private static RiderInfo[] CollectRiderInfosWindows()
{
var installInfos = new List<RiderInfo>();
@@ -217,6 +219,7 @@ namespace GodotTools.Ides.Rider
throw new Exception("Unknown OS.");
}
+ [SupportedOSPlatform("windows")]
private static void CollectPathsFromRegistry(string registryKey, List<string> installPaths)
{
using (var key = Registry.CurrentUser.OpenSubKey(registryKey))
@@ -229,6 +232,7 @@ namespace GodotTools.Ides.Rider
}
}
+ [SupportedOSPlatform("windows")]
private static void CollectPathsFromRegistry(List<string> installPaths, RegistryKey key)
{
if (key == null) return;
@@ -324,7 +328,7 @@ namespace GodotTools.Ides.Rider
{
public string install_location;
- [CanBeNull]
+ [return: MaybeNull]
public static string GetInstallLocationFromJson(string json)
{
try
@@ -378,7 +382,7 @@ namespace GodotTools.Ides.Rider
public string version;
public string versionSuffix;
- [CanBeNull]
+ [return: MaybeNull]
internal static ProductInfo GetProductInfo(string json)
{
try
@@ -402,7 +406,7 @@ namespace GodotTools.Ides.Rider
// ReSharper disable once InconsistentNaming
public ActiveApplication active_application;
- [CanBeNull]
+ [return: MaybeNull]
public static string GetLatestBuildFromJson(string json)
{
try
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs
index 3440eb701c..60602a5847 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs
@@ -22,7 +22,7 @@ namespace GodotTools.Ides.Rider
public static void Initialize()
{
var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
- var editor = (ExternalEditorId)editorSettings.GetSetting("mono/editor/external_editor");
+ var editor = (ExternalEditorId)(int)editorSettings.GetSetting("mono/editor/external_editor");
if (editor == ExternalEditorId.Rider)
{
if (!editorSettings.HasSetting(EditorPathSettingName))
@@ -30,9 +30,9 @@ namespace GodotTools.Ides.Rider
Globals.EditorDef(EditorPathSettingName, "Optional");
editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary
{
- ["type"] = Variant.Type.String,
+ ["type"] = (int)Variant.Type.String,
["name"] = EditorPathSettingName,
- ["hint"] = PropertyHint.File,
+ ["hint"] = (int)PropertyHint.File,
["hint_string"] = ""
});
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs
index 70ba7c733a..8f39ad063e 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs
@@ -1,6 +1,7 @@
using System;
using System.Runtime.CompilerServices;
using Godot;
+using Godot.NativeInterop;
namespace GodotTools.Internals
{
@@ -8,19 +9,12 @@ namespace GodotTools.Internals
{
public string Task { get; }
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_Create(string task, string label, int amount, bool canCancel);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_Dispose(string task);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool internal_Step(string task, string state, int step, bool forceRefresh);
-
public EditorProgress(string task, string label, int amount, bool canCancel = false)
{
Task = task;
- internal_Create(task, label, amount, canCancel);
+ using godot_string taskIn = Marshaling.ConvertStringToNative(task);
+ using godot_string labelIn = Marshaling.ConvertStringToNative(label);
+ Internal.godot_icall_EditorProgress_Create(taskIn, labelIn, amount, canCancel);
}
~EditorProgress()
@@ -33,18 +27,23 @@ namespace GodotTools.Internals
public void Dispose()
{
- internal_Dispose(Task);
+ using godot_string taskIn = Marshaling.ConvertStringToNative(Task);
+ Internal.godot_icall_EditorProgress_Dispose(taskIn);
GC.SuppressFinalize(this);
}
public void Step(string state, int step = -1, bool forceRefresh = true)
{
- internal_Step(Task, state, step, forceRefresh);
+ using godot_string taskIn = Marshaling.ConvertStringToNative(Task);
+ using godot_string stateIn = Marshaling.ConvertStringToNative(state);
+ Internal.godot_icall_EditorProgress_Step(taskIn, stateIn, step, forceRefresh);
}
public bool TryStep(string state, int step = -1, bool forceRefresh = true)
{
- return internal_Step(Task, state, step, forceRefresh);
+ using godot_string taskIn = Marshaling.ConvertStringToNative(Task);
+ using godot_string stateIn = Marshaling.ConvertStringToNative(state);
+ return Internal.godot_icall_EditorProgress_Step(taskIn, stateIn, step, forceRefresh);
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
index 5c5ced8c29..acb7cc3ab0 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
@@ -1,3 +1,4 @@
+using Godot.NativeInterop;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
@@ -5,35 +6,41 @@ namespace GodotTools.Internals
{
public static class Globals
{
- public static float EditorScale => internal_EditorScale();
-
- public static object GlobalDef(string setting, object defaultValue, bool restartIfChanged = false) =>
- internal_GlobalDef(setting, defaultValue, restartIfChanged);
-
- public static object EditorDef(string setting, object defaultValue, bool restartIfChanged = false) =>
- internal_EditorDef(setting, defaultValue, restartIfChanged);
-
- public static object EditorShortcut(string setting) =>
- internal_EditorShortcut(setting);
+ public static float EditorScale => Internal.godot_icall_Globals_EditorScale();
+
+ public static unsafe object GlobalDef(string setting, object defaultValue, bool restartIfChanged = false)
+ {
+ using godot_string settingIn = Marshaling.ConvertStringToNative(setting);
+ using godot_variant defaultValueIn = Marshaling.ConvertManagedObjectToVariant(defaultValue);
+ Internal.godot_icall_Globals_GlobalDef(settingIn, defaultValueIn, restartIfChanged, out godot_variant result);
+ using (result)
+ return Marshaling.ConvertVariantToManagedObject(result);
+ }
+
+ public static unsafe object EditorDef(string setting, object defaultValue, bool restartIfChanged = false)
+ {
+ using godot_string settingIn = Marshaling.ConvertStringToNative(setting);
+ using godot_variant defaultValueIn = Marshaling.ConvertManagedObjectToVariant(defaultValue);
+ Internal.godot_icall_Globals_EditorDef(settingIn, defaultValueIn, restartIfChanged, out godot_variant result);
+ using (result)
+ return Marshaling.ConvertVariantToManagedObject(result);
+ }
+
+ public static object EditorShortcut(string setting)
+ {
+ using godot_string settingIn = Marshaling.ConvertStringToNative(setting);
+ Internal.godot_icall_Globals_EditorShortcut(settingIn, out godot_variant result);
+ using (result)
+ return Marshaling.ConvertVariantToManagedObject(result);
+ }
[SuppressMessage("ReSharper", "InconsistentNaming")]
- public static string TTR(this string text) => internal_TTR(text);
-
- // Internal Calls
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern float internal_EditorScale();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern object internal_GlobalDef(string setting, object defaultValue, bool restartIfChanged);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern object internal_EditorDef(string setting, object defaultValue, bool restartIfChanged);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern object internal_EditorShortcut(string setting);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_TTR(string text);
+ public static string TTR(this string text)
+ {
+ using godot_string textIn = Marshaling.ConvertStringToNative(text);
+ Internal.godot_icall_Globals_TTR(textIn, out godot_string dest);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
+ }
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs
index 5e70c399b2..14285cc0f1 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs
@@ -1,103 +1,125 @@
-using System.Runtime.CompilerServices;
+using System.IO;
+using Godot;
+using Godot.NativeInterop;
+using GodotTools.Core;
+using static GodotTools.Internals.Globals;
namespace GodotTools.Internals
{
public static class GodotSharpDirs
{
- public static string ResDataDir => internal_ResDataDir();
- public static string ResMetadataDir => internal_ResMetadataDir();
- public static string ResAssembliesBaseDir => internal_ResAssembliesBaseDir();
- public static string ResAssembliesDir => internal_ResAssembliesDir();
- public static string ResConfigDir => internal_ResConfigDir();
- public static string ResTempDir => internal_ResTempDir();
- public static string ResTempAssembliesBaseDir => internal_ResTempAssembliesBaseDir();
- public static string ResTempAssembliesDir => internal_ResTempAssembliesDir();
-
- public static string MonoUserDir => internal_MonoUserDir();
- public static string MonoLogsDir => internal_MonoLogsDir();
-
- #region Tools-only
- public static string MonoSolutionsDir => internal_MonoSolutionsDir();
- public static string BuildLogsDirs => internal_BuildLogsDirs();
-
- public static string ProjectSlnPath => internal_ProjectSlnPath();
- public static string ProjectCsProjPath => internal_ProjectCsProjPath();
-
- public static string DataEditorToolsDir => internal_DataEditorToolsDir();
- public static string DataEditorPrebuiltApiDir => internal_DataEditorPrebuiltApiDir();
- #endregion
-
- public static string DataMonoEtcDir => internal_DataMonoEtcDir();
- public static string DataMonoLibDir => internal_DataMonoLibDir();
-
- #region Windows-only
- public static string DataMonoBinDir => internal_DataMonoBinDir();
- #endregion
-
-
- #region Internal
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResDataDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResMetadataDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResAssembliesBaseDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResAssembliesDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResConfigDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResTempDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResTempAssembliesBaseDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ResTempAssembliesDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_MonoUserDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_MonoLogsDir();
-
- #region Tools-only
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_MonoSolutionsDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_BuildLogsDirs();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ProjectSlnPath();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_ProjectCsProjPath();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_DataEditorToolsDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_DataEditorPrebuiltApiDir();
- #endregion
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_DataMonoEtcDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_DataMonoLibDir();
-
- #region Windows-only
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_DataMonoBinDir();
- #endregion
-
- #endregion
+ public static string ResMetadataDir
+ {
+ get
+ {
+ Internal.godot_icall_GodotSharpDirs_ResMetadataDir(out godot_string dest);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
+ }
+ }
+
+ public static string MonoUserDir
+ {
+ get
+ {
+ Internal.godot_icall_GodotSharpDirs_MonoUserDir(out godot_string dest);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
+ }
+ }
+
+ public static string BuildLogsDirs
+ {
+ get
+ {
+ Internal.godot_icall_GodotSharpDirs_BuildLogsDirs(out godot_string dest);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
+ }
+ }
+
+ public static string DataEditorToolsDir
+ {
+ get
+ {
+ Internal.godot_icall_GodotSharpDirs_DataEditorToolsDir(out godot_string dest);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
+ }
+ }
+
+ public static void RegisterProjectSettings()
+ {
+ GlobalDef("dotnet/project/assembly_name", "");
+ GlobalDef("dotnet/project/solution_directory", "");
+ GlobalDef("dotnet/project/c#_project_directory", "");
+ }
+
+ private static void DetermineProjectLocation()
+ {
+ static string DetermineProjectName()
+ {
+ string projectAssemblyName = (string)ProjectSettings.GetSetting("application/config/name");
+ projectAssemblyName = projectAssemblyName.ToSafeDirName();
+ if (string.IsNullOrEmpty(projectAssemblyName))
+ projectAssemblyName = "UnnamedProject";
+ return projectAssemblyName;
+ }
+
+ _projectAssemblyName = (string)ProjectSettings.GetSetting("dotnet/project/assembly_name");
+ if (string.IsNullOrEmpty(_projectAssemblyName))
+ {
+ _projectAssemblyName = DetermineProjectName();
+ ProjectSettings.SetSetting("dotnet/project/assembly_name", _projectAssemblyName);
+ }
+
+ string slnParentDir = (string)ProjectSettings.GetSetting("dotnet/project/solution_directory");
+ if (string.IsNullOrEmpty(slnParentDir))
+ slnParentDir = "res://";
+
+ string csprojParentDir = (string)ProjectSettings.GetSetting("dotnet/project/c#_project_directory");
+ if (string.IsNullOrEmpty(csprojParentDir))
+ csprojParentDir = "res://";
+
+ _projectSlnPath = Path.Combine(ProjectSettings.GlobalizePath(slnParentDir),
+ string.Concat(_projectAssemblyName, ".sln"));
+
+ _projectCsProjPath = Path.Combine(ProjectSettings.GlobalizePath(csprojParentDir),
+ string.Concat(_projectAssemblyName, ".csproj"));
+ }
+
+ private static string _projectAssemblyName;
+ private static string _projectSlnPath;
+ private static string _projectCsProjPath;
+
+ public static string ProjectAssemblyName
+ {
+ get
+ {
+ if (_projectAssemblyName == null)
+ DetermineProjectLocation();
+ return _projectAssemblyName;
+ }
+ }
+
+ public static string ProjectSlnPath
+ {
+ get
+ {
+ if (_projectSlnPath == null)
+ DetermineProjectLocation();
+ return _projectSlnPath;
+ }
+ }
+
+ public static string ProjectCsProjPath
+ {
+ get
+ {
+ if (_projectCsProjPath == null)
+ DetermineProjectLocation();
+ return _projectCsProjPath;
+ }
+ }
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
index 12c90178c9..e3fe1622d0 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
@@ -1,114 +1,161 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Godot;
+using Godot.NativeInterop;
+using Godot.SourceGenerators.Internal;
using GodotTools.IdeMessaging.Requests;
namespace GodotTools.Internals
{
- public static class Internal
+ [SuppressMessage("ReSharper", "InconsistentNaming")]
+ [GenerateUnmanagedCallbacks(typeof(InternalUnmanagedCallbacks))]
+ internal static partial class Internal
{
public const string CSharpLanguageType = "CSharpScript";
public const string CSharpLanguageExtension = ".cs";
- public static string UpdateApiAssembliesFromPrebuilt(string config) =>
- internal_UpdateApiAssembliesFromPrebuilt(config);
+ public static string FullExportTemplatesDir
+ {
+ get
+ {
+ godot_icall_Internal_FullExportTemplatesDir(out godot_string dest);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
+ }
+ }
- public static string FullExportTemplatesDir =>
- internal_FullExportTemplatesDir();
+ public static string SimplifyGodotPath(this string path) => Godot.StringExtensions.SimplifyPath(path);
- public static string SimplifyGodotPath(this string path) => internal_SimplifyGodotPath(path);
+ public static bool IsMacOSAppBundleInstalled(string bundleId)
+ {
+ using godot_string bundleIdIn = Marshaling.ConvertStringToNative(bundleId);
+ return godot_icall_Internal_IsMacOSAppBundleInstalled(bundleIdIn);
+ }
- public static bool IsMacOSAppBundleInstalled(string bundleId) => internal_IsMacOSAppBundleInstalled(bundleId);
+ public static bool GodotIs32Bits() => godot_icall_Internal_GodotIs32Bits();
- public static bool GodotIs32Bits() => internal_GodotIs32Bits();
+ public static bool GodotIsRealTDouble() => godot_icall_Internal_GodotIsRealTDouble();
- public static bool GodotIsRealTDouble() => internal_GodotIsRealTDouble();
+ public static void GodotMainIteration() => godot_icall_Internal_GodotMainIteration();
- public static void GodotMainIteration() => internal_GodotMainIteration();
+ public static bool IsAssembliesReloadingNeeded() => godot_icall_Internal_IsAssembliesReloadingNeeded();
- public static ulong GetCoreApiHash() => internal_GetCoreApiHash();
+ public static void ReloadAssemblies(bool softReload) => godot_icall_Internal_ReloadAssemblies(softReload);
- public static ulong GetEditorApiHash() => internal_GetEditorApiHash();
+ public static void EditorDebuggerNodeReloadScripts() => godot_icall_Internal_EditorDebuggerNodeReloadScripts();
- public static bool IsAssembliesReloadingNeeded() => internal_IsAssembliesReloadingNeeded();
+ public static bool ScriptEditorEdit(Resource resource, int line, int col, bool grabFocus = true) =>
+ godot_icall_Internal_ScriptEditorEdit(resource.NativeInstance, line, col, grabFocus);
- public static void ReloadAssemblies(bool softReload) => internal_ReloadAssemblies(softReload);
+ public static void EditorNodeShowScriptScreen() => godot_icall_Internal_EditorNodeShowScriptScreen();
- public static void EditorDebuggerNodeReloadScripts() => internal_EditorDebuggerNodeReloadScripts();
+ public static void EditorRunPlay() => godot_icall_Internal_EditorRunPlay();
- public static bool ScriptEditorEdit(Resource resource, int line, int col, bool grabFocus = true) =>
- internal_ScriptEditorEdit(resource, line, col, grabFocus);
+ public static void EditorRunStop() => godot_icall_Internal_EditorRunStop();
- public static void EditorNodeShowScriptScreen() => internal_EditorNodeShowScriptScreen();
+ public static void ScriptEditorDebugger_ReloadScripts() =>
+ godot_icall_Internal_ScriptEditorDebugger_ReloadScripts();
- public static string MonoWindowsInstallRoot => internal_MonoWindowsInstallRoot();
+ public static string[] CodeCompletionRequest(CodeCompletionRequest.CompletionKind kind,
+ string scriptFile)
+ {
+ using godot_string scriptFileIn = Marshaling.ConvertStringToNative(scriptFile);
+ godot_icall_Internal_CodeCompletionRequest((int)kind, scriptFileIn, out godot_packed_string_array res);
+ using (res)
+ return Marshaling.ConvertNativePackedStringArrayToSystemArray(res);
+ }
- public static void EditorRunPlay() => internal_EditorRunPlay();
+ #region Internal
- public static void EditorRunStop() => internal_EditorRunStop();
+ private static bool initialized = false;
- public static void ScriptEditorDebugger_ReloadScripts() => internal_ScriptEditorDebugger_ReloadScripts();
+ // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global
+ internal static unsafe void Initialize(IntPtr unmanagedCallbacks, int unmanagedCallbacksSize)
+ {
+ if (initialized)
+ throw new InvalidOperationException("Already initialized");
+ initialized = true;
- public static string[] CodeCompletionRequest(CodeCompletionRequest.CompletionKind kind, string scriptFile) =>
- internal_CodeCompletionRequest((int)kind, scriptFile);
+ if (unmanagedCallbacksSize != sizeof(InternalUnmanagedCallbacks))
+ throw new ArgumentException("Unmanaged callbacks size mismatch");
- #region Internal
+ _unmanagedCallbacks = Unsafe.AsRef<InternalUnmanagedCallbacks>((void*)unmanagedCallbacks);
+ }
+
+ private partial struct InternalUnmanagedCallbacks
+ {
+ }
+
+ /*
+ * IMPORTANT:
+ * The order of the methods defined in NativeFuncs must match the order
+ * in the array defined at the bottom of 'editor/editor_internal_calls.cpp'.
+ */
+
+ public static partial void godot_icall_GodotSharpDirs_ResMetadataDir(out godot_string r_dest);
+
+ public static partial void godot_icall_GodotSharpDirs_MonoUserDir(out godot_string r_dest);
+
+ public static partial void godot_icall_GodotSharpDirs_BuildLogsDirs(out godot_string r_dest);
+
+ public static partial void godot_icall_GodotSharpDirs_DataEditorToolsDir(out godot_string r_dest);
+
+ public static partial void godot_icall_EditorProgress_Create(in godot_string task, in godot_string label,
+ int amount, bool canCancel);
+
+ public static partial void godot_icall_EditorProgress_Dispose(in godot_string task);
+
+ public static partial bool godot_icall_EditorProgress_Step(in godot_string task, in godot_string state,
+ int step,
+ bool forceRefresh);
+
+ private static partial void godot_icall_Internal_FullExportTemplatesDir(out godot_string dest);
+
+ private static partial bool godot_icall_Internal_IsMacOSAppBundleInstalled(in godot_string bundleId);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_UpdateApiAssembliesFromPrebuilt(string config);
+ private static partial bool godot_icall_Internal_GodotIs32Bits();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_FullExportTemplatesDir();
+ private static partial bool godot_icall_Internal_GodotIsRealTDouble();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_SimplifyGodotPath(this string path);
+ private static partial void godot_icall_Internal_GodotMainIteration();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool internal_IsMacOSAppBundleInstalled(string bundleId);
+ private static partial bool godot_icall_Internal_IsAssembliesReloadingNeeded();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool internal_GodotIs32Bits();
+ private static partial void godot_icall_Internal_ReloadAssemblies(bool softReload);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool internal_GodotIsRealTDouble();
+ private static partial void godot_icall_Internal_EditorDebuggerNodeReloadScripts();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_GodotMainIteration();
+ private static partial bool godot_icall_Internal_ScriptEditorEdit(IntPtr resource, int line, int col,
+ bool grabFocus);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern ulong internal_GetCoreApiHash();
+ private static partial void godot_icall_Internal_EditorNodeShowScriptScreen();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern ulong internal_GetEditorApiHash();
+ private static partial void godot_icall_Internal_EditorRunPlay();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool internal_IsAssembliesReloadingNeeded();
+ private static partial void godot_icall_Internal_EditorRunStop();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_ReloadAssemblies(bool softReload);
+ private static partial void godot_icall_Internal_ScriptEditorDebugger_ReloadScripts();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_EditorDebuggerNodeReloadScripts();
+ private static partial void godot_icall_Internal_CodeCompletionRequest(int kind, in godot_string scriptFile,
+ out godot_packed_string_array res);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool internal_ScriptEditorEdit(Resource resource, int line, int col, bool grabFocus);
+ public static partial float godot_icall_Globals_EditorScale();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_EditorNodeShowScriptScreen();
+ public static partial void godot_icall_Globals_GlobalDef(in godot_string setting, in godot_variant defaultValue,
+ bool restartIfChanged, out godot_variant result);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string internal_MonoWindowsInstallRoot();
+ public static partial void godot_icall_Globals_EditorDef(in godot_string setting, in godot_variant defaultValue,
+ bool restartIfChanged, out godot_variant result);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_EditorRunPlay();
+ public static partial void
+ godot_icall_Globals_EditorShortcut(in godot_string setting, out godot_variant result);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_EditorRunStop();
+ public static partial void godot_icall_Globals_TTR(in godot_string text, out godot_string dest);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void internal_ScriptEditorDebugger_ReloadScripts();
+ public static partial void godot_icall_Utils_OS_GetPlatformName(out godot_string dest);
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string[] internal_CodeCompletionRequest(int kind, string scriptFile);
+ public static partial bool godot_icall_Utils_OS_UnixFileHasExecutableAccess(in godot_string filePath);
#endregion
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs
index 05499339b1..89bda704bb 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs
@@ -1,14 +1,14 @@
using System;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using Godot;
using GodotTools.Core;
-using JetBrains.Annotations;
namespace GodotTools.Utils
{
public static class FsPathUtils
{
- private static readonly string _resourcePath = ProjectSettings.GlobalizePath("res://");
+ private static readonly string ResourcePath = ProjectSettings.GlobalizePath("res://");
private static bool PathStartsWithAlreadyNorm(this string childPath, string parentPath)
{
@@ -30,11 +30,11 @@ namespace GodotTools.Utils
return childPathNorm.PathStartsWithAlreadyNorm(parentPathNorm);
}
- [CanBeNull]
+ [return: MaybeNull]
public static string LocalizePathWithCaseChecked(string path)
{
string pathNorm = path.NormalizePath() + Path.DirectorySeparatorChar;
- string resourcePathNorm = _resourcePath.NormalizePath() + Path.DirectorySeparatorChar;
+ string resourcePathNorm = ResourcePath.NormalizePath() + Path.DirectorySeparatorChar;
if (!pathNorm.PathStartsWithAlreadyNorm(resourcePathNorm))
return null;
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
index 5cef6e5c3c..651922d019 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
@@ -1,24 +1,24 @@
+using Godot.NativeInterop;
using System;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
-using System.Runtime.CompilerServices;
-using JetBrains.Annotations;
+using System.Runtime.Versioning;
+using System.Text;
+using GodotTools.Internals;
namespace GodotTools.Utils
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
public static class OS
{
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string GetPlatformName();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool UnixFileHasExecutableAccess(string filePath);
-
- public static class Names
+ /// <summary>
+ /// Display names for the OS platforms.
+ /// </summary>
+ private static class Names
{
public const string Windows = "Windows";
public const string MacOS = "macOS";
@@ -26,7 +26,6 @@ namespace GodotTools.Utils
public const string FreeBSD = "FreeBSD";
public const string NetBSD = "NetBSD";
public const string BSD = "BSD";
- public const string Server = "Server";
public const string UWP = "UWP";
public const string Haiku = "Haiku";
public const string Android = "Android";
@@ -34,12 +33,14 @@ namespace GodotTools.Utils
public const string HTML5 = "HTML5";
}
+ /// <summary>
+ /// Godot platform identifiers.
+ /// </summary>
public static class Platforms
{
public const string Windows = "windows";
public const string MacOS = "macos";
public const string LinuxBSD = "linuxbsd";
- public const string Server = "server";
public const string UWP = "uwp";
public const string Haiku = "haiku";
public const string Android = "android";
@@ -47,6 +48,38 @@ namespace GodotTools.Utils
public const string HTML5 = "javascript";
}
+ /// <summary>
+ /// OS name part of the .NET runtime identifier (RID).
+ /// See https://docs.microsoft.com/en-us/dotnet/core/rid-catalog.
+ /// </summary>
+ public static class DotNetOS
+ {
+ public const string Win = "win";
+ public const string OSX = "osx";
+ public const string Linux = "linux";
+ public const string Win10 = "win10";
+ public const string Android = "android";
+ public const string iOS = "ios";
+ public const string Browser = "browser";
+ }
+
+ public static readonly Dictionary<string, string> PlatformFeatureMap = new Dictionary<string, string>(
+ // Export `features` may be in lower case
+ StringComparer.InvariantCultureIgnoreCase
+ )
+ {
+ ["Windows"] = Platforms.Windows,
+ ["macOS"] = Platforms.MacOS,
+ ["LinuxBSD"] = Platforms.LinuxBSD,
+ // "X11" for compatibility, temporarily, while we are on an outdated branch
+ ["X11"] = Platforms.LinuxBSD,
+ ["UWP"] = Platforms.UWP,
+ ["Haiku"] = Platforms.Haiku,
+ ["Android"] = Platforms.Android,
+ ["iOS"] = Platforms.iOS,
+ ["HTML5"] = Platforms.HTML5
+ };
+
public static readonly Dictionary<string, string> PlatformNameMap = new Dictionary<string, string>
{
[Names.Windows] = Platforms.Windows,
@@ -55,7 +88,6 @@ namespace GodotTools.Utils
[Names.FreeBSD] = Platforms.LinuxBSD,
[Names.NetBSD] = Platforms.LinuxBSD,
[Names.BSD] = Platforms.LinuxBSD,
- [Names.Server] = Platforms.Server,
[Names.UWP] = Platforms.UWP,
[Names.Haiku] = Platforms.Haiku,
[Names.Android] = Platforms.Android,
@@ -63,47 +95,78 @@ namespace GodotTools.Utils
[Names.HTML5] = Platforms.HTML5
};
+ public static readonly Dictionary<string, string> DotNetOSPlatformMap = new Dictionary<string, string>
+ {
+ [Platforms.Windows] = DotNetOS.Win,
+ [Platforms.MacOS] = DotNetOS.OSX,
+ // TODO:
+ // Does .NET 6 support BSD variants? If it does, it may need the name `unix`
+ // instead of `linux` in the runtime identifier. This would be a problem as
+ // Godot has a single export profile for both, named LinuxBSD.
+ [Platforms.LinuxBSD] = DotNetOS.Linux,
+ [Platforms.UWP] = DotNetOS.Win10,
+ [Platforms.Android] = DotNetOS.Android,
+ [Platforms.iOS] = DotNetOS.iOS,
+ [Platforms.HTML5] = DotNetOS.Browser
+ };
+
private static bool IsOS(string name)
{
- return name.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
+ Internal.godot_icall_Utils_OS_GetPlatformName(out godot_string dest);
+ using (dest)
+ {
+ string platformName = Marshaling.ConvertStringToManaged(dest);
+ return name.Equals(platformName, StringComparison.OrdinalIgnoreCase);
+ }
}
private static bool IsAnyOS(IEnumerable<string> names)
{
- return names.Any(p => p.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase));
+ Internal.godot_icall_Utils_OS_GetPlatformName(out godot_string dest);
+ using (dest)
+ {
+ string platformName = Marshaling.ConvertStringToManaged(dest);
+ return names.Any(p => p.Equals(platformName, StringComparison.OrdinalIgnoreCase));
+ }
}
private static readonly IEnumerable<string> LinuxBSDPlatforms =
new[] { Names.Linux, Names.FreeBSD, Names.NetBSD, Names.BSD };
private static readonly IEnumerable<string> UnixLikePlatforms =
- new[] { Names.MacOS, Names.Server, Names.Haiku, Names.Android, Names.iOS }
+ new[] { Names.MacOS, Names.Haiku, Names.Android, Names.iOS }
.Concat(LinuxBSDPlatforms).ToArray();
- private static readonly Lazy<bool> _isWindows = new Lazy<bool>(() => IsOS(Names.Windows));
- private static readonly Lazy<bool> _isMacOS = new Lazy<bool>(() => IsOS(Names.MacOS));
- private static readonly Lazy<bool> _isLinuxBSD = new Lazy<bool>(() => IsAnyOS(LinuxBSDPlatforms));
- private static readonly Lazy<bool> _isServer = new Lazy<bool>(() => IsOS(Names.Server));
- private static readonly Lazy<bool> _isUWP = new Lazy<bool>(() => IsOS(Names.UWP));
- private static readonly Lazy<bool> _isHaiku = new Lazy<bool>(() => IsOS(Names.Haiku));
- private static readonly Lazy<bool> _isAndroid = new Lazy<bool>(() => IsOS(Names.Android));
- private static readonly Lazy<bool> _isiOS = new Lazy<bool>(() => IsOS(Names.iOS));
- private static readonly Lazy<bool> _isHTML5 = new Lazy<bool>(() => IsOS(Names.HTML5));
- private static readonly Lazy<bool> _isUnixLike = new Lazy<bool>(() => IsAnyOS(UnixLikePlatforms));
-
- public static bool IsWindows => _isWindows.Value || IsUWP;
- public static bool IsMacOS => _isMacOS.Value;
- public static bool IsLinuxBSD => _isLinuxBSD.Value;
- public static bool IsServer => _isServer.Value;
- public static bool IsUWP => _isUWP.Value;
+ private static readonly Lazy<bool> _isWindows = new(() => IsOS(Names.Windows));
+ private static readonly Lazy<bool> _isMacOS = new(() => IsOS(Names.MacOS));
+ private static readonly Lazy<bool> _isLinuxBSD = new(() => IsAnyOS(LinuxBSDPlatforms));
+ private static readonly Lazy<bool> _isUWP = new(() => IsOS(Names.UWP));
+ private static readonly Lazy<bool> _isHaiku = new(() => IsOS(Names.Haiku));
+ private static readonly Lazy<bool> _isAndroid = new(() => IsOS(Names.Android));
+ private static readonly Lazy<bool> _isiOS = new(() => IsOS(Names.iOS));
+ private static readonly Lazy<bool> _isHTML5 = new(() => IsOS(Names.HTML5));
+ private static readonly Lazy<bool> _isUnixLike = new(() => IsAnyOS(UnixLikePlatforms));
+
+ [SupportedOSPlatformGuard("windows")] public static bool IsWindows => _isWindows.Value || IsUWP;
+
+ [SupportedOSPlatformGuard("osx")] public static bool IsMacOS => _isMacOS.Value;
+
+ [SupportedOSPlatformGuard("linux")] public static bool IsLinuxBSD => _isLinuxBSD.Value;
+
+ [SupportedOSPlatformGuard("windows")] public static bool IsUWP => _isUWP.Value;
+
public static bool IsHaiku => _isHaiku.Value;
- public static bool IsAndroid => _isAndroid.Value;
- public static bool IsiOS => _isiOS.Value;
- public static bool IsHTML5 => _isHTML5.Value;
+
+ [SupportedOSPlatformGuard("android")] public static bool IsAndroid => _isAndroid.Value;
+
+ [SupportedOSPlatformGuard("ios")] public static bool IsiOS => _isiOS.Value;
+
+ [SupportedOSPlatformGuard("browser")] public static bool IsHTML5 => _isHTML5.Value;
public static bool IsUnixLike => _isUnixLike.Value;
public static char PathSep => IsWindows ? ';' : ':';
+ [return: MaybeNull]
public static string PathWhich([NotNull] string name)
{
if (IsWindows)
@@ -112,9 +175,11 @@ namespace GodotTools.Utils
return PathWhichUnix(name);
}
+ [return: MaybeNull]
private static string PathWhichWindows([NotNull] string name)
{
- string[] windowsExts = Environment.GetEnvironmentVariable("PATHEXT")?.Split(PathSep) ?? Array.Empty<string>();
+ string[] windowsExts =
+ Environment.GetEnvironmentVariable("PATHEXT")?.Split(PathSep) ?? Array.Empty<string>();
string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep);
char[] invalidPathChars = Path.GetInvalidPathChars();
@@ -133,7 +198,7 @@ namespace GodotTools.Utils
string nameExt = Path.GetExtension(name);
bool hasPathExt = !string.IsNullOrEmpty(nameExt) &&
- windowsExts.Contains(nameExt, StringComparer.OrdinalIgnoreCase);
+ windowsExts.Contains(nameExt, StringComparer.OrdinalIgnoreCase);
searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list
@@ -141,12 +206,13 @@ namespace GodotTools.Utils
return searchDirs.Select(dir => Path.Combine(dir, name)).FirstOrDefault(File.Exists);
return (from dir in searchDirs
- select Path.Combine(dir, name)
+ select Path.Combine(dir, name)
into path
- from ext in windowsExts
- select path + ext).FirstOrDefault(File.Exists);
+ from ext in windowsExts
+ select path + ext).FirstOrDefault(File.Exists);
}
+ [return: MaybeNull]
private static string PathWhichUnix([NotNull] string name)
{
string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep);
@@ -168,19 +234,16 @@ namespace GodotTools.Utils
searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list
return searchDirs.Select(dir => Path.Combine(dir, name))
- .FirstOrDefault(path => File.Exists(path) && UnixFileHasExecutableAccess(path));
+ .FirstOrDefault(path =>
+ {
+ using godot_string pathIn = Marshaling.ConvertStringToNative(path);
+ return File.Exists(path) && Internal.godot_icall_Utils_OS_UnixFileHasExecutableAccess(pathIn);
+ });
}
public static void RunProcess(string command, IEnumerable<string> arguments)
{
- // TODO: Once we move to .NET Standard 2.1 we can use ProcessStartInfo.ArgumentList instead
- string CmdLineArgsToString(IEnumerable<string> args)
- {
- // Not perfect, but as long as we are careful...
- return string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg));
- }
-
- var startInfo = new ProcessStartInfo(command, CmdLineArgsToString(arguments))
+ var startInfo = new ProcessStartInfo(command)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
@@ -188,44 +251,104 @@ namespace GodotTools.Utils
CreateNoWindow = true
};
- using (Process process = Process.Start(startInfo))
- {
- if (process == null)
- throw new Exception("No process was started");
+ foreach (string arg in arguments)
+ startInfo.ArgumentList.Add(arg);
- process.BeginOutputReadLine();
- process.BeginErrorReadLine();
- if (IsWindows && process.Id > 0)
- User32Dll.AllowSetForegroundWindow(process.Id); // allows application to focus itself
- }
+ using Process process = Process.Start(startInfo);
+
+ if (process == null)
+ throw new Exception("No process was started");
+
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+
+ if (IsWindows && process.Id > 0)
+ User32Dll.AllowSetForegroundWindow(process.Id); // Allows application to focus itself
}
public static int ExecuteCommand(string command, IEnumerable<string> arguments)
{
- // TODO: Once we move to .NET Standard 2.1 we can use ProcessStartInfo.ArgumentList instead
- string CmdLineArgsToString(IEnumerable<string> args)
+ var startInfo = new ProcessStartInfo(command)
{
- // Not perfect, but as long as we are careful...
- return string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg));
- }
+ // Print the output
+ RedirectStandardOutput = false,
+ RedirectStandardError = false,
+ UseShellExecute = false
+ };
+
+ foreach (string arg in arguments)
+ startInfo.ArgumentList.Add(arg);
- var startInfo = new ProcessStartInfo(command, CmdLineArgsToString(arguments));
+ Console.WriteLine(startInfo.GetCommandLineDisplay(new StringBuilder("Executing: ")).ToString());
- Console.WriteLine($"Executing: \"{startInfo.FileName}\" {startInfo.Arguments}");
+ using var process = new Process { StartInfo = startInfo };
+ process.Start();
+ process.WaitForExit();
+
+ return process.ExitCode;
+ }
- // Print the output
- startInfo.RedirectStandardOutput = false;
- startInfo.RedirectStandardError = false;
+ private static void AppendProcessFileNameForDisplay(this StringBuilder builder, string fileName)
+ {
+ if (builder.Length > 0)
+ builder.Append(' ');
+
+ if (fileName.Contains(' '))
+ {
+ builder.Append('"');
+ builder.Append(fileName);
+ builder.Append('"');
+ }
+ else
+ {
+ builder.Append(fileName);
+ }
+ }
- startInfo.UseShellExecute = false;
+ private static void AppendProcessArgumentsForDisplay(this StringBuilder builder,
+ Collection<string> argumentList)
+ {
+ // This is intended just for reading. It doesn't need to be a valid command line.
+ // E.g.: We don't handle escaping of quotes.
- using (var process = new Process { StartInfo = startInfo })
+ foreach (string argument in argumentList)
{
- process.Start();
- process.WaitForExit();
+ if (builder.Length > 0)
+ builder.Append(' ');
- return process.ExitCode;
+ if (argument.Contains(' '))
+ {
+ builder.Append('"');
+ builder.Append(argument);
+ builder.Append('"');
+ }
+ else
+ {
+ builder.Append(argument);
+ }
}
}
+
+ public static StringBuilder GetCommandLineDisplay(
+ this ProcessStartInfo startInfo,
+ StringBuilder optionalBuilder = null
+ )
+ {
+ var builder = optionalBuilder ?? new StringBuilder();
+
+ builder.AppendProcessFileNameForDisplay(startInfo.FileName);
+
+ if (startInfo.ArgumentList.Count == 0)
+ {
+ builder.Append(' ');
+ builder.Append(startInfo.Arguments);
+ }
+ else
+ {
+ builder.AppendProcessArgumentsForDisplay(startInfo.ArgumentList);
+ }
+
+ return builder;
+ }
}
}
diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp
index 2e628cb576..5e51a28551 100644
--- a/modules/mono/editor/bindings_generator.cpp
+++ b/modules/mono/editor/bindings_generator.cpp
@@ -41,69 +41,99 @@
#include "core/string/ucaps.h"
#include "main/main.h"
-#include "../glue/cs_glue_version.gen.h"
#include "../godotsharp_defs.h"
-#include "../mono_gd/gd_mono_marshal.h"
#include "../utils/path_utils.h"
#include "../utils/string_utils.h"
+StringBuilder &operator<<(StringBuilder &r_sb, const String &p_string) {
+ r_sb.append(p_string);
+ return r_sb;
+}
+
+StringBuilder &operator<<(StringBuilder &r_sb, const char *p_cstring) {
+ r_sb.append(p_cstring);
+ return r_sb;
+}
+
#define CS_INDENT " " // 4 whitespaces
#define INDENT1 CS_INDENT
#define INDENT2 INDENT1 INDENT1
#define INDENT3 INDENT2 INDENT1
#define INDENT4 INDENT3 INDENT1
-#define INDENT5 INDENT4 INDENT1
-#define MEMBER_BEGIN "\n" INDENT2
+#define MEMBER_BEGIN "\n" INDENT1
#define OPEN_BLOCK "{\n"
#define CLOSE_BLOCK "}\n"
-#define OPEN_BLOCK_L2 INDENT2 OPEN_BLOCK INDENT3
-#define OPEN_BLOCK_L3 INDENT3 OPEN_BLOCK INDENT4
+#define OPEN_BLOCK_L1 INDENT1 OPEN_BLOCK
+#define OPEN_BLOCK_L2 INDENT2 OPEN_BLOCK
+#define CLOSE_BLOCK_L1 INDENT1 CLOSE_BLOCK
#define CLOSE_BLOCK_L2 INDENT2 CLOSE_BLOCK
#define CLOSE_BLOCK_L3 INDENT3 CLOSE_BLOCK
-#define CS_FIELD_MEMORYOWN "memoryOwn"
+#define BINDINGS_GLOBAL_SCOPE_CLASS "GD"
+#define BINDINGS_NATIVE_NAME_FIELD "NativeName"
+
+#define CS_PARAM_MEMORYOWN "memoryOwn"
#define CS_PARAM_METHODBIND "method"
#define CS_PARAM_INSTANCE "ptr"
-#define CS_SMETHOD_GETINSTANCE "GetPtr"
+#define CS_STATIC_METHOD_GETINSTANCE "GetPtr"
#define CS_METHOD_CALL "Call"
+#define CS_PROPERTY_SINGLETON "Singleton"
+#define CS_METHOD_INVOKE_GODOT_CLASS_METHOD "InvokeGodotClassMethod"
+#define CS_METHOD_HAS_GODOT_CLASS_METHOD "HasGodotClassMethod"
+
+#define CS_STATIC_FIELD_NATIVE_CTOR "NativeCtor"
+#define CS_STATIC_FIELD_METHOD_BIND_PREFIX "MethodBind"
+#define CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX "MethodProxyName_"
-#define GLUE_HEADER_FILE "glue_header.h"
#define ICALL_PREFIX "godot_icall_"
-#define SINGLETON_ICALL_SUFFIX "_get_singleton"
-#define ICALL_GET_METHODBIND "__ClassDB_get_method"
+#define ICALL_CLASSDB_GET_METHOD "ClassDB_get_method"
+#define ICALL_CLASSDB_GET_CONSTRUCTOR "ClassDB_get_constructor"
#define C_LOCAL_RET "ret"
#define C_LOCAL_VARARG_RET "vararg_ret"
#define C_LOCAL_PTRCALL_ARGS "call_args"
-#define C_MACRO_OBJECT_CONSTRUCT "GODOTSHARP_INSTANCE_OBJECT"
-
-#define C_NS_MONOUTILS "GDMonoUtils"
-#define C_NS_MONOINTERNALS "GDMonoInternals"
-#define C_METHOD_TIE_MANAGED_TO_UNMANAGED C_NS_MONOINTERNALS "::tie_managed_to_unmanaged"
-#define C_METHOD_UNMANAGED_GET_MANAGED C_NS_MONOUTILS "::unmanaged_get_managed"
-
-#define C_NS_MONOMARSHAL "GDMonoMarshal"
-#define C_METHOD_MANAGED_TO_VARIANT C_NS_MONOMARSHAL "::mono_object_to_variant"
-#define C_METHOD_MANAGED_FROM_VARIANT C_NS_MONOMARSHAL "::variant_to_mono_object"
-#define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL "::mono_string_to_godot"
-#define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL "::mono_string_from_godot"
-#define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL "::mono_array_to_" #m_type
-#define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL "::" #m_type "_to_mono_array"
-#define C_METHOD_MANAGED_TO_CALLABLE C_NS_MONOMARSHAL "::managed_to_callable"
-#define C_METHOD_MANAGED_FROM_CALLABLE C_NS_MONOMARSHAL "::callable_to_managed"
-#define C_METHOD_MANAGED_TO_SIGNAL C_NS_MONOMARSHAL "::signal_info_to_callable"
-#define C_METHOD_MANAGED_FROM_SIGNAL C_NS_MONOMARSHAL "::callable_to_signal_info"
-
-#define BINDINGS_GENERATOR_VERSION UINT32_C(13)
+
+#define C_CLASS_NATIVE_FUNCS "NativeFuncs"
+#define C_NS_MONOUTILS "InteropUtils"
+#define C_METHOD_UNMANAGED_GET_MANAGED C_NS_MONOUTILS ".UnmanagedGetManaged"
+#define C_METHOD_ENGINE_GET_SINGLETON C_NS_MONOUTILS ".EngineGetSingleton"
+
+#define C_NS_MONOMARSHAL "Marshaling"
+#define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL ".ConvertStringToNative"
+#define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL ".ConvertStringToManaged"
+#define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL ".ConvertSystemArrayToNative" #m_type
+#define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL ".ConvertNative" #m_type "ToSystemArray"
+#define C_METHOD_MANAGED_TO_CALLABLE C_NS_MONOMARSHAL ".ConvertCallableToNative"
+#define C_METHOD_MANAGED_FROM_CALLABLE C_NS_MONOMARSHAL ".ConvertCallableToManaged"
+#define C_METHOD_MANAGED_TO_SIGNAL C_NS_MONOMARSHAL ".ConvertSignalToNative"
+#define C_METHOD_MANAGED_FROM_SIGNAL C_NS_MONOMARSHAL ".ConvertSignalToManaged"
// Types that will be ignored by the generator and won't be available in C#.
const Vector<String> ignored_types = { "PhysicsServer3DExtension" };
-const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN("\t%0 %1_in = %1;\n");
+void BindingsGenerator::TypeInterface::postsetup_enum_type(BindingsGenerator::TypeInterface &r_enum_itype) {
+ // C interface for enums is the same as that of 'uint32_t'. Remember to apply
+ // any of the changes done here to the 'uint32_t' type interface as well.
+
+ r_enum_itype.cs_type = r_enum_itype.proxy_name;
+ r_enum_itype.cs_in_expr = "(int)%0";
+ r_enum_itype.cs_out = "%5return (%2)%0(%1);";
+
+ {
+ // The expected types for parameters and return value in ptrcall are 'int64_t' or 'uint64_t'.
+ r_enum_itype.c_in = "%5%0 %1_in = %1;\n";
+ r_enum_itype.c_out = "%5return (%0)%1;\n";
+ r_enum_itype.c_type = "long";
+ r_enum_itype.c_arg_in = "&%s_in";
+ }
+ r_enum_itype.c_type_in = "int";
+ r_enum_itype.c_type_out = r_enum_itype.c_type_in;
+ r_enum_itype.class_doc = &EditorHelp::get_doc_data()->class_list[r_enum_itype.proxy_name];
+}
static String fix_doc_description(const String &p_bbcode) {
// This seems to be the correct way to do this. It's the same EditorHelp does.
@@ -359,23 +389,23 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
xml_output.append(tag);
xml_output.append("</c>");
} else if (tag == "PackedByteArray") {
- xml_output.append("<see cref=\"T:byte[]\"/>");
+ xml_output.append("<see cref=\"byte\"/>[]");
} else if (tag == "PackedInt32Array") {
- xml_output.append("<see cref=\"T:int[]\"/>");
+ xml_output.append("<see cref=\"int\"/>[]");
} else if (tag == "PackedInt64Array") {
- xml_output.append("<see cref=\"T:long[]\"/>");
+ xml_output.append("<see cref=\"long\"/>[]");
} else if (tag == "PackedFloat32Array") {
- xml_output.append("<see cref=\"T:float[]\"/>");
+ xml_output.append("<see cref=\"float\"/>[]");
} else if (tag == "PackedFloat64Array") {
- xml_output.append("<see cref=\"T:double[]\"/>");
+ xml_output.append("<see cref=\"double\"/>[]");
} else if (tag == "PackedStringArray") {
- xml_output.append("<see cref=\"T:string[]\"/>");
+ xml_output.append("<see cref=\"string\"/>[]");
} else if (tag == "PackedVector2Array") {
- xml_output.append("<see cref=\"T:" BINDINGS_NAMESPACE ".Vector2[]\"/>");
+ xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector2\"/>[]");
} else if (tag == "PackedVector3Array") {
- xml_output.append("<see cref=\"T:" BINDINGS_NAMESPACE ".Vector3[]\"/>");
+ xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector3\"/>[]");
} else if (tag == "PackedColorArray") {
- xml_output.append("<see cref=\"T:" BINDINGS_NAMESPACE ".Color[]\"/>");
+ xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Color\"/>[]");
} else {
const TypeInterface *target_itype = _get_type_or_null(TypeReference(tag));
@@ -794,49 +824,28 @@ void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumI
}
}
-void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
+Error BindingsGenerator::_populate_method_icalls_table(const TypeInterface &p_itype) {
for (const MethodInterface &imethod : p_itype.methods) {
if (imethod.is_virtual) {
continue;
}
- const TypeInterface *return_type = _get_type_or_placeholder(imethod.return_type);
+ const TypeInterface *return_type = _get_type_or_null(imethod.return_type);
+ ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
- String im_sig = "IntPtr " CS_PARAM_METHODBIND;
- String im_unique_sig = imethod.return_type.cname.operator String() + ",IntPtr";
+ String im_unique_sig = get_ret_unique_sig(return_type) + ",CallMethodBind";
if (!imethod.is_static) {
- im_sig += ", IntPtr " CS_PARAM_INSTANCE;
- im_unique_sig += ",IntPtr";
+ im_unique_sig += ",CallInstance";
}
// Get arguments information
- int i = 0;
for (const ArgumentInterface &iarg : imethod.arguments) {
- const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
-
- im_sig += ", ";
- im_sig += arg_type->im_type_in;
- im_sig += " arg";
- im_sig += itos(i + 1);
+ const TypeInterface *arg_type = _get_type_or_null(iarg.type);
+ ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
im_unique_sig += ",";
- im_unique_sig += get_unique_sig(*arg_type);
-
- i++;
- }
-
- String im_type_out = return_type->im_type_out;
-
- if (return_type->ret_as_byref_arg) {
- // Doesn't affect the unique signature
- im_type_out = "void";
-
- im_sig += ", ";
- im_sig += return_type->im_type_out;
- im_sig += " argRet";
-
- i++;
+ im_unique_sig += get_arg_unique_sig(*arg_type);
}
// godot_icall_{argc}_{icallcount}
@@ -845,7 +854,15 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
icall_method += "_";
icall_method += itos(method_icalls.size());
- InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, im_type_out, im_sig, im_unique_sig);
+ InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, im_unique_sig);
+
+ im_icall.is_vararg = imethod.is_vararg;
+ im_icall.is_static = imethod.is_static;
+ im_icall.return_type = imethod.return_type;
+
+ for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) {
+ im_icall.argument_types.push_back(F->get().type);
+ }
List<InternalCall>::Element *match = method_icalls.find(im_icall);
@@ -859,47 +876,49 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
method_icalls_map.insert(&imethod, &added->get());
}
}
+
+ return OK;
}
void BindingsGenerator::_generate_array_extensions(StringBuilder &p_output) {
+ p_output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
p_output.append("using System;\n\n");
- p_output.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
// The class where we put the extensions doesn't matter, so just use "GD".
- p_output.append(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{");
+ p_output.append("public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n{");
#define ARRAY_IS_EMPTY(m_type) \
- p_output.append("\n" INDENT2 "/// <summary>\n"); \
- p_output.append(INDENT2 "/// Returns true if this " #m_type " array is empty or doesn't exist.\n"); \
- p_output.append(INDENT2 "/// </summary>\n"); \
- p_output.append(INDENT2 "/// <param name=\"instance\">The " #m_type " array check.</param>\n"); \
- p_output.append(INDENT2 "/// <returns>Whether or not the array is empty.</returns>\n"); \
- p_output.append(INDENT2 "public static bool IsEmpty(this " #m_type "[] instance)\n"); \
- p_output.append(INDENT2 OPEN_BLOCK); \
- p_output.append(INDENT3 "return instance == null || instance.Length == 0;\n"); \
- p_output.append(INDENT2 CLOSE_BLOCK);
+ p_output.append("\n" INDENT1 "/// <summary>\n"); \
+ p_output.append(INDENT1 "/// Returns true if this " #m_type " array is empty or doesn't exist.\n"); \
+ p_output.append(INDENT1 "/// </summary>\n"); \
+ p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array check.</param>\n"); \
+ p_output.append(INDENT1 "/// <returns>Whether or not the array is empty.</returns>\n"); \
+ p_output.append(INDENT1 "public static bool IsEmpty(this " #m_type "[] instance)\n"); \
+ p_output.append(OPEN_BLOCK_L1); \
+ p_output.append(INDENT2 "return instance == null || instance.Length == 0;\n"); \
+ p_output.append(INDENT1 CLOSE_BLOCK);
#define ARRAY_JOIN(m_type) \
- p_output.append("\n" INDENT2 "/// <summary>\n"); \
- p_output.append(INDENT2 "/// Converts this " #m_type " array to a string delimited by the given string.\n"); \
- p_output.append(INDENT2 "/// </summary>\n"); \
- p_output.append(INDENT2 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
- p_output.append(INDENT2 "/// <param name=\"delimiter\">The delimiter to use between items.</param>\n"); \
- p_output.append(INDENT2 "/// <returns>A single string with all items.</returns>\n"); \
- p_output.append(INDENT2 "public static string Join(this " #m_type "[] instance, string delimiter = \", \")\n"); \
- p_output.append(INDENT2 OPEN_BLOCK); \
- p_output.append(INDENT3 "return String.Join(delimiter, instance);\n"); \
- p_output.append(INDENT2 CLOSE_BLOCK);
+ p_output.append("\n" INDENT1 "/// <summary>\n"); \
+ p_output.append(INDENT1 "/// Converts this " #m_type " array to a string delimited by the given string.\n"); \
+ p_output.append(INDENT1 "/// </summary>\n"); \
+ p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
+ p_output.append(INDENT1 "/// <param name=\"delimiter\">The delimiter to use between items.</param>\n"); \
+ p_output.append(INDENT1 "/// <returns>A single string with all items.</returns>\n"); \
+ p_output.append(INDENT1 "public static string Join(this " #m_type "[] instance, string delimiter = \", \")\n"); \
+ p_output.append(OPEN_BLOCK_L1); \
+ p_output.append(INDENT2 "return String.Join(delimiter, instance);\n"); \
+ p_output.append(INDENT1 CLOSE_BLOCK);
#define ARRAY_STRINGIFY(m_type) \
- p_output.append("\n" INDENT2 "/// <summary>\n"); \
- p_output.append(INDENT2 "/// Converts this " #m_type " array to a string with brackets.\n"); \
- p_output.append(INDENT2 "/// </summary>\n"); \
- p_output.append(INDENT2 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
- p_output.append(INDENT2 "/// <returns>A single string with all items.</returns>\n"); \
- p_output.append(INDENT2 "public static string Stringify(this " #m_type "[] instance)\n"); \
- p_output.append(INDENT2 OPEN_BLOCK); \
- p_output.append(INDENT3 "return \"[\" + instance.Join() + \"]\";\n"); \
- p_output.append(INDENT2 CLOSE_BLOCK);
+ p_output.append("\n" INDENT1 "/// <summary>\n"); \
+ p_output.append(INDENT1 "/// Converts this " #m_type " array to a string with brackets.\n"); \
+ p_output.append(INDENT1 "/// </summary>\n"); \
+ p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
+ p_output.append(INDENT1 "/// <returns>A single string with all items.</returns>\n"); \
+ p_output.append(INDENT1 "public static string Stringify(this " #m_type "[] instance)\n"); \
+ p_output.append(OPEN_BLOCK_L1); \
+ p_output.append(INDENT2 "return \"[\" + instance.Join() + \"]\";\n"); \
+ p_output.append(INDENT1 CLOSE_BLOCK);
#define ARRAY_ALL(m_type) \
ARRAY_IS_EMPTY(m_type) \
@@ -925,18 +944,18 @@ void BindingsGenerator::_generate_array_extensions(StringBuilder &p_output) {
#undef ARRAY_JOIN
#undef ARRAY_STRINGIFY
- p_output.append(INDENT1 CLOSE_BLOCK); // End of GD class.
- p_output.append(CLOSE_BLOCK); // End of namespace.
+ p_output.append(CLOSE_BLOCK); // End of GD class.
}
void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
// Constants (in partial GD class)
+ p_output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
+
p_output.append("\n#pragma warning disable CS1591 // Disable warning: "
"'Missing XML comment for publicly visible type or member'\n");
- p_output.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
- p_output.append(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{");
+ p_output.append("public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n{");
for (const ConstantInterface &iconstant : global_constants) {
if (iconstant.const_doc && iconstant.const_doc->description.size()) {
@@ -947,12 +966,12 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- p_output.append(INDENT2 "/// ");
+ p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
- p_output.append(INDENT2 "/// </summary>");
+ p_output.append(INDENT1 "/// </summary>");
}
}
@@ -967,7 +986,7 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
p_output.append("\n");
}
- p_output.append(INDENT1 CLOSE_BLOCK); // end of GD class
+ p_output.append(CLOSE_BLOCK); // end of GD class
// Enums
@@ -985,21 +1004,21 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
CRASH_COND(enum_class_name != "Variant"); // Hard-coded...
- _log("Declaring global enum '%s' inside static class '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data());
+ _log("Declaring global enum '%s' inside struct '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data());
- p_output.append("\n" INDENT1 "public static partial class ");
+ p_output.append("\npublic partial struct ");
p_output.append(enum_class_name);
- p_output.append("\n" INDENT1 OPEN_BLOCK);
+ p_output.append("\n" OPEN_BLOCK);
}
if (ienum.is_flags) {
- p_output.append("\n" INDENT1 "[System.Flags]");
+ p_output.append("\n[System.Flags]");
}
- p_output.append("\n" INDENT1 "public enum ");
+ p_output.append("\npublic enum ");
p_output.append(enum_proxy_name);
p_output.append(" : long");
- p_output.append("\n" INDENT1 OPEN_BLOCK);
+ p_output.append("\n" OPEN_BLOCK);
const ConstantInterface &last = ienum.constants.back()->get();
for (const ConstantInterface &iconstant : ienum.constants) {
@@ -1008,34 +1027,32 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
- p_output.append(INDENT2 "/// <summary>\n");
+ p_output.append(INDENT1 "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- p_output.append(INDENT2 "/// ");
+ p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
- p_output.append(INDENT2 "/// </summary>\n");
+ p_output.append(INDENT1 "/// </summary>\n");
}
}
- p_output.append(INDENT2);
+ p_output.append(INDENT1);
p_output.append(iconstant.proxy_name);
p_output.append(" = ");
p_output.append(itos(iconstant.value));
p_output.append(&iconstant != &last ? ",\n" : "\n");
}
- p_output.append(INDENT1 CLOSE_BLOCK);
+ p_output.append(CLOSE_BLOCK);
if (enum_in_static_class) {
- p_output.append(INDENT1 CLOSE_BLOCK);
+ p_output.append(CLOSE_BLOCK);
}
}
- p_output.append(CLOSE_BLOCK); // end of namespace
-
p_output.append("\n#pragma warning restore CS1591\n");
}
@@ -1106,42 +1123,38 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
compile_items.push_back(output_file);
}
- // Generate sources from compressed files
+ // Generate native calls
StringBuilder cs_icalls_content;
+ cs_icalls_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
cs_icalls_content.append("using System;\n"
- "using System.Runtime.CompilerServices;\n"
+ "using System.Diagnostics.CodeAnalysis;\n"
+ "using System.Runtime.InteropServices;\n"
+ "using Godot.NativeInterop;\n"
"\n");
- cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
- cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS "\n" INDENT1 "{");
+ cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"InconsistentNaming\")]\n");
+ cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantUnsafeContext\")]\n");
+ cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantNameQualifier\")]\n");
+ cs_icalls_content.append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
+ cs_icalls_content.append("internal static class " BINDINGS_CLASS_NATIVECALLS "\n{");
cs_icalls_content.append(MEMBER_BEGIN "internal static ulong godot_api_hash = ");
- cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + ";\n");
- cs_icalls_content.append(MEMBER_BEGIN "internal static uint bindings_version = ");
- cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
- cs_icalls_content.append(MEMBER_BEGIN "internal static uint cs_glue_version = ");
- cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n");
+ cs_icalls_content.append(String::num_uint64(ClassDB::get_api_hash(ClassDB::API_CORE)) + ";\n");
-#define ADD_INTERNAL_CALL(m_icall) \
- if (!m_icall.editor_only) { \
- cs_icalls_content.append(MEMBER_BEGIN "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
- cs_icalls_content.append(INDENT2 "internal static extern "); \
- cs_icalls_content.append(m_icall.im_type_out + " "); \
- cs_icalls_content.append(m_icall.name + "("); \
- cs_icalls_content.append(m_icall.im_sig + ");\n"); \
- }
+ cs_icalls_content.append(MEMBER_BEGIN "private const int VarArgsSpanThreshold = 10;\n");
- for (const InternalCall &internal_call : core_custom_icalls) {
- ADD_INTERNAL_CALL(internal_call);
- }
- for (const InternalCall &internal_call : method_icalls) {
- ADD_INTERNAL_CALL(internal_call);
+ for (const InternalCall &icall : method_icalls) {
+ if (icall.editor_only) {
+ continue;
+ }
+ Error err = _generate_cs_native_calls(icall, cs_icalls_content);
+ if (err != OK) {
+ return err;
+ }
}
-#undef ADD_INTERNAL_CALL
-
- cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
+ cs_icalls_content.append(CLOSE_BLOCK);
String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
@@ -1152,6 +1165,8 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
compile_items.push_back(internal_methods_file);
+ // Generate GeneratedIncludes.props
+
StringBuilder includes_props_content;
includes_props_content.append("<Project>\n"
" <ItemGroup>\n");
@@ -1215,41 +1230,40 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
compile_items.push_back(output_file);
}
+ // Generate native calls
+
StringBuilder cs_icalls_content;
+ cs_icalls_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
cs_icalls_content.append("using System;\n"
- "using System.Runtime.CompilerServices;\n"
+ "using System.Diagnostics.CodeAnalysis;\n"
+ "using System.Runtime.InteropServices;\n"
+ "using Godot.NativeInterop;\n"
"\n");
- cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
- cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" INDENT1 OPEN_BLOCK);
-
- cs_icalls_content.append(INDENT2 "internal static ulong godot_api_hash = ");
- cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + ";\n");
- cs_icalls_content.append(INDENT2 "internal static uint bindings_version = ");
- cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
- cs_icalls_content.append(INDENT2 "internal static uint cs_glue_version = ");
- cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n");
- cs_icalls_content.append("\n");
+ cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"InconsistentNaming\")]\n");
+ cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantUnsafeContext\")]\n");
+ cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantNameQualifier\")]\n");
+ cs_icalls_content.append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
+ cs_icalls_content.append("internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" OPEN_BLOCK);
-#define ADD_INTERNAL_CALL(m_icall) \
- if (m_icall.editor_only) { \
- cs_icalls_content.append(INDENT2 "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
- cs_icalls_content.append(INDENT2 "internal static extern "); \
- cs_icalls_content.append(m_icall.im_type_out + " "); \
- cs_icalls_content.append(m_icall.name + "("); \
- cs_icalls_content.append(m_icall.im_sig + ");\n"); \
- }
+ cs_icalls_content.append(INDENT1 "internal static ulong godot_api_hash = ");
+ cs_icalls_content.append(String::num_uint64(ClassDB::get_api_hash(ClassDB::API_EDITOR)) + ";\n");
- for (const InternalCall &internal_call : editor_custom_icalls) {
- ADD_INTERNAL_CALL(internal_call);
- }
- for (const InternalCall &internal_call : method_icalls) {
- ADD_INTERNAL_CALL(internal_call);
- }
+ cs_icalls_content.append(MEMBER_BEGIN "private const int VarArgsSpanThreshold = 10;\n");
-#undef ADD_INTERNAL_CALL
+ cs_icalls_content.append("\n");
+
+ for (const InternalCall &icall : method_icalls) {
+ if (!icall.editor_only) {
+ continue;
+ }
+ Error err = _generate_cs_native_calls(icall, cs_icalls_content);
+ if (err != OK) {
+ return err;
+ }
+ }
- cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
+ cs_icalls_content.append(CLOSE_BLOCK);
String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
@@ -1260,6 +1274,8 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
compile_items.push_back(internal_methods_file);
+ // Generate GeneratedIncludes.props
+
StringBuilder includes_props_content;
includes_props_content.append("<Project>\n"
" <ItemGroup>\n");
@@ -1343,16 +1359,15 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
CRASH_COND(itype.is_singleton);
}
- List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
-
_log("Generating %s.cs...\n", itype.proxy_name.utf8().get_data());
- String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
-
StringBuilder output;
+ output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
+
output.append("using System;\n"); // IntPtr
output.append("using System.Diagnostics;\n"); // DebuggerBrowsable
+ output.append("using Godot.NativeInterop;\n");
output.append("\n"
"#pragma warning disable CS1591 // Disable warning: "
@@ -1360,7 +1375,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
"#pragma warning disable CS1573 // Disable warning: "
"'Parameter has no matching param tag in the XML comment'\n");
- output.append("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
+ output.append("\n#nullable disable\n");
const DocData::ClassDoc *class_doc = itype.class_doc;
@@ -1369,40 +1384,48 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
- output.append(INDENT1 "/// <summary>\n");
+ output.append("/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- output.append(INDENT1 "/// ");
+ output.append("/// ");
output.append(summary_lines[i]);
output.append("\n");
}
- output.append(INDENT1 "/// </summary>\n");
+ output.append("/// </summary>\n");
}
}
- output.append(INDENT1 "public ");
+ // We generate a `GodotClassName` attribute if the engine class name is not the same as the
+ // generated C# class name. This allows introspection code to find the name associated with
+ // the class. If the attribute is not present, the C# class name can be used instead.
+ if (itype.name != itype.proxy_name) {
+ output << "[GodotClassName(\"" << itype.name << "\")]\n";
+ }
+
+ output.append("public ");
if (itype.is_singleton) {
output.append("static partial class ");
} else {
- output.append(itype.is_instantiable ? "partial class " : "abstract partial class ");
+ // Even if the class is not instantiable, we can't declare it abstract because
+ // the engine can still instantiate them and return them via the scripting API.
+ // Example: `SceneTreeTimer` returned from `SceneTree.create_timer`.
+ // See the reverted commit: ef5672d3f94a7321ed779c922088bb72adbb1521
+ output.append("partial class ");
}
output.append(itype.proxy_name);
- if (itype.is_singleton) {
- output.append("\n");
- } else if (is_derived_type) {
+ if (is_derived_type && !itype.is_singleton) {
if (obj_types.has(itype.base_name)) {
output.append(" : ");
output.append(obj_types[itype.base_name].proxy_name);
- output.append("\n");
} else {
ERR_PRINT("Base type '" + itype.base_name.operator String() + "' does not exist, for class '" + itype.name + "'.");
return ERR_INVALID_DATA;
}
}
- output.append(INDENT1 "{");
+ output.append("\n{");
// Add constants
@@ -1415,12 +1438,12 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- output.append(INDENT2 "/// ");
+ output.append(INDENT1 "/// ");
output.append(summary_lines[i]);
output.append("\n");
}
- output.append(INDENT2 "/// </summary>");
+ output.append(INDENT1 "/// </summary>");
}
}
@@ -1456,26 +1479,26 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
- output.append(INDENT3 "/// <summary>\n");
+ output.append(INDENT2 "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- output.append(INDENT3 "/// ");
+ output.append(INDENT2 "/// ");
output.append(summary_lines[i]);
output.append("\n");
}
- output.append(INDENT3 "/// </summary>\n");
+ output.append(INDENT2 "/// </summary>\n");
}
}
- output.append(INDENT3);
+ output.append(INDENT2);
output.append(iconstant.proxy_name);
output.append(" = ");
output.append(itos(iconstant.value));
output.append(&iconstant != &last ? ",\n" : "\n");
}
- output.append(INDENT2 CLOSE_BLOCK);
+ output.append(INDENT1 CLOSE_BLOCK);
}
// Add properties
@@ -1491,55 +1514,68 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
// Add the type name and the singleton pointer as static fields
output.append(MEMBER_BEGIN "private static Godot.Object singleton;\n");
- output.append(MEMBER_BEGIN "public static Godot.Object Singleton\n" INDENT2 "{\n" INDENT3
- "get\n" INDENT3 "{\n" INDENT4 "if (singleton == null)\n" INDENT5
- "singleton = Engine.GetSingleton(typeof(");
- output.append(itype.proxy_name);
- output.append(").Name);\n" INDENT4 "return singleton;\n" INDENT3 "}\n" INDENT2 "}\n");
- output.append(MEMBER_BEGIN "private static StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
+ output << MEMBER_BEGIN "public static Godot.Object " CS_PROPERTY_SINGLETON "\n" INDENT1 "{\n"
+ << INDENT2 "get\n" INDENT2 "{\n" INDENT3 "if (singleton == null)\n"
+ << INDENT4 "singleton = " C_METHOD_ENGINE_GET_SINGLETON "(typeof("
+ << itype.proxy_name
+ << ").Name);\n" INDENT3 "return singleton;\n" INDENT2 "}\n" INDENT1 "}\n";
+
+ output.append(MEMBER_BEGIN "private static readonly StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
output.append(itype.name);
output.append("\";\n");
+ } else {
+ // IMPORTANT: We also generate the static fields for Godot.Object instead of declaring
+ // them manually in the `Object.base.cs` partial class declaration, because they're
+ // required by other static fields in this generated partial class declaration.
+ // Static fields are initialized in order of declaration, but when they're in different
+ // partial class declarations then it becomes harder to tell (Rider warns about this).
- output.append(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = ");
- output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
- output.append("." ICALL_PREFIX);
- output.append(itype.name);
- output.append(SINGLETON_ICALL_SUFFIX "();\n");
- } else if (is_derived_type) {
- // Add member fields
+ // Add native name static field
+
+ if (is_derived_type) {
+ output << MEMBER_BEGIN "private static readonly System.Type CachedType = typeof(" << itype.proxy_name << ");\n";
+ }
- output.append(MEMBER_BEGIN "private static StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
+ output.append(MEMBER_BEGIN "private static readonly StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
output.append(itype.name);
output.append("\";\n");
- // Add default constructor
if (itype.is_instantiable) {
- output.append(MEMBER_BEGIN "public ");
- output.append(itype.proxy_name);
- output.append("() : this(");
- output.append(itype.memory_own ? "true" : "false");
-
- // The default constructor may also be called by the engine when instancing existing native objects
- // The engine will initialize the pointer field of the managed side before calling the constructor
- // This is why we only allocate a new native object from the constructor if the pointer field is not set
- output.append(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = ");
- output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
- output.append("." + ctor_method);
- output.append("(this);\n" INDENT3 "_InitializeGodotScriptInstanceInternals();\n" CLOSE_BLOCK_L2);
- } else {
- // Hide the constructor
+ // Add native constructor static field
+
+ output << MEMBER_BEGIN << "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
+ << INDENT1 "private static readonly unsafe delegate* unmanaged<IntPtr> "
+ << CS_STATIC_FIELD_NATIVE_CTOR " = " ICALL_CLASSDB_GET_CONSTRUCTOR
+ << "(" BINDINGS_NATIVE_NAME_FIELD ");\n";
+ }
+
+ if (is_derived_type) {
+ // Add default constructor
+ if (itype.is_instantiable) {
+ output << MEMBER_BEGIN "public " << itype.proxy_name << "() : this("
+ << (itype.memory_own ? "true" : "false") << ")\n" OPEN_BLOCK_L1
+ << INDENT2 "unsafe\n" INDENT2 OPEN_BLOCK
+ << INDENT3 "_ConstructAndInitialize(" CS_STATIC_FIELD_NATIVE_CTOR ", "
+ << BINDINGS_NATIVE_NAME_FIELD ", CachedType, refCounted: "
+ << (itype.is_ref_counted ? "true" : "false") << ");\n"
+ << CLOSE_BLOCK_L2 CLOSE_BLOCK_L1;
+ } else {
+ // Hide the constructor
+ output.append(MEMBER_BEGIN "internal ");
+ output.append(itype.proxy_name);
+ output.append("() {}\n");
+ }
+
+ // Add.. em.. trick constructor. Sort of.
output.append(MEMBER_BEGIN "internal ");
output.append(itype.proxy_name);
- output.append("() {}\n");
+ output.append("(bool " CS_PARAM_MEMORYOWN ") : base(" CS_PARAM_MEMORYOWN ") {}\n");
}
-
- // Add.. em.. trick constructor. Sort of.
- output.append(MEMBER_BEGIN "internal ");
- output.append(itype.proxy_name);
- output.append("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n");
}
+ // Methods
+
int method_bind_count = 0;
for (const MethodInterface &imethod : itype.methods) {
Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output);
@@ -1547,30 +1583,186 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
"Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
}
+ // Signals
+
for (const SignalInterface &isignal : itype.signals_) {
Error method_err = _generate_cs_signal(itype, isignal, output);
ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
"Failed to generate signal '" + isignal.name + "' for class '" + itype.name + "'.");
}
- if (itype.is_singleton) {
- InternalCall singleton_icall = InternalCall(itype.api_type, ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX, "IntPtr");
+ // Script members look-up
- if (!find_icall_by_name(singleton_icall.name, custom_icalls)) {
- custom_icalls.push_back(singleton_icall);
+ if (!itype.is_singleton && (is_derived_type || itype.has_virtual_methods)) {
+ // Generate method names cache fields
+
+ for (const MethodInterface &imethod : itype.methods) {
+ if (!imethod.is_virtual) {
+ continue;
+ }
+
+ output << MEMBER_BEGIN "// ReSharper disable once InconsistentNaming\n"
+ << INDENT1 "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
+ << INDENT1 "private static readonly StringName "
+ << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
+ << " = \"" << imethod.proxy_name << "\";\n";
}
- }
- if (is_derived_type && itype.is_instantiable) {
- InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
+ // TODO: Only generate HasGodotClassMethod and InvokeGodotClassMethod if there's any method
+
+ // Generate InvokeGodotClassMethod
+
+ output << MEMBER_BEGIN "protected internal " << (is_derived_type ? "override" : "virtual")
+ << " bool " CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(in godot_string_name method, "
+ << "NativeVariantPtrArgs args, int argCount, out godot_variant ret)\n"
+ << INDENT1 "{\n";
+
+ for (const MethodInterface &imethod : itype.methods) {
+ if (!imethod.is_virtual) {
+ continue;
+ }
- if (!find_icall_by_name(ctor_icall.name, custom_icalls)) {
- custom_icalls.push_back(ctor_icall);
+ // We also call HasGodotClassMethod to ensure the method is overridden and avoid calling
+ // the stub implementation. This solution adds some extra overhead to calls, but it's
+ // much simpler than other solutions. This won't be a problem once we move to function
+ // pointers of generated wrappers for each method, as lookup will only happen once.
+
+ // We check both native names (snake_case) and proxy names (PascalCase)
+ output << INDENT2 "if ((method == " << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
+ << " || method == MethodName." << imethod.proxy_name
+ << ") && argCount == " << itos(imethod.arguments.size())
+ << " && " << CS_METHOD_HAS_GODOT_CLASS_METHOD << "((godot_string_name)"
+ << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name << ".NativeValue))\n"
+ << INDENT2 "{\n";
+
+ if (imethod.return_type.cname != name_cache.type_void) {
+ output << INDENT3 "var callRet = ";
+ } else {
+ output << INDENT3;
+ }
+
+ output << imethod.proxy_name << "(";
+
+ for (int i = 0; i < imethod.arguments.size(); i++) {
+ const ArgumentInterface &iarg = imethod.arguments[i];
+
+ const TypeInterface *arg_type = _get_type_or_null(iarg.type);
+ ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
+
+ if (i != 0) {
+ output << ", ";
+ }
+
+ if (arg_type->cname == name_cache.type_Array_generic || arg_type->cname == name_cache.type_Dictionary_generic) {
+ String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
+
+ output << "new " << arg_cs_type << "(" << sformat(arg_type->cs_variant_to_managed, "args[" + itos(i) + "]", arg_type->cs_type, arg_type->name) << ")";
+ } else {
+ output << sformat(arg_type->cs_variant_to_managed,
+ "args[" + itos(i) + "]", arg_type->cs_type, arg_type->name);
+ }
+ }
+
+ output << ");\n";
+
+ if (imethod.return_type.cname != name_cache.type_void) {
+ const TypeInterface *return_type = _get_type_or_null(imethod.return_type);
+ ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
+
+ output << INDENT3 "ret = "
+ << sformat(return_type->cs_managed_to_variant, "callRet", return_type->cs_type, return_type->name)
+ << ";\n"
+ << INDENT3 "return true;\n";
+ } else {
+ output << INDENT3 "ret = default;\n"
+ << INDENT3 "return true;\n";
+ }
+
+ output << INDENT2 "}\n";
+ }
+
+ if (is_derived_type) {
+ output << INDENT2 "return base." CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(method, args, argCount, out ret);\n";
+ } else {
+ output << INDENT2 "ret = default;\n"
+ << INDENT2 "return false;\n";
+ }
+
+ output << INDENT1 "}\n";
+
+ // Generate HasGodotClassMethod
+
+ output << MEMBER_BEGIN "protected internal " << (is_derived_type ? "override" : "virtual")
+ << " bool " CS_METHOD_HAS_GODOT_CLASS_METHOD "(in godot_string_name method)\n"
+ << INDENT1 "{\n";
+
+ for (const MethodInterface &imethod : itype.methods) {
+ if (!imethod.is_virtual) {
+ continue;
+ }
+
+ // We check for native names (snake_case). If we detect one, we call HasGodotClassMethod
+ // again, but this time with the respective proxy name (PascalCase). It's the job of
+ // user derived classes to override the method and check for those. Our C# source
+ // generators take care of generating those override methods.
+ output << INDENT2 "if (method == MethodName." << imethod.proxy_name
+ << ")\n" INDENT2 "{\n"
+ << INDENT3 "if (" CS_METHOD_HAS_GODOT_CLASS_METHOD "("
+ << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
+ << ".NativeValue.DangerousSelfRef))\n" INDENT3 "{\n"
+ << INDENT4 "return true;\n"
+ << INDENT3 "}\n" INDENT2 "}\n";
}
+
+ if (is_derived_type) {
+ output << INDENT2 "return base." CS_METHOD_HAS_GODOT_CLASS_METHOD "(method);\n";
+ } else {
+ output << INDENT2 "return false;\n";
+ }
+
+ output << INDENT1 "}\n";
}
- output.append(INDENT1 CLOSE_BLOCK /* class */
- CLOSE_BLOCK /* namespace */);
+ //Generate StringName for all class members
+ bool is_inherit = !itype.is_singleton && obj_types.has(itype.base_name);
+ //PropertyName
+ if (is_inherit) {
+ output << MEMBER_BEGIN "public new class PropertyName : " << obj_types[itype.base_name].proxy_name << ".PropertyName";
+ } else {
+ output << MEMBER_BEGIN "public class PropertyName";
+ }
+ output << "\n"
+ << INDENT1 "{\n";
+ for (const PropertyInterface &iprop : itype.properties) {
+ output << INDENT2 "public static readonly StringName " << iprop.proxy_name << " = \"" << iprop.cname << "\";\n";
+ }
+ output << INDENT1 "}\n";
+ //MethodName
+ if (is_inherit) {
+ output << MEMBER_BEGIN "public new class MethodName : " << obj_types[itype.base_name].proxy_name << ".MethodName";
+ } else {
+ output << MEMBER_BEGIN "public class MethodName";
+ }
+ output << "\n"
+ << INDENT1 "{\n";
+ for (const MethodInterface &imethod : itype.methods) {
+ output << INDENT2 "public static readonly StringName " << imethod.proxy_name << " = \"" << imethod.cname << "\";\n";
+ }
+ output << INDENT1 "}\n";
+ //SignalName
+ if (is_inherit) {
+ output << MEMBER_BEGIN "public new class SignalName : " << obj_types[itype.base_name].proxy_name << ".SignalName";
+ } else {
+ output << MEMBER_BEGIN "public class SignalName";
+ }
+ output << "\n"
+ << INDENT1 "{\n";
+ for (const SignalInterface &isignal : itype.signals_) {
+ output << INDENT2 "public static readonly StringName " << isignal.proxy_name << " = \"" << isignal.cname << "\";\n";
+ }
+ output << INDENT1 "}\n";
+
+ output.append(CLOSE_BLOCK /* class */);
output.append("\n"
"#pragma warning restore CS1591\n"
@@ -1649,12 +1841,12 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- p_output.append(INDENT2 "/// ");
+ p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
- p_output.append(INDENT2 "/// </summary>");
+ p_output.append(INDENT1 "/// </summary>");
}
}
@@ -1669,15 +1861,15 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte
p_output.append(prop_cs_type);
p_output.append(" ");
p_output.append(p_iprop.proxy_name);
- p_output.append("\n" INDENT2 OPEN_BLOCK);
+ p_output.append("\n" OPEN_BLOCK_L1);
if (getter) {
- p_output.append(INDENT3 "get\n"
+ p_output.append(INDENT2 "get\n"
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning disable CS0618 // Disable warning about obsolete method\n"
- OPEN_BLOCK_L3);
+ OPEN_BLOCK_L2 INDENT3);
p_output.append("return ");
p_output.append(getter->proxy_name + "(");
@@ -1694,19 +1886,19 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte
}
p_output.append(");\n"
- CLOSE_BLOCK_L3
+ CLOSE_BLOCK_L2
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning restore CS0618\n");
}
if (setter) {
- p_output.append(INDENT3 "set\n"
+ p_output.append(INDENT2 "set\n"
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning disable CS0618 // Disable warning about obsolete method\n"
- OPEN_BLOCK_L3);
+ OPEN_BLOCK_L2 INDENT3);
p_output.append(setter->proxy_name + "(");
if (p_iprop.index != -1) {
@@ -1722,19 +1914,20 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte
}
p_output.append("value);\n"
- CLOSE_BLOCK_L3
+ CLOSE_BLOCK_L2
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning restore CS0618\n");
}
- p_output.append(CLOSE_BLOCK_L2);
+ p_output.append(CLOSE_BLOCK_L1);
return OK;
}
Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output) {
- const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
+ const TypeInterface *return_type = _get_type_or_null(p_imethod.return_type);
+ ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
ERR_FAIL_COND_V_MSG(return_type->is_singleton, ERR_BUG,
"Method return type is a singleton: '" + p_itype.name + "." + p_imethod.name + "'.");
@@ -1745,14 +1938,21 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
"' from the editor API. Core API cannot have dependencies on the editor API.");
}
- String method_bind_field = "__method_bind_" + itos(p_method_bind_count);
+ String method_bind_field = CS_STATIC_FIELD_METHOD_BIND_PREFIX + itos(p_method_bind_count);
String arguments_sig;
- String cs_in_statements;
+ StringBuilder cs_in_statements;
+ bool cs_in_expr_is_unsafe = false;
String icall_params = method_bind_field;
+
if (!p_imethod.is_static) {
- icall_params += ", " + sformat(p_itype.cs_in, "this");
+ if (p_itype.cs_in.size()) {
+ cs_in_statements << sformat(p_itype.cs_in, p_itype.c_type, "this",
+ String(), String(), String(), INDENT2);
+ }
+
+ icall_params += ", " + sformat(p_itype.cs_in_expr, "this");
}
StringBuilder default_args_doc;
@@ -1760,7 +1960,8 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
// Retrieve information from the arguments
const ArgumentInterface &first = p_imethod.arguments.front()->get();
for (const ArgumentInterface &iarg : p_imethod.arguments) {
- const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
+ const TypeInterface *arg_type = _get_type_or_null(iarg.type);
+ ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
"Argument type is a singleton: '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
@@ -1813,27 +2014,23 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT) {
// The default value of an argument must be constant. Otherwise we make it Nullable and do the following:
// Type arg_in = arg.HasValue ? arg.Value : <non-const default value>;
- String arg_in = iarg.name;
- arg_in += "_in";
+ String arg_or_defval_local = iarg.name;
+ arg_or_defval_local += "OrDefVal";
- cs_in_statements += arg_cs_type;
- cs_in_statements += " ";
- cs_in_statements += arg_in;
- cs_in_statements += " = ";
- cs_in_statements += iarg.name;
+ cs_in_statements << INDENT2 << arg_cs_type << " " << arg_or_defval_local << " = " << iarg.name;
if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
- cs_in_statements += ".HasValue ? ";
+ cs_in_statements << ".HasValue ? ";
} else {
- cs_in_statements += " != null ? ";
+ cs_in_statements << " != null ? ";
}
- cs_in_statements += iarg.name;
+ cs_in_statements << iarg.name;
if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
- cs_in_statements += ".Value : ";
+ cs_in_statements << ".Value : ";
} else {
- cs_in_statements += " : ";
+ cs_in_statements << " : ";
}
String cs_type = arg_cs_type;
@@ -1843,10 +2040,18 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
String def_arg = sformat(iarg.default_argument, cs_type);
- cs_in_statements += def_arg;
- cs_in_statements += ";\n" INDENT3;
+ cs_in_statements << def_arg << ";\n";
+
+ if (arg_type->cs_in.size()) {
+ cs_in_statements << sformat(arg_type->cs_in, arg_type->c_type, arg_or_defval_local,
+ String(), String(), String(), INDENT2);
+ }
- icall_params += arg_type->cs_in.is_empty() ? arg_in : sformat(arg_type->cs_in, arg_in);
+ if (arg_type->cs_in_expr.is_empty()) {
+ icall_params += arg_or_defval_local;
+ } else {
+ icall_params += sformat(arg_type->cs_in_expr, arg_or_defval_local, arg_type->c_type);
+ }
// Apparently the name attribute must not include the @
String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1, iarg.name.length()) : iarg.name;
@@ -1855,18 +2060,32 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
default_args_doc.append(MEMBER_BEGIN "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is <c>" + param_def_arg + "</c>.</param>");
} else {
- icall_params += arg_type->cs_in.is_empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name);
+ if (arg_type->cs_in.size()) {
+ cs_in_statements << sformat(arg_type->cs_in, arg_type->c_type, iarg.name,
+ String(), String(), String(), INDENT2);
+ }
+
+ icall_params += arg_type->cs_in_expr.is_empty() ? iarg.name : sformat(arg_type->cs_in_expr, iarg.name, arg_type->c_type);
}
+
+ cs_in_expr_is_unsafe |= arg_type->cs_in_expr_is_unsafe;
}
// Generate method
{
if (!p_imethod.is_virtual && !p_imethod.requires_object_call) {
- p_output.append(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static readonly IntPtr ");
- p_output.append(method_bind_field);
- p_output.append(" = Object." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \"");
- p_output.append(p_imethod.name);
- p_output.append("\");\n");
+ p_output << MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
+ << INDENT1 "private static readonly IntPtr " << method_bind_field << " = ";
+
+ if (p_itype.is_singleton) {
+ // Singletons are static classes. They don't derive Godot.Object,
+ // so we need to specify the type to call the static method.
+ p_output << "Object.";
+ }
+
+ p_output << ICALL_CLASSDB_GET_METHOD "(" BINDINGS_NATIVE_NAME_FIELD ", MethodName."
+ << p_imethod.proxy_name
+ << ");\n";
}
if (p_imethod.method_doc && p_imethod.method_doc->description.size()) {
@@ -1877,12 +2096,12 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- p_output.append(INDENT2 "/// ");
+ p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
- p_output.append(INDENT2 "/// </summary>");
+ p_output.append(INDENT1 "/// </summary>");
}
}
@@ -1890,16 +2109,6 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
p_output.append(default_args_doc.as_string());
}
- if (!p_imethod.is_internal) {
- // TODO: This alone adds ~0.2 MB of bloat to the core API assembly. It would be
- // better to generate a table in the C++ glue instead. That way the strings wouldn't
- // add that much extra bloat as they're already used in engine code. Also, it would
- // probably be much faster than looking up the attributes when fetching methods.
- p_output.append(MEMBER_BEGIN "[GodotMethod(\"");
- p_output.append(p_imethod.name);
- p_output.append("\")]");
- }
-
if (p_imethod.is_deprecated) {
if (p_imethod.deprecation_message.is_empty()) {
WARN_PRINT("An empty deprecation message is discouraged. Method: '" + p_imethod.proxy_name + "'.");
@@ -1919,21 +2128,23 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
p_output.append("virtual ");
}
+ if (cs_in_expr_is_unsafe) {
+ p_output.append("unsafe ");
+ }
+
String return_cs_type = return_type->cs_type + _get_generic_type_parameters(*return_type, p_imethod.return_type.generic_type_parameters);
p_output.append(return_cs_type + " ");
p_output.append(p_imethod.proxy_name + "(");
- p_output.append(arguments_sig + ")\n" OPEN_BLOCK_L2);
+ p_output.append(arguments_sig + ")\n" OPEN_BLOCK_L1);
if (p_imethod.is_virtual) {
// Godot virtual method must be overridden, therefore we return a default value by default.
if (return_type->cname == name_cache.type_void) {
- p_output.append("return;\n" CLOSE_BLOCK_L2);
+ p_output.append(CLOSE_BLOCK_L1);
} else {
- p_output.append("return default(");
- p_output.append(return_cs_type);
- p_output.append(");\n" CLOSE_BLOCK_L2);
+ p_output.append(INDENT2 "return default;\n" CLOSE_BLOCK_L1);
}
return OK; // Won't increment method bind count
@@ -1942,7 +2153,7 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
if (p_imethod.requires_object_call) {
// Fallback to Godot's object.Call(string, params)
- p_output.append(CS_METHOD_CALL "(\"");
+ p_output.append(INDENT2 CS_METHOD_CALL "(\"");
p_output.append(p_imethod.name);
p_output.append("\"");
@@ -1951,7 +2162,7 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
p_output.append(iarg.name);
}
- p_output.append(");\n" CLOSE_BLOCK_L2);
+ p_output.append(");\n" CLOSE_BLOCK_L1);
return OK; // Won't increment method bind count
}
@@ -1965,20 +2176,21 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
im_call += ".";
im_call += im_icall->name;
- if (p_imethod.arguments.size()) {
- p_output.append(cs_in_statements);
+ if (p_imethod.arguments.size() && cs_in_statements.get_string_length() > 0) {
+ p_output.append(cs_in_statements.as_string());
}
if (return_type->cname == name_cache.type_void) {
- p_output.append(im_call + "(" + icall_params + ");\n");
+ p_output << INDENT2 << im_call << "(" << icall_params << ");\n";
} else if (return_type->cs_out.is_empty()) {
- p_output.append("return " + im_call + "(" + icall_params + ");\n");
+ p_output << INDENT2 "return " << im_call << "(" << icall_params << ");\n";
} else {
- p_output.append(sformat(return_type->cs_out, im_call, icall_params, return_cs_type, return_type->im_type_out));
+ p_output.append(sformat(return_type->cs_out, im_call, icall_params,
+ return_cs_type, return_type->c_type_out, String(), INDENT2));
p_output.append("\n");
}
- p_output.append(CLOSE_BLOCK_L2);
+ p_output.append(CLOSE_BLOCK_L1);
}
p_method_bind_count++;
@@ -1992,7 +2204,8 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
// Retrieve information from the arguments
const ArgumentInterface &first = p_isignal.arguments.front()->get();
for (const ArgumentInterface &iarg : p_isignal.arguments) {
- const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
+ const TypeInterface *arg_type = _get_type_or_null(iarg.type);
+ ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
"Argument type is a singleton: '" + iarg.name + "' of signal '" + p_itype.name + "." + p_isignal.name + "'.");
@@ -2024,12 +2237,12 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
- p_output.append(INDENT2 "/// ");
+ p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
- p_output.append(INDENT2 "/// </summary>");
+ p_output.append(INDENT1 "/// </summary>");
}
}
@@ -2057,13 +2270,6 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
// Could we assume the StringName instance of signal name will never be freed (it's stored in ClassDB) before the managed world is unloaded?
// If so, we could store the pointer we get from `data_unique_pointer()` instead of allocating StringName here.
- // Cached signal name (StringName)
- p_output.append(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static StringName __signal_name_");
- p_output.append(p_isignal.name);
- p_output.append(" = \"");
- p_output.append(p_isignal.name);
- p_output.append("\";\n");
-
// Generate event
p_output.append(MEMBER_BEGIN "[Signal]" MEMBER_BEGIN "public ");
@@ -2075,413 +2281,241 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
p_output.append(delegate_name);
p_output.append(" ");
p_output.append(p_isignal.proxy_name);
- p_output.append("\n" OPEN_BLOCK_L2);
+ p_output.append("\n" OPEN_BLOCK_L1 INDENT2);
if (p_itype.is_singleton) {
- p_output.append("add => Singleton.Connect(__signal_name_");
+ p_output.append("add => " CS_PROPERTY_SINGLETON ".Connect(SignalName.");
} else {
- p_output.append("add => Connect(__signal_name_");
+ p_output.append("add => Connect(SignalName.");
}
- p_output.append(p_isignal.name);
+ p_output.append(p_isignal.proxy_name);
p_output.append(", new Callable(value));\n");
if (p_itype.is_singleton) {
- p_output.append(INDENT3 "remove => Singleton.Disconnect(__signal_name_");
+ p_output.append(INDENT2 "remove => " CS_PROPERTY_SINGLETON ".Disconnect(SignalName.");
} else {
- p_output.append(INDENT3 "remove => Disconnect(__signal_name_");
+ p_output.append(INDENT2 "remove => Disconnect(SignalName.");
}
- p_output.append(p_isignal.name);
+ p_output.append(p_isignal.proxy_name);
p_output.append(", new Callable(value));\n");
- p_output.append(CLOSE_BLOCK_L2);
- }
-
- return OK;
-}
-
-Error BindingsGenerator::generate_glue(const String &p_output_dir) {
- ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
-
- bool dir_exists = DirAccess::exists(p_output_dir);
- ERR_FAIL_COND_V_MSG(!dir_exists, ERR_FILE_BAD_PATH, "The output directory does not exist.");
-
- StringBuilder output;
-
- output.append("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
- output.append("#include \"" GLUE_HEADER_FILE "\"\n");
- output.append("\n#ifdef MONO_GLUE_ENABLED\n");
-
- generated_icall_funcs.clear();
-
- for (const KeyValue<StringName, TypeInterface> &type_elem : obj_types) {
- const TypeInterface &itype = type_elem.value;
-
- bool is_derived_type = itype.base_name != StringName();
-
- if (!is_derived_type) {
- // Some Object assertions
- CRASH_COND(itype.cname != name_cache.type_Object);
- CRASH_COND(!itype.is_instantiable);
- CRASH_COND(itype.api_type != ClassDB::API_CORE);
- CRASH_COND(itype.is_singleton);
- }
-
- List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
-
- OS::get_singleton()->print("Generating %s...\n", itype.name.utf8().get_data());
-
- String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
-
- for (const MethodInterface &imethod : itype.methods) {
- Error method_err = _generate_glue_method(itype, imethod, output);
- ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
- "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
- }
-
- if (itype.is_singleton) {
- String singleton_icall_name = ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX;
- InternalCall singleton_icall = InternalCall(itype.api_type, singleton_icall_name, "IntPtr");
-
- if (!find_icall_by_name(singleton_icall.name, custom_icalls)) {
- custom_icalls.push_back(singleton_icall);
- }
-
- output.append("Object* ");
- output.append(singleton_icall_name);
- output.append("() " OPEN_BLOCK "\treturn Engine::get_singleton()->get_singleton_object(\"");
- output.append(itype.proxy_name);
- output.append("\");\n" CLOSE_BLOCK "\n");
- }
-
- if (is_derived_type && itype.is_instantiable) {
- InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
-
- if (!find_icall_by_name(ctor_icall.name, custom_icalls)) {
- custom_icalls.push_back(ctor_icall);
- }
-
- output.append("Object* ");
- output.append(ctor_method);
- output.append("(MonoObject* obj) " OPEN_BLOCK
- "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \"");
- output.append(itype.name);
- output.append("\");\n"
- "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n"
- "\treturn instance;\n" CLOSE_BLOCK "\n");
- }
- }
-
- output.append("namespace GodotSharpBindings\n" OPEN_BLOCK "\n");
-
- output.append("uint64_t get_core_api_hash() { return ");
- output.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + "U; }\n");
-
- output.append("#ifdef TOOLS_ENABLED\n"
- "uint64_t get_editor_api_hash() { return ");
- output.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + "U; }\n");
- output.append("#endif // TOOLS_ENABLED\n");
-
- output.append("uint32_t get_bindings_version() { return ");
- output.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + "; }\n");
-
- output.append("uint32_t get_cs_glue_version() { return ");
- output.append(String::num_uint64(CS_GLUE_VERSION) + "; }\n");
-
- output.append("\nvoid register_generated_icalls() " OPEN_BLOCK);
- output.append("\tgodot_register_glue_header_icalls();\n");
-
-#define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \
- { \
- output.append("\tGDMonoUtils::add_internal_call("); \
- output.append("\"" BINDINGS_NAMESPACE "."); \
- output.append(m_icall.editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); \
- output.append("::"); \
- output.append(m_icall.name); \
- output.append("\", "); \
- output.append(m_icall.name); \
- output.append(");\n"); \
- }
-
- bool tools_sequence = false;
- for (const InternalCall &internal_call : core_custom_icalls) {
- if (tools_sequence) {
- if (!internal_call.editor_only) {
- tools_sequence = false;
- output.append("#endif\n");
- }
- } else {
- if (internal_call.editor_only) {
- output.append("#ifdef TOOLS_ENABLED\n");
- tools_sequence = true;
- }
- }
-
- ADD_INTERNAL_CALL_REGISTRATION(internal_call);
- }
-
- if (tools_sequence) {
- tools_sequence = false;
- output.append("#endif\n");
- }
-
- output.append("#ifdef TOOLS_ENABLED\n");
- 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) {
- if (tools_sequence) {
- if (!internal_call.editor_only) {
- tools_sequence = false;
- output.append("#endif\n");
- }
- } else {
- if (internal_call.editor_only) {
- output.append("#ifdef TOOLS_ENABLED\n");
- tools_sequence = true;
- }
- }
-
- ADD_INTERNAL_CALL_REGISTRATION(internal_call);
- }
-
- if (tools_sequence) {
- tools_sequence = false;
- output.append("#endif\n");
- }
-
-#undef ADD_INTERNAL_CALL_REGISTRATION
-
- output.append(CLOSE_BLOCK "\n} // namespace GodotSharpBindings\n");
-
- output.append("\n#endif // MONO_GLUE_ENABLED\n");
-
- Error save_err = _save_file(path::join(p_output_dir, "mono_glue.gen.cpp"), output);
- if (save_err != OK) {
- return save_err;
+ p_output.append(CLOSE_BLOCK_L1);
}
- OS::get_singleton()->print("Mono glue generated successfully\n");
-
- return OK;
-}
-
-uint32_t BindingsGenerator::get_version() {
- return BINDINGS_GENERATOR_VERSION;
-}
-
-Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) {
- Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE);
- ERR_FAIL_COND_V_MSG(file.is_null(), ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'.");
-
- file->store_string(p_content.as_string());
-
return OK;
}
-Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, StringBuilder &p_output) {
- if (p_imethod.is_virtual) {
- return OK; // Ignore
- }
+Error BindingsGenerator::_generate_cs_native_calls(const InternalCall &p_icall, StringBuilder &r_output) {
+ bool ret_void = p_icall.return_type.cname == name_cache.type_void;
- bool ret_void = p_imethod.return_type.cname == name_cache.type_void;
+ const TypeInterface *return_type = _get_type_or_null(p_icall.return_type);
+ ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
- const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
+ StringBuilder c_func_sig;
+ StringBuilder c_in_statements;
+ StringBuilder c_args_var_content;
- String argc_str = itos(p_imethod.arguments.size());
+ c_func_sig << "IntPtr " CS_PARAM_METHODBIND;
- String c_func_sig = "MethodBind* " CS_PARAM_METHODBIND;
- if (!p_imethod.is_static) {
- c_func_sig += ", " + p_itype.c_type_in + " " CS_PARAM_INSTANCE;
+ if (!p_icall.is_static) {
+ c_func_sig += ", IntPtr " CS_PARAM_INSTANCE;
}
- String c_in_statements;
- String c_args_var_content;
// Get arguments information
int i = 0;
- for (const ArgumentInterface &iarg : p_imethod.arguments) {
- const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
+ for (const TypeReference &arg_type_ref : p_icall.argument_types) {
+ const TypeInterface *arg_type = _get_type_or_null(arg_type_ref);
+ ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Return type not found
String c_param_name = "arg" + itos(i + 1);
- if (p_imethod.is_vararg) {
- if (i < p_imethod.arguments.size() - 1) {
- c_in_statements += sformat(arg_type->c_in.size() ? arg_type->c_in : TypeInterface::DEFAULT_VARARG_C_IN, "Variant", c_param_name);
- c_in_statements += "\t" C_LOCAL_PTRCALL_ARGS ".set(";
- c_in_statements += itos(i);
- c_in_statements += sformat(", &%s_in);\n", c_param_name);
+ if (p_icall.is_vararg) {
+ if (i < p_icall.get_arguments_count() - 1) {
+ String c_in_vararg = arg_type->c_in_vararg;
+
+ if (arg_type->is_object_type) {
+ c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromGodotObjectPtr(%1);\n";
+ }
+
+ ERR_FAIL_COND_V_MSG(c_in_vararg.is_empty(), ERR_BUG,
+ "VarArg support not implemented for parameter type: " + arg_type->name);
+
+ c_in_statements
+ << sformat(c_in_vararg, return_type->c_type, c_param_name,
+ String(), String(), String(), INDENT3)
+ << INDENT3 C_LOCAL_PTRCALL_ARGS "[" << itos(i)
+ << "] = new IntPtr(&" << c_param_name << "_in);\n";
}
} else {
if (i > 0) {
- c_args_var_content += ", ";
+ c_args_var_content << ", ";
}
if (arg_type->c_in.size()) {
- c_in_statements += sformat(arg_type->c_in, arg_type->c_type, c_param_name);
+ c_in_statements << sformat(arg_type->c_in, arg_type->c_type, c_param_name,
+ String(), String(), String(), INDENT2);
}
- c_args_var_content += sformat(arg_type->c_arg_in, c_param_name);
+ c_args_var_content << sformat(arg_type->c_arg_in, c_param_name);
}
- c_func_sig += ", ";
- c_func_sig += arg_type->c_type_in;
- c_func_sig += " ";
- c_func_sig += c_param_name;
+ c_func_sig << ", " << arg_type->c_type_in << " " << c_param_name;
i++;
}
- if (return_type->ret_as_byref_arg) {
- c_func_sig += ", ";
- c_func_sig += return_type->c_type_in;
- c_func_sig += " ";
- c_func_sig += "arg_ret";
-
- i++;
- }
+ String icall_method = p_icall.name;
- HashMap<const MethodInterface *, const InternalCall *>::ConstIterator match = method_icalls_map.find(&p_imethod);
- ERR_FAIL_NULL_V(match, ERR_BUG);
+ // Generate icall function
- const InternalCall *im_icall = match->value;
- String icall_method = im_icall->name;
+ r_output << MEMBER_BEGIN "internal static unsafe " << (ret_void ? "void" : return_type->c_type_out) << " "
+ << icall_method << "(" << c_func_sig.as_string() << ") " OPEN_BLOCK;
- if (!generated_icall_funcs.find(im_icall)) {
- generated_icall_funcs.push_back(im_icall);
+ if (!ret_void && (!p_icall.is_vararg || return_type->cname != name_cache.type_Variant)) {
+ String ptrcall_return_type;
+ String initialization;
- if (im_icall->editor_only) {
- p_output.append("#ifdef TOOLS_ENABLED\n");
+ if (return_type->is_object_type) {
+ ptrcall_return_type = return_type->is_ref_counted ? "godot_ref" : return_type->c_type;
+ initialization = " = default";
+ } else {
+ ptrcall_return_type = return_type->c_type;
}
- // Generate icall function
-
- p_output.append((ret_void || return_type->ret_as_byref_arg) ? "void " : return_type->c_type_out + " ");
- p_output.append(icall_method);
- p_output.append("(");
- p_output.append(c_func_sig);
- p_output.append(") " OPEN_BLOCK);
+ r_output << INDENT2;
- if (!ret_void) {
- String ptrcall_return_type;
- String initialization;
+ if (return_type->is_ref_counted || return_type->c_type_is_disposable_struct) {
+ r_output << "using ";
- if (p_imethod.is_vararg && return_type->cname != name_cache.type_Variant) {
- // VarArg methods always return Variant, but there are some cases in which MethodInfo provides
- // a specific return type. We trust this information is valid. We need a temporary local to keep
- // the Variant alive until the method returns. Otherwise, if the returned Variant holds a RefPtr,
- // it could be deleted too early. This is the case with GDScript.new() which returns OBJECT.
- // Alternatively, we could just return Variant, but that would result in a worse API.
- p_output.append("\tVariant " C_LOCAL_VARARG_RET ";\n");
+ if (initialization.is_empty()) {
+ initialization = " = default";
}
+ } else if (return_type->c_ret_needs_default_initialization) {
+ initialization = " = default";
+ }
- if (return_type->is_object_type) {
- ptrcall_return_type = return_type->is_ref_counted ? "Ref<RefCounted>" : return_type->c_type;
- initialization = return_type->is_ref_counted ? "" : " = nullptr";
- } else {
- ptrcall_return_type = return_type->c_type;
- }
+ r_output << ptrcall_return_type << " " C_LOCAL_RET << initialization << ";\n";
+ }
- p_output.append("\t" + ptrcall_return_type);
- p_output.append(" " C_LOCAL_RET);
- p_output.append(initialization + ";\n");
+ if (!p_icall.is_static) {
+ r_output << INDENT2 "if (" CS_PARAM_INSTANCE " == IntPtr.Zero)\n"
+ << INDENT3 "throw new ArgumentNullException(nameof(" CS_PARAM_INSTANCE "));\n";
+ }
- String fail_ret = return_type->c_type_out.ends_with("*") && !return_type->ret_as_byref_arg ? "nullptr" : return_type->c_type_out + "()";
+ String argc_str = itos(p_icall.get_arguments_count());
- if (!p_imethod.is_static) {
- if (return_type->ret_as_byref_arg) {
- p_output.append("\tif (" CS_PARAM_INSTANCE " == nullptr) { *arg_ret = ");
- p_output.append(fail_ret);
- p_output.append("; ERR_FAIL_MSG(\"Parameter ' " CS_PARAM_INSTANCE " ' is null.\"); }\n");
- } else {
- p_output.append("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE ", ");
- p_output.append(fail_ret);
- p_output.append(");\n");
- }
- }
- } else {
- if (!p_imethod.is_static) {
- p_output.append("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n");
- }
- }
-
- if (p_imethod.arguments.size()) {
- if (p_imethod.is_vararg) {
- String vararg_arg = "arg" + argc_str;
- String real_argc_str = itos(p_imethod.arguments.size() - 1); // Arguments count without vararg
-
- p_output.append("\tint vararg_length = mono_array_length(");
- p_output.append(vararg_arg);
- p_output.append(");\n\tint total_length = ");
- p_output.append(real_argc_str);
- p_output.append(" + vararg_length;\n"
- "\tArgumentsVector<Variant> varargs(vararg_length);\n"
- "\tArgumentsVector<const Variant *> " C_LOCAL_PTRCALL_ARGS "(total_length);\n");
- p_output.append(c_in_statements);
- p_output.append("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK
- "\t\tMonoObject* elem = mono_array_get(");
- p_output.append(vararg_arg);
- p_output.append(", MonoObject*, i);\n"
- "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n"
- "\t\t" C_LOCAL_PTRCALL_ARGS ".set(");
- p_output.append(real_argc_str);
- p_output.append(" + i, &varargs.get(i));\n\t" CLOSE_BLOCK);
- } else {
- p_output.append(c_in_statements);
- p_output.append("\tconst void* " C_LOCAL_PTRCALL_ARGS "[");
- p_output.append(argc_str + "] = { ");
- p_output.append(c_args_var_content + " };\n");
- }
- }
+ auto generate_call_and_return_stmts = [&](const char *base_indent) {
+ if (p_icall.is_vararg) {
+ // MethodBind Call
+ r_output << base_indent;
- if (p_imethod.is_vararg) {
- p_output.append("\tCallable::CallError vcall_error;\n\t");
+ // VarArg methods always return Variant, but there are some cases in which MethodInfo provides
+ // a specific return type. We trust this information is valid. We need a temporary local to keep
+ // the Variant alive until the method returns. Otherwise, if the returned Variant holds a RefPtr,
+ // it could be deleted too early. This is the case with GDScript.new() which returns OBJECT.
+ // Alternatively, we could just return Variant, but that would result in a worse API.
if (!ret_void) {
- // See the comment on the C_LOCAL_VARARG_RET declaration
if (return_type->cname != name_cache.type_Variant) {
- p_output.append(C_LOCAL_VARARG_RET " = ");
+ r_output << "using godot_variant " << C_LOCAL_VARARG_RET " = ";
} else {
- p_output.append(C_LOCAL_RET " = ");
+ r_output << "using godot_variant " << C_LOCAL_RET " = ";
}
}
- p_output.append(CS_PARAM_METHODBIND "->call(");
- p_output.append(p_imethod.is_static ? "nullptr" : CS_PARAM_INSTANCE);
- p_output.append(", ");
- p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ".ptr()" : "nullptr");
- p_output.append(", total_length, vcall_error);\n");
+ r_output << C_CLASS_NATIVE_FUNCS ".godotsharp_method_bind_call("
+ << CS_PARAM_METHODBIND ", " << (p_icall.is_static ? "IntPtr.Zero" : CS_PARAM_INSTANCE)
+ << ", " << (p_icall.get_arguments_count() ? "(godot_variant**)" C_LOCAL_PTRCALL_ARGS : "null")
+ << ", total_length, out _);\n";
if (!ret_void) {
- // See the comment on the C_LOCAL_VARARG_RET declaration
if (return_type->cname != name_cache.type_Variant) {
- p_output.append("\t" C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n");
+ if (return_type->cname == name_cache.enum_Error) {
+ r_output << base_indent << C_LOCAL_RET " = VariantUtils.ConvertToInt64(" C_LOCAL_VARARG_RET ");\n";
+ } else {
+ // TODO: Use something similar to c_in_vararg (see usage above, with error if not implemented)
+ CRASH_NOW_MSG("Custom VarArg return type not implemented: " + return_type->name);
+ r_output << base_indent << C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n";
+ }
}
}
} else {
- p_output.append("\t" CS_PARAM_METHODBIND "->ptrcall(");
- p_output.append(p_imethod.is_static ? "nullptr" : CS_PARAM_INSTANCE);
- p_output.append(", ");
- p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "nullptr, ");
- p_output.append(!ret_void ? "&" C_LOCAL_RET ");\n" : "nullptr);\n");
+ // MethodBind PtrCall
+ r_output << base_indent << C_CLASS_NATIVE_FUNCS ".godotsharp_method_bind_ptrcall("
+ << CS_PARAM_METHODBIND ", " << (p_icall.is_static ? "IntPtr.Zero" : CS_PARAM_INSTANCE)
+ << ", " << (p_icall.get_arguments_count() ? C_LOCAL_PTRCALL_ARGS : "null")
+ << ", " << (!ret_void ? "&" C_LOCAL_RET ");\n" : "null);\n");
}
+ // Return statement
+
if (!ret_void) {
if (return_type->c_out.is_empty()) {
- p_output.append("\treturn " C_LOCAL_RET ";\n");
- } else if (return_type->ret_as_byref_arg) {
- p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name, "arg_ret"));
+ r_output << base_indent << "return " C_LOCAL_RET ";\n";
} else {
- p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name));
+ r_output << sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET,
+ return_type->name, String(), String(), base_indent);
}
}
+ };
+
+ if (p_icall.get_arguments_count()) {
+ if (p_icall.is_vararg) {
+ String vararg_arg = "arg" + argc_str;
+ String real_argc_str = itos(p_icall.get_arguments_count() - 1); // Arguments count without vararg
- p_output.append(CLOSE_BLOCK "\n");
+ p_icall.get_arguments_count();
- if (im_icall->editor_only) {
- p_output.append("#endif // TOOLS_ENABLED\n");
+ r_output << INDENT2 "int vararg_length = " << vararg_arg << ".Length;\n"
+ << INDENT2 "int total_length = " << real_argc_str << " + vararg_length;\n";
+
+ r_output << INDENT2 "Span<godot_variant.movable> varargs_span = vararg_length <= VarArgsSpanThreshold ?\n"
+ << INDENT3 "stackalloc godot_variant.movable[VarArgsSpanThreshold].Cleared() :\n"
+ << INDENT3 "new godot_variant.movable[vararg_length];\n";
+
+ r_output << INDENT2 "Span<IntPtr> " C_LOCAL_PTRCALL_ARGS "_span = total_length <= VarArgsSpanThreshold ?\n"
+ << INDENT3 "stackalloc IntPtr[VarArgsSpanThreshold] :\n"
+ << INDENT3 "new IntPtr[total_length];\n";
+
+ r_output << INDENT2 "using var variantSpanDisposer = new VariantSpanDisposer(varargs_span);\n";
+
+ r_output << INDENT2 "fixed (godot_variant.movable* varargs = &MemoryMarshal.GetReference(varargs_span))\n"
+ << INDENT2 "fixed (IntPtr* " C_LOCAL_PTRCALL_ARGS " = "
+ "&MemoryMarshal.GetReference(" C_LOCAL_PTRCALL_ARGS "_span))\n"
+ << OPEN_BLOCK_L2;
+
+ r_output << c_in_statements.as_string();
+
+ r_output << INDENT3 "for (int i = 0; i < vararg_length; i++) " OPEN_BLOCK
+ << INDENT4 "varargs[i] = " << vararg_arg << "[i].NativeVar;\n"
+ << INDENT4 C_LOCAL_PTRCALL_ARGS "[" << real_argc_str << " + i] = new IntPtr(&varargs[i]);\n"
+ << CLOSE_BLOCK_L3;
+
+ generate_call_and_return_stmts(INDENT3);
+
+ r_output << CLOSE_BLOCK_L2;
+ } else {
+ r_output << c_in_statements.as_string();
+
+ r_output << INDENT2 "void** " C_LOCAL_PTRCALL_ARGS " = stackalloc void*["
+ << argc_str << "] { " << c_args_var_content.as_string() << " };\n";
+
+ generate_call_and_return_stmts(INDENT2);
}
+ } else {
+ generate_call_and_return_stmts(INDENT2);
}
+ r_output << CLOSE_BLOCK_L1;
+
+ return OK;
+}
+
+Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) {
+ Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE);
+ ERR_FAIL_COND_V_MSG(file.is_null(), ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'.");
+
+ file->store_string(p_content.as_string());
+
return OK;
}
@@ -2514,27 +2548,6 @@ const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(con
return nullptr;
}
-const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placeholder(const TypeReference &p_typeref) {
- const TypeInterface *found = _get_type_or_null(p_typeref);
-
- if (found) {
- return found;
- }
-
- ERR_PRINT(String() + "Type not found. Creating placeholder: '" + p_typeref.cname.operator String() + "'.");
-
- HashMap<StringName, TypeInterface>::ConstIterator match = placeholder_types.find(p_typeref.cname);
-
- if (match) {
- return &match->value;
- }
-
- TypeInterface placeholder;
- TypeInterface::create_placeholder_type(placeholder, p_typeref.cname);
-
- return &placeholder_types.insert(placeholder.cname, placeholder)->value;
-}
-
const String BindingsGenerator::_get_generic_type_parameters(const TypeInterface &p_itype, const List<TypeReference> &p_generic_type_parameters) {
if (p_generic_type_parameters.is_empty()) {
return "";
@@ -2548,7 +2561,8 @@ const String BindingsGenerator::_get_generic_type_parameters(const TypeInterface
int i = 0;
String params = "<";
for (const TypeReference &param_type : p_generic_type_parameters) {
- const TypeInterface *param_itype = _get_type_or_placeholder(param_type);
+ const TypeInterface *param_itype = _get_type_or_null(param_type);
+ ERR_FAIL_NULL_V(param_itype, "");
ERR_FAIL_COND_V_MSG(param_itype->is_singleton, "",
"Generic type parameter is a singleton: '" + param_itype->name + "'.");
@@ -2666,8 +2680,6 @@ bool BindingsGenerator::_arg_default_value_is_assignable_to_type(const Variant &
case Variant::RECT2:
case Variant::VECTOR3:
case Variant::RID:
- case Variant::ARRAY:
- case Variant::DICTIONARY:
case Variant::PACKED_BYTE_ARRAY:
case Variant::PACKED_INT32_ARRAY:
case Variant::PACKED_INT64_ARRAY:
@@ -2680,6 +2692,10 @@ bool BindingsGenerator::_arg_default_value_is_assignable_to_type(const Variant &
case Variant::CALLABLE:
case Variant::SIGNAL:
return p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ case Variant::ARRAY:
+ return p_arg_type.name == Variant::get_type_name(p_val.get_type()) || p_arg_type.cname == name_cache.type_Array_generic;
+ case Variant::DICTIONARY:
+ return p_arg_type.name == Variant::get_type_name(p_val.get_type()) || p_arg_type.cname == name_cache.type_Dictionary_generic;
case Variant::OBJECT:
return p_arg_type.is_object_type;
case Variant::VECTOR2I:
@@ -2744,18 +2760,27 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
itype.is_ref_counted = ClassDB::is_parent_class(type_cname, name_cache.type_RefCounted);
itype.memory_own = itype.is_ref_counted;
- itype.c_out = "\treturn ";
+ itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToGodotObject(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromGodotObject(%0)";
+
+ itype.c_out = "%5return ";
itype.c_out += C_METHOD_UNMANAGED_GET_MANAGED;
- itype.c_out += itype.is_ref_counted ? "(%1.ptr());\n" : "(%1);\n";
+ itype.c_out += itype.is_ref_counted ? "(%1.Reference);\n" : "(%1);\n";
+
+ itype.cs_type = itype.proxy_name;
+
+ if (itype.is_singleton) {
+ itype.cs_in_expr = "Object." CS_STATIC_METHOD_GETINSTANCE "(" CS_PROPERTY_SINGLETON ")";
+ } else {
+ itype.cs_in_expr = "Object." CS_STATIC_METHOD_GETINSTANCE "(%0)";
+ }
- itype.cs_in = itype.is_singleton ? BINDINGS_PTR_FIELD : "Object." CS_SMETHOD_GETINSTANCE "(%0)";
+ itype.cs_out = "%5return (%2)%0(%1);";
- itype.c_type = "Object*";
+ itype.c_arg_in = "(void*)%s";
+ itype.c_type = "IntPtr";
itype.c_type_in = itype.c_type;
- itype.c_type_out = "MonoObject*";
- itype.cs_type = itype.proxy_name;
- itype.im_type_in = "IntPtr";
- itype.im_type_out = itype.proxy_name;
+ itype.c_type_out = "Object";
// Populate properties
@@ -2846,6 +2871,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
if (method_info.flags & METHOD_FLAG_VIRTUAL) {
imethod.is_virtual = true;
+ itype.has_virtual_methods = true;
}
PropertyInfo return_info = method_info.return_val;
@@ -2887,7 +2913,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
" Are you returning a reference type by pointer? Method: '" + itype.name + "." + imethod.name + "'.");
} else if (return_info.type == Variant::ARRAY && return_info.hint == PROPERTY_HINT_ARRAY_TYPE) {
- imethod.return_type.cname = Variant::get_type_name(return_info.type);
+ imethod.return_type.cname = Variant::get_type_name(return_info.type) + "_@generic";
imethod.return_type.generic_type_parameters.push_back(TypeReference(return_info.hint_string));
} else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
imethod.return_type.cname = return_info.hint_string;
@@ -2919,7 +2945,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
} else if (arginfo.class_name != StringName()) {
iarg.type.cname = arginfo.class_name;
} else if (arginfo.type == Variant::ARRAY && arginfo.hint == PROPERTY_HINT_ARRAY_TYPE) {
- iarg.type.cname = Variant::get_type_name(arginfo.type);
+ iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
iarg.type.generic_type_parameters.push_back(TypeReference(arginfo.hint_string));
} else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
iarg.type.cname = arginfo.hint_string;
@@ -2985,7 +3011,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
ERR_FAIL_COND_V_MSG(itype.find_property_by_name(imethod.cname), false,
"Method name conflicts with property: '" + itype.name + "." + imethod.name + "'.");
- // Classes starting with an underscore are ignored unless they're used as a property setter or getter
+ // Methods starting with an underscore are ignored unless they're used as a property setter or getter
if (!imethod.is_virtual && imethod.name[0] == '_') {
for (const PropertyInterface &iprop : itype.properties) {
if (iprop.setter == imethod.name || iprop.getter == imethod.name) {
@@ -3027,7 +3053,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
} else if (arginfo.class_name != StringName()) {
iarg.type.cname = arginfo.class_name;
} else if (arginfo.type == Variant::ARRAY && arginfo.hint == PROPERTY_HINT_ARRAY_TYPE) {
- iarg.type.cname = Variant::get_type_name(arginfo.type);
+ iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
iarg.type.generic_type_parameters.push_back(TypeReference(arginfo.hint_string));
} else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
iarg.type.cname = arginfo.hint_string;
@@ -3132,6 +3158,8 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
enum_itype.cname = StringName(enum_itype.name);
enum_itype.proxy_name = itype.proxy_name + "." + enum_proxy_name;
TypeInterface::postsetup_enum_type(enum_itype);
+ enum_itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToInt32(%0)";
+ enum_itype.cs_managed_to_variant = "VariantUtils.CreateFromInt((int)%0)";
enum_types.insert(enum_itype.cname, enum_itype);
}
@@ -3169,7 +3197,7 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
switch (p_val.get_type()) {
case Variant::NIL:
// Either Object type or Variant
- r_iarg.default_argument = "null";
+ r_iarg.default_argument = "default";
break;
// Atomic types
case Variant::BOOL:
@@ -3189,8 +3217,13 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
case Variant::STRING_NAME:
case Variant::NODE_PATH:
if (r_iarg.type.cname == name_cache.type_StringName || r_iarg.type.cname == name_cache.type_NodePath) {
- r_iarg.default_argument = "(%s)\"" + r_iarg.default_argument + "\"";
- r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
+ if (r_iarg.default_argument.length() > 0) {
+ r_iarg.default_argument = "(%s)\"" + r_iarg.default_argument + "\"";
+ r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
+ } else {
+ // No need for a special `in` statement to change `null` to `""`. Marshaling takes care of this already.
+ r_iarg.default_argument = "null";
+ }
} else {
CRASH_COND(r_iarg.type.cname != name_cache.type_String);
r_iarg.default_argument = "\"" + r_iarg.default_argument + "\"";
@@ -3236,8 +3269,11 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
r_iarg.default_argument = "null";
break;
case Variant::DICTIONARY:
- r_iarg.default_argument = "new %s()";
- r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
+ ERR_FAIL_COND_V_MSG(!p_val.operator Dictionary().is_empty(), false,
+ "Default value of type 'Dictionary' must be an empty dictionary.");
+ // The [cs_in] expression already interprets null values as empty dictionaries.
+ r_iarg.default_argument = "null";
+ r_iarg.def_param_mode = ArgumentInterface::CONSTANT;
break;
case Variant::RID:
ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_RID, false,
@@ -3246,11 +3282,14 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
"Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
- r_iarg.default_argument = "null";
+ r_iarg.default_argument = "default";
break;
case Variant::ARRAY:
- r_iarg.default_argument = "new %s { }";
- r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
+ ERR_FAIL_COND_V_MSG(!p_val.operator Array().is_empty(), false,
+ "Default value of type 'Array' must be an empty array.");
+ // The [cs_in] expression already interprets null values as empty arrays.
+ r_iarg.default_argument = "null";
+ r_iarg.def_param_mode = ArgumentInterface::CONSTANT;
break;
case Variant::PACKED_BYTE_ARRAY:
case Variant::PACKED_INT32_ARRAY:
@@ -3325,12 +3364,12 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
r_iarg.default_argument = "default";
break;
default:
- CRASH_NOW_MSG("Unexpected Variant type: " + itos(p_val.get_type()));
+ ERR_FAIL_V_MSG(false, "Unexpected Variant type: " + itos(p_val.get_type()));
break;
}
- if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null") {
- r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
+ if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "default") {
+ r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
}
return true;
@@ -3344,16 +3383,12 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
#define INSERT_STRUCT_TYPE(m_type) \
{ \
itype = TypeInterface::create_value_type(String(#m_type)); \
- itype.c_in = "\t%0 %1_in = MARSHALLED_IN(" #m_type ", %1);\n"; \
- itype.c_out = "\t*%3 = MARSHALLED_OUT(" #m_type ", %1);\n"; \
- itype.c_arg_in = "&%s_in"; \
- itype.c_type_in = "GDMonoMarshal::M_" #m_type "*"; \
- itype.c_type_out = "GDMonoMarshal::M_" #m_type; \
- itype.cs_in = "ref %s"; \
- /* in cs_out, im_type_out (%3) includes the 'out ' part */ \
- itype.cs_out = "%0(%1, %3 argRet); return argRet;"; \
- itype.im_type_out = "out " + itype.cs_type; \
- itype.ret_as_byref_arg = true; \
+ itype.c_type_in = #m_type "*"; \
+ itype.c_type_out = itype.cs_type; \
+ itype.cs_in_expr = "&%0"; \
+ itype.cs_in_expr_is_unsafe = true; \
+ itype.cs_variant_to_managed = "VariantUtils.ConvertTo%2(%0)"; \
+ itype.cs_managed_to_variant = "VariantUtils.CreateFrom%2(%0)"; \
builtin_types.insert(itype.cname, itype); \
}
@@ -3370,54 +3405,60 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
INSERT_STRUCT_TYPE(AABB)
INSERT_STRUCT_TYPE(Color)
INSERT_STRUCT_TYPE(Plane)
+ INSERT_STRUCT_TYPE(Vector4)
+ INSERT_STRUCT_TYPE(Vector4i)
+ INSERT_STRUCT_TYPE(Projection)
#undef INSERT_STRUCT_TYPE
// bool
itype = TypeInterface::create_value_type(String("bool"));
- {
- // MonoBoolean <---> bool
- itype.c_in = "\t%0 %1_in = (%0)%1;\n";
- itype.c_out = "\treturn (%0)%1;\n";
- itype.c_type = "bool";
- itype.c_type_in = "MonoBoolean";
- itype.c_type_out = itype.c_type_in;
- itype.c_arg_in = "&%s_in";
- }
- itype.im_type_in = itype.name;
- itype.im_type_out = itype.name;
+ itype.cs_in_expr = "%0.ToGodotBool()";
+ itype.cs_out = "%5return %0(%1).ToBool();";
+ itype.c_type = "godot_bool";
+ itype.c_type_in = itype.c_type;
+ itype.c_type_out = itype.c_type;
+ itype.c_arg_in = "&%s";
+ itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromBool(%1);\n";
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToBool(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromBool(%0)";
builtin_types.insert(itype.cname, itype);
// Integer types
{
// C interface for 'uint32_t' is the same as that of enums. Remember to apply
// any of the changes done here to 'TypeInterface::postsetup_enum_type' as well.
-#define INSERT_INT_TYPE(m_name, m_c_type_in_out, m_c_type) \
- { \
- itype = TypeInterface::create_value_type(String(m_name)); \
- { \
- itype.c_in = "\t%0 %1_in = (%0)%1;\n"; \
- itype.c_out = "\treturn (%0)%1;\n"; \
- itype.c_type = #m_c_type; \
- itype.c_arg_in = "&%s_in"; \
- } \
- itype.c_type_in = #m_c_type_in_out; \
- itype.c_type_out = itype.c_type_in; \
- itype.im_type_in = itype.name; \
- itype.im_type_out = itype.name; \
- builtin_types.insert(itype.cname, itype); \
+#define INSERT_INT_TYPE(m_name, m_int_struct_name) \
+ { \
+ itype = TypeInterface::create_value_type(String(m_name)); \
+ if (itype.name != "long" && itype.name != "ulong") { \
+ itype.c_in = "%5%0 %1_in = %1;\n"; \
+ itype.c_out = "%5return (%0)%1;\n"; \
+ itype.c_type = "long"; \
+ itype.c_arg_in = "&%s_in"; \
+ } else { \
+ itype.c_arg_in = "&%s"; \
+ } \
+ itype.c_type_in = itype.name; \
+ itype.c_type_out = itype.name; \
+ itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromInt(%1);\n"; \
+ itype.cs_variant_to_managed = "VariantUtils.ConvertTo" m_int_struct_name "(%0)"; \
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromInt(%0)"; \
+ builtin_types.insert(itype.cname, itype); \
}
// The expected type for all integers in ptrcall is 'int64_t', so that's what we use for 'c_type'
- INSERT_INT_TYPE("sbyte", int8_t, int64_t);
- INSERT_INT_TYPE("short", int16_t, int64_t);
- INSERT_INT_TYPE("int", int32_t, int64_t);
- INSERT_INT_TYPE("long", int64_t, int64_t);
- INSERT_INT_TYPE("byte", uint8_t, int64_t);
- INSERT_INT_TYPE("ushort", uint16_t, int64_t);
- INSERT_INT_TYPE("uint", uint32_t, int64_t);
- INSERT_INT_TYPE("ulong", uint64_t, int64_t);
+ INSERT_INT_TYPE("sbyte", "Int8");
+ INSERT_INT_TYPE("short", "Int16");
+ INSERT_INT_TYPE("int", "Int32");
+ INSERT_INT_TYPE("long", "Int64");
+ INSERT_INT_TYPE("byte", "UInt8");
+ INSERT_INT_TYPE("ushort", "UInt16");
+ INSERT_INT_TYPE("uint", "UInt32");
+ INSERT_INT_TYPE("ulong", "UInt64");
+
+#undef INSERT_INT_TYPE
}
// Floating point types
@@ -3427,18 +3468,19 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "float";
itype.cname = itype.name;
itype.proxy_name = "float";
+ itype.cs_type = itype.proxy_name;
{
// The expected type for 'float' in ptrcall is 'double'
- itype.c_in = "\t%0 %1_in = (%0)%1;\n";
- itype.c_out = "\treturn (%0)%1;\n";
+ itype.c_in = "%5%0 %1_in = %1;\n";
+ itype.c_out = "%5return (%0)%1;\n";
itype.c_type = "double";
- itype.c_type_in = "float";
- itype.c_type_out = "float";
itype.c_arg_in = "&%s_in";
}
- itype.cs_type = itype.proxy_name;
- itype.im_type_in = itype.proxy_name;
- itype.im_type_out = itype.proxy_name;
+ itype.c_type_in = itype.proxy_name;
+ itype.c_type_out = itype.proxy_name;
+ itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromFloat(%1);\n";
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToFloat32(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromFloat(%0)";
builtin_types.insert(itype.cname, itype);
// double
@@ -3446,15 +3488,14 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "double";
itype.cname = itype.name;
itype.proxy_name = "double";
- {
- itype.c_type = "double";
- itype.c_type_in = "double";
- itype.c_type_out = "double";
- itype.c_arg_in = "&%s";
- }
itype.cs_type = itype.proxy_name;
- itype.im_type_in = itype.proxy_name;
- itype.im_type_out = itype.proxy_name;
+ itype.c_type = "double";
+ itype.c_arg_in = "&%s";
+ itype.c_type_in = itype.proxy_name;
+ itype.c_type_out = itype.proxy_name;
+ itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromFloat(%1);\n";
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToFloat64(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromFloat(%0)";
builtin_types.insert(itype.cname, itype);
}
@@ -3463,15 +3504,17 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "String";
itype.cname = itype.name;
itype.proxy_name = "string";
- itype.c_in = "\t%0 %1_in = " C_METHOD_MONOSTR_TO_GODOT "(%1);\n";
- itype.c_out = "\treturn " C_METHOD_MONOSTR_FROM_GODOT "(%1);\n";
- itype.c_arg_in = "&%s_in";
- itype.c_type = itype.name;
- itype.c_type_in = "MonoString*";
- itype.c_type_out = "MonoString*";
itype.cs_type = itype.proxy_name;
- itype.im_type_in = itype.proxy_name;
- itype.im_type_out = itype.proxy_name;
+ itype.c_in = "%5using %0 %1_in = " C_METHOD_MONOSTR_TO_GODOT "(%1);\n";
+ itype.c_out = "%5return " C_METHOD_MONOSTR_FROM_GODOT "(%1);\n";
+ itype.c_arg_in = "&%s_in";
+ itype.c_type = "godot_string";
+ itype.c_type_in = itype.cs_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_type_is_disposable_struct = true;
+ itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromString(%1);\n";
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToStringObject(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromString(%0)";
builtin_types.insert(itype.cname, itype);
// StringName
@@ -3479,17 +3522,19 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "StringName";
itype.cname = itype.name;
itype.proxy_name = "StringName";
- itype.c_in = "\t%0 %1_in = %1 ? *%1 : StringName();\n";
- itype.c_out = "\treturn memnew(StringName(%1));\n";
- itype.c_arg_in = "&%s_in";
- itype.c_type = itype.name;
- itype.c_type_in = itype.c_type + "*";
- itype.c_type_out = itype.c_type + "*";
itype.cs_type = itype.proxy_name;
- itype.cs_in = "StringName." CS_SMETHOD_GETINSTANCE "(%0)";
- itype.cs_out = "return new %2(%0(%1));";
- itype.im_type_in = "IntPtr";
- itype.im_type_out = "IntPtr";
+ itype.cs_in_expr = "(%1)(%0?.NativeValue ?? default)";
+ // Cannot pass null StringName to ptrcall
+ itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
+ itype.c_arg_in = "&%s";
+ itype.c_type = "godot_string_name";
+ itype.c_type_in = itype.c_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromStringName(%1);\n";
+ itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
+ itype.c_ret_needs_default_initialization = true;
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToStringNameObject(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromStringName(%0)";
builtin_types.insert(itype.cname, itype);
// NodePath
@@ -3497,15 +3542,18 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "NodePath";
itype.cname = itype.name;
itype.proxy_name = "NodePath";
- itype.c_out = "\treturn memnew(NodePath(%1));\n";
- itype.c_type = itype.name;
- itype.c_type_in = itype.c_type + "*";
- itype.c_type_out = itype.c_type + "*";
itype.cs_type = itype.proxy_name;
- itype.cs_in = "NodePath." CS_SMETHOD_GETINSTANCE "(%0)";
- itype.cs_out = "return new %2(%0(%1));";
- itype.im_type_in = "IntPtr";
- itype.im_type_out = "IntPtr";
+ itype.cs_in_expr = "(%1)(%0?.NativeValue ?? default)";
+ // Cannot pass null NodePath to ptrcall
+ itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
+ itype.c_arg_in = "&%s";
+ itype.c_type = "godot_node_path";
+ itype.c_type_in = itype.c_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
+ itype.c_ret_needs_default_initialization = true;
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToNodePathObject(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromNodePath(%0)";
builtin_types.insert(itype.cname, itype);
// RID
@@ -3513,45 +3561,45 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "RID";
itype.cname = itype.name;
itype.proxy_name = "RID";
- itype.c_out = "\treturn memnew(RID(%1));\n";
- itype.c_type = itype.name;
- itype.c_type_in = itype.c_type + "*";
- itype.c_type_out = itype.c_type + "*";
itype.cs_type = itype.proxy_name;
- itype.cs_in = "RID." CS_SMETHOD_GETINSTANCE "(%0)";
- itype.cs_out = "return new %2(%0(%1));";
- itype.im_type_in = "IntPtr";
- itype.im_type_out = "IntPtr";
+ itype.c_arg_in = "&%s";
+ itype.c_type = itype.cs_type;
+ itype.c_type_in = itype.c_type;
+ itype.c_type_out = itype.c_type;
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToRID(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromRID(%0)";
builtin_types.insert(itype.cname, itype);
// Variant
itype = TypeInterface();
itype.name = "Variant";
itype.cname = itype.name;
- itype.proxy_name = "object";
- itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_VARIANT "(%1);\n";
- itype.c_out = "\treturn " C_METHOD_MANAGED_FROM_VARIANT "(%1);\n";
- itype.c_arg_in = "&%s_in";
- itype.c_type = itype.name;
- itype.c_type_in = "MonoObject*";
- itype.c_type_out = "MonoObject*";
+ itype.proxy_name = "Variant";
itype.cs_type = itype.proxy_name;
- itype.im_type_in = "object";
- itype.im_type_out = itype.proxy_name;
+ itype.c_in = "%5%0 %1_in = (%0)%1.NativeVar;\n";
+ itype.c_out = "%5return Variant.CreateTakingOwnershipOfDisposableValue(%1);\n";
+ itype.c_arg_in = "&%s_in";
+ itype.c_type = "godot_variant";
+ itype.c_type_in = itype.cs_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
+ itype.c_ret_needs_default_initialization = true;
+ itype.cs_variant_to_managed = "Variant.CreateCopyingBorrowed(%0)";
+ itype.cs_managed_to_variant = "%0.CopyNativeVariant()";
builtin_types.insert(itype.cname, itype);
// Callable
itype = TypeInterface::create_value_type(String("Callable"));
- itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_CALLABLE "(*%1);\n";
- itype.c_out = "\t*%3 = " C_METHOD_MANAGED_FROM_CALLABLE "(%1);\n";
+ itype.cs_in_expr = "%0";
+ itype.c_in = "%5using %0 %1_in = " C_METHOD_MANAGED_TO_CALLABLE "(in %1);\n";
+ itype.c_out = "%5return " C_METHOD_MANAGED_FROM_CALLABLE "(in %1);\n";
itype.c_arg_in = "&%s_in";
- itype.c_type_in = "GDMonoMarshal::M_Callable*";
- itype.c_type_out = "GDMonoMarshal::M_Callable";
- itype.cs_in = "ref %s";
- /* in cs_out, im_type_out (%3) includes the 'out ' part */
- itype.cs_out = "%0(%1, %3 argRet); return argRet;";
- itype.im_type_out = "out " + itype.cs_type;
- itype.ret_as_byref_arg = true;
+ itype.c_type = "godot_callable";
+ itype.c_type_in = "in " + itype.cs_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_type_is_disposable_struct = true;
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToCallableManaged(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromCallable(%0)";
builtin_types.insert(itype.cname, itype);
// Signal
@@ -3559,66 +3607,65 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "Signal";
itype.cname = itype.name;
itype.proxy_name = "SignalInfo";
- itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_SIGNAL "(*%1);\n";
- itype.c_out = "\t*%3 = " C_METHOD_MANAGED_FROM_SIGNAL "(%1);\n";
- itype.c_arg_in = "&%s_in";
- itype.c_type = itype.name;
- itype.c_type_in = "GDMonoMarshal::M_SignalInfo*";
- itype.c_type_out = "GDMonoMarshal::M_SignalInfo";
- itype.cs_in = "ref %s";
- /* in cs_out, im_type_out (%3) includes the 'out ' part */
- itype.cs_out = "%0(%1, %3 argRet); return argRet;";
itype.cs_type = itype.proxy_name;
- itype.im_type_in = "ref " + itype.cs_type;
- itype.im_type_out = "out " + itype.cs_type;
- itype.ret_as_byref_arg = true;
+ itype.cs_in_expr = "%0";
+ itype.c_in = "%5using %0 %1_in = " C_METHOD_MANAGED_TO_SIGNAL "(in %1);\n";
+ itype.c_out = "%5return " C_METHOD_MANAGED_FROM_SIGNAL "(&%1);\n";
+ itype.c_arg_in = "&%s_in";
+ itype.c_type = "godot_signal";
+ itype.c_type_in = "in " + itype.cs_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_type_is_disposable_struct = true;
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToSignalInfo(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromSignalInfo(%0)";
builtin_types.insert(itype.cname, itype);
// VarArg (fictitious type to represent variable arguments)
itype = TypeInterface();
itype.name = "VarArg";
itype.cname = itype.name;
- itype.proxy_name = "object[]";
- itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(Array) "(%1);\n";
+ itype.proxy_name = "Variant[]";
+ itype.cs_type = "params Variant[]";
+ itype.cs_in_expr = "%0 ?? Array.Empty<Variant>()";
+ // c_type, c_in and c_arg_in are hard-coded in the generator.
+ // c_out and c_type_out are not applicable to VarArg.
itype.c_arg_in = "&%s_in";
- itype.c_type = "Array";
- itype.c_type_in = "MonoArray*";
- itype.cs_type = "params object[]";
- itype.im_type_in = "object[]";
+ itype.c_type_in = "Variant[]";
builtin_types.insert(itype.cname, itype);
-#define INSERT_ARRAY_FULL(m_name, m_type, m_proxy_t) \
- { \
- itype = TypeInterface(); \
- itype.name = #m_name; \
- itype.cname = itype.name; \
- itype.proxy_name = #m_proxy_t "[]"; \
- itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(m_type) "(%1);\n"; \
- itype.c_out = "\treturn " C_METHOD_MONOARRAY_FROM(m_type) "(%1);\n"; \
- itype.c_arg_in = "&%s_in"; \
- itype.c_type = #m_type; \
- itype.c_type_in = "MonoArray*"; \
- itype.c_type_out = "MonoArray*"; \
- itype.cs_type = itype.proxy_name; \
- itype.im_type_in = itype.proxy_name; \
- itype.im_type_out = itype.proxy_name; \
- builtin_types.insert(itype.name, itype); \
+#define INSERT_ARRAY_FULL(m_name, m_type, m_managed_type, m_proxy_t) \
+ { \
+ itype = TypeInterface(); \
+ itype.name = #m_name; \
+ itype.cname = itype.name; \
+ itype.proxy_name = #m_proxy_t "[]"; \
+ itype.cs_type = itype.proxy_name; \
+ itype.c_in = "%5using %0 %1_in = " C_METHOD_MONOARRAY_TO(m_type) "(%1);\n"; \
+ itype.c_out = "%5return " C_METHOD_MONOARRAY_FROM(m_type) "(%1);\n"; \
+ itype.c_arg_in = "&%s_in"; \
+ itype.c_type = #m_managed_type; \
+ itype.c_type_in = itype.proxy_name; \
+ itype.c_type_out = itype.proxy_name; \
+ itype.c_type_is_disposable_struct = true; \
+ itype.cs_variant_to_managed = "VariantUtils.ConvertAs%2ToSystemArray(%0)"; \
+ itype.cs_managed_to_variant = "VariantUtils.CreateFrom%2(%0)"; \
+ builtin_types.insert(itype.name, itype); \
}
-#define INSERT_ARRAY(m_type, m_proxy_t) INSERT_ARRAY_FULL(m_type, m_type, m_proxy_t)
+#define INSERT_ARRAY(m_type, m_managed_type, m_proxy_t) INSERT_ARRAY_FULL(m_type, m_type, m_managed_type, m_proxy_t)
- INSERT_ARRAY(PackedInt32Array, int);
- INSERT_ARRAY(PackedInt64Array, long);
- INSERT_ARRAY_FULL(PackedByteArray, PackedByteArray, byte);
+ INSERT_ARRAY(PackedInt32Array, godot_packed_int32_array, int);
+ INSERT_ARRAY(PackedInt64Array, godot_packed_int64_array, long);
+ INSERT_ARRAY_FULL(PackedByteArray, PackedByteArray, godot_packed_byte_array, byte);
- INSERT_ARRAY(PackedFloat32Array, float);
- INSERT_ARRAY(PackedFloat64Array, double);
+ INSERT_ARRAY(PackedFloat32Array, godot_packed_float32_array, float);
+ INSERT_ARRAY(PackedFloat64Array, godot_packed_float64_array, double);
- INSERT_ARRAY(PackedStringArray, string);
+ INSERT_ARRAY(PackedStringArray, godot_packed_string_array, string);
- INSERT_ARRAY(PackedColorArray, Color);
- INSERT_ARRAY(PackedVector2Array, Vector2);
- INSERT_ARRAY(PackedVector3Array, Vector3);
+ INSERT_ARRAY(PackedColorArray, godot_packed_color_array, Color);
+ INSERT_ARRAY(PackedVector2Array, godot_packed_vector2_array, Vector2);
+ INSERT_ARRAY(PackedVector3Array, godot_packed_vector3_array, Vector3);
#undef INSERT_ARRAY
@@ -3628,15 +3675,24 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.cname = itype.name;
itype.proxy_name = itype.name;
itype.type_parameter_count = 1;
- itype.c_out = "\treturn memnew(Array(%1));\n";
- itype.c_type = itype.name;
- itype.c_type_in = itype.c_type + "*";
- itype.c_type_out = itype.c_type + "*";
itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
- itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
- itype.cs_out = "return new %2(%0(%1));";
- itype.im_type_in = "IntPtr";
- itype.im_type_out = "IntPtr";
+ itype.cs_in_expr = "(%1)(%0 ?? new()).NativeValue";
+ itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
+ itype.c_arg_in = "&%s";
+ itype.c_type = "godot_array";
+ itype.c_type_in = itype.c_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
+ itype.c_ret_needs_default_initialization = true;
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToArrayObject(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromArray(%0)";
+ builtin_types.insert(itype.cname, itype);
+
+ // Array_@generic
+ // Re-use Array's itype
+ itype.name = "Array_@generic";
+ itype.cname = itype.name;
+ itype.cs_out = "%5return new %2(%0(%1));";
builtin_types.insert(itype.cname, itype);
// Dictionary
@@ -3645,15 +3701,24 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.cname = itype.name;
itype.proxy_name = itype.name;
itype.type_parameter_count = 2;
- itype.c_out = "\treturn memnew(Dictionary(%1));\n";
- itype.c_type = itype.name;
- itype.c_type_in = itype.c_type + "*";
- itype.c_type_out = itype.c_type + "*";
itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
- itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
- itype.cs_out = "return new %2(%0(%1));";
- itype.im_type_in = "IntPtr";
- itype.im_type_out = "IntPtr";
+ itype.cs_in_expr = "(%1)(%0 ?? new()).NativeValue";
+ itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
+ itype.c_arg_in = "&%s";
+ itype.c_type = "godot_dictionary";
+ itype.c_type_in = itype.c_type;
+ itype.c_type_out = itype.cs_type;
+ itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
+ itype.c_ret_needs_default_initialization = true;
+ itype.cs_variant_to_managed = "VariantUtils.ConvertToDictionaryObject(%0)";
+ itype.cs_managed_to_variant = "VariantUtils.CreateFromDictionary(%0)";
+ builtin_types.insert(itype.cname, itype);
+
+ // Dictionary_@generic
+ // Re-use Dictionary's itype
+ itype.name = "Dictionary_@generic";
+ itype.cname = itype.name;
+ itype.cs_out = "%5return new %2(%0(%1));";
builtin_types.insert(itype.cname, itype);
// void (fictitious type to represent the return type of methods that do not return anything)
@@ -3661,12 +3726,10 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.name = "void";
itype.cname = itype.name;
itype.proxy_name = itype.name;
- itype.c_type = itype.name;
+ itype.cs_type = itype.proxy_name;
+ itype.c_type = itype.proxy_name;
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.c_type;
- itype.cs_type = itype.proxy_name;
- itype.im_type_in = itype.proxy_name;
- itype.im_type_out = itype.proxy_name;
builtin_types.insert(itype.cname, itype);
}
@@ -3721,6 +3784,8 @@ void BindingsGenerator::_populate_global_constants() {
enum_itype.cname = ienum.cname;
enum_itype.proxy_name = enum_itype.name;
TypeInterface::postsetup_enum_type(enum_itype);
+ enum_itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToInt32(%0)";
+ enum_itype.cs_managed_to_variant = "VariantUtils.CreateFromInt((int)%0)";
enum_types.insert(enum_itype.cname, enum_itype);
int prefix_length = _determine_enum_prefix(ienum);
@@ -3753,6 +3818,8 @@ void BindingsGenerator::_populate_global_constants() {
enum_itype.cname = enum_cname;
enum_itype.proxy_name = enum_itype.name;
TypeInterface::postsetup_enum_type(enum_itype);
+ enum_itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToInt32(%0)";
+ enum_itype.cs_managed_to_variant = "VariantUtils.CreateFromInt((int)%0)";
enum_types.insert(enum_itype.cname, enum_itype);
}
}
@@ -3791,21 +3858,18 @@ void BindingsGenerator::_initialize() {
// Generate internal calls (after populating type interfaces and global constants)
- core_custom_icalls.clear();
- editor_custom_icalls.clear();
-
for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
- _generate_method_icalls(E.value);
+ const TypeInterface &itype = E.value;
+ Error err = _populate_method_icalls_table(itype);
+ ERR_FAIL_COND_MSG(err != OK, "Failed to generate icalls table for type: " + itype.name);
}
initialized = true;
}
static String generate_all_glue_option = "--generate-mono-glue";
-static String generate_cs_glue_option = "--generate-mono-cs-glue";
-static String generate_cpp_glue_option = "--generate-mono-cpp-glue";
-static void handle_cmdline_options(String glue_dir_path, String cs_dir_path, String cpp_dir_path) {
+static void handle_cmdline_options(String glue_dir_path) {
BindingsGenerator bindings_generator;
bindings_generator.set_log_print_enabled(true);
@@ -3814,43 +3878,25 @@ static void handle_cmdline_options(String glue_dir_path, String cs_dir_path, Str
return;
}
- if (glue_dir_path.length()) {
- if (bindings_generator.generate_glue(glue_dir_path) != OK) {
- ERR_PRINT(generate_all_glue_option + ": Failed to generate the C++ glue.");
- }
-
- if (bindings_generator.generate_cs_api(glue_dir_path.plus_file(API_SOLUTION_NAME)) != OK) {
- ERR_PRINT(generate_all_glue_option + ": Failed to generate the C# API.");
- }
- }
+ CRASH_COND(glue_dir_path.is_empty());
- if (cs_dir_path.length()) {
- if (bindings_generator.generate_cs_api(cs_dir_path) != OK) {
- ERR_PRINT(generate_cs_glue_option + ": Failed to generate the C# API.");
- }
+ if (bindings_generator.generate_cs_api(glue_dir_path.plus_file(API_SOLUTION_NAME)) != OK) {
+ ERR_PRINT(generate_all_glue_option + ": Failed to generate the C# API.");
}
+}
- if (cpp_dir_path.length()) {
- if (bindings_generator.generate_glue(cpp_dir_path) != OK) {
- ERR_PRINT(generate_cpp_glue_option + ": Failed to generate the C++ glue.");
- }
- }
+static void cleanup_and_exit_godot() {
+ // Exit once done
+ Main::cleanup(true);
+ ::exit(0);
}
void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
- const int NUM_OPTIONS = 2;
-
String glue_dir_path;
- String cs_dir_path;
- String cpp_dir_path;
-
- int options_left = NUM_OPTIONS;
-
- bool exit_godot = false;
const List<String>::Element *elem = p_cmdline_args.front();
- while (elem && options_left) {
+ while (elem) {
if (elem->get() == generate_all_glue_option) {
const List<String>::Element *path_elem = elem->next();
@@ -3859,48 +3905,20 @@ void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args)
elem = elem->next();
} else {
ERR_PRINT(generate_all_glue_option + ": No output directory specified (expected path to '{GODOT_ROOT}/modules/mono/glue').");
- exit_godot = true;
- }
-
- --options_left;
- } else if (elem->get() == generate_cs_glue_option) {
- const List<String>::Element *path_elem = elem->next();
-
- if (path_elem) {
- cs_dir_path = path_elem->get();
- elem = elem->next();
- } else {
- ERR_PRINT(generate_cs_glue_option + ": No output directory specified.");
- exit_godot = true;
+ // Exit once done with invalid command line arguments
+ cleanup_and_exit_godot();
}
- --options_left;
- } else if (elem->get() == generate_cpp_glue_option) {
- const List<String>::Element *path_elem = elem->next();
-
- if (path_elem) {
- cpp_dir_path = path_elem->get();
- elem = elem->next();
- } else {
- ERR_PRINT(generate_cpp_glue_option + ": No output directory specified.");
- exit_godot = true;
- }
-
- --options_left;
+ break;
}
elem = elem->next();
}
- if (glue_dir_path.length() || cs_dir_path.length() || cpp_dir_path.length()) {
- handle_cmdline_options(glue_dir_path, cs_dir_path, cpp_dir_path);
- exit_godot = true;
- }
-
- if (exit_godot) {
+ if (glue_dir_path.length()) {
+ handle_cmdline_options(glue_dir_path);
// Exit once done
- Main::cleanup(true);
- ::exit(0);
+ cleanup_and_exit_godot();
}
}
diff --git a/modules/mono/editor/bindings_generator.h b/modules/mono/editor/bindings_generator.h
index ee170e4558..c1295385dc 100644
--- a/modules/mono/editor/bindings_generator.h
+++ b/modules/mono/editor/bindings_generator.h
@@ -229,6 +229,23 @@ class BindingsGenerator {
bool is_ref_counted = false;
/**
+ * Determines whether the native return value of this type must be disposed
+ * by the generated internal call (think of `godot_string`, whose destructor
+ * must be called). Some structs that are disposable may still disable this
+ * flag if the ownership is transferred.
+ */
+ bool c_type_is_disposable_struct = false;
+
+ /**
+ * Determines whether the native return value of this type must be zero initialized
+ * before its address is passed to ptrcall. This is required for types whose destructor
+ * is called before being assigned the return value by `PtrToArg::encode`, e.g.:
+ * Array, Dictionary, String, StringName, Variant.
+ * It's not necessary to set this to `true` if [c_type_is_disposable_struct] is already `true`.
+ */
+ bool c_ret_needs_default_initialization = false;
+
+ /**
* Used only by Object-derived types.
* Determines if this type is not abstract (incomplete).
* e.g.: CanvasItem cannot be instantiated.
@@ -242,31 +259,34 @@ class BindingsGenerator {
*/
bool memory_own = false;
- /**
- * This must be set to true for any struct bigger than 32-bits. Those cannot be passed/returned by value
- * with internal calls, so we must use pointers instead. Returns must be replace with out parameters.
- * In this case, [c_out] and [cs_out] must have a different format, explained below.
- * The Mono IL interpreter icall trampolines don't support passing structs bigger than 32-bits by value (at least not on WASM).
- */
- bool ret_as_byref_arg = false;
-
// !! The comments of the following fields make reference to other fields via square brackets, e.g.: [field_name]
// !! When renaming those fields, make sure to rename their references in the comments
// --- C INTERFACE ---
- static const char *DEFAULT_VARARG_C_IN;
+ /**
+ * One or more statements that transform the parameter before being passed as argument of a ptrcall.
+ * If the statement adds a local that must be passed as the argument instead of the parameter,
+ * the expression with the name of that local must be specified with [c_arg_in].
+ * Formatting elements:
+ * %0: [c_type] of the parameter
+ * %1: name of the parameter
+ * %2-4: reserved
+ * %5: indentation text
+ */
+ String c_in;
/**
- * One or more statements that manipulate the parameter before being passed as argument of a ptrcall.
+ * One or more statements that transform the parameter before being passed as argument of a vararg call.
* If the statement adds a local that must be passed as the argument instead of the parameter,
* the name of that local must be specified with [c_arg_in].
- * For variadic methods, this field is required and, if empty, [DEFAULT_VARARG_C_IN] is used instead.
* Formatting elements:
* %0: [c_type] of the parameter
* %1: name of the parameter
+ * %2-4: reserved
+ * %5: indentation text
*/
- String c_in;
+ String c_in_vararg;
/**
* Determines the expression that will be passed as argument to ptrcall.
@@ -291,7 +311,8 @@ class BindingsGenerator {
* %0: [c_type_out] of the return type
* %1: name of the variable to be returned
* %2: [name] of the return type
- * %3: name of the parameter that must be assigned the return value
+ * %3-4: reserved
+ * %5: indentation text
*/
String c_out;
@@ -327,7 +348,21 @@ class BindingsGenerator {
* An expression that overrides the way the parameter is passed to the internal call.
* If empty, the parameter is passed as is.
* Formatting elements:
- * %0 or %s: name of the parameter
+ * %0: name of the parameter
+ * %1: [c_type] of the parameter
+ */
+ String cs_in_expr;
+ bool cs_in_expr_is_unsafe = false;
+
+ /**
+ * One or more statements that transform the parameter before being passed to the internal call.
+ * If the statement adds a local that must be passed as the argument instead of the parameter,
+ * the expression with the name of that local must be specified with [cs_in_expr].
+ * Formatting elements:
+ * %0: [c_type] of the parameter
+ * %1: name of the parameter
+ * %2-4: reserved
+ * %5: indentation text
*/
String cs_in;
@@ -338,7 +373,9 @@ class BindingsGenerator {
* %0: internal method name
* %1: internal method call arguments without surrounding parenthesis
* %2: [cs_type] of the return type
- * %3: [im_type_out] of the return type
+ * %3: [c_type_out] of the return type
+ * %4: reserved
+ * %5: indentation text
*/
String cs_out;
@@ -349,14 +386,20 @@ class BindingsGenerator {
String cs_type;
/**
- * Type used for parameters of internal call methods.
+ * Formatting elements:
+ * %0: input expression of type `in godot_variant`
+ * %1: [cs_type] of this type
+ * %2: [name] of this type
*/
- String im_type_in;
+ String cs_variant_to_managed;
/**
- * Type used for the return type of internal call methods.
+ * Formatting elements:
+ * %0: input expression
+ * %1: [cs_type] of this type
+ * %2: [name] of this type
*/
- String im_type_out;
+ String cs_managed_to_variant;
const DocData::ClassDoc *class_doc = nullptr;
@@ -366,6 +409,8 @@ class BindingsGenerator {
List<MethodInterface> methods;
List<SignalInterface> signals_;
+ bool has_virtual_methods = false;
+
const MethodInterface *find_method_by_name(const StringName &p_cname) const {
for (const MethodInterface &E : methods) {
if (E.cname == p_cname) {
@@ -432,8 +477,8 @@ class BindingsGenerator {
itype.c_type = itype.name;
itype.cs_type = itype.proxy_name;
- itype.im_type_in = "ref " + itype.proxy_name;
- itype.im_type_out = itype.proxy_name;
+ itype.c_type_in = itype.proxy_name + "*";
+ itype.c_type_out = itype.proxy_name;
itype.class_doc = &EditorHelp::get_doc_data()->class_list[itype.proxy_name];
}
@@ -467,65 +512,27 @@ class BindingsGenerator {
return itype;
}
- static void create_placeholder_type(TypeInterface &r_itype, const StringName &p_cname) {
- r_itype.name = p_cname;
- r_itype.cname = p_cname;
- r_itype.proxy_name = r_itype.name;
-
- r_itype.c_type = r_itype.name;
- r_itype.c_type_in = "MonoObject*";
- r_itype.c_type_out = "MonoObject*";
- r_itype.cs_type = r_itype.proxy_name;
- r_itype.im_type_in = r_itype.proxy_name;
- r_itype.im_type_out = r_itype.proxy_name;
- }
-
- static void postsetup_enum_type(TypeInterface &r_enum_itype) {
- // C interface for enums is the same as that of 'uint32_t'. Remember to apply
- // any of the changes done here to the 'uint32_t' type interface as well.
-
- r_enum_itype.c_arg_in = "&%s_in";
- {
- // The expected types for parameters and return value in ptrcall are 'int64_t' or 'uint64_t'.
- r_enum_itype.c_in = "\t%0 %1_in = (%0)%1;\n";
- r_enum_itype.c_out = "\treturn (%0)%1;\n";
- r_enum_itype.c_type = "int64_t";
- }
- r_enum_itype.c_type_in = "int32_t";
- r_enum_itype.c_type_out = r_enum_itype.c_type_in;
-
- r_enum_itype.cs_type = r_enum_itype.proxy_name;
- r_enum_itype.cs_in = "(int)%s";
- r_enum_itype.cs_out = "return (%2)%0(%1);";
- r_enum_itype.im_type_in = "int";
- r_enum_itype.im_type_out = "int";
- r_enum_itype.class_doc = &EditorHelp::get_doc_data()->class_list[r_enum_itype.proxy_name];
- }
+ static void postsetup_enum_type(TypeInterface &r_enum_itype);
TypeInterface() {}
};
struct InternalCall {
String name;
- String im_type_out; // Return type for the C# method declaration. Also used as companion of [unique_siq]
- String im_sig; // Signature for the C# method declaration
String unique_sig; // Unique signature to avoid duplicates in containers
bool editor_only = false;
- InternalCall() {}
+ bool is_vararg = false;
+ bool is_static = false;
+ TypeReference return_type;
+ List<TypeReference> argument_types;
- InternalCall(const String &p_name, const String &p_im_type_out, const String &p_im_sig = String(), const String &p_unique_sig = String()) {
- name = p_name;
- im_type_out = p_im_type_out;
- im_sig = p_im_sig;
- unique_sig = p_unique_sig;
- editor_only = false;
- }
+ _FORCE_INLINE_ int get_arguments_count() const { return argument_types.size(); }
+
+ InternalCall() {}
- InternalCall(ClassDB::APIType api_type, const String &p_name, const String &p_im_type_out, const String &p_im_sig = String(), const String &p_unique_sig = String()) {
+ InternalCall(ClassDB::APIType api_type, const String &p_name, const String &p_unique_sig = String()) {
name = p_name;
- im_type_out = p_im_type_out;
- im_sig = p_im_sig;
unique_sig = p_unique_sig;
editor_only = api_type == ClassDB::API_EDITOR;
}
@@ -540,7 +547,6 @@ class BindingsGenerator {
HashMap<StringName, TypeInterface> obj_types;
- HashMap<StringName, TypeInterface> placeholder_types;
HashMap<StringName, TypeInterface> builtin_types;
HashMap<StringName, TypeInterface> enum_types;
@@ -548,13 +554,9 @@ class BindingsGenerator {
List<ConstantInterface> global_constants;
List<InternalCall> method_icalls;
+ /// Stores the unique internal calls from [method_icalls] that are assigned to each method.
HashMap<const MethodInterface *, const InternalCall *> method_icalls_map;
- List<const InternalCall *> generated_icall_funcs;
-
- List<InternalCall> core_custom_icalls;
- List<InternalCall> editor_custom_icalls;
-
HashMap<StringName, List<StringName>> blacklisted_methods;
void _initialize_blacklisted_methods();
@@ -571,6 +573,8 @@ class BindingsGenerator {
StringName type_String = StaticCString::create("String");
StringName type_StringName = StaticCString::create("StringName");
StringName type_NodePath = StaticCString::create("NodePath");
+ StringName type_Array_generic = StaticCString::create("Array_@generic");
+ StringName type_Dictionary_generic = StaticCString::create("Dictionary_@generic");
StringName type_at_GlobalScope = StaticCString::create("@GlobalScope");
StringName enum_Error = StaticCString::create("Error");
@@ -595,12 +599,14 @@ class BindingsGenerator {
StringName type_Vector4i = StaticCString::create("Vector4i");
// Object not included as it must be checked for all derived classes
- static constexpr int nullable_types_count = 17;
+ static constexpr int nullable_types_count = 18;
StringName nullable_types[nullable_types_count] = {
type_String,
type_StringName,
type_NodePath,
+ type_Array_generic,
+ type_Dictionary_generic,
StaticCString::create(_STR(Array)),
StaticCString::create(_STR(Dictionary)),
StaticCString::create(_STR(Callable)),
@@ -636,17 +642,6 @@ class BindingsGenerator {
NameCache name_cache;
- const List<InternalCall>::Element *find_icall_by_name(const String &p_name, const List<InternalCall> &p_list) {
- const List<InternalCall>::Element *it = p_list.front();
- while (it) {
- if (it->get().name == p_name) {
- return it;
- }
- it = it->next();
- }
- return nullptr;
- }
-
const ConstantInterface *find_constant_by_name(const String &p_name, const List<ConstantInterface> &p_constants) const {
for (const ConstantInterface &E : p_constants) {
if (E.name == p_name) {
@@ -657,18 +652,38 @@ class BindingsGenerator {
return nullptr;
}
- inline String get_unique_sig(const TypeInterface &p_type) {
- if (p_type.is_ref_counted) {
- return "Ref";
- } else if (p_type.is_object_type) {
+ inline String get_arg_unique_sig(const TypeInterface &p_type) {
+ // For parameters, we treat reference and non-reference derived types the same.
+ if (p_type.is_object_type) {
return "Obj";
} else if (p_type.is_enum) {
return "int";
+ } else if (p_type.cname == name_cache.type_Array_generic) {
+ return "Array";
+ } else if (p_type.cname == name_cache.type_Dictionary_generic) {
+ return "Dictionary";
}
return p_type.name;
}
+ inline String get_ret_unique_sig(const TypeInterface *p_type) {
+ // Reference derived return types are treated differently.
+ if (p_type->is_ref_counted) {
+ return "Ref";
+ } else if (p_type->is_object_type) {
+ return "Obj";
+ } else if (p_type->is_enum) {
+ return "int";
+ } else if (p_type->cname == name_cache.type_Array_generic) {
+ return "Array";
+ } else if (p_type->cname == name_cache.type_Dictionary_generic) {
+ return "Dictionary";
+ }
+
+ return p_type->name;
+ }
+
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);
@@ -682,10 +697,9 @@ class BindingsGenerator {
int _determine_enum_prefix(const EnumInterface &p_ienum);
void _apply_prefix_to_enum_constants(EnumInterface &p_ienum, int p_prefix_length);
- void _generate_method_icalls(const TypeInterface &p_itype);
+ Error _populate_method_icalls_table(const TypeInterface &p_itype);
const TypeInterface *_get_type_or_null(const TypeReference &p_typeref);
- const TypeInterface *_get_type_or_placeholder(const TypeReference &p_typeref);
const String _get_generic_type_parameters(const TypeInterface &p_itype, const List<TypeReference> &p_generic_type_parameters);
@@ -706,11 +720,11 @@ class BindingsGenerator {
Error _generate_cs_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output);
Error _generate_cs_signal(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::SignalInterface &p_isignal, StringBuilder &p_output);
+ Error _generate_cs_native_calls(const InternalCall &p_icall, StringBuilder &r_output);
+
void _generate_array_extensions(StringBuilder &p_output);
void _generate_global_constants(StringBuilder &p_output);
- Error _generate_glue_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, StringBuilder &p_output);
-
Error _save_file(const String &p_path, const StringBuilder &p_content);
void _log(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3;
@@ -721,15 +735,12 @@ public:
Error generate_cs_core_project(const String &p_proj_dir);
Error generate_cs_editor_project(const String &p_proj_dir);
Error generate_cs_api(const String &p_output_dir);
- Error generate_glue(const String &p_output_dir);
_FORCE_INLINE_ bool is_log_print_enabled() { return log_print_enabled; }
_FORCE_INLINE_ void set_log_print_enabled(bool p_enabled) { log_print_enabled = p_enabled; }
_FORCE_INLINE_ bool is_initialized() { return initialized; }
- static uint32_t get_version();
-
static void handle_cmdline_args(const List<String> &p_cmdline_args);
BindingsGenerator() {
diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp
index f830c7ffe1..1ef78c3ac2 100644
--- a/modules/mono/editor/editor_internal_calls.cpp
+++ b/modules/mono/editor/editor_internal_calls.cpp
@@ -46,179 +46,81 @@
#include "main/main.h"
#include "../csharp_script.h"
-#include "../glue/cs_glue_version.gen.h"
#include "../godotsharp_dirs.h"
-#include "../mono_gd/gd_mono_marshal.h"
#include "../utils/macos_utils.h"
#include "code_completion.h"
-#include "godotsharp_export.h"
-MonoString *godot_icall_GodotSharpDirs_ResDataDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_data_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_ResMetadataDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_metadata_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_ResAssembliesBaseDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_assemblies_base_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_ResAssembliesDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_assemblies_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_ResConfigDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_config_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_ResTempDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_ResTempAssembliesBaseDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_assemblies_base_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_ResTempAssembliesDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_assemblies_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_MonoUserDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_user_dir());
-}
+#include "../interop_types.h"
-MonoString *godot_icall_GodotSharpDirs_MonoLogsDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_logs_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_MonoSolutionsDir() {
-#ifdef TOOLS_ENABLED
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_solutions_dir());
-#else
- return nullptr;
+#ifdef __cplusplus
+extern "C" {
#endif
-}
-MonoString *godot_icall_GodotSharpDirs_BuildLogsDirs() {
-#ifdef TOOLS_ENABLED
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_build_logs_dir());
-#else
- return nullptr;
-#endif
+void godot_icall_GodotSharpDirs_ResMetadataDir(godot_string *r_dest) {
+ memnew_placement(r_dest, String(GodotSharpDirs::get_res_metadata_dir()));
}
-MonoString *godot_icall_GodotSharpDirs_ProjectSlnPath() {
-#ifdef TOOLS_ENABLED
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_project_sln_path());
-#else
- return nullptr;
-#endif
+void godot_icall_GodotSharpDirs_MonoUserDir(godot_string *r_dest) {
+ memnew_placement(r_dest, String(GodotSharpDirs::get_mono_user_dir()));
}
-MonoString *godot_icall_GodotSharpDirs_ProjectCsProjPath() {
+void godot_icall_GodotSharpDirs_BuildLogsDirs(godot_string *r_dest) {
#ifdef TOOLS_ENABLED
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_project_csproj_path());
+ memnew_placement(r_dest, String(GodotSharpDirs::get_build_logs_dir()));
#else
return nullptr;
#endif
}
-MonoString *godot_icall_GodotSharpDirs_DataEditorToolsDir() {
+void godot_icall_GodotSharpDirs_DataEditorToolsDir(godot_string *r_dest) {
#ifdef TOOLS_ENABLED
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_editor_tools_dir());
+ memnew_placement(r_dest, String(GodotSharpDirs::get_data_editor_tools_dir()));
#else
return nullptr;
#endif
}
-MonoString *godot_icall_GodotSharpDirs_DataEditorPrebuiltApiDir() {
-#ifdef TOOLS_ENABLED
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_editor_prebuilt_api_dir());
-#else
- return nullptr;
-#endif
-}
-
-MonoString *godot_icall_GodotSharpDirs_DataMonoEtcDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_etc_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_DataMonoLibDir() {
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_lib_dir());
-}
-
-MonoString *godot_icall_GodotSharpDirs_DataMonoBinDir() {
-#ifdef WINDOWS_ENABLED
- return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_bin_dir());
-#else
- return nullptr;
-#endif
-}
-
-void godot_icall_EditorProgress_Create(MonoString *p_task, MonoString *p_label, int32_t p_amount, MonoBoolean p_can_cancel) {
- String task = GDMonoMarshal::mono_string_to_godot(p_task);
- String label = GDMonoMarshal::mono_string_to_godot(p_label);
+void godot_icall_EditorProgress_Create(const godot_string *p_task, const godot_string *p_label, int32_t p_amount, bool p_can_cancel) {
+ String task = *reinterpret_cast<const String *>(p_task);
+ String label = *reinterpret_cast<const String *>(p_label);
EditorNode::progress_add_task(task, label, p_amount, (bool)p_can_cancel);
}
-void godot_icall_EditorProgress_Dispose(MonoString *p_task) {
- String task = GDMonoMarshal::mono_string_to_godot(p_task);
+void godot_icall_EditorProgress_Dispose(const godot_string *p_task) {
+ String task = *reinterpret_cast<const String *>(p_task);
EditorNode::progress_end_task(task);
}
-MonoBoolean godot_icall_EditorProgress_Step(MonoString *p_task, MonoString *p_state, int32_t p_step, MonoBoolean p_force_refresh) {
- String task = GDMonoMarshal::mono_string_to_godot(p_task);
- String state = GDMonoMarshal::mono_string_to_godot(p_state);
+bool godot_icall_EditorProgress_Step(const godot_string *p_task, const godot_string *p_state, int32_t p_step, bool p_force_refresh) {
+ String task = *reinterpret_cast<const String *>(p_task);
+ String state = *reinterpret_cast<const String *>(p_state);
return EditorNode::progress_task_step(task, state, p_step, (bool)p_force_refresh);
}
-uint32_t godot_icall_ExportPlugin_GetExportedAssemblyDependencies(MonoObject *p_initial_assemblies,
- MonoString *p_build_config, MonoString *p_custom_bcl_dir, MonoObject *r_assembly_dependencies) {
- Dictionary initial_dependencies = GDMonoMarshal::mono_object_to_variant(p_initial_assemblies);
- String build_config = GDMonoMarshal::mono_string_to_godot(p_build_config);
- String custom_bcl_dir = GDMonoMarshal::mono_string_to_godot(p_custom_bcl_dir);
- Dictionary assembly_dependencies = GDMonoMarshal::mono_object_to_variant(r_assembly_dependencies);
-
- return GodotSharpExport::get_exported_assembly_dependencies(initial_dependencies, build_config, custom_bcl_dir, assembly_dependencies);
-}
-
-MonoString *godot_icall_Internal_UpdateApiAssembliesFromPrebuilt(MonoString *p_config) {
- String config = GDMonoMarshal::mono_string_to_godot(p_config);
- String error_str = GDMono::get_singleton()->update_api_assemblies_from_prebuilt(config);
- return GDMonoMarshal::mono_string_from_godot(error_str);
-}
-
-MonoString *godot_icall_Internal_FullExportTemplatesDir() {
+void godot_icall_Internal_FullExportTemplatesDir(godot_string *r_dest) {
String full_templates_dir = EditorPaths::get_singleton()->get_export_templates_dir().plus_file(VERSION_FULL_CONFIG);
- return GDMonoMarshal::mono_string_from_godot(full_templates_dir);
-}
-
-MonoString *godot_icall_Internal_SimplifyGodotPath(MonoString *p_path) {
- String path = GDMonoMarshal::mono_string_to_godot(p_path);
- return GDMonoMarshal::mono_string_from_godot(path.simplify_path());
+ memnew_placement(r_dest, String(full_templates_dir));
}
-MonoBoolean godot_icall_Internal_IsMacOSAppBundleInstalled(MonoString *p_bundle_id) {
+bool godot_icall_Internal_IsMacOSAppBundleInstalled(const godot_string *p_bundle_id) {
#ifdef MACOS_ENABLED
- String bundle_id = GDMonoMarshal::mono_string_to_godot(p_bundle_id);
- return (MonoBoolean)macos_is_app_bundle_installed(bundle_id);
+ String bundle_id = *reinterpret_cast<const String *>(p_bundle_id);
+ return (bool)macos_is_app_bundle_installed(bundle_id);
#else
(void)p_bundle_id; // UNUSED
- return (MonoBoolean) false;
+ return (bool)false;
#endif
}
-MonoBoolean godot_icall_Internal_GodotIs32Bits() {
+bool godot_icall_Internal_GodotIs32Bits() {
return sizeof(void *) == 4;
}
-MonoBoolean godot_icall_Internal_GodotIsRealTDouble() {
+bool godot_icall_Internal_GodotIsRealTDouble() {
#ifdef REAL_T_IS_DOUBLE
- return (MonoBoolean) true;
+ return (bool)true;
#else
- return (MonoBoolean) false;
+ return (bool)false;
#endif
}
@@ -226,23 +128,15 @@ void godot_icall_Internal_GodotMainIteration() {
Main::iteration();
}
-uint64_t godot_icall_Internal_GetCoreApiHash() {
- return ClassDB::get_api_hash(ClassDB::API_CORE);
-}
-
-uint64_t godot_icall_Internal_GetEditorApiHash() {
- return ClassDB::get_api_hash(ClassDB::API_EDITOR);
-}
-
-MonoBoolean godot_icall_Internal_IsAssembliesReloadingNeeded() {
+bool godot_icall_Internal_IsAssembliesReloadingNeeded() {
#ifdef GD_MONO_HOT_RELOAD
- return (MonoBoolean)CSharpLanguage::get_singleton()->is_assembly_reloading_needed();
+ return (bool)CSharpLanguage::get_singleton()->is_assembly_reloading_needed();
#else
- return (MonoBoolean) false;
+ return (bool)false;
#endif
}
-void godot_icall_Internal_ReloadAssemblies(MonoBoolean p_soft_reload) {
+void godot_icall_Internal_ReloadAssemblies(bool p_soft_reload) {
#ifdef GD_MONO_HOT_RELOAD
mono_bind::GodotSharp::get_singleton()->call_deferred(SNAME("_reload_assemblies"), (bool)p_soft_reload);
#endif
@@ -252,24 +146,15 @@ void godot_icall_Internal_EditorDebuggerNodeReloadScripts() {
EditorDebuggerNode::get_singleton()->reload_scripts();
}
-MonoBoolean godot_icall_Internal_ScriptEditorEdit(MonoObject *p_resource, int32_t p_line, int32_t p_col, MonoBoolean p_grab_focus) {
- Ref<Resource> resource = GDMonoMarshal::mono_object_to_variant(p_resource);
- return (MonoBoolean)ScriptEditor::get_singleton()->edit(resource, p_line, p_col, (bool)p_grab_focus);
+bool godot_icall_Internal_ScriptEditorEdit(Resource *p_resource, int32_t p_line, int32_t p_col, bool p_grab_focus) {
+ Ref<Resource> resource = p_resource;
+ return (bool)ScriptEditor::get_singleton()->edit(resource, p_line, p_col, (bool)p_grab_focus);
}
void godot_icall_Internal_EditorNodeShowScriptScreen() {
EditorNode::get_singleton()->call("_editor_select", EditorNode::EDITOR_SCRIPT);
}
-MonoString *godot_icall_Internal_MonoWindowsInstallRoot() {
-#ifdef WINDOWS_ENABLED
- String install_root_dir = GDMono::get_singleton()->get_mono_reg_info().install_root_dir;
- return GDMonoMarshal::mono_string_from_godot(install_root_dir);
-#else
- return nullptr;
-#endif
-}
-
void godot_icall_Internal_EditorRunPlay() {
EditorNode::get_singleton()->run_play();
}
@@ -285,114 +170,93 @@ void godot_icall_Internal_ScriptEditorDebugger_ReloadScripts() {
}
}
-MonoArray *godot_icall_Internal_CodeCompletionRequest(int32_t p_kind, MonoString *p_script_file) {
- String script_file = GDMonoMarshal::mono_string_to_godot(p_script_file);
+void godot_icall_Internal_CodeCompletionRequest(int32_t p_kind, const godot_string *p_script_file, godot_packed_array *r_ret) {
+ String script_file = *reinterpret_cast<const String *>(p_script_file);
PackedStringArray suggestions = gdmono::get_code_completion((gdmono::CompletionKind)p_kind, script_file);
- return GDMonoMarshal::PackedStringArray_to_mono_array(suggestions);
+ memnew_placement(r_ret, PackedStringArray(suggestions));
}
float godot_icall_Globals_EditorScale() {
return EDSCALE;
}
-MonoObject *godot_icall_Globals_GlobalDef(MonoString *p_setting, MonoObject *p_default_value, MonoBoolean p_restart_if_changed) {
- String setting = GDMonoMarshal::mono_string_to_godot(p_setting);
- Variant default_value = GDMonoMarshal::mono_object_to_variant(p_default_value);
+void godot_icall_Globals_GlobalDef(const godot_string *p_setting, const godot_variant *p_default_value, bool p_restart_if_changed, godot_variant *r_result) {
+ String setting = *reinterpret_cast<const String *>(p_setting);
+ Variant default_value = *reinterpret_cast<const Variant *>(p_default_value);
Variant result = _GLOBAL_DEF(setting, default_value, (bool)p_restart_if_changed);
- return GDMonoMarshal::variant_to_mono_object(result);
+ memnew_placement(r_result, Variant(result));
}
-MonoObject *godot_icall_Globals_EditorDef(MonoString *p_setting, MonoObject *p_default_value, MonoBoolean p_restart_if_changed) {
- String setting = GDMonoMarshal::mono_string_to_godot(p_setting);
- Variant default_value = GDMonoMarshal::mono_object_to_variant(p_default_value);
+void godot_icall_Globals_EditorDef(const godot_string *p_setting, const godot_variant *p_default_value, bool p_restart_if_changed, godot_variant *r_result) {
+ String setting = *reinterpret_cast<const String *>(p_setting);
+ Variant default_value = *reinterpret_cast<const Variant *>(p_default_value);
Variant result = _EDITOR_DEF(setting, default_value, (bool)p_restart_if_changed);
- return GDMonoMarshal::variant_to_mono_object(result);
+ memnew_placement(r_result, Variant(result));
}
-MonoObject *godot_icall_Globals_EditorShortcut(MonoString *p_setting) {
- String setting = GDMonoMarshal::mono_string_to_godot(p_setting);
+void godot_icall_Globals_EditorShortcut(const godot_string *p_setting, godot_variant *r_result) {
+ String setting = *reinterpret_cast<const String *>(p_setting);
Ref<Shortcut> result = ED_GET_SHORTCUT(setting);
- return GDMonoMarshal::variant_to_mono_object(result);
+ memnew_placement(r_result, Variant(result));
}
-MonoString *godot_icall_Globals_TTR(MonoString *p_text) {
- String text = GDMonoMarshal::mono_string_to_godot(p_text);
- return GDMonoMarshal::mono_string_from_godot(TTR(text));
+void godot_icall_Globals_TTR(const godot_string *p_text, godot_string *r_dest) {
+ String text = *reinterpret_cast<const String *>(p_text);
+ memnew_placement(r_dest, String(TTR(text)));
}
-MonoString *godot_icall_Utils_OS_GetPlatformName() {
+void godot_icall_Utils_OS_GetPlatformName(godot_string *r_dest) {
String os_name = OS::get_singleton()->get_name();
- return GDMonoMarshal::mono_string_from_godot(os_name);
+ memnew_placement(r_dest, String(os_name));
}
-MonoBoolean godot_icall_Utils_OS_UnixFileHasExecutableAccess(MonoString *p_file_path) {
+bool godot_icall_Utils_OS_UnixFileHasExecutableAccess(const godot_string *p_file_path) {
#ifdef UNIX_ENABLED
- String file_path = GDMonoMarshal::mono_string_to_godot(p_file_path);
+ String file_path = *reinterpret_cast<const String *>(p_file_path);
return access(file_path.utf8().get_data(), X_OK) == 0;
#else
ERR_FAIL_V(false);
#endif
}
-void register_editor_internal_calls() {
- // GodotSharpDirs
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResDataDir", godot_icall_GodotSharpDirs_ResDataDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResMetadataDir", godot_icall_GodotSharpDirs_ResMetadataDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesBaseDir", godot_icall_GodotSharpDirs_ResAssembliesBaseDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesDir", godot_icall_GodotSharpDirs_ResAssembliesDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResConfigDir", godot_icall_GodotSharpDirs_ResConfigDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempDir", godot_icall_GodotSharpDirs_ResTempDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesBaseDir", godot_icall_GodotSharpDirs_ResTempAssembliesBaseDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesDir", godot_icall_GodotSharpDirs_ResTempAssembliesDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoUserDir", godot_icall_GodotSharpDirs_MonoUserDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoLogsDir", godot_icall_GodotSharpDirs_MonoLogsDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoSolutionsDir", godot_icall_GodotSharpDirs_MonoSolutionsDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_BuildLogsDirs", godot_icall_GodotSharpDirs_BuildLogsDirs);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectSlnPath", godot_icall_GodotSharpDirs_ProjectSlnPath);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectCsProjPath", godot_icall_GodotSharpDirs_ProjectCsProjPath);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorToolsDir", godot_icall_GodotSharpDirs_DataEditorToolsDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorPrebuiltApiDir", godot_icall_GodotSharpDirs_DataEditorPrebuiltApiDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoEtcDir", godot_icall_GodotSharpDirs_DataMonoEtcDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoLibDir", godot_icall_GodotSharpDirs_DataMonoLibDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoBinDir", godot_icall_GodotSharpDirs_DataMonoBinDir);
-
- // EditorProgress
- GDMonoUtils::add_internal_call("GodotTools.Internals.EditorProgress::internal_Create", godot_icall_EditorProgress_Create);
- GDMonoUtils::add_internal_call("GodotTools.Internals.EditorProgress::internal_Dispose", godot_icall_EditorProgress_Dispose);
- GDMonoUtils::add_internal_call("GodotTools.Internals.EditorProgress::internal_Step", godot_icall_EditorProgress_Step);
-
- // ExportPlugin
- GDMonoUtils::add_internal_call("GodotTools.Export.ExportPlugin::internal_GetExportedAssemblyDependencies", godot_icall_ExportPlugin_GetExportedAssemblyDependencies);
-
- // Internals
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_UpdateApiAssembliesFromPrebuilt", godot_icall_Internal_UpdateApiAssembliesFromPrebuilt);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_FullExportTemplatesDir", godot_icall_Internal_FullExportTemplatesDir);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_SimplifyGodotPath", godot_icall_Internal_SimplifyGodotPath);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_IsMacOSAppBundleInstalled", godot_icall_Internal_IsMacOSAppBundleInstalled);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GodotIs32Bits", godot_icall_Internal_GodotIs32Bits);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GodotIsRealTDouble", godot_icall_Internal_GodotIsRealTDouble);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GodotMainIteration", godot_icall_Internal_GodotMainIteration);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GetCoreApiHash", godot_icall_Internal_GetCoreApiHash);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GetEditorApiHash", godot_icall_Internal_GetEditorApiHash);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_IsAssembliesReloadingNeeded", godot_icall_Internal_IsAssembliesReloadingNeeded);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_ReloadAssemblies", godot_icall_Internal_ReloadAssemblies);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorDebuggerNodeReloadScripts", godot_icall_Internal_EditorDebuggerNodeReloadScripts);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorEdit", godot_icall_Internal_ScriptEditorEdit);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorNodeShowScriptScreen", godot_icall_Internal_EditorNodeShowScriptScreen);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_MonoWindowsInstallRoot", godot_icall_Internal_MonoWindowsInstallRoot);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorRunPlay", godot_icall_Internal_EditorRunPlay);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorRunStop", godot_icall_Internal_EditorRunStop);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorDebugger_ReloadScripts", godot_icall_Internal_ScriptEditorDebugger_ReloadScripts);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_CodeCompletionRequest", godot_icall_Internal_CodeCompletionRequest);
-
- // Globals
- GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorScale", godot_icall_Globals_EditorScale);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_GlobalDef", godot_icall_Globals_GlobalDef);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorDef", godot_icall_Globals_EditorDef);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorShortcut", godot_icall_Globals_EditorShortcut);
- GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_TTR", godot_icall_Globals_TTR);
-
- // Utils.OS
- GDMonoUtils::add_internal_call("GodotTools.Utils.OS::GetPlatformName", godot_icall_Utils_OS_GetPlatformName);
- GDMonoUtils::add_internal_call("GodotTools.Utils.OS::UnixFileHasExecutableAccess", godot_icall_Utils_OS_UnixFileHasExecutableAccess);
+#ifdef __cplusplus
+}
+#endif
+
+// The order in this array must match the declaration order of
+// the methods in 'GodotTools/Internals/Internal.cs'.
+static const void *unmanaged_callbacks[]{
+ (void *)godot_icall_GodotSharpDirs_ResMetadataDir,
+ (void *)godot_icall_GodotSharpDirs_MonoUserDir,
+ (void *)godot_icall_GodotSharpDirs_BuildLogsDirs,
+ (void *)godot_icall_GodotSharpDirs_DataEditorToolsDir,
+ (void *)godot_icall_EditorProgress_Create,
+ (void *)godot_icall_EditorProgress_Dispose,
+ (void *)godot_icall_EditorProgress_Step,
+ (void *)godot_icall_Internal_FullExportTemplatesDir,
+ (void *)godot_icall_Internal_IsMacOSAppBundleInstalled,
+ (void *)godot_icall_Internal_GodotIs32Bits,
+ (void *)godot_icall_Internal_GodotIsRealTDouble,
+ (void *)godot_icall_Internal_GodotMainIteration,
+ (void *)godot_icall_Internal_IsAssembliesReloadingNeeded,
+ (void *)godot_icall_Internal_ReloadAssemblies,
+ (void *)godot_icall_Internal_EditorDebuggerNodeReloadScripts,
+ (void *)godot_icall_Internal_ScriptEditorEdit,
+ (void *)godot_icall_Internal_EditorNodeShowScriptScreen,
+ (void *)godot_icall_Internal_EditorRunPlay,
+ (void *)godot_icall_Internal_EditorRunStop,
+ (void *)godot_icall_Internal_ScriptEditorDebugger_ReloadScripts,
+ (void *)godot_icall_Internal_CodeCompletionRequest,
+ (void *)godot_icall_Globals_EditorScale,
+ (void *)godot_icall_Globals_GlobalDef,
+ (void *)godot_icall_Globals_EditorDef,
+ (void *)godot_icall_Globals_EditorShortcut,
+ (void *)godot_icall_Globals_TTR,
+ (void *)godot_icall_Utils_OS_GetPlatformName,
+ (void *)godot_icall_Utils_OS_UnixFileHasExecutableAccess,
+};
+
+const void **godotsharp::get_editor_interop_funcs(int32_t &r_size) {
+ r_size = sizeof(unmanaged_callbacks);
+ return unmanaged_callbacks;
}
diff --git a/modules/mono/editor/editor_internal_calls.h b/modules/mono/editor/editor_internal_calls.h
index 8262ac211a..35391f1f04 100644
--- a/modules/mono/editor/editor_internal_calls.h
+++ b/modules/mono/editor/editor_internal_calls.h
@@ -31,6 +31,10 @@
#ifndef EDITOR_INTERNAL_CALLS_H
#define EDITOR_INTERNAL_CALLS_H
-void register_editor_internal_calls();
+#include "core/typedefs.h"
+
+namespace godotsharp {
+const void **get_editor_interop_funcs(int32_t &r_size);
+}
#endif // EDITOR_INTERNAL_CALLS_H
diff --git a/modules/mono/editor/godotsharp_export.cpp b/modules/mono/editor/godotsharp_export.cpp
deleted file mode 100644
index f9ea403334..0000000000
--- a/modules/mono/editor/godotsharp_export.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/*************************************************************************/
-/* godotsharp_export.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 "godotsharp_export.h"
-
-#include <mono/metadata/image.h>
-
-#include "core/config/project_settings.h"
-#include "core/io/file_access_pack.h"
-#include "core/os/os.h"
-
-#include "../mono_gd/gd_mono.h"
-#include "../mono_gd/gd_mono_assembly.h"
-#include "../mono_gd/gd_mono_cache.h"
-#include "../utils/macros.h"
-
-namespace GodotSharpExport {
-
-MonoAssemblyName *new_mono_assembly_name() {
- // Mono has no public API to create an empty MonoAssemblyName and the struct is private.
- // As such the only way to create it is with a stub name and then clear it.
-
- MonoAssemblyName *aname = mono_assembly_name_new("stub");
- CRASH_COND(aname == nullptr);
- mono_assembly_name_free(aname); // Frees the string fields, not the struct
- return aname;
-}
-
-struct AssemblyRefInfo {
- String name;
- uint16_t major = 0;
- uint16_t minor = 0;
- uint16_t build = 0;
- uint16_t revision = 0;
-};
-
-AssemblyRefInfo get_assemblyref_name(MonoImage *p_image, int index) {
- const MonoTableInfo *table_info = mono_image_get_table_info(p_image, MONO_TABLE_ASSEMBLYREF);
-
- uint32_t cols[MONO_ASSEMBLYREF_SIZE];
-
- mono_metadata_decode_row(table_info, index, cols, MONO_ASSEMBLYREF_SIZE);
-
- return {
- String::utf8(mono_metadata_string_heap(p_image, cols[MONO_ASSEMBLYREF_NAME])),
- (uint16_t)cols[MONO_ASSEMBLYREF_MAJOR_VERSION],
- (uint16_t)cols[MONO_ASSEMBLYREF_MINOR_VERSION],
- (uint16_t)cols[MONO_ASSEMBLYREF_BUILD_NUMBER],
- (uint16_t)cols[MONO_ASSEMBLYREF_REV_NUMBER]
- };
-}
-
-Error get_assembly_dependencies(GDMonoAssembly *p_assembly, MonoAssemblyName *reusable_aname, const Vector<String> &p_search_dirs, Dictionary &r_assembly_dependencies) {
- MonoImage *image = p_assembly->get_image();
-
- for (int i = 0; i < mono_image_get_table_rows(image, MONO_TABLE_ASSEMBLYREF); i++) {
- AssemblyRefInfo ref_info = get_assemblyref_name(image, i);
-
- const String &ref_name = ref_info.name;
-
- if (r_assembly_dependencies.has(ref_name)) {
- continue;
- }
-
- mono_assembly_get_assemblyref(image, i, reusable_aname);
-
- GDMonoAssembly *ref_assembly = nullptr;
- if (!GDMono::get_singleton()->load_assembly(ref_name, reusable_aname, &ref_assembly, /* refonly: */ true, p_search_dirs)) {
- ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + ref_name + "'.");
- }
-
- r_assembly_dependencies[ref_name] = ref_assembly->get_path();
-
- Error err = get_assembly_dependencies(ref_assembly, reusable_aname, p_search_dirs, r_assembly_dependencies);
- ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot load one of the dependencies for the assembly: '" + ref_name + "'.");
- }
-
- return OK;
-}
-
-Error get_exported_assembly_dependencies(const Dictionary &p_initial_assemblies,
- const String &p_build_config, const String &p_custom_bcl_dir, Dictionary &r_assembly_dependencies) {
- MonoDomain *export_domain = GDMonoUtils::create_domain("GodotEngine.Domain.ProjectExport");
- ERR_FAIL_NULL_V(export_domain, FAILED);
- _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(export_domain);
-
- _GDMONO_SCOPE_DOMAIN_(export_domain);
-
- Vector<String> search_dirs;
- GDMonoAssembly::fill_search_dirs(search_dirs, p_build_config, p_custom_bcl_dir);
-
- if (p_custom_bcl_dir.length()) {
- // Only one mscorlib can be loaded. We need this workaround to make sure we get it from the right BCL directory.
- r_assembly_dependencies["mscorlib"] = p_custom_bcl_dir.plus_file("mscorlib.dll").simplify_path();
- }
-
- for (const Variant *key = p_initial_assemblies.next(); key; key = p_initial_assemblies.next(key)) {
- String assembly_name = *key;
- String assembly_path = p_initial_assemblies[*key];
-
- GDMonoAssembly *assembly = nullptr;
- bool load_success = GDMono::get_singleton()->load_assembly_from(assembly_name, assembly_path, &assembly, /* refonly: */ true);
-
- ERR_FAIL_COND_V_MSG(!load_success, ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + assembly_name + "'.");
-
- MonoAssemblyName *reusable_aname = new_mono_assembly_name();
- SCOPE_EXIT { mono_free(reusable_aname); };
-
- Error err = get_assembly_dependencies(assembly, reusable_aname, search_dirs, r_assembly_dependencies);
- if (err != OK) {
- return err;
- }
- }
-
- return OK;
-}
-} // namespace GodotSharpExport
diff --git a/modules/mono/editor/godotsharp_export.h b/modules/mono/editor/godotsharp_export.h
deleted file mode 100644
index 60620b5f4d..0000000000
--- a/modules/mono/editor/godotsharp_export.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*************************************************************************/
-/* godotsharp_export.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 GODOTSHARP_EXPORT_H
-#define GODOTSHARP_EXPORT_H
-
-#include "core/error/error_list.h"
-#include "core/string/ustring.h"
-#include "core/variant/dictionary.h"
-
-#include "../mono_gd/gd_mono_header.h"
-
-namespace GodotSharpExport {
-
-Error get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Dictionary &r_dependencies);
-
-Error get_exported_assembly_dependencies(const Dictionary &p_initial_assemblies,
- const String &p_build_config, const String &p_custom_lib_dir, Dictionary &r_assembly_dependencies);
-} // namespace GodotSharpExport
-
-#endif // GODOTSHARP_EXPORT_H
diff --git a/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs b/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs
index 2ca81ab7cd..c34f1a17f3 100644
--- a/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs
+++ b/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs
@@ -9,7 +9,7 @@ public partial class _CLASS_ : _BASE_
public const float JumpVelocity = -400.0f;
// Get the gravity from the project settings to be synced with RigidDynamicBody nodes.
- public float gravity = (float)ProjectSettings.GetSetting("physics/2d/default_gravity");
+ public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
public override void _PhysicsProcess(float delta)
{
diff --git a/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs b/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs
index a6935fe497..069908c426 100644
--- a/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs
+++ b/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs
@@ -9,7 +9,7 @@ public partial class _CLASS_ : _BASE_
public const float JumpVelocity = 4.5f;
// Get the gravity from the project settings to be synced with RigidDynamicBody nodes.
- public float gravity = (float)ProjectSettings.GetSetting("physics/3d/default_gravity");
+ public float gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle();
public override void _PhysicsProcess(float delta)
{
@@ -26,7 +26,7 @@ public partial class _CLASS_ : _BASE_
// Get the input direction and handle the movement/deceleration.
// As good practice, you should replace UI actions with custom gameplay actions.
Vector2 inputDir = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
- Vector3 direction = Transform.basis.Xform(new Vector3(inputDir.x, 0, inputDir.y)).Normalized();
+ Vector3 direction = (Transform.basis * new Vector3(inputDir.x, 0, inputDir.y)).Normalized();
if (direction != Vector3.Zero)
{
velocity.x = direction.x * Speed;
diff --git a/modules/mono/editor/script_templates/VisualShaderNodeCustom/basic.cs b/modules/mono/editor/script_templates/VisualShaderNodeCustom/basic.cs
index a1b93e7daa..bb482e0d6a 100644
--- a/modules/mono/editor/script_templates/VisualShaderNodeCustom/basic.cs
+++ b/modules/mono/editor/script_templates/VisualShaderNodeCustom/basic.cs
@@ -55,7 +55,7 @@ public partial class VisualShaderNode_CLASS_ : _BASE_
return 0;
}
- public override string _GetCode(Godot.Collections.Array inputVars, Godot.Collections.Array outputVars, Shader.Mode mode, VisualShader.Type type)
+ public override string _GetCode(Godot.Collections.Array<string> inputVars, Godot.Collections.Array<string> outputVars, Shader.Mode mode, VisualShader.Type type)
{
return "";
}
diff --git a/modules/mono/glue/GodotSharp/.editorconfig b/modules/mono/glue/GodotSharp/.editorconfig
new file mode 100644
index 0000000000..d4e71b1bd9
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/.editorconfig
@@ -0,0 +1,8 @@
+[**/Generated/**.cs]
+# Validate parameter is non-null before using it
+# Useful for generated code, as it disables nullable
+dotnet_diagnostic.CA1062.severity = error
+# CA1069: Enums should not have duplicate values
+dotnet_diagnostic.CA1069.severity = none
+# CA1708: Identifiers should differ by more than case
+dotnet_diagnostic.CA1708.severity = none
diff --git a/modules/mono/glue/GodotSharp/ExternalAnnotations/System.Runtime.InteropServices.xml b/modules/mono/glue/GodotSharp/ExternalAnnotations/System.Runtime.InteropServices.xml
new file mode 100644
index 0000000000..2dc350d4f2
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/ExternalAnnotations/System.Runtime.InteropServices.xml
@@ -0,0 +1,5 @@
+<assembly name="System.Runtime.InteropServices">
+ <member name="T:System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute">
+ <attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
+ </member>
+</assembly>
diff --git a/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/CallbacksInfo.cs b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/CallbacksInfo.cs
new file mode 100644
index 0000000000..686023a077
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/CallbacksInfo.cs
@@ -0,0 +1,24 @@
+using System.Collections.Immutable;
+using System.Linq;
+using Microsoft.CodeAnalysis;
+
+namespace Godot.SourceGenerators.Internal;
+
+internal struct CallbacksData
+{
+ public CallbacksData(INamedTypeSymbol nativeTypeSymbol, INamedTypeSymbol funcStructSymbol)
+ {
+ NativeTypeSymbol = nativeTypeSymbol;
+ FuncStructSymbol = funcStructSymbol;
+ Methods = NativeTypeSymbol.GetMembers()
+ .Where(symbol => symbol is IMethodSymbol { IsPartialDefinition: true })
+ .Cast<IMethodSymbol>()
+ .ToImmutableArray();
+ }
+
+ public INamedTypeSymbol NativeTypeSymbol { get; }
+
+ public INamedTypeSymbol FuncStructSymbol { get; }
+
+ public ImmutableArray<IMethodSymbol> Methods { get; }
+}
diff --git a/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Common.cs b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Common.cs
new file mode 100644
index 0000000000..16e96c725a
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Common.cs
@@ -0,0 +1,65 @@
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace Godot.SourceGenerators.Internal;
+
+internal static class Common
+{
+ public static void ReportNonPartialUnmanagedCallbacksClass(
+ GeneratorExecutionContext context,
+ ClassDeclarationSyntax cds, INamedTypeSymbol symbol
+ )
+ {
+ string message =
+ "Missing partial modifier on declaration of type '" +
+ $"{symbol.FullQualifiedName()}' which has attribute '{GeneratorClasses.GenerateUnmanagedCallbacksAttr}'";
+
+ string description = $"{message}. Classes with attribute '{GeneratorClasses.GenerateUnmanagedCallbacksAttr}' " +
+ "must be declared with the partial modifier.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GODOT-INTERNAL-G0001",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ cds.GetLocation(),
+ cds.SyntaxTree.FilePath));
+ }
+
+ public static void ReportNonPartialUnmanagedCallbacksOuterClass(
+ GeneratorExecutionContext context,
+ TypeDeclarationSyntax outerTypeDeclSyntax
+ )
+ {
+ var outerSymbol = context.Compilation
+ .GetSemanticModel(outerTypeDeclSyntax.SyntaxTree)
+ .GetDeclaredSymbol(outerTypeDeclSyntax);
+
+ string fullQualifiedName = outerSymbol is INamedTypeSymbol namedTypeSymbol ?
+ namedTypeSymbol.FullQualifiedName() :
+ "type not found";
+
+ string message =
+ $"Missing partial modifier on declaration of type '{fullQualifiedName}', " +
+ $"which contains one or more subclasses with attribute " +
+ $"'{GeneratorClasses.GenerateUnmanagedCallbacksAttr}'";
+
+ string description = $"{message}. Classes with attribute " +
+ $"'{GeneratorClasses.GenerateUnmanagedCallbacksAttr}' and their " +
+ "containing types must be declared with the partial modifier.";
+
+ context.ReportDiagnostic(Diagnostic.Create(
+ new DiagnosticDescriptor(id: "GODOT-INTERNAL-G0002",
+ title: message,
+ messageFormat: message,
+ category: "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description),
+ outerTypeDeclSyntax.GetLocation(),
+ outerTypeDeclSyntax.SyntaxTree.FilePath));
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/ExtensionMethods.cs b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/ExtensionMethods.cs
new file mode 100644
index 0000000000..fac362479a
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/ExtensionMethods.cs
@@ -0,0 +1,119 @@
+using System.Collections.Generic;
+using System.Linq;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace Godot.SourceGenerators.Internal;
+
+internal static class ExtensionMethods
+{
+ public static AttributeData? GetGenerateUnmanagedCallbacksAttribute(this INamedTypeSymbol symbol)
+ => symbol.GetAttributes()
+ .FirstOrDefault(a => a.AttributeClass?.IsGenerateUnmanagedCallbacksAttribute() ?? false);
+
+ private static bool HasGenerateUnmanagedCallbacksAttribute(
+ this ClassDeclarationSyntax cds, Compilation compilation,
+ out INamedTypeSymbol? symbol
+ )
+ {
+ var sm = compilation.GetSemanticModel(cds.SyntaxTree);
+
+ var classTypeSymbol = sm.GetDeclaredSymbol(cds);
+ if (classTypeSymbol == null)
+ {
+ symbol = null;
+ return false;
+ }
+
+ if (!classTypeSymbol.GetAttributes()
+ .Any(a => a.AttributeClass?.IsGenerateUnmanagedCallbacksAttribute() ?? false))
+ {
+ symbol = null;
+ return false;
+ }
+
+ symbol = classTypeSymbol;
+ return true;
+ }
+
+ private static bool IsGenerateUnmanagedCallbacksAttribute(this INamedTypeSymbol symbol)
+ => symbol.ToString() == GeneratorClasses.GenerateUnmanagedCallbacksAttr;
+
+ public static IEnumerable<(ClassDeclarationSyntax cds, INamedTypeSymbol symbol)> SelectUnmanagedCallbacksClasses(
+ this IEnumerable<ClassDeclarationSyntax> source,
+ Compilation compilation
+ )
+ {
+ foreach (var cds in source)
+ {
+ if (cds.HasGenerateUnmanagedCallbacksAttribute(compilation, out var symbol))
+ yield return (cds, symbol!);
+ }
+ }
+
+ public static bool IsNested(this TypeDeclarationSyntax cds)
+ => cds.Parent is TypeDeclarationSyntax;
+
+ public static bool IsPartial(this TypeDeclarationSyntax cds)
+ => cds.Modifiers.Any(SyntaxKind.PartialKeyword);
+
+ public static bool AreAllOuterTypesPartial(
+ this TypeDeclarationSyntax cds,
+ out TypeDeclarationSyntax? typeMissingPartial
+ )
+ {
+ SyntaxNode? outerSyntaxNode = cds.Parent;
+
+ while (outerSyntaxNode is TypeDeclarationSyntax outerTypeDeclSyntax)
+ {
+ if (!outerTypeDeclSyntax.IsPartial())
+ {
+ typeMissingPartial = outerTypeDeclSyntax;
+ return false;
+ }
+
+ outerSyntaxNode = outerSyntaxNode.Parent;
+ }
+
+ typeMissingPartial = null;
+ return true;
+ }
+
+ public static string GetDeclarationKeyword(this INamedTypeSymbol namedTypeSymbol)
+ {
+ string? keyword = namedTypeSymbol.DeclaringSyntaxReferences
+ .OfType<TypeDeclarationSyntax>().FirstOrDefault()?
+ .Keyword.Text;
+
+ return keyword ?? namedTypeSymbol.TypeKind switch
+ {
+ TypeKind.Interface => "interface",
+ TypeKind.Struct => "struct",
+ _ => "class"
+ };
+ }
+
+ private static SymbolDisplayFormat FullyQualifiedFormatOmitGlobal { get; } =
+ SymbolDisplayFormat.FullyQualifiedFormat
+ .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
+
+ public static string FullQualifiedName(this ITypeSymbol symbol)
+ => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatOmitGlobal);
+
+ public static string NameWithTypeParameters(this INamedTypeSymbol symbol)
+ {
+ return symbol.IsGenericType ?
+ string.Concat(symbol.Name, "<", string.Join(", ", symbol.TypeParameters), ">") :
+ symbol.Name;
+ }
+
+ public static string FullQualifiedName(this INamespaceSymbol symbol)
+ => symbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
+
+ public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
+ => qualifiedName
+ // AddSource() doesn't support angle brackets
+ .Replace("<", "(Of ")
+ .Replace(">", ")");
+}
diff --git a/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/GeneratorClasses.cs b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/GeneratorClasses.cs
new file mode 100644
index 0000000000..1bbb33f5a1
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/GeneratorClasses.cs
@@ -0,0 +1,6 @@
+namespace Godot.SourceGenerators.Internal;
+
+internal static class GeneratorClasses
+{
+ public const string GenerateUnmanagedCallbacksAttr = "Godot.SourceGenerators.Internal.GenerateUnmanagedCallbacksAttribute";
+}
diff --git a/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Godot.SourceGenerators.Internal.csproj b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Godot.SourceGenerators.Internal.csproj
new file mode 100644
index 0000000000..4d1a5bb76c
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/Godot.SourceGenerators.Internal.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ <LangVersion>10</LangVersion>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.10.0" PrivateAssets="all" />
+ <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
+ </ItemGroup>
+</Project>
diff --git a/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/UnmanagedCallbacksGenerator.cs b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/UnmanagedCallbacksGenerator.cs
new file mode 100644
index 0000000000..da578309bc
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/UnmanagedCallbacksGenerator.cs
@@ -0,0 +1,463 @@
+using System.Text;
+using System.Linq;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace Godot.SourceGenerators.Internal;
+
+[Generator]
+public class UnmanagedCallbacksGenerator : ISourceGenerator
+{
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ context.RegisterForPostInitialization(ctx => { GenerateAttribute(ctx); });
+ }
+
+ public void Execute(GeneratorExecutionContext context)
+ {
+ INamedTypeSymbol[] unmanagedCallbacksClasses = context
+ .Compilation.SyntaxTrees
+ .SelectMany(tree =>
+ tree.GetRoot().DescendantNodes()
+ .OfType<ClassDeclarationSyntax>()
+ .SelectUnmanagedCallbacksClasses(context.Compilation)
+ // Report and skip non-partial classes
+ .Where(x =>
+ {
+ if (x.cds.IsPartial())
+ {
+ if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
+ {
+ Common.ReportNonPartialUnmanagedCallbacksOuterClass(context, typeMissingPartial!);
+ return false;
+ }
+
+ return true;
+ }
+
+ Common.ReportNonPartialUnmanagedCallbacksClass(context, x.cds, x.symbol);
+ return false;
+ })
+ .Select(x => x.symbol)
+ )
+ .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
+ .ToArray();
+
+ foreach (var symbol in unmanagedCallbacksClasses)
+ {
+ var attr = symbol.GetGenerateUnmanagedCallbacksAttribute();
+ if (attr == null || attr.ConstructorArguments.Length != 1)
+ {
+ // TODO: Report error or throw exception, this is an invalid case and should never be reached
+ System.Diagnostics.Debug.Fail("FAILED!");
+ continue;
+ }
+
+ var funcStructType = (INamedTypeSymbol?)attr.ConstructorArguments[0].Value;
+ if (funcStructType == null)
+ {
+ // TODO: Report error or throw exception, this is an invalid case and should never be reached
+ System.Diagnostics.Debug.Fail("FAILED!");
+ continue;
+ }
+
+ var data = new CallbacksData(symbol, funcStructType);
+ GenerateInteropMethodImplementations(context, data);
+ GenerateUnmanagedCallbacksStruct(context, data);
+ }
+ }
+
+ private void GenerateAttribute(GeneratorPostInitializationContext context)
+ {
+ string source = @"using System;
+
+namespace Godot.SourceGenerators.Internal
+{
+internal class GenerateUnmanagedCallbacksAttribute : Attribute
+{
+ public Type FuncStructType { get; }
+
+ public GenerateUnmanagedCallbacksAttribute(Type funcStructType)
+ {
+ FuncStructType = funcStructType;
+ }
+}
+}";
+
+ context.AddSource("GenerateUnmanagedCallbacksAttribute.generated",
+ SourceText.From(source, Encoding.UTF8));
+ }
+
+ private void GenerateInteropMethodImplementations(GeneratorExecutionContext context, CallbacksData data)
+ {
+ var symbol = data.NativeTypeSymbol;
+
+ INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
+ string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
+ namespaceSymbol.FullQualifiedName() :
+ string.Empty;
+ bool hasNamespace = classNs.Length != 0;
+ bool isInnerClass = symbol.ContainingType != null;
+
+ var source = new StringBuilder();
+ var methodSource = new StringBuilder();
+ var methodCallArguments = new StringBuilder();
+ var methodSourceAfterCall = new StringBuilder();
+
+ source.Append(
+ @"using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Godot.Bridge;
+using Godot.NativeInterop;
+
+#pragma warning disable CA1707 // Disable warning: Identifiers should not contain underscores
+
+");
+
+ if (hasNamespace)
+ {
+ source.Append("namespace ");
+ source.Append(classNs);
+ source.Append("\n{\n");
+ }
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("partial ");
+ source.Append(containingType.GetDeclarationKeyword());
+ source.Append(" ");
+ source.Append(containingType.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ source.Append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
+ source.Append($"unsafe partial class {symbol.Name}\n");
+ source.Append("{\n");
+ source.Append($" private static {data.FuncStructSymbol.FullQualifiedName()} _unmanagedCallbacks;\n\n");
+
+ foreach (var callback in data.Methods)
+ {
+ methodSource.Clear();
+ methodCallArguments.Clear();
+ methodSourceAfterCall.Clear();
+
+ source.Append(" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]\n");
+ source.Append($" {SyntaxFacts.GetText(callback.DeclaredAccessibility)} ");
+
+ if (callback.IsStatic)
+ source.Append("static ");
+
+ source.Append("partial ");
+ source.Append(callback.ReturnType.FullQualifiedName());
+ source.Append(' ');
+ source.Append(callback.Name);
+ source.Append('(');
+
+ for (int i = 0; i < callback.Parameters.Length; i++)
+ {
+ var parameter = callback.Parameters[i];
+
+ source.Append(parameter.ToDisplayString());
+ source.Append(' ');
+ source.Append(parameter.Name);
+
+ if (parameter.RefKind == RefKind.Out)
+ {
+ // Only assign default if the parameter won't be passed by-ref or copied later.
+ if (IsGodotInteropStruct(parameter.Type))
+ methodSource.Append($" {parameter.Name} = default;\n");
+ }
+
+ if (IsByRefParameter(parameter))
+ {
+ if (IsGodotInteropStruct(parameter.Type))
+ {
+ methodSource.Append(" ");
+ AppendCustomUnsafeAsPointer(methodSource, parameter, out string varName);
+ methodCallArguments.Append(varName);
+ }
+ else if (parameter.Type.IsValueType)
+ {
+ methodSource.Append(" ");
+ AppendCopyToStackAndGetPointer(methodSource, parameter, out string varName);
+ methodCallArguments.Append($"&{varName}");
+
+ if (parameter.RefKind is RefKind.Out or RefKind.Ref)
+ {
+ methodSourceAfterCall.Append($" {parameter.Name} = {varName};\n");
+ }
+ }
+ else
+ {
+ // If it's a by-ref param and we can't get the pointer
+ // just pass it by-ref and let it be pinned.
+ AppendRefKind(methodCallArguments, parameter.RefKind)
+ .Append(' ')
+ .Append(parameter.Name);
+ }
+ }
+ else
+ {
+ methodCallArguments.Append(parameter.Name);
+ }
+
+ if (i < callback.Parameters.Length - 1)
+ {
+ source.Append(", ");
+ methodCallArguments.Append(", ");
+ }
+ }
+
+ source.Append(")\n");
+ source.Append(" {\n");
+
+ source.Append(methodSource);
+ source.Append(" ");
+
+ if (!callback.ReturnsVoid)
+ {
+ if (methodSourceAfterCall.Length != 0)
+ source.Append($"{callback.ReturnType.FullQualifiedName()} ret = ");
+ else
+ source.Append("return ");
+ }
+
+ source.Append($"_unmanagedCallbacks.{callback.Name}(");
+ source.Append(methodCallArguments);
+ source.Append(");\n");
+
+ if (methodSourceAfterCall.Length != 0)
+ {
+ source.Append(methodSourceAfterCall);
+
+ if (!callback.ReturnsVoid)
+ source.Append(" return ret;\n");
+ }
+
+ source.Append(" }\n\n");
+ }
+
+ source.Append("}\n");
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("}\n"); // outer class
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ if (hasNamespace)
+ source.Append("\n}");
+
+ source.Append("\n\n#pragma warning restore CA1707\n");
+
+ context.AddSource($"{data.NativeTypeSymbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()}.generated",
+ SourceText.From(source.ToString(), Encoding.UTF8));
+ }
+
+ private void GenerateUnmanagedCallbacksStruct(GeneratorExecutionContext context, CallbacksData data)
+ {
+ var symbol = data.FuncStructSymbol;
+
+ INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
+ string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
+ namespaceSymbol.FullQualifiedName() :
+ string.Empty;
+ bool hasNamespace = classNs.Length != 0;
+ bool isInnerClass = symbol.ContainingType != null;
+
+ var source = new StringBuilder();
+
+ source.Append(
+ @"using System.Runtime.InteropServices;
+using Godot.NativeInterop;
+
+#pragma warning disable CA1707 // Disable warning: Identifiers should not contain underscores
+
+");
+ if (hasNamespace)
+ {
+ source.Append("namespace ");
+ source.Append(classNs);
+ source.Append("\n{\n");
+ }
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("partial ");
+ source.Append(containingType.GetDeclarationKeyword());
+ source.Append(" ");
+ source.Append(containingType.NameWithTypeParameters());
+ source.Append("\n{\n");
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ source.Append("[StructLayout(LayoutKind.Sequential)]\n");
+ source.Append($"unsafe partial struct {symbol.Name}\n{{\n");
+
+ foreach (var callback in data.Methods)
+ {
+ source.Append(" ");
+ source.Append(callback.DeclaredAccessibility == Accessibility.Public ? "public " : "internal ");
+
+ source.Append("delegate* unmanaged<");
+
+ foreach (var parameter in callback.Parameters)
+ {
+ if (IsByRefParameter(parameter))
+ {
+ if (IsGodotInteropStruct(parameter.Type) || parameter.Type.IsValueType)
+ {
+ AppendPointerType(source, parameter.Type);
+ }
+ else
+ {
+ // If it's a by-ref param and we can't get the pointer
+ // just pass it by-ref and let it be pinned.
+ AppendRefKind(source, parameter.RefKind)
+ .Append(' ')
+ .Append(parameter.Type.FullQualifiedName());
+ }
+ }
+ else
+ {
+ source.Append(parameter.Type.FullQualifiedName());
+ }
+
+ source.Append(", ");
+ }
+
+ source.Append(callback.ReturnType.FullQualifiedName());
+ source.Append($"> {callback.Name};\n");
+ }
+
+ source.Append("}\n");
+
+ if (isInnerClass)
+ {
+ var containingType = symbol.ContainingType;
+
+ while (containingType != null)
+ {
+ source.Append("}\n"); // outer class
+
+ containingType = containingType.ContainingType;
+ }
+ }
+
+ if (hasNamespace)
+ source.Append("}\n");
+
+ source.Append("\n#pragma warning restore CA1707\n");
+
+ context.AddSource($"{symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()}.generated",
+ SourceText.From(source.ToString(), Encoding.UTF8));
+ }
+
+ private static bool IsGodotInteropStruct(ITypeSymbol type) =>
+ GodotInteropStructs.Contains(type.FullQualifiedName());
+
+ private static bool IsByRefParameter(IParameterSymbol parameter) =>
+ parameter.RefKind is RefKind.In or RefKind.Out or RefKind.Ref;
+
+ private static StringBuilder AppendRefKind(StringBuilder source, RefKind refKind) =>
+ refKind switch
+ {
+ RefKind.In => source.Append("in"),
+ RefKind.Out => source.Append("out"),
+ RefKind.Ref => source.Append("ref"),
+ _ => source,
+ };
+
+ private static void AppendPointerType(StringBuilder source, ITypeSymbol type)
+ {
+ source.Append(type.FullQualifiedName());
+ source.Append('*');
+ }
+
+ private static void AppendCustomUnsafeAsPointer(StringBuilder source, IParameterSymbol parameter,
+ out string varName)
+ {
+ varName = $"{parameter.Name}_ptr";
+
+ AppendPointerType(source, parameter.Type);
+ source.Append(' ');
+ source.Append(varName);
+ source.Append(" = ");
+
+ source.Append('(');
+ AppendPointerType(source, parameter.Type);
+ source.Append(')');
+
+ if (parameter.RefKind == RefKind.In)
+ source.Append("CustomUnsafe.ReadOnlyRefAsPointer(in ");
+ else
+ source.Append("CustomUnsafe.AsPointer(ref ");
+
+ source.Append(parameter.Name);
+
+ source.Append(");\n");
+ }
+
+ private static void AppendCopyToStackAndGetPointer(StringBuilder source, IParameterSymbol parameter,
+ out string varName)
+ {
+ varName = $"{parameter.Name}_copy";
+
+ source.Append(parameter.Type.FullQualifiedName());
+ source.Append(' ');
+ source.Append(varName);
+ if (parameter.RefKind is RefKind.In or RefKind.Ref)
+ {
+ source.Append(" = ");
+ source.Append(parameter.Name);
+ }
+
+ source.Append(";\n");
+ }
+
+ private static readonly string[] GodotInteropStructs =
+ {
+ "Godot.NativeInterop.godot_ref",
+ "Godot.NativeInterop.godot_variant_call_error",
+ "Godot.NativeInterop.godot_variant",
+ "Godot.NativeInterop.godot_string",
+ "Godot.NativeInterop.godot_string_name",
+ "Godot.NativeInterop.godot_node_path",
+ "Godot.NativeInterop.godot_signal",
+ "Godot.NativeInterop.godot_callable",
+ "Godot.NativeInterop.godot_array",
+ "Godot.NativeInterop.godot_dictionary",
+ "Godot.NativeInterop.godot_packed_byte_array",
+ "Godot.NativeInterop.godot_packed_int32_array",
+ "Godot.NativeInterop.godot_packed_int64_array",
+ "Godot.NativeInterop.godot_packed_float32_array",
+ "Godot.NativeInterop.godot_packed_float64_array",
+ "Godot.NativeInterop.godot_packed_string_array",
+ "Godot.NativeInterop.godot_packed_vector2_array",
+ "Godot.NativeInterop.godot_packed_vector3_array",
+ "Godot.NativeInterop.godot_packed_color_array",
+ };
+}
diff --git a/modules/mono/glue/GodotSharp/GodotPlugins/GodotPlugins.csproj b/modules/mono/glue/GodotSharp/GodotPlugins/GodotPlugins.csproj
new file mode 100644
index 0000000000..e720d3878c
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotPlugins/GodotPlugins.csproj
@@ -0,0 +1,17 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <LangVersion>10</LangVersion>
+ <Nullable>enable</Nullable>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+
+ <!-- To generate the .runtimeconfig.json file-->
+ <EnableDynamicLoading>true</EnableDynamicLoading>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\GodotSharp\GodotSharp.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/modules/mono/glue/GodotSharp/GodotPlugins/Main.cs b/modules/mono/glue/GodotSharp/GodotPlugins/Main.cs
new file mode 100644
index 0000000000..dad7464410
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotPlugins/Main.cs
@@ -0,0 +1,270 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Loader;
+using Godot.Bridge;
+using Godot.NativeInterop;
+
+namespace GodotPlugins
+{
+ public static class Main
+ {
+ // IMPORTANT:
+ // Keeping strong references to the AssemblyLoadContext (our PluginLoadContext) prevents
+ // it from being unloaded. To avoid issues, we wrap the reference in this class, and mark
+ // all the methods that access it as non-inlineable. This way we prevent local references
+ // (either real or introduced by the JIT) to escape the scope of these methods due to
+ // inlining, which could keep the AssemblyLoadContext alive while trying to unload.
+ private sealed class PluginLoadContextWrapper
+ {
+ private PluginLoadContext? _pluginLoadContext;
+
+ public string? AssemblyLoadedPath
+ {
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ get => _pluginLoadContext?.AssemblyLoadedPath;
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ public static (Assembly, PluginLoadContextWrapper) CreateAndLoadFromAssemblyName(
+ AssemblyName assemblyName,
+ string pluginPath,
+ ICollection<string> sharedAssemblies,
+ AssemblyLoadContext mainLoadContext
+ )
+ {
+ var wrapper = new PluginLoadContextWrapper();
+ wrapper._pluginLoadContext = new PluginLoadContext(
+ pluginPath, sharedAssemblies, mainLoadContext);
+ var assembly = wrapper._pluginLoadContext.LoadFromAssemblyName(assemblyName);
+ return (assembly, wrapper);
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ public WeakReference CreateWeakReference()
+ {
+ return new WeakReference(_pluginLoadContext, trackResurrection: true);
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ internal void Unload()
+ {
+ _pluginLoadContext?.Unload();
+ _pluginLoadContext = null;
+ }
+ }
+
+ private static readonly List<AssemblyName> SharedAssemblies = new();
+ private static readonly Assembly CoreApiAssembly = typeof(Godot.Object).Assembly;
+ private static Assembly? _editorApiAssembly;
+ private static PluginLoadContextWrapper? _projectLoadContext;
+
+ private static readonly AssemblyLoadContext MainLoadContext =
+ AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()) ??
+ AssemblyLoadContext.Default;
+
+ private static DllImportResolver? _dllImportResolver;
+
+ // Right now we do it this way for simplicity as hot-reload is disabled. It will need to be changed later.
+ [UnmanagedCallersOnly]
+ // ReSharper disable once UnusedMember.Local
+ private static unsafe godot_bool InitializeFromEngine(IntPtr godotDllHandle, godot_bool editorHint,
+ PluginsCallbacks* pluginsCallbacks, ManagedCallbacks* managedCallbacks,
+ IntPtr unmanagedCallbacks, int unmanagedCallbacksSize)
+ {
+ try
+ {
+ _dllImportResolver = new GodotDllImportResolver(godotDllHandle).OnResolveDllImport;
+
+ SharedAssemblies.Add(CoreApiAssembly.GetName());
+ NativeLibrary.SetDllImportResolver(CoreApiAssembly, _dllImportResolver);
+
+ AlcReloadCfg.Configure(alcReloadEnabled: editorHint.ToBool());
+ NativeFuncs.Initialize(unmanagedCallbacks, unmanagedCallbacksSize);
+
+ if (editorHint.ToBool())
+ {
+ _editorApiAssembly = Assembly.Load("GodotSharpEditor");
+ SharedAssemblies.Add(_editorApiAssembly.GetName());
+ NativeLibrary.SetDllImportResolver(_editorApiAssembly, _dllImportResolver);
+ }
+
+ *pluginsCallbacks = new()
+ {
+ LoadProjectAssemblyCallback = &LoadProjectAssembly,
+ LoadToolsAssemblyCallback = &LoadToolsAssembly,
+ UnloadProjectPluginCallback = &UnloadProjectPlugin,
+ };
+
+ *managedCallbacks = ManagedCallbacks.Create();
+
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine(e);
+ return godot_bool.False;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct PluginsCallbacks
+ {
+ public unsafe delegate* unmanaged<char*, godot_string*, godot_bool> LoadProjectAssemblyCallback;
+ public unsafe delegate* unmanaged<char*, IntPtr, int, IntPtr> LoadToolsAssemblyCallback;
+ public unsafe delegate* unmanaged<godot_bool> UnloadProjectPluginCallback;
+ }
+
+ [UnmanagedCallersOnly]
+ private static unsafe godot_bool LoadProjectAssembly(char* nAssemblyPath, godot_string* outLoadedAssemblyPath)
+ {
+ try
+ {
+ if (_projectLoadContext != null)
+ return godot_bool.True; // Already loaded
+
+ string assemblyPath = new(nAssemblyPath);
+
+ (var projectAssembly, _projectLoadContext) = LoadPlugin(assemblyPath);
+
+ string loadedAssemblyPath = _projectLoadContext.AssemblyLoadedPath ?? assemblyPath;
+ *outLoadedAssemblyPath = Marshaling.ConvertStringToNative(loadedAssemblyPath);
+
+ ScriptManagerBridge.LookupScriptsInAssembly(projectAssembly);
+
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ private static unsafe IntPtr LoadToolsAssembly(char* nAssemblyPath,
+ IntPtr unmanagedCallbacks, int unmanagedCallbacksSize)
+ {
+ try
+ {
+ string assemblyPath = new(nAssemblyPath);
+
+ if (_editorApiAssembly == null)
+ throw new InvalidOperationException("The Godot editor API assembly is not loaded");
+
+ var (assembly, _) = LoadPlugin(assemblyPath);
+
+ NativeLibrary.SetDllImportResolver(assembly, _dllImportResolver!);
+
+ var method = assembly.GetType("GodotTools.GodotSharpEditor")?
+ .GetMethod("InternalCreateInstance",
+ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
+
+ if (method == null)
+ {
+ throw new MissingMethodException("GodotTools.GodotSharpEditor",
+ "InternalCreateInstance");
+ }
+
+ return (IntPtr?)method
+ .Invoke(null, new object[] { unmanagedCallbacks, unmanagedCallbacksSize })
+ ?? IntPtr.Zero;
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine(e);
+ return IntPtr.Zero;
+ }
+ }
+
+ private static (Assembly, PluginLoadContextWrapper) LoadPlugin(string assemblyPath)
+ {
+ string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath);
+
+ var sharedAssemblies = new List<string>();
+
+ foreach (var sharedAssembly in SharedAssemblies)
+ {
+ string? sharedAssemblyName = sharedAssembly.Name;
+ if (sharedAssemblyName != null)
+ sharedAssemblies.Add(sharedAssemblyName);
+ }
+
+ return PluginLoadContextWrapper.CreateAndLoadFromAssemblyName(
+ new AssemblyName(assemblyName), assemblyPath, sharedAssemblies, MainLoadContext);
+ }
+
+ [UnmanagedCallersOnly]
+ private static godot_bool UnloadProjectPlugin()
+ {
+ try
+ {
+ return UnloadPlugin(ref _projectLoadContext).ToGodotBool();
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine(e);
+ return godot_bool.False;
+ }
+ }
+
+ private static bool UnloadPlugin(ref PluginLoadContextWrapper? pluginLoadContext)
+ {
+ try
+ {
+ if (pluginLoadContext == null)
+ return true;
+
+ Console.WriteLine("Unloading assembly load context...");
+
+ var alcWeakReference = pluginLoadContext.CreateWeakReference();
+
+ pluginLoadContext.Unload();
+ pluginLoadContext = null;
+
+ int startTimeMs = Environment.TickCount;
+ bool takingTooLong = false;
+
+ while (alcWeakReference.IsAlive)
+ {
+ GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
+ GC.WaitForPendingFinalizers();
+
+ if (!alcWeakReference.IsAlive)
+ break;
+
+ int elapsedTimeMs = Environment.TickCount - startTimeMs;
+
+ if (!takingTooLong && elapsedTimeMs >= 2000)
+ {
+ takingTooLong = true;
+
+ // TODO: How to log from GodotPlugins? (delegate pointer?)
+ Console.Error.WriteLine("Assembly unloading is taking longer than expected...");
+ }
+ else if (elapsedTimeMs >= 5000)
+ {
+ // TODO: How to log from GodotPlugins? (delegate pointer?)
+ Console.Error.WriteLine(
+ "Failed to unload assemblies. Possible causes: Strong GC handles, running threads, etc.");
+
+ return false;
+ }
+ }
+
+ Console.WriteLine("Assembly load context unloaded successfully.");
+
+ return true;
+ }
+ catch (Exception e)
+ {
+ // TODO: How to log exceptions from GodotPlugins? (delegate pointer?)
+ Console.Error.WriteLine(e);
+ return false;
+ }
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotPlugins/PluginLoadContext.cs b/modules/mono/glue/GodotSharp/GodotPlugins/PluginLoadContext.cs
new file mode 100644
index 0000000000..dcd572c65e
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotPlugins/PluginLoadContext.cs
@@ -0,0 +1,64 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Runtime.Loader;
+
+namespace GodotPlugins
+{
+ public class PluginLoadContext : AssemblyLoadContext
+ {
+ private readonly AssemblyDependencyResolver _resolver;
+ private readonly ICollection<string> _sharedAssemblies;
+ private readonly AssemblyLoadContext _mainLoadContext;
+
+ public string? AssemblyLoadedPath { get; private set; }
+
+ public PluginLoadContext(string pluginPath, ICollection<string> sharedAssemblies,
+ AssemblyLoadContext mainLoadContext)
+ : base(isCollectible: true)
+ {
+ _resolver = new AssemblyDependencyResolver(pluginPath);
+ _sharedAssemblies = sharedAssemblies;
+ _mainLoadContext = mainLoadContext;
+ }
+
+ protected override Assembly? Load(AssemblyName assemblyName)
+ {
+ if (assemblyName.Name == null)
+ return null;
+
+ if (_sharedAssemblies.Contains(assemblyName.Name))
+ return _mainLoadContext.LoadFromAssemblyName(assemblyName);
+
+ string? assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
+ if (assemblyPath != null)
+ {
+ AssemblyLoadedPath = assemblyPath;
+
+ // Load in memory to prevent locking the file
+ using var assemblyFile = File.Open(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
+ string pdbPath = Path.ChangeExtension(assemblyPath, ".pdb");
+
+ if (File.Exists(pdbPath))
+ {
+ using var pdbFile = File.Open(pdbPath, FileMode.Open, FileAccess.Read, FileShare.Read);
+ return LoadFromStream(assemblyFile, pdbFile);
+ }
+
+ return LoadFromStream(assemblyFile);
+ }
+
+ return null;
+ }
+
+ protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
+ {
+ string? libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
+ if (libraryPath != null)
+ return LoadUnmanagedDllFromPath(libraryPath);
+
+ return IntPtr.Zero;
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp.sln b/modules/mono/glue/GodotSharp/GodotSharp.sln
index 4896d0a07d..8db42c2d1a 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp.sln
+++ b/modules/mono/glue/GodotSharp/GodotSharp.sln
@@ -4,6 +4,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotSharp", "GodotSharp\Go
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotSharpEditor", "GodotSharpEditor\GodotSharpEditor.csproj", "{8FBEC238-D944-4074-8548-B3B524305905}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotPlugins", "GodotPlugins\GodotPlugins.csproj", "{944B77DB-497B-47F5-A1E3-81C35E3E9D4E}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Godot.SourceGenerators.Internal", "Godot.SourceGenerators.Internal\Godot.SourceGenerators.Internal.csproj", "{7749662B-E30C-419A-B745-13852573360A}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -18,5 +22,13 @@ Global
{8FBEC238-D944-4074-8548-B3B524305905}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8FBEC238-D944-4074-8548-B3B524305905}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8FBEC238-D944-4074-8548-B3B524305905}.Release|Any CPU.Build.0 = Release|Any CPU
+ {944B77DB-497B-47F5-A1E3-81C35E3E9D4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {944B77DB-497B-47F5-A1E3-81C35E3E9D4E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {944B77DB-497B-47F5-A1E3-81C35E3E9D4E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {944B77DB-497B-47F5-A1E3-81C35E3E9D4E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7749662B-E30C-419A-B745-13852573360A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7749662B-E30C-419A-B745-13852573360A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7749662B-E30C-419A-B745-13852573360A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7749662B-E30C-419A-B745-13852573360A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
diff --git a/modules/mono/glue/GodotSharp/GodotSharp.sln.DotSettings b/modules/mono/glue/GodotSharp/GodotSharp.sln.DotSettings
new file mode 100644
index 0000000000..ba65b61e95
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp.sln.DotSettings
@@ -0,0 +1,8 @@
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+ <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GC/@EntryIndexedValue">GC</s:String>
+ <s:Boolean x:Key="/Default/UserDictionary/Words/=alcs/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/UserDictionary/Words/=gdnative/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/UserDictionary/Words/=godotsharp/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/UserDictionary/Words/=icall/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/UserDictionary/Words/=quat/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/UserDictionary/Words/=vcall/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs
index 850ae7fc3b..f87f37bc43 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs
index a412047196..f2984bd1fb 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs
@@ -1,47 +1,35 @@
using System;
using System.Collections.Generic;
using System.Collections;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
+using Godot.NativeInterop;
namespace Godot.Collections
{
- internal class ArraySafeHandle : SafeHandle
- {
- public ArraySafeHandle(IntPtr handle) : base(IntPtr.Zero, true)
- {
- this.handle = handle;
- }
-
- public override bool IsInvalid
- {
- get { return handle == IntPtr.Zero; }
- }
-
- protected override bool ReleaseHandle()
- {
- Array.godot_icall_Array_Dtor(handle);
- return true;
- }
- }
-
/// <summary>
/// Wrapper around Godot's Array class, an array of Variant
/// typed elements allocated in the engine in C++. Useful when
/// interfacing with the engine. Otherwise prefer .NET collections
/// such as <see cref="System.Array"/> or <see cref="List{T}"/>.
/// </summary>
- public class Array : IList, IDisposable
+ public sealed class Array :
+ IList<Variant>,
+ IReadOnlyList<Variant>,
+ ICollection,
+ IDisposable
{
- private ArraySafeHandle _safeHandle;
- private bool _disposed = false;
+ internal godot_array.movable NativeValue;
+
+ private WeakReference<IDisposable> _weakReferenceToSelf;
/// <summary>
/// Constructs a new empty <see cref="Array"/>.
/// </summary>
public Array()
{
- _safeHandle = new ArraySafeHandle(godot_icall_Array_Ctor());
+ NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
}
/// <summary>
@@ -49,12 +37,12 @@ namespace Godot.Collections
/// </summary>
/// <param name="collection">The collection of elements to construct from.</param>
/// <returns>A new Godot Array.</returns>
- public Array(IEnumerable collection) : this()
+ public Array(IEnumerable<Variant> collection) : this()
{
if (collection == null)
- throw new NullReferenceException($"Parameter '{nameof(collection)} cannot be null.'");
+ throw new ArgumentNullException(nameof(collection));
- foreach (object element in collection)
+ foreach (Variant element in collection)
Add(element);
}
@@ -63,31 +51,126 @@ namespace Godot.Collections
/// </summary>
/// <param name="array">The objects to put in the new array.</param>
/// <returns>A new Godot Array.</returns>
- public Array(params object[] array) : this()
+ public Array(Variant[] array) : this()
{
if (array == null)
- {
- throw new NullReferenceException($"Parameter '{nameof(array)} cannot be null.'");
- }
- _safeHandle = new ArraySafeHandle(godot_icall_Array_Ctor_MonoArray(array));
+ throw new ArgumentNullException(nameof(array));
+
+ NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+
+ int length = array.Length;
+
+ Resize(length);
+
+ for (int i = 0; i < length; i++)
+ this[i] = array[i];
}
- internal Array(ArraySafeHandle handle)
+ public Array(Span<StringName> array) : this()
{
- _safeHandle = handle;
+ if (array == null)
+ throw new ArgumentNullException(nameof(array));
+
+ NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+
+ int length = array.Length;
+
+ Resize(length);
+
+ for (int i = 0; i < length; i++)
+ this[i] = array[i];
}
- internal Array(IntPtr handle)
+ public Array(Span<NodePath> array) : this()
{
- _safeHandle = new ArraySafeHandle(handle);
+ if (array == null)
+ throw new ArgumentNullException(nameof(array));
+
+ NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+
+ int length = array.Length;
+
+ Resize(length);
+
+ for (int i = 0; i < length; i++)
+ this[i] = array[i];
+ }
+
+ public Array(Span<RID> array) : this()
+ {
+ if (array == null)
+ throw new ArgumentNullException(nameof(array));
+
+ NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+
+ int length = array.Length;
+
+ Resize(length);
+
+ for (int i = 0; i < length; i++)
+ this[i] = array[i];
+ }
+
+ // We must use ReadOnlySpan instead of Span here as this can accept implicit conversions
+ // from derived types (e.g.: Node[]). Implicit conversion from Derived[] to Base[] are
+ // fine as long as the array is not mutated. However, Span does this type checking at
+ // instantiation, so it's not possible to use it even when not mutating anything.
+ // ReSharper disable once RedundantNameQualifier
+ public Array(ReadOnlySpan<Godot.Object> array) : this()
+ {
+ if (array == null)
+ throw new ArgumentNullException(nameof(array));
+
+ NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+
+ int length = array.Length;
+
+ Resize(length);
+
+ for (int i = 0; i < length; i++)
+ this[i] = array[i];
}
- internal IntPtr GetPtr()
+ private Array(godot_array nativeValueToOwn)
{
- if (_disposed)
- throw new ObjectDisposedException(GetType().FullName);
+ NativeValue = (godot_array.movable)(nativeValueToOwn.IsAllocated ?
+ nativeValueToOwn :
+ NativeFuncs.godotsharp_array_new());
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+ }
+
+ // Explicit name to make it very clear
+ internal static Array CreateTakingOwnershipOfDisposableValue(godot_array nativeValueToOwn)
+ => new Array(nativeValueToOwn);
- return _safeHandle.DangerousGetHandle();
+ ~Array()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// Disposes of this <see cref="Array"/>.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ public void Dispose(bool disposing)
+ {
+ // Always dispose `NativeValue` even if disposing is true
+ NativeValue.DangerousSelfRef.Dispose();
+
+ if (_weakReferenceToSelf != null)
+ {
+ DisposablesTracker.UnregisterDisposable(_weakReferenceToSelf);
+ }
}
/// <summary>
@@ -97,7 +180,10 @@ namespace Godot.Collections
/// <returns>A new Godot Array.</returns>
public Array Duplicate(bool deep = false)
{
- return new Array(godot_icall_Array_Duplicate(GetPtr(), deep));
+ godot_array newArray;
+ var self = (godot_array)NativeValue;
+ NativeFuncs.godotsharp_array_duplicate(ref self, deep.ToGodotBool(), out newArray);
+ return CreateTakingOwnershipOfDisposableValue(newArray);
}
/// <summary>
@@ -107,7 +193,8 @@ namespace Godot.Collections
/// <returns><see cref="Error.Ok"/> if successful, or an error code.</returns>
public Error Resize(int newSize)
{
- return godot_icall_Array_Resize(GetPtr(), newSize);
+ var self = (godot_array)NativeValue;
+ return NativeFuncs.godotsharp_array_resize(ref self, newSize);
}
/// <summary>
@@ -115,7 +202,8 @@ namespace Godot.Collections
/// </summary>
public void Shuffle()
{
- godot_icall_Array_Shuffle(GetPtr());
+ var self = (godot_array)NativeValue;
+ NativeFuncs.godotsharp_array_shuffle(ref self);
}
/// <summary>
@@ -126,94 +214,136 @@ namespace Godot.Collections
/// <returns>A new Godot Array with the contents of both arrays.</returns>
public static Array operator +(Array left, Array right)
{
- return new Array(godot_icall_Array_Concatenate(left.GetPtr(), right.GetPtr()));
- }
-
- // IDisposable
-
- /// <summary>
- /// Disposes of this <see cref="Array"/>.
- /// </summary>
- public void Dispose()
- {
- if (_disposed)
- return;
-
- if (_safeHandle != null)
+ if (left == null)
{
- _safeHandle.Dispose();
- _safeHandle = null;
+ if (right == null)
+ return new Array();
+
+ return right.Duplicate(deep: false);
}
- _disposed = true;
- }
+ if (right == null)
+ return left.Duplicate(deep: false);
+
+ int leftCount = left.Count;
+ int rightCount = right.Count;
- // IList
+ Array newArray = left.Duplicate(deep: false);
+ newArray.Resize(leftCount + rightCount);
- bool IList.IsReadOnly => false;
+ for (int i = 0; i < rightCount; i++)
+ newArray[i + leftCount] = right[i];
- bool IList.IsFixedSize => false;
+ return newArray;
+ }
/// <summary>
- /// Returns the object at the given <paramref name="index"/>.
+ /// Returns the item at the given <paramref name="index"/>.
/// </summary>
- /// <value>The object at the given <paramref name="index"/>.</value>
- public object this[int index]
+ /// <value>The <see cref="Variant"/> item at the given <paramref name="index"/>.</value>
+ public unsafe Variant this[int index]
{
- get => godot_icall_Array_At(GetPtr(), index);
- set => godot_icall_Array_SetAt(GetPtr(), index, value);
+ get
+ {
+ GetVariantBorrowElementAt(index, out godot_variant borrowElem);
+ return Variant.CreateCopyingBorrowed(borrowElem);
+ }
+ set
+ {
+ if (index < 0 || index >= Count)
+ throw new ArgumentOutOfRangeException(nameof(index));
+ var self = (godot_array)NativeValue;
+ godot_variant* ptrw = NativeFuncs.godotsharp_array_ptrw(ref self);
+ godot_variant* itemPtr = &ptrw[index];
+ (*itemPtr).Dispose();
+ *itemPtr = value.CopyNativeVariant();
+ }
}
/// <summary>
- /// Adds an object to the end of this <see cref="Array"/>.
+ /// Adds an item to the end of this <see cref="Array"/>.
/// This is the same as <c>append</c> or <c>push_back</c> in GDScript.
/// </summary>
- /// <param name="value">The object to add.</param>
- /// <returns>The new size after adding the object.</returns>
- public int Add(object value) => godot_icall_Array_Add(GetPtr(), value);
+ /// <param name="item">The <see cref="Variant"/> item to add.</param>
+ public void Add(Variant item)
+ {
+ godot_variant variantValue = (godot_variant)item.NativeVar;
+ var self = (godot_array)NativeValue;
+ _ = NativeFuncs.godotsharp_array_add(ref self, variantValue);
+ }
/// <summary>
- /// Checks if this <see cref="Array"/> contains the given object.
+ /// Checks if this <see cref="Array"/> contains the given item.
/// </summary>
- /// <param name="value">The item to look for.</param>
- /// <returns>Whether or not this array contains the given object.</returns>
- public bool Contains(object value) => godot_icall_Array_Contains(GetPtr(), value);
+ /// <param name="item">The <see cref="Variant"/> item to look for.</param>
+ /// <returns>Whether or not this array contains the given item.</returns>
+ public bool Contains(Variant item) => IndexOf(item) != -1;
/// <summary>
/// Erases all items from this <see cref="Array"/>.
/// </summary>
- public void Clear() => godot_icall_Array_Clear(GetPtr());
+ public void Clear() => Resize(0);
/// <summary>
- /// Searches this <see cref="Array"/> for an object
+ /// Searches this <see cref="Array"/> for an item
/// and returns its index or -1 if not found.
/// </summary>
- /// <param name="value">The object to search for.</param>
- /// <returns>The index of the object, or -1 if not found.</returns>
- public int IndexOf(object value) => godot_icall_Array_IndexOf(GetPtr(), value);
+ /// <param name="item">The <see cref="Variant"/> item to search for.</param>
+ /// <returns>The index of the item, or -1 if not found.</returns>
+ public int IndexOf(Variant item)
+ {
+ godot_variant variantValue = (godot_variant)item.NativeVar;
+ var self = (godot_array)NativeValue;
+ return NativeFuncs.godotsharp_array_index_of(ref self, variantValue);
+ }
/// <summary>
- /// Inserts a new object at a given position in the array.
+ /// Inserts a new item at a given position in the array.
/// The position must be a valid position of an existing item,
/// or the position at the end of the array.
/// Existing items will be moved to the right.
/// </summary>
/// <param name="index">The index to insert at.</param>
- /// <param name="value">The object to insert.</param>
- public void Insert(int index, object value) => godot_icall_Array_Insert(GetPtr(), index, value);
+ /// <param name="item">The <see cref="Variant"/> item to insert.</param>
+ public void Insert(int index, Variant item)
+ {
+ if (index < 0 || index > Count)
+ throw new ArgumentOutOfRangeException(nameof(index));
+
+ godot_variant variantValue = (godot_variant)item.NativeVar;
+ var self = (godot_array)NativeValue;
+ NativeFuncs.godotsharp_array_insert(ref self, index, variantValue);
+ }
/// <summary>
- /// Removes the first occurrence of the specified <paramref name="value"/>
+ /// Removes the first occurrence of the specified <paramref name="item"/>
/// from this <see cref="Array"/>.
/// </summary>
- /// <param name="value">The value to remove.</param>
- public void Remove(object value) => godot_icall_Array_Remove(GetPtr(), value);
+ /// <param name="item">The value to remove.</param>
+ public bool Remove(Variant item)
+ {
+ int index = IndexOf(item);
+ if (index >= 0)
+ {
+ RemoveAt(index);
+ return true;
+ }
+
+ return false;
+ }
/// <summary>
/// Removes an element from this <see cref="Array"/> by index.
/// </summary>
/// <param name="index">The index of the element to remove.</param>
- public void RemoveAt(int index) => godot_icall_Array_RemoveAt(GetPtr(), index);
+ public void RemoveAt(int index)
+ {
+ if (index < 0 || index > Count)
+ throw new ArgumentOutOfRangeException(nameof(index));
+
+ var self = (godot_array)NativeValue;
+ NativeFuncs.godotsharp_array_remove_at(ref self, index);
+ }
// ICollection
@@ -222,28 +352,77 @@ namespace Godot.Collections
/// This is also known as the size or length of the array.
/// </summary>
/// <returns>The number of elements.</returns>
- public int Count => godot_icall_Array_Count(GetPtr());
-
- object ICollection.SyncRoot => this;
+ public int Count => NativeValue.DangerousSelfRef.Size;
bool ICollection.IsSynchronized => false;
+ object ICollection.SyncRoot => false;
+
+ bool ICollection<Variant>.IsReadOnly => false;
+
/// <summary>
/// Copies the elements of this <see cref="Array"/> to the given
- /// untyped C# array, starting at the given index.
+ /// <see cref="Variant"/> C# array, starting at the given index.
/// </summary>
/// <param name="array">The array to copy to.</param>
- /// <param name="index">The index to start at.</param>
- public void CopyTo(System.Array array, int index)
+ /// <param name="arrayIndex">The index to start at.</param>
+ public void CopyTo(Variant[] array, int arrayIndex)
+ {
+ if (array == null)
+ throw new ArgumentNullException(nameof(array), "Value cannot be null.");
+
+ if (arrayIndex < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex),
+ "Number was less than the array's lower bound in the first dimension.");
+ }
+
+ int count = Count;
+
+ if (array.Length < (arrayIndex + count))
+ {
+ throw new ArgumentException(
+ "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
+ }
+
+ unsafe
+ {
+ for (int i = 0; i < count; i++)
+ {
+ array[arrayIndex] = Variant.CreateCopyingBorrowed(NativeValue.DangerousSelfRef.Elements[i]);
+ arrayIndex++;
+ }
+ }
+ }
+
+ void ICollection.CopyTo(System.Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array), "Value cannot be null.");
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), "Number was less than the array's lower bound in the first dimension.");
+ {
+ throw new ArgumentOutOfRangeException(nameof(index),
+ "Number was less than the array's lower bound in the first dimension.");
+ }
+
+ int count = Count;
- // Internal call may throw ArgumentException
- godot_icall_Array_CopyTo(GetPtr(), array, index);
+ if (array.Length < (index + count))
+ {
+ throw new ArgumentException(
+ "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
+ }
+
+ unsafe
+ {
+ for (int i = 0; i < count; i++)
+ {
+ object obj = Marshaling.ConvertVariantToManagedObject(NativeValue.DangerousSelfRef.Elements[i]);
+ array.SetValue(obj, index);
+ index++;
+ }
+ }
}
// IEnumerable
@@ -252,7 +431,7 @@ namespace Godot.Collections
/// Gets an enumerator for this <see cref="Array"/>.
/// </summary>
/// <returns>An enumerator.</returns>
- public IEnumerator GetEnumerator()
+ public IEnumerator<Variant> GetEnumerator()
{
int count = Count;
@@ -262,77 +441,37 @@ namespace Godot.Collections
}
}
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
+
/// <summary>
/// Converts this <see cref="Array"/> to a string.
/// </summary>
/// <returns>A string representation of this array.</returns>
public override string ToString()
{
- return godot_icall_Array_ToString(GetPtr());
+ var self = (godot_array)NativeValue;
+ NativeFuncs.godotsharp_array_to_string(ref self, out godot_string str);
+ using (str)
+ return Marshaling.ConvertStringToManaged(str);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Array_Ctor();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Array_Ctor_MonoArray(System.Array array);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Array_Dtor(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_Array_At(IntPtr ptr, int index);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_Array_At_Generic(IntPtr ptr, int index, int elemTypeEncoding, IntPtr elemTypeClass);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Array_SetAt(IntPtr ptr, int index, object value);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_Array_Count(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_Array_Add(IntPtr ptr, object item);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Array_Clear(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Array_Concatenate(IntPtr left, IntPtr right);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Array_Contains(IntPtr ptr, object item);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Array_CopyTo(IntPtr ptr, System.Array array, int arrayIndex);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Array_Duplicate(IntPtr ptr, bool deep);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_Array_IndexOf(IntPtr ptr, object item);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Array_Insert(IntPtr ptr, int index, object item);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Array_Remove(IntPtr ptr, object item);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Array_RemoveAt(IntPtr ptr, int index);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern Error godot_icall_Array_Resize(IntPtr ptr, int newSize);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern Error godot_icall_Array_Shuffle(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Array_Generic_GetElementTypeInfo(Type elemType, out int elemTypeEncoding, out IntPtr elemTypeClass);
+ /// <summary>
+ /// The variant returned via the <paramref name="elem"/> parameter is owned by the Array and must not be disposed.
+ /// </summary>
+ internal void GetVariantBorrowElementAt(int index, out godot_variant elem)
+ {
+ if (index < 0 || index >= Count)
+ throw new ArgumentOutOfRangeException(nameof(index));
+ GetVariantBorrowElementAtUnchecked(index, out elem);
+ }
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_Array_ToString(IntPtr ptr);
+ /// <summary>
+ /// The variant returned via the <paramref name="elem"/> parameter is owned by the Array and must not be disposed.
+ /// </summary>
+ internal unsafe void GetVariantBorrowElementAtUnchecked(int index, out godot_variant elem)
+ {
+ elem = NativeValue.DangerousSelfRef.Elements[index];
+ }
}
/// <summary>
@@ -342,16 +481,45 @@ namespace Godot.Collections
/// such as arrays or <see cref="List{T}"/>.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
- public class Array<T> : IList<T>, ICollection<T>, IEnumerable<T>
+ [SuppressMessage("ReSharper", "RedundantExtendsListEntry")]
+ [SuppressMessage("Naming", "CA1710", MessageId = "Identifiers should have correct suffix")]
+ public sealed class Array<[MustBeVariant] T> :
+ IList<T>,
+ IReadOnlyList<T>,
+ ICollection<T>,
+ IEnumerable<T>
{
- private Array _objectArray;
+ // ReSharper disable StaticMemberInGenericType
+ // Warning is about unique static fields being created for each generic type combination:
+ // https://www.jetbrains.com/help/resharper/StaticMemberInGenericType.html
+ // In our case this is exactly what we want.
- internal static int elemTypeEncoding;
- internal static IntPtr elemTypeClass;
+ private static unsafe delegate* managed<in T, godot_variant> _convertToVariantCallback;
+ private static unsafe delegate* managed<in godot_variant, T> _convertToManagedCallback;
- static Array()
+ // ReSharper restore StaticMemberInGenericType
+
+ static unsafe Array()
{
- Array.godot_icall_Array_Generic_GetElementTypeInfo(typeof(T), out elemTypeEncoding, out elemTypeClass);
+ _convertToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<T>();
+ _convertToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<T>();
+ }
+
+ private static unsafe void ValidateVariantConversionCallbacks()
+ {
+ if (_convertToVariantCallback == null || _convertToManagedCallback == null)
+ {
+ throw new InvalidOperationException(
+ $"The array element type is not supported for conversion to Variant: '{typeof(T).FullName}'");
+ }
+ }
+
+ private readonly Array _underlyingArray;
+
+ internal ref godot_array.movable NativeValue
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => ref _underlyingArray.NativeValue;
}
/// <summary>
@@ -359,7 +527,9 @@ namespace Godot.Collections
/// </summary>
public Array()
{
- _objectArray = new Array();
+ ValidateVariantConversionCallbacks();
+
+ _underlyingArray = new Array();
}
/// <summary>
@@ -369,10 +539,15 @@ namespace Godot.Collections
/// <returns>A new Godot Array.</returns>
public Array(IEnumerable<T> collection)
{
+ ValidateVariantConversionCallbacks();
+
if (collection == null)
- throw new NullReferenceException($"Parameter '{nameof(collection)} cannot be null.'");
+ throw new ArgumentNullException(nameof(collection));
+
+ _underlyingArray = new Array();
- _objectArray = new Array(collection);
+ foreach (T element in collection)
+ Add(element);
}
/// <summary>
@@ -380,13 +555,17 @@ namespace Godot.Collections
/// </summary>
/// <param name="array">The items to put in the new array.</param>
/// <returns>A new Godot Array.</returns>
- public Array(params T[] array) : this()
+ public Array(T[] array) : this()
{
+ ValidateVariantConversionCallbacks();
+
if (array == null)
- {
- throw new NullReferenceException($"Parameter '{nameof(array)} cannot be null.'");
- }
- _objectArray = new Array(array);
+ throw new ArgumentNullException(nameof(array));
+
+ _underlyingArray = new Array();
+
+ foreach (T element in array)
+ Add(element);
}
/// <summary>
@@ -395,23 +574,14 @@ namespace Godot.Collections
/// <param name="array">The untyped array to construct from.</param>
public Array(Array array)
{
- _objectArray = array;
- }
+ ValidateVariantConversionCallbacks();
- internal Array(IntPtr handle)
- {
- _objectArray = new Array(handle);
+ _underlyingArray = array;
}
- internal Array(ArraySafeHandle handle)
- {
- _objectArray = new Array(handle);
- }
-
- internal IntPtr GetPtr()
- {
- return _objectArray.GetPtr();
- }
+ // Explicit name to make it very clear
+ internal static Array<T> CreateTakingOwnershipOfDisposableValue(godot_array nativeValueToOwn)
+ => new Array<T>(Array.CreateTakingOwnershipOfDisposableValue(nativeValueToOwn));
/// <summary>
/// Converts this typed <see cref="Array{T}"/> to an untyped <see cref="Array"/>.
@@ -419,7 +589,7 @@ namespace Godot.Collections
/// <param name="from">The typed array to convert.</param>
public static explicit operator Array(Array<T> from)
{
- return from._objectArray;
+ return from?._underlyingArray;
}
/// <summary>
@@ -429,7 +599,7 @@ namespace Godot.Collections
/// <returns>A new Godot Array.</returns>
public Array<T> Duplicate(bool deep = false)
{
- return new Array<T>(_objectArray.Duplicate(deep));
+ return new Array<T>(_underlyingArray.Duplicate(deep));
}
/// <summary>
@@ -439,7 +609,7 @@ namespace Godot.Collections
/// <returns><see cref="Error.Ok"/> if successful, or an error code.</returns>
public Error Resize(int newSize)
{
- return _objectArray.Resize(newSize);
+ return _underlyingArray.Resize(newSize);
}
/// <summary>
@@ -447,7 +617,7 @@ namespace Godot.Collections
/// </summary>
public void Shuffle()
{
- _objectArray.Shuffle();
+ _underlyingArray.Shuffle();
}
/// <summary>
@@ -458,7 +628,18 @@ namespace Godot.Collections
/// <returns>A new Godot Array with the contents of both arrays.</returns>
public static Array<T> operator +(Array<T> left, Array<T> right)
{
- return new Array<T>(left._objectArray + right._objectArray);
+ if (left == null)
+ {
+ if (right == null)
+ return new Array<T>();
+
+ return right.Duplicate(deep: false);
+ }
+
+ if (right == null)
+ return left.Duplicate(deep: false);
+
+ return new Array<T>(left._underlyingArray + right._underlyingArray);
}
// IList<T>
@@ -467,10 +648,23 @@ namespace Godot.Collections
/// Returns the value at the given <paramref name="index"/>.
/// </summary>
/// <value>The value at the given <paramref name="index"/>.</value>
- public T this[int index]
+ public unsafe T this[int index]
{
- get { return (T)Array.godot_icall_Array_At_Generic(GetPtr(), index, elemTypeEncoding, elemTypeClass); }
- set { _objectArray[index] = value; }
+ get
+ {
+ _underlyingArray.GetVariantBorrowElementAt(index, out godot_variant borrowElem);
+ return _convertToManagedCallback(borrowElem);
+ }
+ set
+ {
+ if (index < 0 || index >= Count)
+ throw new ArgumentOutOfRangeException(nameof(index));
+ var self = (godot_array)_underlyingArray.NativeValue;
+ godot_variant* ptrw = NativeFuncs.godotsharp_array_ptrw(ref self);
+ godot_variant* itemPtr = &ptrw[index];
+ (*itemPtr).Dispose();
+ *itemPtr = _convertToVariantCallback(value);
+ }
}
/// <summary>
@@ -479,9 +673,11 @@ namespace Godot.Collections
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The index of the item, or -1 if not found.</returns>
- public int IndexOf(T item)
+ public unsafe int IndexOf(T item)
{
- return _objectArray.IndexOf(item);
+ using var variantValue = _convertToVariantCallback(item);
+ var self = (godot_array)_underlyingArray.NativeValue;
+ return NativeFuncs.godotsharp_array_index_of(ref self, variantValue);
}
/// <summary>
@@ -492,9 +688,14 @@ namespace Godot.Collections
/// </summary>
/// <param name="index">The index to insert at.</param>
/// <param name="item">The item to insert.</param>
- public void Insert(int index, T item)
+ public unsafe void Insert(int index, T item)
{
- _objectArray.Insert(index, item);
+ if (index < 0 || index > Count)
+ throw new ArgumentOutOfRangeException(nameof(index));
+
+ using var variantValue = _convertToVariantCallback(item);
+ var self = (godot_array)_underlyingArray.NativeValue;
+ NativeFuncs.godotsharp_array_insert(ref self, index, variantValue);
}
/// <summary>
@@ -503,7 +704,7 @@ namespace Godot.Collections
/// <param name="index">The index of the element to remove.</param>
public void RemoveAt(int index)
{
- _objectArray.RemoveAt(index);
+ _underlyingArray.RemoveAt(index);
}
// ICollection<T>
@@ -513,10 +714,7 @@ namespace Godot.Collections
/// This is also known as the size or length of the array.
/// </summary>
/// <returns>The number of elements.</returns>
- public int Count
- {
- get { return _objectArray.Count; }
- }
+ public int Count => _underlyingArray.Count;
bool ICollection<T>.IsReadOnly => false;
@@ -526,9 +724,11 @@ namespace Godot.Collections
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>The new size after adding the item.</returns>
- public void Add(T item)
+ public unsafe void Add(T item)
{
- _objectArray.Add(item);
+ using var variantValue = _convertToVariantCallback(item);
+ var self = (godot_array)_underlyingArray.NativeValue;
+ _ = NativeFuncs.godotsharp_array_add(ref self, variantValue);
}
/// <summary>
@@ -536,7 +736,7 @@ namespace Godot.Collections
/// </summary>
public void Clear()
{
- _objectArray.Clear();
+ _underlyingArray.Clear();
}
/// <summary>
@@ -544,10 +744,7 @@ namespace Godot.Collections
/// </summary>
/// <param name="item">The item to look for.</param>
/// <returns>Whether or not this array contains the given item.</returns>
- public bool Contains(T item)
- {
- return _objectArray.Contains(item);
- }
+ public bool Contains(T item) => IndexOf(item) != -1;
/// <summary>
/// Copies the elements of this <see cref="Array{T}"/> to the given
@@ -561,19 +758,22 @@ namespace Godot.Collections
throw new ArgumentNullException(nameof(array), "Value cannot be null.");
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(arrayIndex), "Number was less than the array's lower bound in the first dimension.");
-
- // TODO This may be quite slow because every element access is an internal call.
- // It could be moved entirely to an internal call if we find out how to do the cast there.
+ {
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex),
+ "Number was less than the array's lower bound in the first dimension.");
+ }
- int count = _objectArray.Count;
+ int count = Count;
if (array.Length < (arrayIndex + count))
- throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
+ {
+ throw new ArgumentException(
+ "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
+ }
for (int i = 0; i < count; i++)
{
- array[arrayIndex] = (T)this[i];
+ array[arrayIndex] = this[i];
arrayIndex++;
}
}
@@ -586,7 +786,14 @@ namespace Godot.Collections
/// <returns>A <see langword="bool"/> indicating success or failure.</returns>
public bool Remove(T item)
{
- return Array.godot_icall_Array_Remove(GetPtr(), item);
+ int index = IndexOf(item);
+ if (index >= 0)
+ {
+ RemoveAt(index);
+ return true;
+ }
+
+ return false;
}
// IEnumerable<T>
@@ -597,23 +804,26 @@ namespace Godot.Collections
/// <returns>An enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
- int count = _objectArray.Count;
+ int count = _underlyingArray.Count;
for (int i = 0; i < count; i++)
{
- yield return (T)this[i];
+ yield return this[i];
}
}
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Converts this <see cref="Array{T}"/> to a string.
/// </summary>
/// <returns>A string representation of this array.</returns>
- public override string ToString() => _objectArray.ToString();
+ public override string ToString() => _underlyingArray.ToString();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Array<T> from) => Variant.CreateFrom(from);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Array<T>(Variant from) => from.AsGodotArray<T>();
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/AssemblyHasScriptsAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/AssemblyHasScriptsAttribute.cs
index 2febf37f05..b7d633517a 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/AssemblyHasScriptsAttribute.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/AssemblyHasScriptsAttribute.cs
@@ -1,5 +1,7 @@
using System;
+#nullable enable
+
namespace Godot
{
/// <summary>
@@ -8,25 +10,28 @@ namespace Godot
[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyHasScriptsAttribute : Attribute
{
- private readonly bool requiresLookup;
- private readonly System.Type[] scriptTypes;
+ public bool RequiresLookup { get; }
+ public Type[]? ScriptTypes { get; }
/// <summary>
/// Constructs a new AssemblyHasScriptsAttribute instance.
/// </summary>
public AssemblyHasScriptsAttribute()
{
- requiresLookup = true;
+ RequiresLookup = true;
+ ScriptTypes = null;
}
/// <summary>
/// Constructs a new AssemblyHasScriptsAttribute instance.
/// </summary>
/// <param name="scriptTypes">The specified type(s) of scripts.</param>
- public AssemblyHasScriptsAttribute(System.Type[] scriptTypes)
+ public AssemblyHasScriptsAttribute(Type[] scriptTypes)
{
- requiresLookup = false;
- this.scriptTypes = scriptTypes;
+ RequiresLookup = false;
+ ScriptTypes = scriptTypes;
}
}
}
+
+#nullable restore
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/DisableGodotGeneratorsAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/DisableGodotGeneratorsAttribute.cs
deleted file mode 100644
index 0b00878e8c..0000000000
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/DisableGodotGeneratorsAttribute.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using System;
-
-namespace Godot
-{
- /// <summary>
- /// An attribute that disables Godot Generators.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class)]
- public class DisableGodotGeneratorsAttribute : Attribute { }
-}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportAttribute.cs
index 46eb128d37..3d204bdf9f 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportAttribute.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportAttribute.cs
@@ -6,7 +6,7 @@ namespace Godot
/// An attribute used to export objects.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
- public class ExportAttribute : Attribute
+ public sealed class ExportAttribute : Attribute
{
private PropertyHint hint;
private string hintString;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportCategoryAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportCategoryAttribute.cs
new file mode 100644
index 0000000000..101e56f8d3
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportCategoryAttribute.cs
@@ -0,0 +1,22 @@
+using System;
+
+namespace Godot
+{
+ /// <summary>
+ /// Define a new category for the following exported properties. This helps to organize properties in the Inspector dock.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
+ public sealed class ExportCategoryAttribute : Attribute
+ {
+ private string name;
+
+ /// <summary>
+ /// Define a new category for the following exported properties.
+ /// </summary>
+ /// <param name="name">The name of the category.</param>
+ public ExportCategoryAttribute(string name)
+ {
+ this.name = name;
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportGroupAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportGroupAttribute.cs
new file mode 100644
index 0000000000..3bd532cec1
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportGroupAttribute.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Godot
+{
+ /// <summary>
+ /// Define a new group for the following exported properties. This helps to organize properties in the Inspector dock.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
+ public sealed class ExportGroupAttribute : Attribute
+ {
+ private string name;
+ private string prefix;
+
+ /// <summary>
+ /// Define a new group for the following exported properties.
+ /// </summary>
+ /// <param name="name">The name of the group.</param>
+ /// <param name="prefix">If provided, the group would make group to only consider properties that have this prefix.</param>
+ public ExportGroupAttribute(string name, string prefix = "")
+ {
+ this.name = name;
+ this.prefix = prefix;
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportSubgroupAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportSubgroupAttribute.cs
new file mode 100644
index 0000000000..2ae6eb0b68
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ExportSubgroupAttribute.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Godot
+{
+ /// <summary>
+ /// Define a new subgroup for the following exported properties. This helps to organize properties in the Inspector dock.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
+ public sealed class ExportSubgroupAttribute : Attribute
+ {
+ private string name;
+ private string prefix;
+
+ /// <summary>
+ /// Define a new subgroup for the following exported properties. This helps to organize properties in the Inspector dock.
+ /// </summary>
+ /// <param name="name">The name of the subgroup.</param>
+ /// <param name="prefix">If provided, the subgroup would make group to only consider properties that have this prefix.</param>
+ public ExportSubgroupAttribute(string name, string prefix = "")
+ {
+ this.name = name;
+ this.prefix = prefix;
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/GodotMethodAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/GodotMethodAttribute.cs
deleted file mode 100644
index 8d4ff0fdb7..0000000000
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/GodotMethodAttribute.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System;
-
-namespace Godot
-{
- /// <summary>
- /// An attribute for a method.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method)]
- internal class GodotMethodAttribute : Attribute
- {
- private string methodName;
-
- public string MethodName { get { return methodName; } }
-
- /// <summary>
- /// Constructs a new GodotMethodAttribute instance.
- /// </summary>
- /// <param name="methodName">The name of the method.</param>
- public GodotMethodAttribute(string methodName)
- {
- this.methodName = methodName;
- }
- }
-}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/MustBeVariantAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/MustBeVariantAttribute.cs
new file mode 100644
index 0000000000..23088378d1
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/MustBeVariantAttribute.cs
@@ -0,0 +1,11 @@
+using System;
+
+namespace Godot
+{
+ /// <summary>
+ /// Attribute that restricts generic type parameters to be only types
+ /// that can be marshaled from/to a <see cref="Variant"/>.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.GenericParameter)]
+ public class MustBeVariantAttribute : Attribute { }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ScriptPathAttribute.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ScriptPathAttribute.cs
index 3ebb6612de..2c8a53ae1c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ScriptPathAttribute.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/ScriptPathAttribute.cs
@@ -8,7 +8,7 @@ namespace Godot
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ScriptPathAttribute : Attribute
{
- private string path;
+ public string Path { get; }
/// <summary>
/// Constructs a new ScriptPathAttribute instance.
@@ -16,7 +16,7 @@ namespace Godot
/// <param name="path">The file path to the script</param>
public ScriptPathAttribute(string path)
{
- this.path = path;
+ Path = path;
}
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs
index 437878818c..4cb9bf5758 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -167,7 +162,7 @@ namespace Godot
case 2:
return Column2;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(column));
}
}
set
@@ -184,7 +179,7 @@ namespace Godot
Column2 = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(column));
}
}
}
@@ -386,7 +381,7 @@ namespace Godot
case 2:
return Row2;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
@@ -413,7 +408,7 @@ namespace Godot
Row2 = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
@@ -623,41 +618,6 @@ namespace Godot
return tr;
}
- /// <summary>
- /// Returns a vector transformed (multiplied) by the basis matrix.
- /// </summary>
- /// <seealso cref="XformInv(Vector3)"/>
- /// <param name="v">A vector to transform.</param>
- /// <returns>The transformed vector.</returns>
- public Vector3 Xform(Vector3 v)
- {
- return new Vector3
- (
- Row0.Dot(v),
- Row1.Dot(v),
- Row2.Dot(v)
- );
- }
-
- /// <summary>
- /// Returns a vector transformed (multiplied) by the transposed basis matrix.
- ///
- /// Note: This results in a multiplication by the inverse of the
- /// basis matrix only if it represents a rotation-reflection.
- /// </summary>
- /// <seealso cref="Xform(Vector3)"/>
- /// <param name="v">A vector to inversely transform.</param>
- /// <returns>The inversely transformed vector.</returns>
- public Vector3 XformInv(Vector3 v)
- {
- return new Vector3
- (
- Row0[0] * v.x + Row1[0] * v.y + Row2[0] * v.z,
- Row0[1] * v.x + Row1[1] * v.y + Row2[1] * v.z,
- Row0[2] * v.x + Row1[2] * v.y + Row2[2] * v.z
- );
- }
-
private static readonly Basis[] _orthoBases = {
new Basis(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f),
new Basis(0f, -1f, 0f, 1f, 0f, 0f, 0f, 0f, 1f),
@@ -862,6 +822,41 @@ namespace Godot
}
/// <summary>
+ /// Returns a Vector3 transformed (multiplied) by the basis matrix.
+ /// </summary>
+ /// <param name="basis">The basis matrix transformation to apply.</param>
+ /// <param name="vector">A Vector3 to transform.</param>
+ /// <returns>The transformed Vector3.</returns>
+ public static Vector3 operator *(Basis basis, Vector3 vector)
+ {
+ return new Vector3
+ (
+ basis.Row0.Dot(vector),
+ basis.Row1.Dot(vector),
+ basis.Row2.Dot(vector)
+ );
+ }
+
+ /// <summary>
+ /// Returns a Vector3 transformed (multiplied) by the transposed basis matrix.
+ ///
+ /// Note: This results in a multiplication by the inverse of the
+ /// basis matrix only if it represents a rotation-reflection.
+ /// </summary>
+ /// <param name="vector">A Vector3 to inversely transform.</param>
+ /// <param name="basis">The basis matrix transformation to apply.</param>
+ /// <returns>The inversely transformed vector.</returns>
+ public static Vector3 operator *(Vector3 vector, Basis basis)
+ {
+ return new Vector3
+ (
+ basis.Row0[0] * vector.x + basis.Row1[0] * vector.y + basis.Row2[0] * vector.z,
+ basis.Row0[1] * vector.x + basis.Row1[1] * vector.y + basis.Row2[1] * vector.z,
+ basis.Row0[2] * vector.x + basis.Row1[2] * vector.y + basis.Row2[2] * vector.z
+ );
+ }
+
+ /// <summary>
/// Returns <see langword="true"/> if the basis matrices are exactly
/// equal. Note: Due to floating-point precision errors, consider using
/// <see cref="IsEqualApprox"/> instead, which is more reliable.
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/AlcReloadCfg.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/AlcReloadCfg.cs
new file mode 100644
index 0000000000..ac2e2fae3c
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/AlcReloadCfg.cs
@@ -0,0 +1,18 @@
+namespace Godot.Bridge;
+
+public static class AlcReloadCfg
+{
+ private static bool _configured = false;
+
+ public static void Configure(bool alcReloadEnabled)
+ {
+ if (_configured)
+ return;
+
+ _configured = true;
+
+ IsAlcReloadingEnabled = alcReloadEnabled;
+ }
+
+ internal static bool IsAlcReloadingEnabled = false;
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
new file mode 100644
index 0000000000..ae44f8f4ba
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
@@ -0,0 +1,253 @@
+using System;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
+
+namespace Godot.Bridge
+{
+ internal static class CSharpInstanceBridge
+ {
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool Call(IntPtr godotObjectGCHandle, godot_string_name* method,
+ godot_variant** args, int argCount, godot_variant_call_error* refCallError, godot_variant* ret)
+ {
+ try
+ {
+ var godotObject = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (godotObject == null)
+ {
+ *ret = default;
+ (*refCallError).Error = godot_variant_call_error_error.GODOT_CALL_ERROR_CALL_ERROR_INSTANCE_IS_NULL;
+ return godot_bool.False;
+ }
+
+ bool methodInvoked = godotObject.InvokeGodotClassMethod(CustomUnsafe.AsRef(method),
+ new NativeVariantPtrArgs(args),
+ argCount, out godot_variant retValue);
+
+ if (!methodInvoked)
+ {
+ *ret = default;
+ // This is important, as it tells Object::call that no method was called.
+ // Otherwise, it would prevent Object::call from calling native methods.
+ (*refCallError).Error = godot_variant_call_error_error.GODOT_CALL_ERROR_CALL_ERROR_INVALID_METHOD;
+ return godot_bool.False;
+ }
+
+ *ret = retValue;
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *ret = default;
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool Set(IntPtr godotObjectGCHandle, godot_string_name* name, godot_variant* value)
+ {
+ try
+ {
+ var godotObject = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (godotObject == null)
+ throw new InvalidOperationException();
+
+ if (godotObject.SetGodotClassPropertyValue(CustomUnsafe.AsRef(name), CustomUnsafe.AsRef(value)))
+ {
+ return godot_bool.True;
+ }
+
+ var nameManaged = StringName.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_string_name_new_copy(CustomUnsafe.AsRef(name)));
+
+ Variant valueManaged = Variant.CreateCopyingBorrowed(*value);
+
+ return godotObject._Set(nameManaged, valueManaged).ToGodotBool();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool Get(IntPtr godotObjectGCHandle, godot_string_name* name,
+ godot_variant* outRet)
+ {
+ try
+ {
+ var godotObject = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (godotObject == null)
+ throw new InvalidOperationException();
+
+ if (godotObject.GetGodotClassPropertyValue(CustomUnsafe.AsRef(name), out godot_variant outRetValue))
+ {
+ *outRet = outRetValue;
+ return godot_bool.True;
+ }
+
+ var nameManaged = StringName.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_string_name_new_copy(CustomUnsafe.AsRef(name)));
+
+ Variant ret = godotObject._Get(nameManaged);
+
+ if (ret.VariantType == Variant.Type.Nil)
+ {
+ *outRet = default;
+ return godot_bool.False;
+ }
+
+ *outRet = Marshaling.ConvertManagedObjectToVariant(ret);
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outRet = default;
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static void CallDispose(IntPtr godotObjectGCHandle, godot_bool okIfNull)
+ {
+ try
+ {
+ var godotObject = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (okIfNull.ToBool())
+ godotObject?.Dispose();
+ else
+ godotObject!.Dispose();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void CallToString(IntPtr godotObjectGCHandle, godot_string* outRes, godot_bool* outValid)
+ {
+ try
+ {
+ var self = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (self == null)
+ {
+ *outRes = default;
+ *outValid = godot_bool.False;
+ return;
+ }
+
+ var resultStr = self.ToString();
+
+ if (resultStr == null)
+ {
+ *outRes = default;
+ *outValid = godot_bool.False;
+ return;
+ }
+
+ *outRes = Marshaling.ConvertStringToNative(resultStr);
+ *outValid = godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outRes = default;
+ *outValid = godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool HasMethodUnknownParams(IntPtr godotObjectGCHandle, godot_string_name* method)
+ {
+ try
+ {
+ var godotObject = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (godotObject == null)
+ return godot_bool.False;
+
+ return godotObject.HasGodotClassMethod(CustomUnsafe.AsRef(method)).ToGodotBool();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void SerializeState(
+ IntPtr godotObjectGCHandle,
+ godot_dictionary* propertiesState,
+ godot_dictionary* signalEventsState
+ )
+ {
+ try
+ {
+ var godotObject = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (godotObject == null)
+ return;
+
+ // Call OnBeforeSerialize
+
+ // ReSharper disable once SuspiciousTypeConversion.Global
+ if (godotObject is ISerializationListener serializationListener)
+ serializationListener.OnBeforeSerialize();
+
+ // Save instance state
+
+ using var info = GodotSerializationInfo.CreateCopyingBorrowed(
+ *propertiesState, *signalEventsState);
+
+ godotObject.SaveGodotObjectData(info);
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void DeserializeState(
+ IntPtr godotObjectGCHandle,
+ godot_dictionary* propertiesState,
+ godot_dictionary* signalEventsState
+ )
+ {
+ try
+ {
+ var godotObject = (Object)GCHandle.FromIntPtr(godotObjectGCHandle).Target;
+
+ if (godotObject == null)
+ return;
+
+ // Restore instance state
+
+ using var info = GodotSerializationInfo.CreateCopyingBorrowed(
+ *propertiesState, *signalEventsState);
+
+ godotObject.RestoreGodotObjectData(info);
+
+ // Call OnAfterDeserialize
+
+ // ReSharper disable once SuspiciousTypeConversion.Global
+ if (godotObject is ISerializationListener serializationListener)
+ serializationListener.OnAfterDeserialize();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GCHandleBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GCHandleBridge.cs
new file mode 100644
index 0000000000..456a118b90
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GCHandleBridge.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
+
+namespace Godot.Bridge
+{
+ internal static class GCHandleBridge
+ {
+ [UnmanagedCallersOnly]
+ internal static void FreeGCHandle(IntPtr gcHandlePtr)
+ {
+ try
+ {
+ CustomGCHandle.Free(GCHandle.FromIntPtr(gcHandlePtr));
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GodotSerializationInfo.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GodotSerializationInfo.cs
new file mode 100644
index 0000000000..6d20f95007
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/GodotSerializationInfo.cs
@@ -0,0 +1,87 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using Godot.NativeInterop;
+
+namespace Godot.Bridge;
+
+public sealed class GodotSerializationInfo : IDisposable
+{
+ private readonly Collections.Dictionary _properties;
+ private readonly Collections.Dictionary _signalEvents;
+
+ public void Dispose()
+ {
+ _properties?.Dispose();
+ _signalEvents?.Dispose();
+
+ GC.SuppressFinalize(this);
+ }
+
+ private GodotSerializationInfo(in godot_dictionary properties, in godot_dictionary signalEvents)
+ {
+ _properties = Collections.Dictionary.CreateTakingOwnershipOfDisposableValue(properties);
+ _signalEvents = Collections.Dictionary.CreateTakingOwnershipOfDisposableValue(signalEvents);
+ }
+
+ internal static GodotSerializationInfo CreateCopyingBorrowed(
+ in godot_dictionary properties, in godot_dictionary signalEvents)
+ {
+ return new(NativeFuncs.godotsharp_dictionary_new_copy(properties),
+ NativeFuncs.godotsharp_dictionary_new_copy(signalEvents));
+ }
+
+ public void AddProperty(StringName name, Variant value)
+ {
+ _properties[name] = value;
+ }
+
+ public bool TryGetProperty(StringName name, out Variant value)
+ {
+ return _properties.TryGetValue(name, out value);
+ }
+
+ public void AddSignalEventDelegate(StringName name, Delegate eventDelegate)
+ {
+ var serializedData = new Collections.Array();
+
+ if (DelegateUtils.TrySerializeDelegate(eventDelegate, serializedData))
+ {
+ _signalEvents[name] = serializedData;
+ }
+ else if (OS.IsStdoutVerbose())
+ {
+ Console.WriteLine($"Failed to serialize event signal delegate: {name}");
+ }
+ }
+
+ public bool TryGetSignalEventDelegate<T>(StringName name, [MaybeNullWhen(false)] out T value)
+ where T : Delegate
+ {
+ if (_signalEvents.TryGetValue(name, out Variant serializedData))
+ {
+ if (DelegateUtils.TryDeserializeDelegate(serializedData.AsGodotArray(), out var eventDelegate))
+ {
+ value = eventDelegate as T;
+
+ if (value == null)
+ {
+ Console.WriteLine($"Cannot cast the deserialized event signal delegate: {name}. " +
+ $"Expected '{typeof(T).FullName}'; got '{eventDelegate.GetType().FullName}'.");
+ return false;
+ }
+
+ return true;
+ }
+ else if (OS.IsStdoutVerbose())
+ {
+ Console.WriteLine($"Failed to deserialize event signal delegate: {name}");
+ }
+
+ value = null;
+ return false;
+ }
+
+ value = null;
+ return false;
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs
new file mode 100644
index 0000000000..57240624bc
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs
@@ -0,0 +1,89 @@
+using System;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
+
+namespace Godot.Bridge
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public unsafe struct ManagedCallbacks
+ {
+ // @formatter:off
+ public delegate* unmanaged<IntPtr, godot_variant**, int, godot_bool*, void> SignalAwaiter_SignalCallback;
+ public delegate* unmanaged<IntPtr, godot_variant**, uint, godot_variant*, void> DelegateUtils_InvokeWithVariantArgs;
+ public delegate* unmanaged<IntPtr, IntPtr, godot_bool> DelegateUtils_DelegateEquals;
+ public delegate* unmanaged<IntPtr, godot_array*, godot_bool> DelegateUtils_TrySerializeDelegateWithGCHandle;
+ public delegate* unmanaged<godot_array*, IntPtr*, godot_bool> DelegateUtils_TryDeserializeDelegateWithGCHandle;
+ public delegate* unmanaged<void> ScriptManagerBridge_FrameCallback;
+ public delegate* unmanaged<godot_string_name*, IntPtr, IntPtr> ScriptManagerBridge_CreateManagedForGodotObjectBinding;
+ public delegate* unmanaged<IntPtr, IntPtr, godot_variant**, int, godot_bool> ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance;
+ public delegate* unmanaged<IntPtr, godot_string_name*, void> ScriptManagerBridge_GetScriptNativeName;
+ public delegate* unmanaged<IntPtr, IntPtr, void> ScriptManagerBridge_SetGodotObjectPtr;
+ public delegate* unmanaged<IntPtr, godot_string_name*, godot_variant**, int, godot_bool*, void> ScriptManagerBridge_RaiseEventSignal;
+ public delegate* unmanaged<IntPtr, IntPtr, godot_bool> ScriptManagerBridge_ScriptIsOrInherits;
+ public delegate* unmanaged<IntPtr, godot_string*, godot_bool> ScriptManagerBridge_AddScriptBridge;
+ public delegate* unmanaged<godot_string*, godot_ref*, void> ScriptManagerBridge_GetOrCreateScriptBridgeForPath;
+ public delegate* unmanaged<IntPtr, void> ScriptManagerBridge_RemoveScriptBridge;
+ public delegate* unmanaged<IntPtr, godot_bool> ScriptManagerBridge_TryReloadRegisteredScriptWithClass;
+ public delegate* unmanaged<IntPtr, godot_bool*, godot_array*, godot_dictionary*, godot_dictionary*, godot_ref*, void> ScriptManagerBridge_UpdateScriptClassInfo;
+ public delegate* unmanaged<IntPtr, IntPtr*, godot_bool, godot_bool> ScriptManagerBridge_SwapGCHandleForType;
+ public delegate* unmanaged<IntPtr, delegate* unmanaged<IntPtr, godot_string*, void*, int, void>, void> ScriptManagerBridge_GetPropertyInfoList;
+ public delegate* unmanaged<IntPtr, delegate* unmanaged<IntPtr, void*, int, void>, void> ScriptManagerBridge_GetPropertyDefaultValues;
+ public delegate* unmanaged<IntPtr, godot_string_name*, godot_variant**, int, godot_variant_call_error*, godot_variant*, godot_bool> CSharpInstanceBridge_Call;
+ public delegate* unmanaged<IntPtr, godot_string_name*, godot_variant*, godot_bool> CSharpInstanceBridge_Set;
+ public delegate* unmanaged<IntPtr, godot_string_name*, godot_variant*, godot_bool> CSharpInstanceBridge_Get;
+ public delegate* unmanaged<IntPtr, godot_bool, void> CSharpInstanceBridge_CallDispose;
+ public delegate* unmanaged<IntPtr, godot_string*, godot_bool*, void> CSharpInstanceBridge_CallToString;
+ public delegate* unmanaged<IntPtr, godot_string_name*, godot_bool> CSharpInstanceBridge_HasMethodUnknownParams;
+ public delegate* unmanaged<IntPtr, godot_dictionary*, godot_dictionary*, void> CSharpInstanceBridge_SerializeState;
+ public delegate* unmanaged<IntPtr, godot_dictionary*, godot_dictionary*, void> CSharpInstanceBridge_DeserializeState;
+ public delegate* unmanaged<IntPtr, void> GCHandleBridge_FreeGCHandle;
+ public delegate* unmanaged<void*, void> DebuggingUtils_GetCurrentStackInfo;
+ public delegate* unmanaged<void> DisposablesTracker_OnGodotShuttingDown;
+ public delegate* unmanaged<godot_bool, void> GD_OnCoreApiAssemblyLoaded;
+ // @formatter:on
+
+ public static ManagedCallbacks Create()
+ {
+ return new()
+ {
+ // @formatter:off
+ SignalAwaiter_SignalCallback = &SignalAwaiter.SignalCallback,
+ DelegateUtils_InvokeWithVariantArgs = &DelegateUtils.InvokeWithVariantArgs,
+ DelegateUtils_DelegateEquals = &DelegateUtils.DelegateEquals,
+ DelegateUtils_TrySerializeDelegateWithGCHandle = &DelegateUtils.TrySerializeDelegateWithGCHandle,
+ DelegateUtils_TryDeserializeDelegateWithGCHandle = &DelegateUtils.TryDeserializeDelegateWithGCHandle,
+ ScriptManagerBridge_FrameCallback = &ScriptManagerBridge.FrameCallback,
+ ScriptManagerBridge_CreateManagedForGodotObjectBinding = &ScriptManagerBridge.CreateManagedForGodotObjectBinding,
+ ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance = &ScriptManagerBridge.CreateManagedForGodotObjectScriptInstance,
+ ScriptManagerBridge_GetScriptNativeName = &ScriptManagerBridge.GetScriptNativeName,
+ ScriptManagerBridge_SetGodotObjectPtr = &ScriptManagerBridge.SetGodotObjectPtr,
+ ScriptManagerBridge_RaiseEventSignal = &ScriptManagerBridge.RaiseEventSignal,
+ ScriptManagerBridge_ScriptIsOrInherits = &ScriptManagerBridge.ScriptIsOrInherits,
+ ScriptManagerBridge_AddScriptBridge = &ScriptManagerBridge.AddScriptBridge,
+ ScriptManagerBridge_GetOrCreateScriptBridgeForPath = &ScriptManagerBridge.GetOrCreateScriptBridgeForPath,
+ ScriptManagerBridge_RemoveScriptBridge = &ScriptManagerBridge.RemoveScriptBridge,
+ ScriptManagerBridge_TryReloadRegisteredScriptWithClass = &ScriptManagerBridge.TryReloadRegisteredScriptWithClass,
+ ScriptManagerBridge_UpdateScriptClassInfo = &ScriptManagerBridge.UpdateScriptClassInfo,
+ ScriptManagerBridge_SwapGCHandleForType = &ScriptManagerBridge.SwapGCHandleForType,
+ ScriptManagerBridge_GetPropertyInfoList = &ScriptManagerBridge.GetPropertyInfoList,
+ ScriptManagerBridge_GetPropertyDefaultValues = &ScriptManagerBridge.GetPropertyDefaultValues,
+ CSharpInstanceBridge_Call = &CSharpInstanceBridge.Call,
+ CSharpInstanceBridge_Set = &CSharpInstanceBridge.Set,
+ CSharpInstanceBridge_Get = &CSharpInstanceBridge.Get,
+ CSharpInstanceBridge_CallDispose = &CSharpInstanceBridge.CallDispose,
+ CSharpInstanceBridge_CallToString = &CSharpInstanceBridge.CallToString,
+ CSharpInstanceBridge_HasMethodUnknownParams = &CSharpInstanceBridge.HasMethodUnknownParams,
+ CSharpInstanceBridge_SerializeState = &CSharpInstanceBridge.SerializeState,
+ CSharpInstanceBridge_DeserializeState = &CSharpInstanceBridge.DeserializeState,
+ GCHandleBridge_FreeGCHandle = &GCHandleBridge.FreeGCHandle,
+ DebuggingUtils_GetCurrentStackInfo = &DebuggingUtils.GetCurrentStackInfo,
+ DisposablesTracker_OnGodotShuttingDown = &DisposablesTracker.OnGodotShuttingDown,
+ GD_OnCoreApiAssemblyLoaded = &GD.OnCoreApiAssemblyLoaded,
+ // @formatter:on
+ };
+ }
+
+ public static void Create(IntPtr outManagedCallbacks)
+ => *(ManagedCallbacks*)outManagedCallbacks = Create();
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/MethodInfo.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/MethodInfo.cs
new file mode 100644
index 0000000000..647ae436ff
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/MethodInfo.cs
@@ -0,0 +1,25 @@
+using System.Collections.Generic;
+
+namespace Godot.Bridge;
+
+#nullable enable
+
+public struct MethodInfo
+{
+ public StringName Name { get; init; }
+ public PropertyInfo ReturnVal { get; init; }
+ public MethodFlags Flags { get; init; }
+ public int Id { get; init; } = 0;
+ public List<PropertyInfo>? Arguments { get; init; }
+ public List<Variant>? DefaultArguments { get; init; }
+
+ public MethodInfo(StringName name, PropertyInfo returnVal, MethodFlags flags,
+ List<PropertyInfo>? arguments, List<Variant>? defaultArguments)
+ {
+ Name = name;
+ ReturnVal = returnVal;
+ Flags = flags;
+ Arguments = arguments;
+ DefaultArguments = defaultArguments;
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/PropertyInfo.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/PropertyInfo.cs
new file mode 100644
index 0000000000..80d6f7b4a5
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/PropertyInfo.cs
@@ -0,0 +1,24 @@
+namespace Godot.Bridge;
+
+#nullable enable
+
+public struct PropertyInfo
+{
+ public Variant.Type Type { get; init; }
+ public StringName Name { get; init; }
+ public PropertyHint Hint { get; init; }
+ public string HintString { get; init; }
+ public PropertyUsageFlags Usage { get; init; }
+ public bool Exported { get; init; }
+
+ public PropertyInfo(Variant.Type type, StringName name, PropertyHint hint, string hintString,
+ PropertyUsageFlags usage, bool exported)
+ {
+ Type = type;
+ Name = name;
+ Hint = hint;
+ HintString = hintString;
+ Usage = usage;
+ Exported = exported;
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs
new file mode 100644
index 0000000000..0dc5ba7678
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs
@@ -0,0 +1,1028 @@
+#nullable enable
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Loader;
+using System.Runtime.Serialization;
+using Godot.NativeInterop;
+
+namespace Godot.Bridge
+{
+ // TODO: Make class internal once we replace LookupScriptsInAssembly (the only public member) with source generators
+ public static partial class ScriptManagerBridge
+ {
+ private static ConcurrentDictionary<AssemblyLoadContext, ConcurrentDictionary<Type, byte>>
+ _alcData = new();
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void OnAlcUnloading(AssemblyLoadContext alc)
+ {
+ if (_alcData.TryRemove(alc, out var typesInAlc))
+ {
+ foreach (var type in typesInAlc.Keys)
+ {
+ if (_scriptTypeBiMap.RemoveByScriptType(type, out IntPtr scriptPtr) &&
+ !_pathTypeBiMap.TryGetScriptPath(type, out _))
+ {
+ // For scripts without a path, we need to keep the class qualified name for reloading
+ _scriptDataForReload.TryAdd(scriptPtr,
+ (type.Assembly.GetName().Name, type.FullName ?? type.ToString()));
+ }
+
+ _pathTypeBiMap.RemoveByScriptType(type);
+ }
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void AddTypeForAlcReloading(Type type)
+ {
+ var alc = AssemblyLoadContext.GetLoadContext(type.Assembly);
+ if (alc == null)
+ return;
+
+ var typesInAlc = _alcData.GetOrAdd(alc,
+ static alc =>
+ {
+ alc.Unloading += OnAlcUnloading;
+ return new();
+ });
+ typesInAlc.TryAdd(type, 0);
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ public static void TrackAlcForUnloading(AssemblyLoadContext alc)
+ {
+ _ = _alcData.GetOrAdd(alc,
+ static alc =>
+ {
+ alc.Unloading += OnAlcUnloading;
+ return new();
+ });
+ }
+
+ private static ScriptTypeBiMap _scriptTypeBiMap = new();
+ private static PathScriptTypeBiMap _pathTypeBiMap = new();
+
+ private static ConcurrentDictionary<IntPtr, (string? assemblyName, string classFullName)>
+ _scriptDataForReload = new();
+
+ [UnmanagedCallersOnly]
+ internal static void FrameCallback()
+ {
+ try
+ {
+ Dispatcher.DefaultGodotTaskScheduler?.Activate();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe IntPtr CreateManagedForGodotObjectBinding(godot_string_name* nativeTypeName,
+ IntPtr godotObject)
+ {
+ // TODO: Optimize with source generators and delegate pointers
+
+ try
+ {
+ using var stringName = StringName.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_string_name_new_copy(CustomUnsafe.AsRef(nativeTypeName)));
+ string nativeTypeNameStr = stringName.ToString();
+
+ Type nativeType = TypeGetProxyClass(nativeTypeNameStr) ?? throw new InvalidOperationException(
+ "Wrapper class not found for type: " + nativeTypeNameStr);
+ var obj = (Object)FormatterServices.GetUninitializedObject(nativeType);
+
+ var ctor = nativeType.GetConstructor(
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
+ null, Type.EmptyTypes, null);
+
+ obj.NativePtr = godotObject;
+
+ _ = ctor!.Invoke(obj, null);
+
+ return GCHandle.ToIntPtr(CustomGCHandle.AllocStrong(obj));
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return IntPtr.Zero;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool CreateManagedForGodotObjectScriptInstance(IntPtr scriptPtr,
+ IntPtr godotObject,
+ godot_variant** args, int argCount)
+ {
+ // TODO: Optimize with source generators and delegate pointers
+
+ try
+ {
+ // Performance is not critical here as this will be replaced with source generators.
+ Type scriptType = _scriptTypeBiMap.GetScriptType(scriptPtr);
+ var obj = (Object)FormatterServices.GetUninitializedObject(scriptType);
+
+ var ctor = scriptType
+ .GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
+ .Where(c => c.GetParameters().Length == argCount)
+ .FirstOrDefault();
+
+ if (ctor == null)
+ {
+ if (argCount == 0)
+ {
+ throw new MissingMemberException(
+ $"Cannot create script instance. The class '{scriptType.FullName}' does not define a parameterless constructor.");
+ }
+ else
+ {
+ throw new MissingMemberException(
+ $"The class '{scriptType.FullName}' does not define a constructor that takes x parameters.");
+ }
+ }
+
+ var parameters = ctor.GetParameters();
+ int paramCount = parameters.Length;
+
+ var invokeParams = new object?[paramCount];
+
+ for (int i = 0; i < paramCount; i++)
+ {
+ invokeParams[i] = Marshaling.ConvertVariantToManagedObjectOfType(
+ *args[i], parameters[i].ParameterType);
+ }
+
+ obj.NativePtr = godotObject;
+
+ _ = ctor.Invoke(obj, invokeParams);
+
+
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void GetScriptNativeName(IntPtr scriptPtr, godot_string_name* outRes)
+ {
+ try
+ {
+ // Performance is not critical here as this will be replaced with source generators.
+ if (!_scriptTypeBiMap.TryGetScriptType(scriptPtr, out Type? scriptType))
+ {
+ *outRes = default;
+ return;
+ }
+
+ var native = Object.InternalGetClassNativeBase(scriptType);
+
+ var field = native?.GetField("NativeName", BindingFlags.DeclaredOnly | BindingFlags.Static |
+ BindingFlags.Public | BindingFlags.NonPublic);
+
+ if (field == null)
+ {
+ *outRes = default;
+ return;
+ }
+
+ var nativeName = (StringName?)field.GetValue(null);
+
+ if (nativeName == null)
+ {
+ *outRes = default;
+ return;
+ }
+
+ *outRes = NativeFuncs.godotsharp_string_name_new_copy((godot_string_name)nativeName.NativeValue);
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outRes = default;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static void SetGodotObjectPtr(IntPtr gcHandlePtr, IntPtr newPtr)
+ {
+ try
+ {
+ var target = (Object?)GCHandle.FromIntPtr(gcHandlePtr).Target;
+ if (target != null)
+ target.NativePtr = newPtr;
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ private static Type? TypeGetProxyClass(string nativeTypeNameStr)
+ {
+ // Performance is not critical here as this will be replaced with a generated dictionary.
+
+ if (nativeTypeNameStr[0] == '_')
+ nativeTypeNameStr = nativeTypeNameStr.Substring(1);
+
+ Type? wrapperType = typeof(Object).Assembly.GetType("Godot." + nativeTypeNameStr);
+
+ if (wrapperType == null)
+ {
+ wrapperType = AppDomain.CurrentDomain.GetAssemblies()
+ .FirstOrDefault(a => a.GetName().Name == "GodotSharpEditor")?
+ .GetType("Godot." + nativeTypeNameStr);
+ }
+
+ static bool IsStatic(Type type) => type.IsAbstract && type.IsSealed;
+
+ if (wrapperType != null && IsStatic(wrapperType))
+ {
+ // A static class means this is a Godot singleton class. If an instance is needed we use Godot.Object.
+ return typeof(Object);
+ }
+
+ return wrapperType;
+ }
+
+ // Called from GodotPlugins
+ // ReSharper disable once UnusedMember.Local
+ public static void LookupScriptsInAssembly(Assembly assembly)
+ {
+ static void LookupScriptForClass(Type type)
+ {
+ var scriptPathAttr = type.GetCustomAttributes(inherit: false)
+ .OfType<ScriptPathAttribute>()
+ .FirstOrDefault();
+
+ if (scriptPathAttr == null)
+ return;
+
+ _pathTypeBiMap.Add(scriptPathAttr.Path, type);
+
+ if (AlcReloadCfg.IsAlcReloadingEnabled)
+ {
+ AddTypeForAlcReloading(type);
+ }
+ }
+
+ var assemblyHasScriptsAttr = assembly.GetCustomAttributes(inherit: false)
+ .OfType<AssemblyHasScriptsAttribute>()
+ .FirstOrDefault();
+
+ if (assemblyHasScriptsAttr == null)
+ return;
+
+ if (assemblyHasScriptsAttr.RequiresLookup)
+ {
+ // This is supported for scenarios where specifying all types would be cumbersome,
+ // such as when disabling C# source generators (for whatever reason) or when using a
+ // language other than C# that has nothing similar to source generators to automate it.
+
+ var typeOfGodotObject = typeof(Object);
+
+ foreach (var type in assembly.GetTypes())
+ {
+ if (type.IsNested)
+ continue;
+
+ if (!typeOfGodotObject.IsAssignableFrom(type))
+ continue;
+
+ LookupScriptForClass(type);
+ }
+ }
+ else
+ {
+ // This is the most likely scenario as we use C# source generators
+
+ var scriptTypes = assemblyHasScriptsAttr.ScriptTypes;
+
+ if (scriptTypes != null)
+ {
+ for (int i = 0; i < scriptTypes.Length; i++)
+ {
+ LookupScriptForClass(scriptTypes[i]);
+ }
+ }
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void RaiseEventSignal(IntPtr ownerGCHandlePtr,
+ godot_string_name* eventSignalName, godot_variant** args, int argCount, godot_bool* outOwnerIsNull)
+ {
+ try
+ {
+ var owner = (Object?)GCHandle.FromIntPtr(ownerGCHandlePtr).Target;
+
+ if (owner == null)
+ {
+ *outOwnerIsNull = godot_bool.True;
+ return;
+ }
+
+ *outOwnerIsNull = godot_bool.False;
+
+ owner.RaiseGodotClassSignalCallbacks(CustomUnsafe.AsRef(eventSignalName),
+ new NativeVariantPtrArgs(args), argCount);
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outOwnerIsNull = godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static godot_bool ScriptIsOrInherits(IntPtr scriptPtr, IntPtr scriptPtrMaybeBase)
+ {
+ try
+ {
+ if (!_scriptTypeBiMap.TryGetScriptType(scriptPtr, out Type? scriptType))
+ return godot_bool.False;
+
+ if (!_scriptTypeBiMap.TryGetScriptType(scriptPtrMaybeBase, out Type? maybeBaseType))
+ return godot_bool.False;
+
+ return (scriptType == maybeBaseType || maybeBaseType.IsAssignableFrom(scriptType)).ToGodotBool();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool AddScriptBridge(IntPtr scriptPtr, godot_string* scriptPath)
+ {
+ try
+ {
+ lock (_scriptTypeBiMap.ReadWriteLock)
+ {
+ if (!_scriptTypeBiMap.IsScriptRegistered(scriptPtr))
+ {
+ string scriptPathStr = Marshaling.ConvertStringToManaged(*scriptPath);
+
+ if (!_pathTypeBiMap.TryGetScriptType(scriptPathStr, out Type? scriptType))
+ return godot_bool.False;
+
+ _scriptTypeBiMap.Add(scriptPtr, scriptType);
+ }
+ }
+
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void GetOrCreateScriptBridgeForPath(godot_string* scriptPath, godot_ref* outScript)
+ {
+ string scriptPathStr = Marshaling.ConvertStringToManaged(*scriptPath);
+
+ if (!_pathTypeBiMap.TryGetScriptType(scriptPathStr, out Type? scriptType))
+ {
+ NativeFuncs.godotsharp_internal_new_csharp_script(outScript);
+ return;
+ }
+
+ GetOrCreateScriptBridgeForType(scriptType, outScript);
+ }
+
+ private static unsafe void GetOrCreateScriptBridgeForType(Type scriptType, godot_ref* outScript)
+ {
+ lock (_scriptTypeBiMap.ReadWriteLock)
+ {
+ if (_scriptTypeBiMap.TryGetScriptPtr(scriptType, out IntPtr scriptPtr))
+ {
+ // Use existing
+ NativeFuncs.godotsharp_ref_new_from_ref_counted_ptr(out *outScript, scriptPtr);
+ return;
+ }
+
+ // This path is slower, but it's only executed for the first instantiation of the type
+ CreateScriptBridgeForType(scriptType, outScript);
+ }
+ }
+
+ internal static unsafe void GetOrLoadOrCreateScriptForType(Type scriptType, godot_ref* outScript)
+ {
+ static bool GetPathOtherwiseGetOrCreateScript(Type scriptType, godot_ref* outScript,
+ [MaybeNullWhen(false)] out string scriptPath)
+ {
+ lock (_scriptTypeBiMap.ReadWriteLock)
+ {
+ if (_scriptTypeBiMap.TryGetScriptPtr(scriptType, out IntPtr scriptPtr))
+ {
+ // Use existing
+ NativeFuncs.godotsharp_ref_new_from_ref_counted_ptr(out *outScript, scriptPtr);
+ scriptPath = null;
+ return false;
+ }
+
+ // This path is slower, but it's only executed for the first instantiation of the type
+
+ if (_pathTypeBiMap.TryGetScriptPath(scriptType, out scriptPath))
+ return true;
+
+ CreateScriptBridgeForType(scriptType, outScript);
+ scriptPath = null;
+ return false;
+ }
+ }
+
+ if (GetPathOtherwiseGetOrCreateScript(scriptType, outScript, out string? scriptPath))
+ {
+ // This path is slower, but it's only executed for the first instantiation of the type
+
+ // This must be done outside the read-write lock, as the script resource loading can lock it
+ using godot_string scriptPathIn = Marshaling.ConvertStringToNative(scriptPath);
+ if (!NativeFuncs.godotsharp_internal_script_load(scriptPathIn, outScript).ToBool())
+ {
+ GD.PushError($"Cannot load script for type '{scriptType.FullName}'. Path: '{scriptPath}'.");
+
+ // If loading of the script fails, best we can do create a new script
+ // with no path, as we do for types without an associated script file.
+ GetOrCreateScriptBridgeForType(scriptType, outScript);
+ }
+ }
+ }
+
+ private static unsafe void CreateScriptBridgeForType(Type scriptType, godot_ref* outScript)
+ {
+ NativeFuncs.godotsharp_internal_new_csharp_script(outScript);
+ IntPtr scriptPtr = outScript->Reference;
+
+ // Caller takes care of locking
+ _scriptTypeBiMap.Add(scriptPtr, scriptType);
+
+ NativeFuncs.godotsharp_internal_reload_registered_script(scriptPtr);
+ }
+
+ [UnmanagedCallersOnly]
+ internal static void RemoveScriptBridge(IntPtr scriptPtr)
+ {
+ try
+ {
+ lock (_scriptTypeBiMap.ReadWriteLock)
+ {
+ _scriptTypeBiMap.Remove(scriptPtr);
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static godot_bool TryReloadRegisteredScriptWithClass(IntPtr scriptPtr)
+ {
+ try
+ {
+ lock (_scriptTypeBiMap.ReadWriteLock)
+ {
+ if (_scriptTypeBiMap.TryGetScriptType(scriptPtr, out _))
+ {
+ // NOTE:
+ // Currently, we reload all scripts, not only the ones from the unloaded ALC.
+ // As such, we need to handle this case instead of treating it as an error.
+ NativeFuncs.godotsharp_internal_reload_registered_script(scriptPtr);
+ return godot_bool.True;
+ }
+
+ if (!_scriptDataForReload.TryGetValue(scriptPtr, out var dataForReload))
+ {
+ GD.PushError("Missing class qualified name for reloading script");
+ return godot_bool.False;
+ }
+
+ _ = _scriptDataForReload.TryRemove(scriptPtr, out _);
+
+ if (dataForReload.assemblyName == null)
+ {
+ GD.PushError(
+ $"Missing assembly name of class '{dataForReload.classFullName}' for reloading script");
+ return godot_bool.False;
+ }
+
+ var scriptType = ReflectionUtils.FindTypeInLoadedAssemblies(dataForReload.assemblyName,
+ dataForReload.classFullName);
+
+ if (scriptType == null)
+ {
+ // The class was removed, can't reload
+ return godot_bool.False;
+ }
+
+ // ReSharper disable once RedundantNameQualifier
+ if (!typeof(Godot.Object).IsAssignableFrom(scriptType))
+ {
+ // The class no longer inherits Godot.Object, can't reload
+ return godot_bool.False;
+ }
+
+ _scriptTypeBiMap.Add(scriptPtr, scriptType);
+
+ NativeFuncs.godotsharp_internal_reload_registered_script(scriptPtr);
+
+ return godot_bool.True;
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void UpdateScriptClassInfo(IntPtr scriptPtr, godot_bool* outTool,
+ godot_array* outMethodsDest, godot_dictionary* outRpcFunctionsDest,
+ godot_dictionary* outEventSignalsDest, godot_ref* outBaseScript)
+ {
+ try
+ {
+ // Performance is not critical here as this will be replaced with source generators.
+ var scriptType = _scriptTypeBiMap.GetScriptType(scriptPtr);
+
+ *outTool = scriptType.GetCustomAttributes(inherit: false)
+ .OfType<ToolAttribute>()
+ .Any().ToGodotBool();
+
+ if (!(*outTool).ToBool() && scriptType.IsNested)
+ {
+ *outTool = (scriptType.DeclaringType?.GetCustomAttributes(inherit: false)
+ .OfType<ToolAttribute>()
+ .Any() ?? false).ToGodotBool();
+ }
+
+ if (!(*outTool).ToBool() && scriptType.Assembly.GetName().Name == "GodotTools")
+ *outTool = godot_bool.True;
+
+ // Methods
+
+ // Performance is not critical here as this will be replaced with source generators.
+ using var methods = new Collections.Array();
+
+ Type? top = scriptType;
+ Type native = Object.InternalGetClassNativeBase(top);
+
+ while (top != null && top != native)
+ {
+ var methodList = GetMethodListForType(top);
+
+ if (methodList != null)
+ {
+ foreach (var method in methodList)
+ {
+ var methodInfo = new Collections.Dictionary();
+
+ methodInfo.Add("name", method.Name);
+
+ var methodParams = new Collections.Array();
+
+ if (method.Arguments != null)
+ {
+ foreach (var param in method.Arguments)
+ {
+ methodParams.Add(new Collections.Dictionary()
+ {
+ { "name", param.Name },
+ { "type", (int)param.Type },
+ { "usage", (int)param.Usage }
+ });
+ }
+ }
+
+ methodInfo.Add("params", methodParams);
+
+ methods.Add(methodInfo);
+ }
+ }
+
+ top = top.BaseType;
+ }
+
+ *outMethodsDest = NativeFuncs.godotsharp_array_new_copy(
+ (godot_array)methods.NativeValue);
+
+ // RPC functions
+
+ Collections.Dictionary rpcFunctions = new();
+
+ top = scriptType;
+
+ while (top != null && top != native)
+ {
+ foreach (var method in top.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance |
+ BindingFlags.NonPublic | BindingFlags.Public))
+ {
+ if (method.IsStatic)
+ continue;
+
+ string methodName = method.Name;
+
+ if (rpcFunctions.ContainsKey(methodName))
+ continue;
+
+ var rpcAttr = method.GetCustomAttributes(inherit: false)
+ .OfType<RPCAttribute>().FirstOrDefault();
+
+ if (rpcAttr == null)
+ continue;
+
+ var rpcConfig = new Collections.Dictionary();
+
+ rpcConfig["rpc_mode"] = (long)rpcAttr.Mode;
+ rpcConfig["call_local"] = rpcAttr.CallLocal;
+ rpcConfig["transfer_mode"] = (long)rpcAttr.TransferMode;
+ rpcConfig["channel"] = rpcAttr.TransferChannel;
+
+ rpcFunctions.Add(methodName, rpcConfig);
+ }
+
+ top = top.BaseType;
+ }
+
+ *outRpcFunctionsDest = NativeFuncs.godotsharp_dictionary_new_copy(
+ (godot_dictionary)(rpcFunctions).NativeValue);
+
+ // Event signals
+
+ // Performance is not critical here as this will be replaced with source generators.
+ using var signals = new Collections.Dictionary();
+
+ top = scriptType;
+
+ while (top != null && top != native)
+ {
+ var signalList = GetSignalListForType(top);
+
+ if (signalList != null)
+ {
+ foreach (var signal in signalList)
+ {
+ string signalName = signal.Name;
+
+ if (signals.ContainsKey(signalName))
+ continue;
+
+ var signalParams = new Collections.Array();
+
+ if (signal.Arguments != null)
+ {
+ foreach (var param in signal.Arguments)
+ {
+ signalParams.Add(new Collections.Dictionary()
+ {
+ { "name", param.Name },
+ { "type", (int)param.Type },
+ { "usage", (int)param.Usage }
+ });
+ }
+ }
+
+ signals.Add(signalName, signalParams);
+ }
+ }
+
+ top = top.BaseType;
+ }
+
+ *outEventSignalsDest = NativeFuncs.godotsharp_dictionary_new_copy(
+ (godot_dictionary)signals.NativeValue);
+
+ // Base script
+
+ var baseType = scriptType.BaseType;
+ if (baseType != null && baseType != native)
+ {
+ GetOrLoadOrCreateScriptForType(baseType, outBaseScript);
+ }
+ else
+ {
+ *outBaseScript = default;
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outTool = godot_bool.False;
+ *outRpcFunctionsDest = NativeFuncs.godotsharp_dictionary_new();
+ *outEventSignalsDest = NativeFuncs.godotsharp_dictionary_new();
+ *outBaseScript = default;
+ }
+ }
+
+ private static List<MethodInfo>? GetSignalListForType(Type type)
+ {
+ var getGodotSignalListMethod = type.GetMethod(
+ "GetGodotSignalList",
+ BindingFlags.DeclaredOnly | BindingFlags.Static |
+ BindingFlags.NonPublic | BindingFlags.Public);
+
+ if (getGodotSignalListMethod == null)
+ return null;
+
+ return (List<MethodInfo>?)getGodotSignalListMethod.Invoke(null, null);
+ }
+
+ private static List<MethodInfo>? GetMethodListForType(Type type)
+ {
+ var getGodotMethodListMethod = type.GetMethod(
+ "GetGodotMethodList",
+ BindingFlags.DeclaredOnly | BindingFlags.Static |
+ BindingFlags.NonPublic | BindingFlags.Public);
+
+ if (getGodotMethodListMethod == null)
+ return null;
+
+ return (List<MethodInfo>?)getGodotMethodListMethod.Invoke(null, null);
+ }
+
+ // ReSharper disable once InconsistentNaming
+ [SuppressMessage("ReSharper", "NotAccessedField.Local")]
+ [StructLayout(LayoutKind.Sequential)]
+ private ref struct godotsharp_property_info
+ {
+ // Careful with padding...
+ public godot_string_name Name; // Not owned
+ public godot_string HintString;
+ public int Type;
+ public int Hint;
+ public int Usage;
+ public godot_bool Exported;
+
+ public void Dispose()
+ {
+ HintString.Dispose();
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void GetPropertyInfoList(IntPtr scriptPtr,
+ delegate* unmanaged<IntPtr, godot_string*, void*, int, void> addPropInfoFunc)
+ {
+ try
+ {
+ Type scriptType = _scriptTypeBiMap.GetScriptType(scriptPtr);
+ GetPropertyInfoListForType(scriptType, scriptPtr, addPropInfoFunc);
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ private static unsafe void GetPropertyInfoListForType(Type type, IntPtr scriptPtr,
+ delegate* unmanaged<IntPtr, godot_string*, void*, int, void> addPropInfoFunc)
+ {
+ try
+ {
+ var getGodotPropertyListMethod = type.GetMethod(
+ "GetGodotPropertyList",
+ BindingFlags.DeclaredOnly | BindingFlags.Static |
+ BindingFlags.NonPublic | BindingFlags.Public);
+
+ if (getGodotPropertyListMethod == null)
+ return;
+
+ var properties = (List<PropertyInfo>?)
+ getGodotPropertyListMethod.Invoke(null, null);
+
+ if (properties == null || properties.Count <= 0)
+ return;
+
+ int length = properties.Count;
+
+ // There's no recursion here, so it's ok to go with a big enough number for most cases
+ // stackMaxSize = stackMaxLength * sizeof(godotsharp_property_info)
+ const int stackMaxLength = 32;
+ bool useStack = length < stackMaxLength;
+
+ godotsharp_property_info* interopProperties;
+
+ if (useStack)
+ {
+ // Weird limitation, hence the need for aux:
+ // "In the case of pointer types, you can use a stackalloc expression only in a local variable declaration to initialize the variable."
+ var aux = stackalloc godotsharp_property_info[length];
+ interopProperties = aux;
+ }
+ else
+ {
+ interopProperties = ((godotsharp_property_info*)NativeMemory.Alloc((nuint)length))!;
+ }
+
+ try
+ {
+ for (int i = 0; i < length; i++)
+ {
+ var property = properties[i];
+
+ godotsharp_property_info interopProperty = new()
+ {
+ Type = (int)property.Type,
+ Name = (godot_string_name)property.Name.NativeValue, // Not owned
+ Hint = (int)property.Hint,
+ HintString = Marshaling.ConvertStringToNative(property.HintString),
+ Usage = (int)property.Usage,
+ Exported = property.Exported.ToGodotBool()
+ };
+
+ interopProperties[i] = interopProperty;
+ }
+
+ using godot_string currentClassName = Marshaling.ConvertStringToNative(type.Name);
+
+ addPropInfoFunc(scriptPtr, &currentClassName, interopProperties, length);
+
+ // We're borrowing the StringName's without making an owning copy, so the
+ // managed collection needs to be kept alive until `addPropInfoFunc` returns.
+ GC.KeepAlive(properties);
+ }
+ finally
+ {
+ for (int i = 0; i < length; i++)
+ interopProperties[i].Dispose();
+
+ if (!useStack)
+ NativeMemory.Free(interopProperties);
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ // ReSharper disable once InconsistentNaming
+ [SuppressMessage("ReSharper", "NotAccessedField.Local")]
+ [StructLayout(LayoutKind.Sequential)]
+ private ref struct godotsharp_property_def_val_pair
+ {
+ // Careful with padding...
+ public godot_string_name Name; // Not owned
+ public godot_variant Value;
+
+ public void Dispose()
+ {
+ Value.Dispose();
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void GetPropertyDefaultValues(IntPtr scriptPtr,
+ delegate* unmanaged<IntPtr, void*, int, void> addDefValFunc)
+ {
+ try
+ {
+ Type? top = _scriptTypeBiMap.GetScriptType(scriptPtr);
+ Type native = Object.InternalGetClassNativeBase(top);
+
+ while (top != null && top != native)
+ {
+ GetPropertyDefaultValuesForType(top, scriptPtr, addDefValFunc);
+
+ top = top.BaseType;
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ [SkipLocalsInit]
+ private static unsafe void GetPropertyDefaultValuesForType(Type type, IntPtr scriptPtr,
+ delegate* unmanaged<IntPtr, void*, int, void> addDefValFunc)
+ {
+ try
+ {
+ var getGodotPropertyDefaultValuesMethod = type.GetMethod(
+ "GetGodotPropertyDefaultValues",
+ BindingFlags.DeclaredOnly | BindingFlags.Static |
+ BindingFlags.NonPublic | BindingFlags.Public);
+
+ if (getGodotPropertyDefaultValuesMethod == null)
+ return;
+
+ var defaultValues = (Dictionary<StringName, object>?)
+ getGodotPropertyDefaultValuesMethod.Invoke(null, null);
+
+ if (defaultValues == null || defaultValues.Count <= 0)
+ return;
+
+ int length = defaultValues.Count;
+
+ // There's no recursion here, so it's ok to go with a big enough number for most cases
+ // stackMaxSize = stackMaxLength * sizeof(godotsharp_property_def_val_pair)
+ const int stackMaxLength = 32;
+ bool useStack = length < stackMaxLength;
+
+ godotsharp_property_def_val_pair* interopDefaultValues;
+
+ if (useStack)
+ {
+ // Weird limitation, hence the need for aux:
+ // "In the case of pointer types, you can use a stackalloc expression only in a local variable declaration to initialize the variable."
+ var aux = stackalloc godotsharp_property_def_val_pair[length];
+ interopDefaultValues = aux;
+ }
+ else
+ {
+ interopDefaultValues = ((godotsharp_property_def_val_pair*)NativeMemory.Alloc((nuint)length))!;
+ }
+
+ try
+ {
+ int i = 0;
+ foreach (var defaultValuePair in defaultValues)
+ {
+ godotsharp_property_def_val_pair interopProperty = new()
+ {
+ Name = (godot_string_name)defaultValuePair.Key.NativeValue, // Not owned
+ Value = Marshaling.ConvertManagedObjectToVariant(defaultValuePair.Value)
+ };
+
+ interopDefaultValues[i] = interopProperty;
+
+ i++;
+ }
+
+ addDefValFunc(scriptPtr, interopDefaultValues, length);
+
+ // We're borrowing the StringName's without making an owning copy, so the
+ // managed collection needs to be kept alive until `addDefValFunc` returns.
+ GC.KeepAlive(defaultValues);
+ }
+ finally
+ {
+ for (int i = 0; i < length; i++)
+ interopDefaultValues[i].Dispose();
+
+ if (!useStack)
+ NativeMemory.Free(interopDefaultValues);
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool SwapGCHandleForType(IntPtr oldGCHandlePtr, IntPtr* outNewGCHandlePtr,
+ godot_bool createWeak)
+ {
+ try
+ {
+ var oldGCHandle = GCHandle.FromIntPtr(oldGCHandlePtr);
+
+ object? target = oldGCHandle.Target;
+
+ if (target == null)
+ {
+ CustomGCHandle.Free(oldGCHandle);
+ *outNewGCHandlePtr = IntPtr.Zero;
+ return godot_bool.False; // Called after the managed side was collected, so nothing to do here
+ }
+
+ // Release the current weak handle and replace it with a strong handle.
+ var newGCHandle = createWeak.ToBool() ?
+ CustomGCHandle.AllocWeak(target) :
+ CustomGCHandle.AllocStrong(target);
+
+ CustomGCHandle.Free(oldGCHandle);
+ *outNewGCHandlePtr = GCHandle.ToIntPtr(newGCHandle);
+ return godot_bool.True;
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outNewGCHandlePtr = IntPtr.Zero;
+ return godot_bool.False;
+ }
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.types.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.types.cs
new file mode 100644
index 0000000000..a58f6849ad
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.types.cs
@@ -0,0 +1,92 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Runtime.CompilerServices;
+
+namespace Godot.Bridge;
+
+#nullable enable
+
+public static partial class ScriptManagerBridge
+{
+ private class ScriptTypeBiMap
+ {
+ public readonly object ReadWriteLock = new();
+ private System.Collections.Generic.Dictionary<IntPtr, Type> _scriptTypeMap = new();
+ private System.Collections.Generic.Dictionary<Type, IntPtr> _typeScriptMap = new();
+
+ public void Add(IntPtr scriptPtr, Type scriptType)
+ {
+ // TODO: What if this is called while unloading a load context, but after we already did cleanup in preparation for unloading?
+
+ _scriptTypeMap.Add(scriptPtr, scriptType);
+ _typeScriptMap.Add(scriptType, scriptPtr);
+
+ if (AlcReloadCfg.IsAlcReloadingEnabled)
+ {
+ AddTypeForAlcReloading(scriptType);
+ }
+ }
+
+ public void Remove(IntPtr scriptPtr)
+ {
+ if (_scriptTypeMap.Remove(scriptPtr, out Type? scriptType))
+ _ = _typeScriptMap.Remove(scriptType);
+ }
+
+ public bool RemoveByScriptType(Type scriptType, out IntPtr scriptPtr)
+ {
+ if (_typeScriptMap.Remove(scriptType, out scriptPtr))
+ return _scriptTypeMap.Remove(scriptPtr);
+ return false;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Type GetScriptType(IntPtr scriptPtr) => _scriptTypeMap[scriptPtr];
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool TryGetScriptType(IntPtr scriptPtr, [MaybeNullWhen(false)] out Type scriptType) =>
+ _scriptTypeMap.TryGetValue(scriptPtr, out scriptType);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool TryGetScriptPtr(Type scriptType, out IntPtr scriptPtr) =>
+ _typeScriptMap.TryGetValue(scriptType, out scriptPtr);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool IsScriptRegistered(IntPtr scriptPtr) => _scriptTypeMap.ContainsKey(scriptPtr);
+ }
+
+ private class PathScriptTypeBiMap
+ {
+ private System.Collections.Generic.Dictionary<string, Type> _pathTypeMap = new();
+ private System.Collections.Generic.Dictionary<Type, string> _typePathMap = new();
+
+ public void Add(string scriptPath, Type scriptType)
+ {
+ _pathTypeMap.Add(scriptPath, scriptType);
+
+ // Due to partial classes, more than one file can point to the same type, so
+ // there could be duplicate keys in this case. We only add a type as key once.
+ _typePathMap.TryAdd(scriptType, scriptPath);
+ }
+
+ public void RemoveByScriptType(Type scriptType)
+ {
+ foreach (var pair in _pathTypeMap
+ .Where(p => p.Value == scriptType).ToArray())
+ {
+ _pathTypeMap.Remove(pair.Key);
+ }
+
+ _typePathMap.Remove(scriptType);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool TryGetScriptType(string scriptPath, [MaybeNullWhen(false)] out Type scriptType) =>
+ _pathTypeMap.TryGetValue(scriptPath, out scriptType);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool TryGetScriptPath(Type scriptType, [MaybeNullWhen(false)] out string scriptPath) =>
+ _typePathMap.TryGetValue(scriptType, out scriptPath);
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs
index 2722b64e6d..1b7f5158fd 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs
@@ -1,5 +1,7 @@
using System;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
namespace Godot
{
@@ -24,7 +26,7 @@ namespace Godot
/// }
/// </code>
/// </example>
- public struct Callable
+ public readonly struct Callable
{
private readonly Object _target;
private readonly StringName _method;
@@ -34,10 +36,12 @@ namespace Godot
/// Object that contains the method.
/// </summary>
public Object Target => _target;
+
/// <summary>
/// Name of the method that will be called.
/// </summary>
public StringName Method => _method;
+
/// <summary>
/// Delegate of the method that will be called.
/// </summary>
@@ -73,15 +77,43 @@ namespace Godot
_delegate = @delegate;
}
+ private const int VarArgsSpanThreshold = 5;
+
/// <summary>
/// Calls the method represented by this <see cref="Callable"/>.
/// Arguments can be passed and should match the method's signature.
/// </summary>
/// <param name="args">Arguments that will be passed to the method call.</param>
/// <returns>The value returned by the method.</returns>
- public object Call(params object[] args)
+ public unsafe Variant Call(params Variant[] args)
{
- return godot_icall_Callable_Call(ref this, args);
+ using godot_callable callable = Marshaling.ConvertCallableToNative(this);
+
+ int argc = args.Length;
+
+ Span<godot_variant.movable> argsStoreSpan = argc <= VarArgsSpanThreshold ?
+ stackalloc godot_variant.movable[VarArgsSpanThreshold].Cleared() :
+ new godot_variant.movable[argc];
+
+ Span<IntPtr> argsSpan = argc <= 10 ?
+ stackalloc IntPtr[argc] :
+ new IntPtr[argc];
+
+ using var variantSpanDisposer = new VariantSpanDisposer(argsStoreSpan);
+
+ fixed (godot_variant* varargs = &MemoryMarshal.GetReference(argsStoreSpan).DangerousSelfRef)
+ fixed (IntPtr* argsPtr = &MemoryMarshal.GetReference(argsSpan))
+ {
+ for (int i = 0; i < argc; i++)
+ {
+ varargs[i] = (godot_variant)args[i].NativeVar;
+ argsPtr[i] = new IntPtr(&varargs[i]);
+ }
+
+ godot_variant ret = NativeFuncs.godotsharp_callable_call(callable,
+ (godot_variant**)argsPtr, argc, out _);
+ return Variant.CreateTakingOwnershipOfDisposableValue(ret);
+ }
}
/// <summary>
@@ -89,15 +121,33 @@ namespace Godot
/// Arguments can be passed and should match the method's signature.
/// </summary>
/// <param name="args">Arguments that will be passed to the method call.</param>
- public void CallDeferred(params object[] args)
+ public unsafe void CallDeferred(params Variant[] args)
{
- godot_icall_Callable_CallDeferred(ref this, args);
- }
+ using godot_callable callable = Marshaling.ConvertCallableToNative(this);
+
+ int argc = args.Length;
+
+ Span<godot_variant.movable> argsStoreSpan = argc <= VarArgsSpanThreshold ?
+ stackalloc godot_variant.movable[VarArgsSpanThreshold].Cleared() :
+ new godot_variant.movable[argc];
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_Callable_Call(ref Callable callable, object[] args);
+ Span<IntPtr> argsSpan = argc <= 10 ?
+ stackalloc IntPtr[argc] :
+ new IntPtr[argc];
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Callable_CallDeferred(ref Callable callable, object[] args);
+ using var variantSpanDisposer = new VariantSpanDisposer(argsStoreSpan);
+
+ fixed (godot_variant* varargs = &MemoryMarshal.GetReference(argsStoreSpan).DangerousSelfRef)
+ fixed (IntPtr* argsPtr = &MemoryMarshal.GetReference(argsSpan))
+ {
+ for (int i = 0; i < argc; i++)
+ {
+ varargs[i] = (godot_variant)args[i].NativeVar;
+ argsPtr[i] = new IntPtr(&varargs[i]);
+ }
+
+ NativeFuncs.godotsharp_callable_call_deferred(callable, (godot_variant**)argsPtr, argc);
+ }
+ }
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs
index a6324504fc..ed0e1efd35 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs
@@ -210,7 +210,7 @@ namespace Godot
case 3:
return a;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
set
@@ -230,7 +230,7 @@ namespace Godot
a = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
@@ -841,7 +841,7 @@ namespace Godot
return ParseCol4(str, ofs) * 16 + ParseCol4(str, ofs + 1);
}
- private string ToHex32(float val)
+ private static string ToHex32(float val)
{
byte b = (byte)Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255));
return b.HexEncode();
@@ -849,7 +849,7 @@ namespace Godot
internal static bool HtmlIsValid(string color)
{
- if (color.Length == 0)
+ if (string.IsNullOrEmpty(color))
{
return false;
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs
index 68c821b447..bacf7c89e6 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs
@@ -10,152 +10,152 @@ namespace Godot
{
// Color names and values are derived from core/math/color_names.inc
internal static readonly Dictionary<string, Color> namedColors = new Dictionary<string, Color> {
- {"ALICEBLUE", new Color(0.94f, 0.97f, 1.00f)},
- {"ANTIQUEWHITE", new Color(0.98f, 0.92f, 0.84f)},
- {"AQUA", new Color(0.00f, 1.00f, 1.00f)},
- {"AQUAMARINE", new Color(0.50f, 1.00f, 0.83f)},
- {"AZURE", new Color(0.94f, 1.00f, 1.00f)},
- {"BEIGE", new Color(0.96f, 0.96f, 0.86f)},
- {"BISQUE", new Color(1.00f, 0.89f, 0.77f)},
- {"BLACK", new Color(0.00f, 0.00f, 0.00f)},
- {"BLANCHEDALMOND", new Color(1.00f, 0.92f, 0.80f)},
- {"BLUE", new Color(0.00f, 0.00f, 1.00f)},
- {"BLUEVIOLET", new Color(0.54f, 0.17f, 0.89f)},
- {"BROWN", new Color(0.65f, 0.16f, 0.16f)},
- {"BURLYWOOD", new Color(0.87f, 0.72f, 0.53f)},
- {"CADETBLUE", new Color(0.37f, 0.62f, 0.63f)},
- {"CHARTREUSE", new Color(0.50f, 1.00f, 0.00f)},
- {"CHOCOLATE", new Color(0.82f, 0.41f, 0.12f)},
- {"CORAL", new Color(1.00f, 0.50f, 0.31f)},
- {"CORNFLOWERBLUE", new Color(0.39f, 0.58f, 0.93f)},
- {"CORNSILK", new Color(1.00f, 0.97f, 0.86f)},
- {"CRIMSON", new Color(0.86f, 0.08f, 0.24f)},
- {"CYAN", new Color(0.00f, 1.00f, 1.00f)},
- {"DARKBLUE", new Color(0.00f, 0.00f, 0.55f)},
- {"DARKCYAN", new Color(0.00f, 0.55f, 0.55f)},
- {"DARKGOLDENROD", new Color(0.72f, 0.53f, 0.04f)},
- {"DARKGRAY", new Color(0.66f, 0.66f, 0.66f)},
- {"DARKGREEN", new Color(0.00f, 0.39f, 0.00f)},
- {"DARKKHAKI", new Color(0.74f, 0.72f, 0.42f)},
- {"DARKMAGENTA", new Color(0.55f, 0.00f, 0.55f)},
- {"DARKOLIVEGREEN", new Color(0.33f, 0.42f, 0.18f)},
- {"DARKORANGE", new Color(1.00f, 0.55f, 0.00f)},
- {"DARKORCHID", new Color(0.60f, 0.20f, 0.80f)},
- {"DARKRED", new Color(0.55f, 0.00f, 0.00f)},
- {"DARKSALMON", new Color(0.91f, 0.59f, 0.48f)},
- {"DARKSEAGREEN", new Color(0.56f, 0.74f, 0.56f)},
- {"DARKSLATEBLUE", new Color(0.28f, 0.24f, 0.55f)},
- {"DARKSLATEGRAY", new Color(0.18f, 0.31f, 0.31f)},
- {"DARKTURQUOISE", new Color(0.00f, 0.81f, 0.82f)},
- {"DARKVIOLET", new Color(0.58f, 0.00f, 0.83f)},
- {"DEEPPINK", new Color(1.00f, 0.08f, 0.58f)},
- {"DEEPSKYBLUE", new Color(0.00f, 0.75f, 1.00f)},
- {"DIMGRAY", new Color(0.41f, 0.41f, 0.41f)},
- {"DODGERBLUE", new Color(0.12f, 0.56f, 1.00f)},
- {"FIREBRICK", new Color(0.70f, 0.13f, 0.13f)},
- {"FLORALWHITE", new Color(1.00f, 0.98f, 0.94f)},
- {"FORESTGREEN", new Color(0.13f, 0.55f, 0.13f)},
- {"FUCHSIA", new Color(1.00f, 0.00f, 1.00f)},
- {"GAINSBORO", new Color(0.86f, 0.86f, 0.86f)},
- {"GHOSTWHITE", new Color(0.97f, 0.97f, 1.00f)},
- {"GOLD", new Color(1.00f, 0.84f, 0.00f)},
- {"GOLDENROD", new Color(0.85f, 0.65f, 0.13f)},
- {"GRAY", new Color(0.75f, 0.75f, 0.75f)},
- {"GREEN", new Color(0.00f, 1.00f, 0.00f)},
- {"GREENYELLOW", new Color(0.68f, 1.00f, 0.18f)},
- {"HONEYDEW", new Color(0.94f, 1.00f, 0.94f)},
- {"HOTPINK", new Color(1.00f, 0.41f, 0.71f)},
- {"INDIANRED", new Color(0.80f, 0.36f, 0.36f)},
- {"INDIGO", new Color(0.29f, 0.00f, 0.51f)},
- {"IVORY", new Color(1.00f, 1.00f, 0.94f)},
- {"KHAKI", new Color(0.94f, 0.90f, 0.55f)},
- {"LAVENDER", new Color(0.90f, 0.90f, 0.98f)},
- {"LAVENDERBLUSH", new Color(1.00f, 0.94f, 0.96f)},
- {"LAWNGREEN", new Color(0.49f, 0.99f, 0.00f)},
- {"LEMONCHIFFON", new Color(1.00f, 0.98f, 0.80f)},
- {"LIGHTBLUE", new Color(0.68f, 0.85f, 0.90f)},
- {"LIGHTCORAL", new Color(0.94f, 0.50f, 0.50f)},
- {"LIGHTCYAN", new Color(0.88f, 1.00f, 1.00f)},
- {"LIGHTGOLDENROD", new Color(0.98f, 0.98f, 0.82f)},
- {"LIGHTGRAY", new Color(0.83f, 0.83f, 0.83f)},
- {"LIGHTGREEN", new Color(0.56f, 0.93f, 0.56f)},
- {"LIGHTPINK", new Color(1.00f, 0.71f, 0.76f)},
- {"LIGHTSALMON", new Color(1.00f, 0.63f, 0.48f)},
- {"LIGHTSEAGREEN", new Color(0.13f, 0.70f, 0.67f)},
- {"LIGHTSKYBLUE", new Color(0.53f, 0.81f, 0.98f)},
- {"LIGHTSLATEGRAY", new Color(0.47f, 0.53f, 0.60f)},
- {"LIGHTSTEELBLUE", new Color(0.69f, 0.77f, 0.87f)},
- {"LIGHTYELLOW", new Color(1.00f, 1.00f, 0.88f)},
- {"LIME", new Color(0.00f, 1.00f, 0.00f)},
- {"LIMEGREEN", new Color(0.20f, 0.80f, 0.20f)},
- {"LINEN", new Color(0.98f, 0.94f, 0.90f)},
- {"MAGENTA", new Color(1.00f, 0.00f, 1.00f)},
- {"MAROON", new Color(0.69f, 0.19f, 0.38f)},
- {"MEDIUMAQUAMARINE", new Color(0.40f, 0.80f, 0.67f)},
- {"MEDIUMBLUE", new Color(0.00f, 0.00f, 0.80f)},
- {"MEDIUMORCHID", new Color(0.73f, 0.33f, 0.83f)},
- {"MEDIUMPURPLE", new Color(0.58f, 0.44f, 0.86f)},
- {"MEDIUMSEAGREEN", new Color(0.24f, 0.70f, 0.44f)},
- {"MEDIUMSLATEBLUE", new Color(0.48f, 0.41f, 0.93f)},
- {"MEDIUMSPRINGGREEN", new Color(0.00f, 0.98f, 0.60f)},
- {"MEDIUMTURQUOISE", new Color(0.28f, 0.82f, 0.80f)},
- {"MEDIUMVIOLETRED", new Color(0.78f, 0.08f, 0.52f)},
- {"MIDNIGHTBLUE", new Color(0.10f, 0.10f, 0.44f)},
- {"MINTCREAM", new Color(0.96f, 1.00f, 0.98f)},
- {"MISTYROSE", new Color(1.00f, 0.89f, 0.88f)},
- {"MOCCASIN", new Color(1.00f, 0.89f, 0.71f)},
- {"NAVAJOWHITE", new Color(1.00f, 0.87f, 0.68f)},
- {"NAVYBLUE", new Color(0.00f, 0.00f, 0.50f)},
- {"OLDLACE", new Color(0.99f, 0.96f, 0.90f)},
- {"OLIVE", new Color(0.50f, 0.50f, 0.00f)},
- {"OLIVEDRAB", new Color(0.42f, 0.56f, 0.14f)},
- {"ORANGE", new Color(1.00f, 0.65f, 0.00f)},
- {"ORANGERED", new Color(1.00f, 0.27f, 0.00f)},
- {"ORCHID", new Color(0.85f, 0.44f, 0.84f)},
- {"PALEGOLDENROD", new Color(0.93f, 0.91f, 0.67f)},
- {"PALEGREEN", new Color(0.60f, 0.98f, 0.60f)},
- {"PALETURQUOISE", new Color(0.69f, 0.93f, 0.93f)},
- {"PALEVIOLETRED", new Color(0.86f, 0.44f, 0.58f)},
- {"PAPAYAWHIP", new Color(1.00f, 0.94f, 0.84f)},
- {"PEACHPUFF", new Color(1.00f, 0.85f, 0.73f)},
- {"PERU", new Color(0.80f, 0.52f, 0.25f)},
- {"PINK", new Color(1.00f, 0.75f, 0.80f)},
- {"PLUM", new Color(0.87f, 0.63f, 0.87f)},
- {"POWDERBLUE", new Color(0.69f, 0.88f, 0.90f)},
- {"PURPLE", new Color(0.63f, 0.13f, 0.94f)},
- {"REBECCAPURPLE", new Color(0.40f, 0.20f, 0.60f)},
- {"RED", new Color(1.00f, 0.00f, 0.00f)},
- {"ROSYBROWN", new Color(0.74f, 0.56f, 0.56f)},
- {"ROYALBLUE", new Color(0.25f, 0.41f, 0.88f)},
- {"SADDLEBROWN", new Color(0.55f, 0.27f, 0.07f)},
- {"SALMON", new Color(0.98f, 0.50f, 0.45f)},
- {"SANDYBROWN", new Color(0.96f, 0.64f, 0.38f)},
- {"SEAGREEN", new Color(0.18f, 0.55f, 0.34f)},
- {"SEASHELL", new Color(1.00f, 0.96f, 0.93f)},
- {"SIENNA", new Color(0.63f, 0.32f, 0.18f)},
- {"SILVER", new Color(0.75f, 0.75f, 0.75f)},
- {"SKYBLUE", new Color(0.53f, 0.81f, 0.92f)},
- {"SLATEBLUE", new Color(0.42f, 0.35f, 0.80f)},
- {"SLATEGRAY", new Color(0.44f, 0.50f, 0.56f)},
- {"SNOW", new Color(1.00f, 0.98f, 0.98f)},
- {"SPRINGGREEN", new Color(0.00f, 1.00f, 0.50f)},
- {"STEELBLUE", new Color(0.27f, 0.51f, 0.71f)},
- {"TAN", new Color(0.82f, 0.71f, 0.55f)},
- {"TEAL", new Color(0.00f, 0.50f, 0.50f)},
- {"THISTLE", new Color(0.85f, 0.75f, 0.85f)},
- {"TOMATO", new Color(1.00f, 0.39f, 0.28f)},
- {"TRANSPARENT", new Color(1.00f, 1.00f, 1.00f, 0.00f)},
- {"TURQUOISE", new Color(0.25f, 0.88f, 0.82f)},
- {"VIOLET", new Color(0.93f, 0.51f, 0.93f)},
- {"WEBGRAY", new Color(0.50f, 0.50f, 0.50f)},
- {"WEBGREEN", new Color(0.00f, 0.50f, 0.00f)},
- {"WEBMAROON", new Color(0.50f, 0.00f, 0.00f)},
- {"WEBPURPLE", new Color(0.50f, 0.00f, 0.50f)},
- {"WHEAT", new Color(0.96f, 0.87f, 0.70f)},
- {"WHITE", new Color(1.00f, 1.00f, 1.00f)},
- {"WHITESMOKE", new Color(0.96f, 0.96f, 0.96f)},
- {"YELLOW", new Color(1.00f, 1.00f, 0.00f)},
- {"YELLOWGREEN", new Color(0.60f, 0.80f, 0.20f)},
+ { "ALICE_BLUE", new Color(0xF0F8FFFF) },
+ { "ANTIQUE_WHITE", new Color(0xFAEBD7FF) },
+ { "AQUA", new Color(0x00FFFFFF) },
+ { "AQUAMARINE", new Color(0x7FFFD4FF) },
+ { "AZURE", new Color(0xF0FFFFFF) },
+ { "BEIGE", new Color(0xF5F5DCFF) },
+ { "BISQUE", new Color(0xFFE4C4FF) },
+ { "BLACK", new Color(0x000000FF) },
+ { "BLANCHED_ALMOND", new Color(0xFFEBCDFF) },
+ { "BLUE", new Color(0x0000FFFF) },
+ { "BLUE_VIOLET", new Color(0x8A2BE2FF) },
+ { "BROWN", new Color(0xA52A2AFF) },
+ { "BURLYWOOD", new Color(0xDEB887FF) },
+ { "CADET_BLUE", new Color(0x5F9EA0FF) },
+ { "CHARTREUSE", new Color(0x7FFF00FF) },
+ { "CHOCOLATE", new Color(0xD2691EFF) },
+ { "CORAL", new Color(0xFF7F50FF) },
+ { "CORNFLOWER_BLUE", new Color(0x6495EDFF) },
+ { "CORNSILK", new Color(0xFFF8DCFF) },
+ { "CRIMSON", new Color(0xDC143CFF) },
+ { "CYAN", new Color(0x00FFFFFF) },
+ { "DARK_BLUE", new Color(0x00008BFF) },
+ { "DARK_CYAN", new Color(0x008B8BFF) },
+ { "DARK_GOLDENROD", new Color(0xB8860BFF) },
+ { "DARK_GRAY", new Color(0xA9A9A9FF) },
+ { "DARK_GREEN", new Color(0x006400FF) },
+ { "DARK_KHAKI", new Color(0xBDB76BFF) },
+ { "DARK_MAGENTA", new Color(0x8B008BFF) },
+ { "DARK_OLIVE_GREEN", new Color(0x556B2FFF) },
+ { "DARK_ORANGE", new Color(0xFF8C00FF) },
+ { "DARK_ORCHID", new Color(0x9932CCFF) },
+ { "DARK_RED", new Color(0x8B0000FF) },
+ { "DARK_SALMON", new Color(0xE9967AFF) },
+ { "DARK_SEA_GREEN", new Color(0x8FBC8FFF) },
+ { "DARK_SLATE_BLUE", new Color(0x483D8BFF) },
+ { "DARK_SLATE_GRAY", new Color(0x2F4F4FFF) },
+ { "DARK_TURQUOISE", new Color(0x00CED1FF) },
+ { "DARK_VIOLET", new Color(0x9400D3FF) },
+ { "DEEP_PINK", new Color(0xFF1493FF) },
+ { "DEEP_SKY_BLUE", new Color(0x00BFFFFF) },
+ { "DIM_GRAY", new Color(0x696969FF) },
+ { "DODGER_BLUE", new Color(0x1E90FFFF) },
+ { "FIREBRICK", new Color(0xB22222FF) },
+ { "FLORAL_WHITE", new Color(0xFFFAF0FF) },
+ { "FOREST_GREEN", new Color(0x228B22FF) },
+ { "FUCHSIA", new Color(0xFF00FFFF) },
+ { "GAINSBORO", new Color(0xDCDCDCFF) },
+ { "GHOST_WHITE", new Color(0xF8F8FFFF) },
+ { "GOLD", new Color(0xFFD700FF) },
+ { "GOLDENROD", new Color(0xDAA520FF) },
+ { "GRAY", new Color(0xBEBEBEFF) },
+ { "GREEN", new Color(0x00FF00FF) },
+ { "GREEN_YELLOW", new Color(0xADFF2FFF) },
+ { "HONEYDEW", new Color(0xF0FFF0FF) },
+ { "HOT_PINK", new Color(0xFF69B4FF) },
+ { "INDIAN_RED", new Color(0xCD5C5CFF) },
+ { "INDIGO", new Color(0x4B0082FF) },
+ { "IVORY", new Color(0xFFFFF0FF) },
+ { "KHAKI", new Color(0xF0E68CFF) },
+ { "LAVENDER", new Color(0xE6E6FAFF) },
+ { "LAVENDER_BLUSH", new Color(0xFFF0F5FF) },
+ { "LAWN_GREEN", new Color(0x7CFC00FF) },
+ { "LEMON_CHIFFON", new Color(0xFFFACDFF) },
+ { "LIGHT_BLUE", new Color(0xADD8E6FF) },
+ { "LIGHT_CORAL", new Color(0xF08080FF) },
+ { "LIGHT_CYAN", new Color(0xE0FFFFFF) },
+ { "LIGHT_GOLDENROD", new Color(0xFAFAD2FF) },
+ { "LIGHT_GRAY", new Color(0xD3D3D3FF) },
+ { "LIGHT_GREEN", new Color(0x90EE90FF) },
+ { "LIGHT_PINK", new Color(0xFFB6C1FF) },
+ { "LIGHT_SALMON", new Color(0xFFA07AFF) },
+ { "LIGHT_SEA_GREEN", new Color(0x20B2AAFF) },
+ { "LIGHT_SKY_BLUE", new Color(0x87CEFAFF) },
+ { "LIGHT_SLATE_GRAY", new Color(0x778899FF) },
+ { "LIGHT_STEEL_BLUE", new Color(0xB0C4DEFF) },
+ { "LIGHT_YELLOW", new Color(0xFFFFE0FF) },
+ { "LIME", new Color(0x00FF00FF) },
+ { "LIME_GREEN", new Color(0x32CD32FF) },
+ { "LINEN", new Color(0xFAF0E6FF) },
+ { "MAGENTA", new Color(0xFF00FFFF) },
+ { "MAROON", new Color(0xB03060FF) },
+ { "MEDIUM_AQUAMARINE", new Color(0x66CDAAFF) },
+ { "MEDIUM_BLUE", new Color(0x0000CDFF) },
+ { "MEDIUM_ORCHID", new Color(0xBA55D3FF) },
+ { "MEDIUM_PURPLE", new Color(0x9370DBFF) },
+ { "MEDIUM_SEA_GREEN", new Color(0x3CB371FF) },
+ { "MEDIUM_SLATE_BLUE", new Color(0x7B68EEFF) },
+ { "MEDIUM_SPRING_GREEN", new Color(0x00FA9AFF) },
+ { "MEDIUM_TURQUOISE", new Color(0x48D1CCFF) },
+ { "MEDIUM_VIOLET_RED", new Color(0xC71585FF) },
+ { "MIDNIGHT_BLUE", new Color(0x191970FF) },
+ { "MINT_CREAM", new Color(0xF5FFFAFF) },
+ { "MISTY_ROSE", new Color(0xFFE4E1FF) },
+ { "MOCCASIN", new Color(0xFFE4B5FF) },
+ { "NAVAJO_WHITE", new Color(0xFFDEADFF) },
+ { "NAVY_BLUE", new Color(0x000080FF) },
+ { "OLD_LACE", new Color(0xFDF5E6FF) },
+ { "OLIVE", new Color(0x808000FF) },
+ { "OLIVE_DRAB", new Color(0x6B8E23FF) },
+ { "ORANGE", new Color(0xFFA500FF) },
+ { "ORANGE_RED", new Color(0xFF4500FF) },
+ { "ORCHID", new Color(0xDA70D6FF) },
+ { "PALE_GOLDENROD", new Color(0xEEE8AAFF) },
+ { "PALE_GREEN", new Color(0x98FB98FF) },
+ { "PALE_TURQUOISE", new Color(0xAFEEEEFF) },
+ { "PALE_VIOLET_RED", new Color(0xDB7093FF) },
+ { "PAPAYA_WHIP", new Color(0xFFEFD5FF) },
+ { "PEACH_PUFF", new Color(0xFFDAB9FF) },
+ { "PERU", new Color(0xCD853FFF) },
+ { "PINK", new Color(0xFFC0CBFF) },
+ { "PLUM", new Color(0xDDA0DDFF) },
+ { "POWDER_BLUE", new Color(0xB0E0E6FF) },
+ { "PURPLE", new Color(0xA020F0FF) },
+ { "REBECCA_PURPLE", new Color(0x663399FF) },
+ { "RED", new Color(0xFF0000FF) },
+ { "ROSY_BROWN", new Color(0xBC8F8FFF) },
+ { "ROYAL_BLUE", new Color(0x4169E1FF) },
+ { "SADDLE_BROWN", new Color(0x8B4513FF) },
+ { "SALMON", new Color(0xFA8072FF) },
+ { "SANDY_BROWN", new Color(0xF4A460FF) },
+ { "SEA_GREEN", new Color(0x2E8B57FF) },
+ { "SEASHELL", new Color(0xFFF5EEFF) },
+ { "SIENNA", new Color(0xA0522DFF) },
+ { "SILVER", new Color(0xC0C0C0FF) },
+ { "SKY_BLUE", new Color(0x87CEEBFF) },
+ { "SLATE_BLUE", new Color(0x6A5ACDFF) },
+ { "SLATE_GRAY", new Color(0x708090FF) },
+ { "SNOW", new Color(0xFFFAFAFF) },
+ { "SPRING_GREEN", new Color(0x00FF7FFF) },
+ { "STEEL_BLUE", new Color(0x4682B4FF) },
+ { "TAN", new Color(0xD2B48CFF) },
+ { "TEAL", new Color(0x008080FF) },
+ { "THISTLE", new Color(0xD8BFD8FF) },
+ { "TOMATO", new Color(0xFF6347FF) },
+ { "TRANSPARENT", new Color(0xFFFFFF00) },
+ { "TURQUOISE", new Color(0x40E0D0FF) },
+ { "VIOLET", new Color(0xEE82EEFF) },
+ { "WEB_GRAY", new Color(0x808080FF) },
+ { "WEB_GREEN", new Color(0x008000FF) },
+ { "WEB_MAROON", new Color(0x800000FF) },
+ { "WEB_PURPLE", new Color(0x800080FF) },
+ { "WHEAT", new Color(0xF5DEB3FF) },
+ { "WHITE", new Color(0xFFFFFFFF) },
+ { "WHITE_SMOKE", new Color(0xF5F5F5FF) },
+ { "YELLOW", new Color(0xFFFF00FF) },
+ { "YELLOW_GREEN", new Color(0x9ACD32FF) },
};
#pragma warning disable CS1591 // Disable warning: "Missing XML comment for publicly visible type or member"
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/CustomGCHandle.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/CustomGCHandle.cs
new file mode 100644
index 0000000000..42f19ace1a
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/CustomGCHandle.cs
@@ -0,0 +1,98 @@
+#nullable enable
+
+using System;
+using System.Collections.Concurrent;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Loader;
+using Godot.Bridge;
+
+namespace Godot;
+
+/// <summary>
+/// Provides a GCHandle that becomes weak when unloading the assembly load context, without having
+/// to manually replace the GCHandle. This hides all the complexity of releasing strong GC handles
+/// to allow the assembly load context to unload properly.
+///
+/// Internally, a strong CustomGCHandle actually contains a weak GCHandle, while the actual strong
+/// reference is stored in a static table.
+/// </summary>
+public static class CustomGCHandle
+{
+ // ConditionalWeakTable uses DependentHandle, so it stores weak references.
+ // Having the assembly load context as key won't prevent it from unloading.
+ private static ConditionalWeakTable<AssemblyLoadContext, object?> _alcsBeingUnloaded = new();
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ public static bool IsAlcBeingUnloaded(AssemblyLoadContext alc) => _alcsBeingUnloaded.TryGetValue(alc, out _);
+
+ // ReSharper disable once RedundantNameQualifier
+ private static ConcurrentDictionary<
+ AssemblyLoadContext,
+ ConcurrentDictionary<GCHandle, object>
+ > _strongReferencesByAlc = new();
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void OnAlcUnloading(AssemblyLoadContext alc)
+ {
+ _alcsBeingUnloaded.Add(alc, null);
+
+ if (_strongReferencesByAlc.TryRemove(alc, out var strongReferences))
+ {
+ strongReferences.Clear();
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static GCHandle AllocStrong(object value)
+ => AllocStrong(value, value.GetType());
+
+ public static GCHandle AllocStrong(object value, Type valueType)
+ {
+ if (AlcReloadCfg.IsAlcReloadingEnabled)
+ {
+ var alc = AssemblyLoadContext.GetLoadContext(valueType.Assembly);
+
+ if (alc != null)
+ {
+ var weakHandle = GCHandle.Alloc(value, GCHandleType.Weak);
+
+ if (!IsAlcBeingUnloaded(alc))
+ {
+ var strongReferences = _strongReferencesByAlc.GetOrAdd(alc,
+ static alc =>
+ {
+ alc.Unloading += OnAlcUnloading;
+ return new();
+ });
+ strongReferences.TryAdd(weakHandle, value);
+ }
+
+ return weakHandle;
+ }
+ }
+
+ return GCHandle.Alloc(value, GCHandleType.Normal);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static GCHandle AllocWeak(object value) => GCHandle.Alloc(value, GCHandleType.Weak);
+
+ public static void Free(GCHandle handle)
+ {
+ if (AlcReloadCfg.IsAlcReloadingEnabled)
+ {
+ var target = handle.Target;
+
+ if (target != null)
+ {
+ var alc = AssemblyLoadContext.GetLoadContext(target.GetType().Assembly);
+
+ if (alc != null && _strongReferencesByAlc.TryGetValue(alc, out var strongReferences))
+ _ = strongReferences.TryRemove(handle, out _);
+ }
+ }
+
+ handle.Free();
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DebuggingUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DebuggingUtils.cs
index edfe3464ec..6fbc04702a 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/DebuggingUtils.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/DebuggingUtils.cs
@@ -1,13 +1,18 @@
using System;
using System.Diagnostics;
using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
using System.Text;
+using Godot.NativeInterop;
+
+#nullable enable
namespace Godot
{
internal static class DebuggingUtils
{
- internal static void AppendTypeName(this StringBuilder sb, Type type)
+ private static void AppendTypeName(this StringBuilder sb, Type type)
{
if (type.IsPrimitive)
sb.Append(type.Name);
@@ -16,21 +21,97 @@ namespace Godot
else
sb.Append(type);
- sb.Append(" ");
+ sb.Append(' ');
}
- public static void InstallTraceListener()
+ internal static void InstallTraceListener()
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new GodotTraceListener());
}
- public static void GetStackFrameInfo(StackFrame frame, out string fileName, out int fileLineNumber, out string methodDecl)
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ internal ref struct godot_stack_info
+ {
+ public godot_string File;
+ public godot_string Func;
+ public int Line;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ internal ref struct godot_stack_info_vector
{
- fileName = frame.GetFileName();
- fileLineNumber = frame.GetFileLineNumber();
+ private IntPtr _writeProxy;
+ private unsafe godot_stack_info* _ptr;
+
+ public readonly unsafe godot_stack_info* Elements
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public void Resize(int size)
+ {
+ if (size < 0)
+ throw new ArgumentOutOfRangeException(nameof(size));
+ var err = NativeFuncs.godotsharp_stack_info_vector_resize(ref this, size);
+ if (err != Error.Ok)
+ throw new InvalidOperationException("Failed to resize vector. Error code is: " + err.ToString());
+ }
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_stack_info_vector_destroy(ref this);
+ _ptr = null;
+ }
+ }
- MethodBase methodBase = frame.GetMethod();
+ [UnmanagedCallersOnly]
+ internal static unsafe void GetCurrentStackInfo(void* destVector)
+ {
+ try
+ {
+ var vector = (godot_stack_info_vector*)destVector;
+ var stackTrace = new StackTrace(skipFrames: 1, fNeedFileInfo: true);
+ int frameCount = stackTrace.FrameCount;
+
+ if (frameCount == 0)
+ return;
+
+ vector->Resize(frameCount);
+
+ int i = 0;
+ foreach (StackFrame frame in stackTrace.GetFrames())
+ {
+ string? fileName = frame.GetFileName();
+ int fileLineNumber = frame.GetFileLineNumber();
+
+ GetStackFrameMethodDecl(frame, out string methodDecl);
+
+ godot_stack_info* stackInfo = &vector->Elements[i];
+
+ // Assign directly to element in Vector. This way we don't need to worry
+ // about disposal if an exception is thrown. The Vector takes care of it.
+ stackInfo->File = Marshaling.ConvertStringToNative(fileName);
+ stackInfo->Func = Marshaling.ConvertStringToNative(methodDecl);
+ stackInfo->Line = fileLineNumber;
+
+ i++;
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ internal static void GetStackFrameMethodDecl(StackFrame frame, out string methodDecl)
+ {
+ MethodBase? methodBase = frame.GetMethod();
if (methodBase == null)
{
@@ -43,15 +124,15 @@ namespace Godot
if (methodBase is MethodInfo)
sb.AppendTypeName(((MethodInfo)methodBase).ReturnType);
- sb.Append(methodBase.DeclaringType.FullName);
- sb.Append(".");
+ sb.Append(methodBase.DeclaringType?.FullName ?? "<unknown>");
+ sb.Append('.');
sb.Append(methodBase.Name);
if (methodBase.IsGenericMethod)
{
Type[] genericParams = methodBase.GetGenericArguments();
- sb.Append("<");
+ sb.Append('<');
for (int j = 0; j < genericParams.Length; j++)
{
@@ -61,10 +142,10 @@ namespace Godot
sb.AppendTypeName(genericParams[j]);
}
- sb.Append(">");
+ sb.Append('>');
}
- sb.Append("(");
+ sb.Append('(');
bool varArgs = (methodBase.CallingConvention & CallingConventions.VarArgs) != 0;
@@ -81,7 +162,7 @@ namespace Godot
sb.AppendTypeName(parameter[i].ParameterType);
}
- sb.Append(")");
+ sb.Append(')');
methodDecl = sb.ToString();
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs
index 1dca9e6ea7..266038a0af 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs
@@ -1,14 +1,72 @@
+#nullable enable
+
using System;
using System.Collections.Generic;
-using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
namespace Godot
{
internal static class DelegateUtils
{
+ [UnmanagedCallersOnly]
+ internal static godot_bool DelegateEquals(IntPtr delegateGCHandleA, IntPtr delegateGCHandleB)
+ {
+ try
+ {
+ var @delegateA = (Delegate?)GCHandle.FromIntPtr(delegateGCHandleA).Target;
+ var @delegateB = (Delegate?)GCHandle.FromIntPtr(delegateGCHandleB).Target;
+ return (@delegateA! == @delegateB!).ToGodotBool();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe void InvokeWithVariantArgs(IntPtr delegateGCHandle, godot_variant** args, uint argc,
+ godot_variant* outRet)
+ {
+ try
+ {
+ // TODO: Optimize
+ var @delegate = (Delegate)GCHandle.FromIntPtr(delegateGCHandle).Target!;
+ var managedArgs = new object?[argc];
+
+ var parameterInfos = @delegate.Method.GetParameters();
+ var paramsLength = parameterInfos.Length;
+
+ if (argc != paramsLength)
+ {
+ throw new InvalidOperationException(
+ $"The delegate expects {paramsLength} arguments, but received {argc}.");
+ }
+
+ for (uint i = 0; i < argc; i++)
+ {
+ managedArgs[i] = Marshaling.ConvertVariantToManagedObjectOfType(
+ *args[i], parameterInfos[i].ParameterType);
+ }
+
+ object? invokeRet = @delegate.DynamicInvoke(managedArgs);
+
+ *outRet = Marshaling.ConvertManagedObjectToVariant(invokeRet);
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outRet = default;
+ }
+ }
+
+ // TODO: Check if we should be using BindingFlags.DeclaredOnly (would give better reflection performance).
+
private enum TargetKind : uint
{
Static,
@@ -39,20 +97,20 @@ namespace Godot
}
}
- if (TrySerializeSingleDelegate(@delegate, out byte[] buffer))
+ if (TrySerializeSingleDelegate(@delegate, out byte[]? buffer))
{
- serializedData.Add(buffer);
+ serializedData.Add((Span<byte>)buffer);
return true;
}
return false;
}
- private static bool TrySerializeSingleDelegate(Delegate @delegate, out byte[] buffer)
+ private static bool TrySerializeSingleDelegate(Delegate @delegate, [MaybeNullWhen(false)] out byte[] buffer)
{
buffer = null;
- object target = @delegate.Target;
+ object? target = @delegate.Target;
switch (target)
{
@@ -72,12 +130,14 @@ namespace Godot
return true;
}
}
+ // ReSharper disable once RedundantNameQualifier
case Godot.Object godotObject:
{
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream))
{
writer.Write((ulong)TargetKind.GodotObject);
+ // ReSharper disable once RedundantCast
writer.Write((ulong)godotObject.GetInstanceId());
SerializeType(writer, @delegate.GetType());
@@ -93,7 +153,7 @@ namespace Godot
{
Type targetType = target.GetType();
- if (targetType.GetCustomAttribute(typeof(CompilerGeneratedAttribute), true) != null)
+ if (targetType.IsDefined(typeof(CompilerGeneratedAttribute), true))
{
// Compiler generated. Probably a closure. Try to serialize it.
@@ -121,8 +181,18 @@ namespace Godot
if (variantType == Variant.Type.Nil)
return false;
+ static byte[] Var2Bytes(in godot_variant var)
+ {
+ NativeFuncs.godotsharp_var2bytes(var, false.ToGodotBool(), out var varBytes);
+ using (varBytes)
+ return Marshaling.ConvertNativePackedByteArrayToSystemArray(varBytes);
+ }
+
writer.Write(field.Name);
- byte[] valueBuffer = GD.Var2Bytes(field.GetValue(target));
+
+ var fieldValue = field.GetValue(target);
+ using var fieldValueVariant = Marshaling.ConvertManagedObjectToVariant(fieldValue);
+ byte[] valueBuffer = Var2Bytes(fieldValueVariant);
writer.Write(valueBuffer.Length);
writer.Write(valueBuffer);
}
@@ -139,9 +209,6 @@ namespace Godot
private static bool TrySerializeMethodInfo(BinaryWriter writer, MethodInfo methodInfo)
{
- if (methodInfo == null)
- return false;
-
SerializeType(writer, methodInfo.DeclaringType);
writer.Write(methodInfo.Name);
@@ -180,7 +247,7 @@ namespace Godot
return true;
}
- private static void SerializeType(BinaryWriter writer, Type type)
+ private static void SerializeType(BinaryWriter writer, Type? type)
{
if (type == null)
{
@@ -195,9 +262,8 @@ namespace Godot
int genericArgumentsCount = genericArgs.Length;
writer.Write(genericArgumentsCount);
- string assemblyQualifiedName = genericTypeDef.AssemblyQualifiedName;
- Debug.Assert(assemblyQualifiedName != null);
- writer.Write(assemblyQualifiedName);
+ writer.Write(genericTypeDef.Assembly.GetName().Name ?? "");
+ writer.Write(genericTypeDef.FullName ?? genericTypeDef.ToString());
for (int i = 0; i < genericArgs.Length; i++)
SerializeType(writer, genericArgs[i]);
@@ -207,17 +273,71 @@ namespace Godot
int genericArgumentsCount = 0;
writer.Write(genericArgumentsCount);
- string assemblyQualifiedName = type.AssemblyQualifiedName;
- Debug.Assert(assemblyQualifiedName != null);
- writer.Write(assemblyQualifiedName);
+ writer.Write(type.Assembly.GetName().Name ?? "");
+ writer.Write(type.FullName ?? type.ToString());
+ }
+ }
+
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool TrySerializeDelegateWithGCHandle(IntPtr delegateGCHandle,
+ godot_array* nSerializedData)
+ {
+ try
+ {
+ var serializedData = Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(*nSerializedData));
+
+ var @delegate = (Delegate)GCHandle.FromIntPtr(delegateGCHandle).Target!;
+
+ return TrySerializeDelegate(@delegate, serializedData)
+ .ToGodotBool();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ return godot_bool.False;
}
}
- private static bool TryDeserializeDelegate(Collections.Array serializedData, out Delegate @delegate)
+ [UnmanagedCallersOnly]
+ internal static unsafe godot_bool TryDeserializeDelegateWithGCHandle(godot_array* nSerializedData,
+ IntPtr* delegateGCHandle)
{
+ try
+ {
+ var serializedData = Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(*nSerializedData));
+
+ if (TryDeserializeDelegate(serializedData, out Delegate? @delegate))
+ {
+ *delegateGCHandle = GCHandle.ToIntPtr(CustomGCHandle.AllocStrong(@delegate));
+ return godot_bool.True;
+ }
+ else
+ {
+ *delegateGCHandle = IntPtr.Zero;
+ return godot_bool.False;
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *delegateGCHandle = default;
+ return godot_bool.False;
+ }
+ }
+
+ internal static bool TryDeserializeDelegate(Collections.Array serializedData,
+ [MaybeNullWhen(false)] out Delegate @delegate)
+ {
+ @delegate = null;
+
if (serializedData.Count == 1)
{
- object elem = serializedData[0];
+ var elem = serializedData[0].Obj;
+
+ if (elem == null)
+ return false;
if (elem is Collections.Array multiCastData)
return TryDeserializeDelegate(multiCastData, out @delegate);
@@ -225,20 +345,23 @@ namespace Godot
return TryDeserializeSingleDelegate((byte[])elem, out @delegate);
}
- @delegate = null;
-
var delegates = new List<Delegate>(serializedData.Count);
- foreach (object elem in serializedData)
+ foreach (Variant variantElem in serializedData)
{
+ var elem = variantElem.Obj;
+
+ if (elem == null)
+ continue;
+
if (elem is Collections.Array multiCastData)
{
- if (TryDeserializeDelegate(multiCastData, out Delegate oneDelegate))
+ if (TryDeserializeDelegate(multiCastData, out Delegate? oneDelegate))
delegates.Add(oneDelegate);
}
else
{
- if (TryDeserializeSingleDelegate((byte[])elem, out Delegate oneDelegate))
+ if (TryDeserializeSingleDelegate((byte[])elem, out Delegate? oneDelegate))
delegates.Add(oneDelegate);
}
}
@@ -246,11 +369,11 @@ namespace Godot
if (delegates.Count <= 0)
return false;
- @delegate = delegates.Count == 1 ? delegates[0] : Delegate.Combine(delegates.ToArray());
+ @delegate = delegates.Count == 1 ? delegates[0] : Delegate.Combine(delegates.ToArray())!;
return true;
}
- private static bool TryDeserializeSingleDelegate(byte[] buffer, out Delegate @delegate)
+ private static bool TryDeserializeSingleDelegate(byte[] buffer, [MaybeNullWhen(false)] out Delegate @delegate)
{
@delegate = null;
@@ -263,49 +386,59 @@ namespace Godot
{
case TargetKind.Static:
{
- Type delegateType = DeserializeType(reader);
+ Type? delegateType = DeserializeType(reader);
if (delegateType == null)
return false;
- if (!TryDeserializeMethodInfo(reader, out MethodInfo methodInfo))
+ if (!TryDeserializeMethodInfo(reader, out MethodInfo? methodInfo))
+ return false;
+
+ @delegate = Delegate.CreateDelegate(delegateType, null, methodInfo, throwOnBindFailure: false);
+
+ if (@delegate == null)
return false;
- @delegate = Delegate.CreateDelegate(delegateType, null, methodInfo);
return true;
}
case TargetKind.GodotObject:
{
ulong objectId = reader.ReadUInt64();
+ // ReSharper disable once RedundantNameQualifier
Godot.Object godotObject = GD.InstanceFromId(objectId);
if (godotObject == null)
return false;
- Type delegateType = DeserializeType(reader);
+ Type? delegateType = DeserializeType(reader);
if (delegateType == null)
return false;
- if (!TryDeserializeMethodInfo(reader, out MethodInfo methodInfo))
+ if (!TryDeserializeMethodInfo(reader, out MethodInfo? methodInfo))
+ return false;
+
+ @delegate = Delegate.CreateDelegate(delegateType, godotObject, methodInfo,
+ throwOnBindFailure: false);
+
+ if (@delegate == null)
return false;
- @delegate = Delegate.CreateDelegate(delegateType, godotObject, methodInfo);
return true;
}
case TargetKind.CompilerGenerated:
{
- Type targetType = DeserializeType(reader);
+ Type? targetType = DeserializeType(reader);
if (targetType == null)
return false;
- Type delegateType = DeserializeType(reader);
+ Type? delegateType = DeserializeType(reader);
if (delegateType == null)
return false;
- if (!TryDeserializeMethodInfo(reader, out MethodInfo methodInfo))
+ if (!TryDeserializeMethodInfo(reader, out MethodInfo? methodInfo))
return false;
int fieldCount = reader.ReadInt32();
- object recreatedTarget = Activator.CreateInstance(targetType);
+ object recreatedTarget = Activator.CreateInstance(targetType)!;
for (int i = 0; i < fieldCount; i++)
{
@@ -313,11 +446,17 @@ namespace Godot
int valueBufferLength = reader.ReadInt32();
byte[] valueBuffer = reader.ReadBytes(valueBufferLength);
- FieldInfo fieldInfo = targetType.GetField(name, BindingFlags.Instance | BindingFlags.Public);
+ FieldInfo? fieldInfo = targetType.GetField(name,
+ BindingFlags.Instance | BindingFlags.Public);
fieldInfo?.SetValue(recreatedTarget, GD.Bytes2Var(valueBuffer));
}
- @delegate = Delegate.CreateDelegate(delegateType, recreatedTarget, methodInfo);
+ @delegate = Delegate.CreateDelegate(delegateType, recreatedTarget, methodInfo,
+ throwOnBindFailure: false);
+
+ if (@delegate == null)
+ return false;
+
return true;
}
default:
@@ -326,18 +465,22 @@ namespace Godot
}
}
- private static bool TryDeserializeMethodInfo(BinaryReader reader, out MethodInfo methodInfo)
+ private static bool TryDeserializeMethodInfo(BinaryReader reader,
+ [MaybeNullWhen(false)] out MethodInfo methodInfo)
{
methodInfo = null;
- Type declaringType = DeserializeType(reader);
+ Type? declaringType = DeserializeType(reader);
+
+ if (declaringType == null)
+ return false;
string methodName = reader.ReadString();
int flags = reader.ReadInt32();
bool hasReturn = reader.ReadBoolean();
- Type returnType = hasReturn ? DeserializeType(reader) : typeof(void);
+ Type? returnType = hasReturn ? DeserializeType(reader) : typeof(void);
int parametersCount = reader.ReadInt32();
@@ -347,7 +490,7 @@ namespace Godot
for (int i = 0; i < parametersCount; i++)
{
- Type parameterType = DeserializeType(reader);
+ Type? parameterType = DeserializeType(reader);
if (parameterType == null)
return false;
parameterTypes[i] = parameterType;
@@ -361,15 +504,23 @@ namespace Godot
return methodInfo != null && methodInfo.ReturnType == returnType;
}
- private static Type DeserializeType(BinaryReader reader)
+ private static Type? DeserializeType(BinaryReader reader)
{
int genericArgumentsCount = reader.ReadInt32();
if (genericArgumentsCount == -1)
return null;
- string assemblyQualifiedName = reader.ReadString();
- var type = Type.GetType(assemblyQualifiedName);
+ string assemblyName = reader.ReadString();
+
+ if (assemblyName.Length == 0)
+ {
+ GD.PushError($"Missing assembly name of type when attempting to deserialize delegate");
+ return null;
+ }
+
+ string typeFullName = reader.ReadString();
+ var type = ReflectionUtils.FindTypeInLoadedAssemblies(assemblyName, typeFullName);
if (type == null)
return null; // Type not found
@@ -380,7 +531,7 @@ namespace Godot
for (int i = 0; i < genericArgumentsCount; i++)
{
- Type genericArgumentType = DeserializeType(reader);
+ Type? genericArgumentType = DeserializeType(reader);
if (genericArgumentType == null)
return null;
genericArgumentTypes[i] = genericArgumentType;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs
index e80b6af68f..95ad097192 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs
@@ -1,79 +1,50 @@
using System;
using System.Collections.Generic;
using System.Collections;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+using Godot.NativeInterop;
namespace Godot.Collections
{
- internal class DictionarySafeHandle : SafeHandle
- {
- public DictionarySafeHandle(IntPtr handle) : base(IntPtr.Zero, true)
- {
- this.handle = handle;
- }
-
- public override bool IsInvalid
- {
- get { return handle == IntPtr.Zero; }
- }
-
- protected override bool ReleaseHandle()
- {
- Dictionary.godot_icall_Dictionary_Dtor(handle);
- return true;
- }
- }
-
/// <summary>
/// Wrapper around Godot's Dictionary class, a dictionary of Variant
/// typed elements allocated in the engine in C++. Useful when
/// interfacing with the engine.
/// </summary>
- public class Dictionary : IDictionary, IDisposable
+ public sealed class Dictionary :
+ IDictionary<Variant, Variant>,
+ IReadOnlyDictionary<Variant, Variant>,
+ IDisposable
{
- private DictionarySafeHandle _safeHandle;
- private bool _disposed = false;
+ internal godot_dictionary.movable NativeValue;
+
+ private WeakReference<IDisposable> _weakReferenceToSelf;
/// <summary>
/// Constructs a new empty <see cref="Dictionary"/>.
/// </summary>
public Dictionary()
{
- _safeHandle = new DictionarySafeHandle(godot_icall_Dictionary_Ctor());
+ NativeValue = (godot_dictionary.movable)NativeFuncs.godotsharp_dictionary_new();
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
}
- /// <summary>
- /// Constructs a new <see cref="Dictionary"/> from the given dictionary's elements.
- /// </summary>
- /// <param name="dictionary">The dictionary to construct from.</param>
- /// <returns>A new Godot Dictionary.</returns>
- public Dictionary(IDictionary dictionary) : this()
- {
- if (dictionary == null)
- throw new NullReferenceException($"Parameter '{nameof(dictionary)} cannot be null.'");
-
- foreach (DictionaryEntry entry in dictionary)
- Add(entry.Key, entry.Value);
- }
-
- internal Dictionary(DictionarySafeHandle handle)
+ private Dictionary(godot_dictionary nativeValueToOwn)
{
- _safeHandle = handle;
+ NativeValue = (godot_dictionary.movable)(nativeValueToOwn.IsAllocated ?
+ nativeValueToOwn :
+ NativeFuncs.godotsharp_dictionary_new());
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
}
- internal Dictionary(IntPtr handle)
- {
- _safeHandle = new DictionarySafeHandle(handle);
- }
+ // Explicit name to make it very clear
+ internal static Dictionary CreateTakingOwnershipOfDisposableValue(godot_dictionary nativeValueToOwn)
+ => new Dictionary(nativeValueToOwn);
- internal IntPtr GetPtr()
+ ~Dictionary()
{
- if (_disposed)
- throw new ObjectDisposedException(GetType().FullName);
-
- return _safeHandle.DangerousGetHandle();
+ Dispose(false);
}
/// <summary>
@@ -81,16 +52,19 @@ namespace Godot.Collections
/// </summary>
public void Dispose()
{
- if (_disposed)
- return;
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- if (_safeHandle != null)
+ public void Dispose(bool disposing)
+ {
+ // Always dispose `NativeValue` even if disposing is true
+ NativeValue.DangerousSelfRef.Dispose();
+
+ if (_weakReferenceToSelf != null)
{
- _safeHandle.Dispose();
- _safeHandle = null;
+ DisposablesTracker.UnregisterDisposable(_weakReferenceToSelf);
}
-
- _disposed = true;
}
/// <summary>
@@ -100,7 +74,10 @@ namespace Godot.Collections
/// <returns>A new Godot Dictionary.</returns>
public Dictionary Duplicate(bool deep = false)
{
- return new Dictionary(godot_icall_Dictionary_Duplicate(GetPtr(), deep));
+ godot_dictionary newDictionary;
+ var self = (godot_dictionary)NativeValue;
+ NativeFuncs.godotsharp_dictionary_duplicate(ref self, deep.ToGodotBool(), out newDictionary);
+ return CreateTakingOwnershipOfDisposableValue(newDictionary);
}
// IDictionary
@@ -108,176 +85,250 @@ namespace Godot.Collections
/// <summary>
/// Gets the collection of keys in this <see cref="Dictionary"/>.
/// </summary>
- public ICollection Keys
+ public ICollection<Variant> Keys
{
get
{
- IntPtr handle = godot_icall_Dictionary_Keys(GetPtr());
- return new Array(new ArraySafeHandle(handle));
+ godot_array keysArray;
+ var self = (godot_dictionary)NativeValue;
+ NativeFuncs.godotsharp_dictionary_keys(ref self, out keysArray);
+ return Array.CreateTakingOwnershipOfDisposableValue(keysArray);
}
}
/// <summary>
/// Gets the collection of elements in this <see cref="Dictionary"/>.
/// </summary>
- public ICollection Values
+ public ICollection<Variant> Values
{
get
{
- IntPtr handle = godot_icall_Dictionary_Values(GetPtr());
- return new Array(new ArraySafeHandle(handle));
+ godot_array valuesArray;
+ var self = (godot_dictionary)NativeValue;
+ NativeFuncs.godotsharp_dictionary_values(ref self, out valuesArray);
+ return Array.CreateTakingOwnershipOfDisposableValue(valuesArray);
}
}
+ IEnumerable<Variant> IReadOnlyDictionary<Variant, Variant>.Keys => Keys;
+
+ IEnumerable<Variant> IReadOnlyDictionary<Variant, Variant>.Values => Values;
+
private (Array keys, Array values, int count) GetKeyValuePairs()
{
- int count = godot_icall_Dictionary_KeyValuePairs(GetPtr(), out IntPtr keysHandle, out IntPtr valuesHandle);
- Array keys = new Array(new ArraySafeHandle(keysHandle));
- Array values = new Array(new ArraySafeHandle(valuesHandle));
- return (keys, values, count);
- }
+ var self = (godot_dictionary)NativeValue;
- bool IDictionary.IsFixedSize => false;
+ godot_array keysArray;
+ NativeFuncs.godotsharp_dictionary_keys(ref self, out keysArray);
+ var keys = Array.CreateTakingOwnershipOfDisposableValue(keysArray);
- bool IDictionary.IsReadOnly => false;
+ godot_array valuesArray;
+ NativeFuncs.godotsharp_dictionary_keys(ref self, out valuesArray);
+ var values = Array.CreateTakingOwnershipOfDisposableValue(valuesArray);
+
+ int count = NativeFuncs.godotsharp_dictionary_count(ref self);
+
+ return (keys, values, count);
+ }
/// <summary>
- /// Returns the object at the given <paramref name="key"/>.
+ /// Returns the value at the given <paramref name="key"/>.
/// </summary>
- /// <value>The object at the given <paramref name="key"/>.</value>
- public object this[object key]
+ /// <value>The value at the given <paramref name="key"/>.</value>
+ public Variant this[Variant key]
{
- get => godot_icall_Dictionary_GetValue(GetPtr(), key);
- set => godot_icall_Dictionary_SetValue(GetPtr(), key, value);
+ get
+ {
+ var self = (godot_dictionary)NativeValue;
+
+ if (NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ (godot_variant)key.NativeVar, out godot_variant value).ToBool())
+ {
+ return Variant.CreateTakingOwnershipOfDisposableValue(value);
+ }
+ else
+ {
+ throw new KeyNotFoundException();
+ }
+ }
+ set
+ {
+ var self = (godot_dictionary)NativeValue;
+ NativeFuncs.godotsharp_dictionary_set_value(ref self,
+ (godot_variant)key.NativeVar, (godot_variant)value.NativeVar);
+ }
}
/// <summary>
- /// Adds an object <paramref name="value"/> at key <paramref name="key"/>
+ /// Adds an value <paramref name="value"/> at key <paramref name="key"/>
/// to this <see cref="Dictionary"/>.
/// </summary>
- /// <param name="key">The key at which to add the object.</param>
- /// <param name="value">The object to add.</param>
- public void Add(object key, object value) => godot_icall_Dictionary_Add(GetPtr(), key, value);
+ /// <param name="key">The key at which to add the value.</param>
+ /// <param name="value">The value to add.</param>
+ public void Add(Variant key, Variant value)
+ {
+ var variantKey = (godot_variant)key.NativeVar;
+ var self = (godot_dictionary)NativeValue;
+
+ if (NativeFuncs.godotsharp_dictionary_contains_key(ref self, variantKey).ToBool())
+ throw new ArgumentException("An element with the same key already exists", nameof(key));
+
+ godot_variant variantValue = (godot_variant)value.NativeVar;
+ NativeFuncs.godotsharp_dictionary_add(ref self, variantKey, variantValue);
+ }
+
+ void ICollection<KeyValuePair<Variant, Variant>>.Add(KeyValuePair<Variant, Variant> item)
+ => Add(item.Key, item.Value);
/// <summary>
/// Erases all items from this <see cref="Dictionary"/>.
/// </summary>
- public void Clear() => godot_icall_Dictionary_Clear(GetPtr());
+ public void Clear()
+ {
+ var self = (godot_dictionary)NativeValue;
+ NativeFuncs.godotsharp_dictionary_clear(ref self);
+ }
/// <summary>
/// Checks if this <see cref="Dictionary"/> contains the given key.
/// </summary>
/// <param name="key">The key to look for.</param>
/// <returns>Whether or not this dictionary contains the given key.</returns>
- public bool Contains(object key) => godot_icall_Dictionary_ContainsKey(GetPtr(), key);
+ public bool ContainsKey(Variant key)
+ {
+ var self = (godot_dictionary)NativeValue;
+ return NativeFuncs.godotsharp_dictionary_contains_key(ref self, (godot_variant)key.NativeVar).ToBool();
+ }
- /// <summary>
- /// Gets an enumerator for this <see cref="Dictionary"/>.
- /// </summary>
- /// <returns>An enumerator.</returns>
- public IDictionaryEnumerator GetEnumerator() => new DictionaryEnumerator(this);
+ public bool Contains(KeyValuePair<Variant, Variant> item)
+ {
+ godot_variant variantKey = (godot_variant)item.Key.NativeVar;
+ var self = (godot_dictionary)NativeValue;
+ bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ variantKey, out godot_variant retValue).ToBool();
+
+ using (retValue)
+ {
+ if (!found)
+ return false;
+
+ godot_variant variantValue = (godot_variant)item.Value.NativeVar;
+ return NativeFuncs.godotsharp_variant_equals(variantValue, retValue).ToBool();
+ }
+ }
/// <summary>
/// Removes an element from this <see cref="Dictionary"/> by key.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
- public void Remove(object key) => godot_icall_Dictionary_RemoveKey(GetPtr(), key);
+ public bool Remove(Variant key)
+ {
+ var self = (godot_dictionary)NativeValue;
+ return NativeFuncs.godotsharp_dictionary_remove_key(ref self, (godot_variant)key.NativeVar).ToBool();
+ }
- // ICollection
+ public bool Remove(KeyValuePair<Variant, Variant> item)
+ {
+ godot_variant variantKey = (godot_variant)item.Key.NativeVar;
+ var self = (godot_dictionary)NativeValue;
+ bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ variantKey, out godot_variant retValue).ToBool();
+
+ using (retValue)
+ {
+ if (!found)
+ return false;
- object ICollection.SyncRoot => this;
+ godot_variant variantValue = (godot_variant)item.Value.NativeVar;
+ if (NativeFuncs.godotsharp_variant_equals(variantValue, retValue).ToBool())
+ {
+ return NativeFuncs.godotsharp_dictionary_remove_key(
+ ref self, variantKey).ToBool();
+ }
- bool ICollection.IsSynchronized => false;
+ return false;
+ }
+ }
/// <summary>
/// Returns the number of elements in this <see cref="Dictionary"/>.
/// This is also known as the size or length of the dictionary.
/// </summary>
/// <returns>The number of elements.</returns>
- public int Count => godot_icall_Dictionary_Count(GetPtr());
+ public int Count
+ {
+ get
+ {
+ var self = (godot_dictionary)NativeValue;
+ return NativeFuncs.godotsharp_dictionary_count(ref self);
+ }
+ }
+
+ bool ICollection<KeyValuePair<Variant, Variant>>.IsReadOnly => false;
+
+ public bool TryGetValue(Variant key, out Variant value)
+ {
+ var self = (godot_dictionary)NativeValue;
+ bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ (godot_variant)key.NativeVar, out godot_variant retValue).ToBool();
+
+ value = found ? Variant.CreateTakingOwnershipOfDisposableValue(retValue) : default;
+
+ return found;
+ }
/// <summary>
- /// Copies the elements of this <see cref="Dictionary"/> to the given
- /// untyped C# array, starting at the given index.
+ /// Copies the elements of this <see cref="Dictionary"/> to the given untyped
+ /// <see cref="KeyValuePair{TKey, TValue}"/> array, starting at the given index.
/// </summary>
/// <param name="array">The array to copy to.</param>
- /// <param name="index">The index to start at.</param>
- public void CopyTo(System.Array array, int index)
+ /// <param name="arrayIndex">The index to start at.</param>
+ public void CopyTo(KeyValuePair<Variant, Variant>[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array), "Value cannot be null.");
- if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), "Number was less than the array's lower bound in the first dimension.");
+ if (arrayIndex < 0)
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex),
+ "Number was less than the array's lower bound in the first dimension.");
var (keys, values, count) = GetKeyValuePairs();
- if (array.Length < (index + count))
- throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
+ if (array.Length < (arrayIndex + count))
+ throw new ArgumentException(
+ "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
for (int i = 0; i < count; i++)
{
- array.SetValue(new DictionaryEntry(keys[i], values[i]), index);
- index++;
+ array[arrayIndex] = new(keys[i], values[i]);
+ arrayIndex++;
}
}
// IEnumerable
- IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
-
- private class DictionaryEnumerator : IDictionaryEnumerator
+ /// <summary>
+ /// Gets an enumerator for this <see cref="Dictionary"/>.
+ /// </summary>
+ /// <returns>An enumerator.</returns>
+ public IEnumerator<KeyValuePair<Variant, Variant>> GetEnumerator()
{
- private readonly Dictionary _dictionary;
- private readonly int _count;
- private int _index = -1;
- private bool _dirty = true;
-
- private DictionaryEntry _entry;
-
- public DictionaryEnumerator(Dictionary dictionary)
- {
- _dictionary = dictionary;
- _count = dictionary.Count;
- }
-
- public object Current => Entry;
-
- public DictionaryEntry Entry
- {
- get
- {
- if (_dirty)
- {
- UpdateEntry();
- }
- return _entry;
- }
- }
-
- private void UpdateEntry()
+ for (int i = 0; i < Count; i++)
{
- _dirty = false;
- godot_icall_Dictionary_KeyValuePairAt(_dictionary.GetPtr(), _index, out object key, out object value);
- _entry = new DictionaryEntry(key, value);
+ yield return GetKeyValuePair(i);
}
+ }
- public object Key => Entry.Key;
-
- public object Value => Entry.Value;
-
- public bool MoveNext()
- {
- _index++;
- _dirty = true;
- return _index < _count;
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- public void Reset()
- {
- _index = -1;
- _dirty = true;
- }
+ private KeyValuePair<Variant, Variant> GetKeyValuePair(int index)
+ {
+ var self = (godot_dictionary)NativeValue;
+ NativeFuncs.godotsharp_dictionary_key_value_pair_at(ref self, index,
+ out godot_variant key,
+ out godot_variant value);
+ return new KeyValuePair<Variant, Variant>(Variant.CreateTakingOwnershipOfDisposableValue(key),
+ Variant.CreateTakingOwnershipOfDisposableValue(value));
}
/// <summary>
@@ -286,74 +337,11 @@ namespace Godot.Collections
/// <returns>A string representation of this dictionary.</returns>
public override string ToString()
{
- return godot_icall_Dictionary_ToString(GetPtr());
+ var self = (godot_dictionary)NativeValue;
+ NativeFuncs.godotsharp_dictionary_to_string(ref self, out godot_string str);
+ using (str)
+ return Marshaling.ConvertStringToManaged(str);
}
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Dictionary_Ctor();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Dictionary_Dtor(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_Dictionary_GetValue(IntPtr ptr, object key);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_Dictionary_GetValue_Generic(IntPtr ptr, object key, int valTypeEncoding, IntPtr valTypeClass);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Dictionary_SetValue(IntPtr ptr, object key, object value);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Dictionary_Keys(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Dictionary_Values(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_Dictionary_Count(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_Dictionary_KeyValuePairs(IntPtr ptr, out IntPtr keys, out IntPtr values);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Dictionary_KeyValuePairAt(IntPtr ptr, int index, out object key, out object value);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Dictionary_KeyValuePairAt_Generic(IntPtr ptr, int index, out object key, out object value, int valueTypeEncoding, IntPtr valueTypeClass);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Dictionary_Add(IntPtr ptr, object key, object value);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Dictionary_Clear(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Dictionary_Contains(IntPtr ptr, object key, object value);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Dictionary_ContainsKey(IntPtr ptr, object key);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Dictionary_Duplicate(IntPtr ptr, bool deep);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Dictionary_RemoveKey(IntPtr ptr, object key);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Dictionary_Remove(IntPtr ptr, object key, object value);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Dictionary_TryGetValue(IntPtr ptr, object key, out object value);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_Dictionary_TryGetValue_Generic(IntPtr ptr, object key, out object value, int valTypeEncoding, IntPtr valTypeClass);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Dictionary_Generic_GetValueTypeInfo(Type valueType, out int valTypeEncoding, out IntPtr valTypeClass);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_Dictionary_ToString(IntPtr ptr);
}
/// <summary>
@@ -364,16 +352,51 @@ namespace Godot.Collections
/// </summary>
/// <typeparam name="TKey">The type of the dictionary's keys.</typeparam>
/// <typeparam name="TValue">The type of the dictionary's values.</typeparam>
- public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>
+ public class Dictionary<[MustBeVariant] TKey, [MustBeVariant] TValue> :
+ IDictionary<TKey, TValue>,
+ IReadOnlyDictionary<TKey, TValue>
{
- private readonly Dictionary _objectDict;
+ // ReSharper disable StaticMemberInGenericType
+ // Warning is about unique static fields being created for each generic type combination:
+ // https://www.jetbrains.com/help/resharper/StaticMemberInGenericType.html
+ // In our case this is exactly what we want.
+
+ private static unsafe delegate* managed<in TKey, godot_variant> _convertKeyToVariantCallback;
+ private static unsafe delegate* managed<in godot_variant, TKey> _convertKeyToManagedCallback;
+ private static unsafe delegate* managed<in TValue, godot_variant> _convertValueToVariantCallback;
+ private static unsafe delegate* managed<in godot_variant, TValue> _convertValueToManagedCallback;
+
+ // ReSharper restore StaticMemberInGenericType
+
+ static unsafe Dictionary()
+ {
+ _convertKeyToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<TKey>();
+ _convertKeyToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<TKey>();
+ _convertValueToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<TValue>();
+ _convertValueToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<TValue>();
+ }
+
+ private static unsafe void ValidateVariantConversionCallbacks()
+ {
+ if (_convertKeyToVariantCallback == null || _convertKeyToManagedCallback == null)
+ {
+ throw new InvalidOperationException(
+ $"The dictionary key type is not supported for conversion to Variant: '{typeof(TKey).FullName}'");
+ }
+
+ if (_convertValueToVariantCallback == null || _convertValueToManagedCallback == null)
+ {
+ throw new InvalidOperationException(
+ $"The dictionary value type is not supported for conversion to Variant: '{typeof(TValue).FullName}'");
+ }
+ }
- internal static int valTypeEncoding;
- internal static IntPtr valTypeClass;
+ private readonly Dictionary _underlyingDict;
- static Dictionary()
+ internal ref godot_dictionary.movable NativeValue
{
- Dictionary.godot_icall_Dictionary_Generic_GetValueTypeInfo(typeof(TValue), out valTypeEncoding, out valTypeClass);
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => ref _underlyingDict.NativeValue;
}
/// <summary>
@@ -381,7 +404,9 @@ namespace Godot.Collections
/// </summary>
public Dictionary()
{
- _objectDict = new Dictionary();
+ ValidateVariantConversionCallbacks();
+
+ _underlyingDict = new Dictionary();
}
/// <summary>
@@ -391,19 +416,15 @@ namespace Godot.Collections
/// <returns>A new Godot Dictionary.</returns>
public Dictionary(IDictionary<TKey, TValue> dictionary)
{
- _objectDict = new Dictionary();
+ ValidateVariantConversionCallbacks();
if (dictionary == null)
- throw new NullReferenceException($"Parameter '{nameof(dictionary)} cannot be null.'");
-
- // TODO: Can be optimized
+ throw new ArgumentNullException(nameof(dictionary));
- IntPtr godotDictionaryPtr = GetPtr();
+ _underlyingDict = new Dictionary();
foreach (KeyValuePair<TKey, TValue> entry in dictionary)
- {
- Dictionary.godot_icall_Dictionary_Add(godotDictionaryPtr, entry.Key, entry.Value);
- }
+ Add(entry.Key, entry.Value);
}
/// <summary>
@@ -413,18 +434,15 @@ namespace Godot.Collections
/// <returns>A new Godot Dictionary.</returns>
public Dictionary(Dictionary dictionary)
{
- _objectDict = dictionary;
- }
+ ValidateVariantConversionCallbacks();
- internal Dictionary(IntPtr handle)
- {
- _objectDict = new Dictionary(handle);
+ _underlyingDict = dictionary;
}
- internal Dictionary(DictionarySafeHandle handle)
- {
- _objectDict = new Dictionary(handle);
- }
+ // Explicit name to make it very clear
+ internal static Dictionary<TKey, TValue> CreateTakingOwnershipOfDisposableValue(
+ godot_dictionary nativeValueToOwn)
+ => new Dictionary<TKey, TValue>(Dictionary.CreateTakingOwnershipOfDisposableValue(nativeValueToOwn));
/// <summary>
/// Converts this typed <see cref="Dictionary{TKey, TValue}"/> to an untyped <see cref="Dictionary"/>.
@@ -432,12 +450,7 @@ namespace Godot.Collections
/// <param name="from">The typed dictionary to convert.</param>
public static explicit operator Dictionary(Dictionary<TKey, TValue> from)
{
- return from._objectDict;
- }
-
- internal IntPtr GetPtr()
- {
- return _objectDict.GetPtr();
+ return from?._underlyingDict;
}
/// <summary>
@@ -447,7 +460,7 @@ namespace Godot.Collections
/// <returns>A new Godot Dictionary.</returns>
public Dictionary<TKey, TValue> Duplicate(bool deep = false)
{
- return new Dictionary<TKey, TValue>(_objectDict.Duplicate(deep));
+ return new Dictionary<TKey, TValue>(_underlyingDict.Duplicate(deep));
}
// IDictionary<TKey, TValue>
@@ -456,10 +469,32 @@ namespace Godot.Collections
/// Returns the value at the given <paramref name="key"/>.
/// </summary>
/// <value>The value at the given <paramref name="key"/>.</value>
- public TValue this[TKey key]
+ public unsafe TValue this[TKey key]
{
- get { return (TValue)Dictionary.godot_icall_Dictionary_GetValue_Generic(_objectDict.GetPtr(), key, valTypeEncoding, valTypeClass); }
- set { _objectDict[key] = value; }
+ get
+ {
+ using var variantKey = _convertKeyToVariantCallback(key);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+
+ if (NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ variantKey, out godot_variant value).ToBool())
+ {
+ using (value)
+ return _convertValueToManagedCallback(value);
+ }
+ else
+ {
+ throw new KeyNotFoundException();
+ }
+ }
+ set
+ {
+ using var variantKey = _convertKeyToVariantCallback(key);
+ using var variantValue = _convertValueToVariantCallback(value);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ NativeFuncs.godotsharp_dictionary_set_value(ref self,
+ variantKey, variantValue);
+ }
}
/// <summary>
@@ -469,8 +504,10 @@ namespace Godot.Collections
{
get
{
- IntPtr handle = Dictionary.godot_icall_Dictionary_Keys(_objectDict.GetPtr());
- return new Array<TKey>(new ArraySafeHandle(handle));
+ godot_array keyArray;
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ NativeFuncs.godotsharp_dictionary_keys(ref self, out keyArray);
+ return Array<TKey>.CreateTakingOwnershipOfDisposableValue(keyArray);
}
}
@@ -481,15 +518,30 @@ namespace Godot.Collections
{
get
{
- IntPtr handle = Dictionary.godot_icall_Dictionary_Values(_objectDict.GetPtr());
- return new Array<TValue>(new ArraySafeHandle(handle));
+ godot_array valuesArray;
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ NativeFuncs.godotsharp_dictionary_values(ref self, out valuesArray);
+ return Array<TValue>.CreateTakingOwnershipOfDisposableValue(valuesArray);
}
}
- private KeyValuePair<TKey, TValue> GetKeyValuePair(int index)
+ IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys;
+
+ IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values;
+
+ private unsafe KeyValuePair<TKey, TValue> GetKeyValuePair(int index)
{
- Dictionary.godot_icall_Dictionary_KeyValuePairAt_Generic(GetPtr(), index, out object key, out object value, valTypeEncoding, valTypeClass);
- return new KeyValuePair<TKey, TValue>((TKey)key, (TValue)value);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ NativeFuncs.godotsharp_dictionary_key_value_pair_at(ref self, index,
+ out godot_variant key,
+ out godot_variant value);
+ using (key)
+ using (value)
+ {
+ return new KeyValuePair<TKey, TValue>(
+ _convertKeyToManagedCallback(key),
+ _convertValueToManagedCallback(value));
+ }
}
/// <summary>
@@ -498,9 +550,16 @@ namespace Godot.Collections
/// </summary>
/// <param name="key">The key at which to add the object.</param>
/// <param name="value">The object to add.</param>
- public void Add(TKey key, TValue value)
+ public unsafe void Add(TKey key, TValue value)
{
- _objectDict.Add(key, value);
+ using var variantKey = _convertKeyToVariantCallback(key);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+
+ if (NativeFuncs.godotsharp_dictionary_contains_key(ref self, variantKey).ToBool())
+ throw new ArgumentException("An element with the same key already exists", nameof(key));
+
+ using var variantValue = _convertValueToVariantCallback(value);
+ NativeFuncs.godotsharp_dictionary_add(ref self, variantKey, variantValue);
}
/// <summary>
@@ -508,18 +567,22 @@ namespace Godot.Collections
/// </summary>
/// <param name="key">The key to look for.</param>
/// <returns>Whether or not this dictionary contains the given key.</returns>
- public bool ContainsKey(TKey key)
+ public unsafe bool ContainsKey(TKey key)
{
- return _objectDict.Contains(key);
+ using var variantKey = _convertKeyToVariantCallback(key);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ return NativeFuncs.godotsharp_dictionary_contains_key(ref self, variantKey).ToBool();
}
/// <summary>
/// Removes an element from this <see cref="Dictionary{TKey, TValue}"/> by key.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
- public bool Remove(TKey key)
+ public unsafe bool Remove(TKey key)
{
- return Dictionary.godot_icall_Dictionary_RemoveKey(GetPtr(), key);
+ using var variantKey = _convertKeyToVariantCallback(key);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ return NativeFuncs.godotsharp_dictionary_remove_key(ref self, variantKey).ToBool();
}
/// <summary>
@@ -528,10 +591,16 @@ namespace Godot.Collections
/// <param name="key">The key of the element to get.</param>
/// <param name="value">The value at the given <paramref name="key"/>.</param>
/// <returns>If an object was found for the given <paramref name="key"/>.</returns>
- public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
+ public unsafe bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
- bool found = Dictionary.godot_icall_Dictionary_TryGetValue_Generic(GetPtr(), key, out object retValue, valTypeEncoding, valTypeClass);
- value = found ? (TValue)retValue : default;
+ using var variantKey = _convertKeyToVariantCallback(key);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ variantKey, out godot_variant retValue).ToBool();
+
+ using (retValue)
+ value = found ? _convertValueToManagedCallback(retValue) : default;
+
return found;
}
@@ -542,29 +611,33 @@ namespace Godot.Collections
/// This is also known as the size or length of the dictionary.
/// </summary>
/// <returns>The number of elements.</returns>
- public int Count
- {
- get { return _objectDict.Count; }
- }
+ public int Count => _underlyingDict.Count;
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
- {
- _objectDict.Add(item.Key, item.Value);
- }
+ => Add(item.Key, item.Value);
/// <summary>
/// Erases all the items from this <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
- public void Clear()
- {
- _objectDict.Clear();
- }
+ public void Clear() => _underlyingDict.Clear();
- bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
+ unsafe bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
- return _objectDict.Contains(new KeyValuePair<object, object>(item.Key, item.Value));
+ using var variantKey = _convertKeyToVariantCallback(item.Key);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ variantKey, out godot_variant retValue).ToBool();
+
+ using (retValue)
+ {
+ if (!found)
+ return false;
+
+ using var variantValue = _convertValueToVariantCallback(item.Value);
+ return NativeFuncs.godotsharp_variant_equals(variantValue, retValue).ToBool();
+ }
}
/// <summary>
@@ -579,12 +652,14 @@ namespace Godot.Collections
throw new ArgumentNullException(nameof(array), "Value cannot be null.");
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(arrayIndex), "Number was less than the array's lower bound in the first dimension.");
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex),
+ "Number was less than the array's lower bound in the first dimension.");
int count = Count;
if (array.Length < (arrayIndex + count))
- throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
+ throw new ArgumentException(
+ "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
for (int i = 0; i < count; i++)
{
@@ -593,10 +668,27 @@ namespace Godot.Collections
}
}
- bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
+ unsafe bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
- return Dictionary.godot_icall_Dictionary_Remove(GetPtr(), item.Key, item.Value);
- ;
+ using var variantKey = _convertKeyToVariantCallback(item.Key);
+ var self = (godot_dictionary)_underlyingDict.NativeValue;
+ bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self,
+ variantKey, out godot_variant retValue).ToBool();
+
+ using (retValue)
+ {
+ if (!found)
+ return false;
+
+ using var variantValue = _convertValueToVariantCallback(item.Value);
+ if (NativeFuncs.godotsharp_variant_equals(variantValue, retValue).ToBool())
+ {
+ return NativeFuncs.godotsharp_dictionary_remove_key(
+ ref self, variantKey).ToBool();
+ }
+
+ return false;
+ }
}
// IEnumerable<KeyValuePair<TKey, TValue>>
@@ -613,15 +705,18 @@ namespace Godot.Collections
}
}
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Converts this <see cref="Dictionary{TKey, TValue}"/> to a string.
/// </summary>
/// <returns>A string representation of this dictionary.</returns>
- public override string ToString() => _objectDict.ToString();
+ public override string ToString() => _underlyingDict.ToString();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Dictionary<TKey, TValue> from) => Variant.CreateFrom(from);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Dictionary<TKey, TValue>(Variant from) => from.AsGodotDictionary<TKey, TValue>();
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dispatcher.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dispatcher.cs
index 6475237002..e6cb4171a7 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dispatcher.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dispatcher.cs
@@ -1,20 +1,16 @@
-using System.Runtime.CompilerServices;
+using System;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
namespace Godot
{
public static class Dispatcher
{
- /// <summary>
- /// Implements an external instance of GodotTaskScheduler.
- /// </summary>
- /// <returns>A GodotTaskScheduler instance.</returns>
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern GodotTaskScheduler godot_icall_DefaultGodotTaskScheduler();
+ internal static GodotTaskScheduler DefaultGodotTaskScheduler;
- /// <summary>
- /// Initializes the synchronization context as the context of the GodotTaskScheduler.
- /// </summary>
- public static GodotSynchronizationContext SynchronizationContext =>
- godot_icall_DefaultGodotTaskScheduler().Context;
+ internal static void InitializeDefaultGodotTaskScheduler()
+ => DefaultGodotTaskScheduler = new GodotTaskScheduler();
+
+ public static GodotSynchronizationContext SynchronizationContext => DefaultGodotTaskScheduler.Context;
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DisposablesTracker.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DisposablesTracker.cs
new file mode 100644
index 0000000000..75793ea446
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/DisposablesTracker.cs
@@ -0,0 +1,95 @@
+using System;
+using System.Collections.Concurrent;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
+
+#nullable enable
+
+namespace Godot
+{
+ internal static class DisposablesTracker
+ {
+ [UnmanagedCallersOnly]
+ internal static void OnGodotShuttingDown()
+ {
+ try
+ {
+ OnGodotShuttingDownImpl();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
+ }
+
+ private static void OnGodotShuttingDownImpl()
+ {
+ bool isStdoutVerbose;
+
+ try
+ {
+ isStdoutVerbose = OS.IsStdoutVerbose();
+ }
+ catch (ObjectDisposedException)
+ {
+ // OS singleton already disposed. Maybe OnUnloading was called twice.
+ isStdoutVerbose = false;
+ }
+
+ if (isStdoutVerbose)
+ GD.Print("Unloading: Disposing tracked instances...");
+
+ // Dispose Godot Objects first, and only then dispose other disposables
+ // like StringName, NodePath, Godot.Collections.Array/Dictionary, etc.
+ // The Godot Object Dispose() method may need any of the later instances.
+
+ foreach (WeakReference<Object> item in GodotObjectInstances.Keys)
+ {
+ if (item.TryGetTarget(out Object? self))
+ self.Dispose();
+ }
+
+ foreach (WeakReference<IDisposable> item in OtherInstances.Keys)
+ {
+ if (item.TryGetTarget(out IDisposable? self))
+ self.Dispose();
+ }
+
+ if (isStdoutVerbose)
+ GD.Print("Unloading: Finished disposing tracked instances.");
+ }
+
+ // ReSharper disable once RedundantNameQualifier
+ private static ConcurrentDictionary<WeakReference<Godot.Object>, byte> GodotObjectInstances { get; } =
+ new();
+
+ private static ConcurrentDictionary<WeakReference<IDisposable>, byte> OtherInstances { get; } =
+ new();
+
+ public static WeakReference<Object> RegisterGodotObject(Object godotObject)
+ {
+ var weakReferenceToSelf = new WeakReference<Object>(godotObject);
+ GodotObjectInstances.TryAdd(weakReferenceToSelf, 0);
+ return weakReferenceToSelf;
+ }
+
+ public static WeakReference<IDisposable> RegisterDisposable(IDisposable disposable)
+ {
+ var weakReferenceToSelf = new WeakReference<IDisposable>(disposable);
+ OtherInstances.TryAdd(weakReferenceToSelf, 0);
+ return weakReferenceToSelf;
+ }
+
+ public static void UnregisterGodotObject(Object godotObject, WeakReference<Object> weakReferenceToSelf)
+ {
+ if (!GodotObjectInstances.TryRemove(weakReferenceToSelf, out _))
+ throw new ArgumentException("Godot Object not registered", nameof(weakReferenceToSelf));
+ }
+
+ public static void UnregisterDisposable(WeakReference<IDisposable> weakReference)
+ {
+ if (!OtherInstances.TryRemove(weakReference, out _))
+ throw new ArgumentException("Disposable not registered", nameof(weakReference));
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs
deleted file mode 100644
index 26d5f9c796..0000000000
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs
+++ /dev/null
@@ -1,220 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Dynamic;
-using System.Linq.Expressions;
-using System.Runtime.CompilerServices;
-
-namespace Godot
-{
- /// <summary>
- /// Represents an <see cref="Object"/> whose members can be dynamically accessed at runtime through the Variant API.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The <see cref="DynamicGodotObject"/> class enables access to the Variant
- /// members of a <see cref="Object"/> instance at runtime.
- /// </para>
- /// <para>
- /// This allows accessing the class members using their original names in the engine as well as the members from the
- /// script attached to the <see cref="Object"/>, regardless of the scripting language it was written in.
- /// </para>
- /// </remarks>
- /// <example>
- /// This sample shows how to use <see cref="DynamicGodotObject"/> to dynamically access the engine members of a <see cref="Object"/>.
- /// <code>
- /// dynamic sprite = GetNode("Sprite2D").DynamicGodotObject;
- /// sprite.add_child(this);
- ///
- /// if ((sprite.hframes * sprite.vframes) &gt; 0)
- /// sprite.frame = 0;
- /// </code>
- /// </example>
- /// <example>
- /// This sample shows how to use <see cref="DynamicGodotObject"/> to dynamically access the members of the script attached to a <see cref="Object"/>.
- /// <code>
- /// dynamic childNode = GetNode("ChildNode").DynamicGodotObject;
- ///
- /// if (childNode.print_allowed)
- /// {
- /// childNode.message = "Hello from C#";
- /// childNode.print_message(3);
- /// }
- /// </code>
- /// The <c>ChildNode</c> node has the following GDScript script attached:
- /// <code>
- /// // # ChildNode.gd
- /// // var print_allowed = true
- /// // var message = ""
- /// //
- /// // func print_message(times):
- /// // for i in times:
- /// // print(message)
- /// </code>
- /// </example>
- public class DynamicGodotObject : DynamicObject
- {
- /// <summary>
- /// Gets the <see cref="Object"/> associated with this <see cref="DynamicGodotObject"/>.
- /// </summary>
- public Object Value { get; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DynamicGodotObject"/> class.
- /// </summary>
- /// <param name="godotObject">
- /// The <see cref="Object"/> that will be associated with this <see cref="DynamicGodotObject"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// Thrown when the <paramref name="godotObject"/> parameter is <see langword="null"/>.
- /// </exception>
- public DynamicGodotObject(Object godotObject)
- {
- if (godotObject == null)
- throw new ArgumentNullException(nameof(godotObject));
-
- Value = godotObject;
- }
-
- /// <inheritdoc/>
- public override IEnumerable<string> GetDynamicMemberNames()
- {
- return godot_icall_DynamicGodotObject_SetMemberList(Object.GetPtr(Value));
- }
-
- /// <inheritdoc/>
- public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
- {
- switch (binder.Operation)
- {
- case ExpressionType.Equal:
- case ExpressionType.NotEqual:
- if (binder.ReturnType == typeof(bool) || binder.ReturnType.IsAssignableFrom(typeof(bool)))
- {
- if (arg == null)
- {
- bool boolResult = Object.IsInstanceValid(Value);
-
- if (binder.Operation == ExpressionType.Equal)
- boolResult = !boolResult;
-
- result = boolResult;
- return true;
- }
-
- if (arg is Object other)
- {
- bool boolResult = (Value == other);
-
- if (binder.Operation == ExpressionType.NotEqual)
- boolResult = !boolResult;
-
- result = boolResult;
- return true;
- }
- }
-
- break;
- default:
- // We're not implementing operators <, <=, >, and >= (LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual).
- // These are used on the actual pointers in variant_op.cpp. It's better to let the user do that explicitly.
- break;
- }
-
- return base.TryBinaryOperation(binder, arg, out result);
- }
-
- /// <inheritdoc/>
- public override bool TryConvert(ConvertBinder binder, out object result)
- {
- if (binder.Type == typeof(Object))
- {
- result = Value;
- return true;
- }
-
- if (typeof(Object).IsAssignableFrom(binder.Type))
- {
- // Throws InvalidCastException when the cast fails
- result = Convert.ChangeType(Value, binder.Type);
- return true;
- }
-
- return base.TryConvert(binder, out result);
- }
-
- /// <inheritdoc/>
- public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
- {
- if (indexes.Length == 1)
- {
- if (indexes[0] is string name)
- {
- return godot_icall_DynamicGodotObject_GetMember(Object.GetPtr(Value), name, out result);
- }
- }
-
- return base.TryGetIndex(binder, indexes, out result);
- }
-
- /// <inheritdoc/>
- public override bool TryGetMember(GetMemberBinder binder, out object result)
- {
- return godot_icall_DynamicGodotObject_GetMember(Object.GetPtr(Value), binder.Name, out result);
- }
-
- /// <inheritdoc/>
- public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
- {
- return godot_icall_DynamicGodotObject_InvokeMember(Object.GetPtr(Value), binder.Name, args, out result);
- }
-
- /// <inheritdoc/>
- public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
- {
- if (indexes.Length == 1)
- {
- if (indexes[0] is string name)
- {
- return godot_icall_DynamicGodotObject_SetMember(Object.GetPtr(Value), name, value);
- }
- }
-
- return base.TrySetIndex(binder, indexes, value);
- }
-
- /// <inheritdoc/>
- public override bool TrySetMember(SetMemberBinder binder, object value)
- {
- return godot_icall_DynamicGodotObject_SetMember(Object.GetPtr(Value), binder.Name, value);
- }
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string[] godot_icall_DynamicGodotObject_SetMemberList(IntPtr godotObject);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_DynamicGodotObject_InvokeMember(IntPtr godotObject, string name, object[] args, out object result);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_DynamicGodotObject_GetMember(IntPtr godotObject, string name, out object result);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_DynamicGodotObject_SetMember(IntPtr godotObject, string name, object value);
-
- #region We don't override these methods
-
- // Looks like this is not usable from C#
- //public override bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result);
-
- // Object members cannot be deleted
- //public override bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes);
- //public override bool TryDeleteMember(DeleteMemberBinder binder);
-
- // Invocation on the object itself, e.g.: obj(param)
- //public override bool TryInvoke(InvokeBinder binder, object[] args, out object result);
-
- // No unnary operations to handle
- //public override bool TryUnaryOperation(UnaryOperationBinder binder, out object result);
-
- #endregion
- }
-}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/NodeExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/NodeExtensions.cs
index 1dc21b6303..df0e839866 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/NodeExtensions.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/NodeExtensions.cs
@@ -93,8 +93,12 @@ namespace Godot
/// Negative indices access the children from the last one.
/// To access a child node via its name, use <see cref="GetNode"/>.
/// </summary>
- /// <seealso cref="GetChildOrNull{T}(int)"/>
+ /// <seealso cref="GetChildOrNull{T}(int, bool)"/>
/// <param name="idx">Child index.</param>
+ /// <param name="includeInternal">
+ /// If <see langword="false"/>, internal children are skipped (see <c>internal</c>
+ /// parameter in <see cref="AddChild(Node, bool, InternalMode)"/>).
+ /// </param>
/// <exception cref="InvalidCastException">
/// Thrown when the given the fetched node can't be casted to the given type <typeparamref name="T"/>.
/// </exception>
@@ -102,9 +106,9 @@ namespace Godot
/// <returns>
/// The child <see cref="Node"/> at the given index <paramref name="idx"/>.
/// </returns>
- public T GetChild<T>(int idx) where T : class
+ public T GetChild<T>(int idx, bool includeInternal = false) where T : class
{
- return (T)(object)GetChild(idx);
+ return (T)(object)GetChild(idx, includeInternal);
}
/// <summary>
@@ -113,15 +117,20 @@ namespace Godot
/// Negative indices access the children from the last one.
/// To access a child node via its name, use <see cref="GetNode"/>.
/// </summary>
- /// <seealso cref="GetChild{T}(int)"/>
+ /// <seealso cref="GetChild{T}(int, bool)"/>
/// <param name="idx">Child index.</param>
+ /// <param name="includeInternal">
+ /// If <see langword="false"/>, internal children are skipped (see <c>internal</c>
+ /// parameter in <see cref="AddChild(Node, bool, InternalMode)"/>).
+ /// </param>
/// <typeparam name="T">The type to cast to. Should be a descendant of <see cref="Node"/>.</typeparam>
/// <returns>
/// The child <see cref="Node"/> at the given index <paramref name="idx"/>, or <see langword="null"/> if not found.
/// </returns>
- public T GetChildOrNull<T>(int idx) where T : class
+ public T GetChildOrNull<T>(int idx, bool includeInternal = false) where T : class
{
- return GetChild(idx) as T;
+ int count = GetChildCount(includeInternal);
+ return idx >= -count && idx < count ? GetChild(idx, includeInternal) as T : null;
}
/// <summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/ObjectExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/ObjectExtensions.cs
index 691fd85964..4094ceeb22 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/ObjectExtensions.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/ObjectExtensions.cs
@@ -1,5 +1,5 @@
using System;
-using System.Runtime.CompilerServices;
+using Godot.NativeInterop;
namespace Godot
{
@@ -32,10 +32,17 @@ namespace Godot
/// </returns>
public static WeakRef WeakRef(Object obj)
{
- return godot_icall_Object_weakref(GetPtr(obj));
- }
+ if (!IsInstanceValid(obj))
+ return null;
+
+ NativeFuncs.godotsharp_weakref(GetPtr(obj), out godot_ref weakRef);
+ using (weakRef)
+ {
+ if (weakRef.IsNull)
+ return null;
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern WeakRef godot_icall_Object_weakref(IntPtr obj);
+ return (WeakRef)InteropUtils.UnmanagedGetManaged(weakRef.Reference);
+ }
+ }
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs
deleted file mode 100644
index df130a5c77..0000000000
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-using System.Runtime.CompilerServices;
-using Godot.Collections;
-
-namespace Godot
-{
- public partial class SceneTree
- {
- /// <summary>
- /// Returns a list of all nodes assigned to the given <paramref name="group"/>.
- /// </summary>
- /// <typeparam name="T">The type to cast to. Should be a descendant of <see cref="Node"/>.</typeparam>
- public Array<T> GetNodesInGroup<T>(StringName group) where T : class
- {
- return new Array<T>(godot_icall_SceneTree_get_nodes_in_group_Generic(GetPtr(this), StringName.GetPtr(group), typeof(T)));
- }
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_SceneTree_get_nodes_in_group_Generic(IntPtr obj, IntPtr group, Type elemType);
- }
-}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
index 236d0666bc..9e7da7757a 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
@@ -1,11 +1,6 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Collections.Generic;
-using System.Runtime.CompilerServices;
+using Godot.NativeInterop;
namespace Godot
{
@@ -26,9 +21,11 @@ namespace Godot
/// <param name="bytes">Byte array that will be decoded to a <c>Variant</c>.</param>
/// <param name="allowObjects">If objects should be decoded.</param>
/// <returns>The decoded <c>Variant</c>.</returns>
- public static object Bytes2Var(byte[] bytes, bool allowObjects = false)
+ public static Variant Bytes2Var(Span<byte> bytes, bool allowObjects = false)
{
- return godot_icall_GD_bytes2var(bytes, allowObjects);
+ using var varBytes = Marshaling.ConvertSystemArrayToNativePackedByteArray(bytes);
+ NativeFuncs.godotsharp_bytes2var(varBytes, allowObjects.ToGodotBool(), out godot_variant ret);
+ return Variant.CreateTakingOwnershipOfDisposableValue(ret);
}
/// <summary>
@@ -46,9 +43,10 @@ namespace Godot
/// </code>
/// </example>
/// <returns>The <c>Variant</c> converted to the given <paramref name="type"/>.</returns>
- public static object Convert(object what, Variant.Type type)
+ public static Variant Convert(Variant what, Variant.Type type)
{
- return godot_icall_GD_convert(what, type);
+ NativeFuncs.godotsharp_convert((godot_variant)what.NativeVar, (int)type, out godot_variant ret);
+ return Variant.CreateTakingOwnershipOfDisposableValue(ret);
}
/// <summary>
@@ -62,7 +60,7 @@ namespace Godot
return (real_t)Math.Exp(db * 0.11512925464970228420089957273422);
}
- private static object[] GetPrintParams(object[] parameters)
+ private static string[] GetPrintParams(object[] parameters)
{
if (parameters == null)
{
@@ -82,9 +80,9 @@ namespace Godot
/// </example>
/// <param name="var">Variable that will be hashed.</param>
/// <returns>Hash of the variable passed.</returns>
- public static int Hash(object var)
+ public static int Hash(Variant var)
{
- return godot_icall_GD_hash(var);
+ return NativeFuncs.godotsharp_hash((godot_variant)var.NativeVar);
}
/// <summary>
@@ -110,7 +108,7 @@ namespace Godot
/// <returns>The <see cref="Object"/> instance.</returns>
public static Object InstanceFromId(ulong instanceId)
{
- return godot_icall_GD_instance_from_id(instanceId);
+ return InteropUtils.UnmanagedGetManaged(NativeFuncs.godotsharp_instance_from_id(instanceId));
}
/// <summary>
@@ -191,8 +189,6 @@ namespace Godot
/// Pushes an error message to Godot's built-in debugger and to the OS terminal.
///
/// Note: Errors printed this way will not pause project execution.
- /// To print an error message and pause project execution in debug builds,
- /// use [code]assert(false, "test error")[/code] instead.
/// </summary>
/// <example>
/// <code>
@@ -202,7 +198,8 @@ namespace Godot
/// <param name="message">Error message.</param>
public static void PushError(string message)
{
- godot_icall_GD_pusherror(message);
+ using var godotStr = Marshaling.ConvertStringToNative(message);
+ NativeFuncs.godotsharp_pusherror(godotStr);
}
/// <summary>
@@ -214,7 +211,8 @@ namespace Godot
/// <param name="message">Warning message.</param>
public static void PushWarning(string message)
{
- godot_icall_GD_pushwarning(message);
+ using var godotStr = Marshaling.ConvertStringToNative(message);
+ NativeFuncs.godotsharp_pushwarning(godotStr);
}
/// <summary>
@@ -235,7 +233,9 @@ namespace Godot
/// <param name="what">Arguments that will be printed.</param>
public static void Print(params object[] what)
{
- godot_icall_GD_print(GetPrintParams(what));
+ string str = string.Concat(GetPrintParams(what));
+ using var godotStr = Marshaling.ConvertStringToNative(str);
+ NativeFuncs.godotsharp_print(godotStr);
}
/// <summary>
@@ -264,7 +264,9 @@ namespace Godot
/// <param name="what">Arguments that will be printed.</param>
public static void PrintRich(params object[] what)
{
- godot_icall_GD_print_rich(GetPrintParams(what));
+ string str = string.Concat(GetPrintParams(what));
+ using var godotStr = Marshaling.ConvertStringToNative(str);
+ NativeFuncs.godotsharp_print_rich(godotStr);
}
/// <summary>
@@ -286,7 +288,9 @@ namespace Godot
/// <param name="what">Arguments that will be printed.</param>
public static void PrintErr(params object[] what)
{
- godot_icall_GD_printerr(GetPrintParams(what));
+ string str = string.Concat(GetPrintParams(what));
+ using var godotStr = Marshaling.ConvertStringToNative(str);
+ NativeFuncs.godotsharp_printerr(godotStr);
}
/// <summary>
@@ -306,7 +310,9 @@ namespace Godot
/// <param name="what">Arguments that will be printed.</param>
public static void PrintRaw(params object[] what)
{
- godot_icall_GD_printraw(GetPrintParams(what));
+ string str = string.Concat(GetPrintParams(what));
+ using var godotStr = Marshaling.ConvertStringToNative(str);
+ NativeFuncs.godotsharp_printraw(godotStr);
}
/// <summary>
@@ -320,7 +326,9 @@ namespace Godot
/// <param name="what">Arguments that will be printed.</param>
public static void PrintS(params object[] what)
{
- godot_icall_GD_prints(GetPrintParams(what));
+ string str = string.Join(' ', GetPrintParams(what));
+ using var godotStr = Marshaling.ConvertStringToNative(str);
+ NativeFuncs.godotsharp_prints(godotStr);
}
/// <summary>
@@ -334,7 +342,9 @@ namespace Godot
/// <param name="what">Arguments that will be printed.</param>
public static void PrintT(params object[] what)
{
- godot_icall_GD_printt(GetPrintParams(what));
+ string str = string.Join('\t', GetPrintParams(what));
+ using var godotStr = Marshaling.ConvertStringToNative(str);
+ NativeFuncs.godotsharp_printt(godotStr);
}
/// <summary>
@@ -348,7 +358,7 @@ namespace Godot
/// <returns>A random <see langword="float"/> number.</returns>
public static float Randf()
{
- return godot_icall_GD_randf();
+ return NativeFuncs.godotsharp_randf();
}
/// <summary>
@@ -358,7 +368,7 @@ namespace Godot
/// <returns>A random normally-distributed <see langword="float"/> number.</returns>
public static double Randfn(double mean, double deviation)
{
- return godot_icall_GD_randfn(mean, deviation);
+ return NativeFuncs.godotsharp_randfn(mean, deviation);
}
/// <summary>
@@ -376,7 +386,7 @@ namespace Godot
/// <returns>A random <see langword="uint"/> number.</returns>
public static uint Randi()
{
- return godot_icall_GD_randi();
+ return NativeFuncs.godotsharp_randi();
}
/// <summary>
@@ -389,7 +399,7 @@ namespace Godot
/// </summary>
public static void Randomize()
{
- godot_icall_GD_randomize();
+ NativeFuncs.godotsharp_randomize();
}
/// <summary>
@@ -404,7 +414,7 @@ namespace Godot
/// <returns>A random <see langword="double"/> number inside the given range.</returns>
public static double RandRange(double from, double to)
{
- return godot_icall_GD_randf_range(from, to);
+ return NativeFuncs.godotsharp_randf_range(from, to);
}
/// <summary>
@@ -421,7 +431,7 @@ namespace Godot
/// <returns>A random <see langword="int"/> number inside the given range.</returns>
public static int RandRange(int from, int to)
{
- return godot_icall_GD_randi_range(from, to);
+ return NativeFuncs.godotsharp_randi_range(from, to);
}
/// <summary>
@@ -434,7 +444,7 @@ namespace Godot
/// <returns>A random <see langword="uint"/> number.</returns>
public static uint RandFromSeed(ref ulong seed)
{
- return godot_icall_GD_rand_seed(seed, out seed);
+ return NativeFuncs.godotsharp_rand_from_seed(seed, out seed);
}
/// <summary>
@@ -491,7 +501,7 @@ namespace Godot
/// <param name="seed">Seed that will be used.</param>
public static void Seed(ulong seed)
{
- godot_icall_GD_seed(seed);
+ NativeFuncs.godotsharp_seed(seed);
}
/// <summary>
@@ -499,13 +509,16 @@ namespace Godot
/// </summary>
/// <param name="what">Arguments that will converted to string.</param>
/// <returns>The string formed by the given arguments.</returns>
- public static string Str(params object[] what)
+ public static string Str(params Variant[] what)
{
- return godot_icall_GD_str(what);
+ using var whatGodot = new Godot.Collections.Array(what);
+ NativeFuncs.godotsharp_str((godot_array)whatGodot.NativeValue, out godot_string ret);
+ using (ret)
+ return Marshaling.ConvertStringToManaged(ret);
}
/// <summary>
- /// Converts a formatted string that was returned by <see cref="Var2Str(object)"/> to the original value.
+ /// Converts a formatted string that was returned by <see cref="Var2Str(Variant)"/> to the original value.
/// </summary>
/// <example>
/// <code>
@@ -516,32 +529,27 @@ namespace Godot
/// </example>
/// <param name="str">String that will be converted to Variant.</param>
/// <returns>The decoded <c>Variant</c>.</returns>
- public static object Str2Var(string str)
+ public static Variant Str2Var(string str)
{
- return godot_icall_GD_str2var(str);
- }
-
- /// <summary>
- /// Returns whether the given class exists in <see cref="ClassDB"/>.
- /// </summary>
- /// <returns>If the class exists in <see cref="ClassDB"/>.</returns>
- public static bool TypeExists(StringName type)
- {
- return godot_icall_GD_type_exists(StringName.GetPtr(type));
+ using var godotStr = Marshaling.ConvertStringToNative(str);
+ NativeFuncs.godotsharp_str2var(godotStr, out godot_variant ret);
+ return Variant.CreateTakingOwnershipOfDisposableValue(ret);
}
/// <summary>
/// Encodes a <c>Variant</c> value to a byte array.
/// If <paramref name="fullObjects"/> is <see langword="true"/> encoding objects is allowed
/// (and can potentially include code).
- /// Deserialization can be done with <see cref="Bytes2Var(byte[], bool)"/>.
+ /// Deserialization can be done with <see cref="Bytes2Var(Span{byte}, bool)"/>.
/// </summary>
/// <param name="var">Variant that will be encoded.</param>
/// <param name="fullObjects">If objects should be serialized.</param>
/// <returns>The <c>Variant</c> encoded as an array of bytes.</returns>
- public static byte[] Var2Bytes(object var, bool fullObjects = false)
+ public static byte[] Var2Bytes(Variant var, bool fullObjects = false)
{
- return godot_icall_GD_var2bytes(var, fullObjects);
+ NativeFuncs.godotsharp_var2bytes((godot_variant)var.NativeVar, fullObjects.ToGodotBool(), out var varBytes);
+ using (varBytes)
+ return Marshaling.ConvertNativePackedByteArrayToSystemArray(varBytes);
}
/// <summary>
@@ -561,9 +569,11 @@ namespace Godot
/// </example>
/// <param name="var">Variant that will be converted to string.</param>
/// <returns>The <c>Variant</c> encoded as a string.</returns>
- public static string Var2Str(object var)
+ public static string Var2Str(Variant var)
{
- return godot_icall_GD_var2str(var);
+ NativeFuncs.godotsharp_var2str((godot_variant)var.NativeVar, out godot_string ret);
+ using (ret)
+ return Marshaling.ConvertStringToManaged(ret);
}
/// <summary>
@@ -572,85 +582,7 @@ namespace Godot
/// <returns>The <see cref="Variant.Type"/> for the given <paramref name="type"/>.</returns>
public static Variant.Type TypeToVariantType(Type type)
{
- return godot_icall_TypeToVariantType(type);
+ return Marshaling.ConvertManagedTypeToVariantType(type, out bool _);
}
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_GD_bytes2var(byte[] bytes, bool allowObjects);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_GD_convert(object what, Variant.Type type);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_GD_hash(object var);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern Object godot_icall_GD_instance_from_id(ulong instanceId);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_print(object[] what);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_print_rich(object[] what);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_printerr(object[] what);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_printraw(object[] what);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_prints(object[] what);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_printt(object[] what);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_randomize();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern uint godot_icall_GD_randi();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern float godot_icall_GD_randf();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_GD_randi_range(int from, int to);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern double godot_icall_GD_randf_range(double from, double to);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern double godot_icall_GD_randfn(double mean, double deviation);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern uint godot_icall_GD_rand_seed(ulong seed, out ulong newSeed);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_seed(ulong seed);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_GD_str(object[] what);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern object godot_icall_GD_str2var(string str);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool godot_icall_GD_type_exists(IntPtr type);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern byte[] godot_icall_GD_var2bytes(object what, bool fullObjects);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_GD_var2str(object var);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_pusherror(string type);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_GD_pushwarning(string type);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern Variant.Type godot_icall_TypeToVariantType(Type type);
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs
index 9ccac1faaf..78a9d0fe9d 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs
@@ -17,10 +17,7 @@ namespace Godot
public override void Fail(string message, string detailMessage)
{
GD.PrintErr("Assertion failed: ", message);
- if (detailMessage != null)
- {
- GD.PrintErr(" Details: ", detailMessage);
- }
+ GD.PrintErr(" Details: ", detailMessage);
try
{
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs
index 729529d093..a17741ddeb 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs
@@ -1,17 +1,33 @@
using System;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
namespace Godot
{
public static partial class GD
{
- /// <summary>
- /// Fires when an unhandled exception occurs, regardless of project settings.
- /// </summary>
- public static event EventHandler<UnhandledExceptionArgs> UnhandledException;
-
- private static void OnUnhandledException(Exception e)
+ [UnmanagedCallersOnly]
+ internal static void OnCoreApiAssemblyLoaded(godot_bool isDebug)
{
- UnhandledException?.Invoke(null, new UnhandledExceptionArgs(e));
+ try
+ {
+ Dispatcher.InitializeDefaultGodotTaskScheduler();
+
+ if (isDebug.ToBool())
+ {
+ DebuggingUtils.InstallTraceListener();
+
+ AppDomain.CurrentDomain.UnhandledException += (_, e) =>
+ {
+ // Exception.ToString() includes the inner exception
+ ExceptionUtils.LogUnhandledException((Exception)e.ExceptionObject);
+ };
+ }
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ }
}
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs
deleted file mode 100644
index 50ae2eb112..0000000000
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs
+++ /dev/null
@@ -1,154 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace Godot
-{
- internal static class MarshalUtils
- {
- /// <summary>
- /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/>
- /// is <see cref="Collections.Array{T}"/>; otherwise returns <see langword="false"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static bool TypeIsGenericArray(Type type) =>
- type.GetGenericTypeDefinition() == typeof(Collections.Array<>);
-
- /// <summary>
- /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/>
- /// is <see cref="Collections.Dictionary{TKey, TValue}"/>; otherwise returns <see langword="false"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static bool TypeIsGenericDictionary(Type type) =>
- type.GetGenericTypeDefinition() == typeof(Collections.Dictionary<,>);
-
- /// <summary>
- /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/>
- /// is <see cref="List{T}"/>; otherwise returns <see langword="false"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static bool TypeIsSystemGenericList(Type type) =>
- type.GetGenericTypeDefinition() == typeof(List<>);
-
- /// <summary>
- /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/>
- /// is <see cref="Dictionary{TKey, TValue}"/>; otherwise returns <see langword="false"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static bool TypeIsSystemGenericDictionary(Type type) =>
- type.GetGenericTypeDefinition() == typeof(Dictionary<,>);
-
- /// <summary>
- /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/>
- /// is <see cref="IEnumerable{T}"/>; otherwise returns <see langword="false"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static bool TypeIsGenericIEnumerable(Type type) => type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
-
- /// <summary>
- /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/>
- /// is <see cref="ICollection{T}"/>; otherwise returns <see langword="false"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static bool TypeIsGenericICollection(Type type) => type.GetGenericTypeDefinition() == typeof(ICollection<>);
-
- /// <summary>
- /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/>
- /// is <see cref="IDictionary{TKey, TValue}"/>; otherwise returns <see langword="false"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static bool TypeIsGenericIDictionary(Type type) => type.GetGenericTypeDefinition() == typeof(IDictionary<,>);
-
- /// <summary>
- /// Returns <see langword="true"/> if the <see cref="FlagsAttribute"/> is applied to the given type.
- /// </summary>
- private static bool TypeHasFlagsAttribute(Type type) => type.IsDefined(typeof(FlagsAttribute), false);
-
- /// <summary>
- /// Returns the generic type definition of <paramref name="type"/>.
- /// </summary>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="type"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static void GetGenericTypeDefinition(Type type, out Type genericTypeDefinition)
- {
- genericTypeDefinition = type.GetGenericTypeDefinition();
- }
-
- /// <summary>
- /// Gets the element type for the given <paramref name="arrayType"/>.
- /// </summary>
- /// <param name="arrayType">Type for the generic array.</param>
- /// <param name="elementType">Element type for the generic array.</param>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="arrayType"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static void ArrayGetElementType(Type arrayType, out Type elementType)
- {
- elementType = arrayType.GetGenericArguments()[0];
- }
-
- /// <summary>
- /// Gets the key type and the value type for the given <paramref name="dictionaryType"/>.
- /// </summary>
- /// <param name="dictionaryType">The type for the generic dictionary.</param>
- /// <param name="keyType">Key type for the generic dictionary.</param>
- /// <param name="valueType">Value type for the generic dictionary.</param>
- /// <exception cref="InvalidOperationException">
- /// Thrown when the given <paramref name="dictionaryType"/> is not a generic type.
- /// That is, <see cref="Type.IsGenericType"/> returns <see langword="false"/>.
- /// </exception>
- private static void DictionaryGetKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
- {
- var genericArgs = dictionaryType.GetGenericArguments();
- keyType = genericArgs[0];
- valueType = genericArgs[1];
- }
-
- /// <summary>
- /// Constructs a new <see cref="Type"/> from <see cref="Collections.Array{T}"/>
- /// where the generic type for the elements is <paramref name="elemType"/>.
- /// </summary>
- /// <param name="elemType">Element type for the array.</param>
- /// <returns>The generic array type with the specified element type.</returns>
- private static Type MakeGenericArrayType(Type elemType)
- {
- return typeof(Collections.Array<>).MakeGenericType(elemType);
- }
-
- /// <summary>
- /// Constructs a new <see cref="Type"/> from <see cref="Collections.Dictionary{TKey, TValue}"/>
- /// where the generic type for the keys is <paramref name="keyType"/> and
- /// for the values is <paramref name="valueType"/>.
- /// </summary>
- /// <param name="keyType">Key type for the dictionary.</param>
- /// <param name="valueType">Key type for the dictionary.</param>
- /// <returns>The generic dictionary type with the specified key and value types.</returns>
- private static Type MakeGenericDictionaryType(Type keyType, Type valueType)
- {
- return typeof(Collections.Dictionary<,>).MakeGenericType(keyType, valueType);
- }
- }
-}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs
index 36b7d0f80f..41a0dd871c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
namespace Godot
@@ -759,9 +754,10 @@ namespace Godot
}
/// <summary>
- /// 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.
+ /// Returns the <paramref name="value"/> wrapped between <c>0</c> and the <paramref name="length"/>.
+ /// If the limit is reached, the next value the function returned is decreased to the <c>0</c> side
+ /// or increased to the <paramref name="length"/> side (like a triangle wave).
+ /// If <paramref name="length"/> is less than zero, it becomes positive.
/// </summary>
/// <param name="value">The value to pingpong.</param>
/// <param name="length">The maximum value of the function.</param>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs
index f15d01b34b..ea05c1547c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
namespace Godot
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/CustomUnsafe.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/CustomUnsafe.cs
new file mode 100644
index 0000000000..afef20a7f2
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/CustomUnsafe.cs
@@ -0,0 +1,313 @@
+using System.Runtime.CompilerServices;
+
+namespace Godot.NativeInterop;
+
+// Ref structs are not allowed as generic type parameters, so we can't use Unsafe.AsPointer<T>/AsRef<T>.
+// As a workaround we create our own overloads for our structs with some tricks under the hood.
+
+public static class CustomUnsafe
+{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_ref* AsPointer(ref godot_ref value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_ref* ReadOnlyRefAsPointer(in godot_ref value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_ref AsRef(godot_ref* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_ref AsRef(in godot_ref source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_variant_call_error* AsPointer(ref godot_variant_call_error value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_variant_call_error* ReadOnlyRefAsPointer(in godot_variant_call_error value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_variant_call_error AsRef(godot_variant_call_error* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_variant_call_error AsRef(in godot_variant_call_error source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_variant* AsPointer(ref godot_variant value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_variant* ReadOnlyRefAsPointer(in godot_variant value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_variant AsRef(godot_variant* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_variant AsRef(in godot_variant source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_string* AsPointer(ref godot_string value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_string* ReadOnlyRefAsPointer(in godot_string value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_string AsRef(godot_string* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_string AsRef(in godot_string source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_string_name* AsPointer(ref godot_string_name value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_string_name* ReadOnlyRefAsPointer(in godot_string_name value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_string_name AsRef(godot_string_name* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_string_name AsRef(in godot_string_name source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_node_path* AsPointer(ref godot_node_path value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_node_path* ReadOnlyRefAsPointer(in godot_node_path value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_node_path AsRef(godot_node_path* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_node_path AsRef(in godot_node_path source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_signal* AsPointer(ref godot_signal value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_signal* ReadOnlyRefAsPointer(in godot_signal value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_signal AsRef(godot_signal* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_signal AsRef(in godot_signal source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_callable* AsPointer(ref godot_callable value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_callable* ReadOnlyRefAsPointer(in godot_callable value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_callable AsRef(godot_callable* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_callable AsRef(in godot_callable source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_array* AsPointer(ref godot_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_array* ReadOnlyRefAsPointer(in godot_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_array AsRef(godot_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_array AsRef(in godot_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_dictionary* AsPointer(ref godot_dictionary value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_dictionary* ReadOnlyRefAsPointer(in godot_dictionary value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_dictionary AsRef(godot_dictionary* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_dictionary AsRef(in godot_dictionary source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_byte_array* AsPointer(ref godot_packed_byte_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_byte_array* ReadOnlyRefAsPointer(in godot_packed_byte_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_byte_array AsRef(godot_packed_byte_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_byte_array AsRef(in godot_packed_byte_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_int32_array* AsPointer(ref godot_packed_int32_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_int32_array* ReadOnlyRefAsPointer(in godot_packed_int32_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_int32_array AsRef(godot_packed_int32_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_int32_array AsRef(in godot_packed_int32_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_int64_array* AsPointer(ref godot_packed_int64_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_int64_array* ReadOnlyRefAsPointer(in godot_packed_int64_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_int64_array AsRef(godot_packed_int64_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_int64_array AsRef(in godot_packed_int64_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_float32_array* AsPointer(ref godot_packed_float32_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_float32_array* ReadOnlyRefAsPointer(in godot_packed_float32_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_float32_array AsRef(godot_packed_float32_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_float32_array AsRef(in godot_packed_float32_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_float64_array* AsPointer(ref godot_packed_float64_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_float64_array* ReadOnlyRefAsPointer(in godot_packed_float64_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_float64_array AsRef(godot_packed_float64_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_float64_array AsRef(in godot_packed_float64_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_string_array* AsPointer(ref godot_packed_string_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_string_array* ReadOnlyRefAsPointer(in godot_packed_string_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_string_array AsRef(godot_packed_string_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_string_array AsRef(in godot_packed_string_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_vector2_array* AsPointer(ref godot_packed_vector2_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_vector2_array* ReadOnlyRefAsPointer(in godot_packed_vector2_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_vector2_array AsRef(godot_packed_vector2_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_vector2_array AsRef(in godot_packed_vector2_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_vector3_array* AsPointer(ref godot_packed_vector3_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_vector3_array* ReadOnlyRefAsPointer(in godot_packed_vector3_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_vector3_array AsRef(godot_packed_vector3_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_vector3_array AsRef(in godot_packed_vector3_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_color_array* AsPointer(ref godot_packed_color_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_packed_color_array* ReadOnlyRefAsPointer(in godot_packed_color_array value)
+ => value.GetUnsafeAddress();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_color_array AsRef(godot_packed_color_array* source)
+ => ref *source;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ref godot_packed_color_array AsRef(in godot_packed_color_array source)
+ => ref *ReadOnlyRefAsPointer(in source);
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/ExceptionUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/ExceptionUtils.cs
new file mode 100644
index 0000000000..5a0ea2ba13
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/ExceptionUtils.cs
@@ -0,0 +1,139 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+
+#nullable enable
+
+namespace Godot.NativeInterop
+{
+ internal static class ExceptionUtils
+ {
+ public static void PushError(string message)
+ {
+ GD.PushError(message);
+ }
+
+ private static void OnExceptionLoggerException(Exception loggerException, Exception exceptionToLog)
+ {
+ try
+ {
+ // This better not throw
+ PushError(string.Concat("Exception thrown while trying to log another exception...",
+ "\n### Exception ###\n", exceptionToLog.ToString(),
+ "\n### Logger exception ###\n", loggerException.ToString()));
+ }
+ catch (Exception)
+ {
+ // Well, too bad...
+ }
+ }
+
+ private record struct StackInfoTuple(string? File, string Func, int Line);
+
+ private static void CollectExceptionInfo(Exception exception, List<StackInfoTuple> globalFrames,
+ StringBuilder excMsg)
+ {
+ if (excMsg.Length > 0)
+ excMsg.Append(" ---> ");
+ excMsg.Append(exception.GetType().FullName);
+ excMsg.Append(": ");
+ excMsg.Append(exception.Message);
+
+ var innerExc = exception.InnerException;
+
+ if (innerExc != null)
+ {
+ CollectExceptionInfo(innerExc, globalFrames, excMsg);
+ globalFrames.Add(new("", "--- End of inner exception stack trace ---", 0));
+ }
+
+ var stackTrace = new StackTrace(exception, fNeedFileInfo: true);
+
+ foreach (StackFrame frame in stackTrace.GetFrames())
+ {
+ DebuggingUtils.GetStackFrameMethodDecl(frame, out string methodDecl);
+ globalFrames.Add(new(frame.GetFileName(), methodDecl, frame.GetFileLineNumber()));
+ }
+ }
+
+ private static void SendToScriptDebugger(Exception e)
+ {
+ var globalFrames = new List<StackInfoTuple>();
+
+ var excMsg = new StringBuilder();
+
+ CollectExceptionInfo(e, globalFrames, excMsg);
+
+ string file = globalFrames.Count > 0 ? globalFrames[0].File ?? "" : "";
+ string func = globalFrames.Count > 0 ? globalFrames[0].Func : "";
+ int line = globalFrames.Count > 0 ? globalFrames[0].Line : 0;
+ string errorMsg = "Exception";
+
+ using godot_string nFile = Marshaling.ConvertStringToNative(file);
+ using godot_string nFunc = Marshaling.ConvertStringToNative(func);
+ using godot_string nErrorMsg = Marshaling.ConvertStringToNative(errorMsg);
+ using godot_string nExcMsg = Marshaling.ConvertStringToNative(excMsg.ToString());
+
+ using DebuggingUtils.godot_stack_info_vector stackInfoVector = default;
+
+ stackInfoVector.Resize(globalFrames.Count);
+
+ unsafe
+ {
+ for (int i = 0; i < globalFrames.Count; i++)
+ {
+ DebuggingUtils.godot_stack_info* stackInfo = &stackInfoVector.Elements[i];
+
+ var globalFrame = globalFrames[i];
+
+ // Assign directly to element in Vector. This way we don't need to worry
+ // about disposal if an exception is thrown. The Vector takes care of it.
+ stackInfo->File = Marshaling.ConvertStringToNative(globalFrame.File);
+ stackInfo->Func = Marshaling.ConvertStringToNative(globalFrame.Func);
+ stackInfo->Line = globalFrame.Line;
+ }
+
+ NativeFuncs.godotsharp_internal_script_debugger_send_error(nFunc, nFile, line,
+ nErrorMsg, nExcMsg, p_warning: godot_bool.False, stackInfoVector);
+ }
+ }
+
+ public static void LogException(Exception e)
+ {
+ try
+ {
+ if (NativeFuncs.godotsharp_internal_script_debugger_is_active())
+ {
+ SendToScriptDebugger(e);
+ }
+ else
+ {
+ GD.PushError(e.ToString());
+ }
+ }
+ catch (Exception unexpected)
+ {
+ OnExceptionLoggerException(unexpected, e);
+ }
+ }
+
+ public static void LogUnhandledException(Exception e)
+ {
+ try
+ {
+ if (NativeFuncs.godotsharp_internal_script_debugger_is_active())
+ {
+ SendToScriptDebugger(e);
+ }
+
+ // In this case, print it as well in addition to sending it to the script debugger
+ GD.PushError("Unhandled exception\n" + e);
+ }
+ catch (Exception unexpected)
+ {
+ OnExceptionLoggerException(unexpected, e);
+ }
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/GodotDllImportResolver.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/GodotDllImportResolver.cs
new file mode 100644
index 0000000000..5579992d2b
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/GodotDllImportResolver.cs
@@ -0,0 +1,59 @@
+using System;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+#nullable enable
+
+namespace Godot.NativeInterop
+{
+ public class GodotDllImportResolver
+ {
+ private IntPtr _internalHandle;
+
+ public GodotDllImportResolver(IntPtr internalHandle)
+ {
+ _internalHandle = internalHandle;
+ }
+
+ public IntPtr OnResolveDllImport(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
+ {
+ if (libraryName == "__Internal")
+ {
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ return Win32.GetModuleHandle(IntPtr.Zero);
+ }
+ else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
+ {
+ return _internalHandle;
+ }
+ else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
+ {
+ return MacOS.dlopen(IntPtr.Zero, MacOS.RTLD_LAZY);
+ }
+ }
+
+ return IntPtr.Zero;
+ }
+
+ // ReSharper disable InconsistentNaming
+ private static class MacOS
+ {
+ private const string SystemLibrary = "/usr/lib/libSystem.dylib";
+
+ public const int RTLD_LAZY = 1;
+
+ [DllImport(SystemLibrary)]
+ public static extern IntPtr dlopen(IntPtr path, int mode);
+ }
+
+ private static class Win32
+ {
+ private const string SystemLibrary = "Kernel32.dll";
+
+ [DllImport(SystemLibrary)]
+ public static extern IntPtr GetModuleHandle(IntPtr lpModuleName);
+ }
+ // ReSharper restore InconsistentNaming
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropStructs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropStructs.cs
new file mode 100644
index 0000000000..44806e8ecf
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropStructs.cs
@@ -0,0 +1,1091 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace Godot.NativeInterop
+{
+ // NOTES:
+ // ref structs cannot implement interfaces, but they still work in `using` directives if they declare Dispose()
+
+ public static class GodotBoolExtensions
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe godot_bool ToGodotBool(this bool @bool)
+ {
+ return *(godot_bool*)&@bool;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe bool ToBool(this godot_bool godotBool)
+ {
+ return *(bool*)&godotBool;
+ }
+ }
+
+ // Apparently a struct with a byte is not blittable? It crashes when calling a UnmanagedCallersOnly function ptr.
+ // ReSharper disable once InconsistentNaming
+ public enum godot_bool : byte
+ {
+ True = 1,
+ False = 0
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_ref
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_ref* GetUnsafeAddress()
+ => (godot_ref*)Unsafe.AsPointer(ref Unsafe.AsRef(in _reference));
+
+ private IntPtr _reference;
+
+ public void Dispose()
+ {
+ if (_reference == IntPtr.Zero)
+ return;
+ NativeFuncs.godotsharp_ref_destroy(ref this);
+ _reference = IntPtr.Zero;
+ }
+
+ public readonly IntPtr Reference
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _reference;
+ }
+
+ public readonly bool IsNull
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _reference == IntPtr.Zero;
+ }
+ }
+
+ [SuppressMessage("ReSharper", "InconsistentNaming")]
+ public enum godot_variant_call_error_error
+ {
+ GODOT_CALL_ERROR_CALL_OK = 0,
+ 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,
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_variant_call_error
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_variant_call_error* GetUnsafeAddress()
+ => (godot_variant_call_error*)Unsafe.AsPointer(ref Unsafe.AsRef(in error));
+
+ private godot_variant_call_error_error error;
+ private int argument;
+ private int expected;
+
+ public godot_variant_call_error_error Error
+ {
+ readonly get => error;
+ set => error = value;
+ }
+
+ public int Argument
+ {
+ readonly get => argument;
+ set => argument = value;
+ }
+
+ public Godot.Variant.Type Expected
+ {
+ readonly get => (Godot.Variant.Type)expected;
+ set => expected = (int)value;
+ }
+ }
+
+ [StructLayout(LayoutKind.Explicit)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_variant
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_variant* GetUnsafeAddress()
+ => (godot_variant*)Unsafe.AsPointer(ref Unsafe.AsRef(in _typeField));
+
+ // Variant.Type is generated as an enum of type long, so we can't use for the field as it must only take 32-bits.
+ [FieldOffset(0)] private int _typeField;
+
+ // There's padding here
+
+ [FieldOffset(8)] private godot_variant_data _data;
+
+ [StructLayout(LayoutKind.Explicit)]
+ // ReSharper disable once InconsistentNaming
+ private unsafe ref struct godot_variant_data
+ {
+ [FieldOffset(0)] public godot_bool _bool;
+ [FieldOffset(0)] public long _int;
+ [FieldOffset(0)] public double _float;
+ [FieldOffset(0)] public Transform2D* _transform2D;
+ [FieldOffset(0)] public AABB* _aabb;
+ [FieldOffset(0)] public Basis* _basis;
+ [FieldOffset(0)] public Transform3D* _transform3D;
+ [FieldOffset(0)] public Vector4* _vector4;
+ [FieldOffset(0)] public Vector4i* _vector4i;
+ [FieldOffset(0)] public Projection* _projection;
+ [FieldOffset(0)] private godot_variant_data_mem _mem;
+
+ // The following fields are not in the C++ union, but this is how they're stored in _mem.
+ [FieldOffset(0)] public godot_string_name _m_string_name;
+ [FieldOffset(0)] public godot_string _m_string;
+ [FieldOffset(0)] public Vector3 _m_vector3;
+ [FieldOffset(0)] public Vector3i _m_vector3i;
+ [FieldOffset(0)] public Vector2 _m_vector2;
+ [FieldOffset(0)] public Vector2i _m_vector2i;
+ [FieldOffset(0)] public Rect2 _m_rect2;
+ [FieldOffset(0)] public Rect2i _m_rect2i;
+ [FieldOffset(0)] public Plane _m_plane;
+ [FieldOffset(0)] public Quaternion _m_quaternion;
+ [FieldOffset(0)] public Color _m_color;
+ [FieldOffset(0)] public godot_node_path _m_node_path;
+ [FieldOffset(0)] public RID _m_rid;
+ [FieldOffset(0)] public godot_variant_obj_data _m_obj_data;
+ [FieldOffset(0)] public godot_callable _m_callable;
+ [FieldOffset(0)] public godot_signal _m_signal;
+ [FieldOffset(0)] public godot_dictionary _m_dictionary;
+ [FieldOffset(0)] public godot_array _m_array;
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public struct godot_variant_obj_data
+ {
+ public ulong id;
+ public IntPtr obj;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public struct godot_variant_data_mem
+ {
+#pragma warning disable 169
+ private real_t _mem0;
+ private real_t _mem1;
+ private real_t _mem2;
+ private real_t _mem3;
+#pragma warning restore 169
+ }
+ }
+
+ public Variant.Type Type
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => (Variant.Type)_typeField;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _typeField = (int)value;
+ }
+
+ public godot_bool Bool
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._bool;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._bool = value;
+ }
+
+ public long Int
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._int;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._int = value;
+ }
+
+ public double Float
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._float;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._float = value;
+ }
+
+ public readonly unsafe Transform2D* Transform2D
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._transform2D;
+ }
+
+ public readonly unsafe AABB* AABB
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._aabb;
+ }
+
+ public readonly unsafe Basis* Basis
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._basis;
+ }
+
+ public readonly unsafe Transform3D* Transform3D
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._transform3D;
+ }
+
+ public readonly unsafe Vector4* Vector4
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._vector4;
+ }
+
+ public readonly unsafe Vector4i* Vector4i
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._vector4i;
+ }
+
+ public readonly unsafe Projection* Projection
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._projection;
+ }
+
+ public godot_string_name StringName
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_string_name;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_string_name = value;
+ }
+
+ public godot_string String
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_string;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_string = value;
+ }
+
+ public Vector3 Vector3
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_vector3;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_vector3 = value;
+ }
+
+ public Vector3i Vector3i
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_vector3i;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_vector3i = value;
+ }
+
+ public Vector2 Vector2
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_vector2;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_vector2 = value;
+ }
+
+ public Vector2i Vector2i
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_vector2i;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_vector2i = value;
+ }
+
+ public Rect2 Rect2
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_rect2;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_rect2 = value;
+ }
+
+ public Rect2i Rect2i
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_rect2i;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_rect2i = value;
+ }
+
+ public Plane Plane
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_plane;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_plane = value;
+ }
+
+ public Quaternion Quaternion
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_quaternion;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_quaternion = value;
+ }
+
+ public Color Color
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_color;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_color = value;
+ }
+
+ public godot_node_path NodePath
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_node_path;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_node_path = value;
+ }
+
+ public RID RID
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_rid;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_rid = value;
+ }
+
+ public godot_callable Callable
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_callable;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_callable = value;
+ }
+
+ public godot_signal Signal
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_signal;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_signal = value;
+ }
+
+ public godot_dictionary Dictionary
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_dictionary;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_dictionary = value;
+ }
+
+ public godot_array Array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ readonly get => _data._m_array;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ set => _data._m_array = value;
+ }
+
+ public readonly IntPtr Object
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data._m_obj_data.obj;
+ }
+
+ public void Dispose()
+ {
+ switch (Type)
+ {
+ case Variant.Type.Nil:
+ case Variant.Type.Bool:
+ case Variant.Type.Int:
+ case Variant.Type.Float:
+ case Variant.Type.Vector2:
+ case Variant.Type.Vector2i:
+ case Variant.Type.Rect2:
+ case Variant.Type.Rect2i:
+ case Variant.Type.Vector3:
+ case Variant.Type.Vector3i:
+ case Variant.Type.Plane:
+ case Variant.Type.Quaternion:
+ case Variant.Type.Color:
+ case Variant.Type.Rid:
+ return;
+ }
+
+ NativeFuncs.godotsharp_variant_destroy(ref this);
+ Type = Variant.Type.Nil;
+ }
+
+ [StructLayout(LayoutKind.Explicit)]
+ // ReSharper disable once InconsistentNaming
+ internal struct movable
+ {
+ // Variant.Type is generated as an enum of type long, so we can't use for the field as it must only take 32-bits.
+ [FieldOffset(0)] private int _typeField;
+
+ // There's padding here
+
+ [FieldOffset(8)] private godot_variant_data.godot_variant_data_mem _data;
+
+ public static unsafe explicit operator movable(in godot_variant value)
+ => *(movable*)CustomUnsafe.AsPointer(ref CustomUnsafe.AsRef(value));
+
+ public static unsafe explicit operator godot_variant(movable value)
+ => *(godot_variant*)Unsafe.AsPointer(ref value);
+
+ public unsafe ref godot_variant DangerousSelfRef =>
+ ref CustomUnsafe.AsRef((godot_variant*)Unsafe.AsPointer(ref this));
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_string
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_string* GetUnsafeAddress()
+ => (godot_string*)Unsafe.AsPointer(ref Unsafe.AsRef(in _ptr));
+
+ private IntPtr _ptr;
+
+ public void Dispose()
+ {
+ if (_ptr == IntPtr.Zero)
+ return;
+ NativeFuncs.godotsharp_string_destroy(ref this);
+ _ptr = IntPtr.Zero;
+ }
+
+ public readonly IntPtr Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ // Size including the null termination character
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != IntPtr.Zero ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_string_name
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_string_name* GetUnsafeAddress()
+ => (godot_string_name*)Unsafe.AsPointer(ref Unsafe.AsRef(in _data));
+
+ private IntPtr _data;
+
+ public void Dispose()
+ {
+ if (_data == IntPtr.Zero)
+ return;
+ NativeFuncs.godotsharp_string_name_destroy(ref this);
+ _data = IntPtr.Zero;
+ }
+
+ public readonly bool IsAllocated
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data != IntPtr.Zero;
+ }
+
+ public readonly bool IsEmpty
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ // This is all that's needed to check if it's empty. Equivalent to `== StringName()` in C++.
+ get => _data == IntPtr.Zero;
+ }
+
+ public static bool operator ==(godot_string_name left, godot_string_name right)
+ {
+ return left._data == right._data;
+ }
+
+ public static bool operator !=(godot_string_name left, godot_string_name right)
+ {
+ return !(left == right);
+ }
+
+ public bool Equals(godot_string_name other)
+ {
+ return _data == other._data;
+ }
+
+ public override bool Equals(object obj)
+ {
+ return obj is StringName s && s.Equals(this);
+ }
+
+ public override int GetHashCode()
+ {
+ return _data.GetHashCode();
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ internal struct movable
+ {
+ private IntPtr _data;
+
+ public static unsafe explicit operator movable(in godot_string_name value)
+ => *(movable*)CustomUnsafe.AsPointer(ref CustomUnsafe.AsRef(value));
+
+ public static unsafe explicit operator godot_string_name(movable value)
+ => *(godot_string_name*)Unsafe.AsPointer(ref value);
+
+ public unsafe ref godot_string_name DangerousSelfRef =>
+ ref CustomUnsafe.AsRef((godot_string_name*)Unsafe.AsPointer(ref this));
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_node_path
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_node_path* GetUnsafeAddress()
+ => (godot_node_path*)Unsafe.AsPointer(ref Unsafe.AsRef(in _data));
+
+ private IntPtr _data;
+
+ public void Dispose()
+ {
+ if (_data == IntPtr.Zero)
+ return;
+ NativeFuncs.godotsharp_node_path_destroy(ref this);
+ _data = IntPtr.Zero;
+ }
+
+ public readonly bool IsAllocated
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _data != IntPtr.Zero;
+ }
+
+ public readonly bool IsEmpty
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ // This is all that's needed to check if it's empty. It's what the `is_empty()` C++ method does.
+ get => _data == IntPtr.Zero;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ internal struct movable
+ {
+ private IntPtr _data;
+
+ public static unsafe explicit operator movable(in godot_node_path value)
+ => *(movable*)CustomUnsafe.AsPointer(ref CustomUnsafe.AsRef(value));
+
+ public static unsafe explicit operator godot_node_path(movable value)
+ => *(godot_node_path*)Unsafe.AsPointer(ref value);
+
+ public unsafe ref godot_node_path DangerousSelfRef =>
+ ref CustomUnsafe.AsRef((godot_node_path*)Unsafe.AsPointer(ref this));
+ }
+ }
+
+ [StructLayout(LayoutKind.Explicit)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_signal
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_signal* GetUnsafeAddress()
+ => (godot_signal*)Unsafe.AsPointer(ref Unsafe.AsRef(in _getUnsafeAddressHelper));
+
+ [FieldOffset(0)] private byte _getUnsafeAddressHelper;
+
+ [FieldOffset(0)] private godot_string_name _name;
+
+ // There's padding here on 32-bit
+
+ [FieldOffset(8)] private ulong _objectId;
+
+ public godot_signal(godot_string_name name, ulong objectId) : this()
+ {
+ _name = name;
+ _objectId = objectId;
+ }
+
+ public godot_string_name Name
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _name;
+ }
+
+ public ulong ObjectId
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _objectId;
+ }
+
+ public void Dispose()
+ {
+ if (!_name.IsAllocated)
+ return;
+ NativeFuncs.godotsharp_signal_destroy(ref this);
+ _name = default;
+ }
+ }
+
+ [StructLayout(LayoutKind.Explicit)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_callable
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_callable* GetUnsafeAddress()
+ => (godot_callable*)Unsafe.AsPointer(ref Unsafe.AsRef(in _getUnsafeAddressHelper));
+
+ [FieldOffset(0)] private byte _getUnsafeAddressHelper;
+
+ [FieldOffset(0)] private godot_string_name _method;
+
+ // There's padding here on 32-bit
+
+ // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
+ [FieldOffset(8)] private ulong _objectId;
+ [FieldOffset(8)] private IntPtr _custom;
+
+ public godot_callable(godot_string_name method, ulong objectId) : this()
+ {
+ _method = method;
+ _objectId = objectId;
+ }
+
+ public void Dispose()
+ {
+ // _custom needs freeing as well
+ if (!_method.IsAllocated && _custom == IntPtr.Zero)
+ return;
+ NativeFuncs.godotsharp_callable_destroy(ref this);
+ _method = default;
+ _custom = IntPtr.Zero;
+ }
+ }
+
+ // A correctly constructed value needs to call the native default constructor to allocate `_p`.
+ // Don't pass a C# default constructed `godot_array` to native code, unless it's going to
+ // be re-assigned a new value (the copy constructor checks if `_p` is null so that's fine).
+ [StructLayout(LayoutKind.Explicit)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_array* GetUnsafeAddress()
+ => (godot_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _getUnsafeAddressHelper));
+
+ [FieldOffset(0)] private byte _getUnsafeAddressHelper;
+
+ [FieldOffset(0)] private unsafe ArrayPrivate* _p;
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ArrayPrivate
+ {
+ private uint _safeRefCount;
+
+ public VariantVector _arrayVector;
+ // There are more fields here, but we don't care as we never store this in C#
+
+ public readonly int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _arrayVector.Size;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct VariantVector
+ {
+ private IntPtr _writeProxy;
+ public unsafe godot_variant* _ptr;
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ public readonly unsafe godot_variant* Elements
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _p->_arrayVector._ptr;
+ }
+
+ public readonly unsafe bool IsAllocated
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _p != null;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _p != null ? _p->Size : 0;
+ }
+
+ public unsafe void Dispose()
+ {
+ if (_p == null)
+ return;
+ NativeFuncs.godotsharp_array_destroy(ref this);
+ _p = null;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ internal struct movable
+ {
+ private unsafe ArrayPrivate* _p;
+
+ public static unsafe explicit operator movable(in godot_array value)
+ => *(movable*)CustomUnsafe.AsPointer(ref CustomUnsafe.AsRef(value));
+
+ public static unsafe explicit operator godot_array(movable value)
+ => *(godot_array*)Unsafe.AsPointer(ref value);
+
+ public unsafe ref godot_array DangerousSelfRef =>
+ ref CustomUnsafe.AsRef((godot_array*)Unsafe.AsPointer(ref this));
+ }
+ }
+
+ // IMPORTANT:
+ // A correctly constructed value needs to call the native default constructor to allocate `_p`.
+ // Don't pass a C# default constructed `godot_dictionary` to native code, unless it's going to
+ // be re-assigned a new value (the copy constructor checks if `_p` is null so that's fine).
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_dictionary
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_dictionary* GetUnsafeAddress()
+ => (godot_dictionary*)Unsafe.AsPointer(ref Unsafe.AsRef(in _p));
+
+ private IntPtr _p;
+
+ public readonly bool IsAllocated
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _p != IntPtr.Zero;
+ }
+
+ public void Dispose()
+ {
+ if (_p == IntPtr.Zero)
+ return;
+ NativeFuncs.godotsharp_dictionary_destroy(ref this);
+ _p = IntPtr.Zero;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ internal struct movable
+ {
+ private IntPtr _p;
+
+ public static unsafe explicit operator movable(in godot_dictionary value)
+ => *(movable*)CustomUnsafe.AsPointer(ref CustomUnsafe.AsRef(value));
+
+ public static unsafe explicit operator godot_dictionary(movable value)
+ => *(godot_dictionary*)Unsafe.AsPointer(ref value);
+
+ public unsafe ref godot_dictionary DangerousSelfRef =>
+ ref CustomUnsafe.AsRef((godot_dictionary*)Unsafe.AsPointer(ref this));
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_byte_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_byte_array* GetUnsafeAddress()
+ => (godot_packed_byte_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe byte* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_byte_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe byte* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_int32_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_int32_array* GetUnsafeAddress()
+ => (godot_packed_int32_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe int* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_int32_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe int* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *(_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_int64_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_int64_array* GetUnsafeAddress()
+ => (godot_packed_int64_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe long* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_int64_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe long* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_float32_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_float32_array* GetUnsafeAddress()
+ => (godot_packed_float32_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe float* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_float32_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe float* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_float64_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_float64_array* GetUnsafeAddress()
+ => (godot_packed_float64_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe double* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_float64_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe double* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_string_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_string_array* GetUnsafeAddress()
+ => (godot_packed_string_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe godot_string* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_string_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe godot_string* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_vector2_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_vector2_array* GetUnsafeAddress()
+ => (godot_packed_vector2_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe Vector2* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_vector2_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe Vector2* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_vector3_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_vector3_array* GetUnsafeAddress()
+ => (godot_packed_vector3_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe Vector3* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_vector3_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe Vector3* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ // ReSharper disable once InconsistentNaming
+ public ref struct godot_packed_color_array
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal readonly unsafe godot_packed_color_array* GetUnsafeAddress()
+ => (godot_packed_color_array*)Unsafe.AsPointer(ref Unsafe.AsRef(in _writeProxy));
+
+ private IntPtr _writeProxy;
+ private unsafe Color* _ptr;
+
+ public unsafe void Dispose()
+ {
+ if (_ptr == null)
+ return;
+ NativeFuncs.godotsharp_packed_color_array_destroy(ref this);
+ _ptr = null;
+ }
+
+ public readonly unsafe Color* Buffer
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr;
+ }
+
+ public readonly unsafe int Size
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => _ptr != null ? *((int*)_ptr - 1) : 0;
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropUtils.cs
new file mode 100644
index 0000000000..82f1c04d40
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/InteropUtils.cs
@@ -0,0 +1,96 @@
+using System;
+using System.Runtime.InteropServices;
+using Godot.Bridge;
+
+// ReSharper disable InconsistentNaming
+
+namespace Godot.NativeInterop
+{
+ internal static class InteropUtils
+ {
+ public static Object UnmanagedGetManaged(IntPtr unmanaged)
+ {
+ // The native pointer may be null
+ if (unmanaged == IntPtr.Zero)
+ return null;
+
+ IntPtr gcHandlePtr;
+ godot_bool hasCsScriptInstance;
+
+ // First try to get the tied managed instance from a CSharpInstance script instance
+
+ gcHandlePtr = NativeFuncs.godotsharp_internal_unmanaged_get_script_instance_managed(
+ unmanaged, out hasCsScriptInstance);
+
+ if (gcHandlePtr != IntPtr.Zero)
+ return (Object)GCHandle.FromIntPtr(gcHandlePtr).Target;
+
+ // Otherwise, if the object has a CSharpInstance script instance, return null
+
+ if (hasCsScriptInstance.ToBool())
+ return null;
+
+ // If it doesn't have a CSharpInstance script instance, try with native instance bindings
+
+ gcHandlePtr = NativeFuncs.godotsharp_internal_unmanaged_get_instance_binding_managed(unmanaged);
+
+ object target = gcHandlePtr != IntPtr.Zero ? GCHandle.FromIntPtr(gcHandlePtr).Target : null;
+
+ if (target != null)
+ return (Object)target;
+
+ // If the native instance binding GC handle target was collected, create a new one
+
+ gcHandlePtr = NativeFuncs.godotsharp_internal_unmanaged_instance_binding_create_managed(
+ unmanaged, gcHandlePtr);
+
+ return gcHandlePtr != IntPtr.Zero ? (Object)GCHandle.FromIntPtr(gcHandlePtr).Target : null;
+ }
+
+ public static void TieManagedToUnmanaged(Object managed, IntPtr unmanaged,
+ StringName nativeName, bool refCounted, Type type, Type nativeType)
+ {
+ var gcHandle = refCounted ?
+ CustomGCHandle.AllocWeak(managed) :
+ CustomGCHandle.AllocStrong(managed, type);
+
+ if (type == nativeType)
+ {
+ var nativeNameSelf = (godot_string_name)nativeName.NativeValue;
+ NativeFuncs.godotsharp_internal_tie_native_managed_to_unmanaged(
+ GCHandle.ToIntPtr(gcHandle), unmanaged, nativeNameSelf, refCounted.ToGodotBool());
+ }
+ else
+ {
+ unsafe
+ {
+ // We don't dispose `script` ourselves here.
+ // `tie_user_managed_to_unmanaged` does it for us to avoid another P/Invoke call.
+ godot_ref script;
+ ScriptManagerBridge.GetOrLoadOrCreateScriptForType(type, &script);
+
+ // IMPORTANT: This must be called after GetOrCreateScriptBridgeForType
+ NativeFuncs.godotsharp_internal_tie_user_managed_to_unmanaged(
+ GCHandle.ToIntPtr(gcHandle), unmanaged, &script, refCounted.ToGodotBool());
+ }
+ }
+ }
+
+ public static void TieManagedToUnmanagedWithPreSetup(Object managed, IntPtr unmanaged,
+ Type type, Type nativeType)
+ {
+ if (type == nativeType)
+ return;
+
+ var strongGCHandle = CustomGCHandle.AllocStrong(managed);
+ NativeFuncs.godotsharp_internal_tie_managed_to_unmanaged_with_pre_setup(
+ GCHandle.ToIntPtr(strongGCHandle), unmanaged);
+ }
+
+ public static Object EngineGetSingleton(string name)
+ {
+ using godot_string src = Marshaling.ConvertStringToNative(name);
+ return UnmanagedGetManaged(NativeFuncs.godotsharp_engine_get_singleton(src));
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs
new file mode 100644
index 0000000000..eee19aea46
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs
@@ -0,0 +1,1092 @@
+using System;
+using System.Runtime.InteropServices;
+
+// ReSharper disable InconsistentNaming
+
+// We want to use full name qualifiers here even if redundant for clarity
+// ReSharper disable RedundantNameQualifier
+
+#nullable enable
+
+namespace Godot.NativeInterop
+{
+ public static class Marshaling
+ {
+ internal static Variant.Type ConvertManagedTypeToVariantType(Type type, out bool r_nil_is_variant)
+ {
+ r_nil_is_variant = false;
+
+ switch (Type.GetTypeCode(type))
+ {
+ case TypeCode.Boolean:
+ return Variant.Type.Bool;
+ case TypeCode.Char:
+ return Variant.Type.Int;
+ case TypeCode.SByte:
+ return Variant.Type.Int;
+ case TypeCode.Int16:
+ return Variant.Type.Int;
+ case TypeCode.Int32:
+ return Variant.Type.Int;
+ case TypeCode.Int64:
+ return Variant.Type.Int;
+ case TypeCode.Byte:
+ return Variant.Type.Int;
+ case TypeCode.UInt16:
+ return Variant.Type.Int;
+ case TypeCode.UInt32:
+ return Variant.Type.Int;
+ case TypeCode.UInt64:
+ return Variant.Type.Int;
+ case TypeCode.Single:
+ return Variant.Type.Float;
+ case TypeCode.Double:
+ return Variant.Type.Float;
+ case TypeCode.String:
+ return Variant.Type.String;
+ default:
+ {
+ if (type == typeof(Vector2))
+ return Variant.Type.Vector2;
+
+ if (type == typeof(Vector2i))
+ return Variant.Type.Vector2i;
+
+ if (type == typeof(Rect2))
+ return Variant.Type.Rect2;
+
+ if (type == typeof(Rect2i))
+ return Variant.Type.Rect2i;
+
+ if (type == typeof(Transform2D))
+ return Variant.Type.Transform2d;
+
+ if (type == typeof(Vector3))
+ return Variant.Type.Vector3;
+
+ if (type == typeof(Vector3i))
+ return Variant.Type.Vector3i;
+
+ if (type == typeof(Vector4))
+ return Variant.Type.Vector4;
+
+ if (type == typeof(Vector4i))
+ return Variant.Type.Vector4i;
+
+ if (type == typeof(Basis))
+ return Variant.Type.Basis;
+
+ if (type == typeof(Quaternion))
+ return Variant.Type.Quaternion;
+
+ if (type == typeof(Transform3D))
+ return Variant.Type.Transform3d;
+
+ if (type == typeof(Projection))
+ return Variant.Type.Projection;
+
+ if (type == typeof(AABB))
+ return Variant.Type.Aabb;
+
+ if (type == typeof(Color))
+ return Variant.Type.Color;
+
+ if (type == typeof(Plane))
+ return Variant.Type.Plane;
+
+ if (type == typeof(Callable))
+ return Variant.Type.Callable;
+
+ if (type == typeof(SignalInfo))
+ return Variant.Type.Signal;
+
+ if (type.IsEnum)
+ return Variant.Type.Int;
+
+ if (type.IsArray || type.IsSZArray)
+ {
+ if (type == typeof(byte[]))
+ return Variant.Type.PackedByteArray;
+
+ if (type == typeof(int[]))
+ return Variant.Type.PackedInt32Array;
+
+ if (type == typeof(long[]))
+ return Variant.Type.PackedInt64Array;
+
+ if (type == typeof(float[]))
+ return Variant.Type.PackedFloat32Array;
+
+ if (type == typeof(double[]))
+ return Variant.Type.PackedFloat64Array;
+
+ if (type == typeof(string[]))
+ return Variant.Type.PackedStringArray;
+
+ if (type == typeof(Vector2[]))
+ return Variant.Type.PackedVector2Array;
+
+ if (type == typeof(Vector3[]))
+ return Variant.Type.PackedVector3Array;
+
+ if (type == typeof(Color[]))
+ return Variant.Type.PackedColorArray;
+
+ if (type == typeof(StringName[]))
+ return Variant.Type.Array;
+
+ if (type == typeof(NodePath[]))
+ return Variant.Type.Array;
+
+ if (type == typeof(RID[]))
+ return Variant.Type.Array;
+
+ if (typeof(Godot.Object[]).IsAssignableFrom(type))
+ return Variant.Type.Array;
+ }
+ else if (type.IsGenericType)
+ {
+ if (typeof(Godot.Object).IsAssignableFrom(type))
+ return Variant.Type.Object;
+ }
+ else if (type == typeof(Variant))
+ {
+ r_nil_is_variant = true;
+ return Variant.Type.Nil;
+ }
+ else
+ {
+ if (typeof(Godot.Object).IsAssignableFrom(type))
+ return Variant.Type.Object;
+
+ if (typeof(StringName) == type)
+ return Variant.Type.StringName;
+
+ if (typeof(NodePath) == type)
+ return Variant.Type.NodePath;
+
+ if (typeof(RID) == type)
+ return Variant.Type.Rid;
+
+ if (typeof(Collections.Dictionary) == type)
+ return Variant.Type.Dictionary;
+
+ if (typeof(Collections.Array) == type)
+ return Variant.Type.Array;
+ }
+
+ break;
+ }
+ }
+
+ // Unknown
+ return Variant.Type.Nil;
+ }
+
+ /* TODO: Reflection and type checking each time is slow. This will be replaced with source generators. */
+ public static godot_variant ConvertManagedObjectToVariant(object? p_obj)
+ {
+ if (p_obj == null)
+ return new godot_variant();
+
+ switch (p_obj)
+ {
+ case bool @bool:
+ return VariantUtils.CreateFromBool(@bool);
+ case char @char:
+ return VariantUtils.CreateFromInt(@char);
+ case sbyte @int8:
+ return VariantUtils.CreateFromInt(@int8);
+ case short @int16:
+ return VariantUtils.CreateFromInt(@int16);
+ case int @int32:
+ return VariantUtils.CreateFromInt(@int32);
+ case long @int64:
+ return VariantUtils.CreateFromInt(@int64);
+ case byte @uint8:
+ return VariantUtils.CreateFromInt(@uint8);
+ case ushort @uint16:
+ return VariantUtils.CreateFromInt(@uint16);
+ case uint @uint32:
+ return VariantUtils.CreateFromInt(@uint32);
+ case ulong @uint64:
+ return VariantUtils.CreateFromInt(@uint64);
+ case float @float:
+ return VariantUtils.CreateFromFloat(@float);
+ case double @double:
+ return VariantUtils.CreateFromFloat(@double);
+ case Vector2 @vector2:
+ return VariantUtils.CreateFromVector2(@vector2);
+ case Vector2i @vector2i:
+ return VariantUtils.CreateFromVector2i(@vector2i);
+ case Rect2 @rect2:
+ return VariantUtils.CreateFromRect2(@rect2);
+ case Rect2i @rect2i:
+ return VariantUtils.CreateFromRect2i(@rect2i);
+ case Transform2D @transform2D:
+ return VariantUtils.CreateFromTransform2D(@transform2D);
+ case Vector3 @vector3:
+ return VariantUtils.CreateFromVector3(@vector3);
+ case Vector3i @vector3i:
+ return VariantUtils.CreateFromVector3i(@vector3i);
+ case Vector4 @vector4:
+ return VariantUtils.CreateFromVector4(@vector4);
+ case Vector4i @vector4i:
+ return VariantUtils.CreateFromVector4i(@vector4i);
+ case Basis @basis:
+ return VariantUtils.CreateFromBasis(@basis);
+ case Quaternion @quaternion:
+ return VariantUtils.CreateFromQuaternion(@quaternion);
+ case Transform3D @transform3d:
+ return VariantUtils.CreateFromTransform3D(@transform3d);
+ case Projection @projection:
+ return VariantUtils.CreateFromProjection(@projection);
+ case AABB @aabb:
+ return VariantUtils.CreateFromAABB(@aabb);
+ case Color @color:
+ return VariantUtils.CreateFromColor(@color);
+ case Plane @plane:
+ return VariantUtils.CreateFromPlane(@plane);
+ case Callable @callable:
+ return VariantUtils.CreateFromCallable(@callable);
+ case SignalInfo @signalInfo:
+ return VariantUtils.CreateFromSignalInfo(@signalInfo);
+ case Enum @enum:
+ return VariantUtils.CreateFromInt(Convert.ToInt64(@enum));
+ case string @string:
+ return VariantUtils.CreateFromString(@string);
+ case byte[] byteArray:
+ return VariantUtils.CreateFromPackedByteArray(byteArray);
+ case int[] int32Array:
+ return VariantUtils.CreateFromPackedInt32Array(int32Array);
+ case long[] int64Array:
+ return VariantUtils.CreateFromPackedInt64Array(int64Array);
+ case float[] floatArray:
+ return VariantUtils.CreateFromPackedFloat32Array(floatArray);
+ case double[] doubleArray:
+ return VariantUtils.CreateFromPackedFloat64Array(doubleArray);
+ case string[] stringArray:
+ return VariantUtils.CreateFromPackedStringArray(stringArray);
+ case Vector2[] vector2Array:
+ return VariantUtils.CreateFromPackedVector2Array(vector2Array);
+ case Vector3[] vector3Array:
+ return VariantUtils.CreateFromPackedVector3Array(vector3Array);
+ case Color[] colorArray:
+ return VariantUtils.CreateFromPackedColorArray(colorArray);
+ case StringName[] stringNameArray:
+ return VariantUtils.CreateFromSystemArrayOfStringName(stringNameArray);
+ case NodePath[] nodePathArray:
+ return VariantUtils.CreateFromSystemArrayOfNodePath(nodePathArray);
+ case RID[] ridArray:
+ return VariantUtils.CreateFromSystemArrayOfRID(ridArray);
+ case Godot.Object[] godotObjectArray:
+ return VariantUtils.CreateFromSystemArrayOfGodotObject(godotObjectArray);
+ case Godot.Object godotObject:
+ return VariantUtils.CreateFromGodotObject(godotObject);
+ case StringName stringName:
+ return VariantUtils.CreateFromStringName(stringName);
+ case NodePath nodePath:
+ return VariantUtils.CreateFromNodePath(nodePath);
+ case RID rid:
+ return VariantUtils.CreateFromRID(rid);
+ case Collections.Dictionary godotDictionary:
+ return VariantUtils.CreateFromDictionary(godotDictionary);
+ case Collections.Array godotArray:
+ return VariantUtils.CreateFromArray(godotArray);
+ case Variant variant:
+ return NativeFuncs.godotsharp_variant_new_copy((godot_variant)variant.NativeVar);
+ }
+
+ GD.PushError("Attempted to convert an unmarshallable managed type to Variant. Name: '" +
+ p_obj.GetType().FullName + ".");
+ return new godot_variant();
+ }
+
+ public static object? ConvertVariantToManagedObjectOfType(in godot_variant p_var, Type type)
+ {
+ // This function is only needed to set the value of properties. Fields have their own implementation, set_value_from_variant.
+ switch (Type.GetTypeCode(type))
+ {
+ case TypeCode.Boolean:
+ return VariantUtils.ConvertToBool(p_var);
+ case TypeCode.Char:
+ return VariantUtils.ConvertToChar(p_var);
+ case TypeCode.SByte:
+ return VariantUtils.ConvertToInt8(p_var);
+ case TypeCode.Int16:
+ return VariantUtils.ConvertToInt16(p_var);
+ case TypeCode.Int32:
+ return VariantUtils.ConvertToInt32(p_var);
+ case TypeCode.Int64:
+ return VariantUtils.ConvertToInt64(p_var);
+ case TypeCode.Byte:
+ return VariantUtils.ConvertToUInt8(p_var);
+ case TypeCode.UInt16:
+ return VariantUtils.ConvertToUInt16(p_var);
+ case TypeCode.UInt32:
+ return VariantUtils.ConvertToUInt32(p_var);
+ case TypeCode.UInt64:
+ return VariantUtils.ConvertToUInt64(p_var);
+ case TypeCode.Single:
+ return VariantUtils.ConvertToFloat32(p_var);
+ case TypeCode.Double:
+ return VariantUtils.ConvertToFloat64(p_var);
+ case TypeCode.String:
+ return VariantUtils.ConvertToStringObject(p_var);
+ default:
+ {
+ if (type == typeof(Vector2))
+ return VariantUtils.ConvertToVector2(p_var);
+
+ if (type == typeof(Vector2i))
+ return VariantUtils.ConvertToVector2i(p_var);
+
+ if (type == typeof(Rect2))
+ return VariantUtils.ConvertToRect2(p_var);
+
+ if (type == typeof(Rect2i))
+ return VariantUtils.ConvertToRect2i(p_var);
+
+ if (type == typeof(Transform2D))
+ return VariantUtils.ConvertToTransform2D(p_var);
+
+ if (type == typeof(Vector3))
+ return VariantUtils.ConvertToVector3(p_var);
+
+ if (type == typeof(Vector3i))
+ return VariantUtils.ConvertToVector3i(p_var);
+
+ if (type == typeof(Vector4))
+ return VariantUtils.ConvertToVector4(p_var);
+
+ if (type == typeof(Vector4i))
+ return VariantUtils.ConvertToVector4i(p_var);
+
+ if (type == typeof(Basis))
+ return VariantUtils.ConvertToBasis(p_var);
+
+ if (type == typeof(Quaternion))
+ return VariantUtils.ConvertToQuaternion(p_var);
+
+ if (type == typeof(Transform3D))
+ return VariantUtils.ConvertToTransform3D(p_var);
+
+ if (type == typeof(Projection))
+ return VariantUtils.ConvertToProjection(p_var);
+
+ if (type == typeof(AABB))
+ return VariantUtils.ConvertToAABB(p_var);
+
+ if (type == typeof(Color))
+ return VariantUtils.ConvertToColor(p_var);
+
+ if (type == typeof(Plane))
+ return VariantUtils.ConvertToPlane(p_var);
+
+ if (type == typeof(Callable))
+ return VariantUtils.ConvertToCallableManaged(p_var);
+
+ if (type == typeof(SignalInfo))
+ return VariantUtils.ConvertToSignalInfo(p_var);
+
+ if (type.IsEnum)
+ {
+ var enumUnderlyingType = type.GetEnumUnderlyingType();
+ switch (Type.GetTypeCode(enumUnderlyingType))
+ {
+ case TypeCode.SByte:
+ return VariantUtils.ConvertToInt8(p_var);
+ case TypeCode.Int16:
+ return VariantUtils.ConvertToInt16(p_var);
+ case TypeCode.Int32:
+ return VariantUtils.ConvertToInt32(p_var);
+ case TypeCode.Int64:
+ return VariantUtils.ConvertToInt64(p_var);
+ case TypeCode.Byte:
+ return VariantUtils.ConvertToUInt8(p_var);
+ case TypeCode.UInt16:
+ return VariantUtils.ConvertToUInt16(p_var);
+ case TypeCode.UInt32:
+ return VariantUtils.ConvertToUInt32(p_var);
+ case TypeCode.UInt64:
+ return VariantUtils.ConvertToUInt64(p_var);
+ default:
+ {
+ GD.PushError(
+ "Attempted to convert Variant to enum value of unsupported underlying type. Name: " +
+ type.FullName + " : " + enumUnderlyingType.FullName + ".");
+ return null;
+ }
+ }
+ }
+
+ if (type.IsArray || type.IsSZArray)
+ {
+ return ConvertVariantToSystemArrayOfType(p_var, type);
+ }
+ else if (type.IsGenericType)
+ {
+ if (typeof(Godot.Object).IsAssignableFrom(type))
+ {
+ var godotObject = VariantUtils.ConvertToGodotObject(p_var);
+
+ if (!type.IsInstanceOfType(godotObject))
+ {
+ GD.PushError("Invalid cast when marshaling Godot.Object type." +
+ $" `{godotObject.GetType()}` is not assignable to `{type.FullName}`.");
+ return null;
+ }
+
+ return godotObject;
+ }
+
+ return null;
+ }
+ else if (type == typeof(Variant))
+ {
+ return Variant.CreateCopyingBorrowed(p_var);
+ }
+
+ if (ConvertVariantToManagedObjectOfClass(p_var, type, out object? res))
+ return res;
+
+ break;
+ }
+ }
+
+ GD.PushError("Attempted to convert Variant to unsupported type. Name: " +
+ type.FullName + ".");
+ return null;
+ }
+
+ private static object? ConvertVariantToSystemArrayOfType(in godot_variant p_var, Type type)
+ {
+ if (type == typeof(byte[]))
+ return VariantUtils.ConvertAsPackedByteArrayToSystemArray(p_var);
+
+ if (type == typeof(int[]))
+ return VariantUtils.ConvertAsPackedInt32ArrayToSystemArray(p_var);
+
+ if (type == typeof(long[]))
+ return VariantUtils.ConvertAsPackedInt64ArrayToSystemArray(p_var);
+
+ if (type == typeof(float[]))
+ return VariantUtils.ConvertAsPackedFloat32ArrayToSystemArray(p_var);
+
+ if (type == typeof(double[]))
+ return VariantUtils.ConvertAsPackedFloat64ArrayToSystemArray(p_var);
+
+ if (type == typeof(string[]))
+ return VariantUtils.ConvertAsPackedStringArrayToSystemArray(p_var);
+
+ if (type == typeof(Vector2[]))
+ return VariantUtils.ConvertAsPackedVector2ArrayToSystemArray(p_var);
+
+ if (type == typeof(Vector3[]))
+ return VariantUtils.ConvertAsPackedVector3ArrayToSystemArray(p_var);
+
+ if (type == typeof(Color[]))
+ return VariantUtils.ConvertAsPackedColorArrayToSystemArray(p_var);
+
+ if (type == typeof(StringName[]))
+ return VariantUtils.ConvertToSystemArrayOfStringName(p_var);
+
+ if (type == typeof(NodePath[]))
+ return VariantUtils.ConvertToSystemArrayOfNodePath(p_var);
+
+ if (type == typeof(RID[]))
+ return VariantUtils.ConvertToSystemArrayOfRID(p_var);
+
+ if (typeof(Godot.Object[]).IsAssignableFrom(type))
+ return VariantUtils.ConvertToSystemArrayOfGodotObject(p_var, type);
+
+ GD.PushError("Attempted to convert Variant to array of unsupported element type. Name: " +
+ type.GetElementType()!.FullName + ".");
+ return null;
+ }
+
+ private static bool ConvertVariantToManagedObjectOfClass(in godot_variant p_var, Type type,
+ out object? res)
+ {
+ if (typeof(Godot.Object).IsAssignableFrom(type))
+ {
+ if (p_var.Type == Variant.Type.Nil)
+ {
+ res = null;
+ return true;
+ }
+
+ if (p_var.Type != Variant.Type.Object)
+ {
+ GD.PushError("Invalid cast when marshaling Godot.Object type." +
+ $" Variant type is `{p_var.Type}`; expected `{p_var.Object}`.");
+ res = null;
+ return true;
+ }
+
+ var godotObjectPtr = VariantUtils.ConvertToGodotObjectPtr(p_var);
+
+ if (godotObjectPtr == IntPtr.Zero)
+ {
+ res = null;
+ return true;
+ }
+
+ var godotObject = InteropUtils.UnmanagedGetManaged(godotObjectPtr);
+
+ if (!type.IsInstanceOfType(godotObject))
+ {
+ GD.PushError("Invalid cast when marshaling Godot.Object type." +
+ $" `{godotObject.GetType()}` is not assignable to `{type.FullName}`.");
+ res = null;
+ return false;
+ }
+
+ res = godotObject;
+ return true;
+ }
+
+ if (typeof(StringName) == type)
+ {
+ res = VariantUtils.ConvertToStringNameObject(p_var);
+ return true;
+ }
+
+ if (typeof(NodePath) == type)
+ {
+ res = VariantUtils.ConvertToNodePathObject(p_var);
+ return true;
+ }
+
+ if (typeof(RID) == type)
+ {
+ res = VariantUtils.ConvertToRID(p_var);
+ return true;
+ }
+
+ if (typeof(Collections.Dictionary) == type)
+ {
+ res = VariantUtils.ConvertToDictionaryObject(p_var);
+ return true;
+ }
+
+ if (typeof(Collections.Array) == type)
+ {
+ res = VariantUtils.ConvertToArrayObject(p_var);
+ return true;
+ }
+
+ res = null;
+ return false;
+ }
+
+ public static unsafe object? ConvertVariantToManagedObject(in godot_variant p_var)
+ {
+ switch (p_var.Type)
+ {
+ case Variant.Type.Bool:
+ return p_var.Bool.ToBool();
+ case Variant.Type.Int:
+ return p_var.Int;
+ case Variant.Type.Float:
+ {
+#if REAL_T_IS_DOUBLE
+ return p_var.Float;
+#else
+ return (float)p_var.Float;
+#endif
+ }
+ case Variant.Type.String:
+ return ConvertStringToManaged(p_var.String);
+ case Variant.Type.Vector2:
+ return p_var.Vector2;
+ case Variant.Type.Vector2i:
+ return p_var.Vector2i;
+ case Variant.Type.Rect2:
+ return p_var.Rect2;
+ case Variant.Type.Rect2i:
+ return p_var.Rect2i;
+ case Variant.Type.Vector3:
+ return p_var.Vector3;
+ case Variant.Type.Vector3i:
+ return p_var.Vector3i;
+ case Variant.Type.Transform2d:
+ return *p_var.Transform2D;
+ case Variant.Type.Vector4:
+ return *p_var.Vector4;
+ case Variant.Type.Vector4i:
+ return *p_var.Vector4i;
+ case Variant.Type.Plane:
+ return p_var.Plane;
+ case Variant.Type.Quaternion:
+ return p_var.Quaternion;
+ case Variant.Type.Aabb:
+ return *p_var.AABB;
+ case Variant.Type.Basis:
+ return *p_var.Basis;
+ case Variant.Type.Transform3d:
+ return *p_var.Transform3D;
+ case Variant.Type.Projection:
+ return *p_var.Projection;
+ case Variant.Type.Color:
+ return p_var.Color;
+ case Variant.Type.StringName:
+ {
+ // The Variant owns the value, so we need to make a copy
+ return StringName.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_string_name_new_copy(p_var.StringName));
+ }
+ case Variant.Type.NodePath:
+ {
+ // The Variant owns the value, so we need to make a copy
+ return NodePath.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_node_path_new_copy(p_var.NodePath));
+ }
+ case Variant.Type.Rid:
+ return p_var.RID;
+ case Variant.Type.Object:
+ return InteropUtils.UnmanagedGetManaged(p_var.Object);
+ case Variant.Type.Callable:
+ return ConvertCallableToManaged(p_var.Callable);
+ case Variant.Type.Signal:
+ return ConvertSignalToManaged(p_var.Signal);
+ case Variant.Type.Dictionary:
+ {
+ // The Variant owns the value, so we need to make a copy
+ return Collections.Dictionary.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_dictionary_new_copy(p_var.Dictionary));
+ }
+ case Variant.Type.Array:
+ {
+ // The Variant owns the value, so we need to make a copy
+ return Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(p_var.Array));
+ }
+ case Variant.Type.PackedByteArray:
+ return VariantUtils.ConvertAsPackedByteArrayToSystemArray(p_var);
+ case Variant.Type.PackedInt32Array:
+ return VariantUtils.ConvertAsPackedInt32ArrayToSystemArray(p_var);
+ case Variant.Type.PackedInt64Array:
+ return VariantUtils.ConvertAsPackedInt64ArrayToSystemArray(p_var);
+ case Variant.Type.PackedFloat32Array:
+ return VariantUtils.ConvertAsPackedFloat32ArrayToSystemArray(p_var);
+ case Variant.Type.PackedFloat64Array:
+ return VariantUtils.ConvertAsPackedFloat64ArrayToSystemArray(p_var);
+ case Variant.Type.PackedStringArray:
+ return VariantUtils.ConvertAsPackedStringArrayToSystemArray(p_var);
+ case Variant.Type.PackedVector2Array:
+ return VariantUtils.ConvertAsPackedVector2ArrayToSystemArray(p_var);
+ case Variant.Type.PackedVector3Array:
+ return VariantUtils.ConvertAsPackedVector3ArrayToSystemArray(p_var);
+ case Variant.Type.PackedColorArray:
+ return VariantUtils.ConvertAsPackedColorArrayToSystemArray(p_var);
+ default:
+ return null;
+ }
+ }
+
+ // String
+
+ public static unsafe godot_string ConvertStringToNative(string? p_mono_string)
+ {
+ if (p_mono_string == null)
+ return new godot_string();
+
+ fixed (char* methodChars = p_mono_string)
+ {
+ NativeFuncs.godotsharp_string_new_with_utf16_chars(out godot_string dest, methodChars);
+ return dest;
+ }
+ }
+
+ public static unsafe string ConvertStringToManaged(in godot_string p_string)
+ {
+ if (p_string.Buffer == IntPtr.Zero)
+ return string.Empty;
+
+ const int sizeOfChar32 = 4;
+ byte* bytes = (byte*)p_string.Buffer;
+ int size = p_string.Size;
+ if (size == 0)
+ return string.Empty;
+ size -= 1; // zero at the end
+ int sizeInBytes = size * sizeOfChar32;
+ return System.Text.Encoding.UTF32.GetString(bytes, sizeInBytes);
+ }
+
+ // Callable
+
+ public static godot_callable ConvertCallableToNative(in Callable p_managed_callable)
+ {
+ if (p_managed_callable.Delegate != null)
+ {
+ var gcHandle = CustomGCHandle.AllocStrong(p_managed_callable.Delegate);
+ NativeFuncs.godotsharp_callable_new_with_delegate(
+ GCHandle.ToIntPtr(gcHandle), out godot_callable callable);
+ return callable;
+ }
+ else
+ {
+ godot_string_name method;
+
+ if (p_managed_callable.Method != null && !p_managed_callable.Method.IsEmpty)
+ {
+ var src = (godot_string_name)p_managed_callable.Method.NativeValue;
+ method = NativeFuncs.godotsharp_string_name_new_copy(src);
+ }
+ else
+ {
+ method = default;
+ }
+
+ return new godot_callable(method /* Takes ownership of disposable */,
+ p_managed_callable.Target.GetInstanceId());
+ }
+ }
+
+ public static Callable ConvertCallableToManaged(in godot_callable p_callable)
+ {
+ if (NativeFuncs.godotsharp_callable_get_data_for_marshalling(p_callable,
+ out IntPtr delegateGCHandle, out IntPtr godotObject,
+ out godot_string_name name).ToBool())
+ {
+ if (delegateGCHandle != IntPtr.Zero)
+ {
+ return new Callable((Delegate?)GCHandle.FromIntPtr(delegateGCHandle).Target);
+ }
+ else
+ {
+ return new Callable(
+ InteropUtils.UnmanagedGetManaged(godotObject),
+ StringName.CreateTakingOwnershipOfDisposableValue(name));
+ }
+ }
+
+ // Some other unsupported callable
+ return new Callable();
+ }
+
+ // SignalInfo
+
+ public static godot_signal ConvertSignalToNative(in SignalInfo p_managed_signal)
+ {
+ ulong ownerId = p_managed_signal.Owner.GetInstanceId();
+ godot_string_name name;
+
+ if (p_managed_signal.Name != null && !p_managed_signal.Name.IsEmpty)
+ {
+ var src = (godot_string_name)p_managed_signal.Name.NativeValue;
+ name = NativeFuncs.godotsharp_string_name_new_copy(src);
+ }
+ else
+ {
+ name = default;
+ }
+
+ return new godot_signal(name, ownerId);
+ }
+
+ public static SignalInfo ConvertSignalToManaged(in godot_signal p_signal)
+ {
+ var owner = GD.InstanceFromId(p_signal.ObjectId);
+ var name = StringName.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_string_name_new_copy(p_signal.Name));
+ return new SignalInfo(owner, name);
+ }
+
+ // Array
+
+ internal static T[] ConvertNativeGodotArrayToSystemArrayOfGodotObjectType<T>(in godot_array p_array)
+ where T : Godot.Object
+ {
+ var array = Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(p_array));
+
+ int length = array.Count;
+ var ret = new T[length];
+
+ for (int i = 0; i < length; i++)
+ ret[i] = (T)array[i].AsGodotObject();
+
+ return ret;
+ }
+
+ // TODO: This needs reflection. Look for an alternative.
+ internal static Godot.Object[] ConvertNativeGodotArrayToSystemArrayOfGodotObjectType(in godot_array p_array,
+ Type type)
+ {
+ var array = Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(p_array));
+
+ int length = array.Count;
+ var ret = (Godot.Object[])Activator.CreateInstance(type, length)!;
+
+ for (int i = 0; i < length; i++)
+ ret[i] = array[i].AsGodotObject();
+
+ return ret;
+ }
+
+ internal static StringName[] ConvertNativeGodotArrayToSystemArrayOfStringName(in godot_array p_array)
+ {
+ var array = Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(p_array));
+
+ int length = array.Count;
+ var ret = new StringName[length];
+
+ for (int i = 0; i < length; i++)
+ ret[i] = array[i].AsStringName();
+
+ return ret;
+ }
+
+ internal static NodePath[] ConvertNativeGodotArrayToSystemArrayOfNodePath(in godot_array p_array)
+ {
+ var array = Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(p_array));
+
+ int length = array.Count;
+ var ret = new NodePath[length];
+
+ for (int i = 0; i < length; i++)
+ ret[i] = array[i].AsNodePath();
+
+ return ret;
+ }
+
+ internal static RID[] ConvertNativeGodotArrayToSystemArrayOfRID(in godot_array p_array)
+ {
+ var array = Collections.Array.CreateTakingOwnershipOfDisposableValue(
+ NativeFuncs.godotsharp_array_new_copy(p_array));
+
+ int length = array.Count;
+ var ret = new RID[length];
+
+ for (int i = 0; i < length; i++)
+ ret[i] = array[i].AsRID();
+
+ return ret;
+ }
+
+ // PackedByteArray
+
+ public static unsafe byte[] ConvertNativePackedByteArrayToSystemArray(in godot_packed_byte_array p_array)
+ {
+ byte* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<byte>();
+ var array = new byte[size];
+ fixed (byte* dest = array)
+ Buffer.MemoryCopy(buffer, dest, size, size);
+ return array;
+ }
+
+ public static unsafe godot_packed_byte_array ConvertSystemArrayToNativePackedByteArray(Span<byte> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_byte_array();
+ fixed (byte* src = p_array)
+ return NativeFuncs.godotsharp_packed_byte_array_new_mem_copy(src, p_array.Length);
+ }
+
+ // PackedInt32Array
+
+ public static unsafe int[] ConvertNativePackedInt32ArrayToSystemArray(godot_packed_int32_array p_array)
+ {
+ int* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<int>();
+ int sizeInBytes = size * sizeof(int);
+ var array = new int[size];
+ fixed (int* dest = array)
+ Buffer.MemoryCopy(buffer, dest, sizeInBytes, sizeInBytes);
+ return array;
+ }
+
+ public static unsafe godot_packed_int32_array ConvertSystemArrayToNativePackedInt32Array(Span<int> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_int32_array();
+ fixed (int* src = p_array)
+ return NativeFuncs.godotsharp_packed_int32_array_new_mem_copy(src, p_array.Length);
+ }
+
+ // PackedInt64Array
+
+ public static unsafe long[] ConvertNativePackedInt64ArrayToSystemArray(godot_packed_int64_array p_array)
+ {
+ long* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<long>();
+ int sizeInBytes = size * sizeof(long);
+ var array = new long[size];
+ fixed (long* dest = array)
+ Buffer.MemoryCopy(buffer, dest, sizeInBytes, sizeInBytes);
+ return array;
+ }
+
+ public static unsafe godot_packed_int64_array ConvertSystemArrayToNativePackedInt64Array(Span<long> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_int64_array();
+ fixed (long* src = p_array)
+ return NativeFuncs.godotsharp_packed_int64_array_new_mem_copy(src, p_array.Length);
+ }
+
+ // PackedFloat32Array
+
+ public static unsafe float[] ConvertNativePackedFloat32ArrayToSystemArray(godot_packed_float32_array p_array)
+ {
+ float* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<float>();
+ int sizeInBytes = size * sizeof(float);
+ var array = new float[size];
+ fixed (float* dest = array)
+ Buffer.MemoryCopy(buffer, dest, sizeInBytes, sizeInBytes);
+ return array;
+ }
+
+ public static unsafe godot_packed_float32_array ConvertSystemArrayToNativePackedFloat32Array(
+ Span<float> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_float32_array();
+ fixed (float* src = p_array)
+ return NativeFuncs.godotsharp_packed_float32_array_new_mem_copy(src, p_array.Length);
+ }
+
+ // PackedFloat64Array
+
+ public static unsafe double[] ConvertNativePackedFloat64ArrayToSystemArray(godot_packed_float64_array p_array)
+ {
+ double* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<double>();
+ int sizeInBytes = size * sizeof(double);
+ var array = new double[size];
+ fixed (double* dest = array)
+ Buffer.MemoryCopy(buffer, dest, sizeInBytes, sizeInBytes);
+ return array;
+ }
+
+ public static unsafe godot_packed_float64_array ConvertSystemArrayToNativePackedFloat64Array(
+ Span<double> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_float64_array();
+ fixed (double* src = p_array)
+ return NativeFuncs.godotsharp_packed_float64_array_new_mem_copy(src, p_array.Length);
+ }
+
+ // PackedStringArray
+
+ public static unsafe string[] ConvertNativePackedStringArrayToSystemArray(godot_packed_string_array p_array)
+ {
+ godot_string* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<string>();
+ var array = new string[size];
+ for (int i = 0; i < size; i++)
+ array[i] = ConvertStringToManaged(buffer[i]);
+ return array;
+ }
+
+ public static godot_packed_string_array ConvertSystemArrayToNativePackedStringArray(Span<string> p_array)
+ {
+ godot_packed_string_array dest = new godot_packed_string_array();
+
+ if (p_array.IsEmpty)
+ return dest;
+
+ /* TODO: Replace godotsharp_packed_string_array_add with a single internal call to
+ get the write address. We can't use `dest._ptr` directly for writing due to COW. */
+
+ for (int i = 0; i < p_array.Length; i++)
+ {
+ using godot_string godotStrElem = ConvertStringToNative(p_array[i]);
+ NativeFuncs.godotsharp_packed_string_array_add(ref dest, godotStrElem);
+ }
+
+ return dest;
+ }
+
+ // PackedVector2Array
+
+ public static unsafe Vector2[] ConvertNativePackedVector2ArrayToSystemArray(godot_packed_vector2_array p_array)
+ {
+ Vector2* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<Vector2>();
+ int sizeInBytes = size * sizeof(Vector2);
+ var array = new Vector2[size];
+ fixed (Vector2* dest = array)
+ Buffer.MemoryCopy(buffer, dest, sizeInBytes, sizeInBytes);
+ return array;
+ }
+
+ public static unsafe godot_packed_vector2_array ConvertSystemArrayToNativePackedVector2Array(
+ Span<Vector2> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_vector2_array();
+ fixed (Vector2* src = p_array)
+ return NativeFuncs.godotsharp_packed_vector2_array_new_mem_copy(src, p_array.Length);
+ }
+
+ // PackedVector3Array
+
+ public static unsafe Vector3[] ConvertNativePackedVector3ArrayToSystemArray(godot_packed_vector3_array p_array)
+ {
+ Vector3* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<Vector3>();
+ int sizeInBytes = size * sizeof(Vector3);
+ var array = new Vector3[size];
+ fixed (Vector3* dest = array)
+ Buffer.MemoryCopy(buffer, dest, sizeInBytes, sizeInBytes);
+ return array;
+ }
+
+ public static unsafe godot_packed_vector3_array ConvertSystemArrayToNativePackedVector3Array(
+ Span<Vector3> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_vector3_array();
+ fixed (Vector3* src = p_array)
+ return NativeFuncs.godotsharp_packed_vector3_array_new_mem_copy(src, p_array.Length);
+ }
+
+ // PackedColorArray
+
+ public static unsafe Color[] ConvertNativePackedColorArrayToSystemArray(godot_packed_color_array p_array)
+ {
+ Color* buffer = p_array.Buffer;
+ int size = p_array.Size;
+ if (size == 0)
+ return Array.Empty<Color>();
+ int sizeInBytes = size * sizeof(Color);
+ var array = new Color[size];
+ fixed (Color* dest = array)
+ Buffer.MemoryCopy(buffer, dest, sizeInBytes, sizeInBytes);
+ return array;
+ }
+
+ public static unsafe godot_packed_color_array ConvertSystemArrayToNativePackedColorArray(Span<Color> p_array)
+ {
+ if (p_array.IsEmpty)
+ return new godot_packed_color_array();
+ fixed (Color* src = p_array)
+ return NativeFuncs.godotsharp_packed_color_array_new_mem_copy(src, p_array.Length);
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs
new file mode 100644
index 0000000000..6d2534e6f7
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs
@@ -0,0 +1,522 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+using Godot.SourceGenerators.Internal;
+
+// ReSharper disable InconsistentNaming
+
+namespace Godot.NativeInterop
+{
+ /*
+ * IMPORTANT:
+ * The order of the methods defined in NativeFuncs must match the order
+ * in the array defined at the bottom of 'glue/runtime_interop.cpp'.
+ */
+
+ [GenerateUnmanagedCallbacks(typeof(UnmanagedCallbacks))]
+ public static unsafe partial class NativeFuncs
+ {
+ private static bool initialized = false;
+
+ // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global
+ public static void Initialize(IntPtr unmanagedCallbacks, int unmanagedCallbacksSize)
+ {
+ if (initialized)
+ throw new InvalidOperationException("Already initialized");
+ initialized = true;
+
+ if (unmanagedCallbacksSize != sizeof(UnmanagedCallbacks))
+ throw new ArgumentException("Unmanaged callbacks size mismatch");
+
+ _unmanagedCallbacks = Unsafe.AsRef<UnmanagedCallbacks>((void*)unmanagedCallbacks);
+ }
+
+ private partial struct UnmanagedCallbacks
+ {
+ }
+
+ // Custom functions
+
+ public static partial IntPtr godotsharp_method_bind_get_method(in godot_string_name p_classname,
+ in godot_string_name p_methodname);
+
+ public static partial delegate* unmanaged<IntPtr> godotsharp_get_class_constructor(
+ in godot_string_name p_classname);
+
+ public static partial IntPtr godotsharp_engine_get_singleton(in godot_string p_name);
+
+
+ internal static partial Error godotsharp_stack_info_vector_resize(
+ ref DebuggingUtils.godot_stack_info_vector p_stack_info_vector, int p_size);
+
+ internal static partial void godotsharp_stack_info_vector_destroy(
+ ref DebuggingUtils.godot_stack_info_vector p_stack_info_vector);
+
+ internal static partial void godotsharp_internal_script_debugger_send_error(in godot_string p_func,
+ in godot_string p_file, int p_line, in godot_string p_err, in godot_string p_descr,
+ godot_bool p_warning, in DebuggingUtils.godot_stack_info_vector p_stack_info_vector);
+
+ internal static partial bool godotsharp_internal_script_debugger_is_active();
+
+ internal static partial IntPtr godotsharp_internal_object_get_associated_gchandle(IntPtr ptr);
+
+ internal static partial void godotsharp_internal_object_disposed(IntPtr ptr, IntPtr gcHandleToFree);
+
+ internal static partial void godotsharp_internal_refcounted_disposed(IntPtr ptr, IntPtr gcHandleToFree,
+ godot_bool isFinalizer);
+
+ internal static partial Error godotsharp_internal_signal_awaiter_connect(IntPtr source,
+ in godot_string_name signal,
+ IntPtr target, IntPtr awaiterHandlePtr);
+
+ internal static partial void godotsharp_internal_tie_native_managed_to_unmanaged(IntPtr gcHandleIntPtr,
+ IntPtr unmanaged, in godot_string_name nativeName, godot_bool refCounted);
+
+ internal static partial void godotsharp_internal_tie_user_managed_to_unmanaged(IntPtr gcHandleIntPtr,
+ IntPtr unmanaged, godot_ref* scriptPtr, godot_bool refCounted);
+
+ internal static partial void godotsharp_internal_tie_managed_to_unmanaged_with_pre_setup(
+ IntPtr gcHandleIntPtr, IntPtr unmanaged);
+
+ internal static partial IntPtr godotsharp_internal_unmanaged_get_script_instance_managed(IntPtr p_unmanaged,
+ out godot_bool r_has_cs_script_instance);
+
+ internal static partial IntPtr godotsharp_internal_unmanaged_get_instance_binding_managed(IntPtr p_unmanaged);
+
+ internal static partial IntPtr godotsharp_internal_unmanaged_instance_binding_create_managed(IntPtr p_unmanaged,
+ IntPtr oldGCHandlePtr);
+
+ internal static partial void godotsharp_internal_new_csharp_script(godot_ref* r_dest);
+
+ internal static partial godot_bool godotsharp_internal_script_load(in godot_string p_path, godot_ref* r_dest);
+
+ internal static partial void godotsharp_internal_reload_registered_script(IntPtr scriptPtr);
+
+ internal static partial void godotsharp_array_filter_godot_objects_by_native(in godot_string_name p_native_name,
+ in godot_array p_input, out godot_array r_output);
+
+ internal static partial void godotsharp_array_filter_godot_objects_by_non_native(in godot_array p_input,
+ out godot_array r_output);
+
+ public static partial void godotsharp_ref_new_from_ref_counted_ptr(out godot_ref r_dest,
+ IntPtr p_ref_counted_ptr);
+
+ public static partial void godotsharp_ref_destroy(ref godot_ref p_instance);
+
+ public static partial void godotsharp_string_name_new_from_string(out godot_string_name r_dest,
+ in godot_string p_name);
+
+ public static partial void godotsharp_node_path_new_from_string(out godot_node_path r_dest,
+ in godot_string p_name);
+
+ public static partial void
+ godotsharp_string_name_as_string(out godot_string r_dest, in godot_string_name p_name);
+
+ public static partial void godotsharp_node_path_as_string(out godot_string r_dest, in godot_node_path p_np);
+
+ public static partial godot_packed_byte_array godotsharp_packed_byte_array_new_mem_copy(byte* p_src,
+ int p_length);
+
+ public static partial godot_packed_int32_array godotsharp_packed_int32_array_new_mem_copy(int* p_src,
+ int p_length);
+
+ public static partial godot_packed_int64_array godotsharp_packed_int64_array_new_mem_copy(long* p_src,
+ int p_length);
+
+ public static partial godot_packed_float32_array godotsharp_packed_float32_array_new_mem_copy(float* p_src,
+ int p_length);
+
+ public static partial godot_packed_float64_array godotsharp_packed_float64_array_new_mem_copy(double* p_src,
+ int p_length);
+
+ public static partial godot_packed_vector2_array godotsharp_packed_vector2_array_new_mem_copy(Vector2* p_src,
+ int p_length);
+
+ public static partial godot_packed_vector3_array godotsharp_packed_vector3_array_new_mem_copy(Vector3* p_src,
+ int p_length);
+
+ public static partial godot_packed_color_array godotsharp_packed_color_array_new_mem_copy(Color* p_src,
+ int p_length);
+
+ public static partial void godotsharp_packed_string_array_add(ref godot_packed_string_array r_dest,
+ in godot_string p_element);
+
+ public static partial void godotsharp_callable_new_with_delegate(IntPtr p_delegate_handle,
+ out godot_callable r_callable);
+
+ internal static partial godot_bool godotsharp_callable_get_data_for_marshalling(in godot_callable p_callable,
+ out IntPtr r_delegate_handle, out IntPtr r_object, out godot_string_name r_name);
+
+ internal static partial godot_variant godotsharp_callable_call(in godot_callable p_callable,
+ godot_variant** p_args, int p_arg_count, out godot_variant_call_error p_call_error);
+
+ internal static partial void godotsharp_callable_call_deferred(in godot_callable p_callable,
+ godot_variant** p_args, int p_arg_count);
+
+ // GDNative functions
+
+ // gdnative.h
+
+ public static partial void godotsharp_method_bind_ptrcall(IntPtr p_method_bind, IntPtr p_instance, void** p_args,
+ void* p_ret);
+
+ public static partial godot_variant godotsharp_method_bind_call(IntPtr p_method_bind, IntPtr p_instance,
+ godot_variant** p_args, int p_arg_count, out godot_variant_call_error p_call_error);
+
+ // variant.h
+
+ public static partial void
+ godotsharp_variant_new_string_name(out godot_variant r_dest, in godot_string_name p_s);
+
+ public static partial void godotsharp_variant_new_copy(out godot_variant r_dest, in godot_variant p_src);
+
+ public static partial void godotsharp_variant_new_node_path(out godot_variant r_dest, in godot_node_path p_np);
+
+ public static partial void godotsharp_variant_new_object(out godot_variant r_dest, IntPtr p_obj);
+
+ public static partial void godotsharp_variant_new_transform2d(out godot_variant r_dest, in Transform2D p_t2d);
+
+ public static partial void godotsharp_variant_new_vector4(out godot_variant r_dest, in Vector4 p_vec4);
+
+ public static partial void godotsharp_variant_new_vector4i(out godot_variant r_dest, in Vector4i p_vec4i);
+
+ public static partial void godotsharp_variant_new_basis(out godot_variant r_dest, in Basis p_basis);
+
+ public static partial void godotsharp_variant_new_transform3d(out godot_variant r_dest, in Transform3D p_trans);
+
+ public static partial void godotsharp_variant_new_projection(out godot_variant r_dest, in Projection p_proj);
+
+ public static partial void godotsharp_variant_new_aabb(out godot_variant r_dest, in AABB p_aabb);
+
+ public static partial void godotsharp_variant_new_dictionary(out godot_variant r_dest,
+ in godot_dictionary p_dict);
+
+ public static partial void godotsharp_variant_new_array(out godot_variant r_dest, in godot_array p_arr);
+
+ public static partial void godotsharp_variant_new_packed_byte_array(out godot_variant r_dest,
+ in godot_packed_byte_array p_pba);
+
+ public static partial void godotsharp_variant_new_packed_int32_array(out godot_variant r_dest,
+ in godot_packed_int32_array p_pia);
+
+ public static partial void godotsharp_variant_new_packed_int64_array(out godot_variant r_dest,
+ in godot_packed_int64_array p_pia);
+
+ public static partial void godotsharp_variant_new_packed_float32_array(out godot_variant r_dest,
+ in godot_packed_float32_array p_pra);
+
+ public static partial void godotsharp_variant_new_packed_float64_array(out godot_variant r_dest,
+ in godot_packed_float64_array p_pra);
+
+ public static partial void godotsharp_variant_new_packed_string_array(out godot_variant r_dest,
+ in godot_packed_string_array p_psa);
+
+ public static partial void godotsharp_variant_new_packed_vector2_array(out godot_variant r_dest,
+ in godot_packed_vector2_array p_pv2a);
+
+ public static partial void godotsharp_variant_new_packed_vector3_array(out godot_variant r_dest,
+ in godot_packed_vector3_array p_pv3a);
+
+ public static partial void godotsharp_variant_new_packed_color_array(out godot_variant r_dest,
+ in godot_packed_color_array p_pca);
+
+ public static partial godot_bool godotsharp_variant_as_bool(in godot_variant p_self);
+
+ public static partial Int64 godotsharp_variant_as_int(in godot_variant p_self);
+
+ public static partial double godotsharp_variant_as_float(in godot_variant p_self);
+
+ public static partial godot_string godotsharp_variant_as_string(in godot_variant p_self);
+
+ public static partial Vector2 godotsharp_variant_as_vector2(in godot_variant p_self);
+
+ public static partial Vector2i godotsharp_variant_as_vector2i(in godot_variant p_self);
+
+ public static partial Rect2 godotsharp_variant_as_rect2(in godot_variant p_self);
+
+ public static partial Rect2i godotsharp_variant_as_rect2i(in godot_variant p_self);
+
+ public static partial Vector3 godotsharp_variant_as_vector3(in godot_variant p_self);
+
+ public static partial Vector3i godotsharp_variant_as_vector3i(in godot_variant p_self);
+
+ public static partial Transform2D godotsharp_variant_as_transform2d(in godot_variant p_self);
+
+ public static partial Vector4 godotsharp_variant_as_vector4(in godot_variant p_self);
+
+ public static partial Vector4i godotsharp_variant_as_vector4i(in godot_variant p_self);
+
+ public static partial Plane godotsharp_variant_as_plane(in godot_variant p_self);
+
+ public static partial Quaternion godotsharp_variant_as_quaternion(in godot_variant p_self);
+
+ public static partial AABB godotsharp_variant_as_aabb(in godot_variant p_self);
+
+ public static partial Basis godotsharp_variant_as_basis(in godot_variant p_self);
+
+ public static partial Transform3D godotsharp_variant_as_transform3d(in godot_variant p_self);
+
+ public static partial Projection godotsharp_variant_as_projection(in godot_variant p_self);
+
+ public static partial Color godotsharp_variant_as_color(in godot_variant p_self);
+
+ public static partial godot_string_name godotsharp_variant_as_string_name(in godot_variant p_self);
+
+ public static partial godot_node_path godotsharp_variant_as_node_path(in godot_variant p_self);
+
+ public static partial RID godotsharp_variant_as_rid(in godot_variant p_self);
+
+ public static partial godot_callable godotsharp_variant_as_callable(in godot_variant p_self);
+
+ public static partial godot_signal godotsharp_variant_as_signal(in godot_variant p_self);
+
+ public static partial godot_dictionary godotsharp_variant_as_dictionary(in godot_variant p_self);
+
+ public static partial godot_array godotsharp_variant_as_array(in godot_variant p_self);
+
+ public static partial godot_packed_byte_array godotsharp_variant_as_packed_byte_array(in godot_variant p_self);
+
+ public static partial godot_packed_int32_array godotsharp_variant_as_packed_int32_array(in godot_variant p_self);
+
+ public static partial godot_packed_int64_array godotsharp_variant_as_packed_int64_array(in godot_variant p_self);
+
+ public static partial godot_packed_float32_array godotsharp_variant_as_packed_float32_array(
+ in godot_variant p_self);
+
+ public static partial godot_packed_float64_array godotsharp_variant_as_packed_float64_array(
+ in godot_variant p_self);
+
+ public static partial godot_packed_string_array godotsharp_variant_as_packed_string_array(
+ in godot_variant p_self);
+
+ public static partial godot_packed_vector2_array godotsharp_variant_as_packed_vector2_array(
+ in godot_variant p_self);
+
+ public static partial godot_packed_vector3_array godotsharp_variant_as_packed_vector3_array(
+ in godot_variant p_self);
+
+ public static partial godot_packed_color_array godotsharp_variant_as_packed_color_array(in godot_variant p_self);
+
+ public static partial godot_bool godotsharp_variant_equals(in godot_variant p_a, in godot_variant p_b);
+
+ // string.h
+
+ public static partial void godotsharp_string_new_with_utf16_chars(out godot_string r_dest, char* p_contents);
+
+ // string_name.h
+
+ public static partial void godotsharp_string_name_new_copy(out godot_string_name r_dest,
+ in godot_string_name p_src);
+
+ // node_path.h
+
+ public static partial void godotsharp_node_path_new_copy(out godot_node_path r_dest, in godot_node_path p_src);
+
+ // array.h
+
+ public static partial void godotsharp_array_new(out godot_array r_dest);
+
+ public static partial void godotsharp_array_new_copy(out godot_array r_dest, in godot_array p_src);
+
+ public static partial godot_variant* godotsharp_array_ptrw(ref godot_array p_self);
+
+ // dictionary.h
+
+ public static partial void godotsharp_dictionary_new(out godot_dictionary r_dest);
+
+ public static partial void godotsharp_dictionary_new_copy(out godot_dictionary r_dest,
+ in godot_dictionary p_src);
+
+ // destroy functions
+
+ public static partial void godotsharp_packed_byte_array_destroy(ref godot_packed_byte_array p_self);
+
+ public static partial void godotsharp_packed_int32_array_destroy(ref godot_packed_int32_array p_self);
+
+ public static partial void godotsharp_packed_int64_array_destroy(ref godot_packed_int64_array p_self);
+
+ public static partial void godotsharp_packed_float32_array_destroy(ref godot_packed_float32_array p_self);
+
+ public static partial void godotsharp_packed_float64_array_destroy(ref godot_packed_float64_array p_self);
+
+ public static partial void godotsharp_packed_string_array_destroy(ref godot_packed_string_array p_self);
+
+ public static partial void godotsharp_packed_vector2_array_destroy(ref godot_packed_vector2_array p_self);
+
+ public static partial void godotsharp_packed_vector3_array_destroy(ref godot_packed_vector3_array p_self);
+
+ public static partial void godotsharp_packed_color_array_destroy(ref godot_packed_color_array p_self);
+
+ public static partial void godotsharp_variant_destroy(ref godot_variant p_self);
+
+ public static partial void godotsharp_string_destroy(ref godot_string p_self);
+
+ public static partial void godotsharp_string_name_destroy(ref godot_string_name p_self);
+
+ public static partial void godotsharp_node_path_destroy(ref godot_node_path p_self);
+
+ public static partial void godotsharp_signal_destroy(ref godot_signal p_self);
+
+ public static partial void godotsharp_callable_destroy(ref godot_callable p_self);
+
+ public static partial void godotsharp_array_destroy(ref godot_array p_self);
+
+ public static partial void godotsharp_dictionary_destroy(ref godot_dictionary p_self);
+
+ // Array
+
+ public static partial int godotsharp_array_add(ref godot_array p_self, in godot_variant p_item);
+
+ public static partial void
+ godotsharp_array_duplicate(ref godot_array p_self, godot_bool p_deep, out godot_array r_dest);
+
+ public static partial int godotsharp_array_index_of(ref godot_array p_self, in godot_variant p_item);
+
+ public static partial void godotsharp_array_insert(ref godot_array p_self, int p_index, in godot_variant p_item);
+
+ public static partial void godotsharp_array_remove_at(ref godot_array p_self, int p_index);
+
+ public static partial Error godotsharp_array_resize(ref godot_array p_self, int p_new_size);
+
+ public static partial Error godotsharp_array_shuffle(ref godot_array p_self);
+
+ public static partial void godotsharp_array_to_string(ref godot_array p_self, out godot_string r_str);
+
+ // Dictionary
+
+ public static partial godot_bool godotsharp_dictionary_try_get_value(ref godot_dictionary p_self,
+ in godot_variant p_key,
+ out godot_variant r_value);
+
+ public static partial void godotsharp_dictionary_set_value(ref godot_dictionary p_self, in godot_variant p_key,
+ in godot_variant p_value);
+
+ public static partial void godotsharp_dictionary_keys(ref godot_dictionary p_self, out godot_array r_dest);
+
+ public static partial void godotsharp_dictionary_values(ref godot_dictionary p_self, out godot_array r_dest);
+
+ public static partial int godotsharp_dictionary_count(ref godot_dictionary p_self);
+
+ public static partial void godotsharp_dictionary_key_value_pair_at(ref godot_dictionary p_self, int p_index,
+ out godot_variant r_key, out godot_variant r_value);
+
+ public static partial void godotsharp_dictionary_add(ref godot_dictionary p_self, in godot_variant p_key,
+ in godot_variant p_value);
+
+ public static partial void godotsharp_dictionary_clear(ref godot_dictionary p_self);
+
+ public static partial godot_bool godotsharp_dictionary_contains_key(ref godot_dictionary p_self,
+ in godot_variant p_key);
+
+ public static partial void godotsharp_dictionary_duplicate(ref godot_dictionary p_self, godot_bool p_deep,
+ out godot_dictionary r_dest);
+
+ public static partial godot_bool godotsharp_dictionary_remove_key(ref godot_dictionary p_self,
+ in godot_variant p_key);
+
+ public static partial void godotsharp_dictionary_to_string(ref godot_dictionary p_self, out godot_string r_str);
+
+ // StringExtensions
+
+ public static partial void godotsharp_string_md5_buffer(in godot_string p_self,
+ out godot_packed_byte_array r_md5_buffer);
+
+ public static partial void godotsharp_string_md5_text(in godot_string p_self, out godot_string r_md5_text);
+
+ public static partial int godotsharp_string_rfind(in godot_string p_self, in godot_string p_what, int p_from);
+
+ public static partial int godotsharp_string_rfindn(in godot_string p_self, in godot_string p_what, int p_from);
+
+ public static partial void godotsharp_string_sha256_buffer(in godot_string p_self,
+ out godot_packed_byte_array r_sha256_buffer);
+
+ public static partial void godotsharp_string_sha256_text(in godot_string p_self,
+ out godot_string r_sha256_text);
+
+ public static partial void godotsharp_string_simplify_path(in godot_string p_self,
+ out godot_string r_simplified_path);
+
+ // NodePath
+
+ public static partial void godotsharp_node_path_get_as_property_path(in godot_node_path p_self,
+ ref godot_node_path r_dest);
+
+ public static partial void godotsharp_node_path_get_concatenated_names(in godot_node_path p_self,
+ out godot_string r_names);
+
+ public static partial void godotsharp_node_path_get_concatenated_subnames(in godot_node_path p_self,
+ out godot_string r_subnames);
+
+ public static partial void godotsharp_node_path_get_name(in godot_node_path p_self, int p_idx,
+ out godot_string r_name);
+
+ public static partial int godotsharp_node_path_get_name_count(in godot_node_path p_self);
+
+ public static partial void godotsharp_node_path_get_subname(in godot_node_path p_self, int p_idx,
+ out godot_string r_subname);
+
+ public static partial int godotsharp_node_path_get_subname_count(in godot_node_path p_self);
+
+ public static partial godot_bool godotsharp_node_path_is_absolute(in godot_node_path p_self);
+
+ // GD, etc
+
+ internal static partial void godotsharp_bytes2var(in godot_packed_byte_array p_bytes,
+ godot_bool p_allow_objects,
+ out godot_variant r_ret);
+
+ internal static partial void godotsharp_convert(in godot_variant p_what, int p_type,
+ out godot_variant r_ret);
+
+ internal static partial int godotsharp_hash(in godot_variant p_var);
+
+ internal static partial IntPtr godotsharp_instance_from_id(ulong p_instance_id);
+
+ internal static partial void godotsharp_print(in godot_string p_what);
+
+ public static partial void godotsharp_print_rich(in godot_string p_what);
+
+ internal static partial void godotsharp_printerr(in godot_string p_what);
+
+ internal static partial void godotsharp_printraw(in godot_string p_what);
+
+ internal static partial void godotsharp_prints(in godot_string p_what);
+
+ internal static partial void godotsharp_printt(in godot_string p_what);
+
+ internal static partial float godotsharp_randf();
+
+ internal static partial uint godotsharp_randi();
+
+ internal static partial void godotsharp_randomize();
+
+ internal static partial double godotsharp_randf_range(double from, double to);
+
+ internal static partial double godotsharp_randfn(double mean, double deviation);
+
+ internal static partial int godotsharp_randi_range(int from, int to);
+
+ internal static partial uint godotsharp_rand_from_seed(ulong seed, out ulong newSeed);
+
+ internal static partial void godotsharp_seed(ulong seed);
+
+ internal static partial void godotsharp_weakref(IntPtr p_obj, out godot_ref r_weak_ref);
+
+ internal static partial void godotsharp_str(in godot_array p_what, out godot_string r_ret);
+
+ internal static partial void godotsharp_str2var(in godot_string p_str, out godot_variant r_ret);
+
+ internal static partial void godotsharp_var2bytes(in godot_variant p_what, godot_bool p_full_objects,
+ out godot_packed_byte_array r_bytes);
+
+ internal static partial void godotsharp_var2str(in godot_variant p_var, out godot_string r_ret);
+
+ internal static partial void godotsharp_pusherror(in godot_string p_str);
+
+ internal static partial void godotsharp_pushwarning(in godot_string p_str);
+
+ // Object
+
+ public static partial void godotsharp_object_to_string(IntPtr ptr, out godot_string r_str);
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs
new file mode 100644
index 0000000000..2ea3c18d26
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs
@@ -0,0 +1,99 @@
+// ReSharper disable InconsistentNaming
+
+namespace Godot.NativeInterop
+{
+ public static partial class NativeFuncs
+ {
+ public static godot_variant godotsharp_variant_new_copy(in godot_variant src)
+ {
+ switch (src.Type)
+ {
+ case Variant.Type.Nil:
+ return default;
+ case Variant.Type.Bool:
+ return new godot_variant() { Bool = src.Bool };
+ case Variant.Type.Int:
+ return new godot_variant() { Int = src.Int };
+ case Variant.Type.Float:
+ return new godot_variant() { Float = src.Float };
+ case Variant.Type.Vector2:
+ return new godot_variant() { Vector2 = src.Vector2 };
+ case Variant.Type.Vector2i:
+ return new godot_variant() { Vector2i = src.Vector2i };
+ case Variant.Type.Rect2:
+ return new godot_variant() { Rect2 = src.Rect2 };
+ case Variant.Type.Rect2i:
+ return new godot_variant() { Rect2i = src.Rect2i };
+ case Variant.Type.Vector3:
+ return new godot_variant() { Vector3 = src.Vector3 };
+ case Variant.Type.Vector3i:
+ return new godot_variant() { Vector3i = src.Vector3i };
+ case Variant.Type.Plane:
+ return new godot_variant() { Plane = src.Plane };
+ case Variant.Type.Quaternion:
+ return new godot_variant() { Quaternion = src.Quaternion };
+ case Variant.Type.Color:
+ return new godot_variant() { Color = src.Color };
+ case Variant.Type.Rid:
+ return new godot_variant() { RID = src.RID };
+ }
+
+ godotsharp_variant_new_copy(out godot_variant ret, src);
+ return ret;
+ }
+
+ public static godot_string_name godotsharp_string_name_new_copy(in godot_string_name src)
+ {
+ if (src.IsEmpty)
+ return default;
+ godotsharp_string_name_new_copy(out godot_string_name ret, src);
+ return ret;
+ }
+
+ public static godot_node_path godotsharp_node_path_new_copy(in godot_node_path src)
+ {
+ if (src.IsEmpty)
+ return default;
+ godotsharp_node_path_new_copy(out godot_node_path ret, src);
+ return ret;
+ }
+
+ public static godot_array godotsharp_array_new()
+ {
+ godotsharp_array_new(out godot_array ret);
+ return ret;
+ }
+
+ public static godot_array godotsharp_array_new_copy(in godot_array src)
+ {
+ godotsharp_array_new_copy(out godot_array ret, src);
+ return ret;
+ }
+
+ public static godot_dictionary godotsharp_dictionary_new()
+ {
+ godotsharp_dictionary_new(out godot_dictionary ret);
+ return ret;
+ }
+
+ public static godot_dictionary godotsharp_dictionary_new_copy(in godot_dictionary src)
+ {
+ godotsharp_dictionary_new_copy(out godot_dictionary ret, src);
+ return ret;
+ }
+
+ public static godot_string_name godotsharp_string_name_new_from_string(string name)
+ {
+ using godot_string src = Marshaling.ConvertStringToNative(name);
+ godotsharp_string_name_new_from_string(out godot_string_name ret, src);
+ return ret;
+ }
+
+ public static godot_node_path godotsharp_node_path_new_from_string(string name)
+ {
+ using godot_string src = Marshaling.ConvertStringToNative(name);
+ godotsharp_node_path_new_from_string(out godot_node_path ret, src);
+ return ret;
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs
new file mode 100644
index 0000000000..422df74c23
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs
@@ -0,0 +1,20 @@
+using System.Runtime.CompilerServices;
+
+namespace Godot.NativeInterop
+{
+ // Our source generators will add trampolines methods that access variant arguments.
+ // This struct makes that possible without having to enable `AllowUnsafeBlocks` in game projects.
+
+ public unsafe ref struct NativeVariantPtrArgs
+ {
+ private godot_variant** _args;
+
+ internal NativeVariantPtrArgs(godot_variant** args) => _args = args;
+
+ public ref godot_variant this[int index]
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => ref *_args[index];
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs
new file mode 100644
index 0000000000..2b5bf2e142
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs
@@ -0,0 +1,976 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+
+namespace Godot.NativeInterop;
+
+internal static unsafe class VariantConversionCallbacks
+{
+ [SuppressMessage("ReSharper", "RedundantNameQualifier")]
+ internal static delegate* <in T, godot_variant> GetToVariantCallback<T>()
+ {
+ static godot_variant FromBool(in bool @bool) =>
+ VariantUtils.CreateFromBool(@bool);
+
+ static godot_variant FromChar(in char @char) =>
+ VariantUtils.CreateFromInt(@char);
+
+ static godot_variant FromInt8(in sbyte @int8) =>
+ VariantUtils.CreateFromInt(@int8);
+
+ static godot_variant FromInt16(in short @int16) =>
+ VariantUtils.CreateFromInt(@int16);
+
+ static godot_variant FromInt32(in int @int32) =>
+ VariantUtils.CreateFromInt(@int32);
+
+ static godot_variant FromInt64(in long @int64) =>
+ VariantUtils.CreateFromInt(@int64);
+
+ static godot_variant FromUInt8(in byte @uint8) =>
+ VariantUtils.CreateFromInt(@uint8);
+
+ static godot_variant FromUInt16(in ushort @uint16) =>
+ VariantUtils.CreateFromInt(@uint16);
+
+ static godot_variant FromUInt32(in uint @uint32) =>
+ VariantUtils.CreateFromInt(@uint32);
+
+ static godot_variant FromUInt64(in ulong @uint64) =>
+ VariantUtils.CreateFromInt(@uint64);
+
+ static godot_variant FromFloat(in float @float) =>
+ VariantUtils.CreateFromFloat(@float);
+
+ static godot_variant FromDouble(in double @double) =>
+ VariantUtils.CreateFromFloat(@double);
+
+ static godot_variant FromVector2(in Vector2 @vector2) =>
+ VariantUtils.CreateFromVector2(@vector2);
+
+ static godot_variant FromVector2I(in Vector2i vector2I) =>
+ VariantUtils.CreateFromVector2i(vector2I);
+
+ static godot_variant FromRect2(in Rect2 @rect2) =>
+ VariantUtils.CreateFromRect2(@rect2);
+
+ static godot_variant FromRect2I(in Rect2i rect2I) =>
+ VariantUtils.CreateFromRect2i(rect2I);
+
+ static godot_variant FromTransform2D(in Transform2D @transform2D) =>
+ VariantUtils.CreateFromTransform2D(@transform2D);
+
+ static godot_variant FromVector3(in Vector3 @vector3) =>
+ VariantUtils.CreateFromVector3(@vector3);
+
+ static godot_variant FromVector3I(in Vector3i vector3I) =>
+ VariantUtils.CreateFromVector3i(vector3I);
+
+ static godot_variant FromBasis(in Basis @basis) =>
+ VariantUtils.CreateFromBasis(@basis);
+
+ static godot_variant FromQuaternion(in Quaternion @quaternion) =>
+ VariantUtils.CreateFromQuaternion(@quaternion);
+
+ static godot_variant FromTransform3D(in Transform3D @transform3d) =>
+ VariantUtils.CreateFromTransform3D(@transform3d);
+
+ static godot_variant FromAabb(in AABB @aabb) =>
+ VariantUtils.CreateFromAABB(@aabb);
+
+ static godot_variant FromColor(in Color @color) =>
+ VariantUtils.CreateFromColor(@color);
+
+ static godot_variant FromPlane(in Plane @plane) =>
+ VariantUtils.CreateFromPlane(@plane);
+
+ static godot_variant FromCallable(in Callable @callable) =>
+ VariantUtils.CreateFromCallable(@callable);
+
+ static godot_variant FromSignalInfo(in SignalInfo @signalInfo) =>
+ VariantUtils.CreateFromSignalInfo(@signalInfo);
+
+ static godot_variant FromString(in string @string) =>
+ VariantUtils.CreateFromString(@string);
+
+ static godot_variant FromByteArray(in byte[] byteArray) =>
+ VariantUtils.CreateFromPackedByteArray(byteArray);
+
+ static godot_variant FromInt32Array(in int[] int32Array) =>
+ VariantUtils.CreateFromPackedInt32Array(int32Array);
+
+ static godot_variant FromInt64Array(in long[] int64Array) =>
+ VariantUtils.CreateFromPackedInt64Array(int64Array);
+
+ static godot_variant FromFloatArray(in float[] floatArray) =>
+ VariantUtils.CreateFromPackedFloat32Array(floatArray);
+
+ static godot_variant FromDoubleArray(in double[] doubleArray) =>
+ VariantUtils.CreateFromPackedFloat64Array(doubleArray);
+
+ static godot_variant FromStringArray(in string[] stringArray) =>
+ VariantUtils.CreateFromPackedStringArray(stringArray);
+
+ static godot_variant FromVector2Array(in Vector2[] vector2Array) =>
+ VariantUtils.CreateFromPackedVector2Array(vector2Array);
+
+ static godot_variant FromVector3Array(in Vector3[] vector3Array) =>
+ VariantUtils.CreateFromPackedVector3Array(vector3Array);
+
+ static godot_variant FromColorArray(in Color[] colorArray) =>
+ VariantUtils.CreateFromPackedColorArray(colorArray);
+
+ static godot_variant FromStringNameArray(in StringName[] stringNameArray) =>
+ VariantUtils.CreateFromSystemArrayOfStringName(stringNameArray);
+
+ static godot_variant FromNodePathArray(in NodePath[] nodePathArray) =>
+ VariantUtils.CreateFromSystemArrayOfNodePath(nodePathArray);
+
+ static godot_variant FromRidArray(in RID[] ridArray) =>
+ VariantUtils.CreateFromSystemArrayOfRID(ridArray);
+
+ static godot_variant FromGodotObject(in Godot.Object godotObject) =>
+ VariantUtils.CreateFromGodotObject(godotObject);
+
+ static godot_variant FromStringName(in StringName stringName) =>
+ VariantUtils.CreateFromStringName(stringName);
+
+ static godot_variant FromNodePath(in NodePath nodePath) =>
+ VariantUtils.CreateFromNodePath(nodePath);
+
+ static godot_variant FromRid(in RID rid) =>
+ VariantUtils.CreateFromRID(rid);
+
+ static godot_variant FromGodotDictionary(in Collections.Dictionary godotDictionary) =>
+ VariantUtils.CreateFromDictionary(godotDictionary);
+
+ static godot_variant FromGodotArray(in Collections.Array godotArray) =>
+ VariantUtils.CreateFromArray(godotArray);
+
+ static godot_variant FromVariant(in Variant variant) =>
+ NativeFuncs.godotsharp_variant_new_copy((godot_variant)variant.NativeVar);
+
+ var typeOfT = typeof(T);
+
+ if (typeOfT == typeof(bool))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in bool, godot_variant>)
+ &FromBool;
+ }
+
+ if (typeOfT == typeof(char))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in char, godot_variant>)
+ &FromChar;
+ }
+
+ if (typeOfT == typeof(sbyte))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in sbyte, godot_variant>)
+ &FromInt8;
+ }
+
+ if (typeOfT == typeof(short))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in short, godot_variant>)
+ &FromInt16;
+ }
+
+ if (typeOfT == typeof(int))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in int, godot_variant>)
+ &FromInt32;
+ }
+
+ if (typeOfT == typeof(long))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in long, godot_variant>)
+ &FromInt64;
+ }
+
+ if (typeOfT == typeof(byte))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in byte, godot_variant>)
+ &FromUInt8;
+ }
+
+ if (typeOfT == typeof(ushort))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in ushort, godot_variant>)
+ &FromUInt16;
+ }
+
+ if (typeOfT == typeof(uint))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in uint, godot_variant>)
+ &FromUInt32;
+ }
+
+ if (typeOfT == typeof(ulong))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in ulong, godot_variant>)
+ &FromUInt64;
+ }
+
+ if (typeOfT == typeof(float))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in float, godot_variant>)
+ &FromFloat;
+ }
+
+ if (typeOfT == typeof(double))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in double, godot_variant>)
+ &FromDouble;
+ }
+
+ if (typeOfT == typeof(Vector2))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Vector2, godot_variant>)
+ &FromVector2;
+ }
+
+ if (typeOfT == typeof(Vector2i))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Vector2i, godot_variant>)
+ &FromVector2I;
+ }
+
+ if (typeOfT == typeof(Rect2))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Rect2, godot_variant>)
+ &FromRect2;
+ }
+
+ if (typeOfT == typeof(Rect2i))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Rect2i, godot_variant>)
+ &FromRect2I;
+ }
+
+ if (typeOfT == typeof(Transform2D))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Transform2D, godot_variant>)
+ &FromTransform2D;
+ }
+
+ if (typeOfT == typeof(Vector3))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Vector3, godot_variant>)
+ &FromVector3;
+ }
+
+ if (typeOfT == typeof(Vector3i))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Vector3i, godot_variant>)
+ &FromVector3I;
+ }
+
+ if (typeOfT == typeof(Basis))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Basis, godot_variant>)
+ &FromBasis;
+ }
+
+ if (typeOfT == typeof(Quaternion))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Quaternion, godot_variant>)
+ &FromQuaternion;
+ }
+
+ if (typeOfT == typeof(Transform3D))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Transform3D, godot_variant>)
+ &FromTransform3D;
+ }
+
+ if (typeOfT == typeof(AABB))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in AABB, godot_variant>)
+ &FromAabb;
+ }
+
+ if (typeOfT == typeof(Color))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Color, godot_variant>)
+ &FromColor;
+ }
+
+ if (typeOfT == typeof(Plane))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Plane, godot_variant>)
+ &FromPlane;
+ }
+
+ if (typeOfT == typeof(Callable))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Callable, godot_variant>)
+ &FromCallable;
+ }
+
+ if (typeOfT == typeof(SignalInfo))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in SignalInfo, godot_variant>)
+ &FromSignalInfo;
+ }
+
+ if (typeOfT.IsEnum)
+ {
+ var enumUnderlyingType = typeOfT.GetEnumUnderlyingType();
+
+ switch (Type.GetTypeCode(enumUnderlyingType))
+ {
+ case TypeCode.SByte:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in sbyte, godot_variant>)
+ &FromInt8;
+ }
+ case TypeCode.Int16:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in short, godot_variant>)
+ &FromInt16;
+ }
+ case TypeCode.Int32:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in int, godot_variant>)
+ &FromInt32;
+ }
+ case TypeCode.Int64:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in long, godot_variant>)
+ &FromInt64;
+ }
+ case TypeCode.Byte:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in byte, godot_variant>)
+ &FromUInt8;
+ }
+ case TypeCode.UInt16:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in ushort, godot_variant>)
+ &FromUInt16;
+ }
+ case TypeCode.UInt32:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in uint, godot_variant>)
+ &FromUInt32;
+ }
+ case TypeCode.UInt64:
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in ulong, godot_variant>)
+ &FromUInt64;
+ }
+ default:
+ return null;
+ }
+ }
+
+ if (typeOfT == typeof(string))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in string, godot_variant>)
+ &FromString;
+ }
+
+ if (typeOfT == typeof(byte[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in byte[], godot_variant>)
+ &FromByteArray;
+ }
+
+ if (typeOfT == typeof(int[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in int[], godot_variant>)
+ &FromInt32Array;
+ }
+
+ if (typeOfT == typeof(long[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in long[], godot_variant>)
+ &FromInt64Array;
+ }
+
+ if (typeOfT == typeof(float[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in float[], godot_variant>)
+ &FromFloatArray;
+ }
+
+ if (typeOfT == typeof(double[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in double[], godot_variant>)
+ &FromDoubleArray;
+ }
+
+ if (typeOfT == typeof(string[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in string[], godot_variant>)
+ &FromStringArray;
+ }
+
+ if (typeOfT == typeof(Vector2[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Vector2[], godot_variant>)
+ &FromVector2Array;
+ }
+
+ if (typeOfT == typeof(Vector3[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Vector3[], godot_variant>)
+ &FromVector3Array;
+ }
+
+ if (typeOfT == typeof(Color[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Color[], godot_variant>)
+ &FromColorArray;
+ }
+
+ if (typeOfT == typeof(StringName[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in StringName[], godot_variant>)
+ &FromStringNameArray;
+ }
+
+ if (typeOfT == typeof(NodePath[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in NodePath[], godot_variant>)
+ &FromNodePathArray;
+ }
+
+ if (typeOfT == typeof(RID[]))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in RID[], godot_variant>)
+ &FromRidArray;
+ }
+
+ if (typeof(Godot.Object).IsAssignableFrom(typeOfT))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Godot.Object, godot_variant>)
+ &FromGodotObject;
+ }
+
+ if (typeOfT == typeof(StringName))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in StringName, godot_variant>)
+ &FromStringName;
+ }
+
+ if (typeOfT == typeof(NodePath))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in NodePath, godot_variant>)
+ &FromNodePath;
+ }
+
+ if (typeOfT == typeof(RID))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in RID, godot_variant>)
+ &FromRid;
+ }
+
+ if (typeOfT == typeof(Godot.Collections.Dictionary))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Godot.Collections.Dictionary, godot_variant>)
+ &FromGodotDictionary;
+ }
+
+ if (typeOfT == typeof(Godot.Collections.Array))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Godot.Collections.Array, godot_variant>)
+ &FromGodotArray;
+ }
+
+ if (typeOfT == typeof(Variant))
+ {
+ return (delegate* <in T, godot_variant>)(delegate* <in Variant, godot_variant>)
+ &FromVariant;
+ }
+
+ return null;
+ }
+
+ [SuppressMessage("ReSharper", "RedundantNameQualifier")]
+ internal static delegate* <in godot_variant, T> GetToManagedCallback<T>()
+ {
+ static bool ToBool(in godot_variant variant) =>
+ VariantUtils.ConvertToBool(variant);
+
+ static char ToChar(in godot_variant variant) =>
+ VariantUtils.ConvertToChar(variant);
+
+ static sbyte ToInt8(in godot_variant variant) =>
+ VariantUtils.ConvertToInt8(variant);
+
+ static short ToInt16(in godot_variant variant) =>
+ VariantUtils.ConvertToInt16(variant);
+
+ static int ToInt32(in godot_variant variant) =>
+ VariantUtils.ConvertToInt32(variant);
+
+ static long ToInt64(in godot_variant variant) =>
+ VariantUtils.ConvertToInt64(variant);
+
+ static byte ToUInt8(in godot_variant variant) =>
+ VariantUtils.ConvertToUInt8(variant);
+
+ static ushort ToUInt16(in godot_variant variant) =>
+ VariantUtils.ConvertToUInt16(variant);
+
+ static uint ToUInt32(in godot_variant variant) =>
+ VariantUtils.ConvertToUInt32(variant);
+
+ static ulong ToUInt64(in godot_variant variant) =>
+ VariantUtils.ConvertToUInt64(variant);
+
+ static float ToFloat(in godot_variant variant) =>
+ VariantUtils.ConvertToFloat32(variant);
+
+ static double ToDouble(in godot_variant variant) =>
+ VariantUtils.ConvertToFloat64(variant);
+
+ static Vector2 ToVector2(in godot_variant variant) =>
+ VariantUtils.ConvertToVector2(variant);
+
+ static Vector2i ToVector2I(in godot_variant variant) =>
+ VariantUtils.ConvertToVector2i(variant);
+
+ static Rect2 ToRect2(in godot_variant variant) =>
+ VariantUtils.ConvertToRect2(variant);
+
+ static Rect2i ToRect2I(in godot_variant variant) =>
+ VariantUtils.ConvertToRect2i(variant);
+
+ static Transform2D ToTransform2D(in godot_variant variant) =>
+ VariantUtils.ConvertToTransform2D(variant);
+
+ static Vector3 ToVector3(in godot_variant variant) =>
+ VariantUtils.ConvertToVector3(variant);
+
+ static Vector3i ToVector3I(in godot_variant variant) =>
+ VariantUtils.ConvertToVector3i(variant);
+
+ static Basis ToBasis(in godot_variant variant) =>
+ VariantUtils.ConvertToBasis(variant);
+
+ static Quaternion ToQuaternion(in godot_variant variant) =>
+ VariantUtils.ConvertToQuaternion(variant);
+
+ static Transform3D ToTransform3D(in godot_variant variant) =>
+ VariantUtils.ConvertToTransform3D(variant);
+
+ static AABB ToAabb(in godot_variant variant) =>
+ VariantUtils.ConvertToAABB(variant);
+
+ static Color ToColor(in godot_variant variant) =>
+ VariantUtils.ConvertToColor(variant);
+
+ static Plane ToPlane(in godot_variant variant) =>
+ VariantUtils.ConvertToPlane(variant);
+
+ static Callable ToCallable(in godot_variant variant) =>
+ VariantUtils.ConvertToCallableManaged(variant);
+
+ static SignalInfo ToSignalInfo(in godot_variant variant) =>
+ VariantUtils.ConvertToSignalInfo(variant);
+
+ static string ToString(in godot_variant variant) =>
+ VariantUtils.ConvertToStringObject(variant);
+
+ static byte[] ToByteArray(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedByteArrayToSystemArray(variant);
+
+ static int[] ToInt32Array(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedInt32ArrayToSystemArray(variant);
+
+ static long[] ToInt64Array(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedInt64ArrayToSystemArray(variant);
+
+ static float[] ToFloatArray(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedFloat32ArrayToSystemArray(variant);
+
+ static double[] ToDoubleArray(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedFloat64ArrayToSystemArray(variant);
+
+ static string[] ToStringArray(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedStringArrayToSystemArray(variant);
+
+ static Vector2[] ToVector2Array(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedVector2ArrayToSystemArray(variant);
+
+ static Vector3[] ToVector3Array(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedVector3ArrayToSystemArray(variant);
+
+ static Color[] ToColorArray(in godot_variant variant) =>
+ VariantUtils.ConvertAsPackedColorArrayToSystemArray(variant);
+
+ static StringName[] ToStringNameArray(in godot_variant variant) =>
+ VariantUtils.ConvertToSystemArrayOfStringName(variant);
+
+ static NodePath[] ToNodePathArray(in godot_variant variant) =>
+ VariantUtils.ConvertToSystemArrayOfNodePath(variant);
+
+ static RID[] ToRidArray(in godot_variant variant) =>
+ VariantUtils.ConvertToSystemArrayOfRID(variant);
+
+ static Godot.Object ToGodotObject(in godot_variant variant) =>
+ VariantUtils.ConvertToGodotObject(variant);
+
+ static StringName ToStringName(in godot_variant variant) =>
+ VariantUtils.ConvertToStringNameObject(variant);
+
+ static NodePath ToNodePath(in godot_variant variant) =>
+ VariantUtils.ConvertToNodePathObject(variant);
+
+ static RID ToRid(in godot_variant variant) =>
+ VariantUtils.ConvertToRID(variant);
+
+ static Collections.Dictionary ToGodotDictionary(in godot_variant variant) =>
+ VariantUtils.ConvertToDictionaryObject(variant);
+
+ static Collections.Array ToGodotArray(in godot_variant variant) =>
+ VariantUtils.ConvertToArrayObject(variant);
+
+ static Variant ToVariant(in godot_variant variant) =>
+ Variant.CreateCopyingBorrowed(variant);
+
+ var typeOfT = typeof(T);
+
+ // ReSharper disable RedundantCast
+ // Rider is being stupid here. These casts are definitely needed. We get build errors without them.
+
+ if (typeOfT == typeof(bool))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, bool>)
+ &ToBool;
+ }
+
+ if (typeOfT == typeof(char))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, char>)
+ &ToChar;
+ }
+
+ if (typeOfT == typeof(sbyte))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, sbyte>)
+ &ToInt8;
+ }
+
+ if (typeOfT == typeof(short))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, short>)
+ &ToInt16;
+ }
+
+ if (typeOfT == typeof(int))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, int>)
+ &ToInt32;
+ }
+
+ if (typeOfT == typeof(long))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, long>)
+ &ToInt64;
+ }
+
+ if (typeOfT == typeof(byte))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, byte>)
+ &ToUInt8;
+ }
+
+ if (typeOfT == typeof(ushort))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, ushort>)
+ &ToUInt16;
+ }
+
+ if (typeOfT == typeof(uint))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, uint>)
+ &ToUInt32;
+ }
+
+ if (typeOfT == typeof(ulong))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, ulong>)
+ &ToUInt64;
+ }
+
+ if (typeOfT == typeof(float))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, float>)
+ &ToFloat;
+ }
+
+ if (typeOfT == typeof(double))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, double>)
+ &ToDouble;
+ }
+
+ if (typeOfT == typeof(Vector2))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Vector2>)
+ &ToVector2;
+ }
+
+ if (typeOfT == typeof(Vector2i))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Vector2i>)
+ &ToVector2I;
+ }
+
+ if (typeOfT == typeof(Rect2))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Rect2>)
+ &ToRect2;
+ }
+
+ if (typeOfT == typeof(Rect2i))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Rect2i>)
+ &ToRect2I;
+ }
+
+ if (typeOfT == typeof(Transform2D))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Transform2D>)
+ &ToTransform2D;
+ }
+
+ if (typeOfT == typeof(Vector3))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Vector3>)
+ &ToVector3;
+ }
+
+ if (typeOfT == typeof(Vector3i))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Vector3i>)
+ &ToVector3I;
+ }
+
+ if (typeOfT == typeof(Basis))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Basis>)
+ &ToBasis;
+ }
+
+ if (typeOfT == typeof(Quaternion))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Quaternion>)
+ &ToQuaternion;
+ }
+
+ if (typeOfT == typeof(Transform3D))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Transform3D>)
+ &ToTransform3D;
+ }
+
+ if (typeOfT == typeof(AABB))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, AABB>)
+ &ToAabb;
+ }
+
+ if (typeOfT == typeof(Color))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Color>)
+ &ToColor;
+ }
+
+ if (typeOfT == typeof(Plane))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Plane>)
+ &ToPlane;
+ }
+
+ if (typeOfT == typeof(Callable))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Callable>)
+ &ToCallable;
+ }
+
+ if (typeOfT == typeof(SignalInfo))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, SignalInfo>)
+ &ToSignalInfo;
+ }
+
+ if (typeOfT.IsEnum)
+ {
+ var enumUnderlyingType = typeOfT.GetEnumUnderlyingType();
+
+ switch (Type.GetTypeCode(enumUnderlyingType))
+ {
+ case TypeCode.SByte:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, sbyte>)
+ &ToInt8;
+ }
+ case TypeCode.Int16:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, short>)
+ &ToInt16;
+ }
+ case TypeCode.Int32:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, int>)
+ &ToInt32;
+ }
+ case TypeCode.Int64:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, long>)
+ &ToInt64;
+ }
+ case TypeCode.Byte:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, byte>)
+ &ToUInt8;
+ }
+ case TypeCode.UInt16:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, ushort>)
+ &ToUInt16;
+ }
+ case TypeCode.UInt32:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, uint>)
+ &ToUInt32;
+ }
+ case TypeCode.UInt64:
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, ulong>)
+ &ToUInt64;
+ }
+ default:
+ return null;
+ }
+ }
+
+ if (typeOfT == typeof(string))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, string>)
+ &ToString;
+ }
+
+ if (typeOfT == typeof(byte[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, byte[]>)
+ &ToByteArray;
+ }
+
+ if (typeOfT == typeof(int[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, int[]>)
+ &ToInt32Array;
+ }
+
+ if (typeOfT == typeof(long[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, long[]>)
+ &ToInt64Array;
+ }
+
+ if (typeOfT == typeof(float[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, float[]>)
+ &ToFloatArray;
+ }
+
+ if (typeOfT == typeof(double[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, double[]>)
+ &ToDoubleArray;
+ }
+
+ if (typeOfT == typeof(string[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, string[]>)
+ &ToStringArray;
+ }
+
+ if (typeOfT == typeof(Vector2[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Vector2[]>)
+ &ToVector2Array;
+ }
+
+ if (typeOfT == typeof(Vector3[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Vector3[]>)
+ &ToVector3Array;
+ }
+
+ if (typeOfT == typeof(Color[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Color[]>)
+ &ToColorArray;
+ }
+
+ if (typeOfT == typeof(StringName[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, StringName[]>)
+ &ToStringNameArray;
+ }
+
+ if (typeOfT == typeof(NodePath[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, NodePath[]>)
+ &ToNodePathArray;
+ }
+
+ if (typeOfT == typeof(RID[]))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, RID[]>)
+ &ToRidArray;
+ }
+
+ if (typeof(Godot.Object).IsAssignableFrom(typeOfT))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Godot.Object>)
+ &ToGodotObject;
+ }
+
+ if (typeOfT == typeof(StringName))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, StringName>)
+ &ToStringName;
+ }
+
+ if (typeOfT == typeof(NodePath))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, NodePath>)
+ &ToNodePath;
+ }
+
+ if (typeOfT == typeof(RID))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, RID>)
+ &ToRid;
+ }
+
+ if (typeOfT == typeof(Godot.Collections.Dictionary))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Godot.Collections.Dictionary>)
+ &ToGodotDictionary;
+ }
+
+ if (typeOfT == typeof(Godot.Collections.Array))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Godot.Collections.Array>)
+ &ToGodotArray;
+ }
+
+ if (typeOfT == typeof(Variant))
+ {
+ return (delegate* <in godot_variant, T>)(delegate* <in godot_variant, Variant>)
+ &ToVariant;
+ }
+
+ // ReSharper restore RedundantCast
+
+ return null;
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantSpanHelpers.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantSpanHelpers.cs
new file mode 100644
index 0000000000..46f31bbf4e
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantSpanHelpers.cs
@@ -0,0 +1,33 @@
+using System;
+
+namespace Godot.NativeInterop
+{
+ internal readonly ref struct VariantSpanDisposer
+ {
+ private readonly Span<godot_variant.movable> _variantSpan;
+
+ // IMPORTANT: The span element must be default initialized.
+ // Make sure call Clear() on the span if it was created with stackalloc.
+ public VariantSpanDisposer(Span<godot_variant.movable> variantSpan)
+ {
+ _variantSpan = variantSpan;
+ }
+
+ public void Dispose()
+ {
+ for (int i = 0; i < _variantSpan.Length; i++)
+ _variantSpan[i].DangerousSelfRef.Dispose();
+ }
+ }
+
+ internal static class VariantSpanExtensions
+ {
+ // Used to make sure we always initialize the span values to the default,
+ // as we need that in order to safely dispose all elements after.
+ public static Span<godot_variant.movable> Cleared(this Span<godot_variant.movable> span)
+ {
+ span.Clear();
+ return span;
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs
new file mode 100644
index 0000000000..491ccf904e
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs
@@ -0,0 +1,611 @@
+using System;
+using System.Runtime.CompilerServices;
+using Godot.Collections;
+
+// ReSharper disable InconsistentNaming
+
+#nullable enable
+
+namespace Godot.NativeInterop
+{
+ public static class VariantUtils
+ {
+ public static godot_variant CreateFromRID(RID from)
+ => new() { Type = Variant.Type.Rid, RID = from };
+
+ public static godot_variant CreateFromBool(bool from)
+ => new() { Type = Variant.Type.Bool, Bool = from.ToGodotBool() };
+
+ public static godot_variant CreateFromInt(long from)
+ => new() { Type = Variant.Type.Int, Int = from };
+
+ public static godot_variant CreateFromInt(ulong from)
+ => new() { Type = Variant.Type.Int, Int = (long)from };
+
+ public static godot_variant CreateFromFloat(double from)
+ => new() { Type = Variant.Type.Float, Float = from };
+
+ public static godot_variant CreateFromVector2(Vector2 from)
+ => new() { Type = Variant.Type.Vector2, Vector2 = from };
+
+ public static godot_variant CreateFromVector2i(Vector2i from)
+ => new() { Type = Variant.Type.Vector2i, Vector2i = from };
+
+ public static godot_variant CreateFromVector3(Vector3 from)
+ => new() { Type = Variant.Type.Vector3, Vector3 = from };
+
+ public static godot_variant CreateFromVector3i(Vector3i from)
+ => new() { Type = Variant.Type.Vector3i, Vector3i = from };
+
+ public static godot_variant CreateFromRect2(Rect2 from)
+ => new() { Type = Variant.Type.Rect2, Rect2 = from };
+
+ public static godot_variant CreateFromRect2i(Rect2i from)
+ => new() { Type = Variant.Type.Rect2i, Rect2i = from };
+
+ public static godot_variant CreateFromQuaternion(Quaternion from)
+ => new() { Type = Variant.Type.Quaternion, Quaternion = from };
+
+ public static godot_variant CreateFromColor(Color from)
+ => new() { Type = Variant.Type.Color, Color = from };
+
+ public static godot_variant CreateFromPlane(Plane from)
+ => new() { Type = Variant.Type.Plane, Plane = from };
+
+ public static godot_variant CreateFromTransform2D(Transform2D from)
+ {
+ NativeFuncs.godotsharp_variant_new_transform2d(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromVector4(Vector4 from)
+ {
+ NativeFuncs.godotsharp_variant_new_vector4(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromVector4i(Vector4i from)
+ {
+ NativeFuncs.godotsharp_variant_new_vector4i(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromBasis(Basis from)
+ {
+ NativeFuncs.godotsharp_variant_new_basis(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromTransform3D(Transform3D from)
+ {
+ NativeFuncs.godotsharp_variant_new_transform3d(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromProjection(Projection from)
+ {
+ NativeFuncs.godotsharp_variant_new_projection(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromAABB(AABB from)
+ {
+ NativeFuncs.godotsharp_variant_new_aabb(out godot_variant ret, from);
+ return ret;
+ }
+
+ // Explicit name to make it very clear
+ public static godot_variant CreateFromCallableTakingOwnershipOfDisposableValue(godot_callable from)
+ => new() { Type = Variant.Type.Callable, Callable = from };
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromCallable(Callable from)
+ => CreateFromCallableTakingOwnershipOfDisposableValue(
+ Marshaling.ConvertCallableToNative(from));
+
+ // Explicit name to make it very clear
+ public static godot_variant CreateFromSignalTakingOwnershipOfDisposableValue(godot_signal from)
+ => new() { Type = Variant.Type.Signal, Signal = from };
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromSignalInfo(SignalInfo from)
+ => CreateFromSignalTakingOwnershipOfDisposableValue(
+ Marshaling.ConvertSignalToNative(from));
+
+ // Explicit name to make it very clear
+ public static godot_variant CreateFromStringTakingOwnershipOfDisposableValue(godot_string from)
+ => new() { Type = Variant.Type.String, String = from };
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromString(string? from)
+ => CreateFromStringTakingOwnershipOfDisposableValue(Marshaling.ConvertStringToNative(from));
+
+ public static godot_variant CreateFromPackedByteArray(in godot_packed_byte_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_byte_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedInt32Array(in godot_packed_int32_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_int32_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedInt64Array(in godot_packed_int64_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_int64_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedFloat32Array(in godot_packed_float32_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_float32_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedFloat64Array(in godot_packed_float64_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_float64_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedStringArray(in godot_packed_string_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_string_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedVector2Array(in godot_packed_vector2_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_vector2_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedVector3Array(in godot_packed_vector3_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_vector3_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ public static godot_variant CreateFromPackedColorArray(in godot_packed_color_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_packed_color_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedByteArray(Span<byte> from)
+ => CreateFromPackedByteArray(Marshaling.ConvertSystemArrayToNativePackedByteArray(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedInt32Array(Span<int> from)
+ => CreateFromPackedInt32Array(Marshaling.ConvertSystemArrayToNativePackedInt32Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedInt64Array(Span<long> from)
+ => CreateFromPackedInt64Array(Marshaling.ConvertSystemArrayToNativePackedInt64Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedFloat32Array(Span<float> from)
+ => CreateFromPackedFloat32Array(Marshaling.ConvertSystemArrayToNativePackedFloat32Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedFloat64Array(Span<double> from)
+ => CreateFromPackedFloat64Array(Marshaling.ConvertSystemArrayToNativePackedFloat64Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedStringArray(Span<string> from)
+ => CreateFromPackedStringArray(Marshaling.ConvertSystemArrayToNativePackedStringArray(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedVector2Array(Span<Vector2> from)
+ => CreateFromPackedVector2Array(Marshaling.ConvertSystemArrayToNativePackedVector2Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedVector3Array(Span<Vector3> from)
+ => CreateFromPackedVector3Array(Marshaling.ConvertSystemArrayToNativePackedVector3Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromPackedColorArray(Span<Color> from)
+ => CreateFromPackedColorArray(Marshaling.ConvertSystemArrayToNativePackedColorArray(from));
+
+ public static godot_variant CreateFromSystemArrayOfStringName(Span<StringName> from)
+ => CreateFromArray(new Collections.Array(from));
+
+ public static godot_variant CreateFromSystemArrayOfNodePath(Span<NodePath> from)
+ => CreateFromArray(new Collections.Array(from));
+
+ public static godot_variant CreateFromSystemArrayOfRID(Span<RID> from)
+ => CreateFromArray(new Collections.Array(from));
+
+ // ReSharper disable once RedundantNameQualifier
+ public static godot_variant CreateFromSystemArrayOfGodotObject(Godot.Object[]? from)
+ {
+ if (from == null)
+ return default; // Nil
+ using var fromGodot = new Collections.Array(from);
+ return CreateFromArray((godot_array)fromGodot.NativeValue);
+ }
+
+ public static godot_variant CreateFromArray(godot_array from)
+ {
+ NativeFuncs.godotsharp_variant_new_array(out godot_variant ret, from);
+ return ret;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromArray(Collections.Array? from)
+ => from != null ? CreateFromArray((godot_array)from.NativeValue) : default;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromArray<T>(Array<T>? from)
+ => from != null ? CreateFromArray((godot_array)((Collections.Array)from).NativeValue) : default;
+
+ public static godot_variant CreateFromDictionary(godot_dictionary from)
+ {
+ NativeFuncs.godotsharp_variant_new_dictionary(out godot_variant ret, from);
+ return ret;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromDictionary(Dictionary? from)
+ => from != null ? CreateFromDictionary((godot_dictionary)from.NativeValue) : default;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromDictionary<TKey, TValue>(Dictionary<TKey, TValue>? from)
+ => from != null ? CreateFromDictionary((godot_dictionary)((Dictionary)from).NativeValue) : default;
+
+ public static godot_variant CreateFromStringName(godot_string_name from)
+ {
+ NativeFuncs.godotsharp_variant_new_string_name(out godot_variant ret, from);
+ return ret;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromStringName(StringName? from)
+ => from != null ? CreateFromStringName((godot_string_name)from.NativeValue) : default;
+
+ public static godot_variant CreateFromNodePath(godot_node_path from)
+ {
+ NativeFuncs.godotsharp_variant_new_node_path(out godot_variant ret, from);
+ return ret;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_variant CreateFromNodePath(NodePath? from)
+ => from != null ? CreateFromNodePath((godot_node_path)from.NativeValue) : default;
+
+ public static godot_variant CreateFromGodotObjectPtr(IntPtr from)
+ {
+ if (from == IntPtr.Zero)
+ return new godot_variant();
+ NativeFuncs.godotsharp_variant_new_object(out godot_variant ret, from);
+ return ret;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ // ReSharper disable once RedundantNameQualifier
+ public static godot_variant CreateFromGodotObject(Godot.Object? from)
+ => from != null ? CreateFromGodotObjectPtr(Object.GetPtr(from)) : default;
+
+ // We avoid the internal call if the stored type is the same we want.
+
+ public static bool ConvertToBool(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Bool ?
+ p_var.Bool.ToBool() :
+ NativeFuncs.godotsharp_variant_as_bool(p_var).ToBool();
+
+ public static char ConvertToChar(in godot_variant p_var)
+ => (char)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static sbyte ConvertToInt8(in godot_variant p_var)
+ => (sbyte)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static short ConvertToInt16(in godot_variant p_var)
+ => (short)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static int ConvertToInt32(in godot_variant p_var)
+ => (int)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static long ConvertToInt64(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Int ? p_var.Int : NativeFuncs.godotsharp_variant_as_int(p_var);
+
+ public static byte ConvertToUInt8(in godot_variant p_var)
+ => (byte)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static ushort ConvertToUInt16(in godot_variant p_var)
+ => (ushort)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static uint ConvertToUInt32(in godot_variant p_var)
+ => (uint)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static ulong ConvertToUInt64(in godot_variant p_var)
+ => (ulong)(p_var.Type == Variant.Type.Int ?
+ p_var.Int :
+ NativeFuncs.godotsharp_variant_as_int(p_var));
+
+ public static float ConvertToFloat32(in godot_variant p_var)
+ => (float)(p_var.Type == Variant.Type.Float ?
+ p_var.Float :
+ NativeFuncs.godotsharp_variant_as_float(p_var));
+
+ public static double ConvertToFloat64(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Float ?
+ p_var.Float :
+ NativeFuncs.godotsharp_variant_as_float(p_var);
+
+ public static Vector2 ConvertToVector2(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Vector2 ?
+ p_var.Vector2 :
+ NativeFuncs.godotsharp_variant_as_vector2(p_var);
+
+ public static Vector2i ConvertToVector2i(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Vector2i ?
+ p_var.Vector2i :
+ NativeFuncs.godotsharp_variant_as_vector2i(p_var);
+
+ public static Rect2 ConvertToRect2(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Rect2 ?
+ p_var.Rect2 :
+ NativeFuncs.godotsharp_variant_as_rect2(p_var);
+
+ public static Rect2i ConvertToRect2i(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Rect2i ?
+ p_var.Rect2i :
+ NativeFuncs.godotsharp_variant_as_rect2i(p_var);
+
+ public static unsafe Transform2D ConvertToTransform2D(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Transform2d ?
+ *p_var.Transform2D :
+ NativeFuncs.godotsharp_variant_as_transform2d(p_var);
+
+ public static Vector3 ConvertToVector3(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Vector3 ?
+ p_var.Vector3 :
+ NativeFuncs.godotsharp_variant_as_vector3(p_var);
+
+ public static Vector3i ConvertToVector3i(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Vector3i ?
+ p_var.Vector3i :
+ NativeFuncs.godotsharp_variant_as_vector3i(p_var);
+
+ public static unsafe Vector4 ConvertToVector4(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Vector4 ?
+ *p_var.Vector4 :
+ NativeFuncs.godotsharp_variant_as_vector4(p_var);
+
+ public static unsafe Vector4i ConvertToVector4i(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Vector4i ?
+ *p_var.Vector4i :
+ NativeFuncs.godotsharp_variant_as_vector4i(p_var);
+
+ public static unsafe Basis ConvertToBasis(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Basis ?
+ *p_var.Basis :
+ NativeFuncs.godotsharp_variant_as_basis(p_var);
+
+ public static Quaternion ConvertToQuaternion(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Quaternion ?
+ p_var.Quaternion :
+ NativeFuncs.godotsharp_variant_as_quaternion(p_var);
+
+ public static unsafe Transform3D ConvertToTransform3D(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Transform3d ?
+ *p_var.Transform3D :
+ NativeFuncs.godotsharp_variant_as_transform3d(p_var);
+
+ public static unsafe Projection ConvertToProjection(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Projection ?
+ *p_var.Projection :
+ NativeFuncs.godotsharp_variant_as_projection(p_var);
+
+ public static unsafe AABB ConvertToAABB(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Aabb ?
+ *p_var.AABB :
+ NativeFuncs.godotsharp_variant_as_aabb(p_var);
+
+ public static Color ConvertToColor(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Color ?
+ p_var.Color :
+ NativeFuncs.godotsharp_variant_as_color(p_var);
+
+ public static Plane ConvertToPlane(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Plane ?
+ p_var.Plane :
+ NativeFuncs.godotsharp_variant_as_plane(p_var);
+
+ public static RID ConvertToRID(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Rid ?
+ p_var.RID :
+ NativeFuncs.godotsharp_variant_as_rid(p_var);
+
+ public static IntPtr ConvertToGodotObjectPtr(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Object ? p_var.Object : IntPtr.Zero;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ // ReSharper disable once RedundantNameQualifier
+ public static Godot.Object ConvertToGodotObject(in godot_variant p_var)
+ => InteropUtils.UnmanagedGetManaged(ConvertToGodotObjectPtr(p_var));
+
+ public static string ConvertToStringObject(in godot_variant p_var)
+ {
+ switch (p_var.Type)
+ {
+ case Variant.Type.Nil:
+ return ""; // Otherwise, Variant -> String would return the string "Null"
+ case Variant.Type.String:
+ {
+ // We avoid the internal call if the stored type is the same we want.
+ return Marshaling.ConvertStringToManaged(p_var.String);
+ }
+ default:
+ {
+ using godot_string godotString = NativeFuncs.godotsharp_variant_as_string(p_var);
+ return Marshaling.ConvertStringToManaged(godotString);
+ }
+ }
+ }
+
+ public static godot_string_name ConvertToStringName(in godot_variant p_var)
+ => p_var.Type == Variant.Type.StringName ?
+ NativeFuncs.godotsharp_string_name_new_copy(p_var.StringName) :
+ NativeFuncs.godotsharp_variant_as_string_name(p_var);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static StringName ConvertToStringNameObject(in godot_variant p_var)
+ => StringName.CreateTakingOwnershipOfDisposableValue(ConvertToStringName(p_var));
+
+ public static godot_node_path ConvertToNodePath(in godot_variant p_var)
+ => p_var.Type == Variant.Type.NodePath ?
+ NativeFuncs.godotsharp_node_path_new_copy(p_var.NodePath) :
+ NativeFuncs.godotsharp_variant_as_node_path(p_var);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static NodePath ConvertToNodePathObject(in godot_variant p_var)
+ => NodePath.CreateTakingOwnershipOfDisposableValue(ConvertToNodePath(p_var));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_callable ConvertToCallable(in godot_variant p_var)
+ => NativeFuncs.godotsharp_variant_as_callable(p_var);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Callable ConvertToCallableManaged(in godot_variant p_var)
+ => Marshaling.ConvertCallableToManaged(ConvertToCallable(p_var));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static godot_signal ConvertToSignal(in godot_variant p_var)
+ => NativeFuncs.godotsharp_variant_as_signal(p_var);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static SignalInfo ConvertToSignalInfo(in godot_variant p_var)
+ => Marshaling.ConvertSignalToManaged(ConvertToSignal(p_var));
+
+ public static godot_array ConvertToArray(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Array ?
+ NativeFuncs.godotsharp_array_new_copy(p_var.Array) :
+ NativeFuncs.godotsharp_variant_as_array(p_var);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Collections.Array ConvertToArrayObject(in godot_variant p_var)
+ => Collections.Array.CreateTakingOwnershipOfDisposableValue(ConvertToArray(p_var));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Array<T> ConvertToArrayObject<T>(in godot_variant p_var)
+ => Array<T>.CreateTakingOwnershipOfDisposableValue(ConvertToArray(p_var));
+
+ public static godot_dictionary ConvertToDictionary(in godot_variant p_var)
+ => p_var.Type == Variant.Type.Dictionary ?
+ NativeFuncs.godotsharp_dictionary_new_copy(p_var.Dictionary) :
+ NativeFuncs.godotsharp_variant_as_dictionary(p_var);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Dictionary ConvertToDictionaryObject(in godot_variant p_var)
+ => Dictionary.CreateTakingOwnershipOfDisposableValue(ConvertToDictionary(p_var));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Dictionary<TKey, TValue> ConvertToDictionaryObject<TKey, TValue>(in godot_variant p_var)
+ => Dictionary<TKey, TValue>.CreateTakingOwnershipOfDisposableValue(ConvertToDictionary(p_var));
+
+ public static byte[] ConvertAsPackedByteArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_byte_array(p_var);
+ return Marshaling.ConvertNativePackedByteArrayToSystemArray(packedArray);
+ }
+
+ public static int[] ConvertAsPackedInt32ArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_int32_array(p_var);
+ return Marshaling.ConvertNativePackedInt32ArrayToSystemArray(packedArray);
+ }
+
+ public static long[] ConvertAsPackedInt64ArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_int64_array(p_var);
+ return Marshaling.ConvertNativePackedInt64ArrayToSystemArray(packedArray);
+ }
+
+ public static float[] ConvertAsPackedFloat32ArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_float32_array(p_var);
+ return Marshaling.ConvertNativePackedFloat32ArrayToSystemArray(packedArray);
+ }
+
+ public static double[] ConvertAsPackedFloat64ArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_float64_array(p_var);
+ return Marshaling.ConvertNativePackedFloat64ArrayToSystemArray(packedArray);
+ }
+
+ public static string[] ConvertAsPackedStringArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_string_array(p_var);
+ return Marshaling.ConvertNativePackedStringArrayToSystemArray(packedArray);
+ }
+
+ public static Vector2[] ConvertAsPackedVector2ArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_vector2_array(p_var);
+ return Marshaling.ConvertNativePackedVector2ArrayToSystemArray(packedArray);
+ }
+
+ public static Vector3[] ConvertAsPackedVector3ArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_vector3_array(p_var);
+ return Marshaling.ConvertNativePackedVector3ArrayToSystemArray(packedArray);
+ }
+
+ public static Color[] ConvertAsPackedColorArrayToSystemArray(in godot_variant p_var)
+ {
+ using var packedArray = NativeFuncs.godotsharp_variant_as_packed_color_array(p_var);
+ return Marshaling.ConvertNativePackedColorArrayToSystemArray(packedArray);
+ }
+
+ public static StringName[] ConvertToSystemArrayOfStringName(in godot_variant p_var)
+ {
+ using var godotArray = NativeFuncs.godotsharp_variant_as_array(p_var);
+ return Marshaling.ConvertNativeGodotArrayToSystemArrayOfStringName(godotArray);
+ }
+
+ public static NodePath[] ConvertToSystemArrayOfNodePath(in godot_variant p_var)
+ {
+ using var godotArray = NativeFuncs.godotsharp_variant_as_array(p_var);
+ return Marshaling.ConvertNativeGodotArrayToSystemArrayOfNodePath(godotArray);
+ }
+
+ public static RID[] ConvertToSystemArrayOfRID(in godot_variant p_var)
+ {
+ using var godotArray = NativeFuncs.godotsharp_variant_as_array(p_var);
+ return Marshaling.ConvertNativeGodotArrayToSystemArrayOfRID(godotArray);
+ }
+
+ public static T[] ConvertToSystemArrayOfGodotObject<T>(in godot_variant p_var)
+ // ReSharper disable once RedundantNameQualifier
+ where T : Godot.Object
+ {
+ using var godotArray = NativeFuncs.godotsharp_variant_as_array(p_var);
+ return Marshaling.ConvertNativeGodotArrayToSystemArrayOfGodotObjectType<T>(godotArray);
+ }
+
+ // ReSharper disable once RedundantNameQualifier
+ public static Godot.Object[] ConvertToSystemArrayOfGodotObject(in godot_variant p_var, Type type)
+ {
+ using var godotArray = NativeFuncs.godotsharp_variant_as_array(p_var);
+ return Marshaling.ConvertNativeGodotArrayToSystemArrayOfGodotObjectType(godotArray, type);
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NodePath.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NodePath.cs
index 9ae01016cb..b02bd167a1 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NodePath.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NodePath.cs
@@ -1,5 +1,5 @@
using System;
-using System.Runtime.CompilerServices;
+using Godot.NativeInterop;
namespace Godot
{
@@ -39,22 +39,11 @@ namespace Godot
/// new NodePath("/root/MyAutoload"); // If you have an autoloaded node or scene.
/// </code>
/// </example>
- public sealed partial class NodePath : IDisposable
+ public sealed class NodePath : IDisposable
{
- private bool _disposed = false;
+ internal godot_node_path.movable NativeValue;
- private IntPtr ptr;
-
- internal static IntPtr GetPtr(NodePath instance)
- {
- if (instance == null)
- throw new NullReferenceException($"The instance of type {nameof(NodePath)} is null.");
-
- if (instance._disposed)
- throw new ObjectDisposedException(instance.GetType().FullName);
-
- return instance.ptr;
- }
+ private WeakReference<IDisposable> _weakReferenceToSelf;
~NodePath()
{
@@ -70,29 +59,33 @@ namespace Godot
GC.SuppressFinalize(this);
}
- private void Dispose(bool disposing)
+ public void Dispose(bool disposing)
{
- if (_disposed)
- return;
+ // Always dispose `NativeValue` even if disposing is true
+ NativeValue.DangerousSelfRef.Dispose();
- if (ptr != IntPtr.Zero)
+ if (_weakReferenceToSelf != null)
{
- godot_icall_NodePath_Dtor(ptr);
- ptr = IntPtr.Zero;
+ DisposablesTracker.UnregisterDisposable(_weakReferenceToSelf);
}
-
- _disposed = true;
}
- internal NodePath(IntPtr ptr)
+ private NodePath(godot_node_path nativeValueToOwn)
{
- this.ptr = ptr;
+ NativeValue = (godot_node_path.movable)nativeValueToOwn;
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
}
+ // Explicit name to make it very clear
+ internal static NodePath CreateTakingOwnershipOfDisposableValue(godot_node_path nativeValueToOwn)
+ => new NodePath(nativeValueToOwn);
+
/// <summary>
/// Constructs an empty <see cref="NodePath"/>.
/// </summary>
- public NodePath() : this(string.Empty) { }
+ public NodePath()
+ {
+ }
/// <summary>
/// Constructs a <see cref="NodePath"/> from a string <paramref name="path"/>,
@@ -125,7 +118,11 @@ namespace Godot
/// <param name="path">A string that represents a path in a scene tree.</param>
public NodePath(string path)
{
- ptr = godot_icall_NodePath_Ctor(path);
+ if (!string.IsNullOrEmpty(path))
+ {
+ NativeValue = (godot_node_path.movable)NativeFuncs.godotsharp_node_path_new_from_string(path);
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+ }
}
/// <summary>
@@ -138,7 +135,7 @@ namespace Godot
/// Converts this <see cref="NodePath"/> to a string.
/// </summary>
/// <param name="from">The <see cref="NodePath"/> to convert.</param>
- public static implicit operator string(NodePath from) => from.ToString();
+ public static implicit operator string(NodePath from) => from?.ToString();
/// <summary>
/// Converts this <see cref="NodePath"/> to a string.
@@ -146,7 +143,13 @@ namespace Godot
/// <returns>A string representation of this <see cref="NodePath"/>.</returns>
public override string ToString()
{
- return godot_icall_NodePath_operator_String(GetPtr(this));
+ if (IsEmpty)
+ return string.Empty;
+
+ var src = (godot_node_path)NativeValue;
+ NativeFuncs.godotsharp_node_path_as_string(out godot_string dest, src);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
}
/// <summary>
@@ -166,7 +169,10 @@ namespace Godot
/// <returns>The <see cref="NodePath"/> as a pure property path.</returns>
public NodePath GetAsPropertyPath()
{
- return new NodePath(godot_icall_NodePath_get_as_property_path(GetPtr(this)));
+ godot_node_path propertyPath = default;
+ var self = (godot_node_path)NativeValue;
+ NativeFuncs.godotsharp_node_path_get_as_property_path(self, ref propertyPath);
+ return CreateTakingOwnershipOfDisposableValue(propertyPath);
}
/// <summary>
@@ -181,7 +187,10 @@ namespace Godot
/// <returns>The names concatenated with <c>/</c>.</returns>
public string GetConcatenatedNames()
{
- return godot_icall_NodePath_get_concatenated_names(GetPtr(this));
+ var self = (godot_node_path)NativeValue;
+ NativeFuncs.godotsharp_node_path_get_concatenated_names(self, out godot_string names);
+ using (names)
+ return Marshaling.ConvertStringToManaged(names);
}
/// <summary>
@@ -195,9 +204,12 @@ namespace Godot
/// </code>
/// </example>
/// <returns>The subnames concatenated with <c>:</c>.</returns>
- public string GetConcatenatedSubnames()
+ public string GetConcatenatedSubNames()
{
- return godot_icall_NodePath_get_concatenated_subnames(GetPtr(this));
+ var self = (godot_node_path)NativeValue;
+ NativeFuncs.godotsharp_node_path_get_concatenated_subnames(self, out godot_string subNames);
+ using (subNames)
+ return Marshaling.ConvertStringToManaged(subNames);
}
/// <summary>
@@ -215,28 +227,35 @@ namespace Godot
/// <returns>The name at the given index <paramref name="idx"/>.</returns>
public string GetName(int idx)
{
- return godot_icall_NodePath_get_name(GetPtr(this), idx);
+ var self = (godot_node_path)NativeValue;
+ NativeFuncs.godotsharp_node_path_get_name(self, idx, out godot_string name);
+ using (name)
+ return Marshaling.ConvertStringToManaged(name);
}
/// <summary>
/// Gets the number of node names which make up the path.
- /// Subnames (see <see cref="GetSubnameCount"/>) are not included.
+ /// Subnames (see <see cref="GetSubNameCount"/>) are not included.
/// For example, <c>"Path2D/PathFollow2D/Sprite2D"</c> has 3 names.
/// </summary>
/// <returns>The number of node names which make up the path.</returns>
public int GetNameCount()
{
- return godot_icall_NodePath_get_name_count(GetPtr(this));
+ var self = (godot_node_path)NativeValue;
+ return NativeFuncs.godotsharp_node_path_get_name_count(self);
}
/// <summary>
- /// Gets the resource or property name indicated by <paramref name="idx"/> (0 to <see cref="GetSubnameCount"/>).
+ /// Gets the resource or property name indicated by <paramref name="idx"/> (0 to <see cref="GetSubNameCount"/>).
/// </summary>
/// <param name="idx">The subname index.</param>
/// <returns>The subname at the given index <paramref name="idx"/>.</returns>
- public string GetSubname(int idx)
+ public string GetSubName(int idx)
{
- return godot_icall_NodePath_get_subname(GetPtr(this), idx);
+ var self = (godot_node_path)NativeValue;
+ NativeFuncs.godotsharp_node_path_get_subname(self, idx, out godot_string subName);
+ using (subName)
+ return Marshaling.ConvertStringToManaged(subName);
}
/// <summary>
@@ -245,9 +264,10 @@ namespace Godot
/// For example, <c>"Path2D/PathFollow2D/Sprite2D:texture:load_path"</c> has 2 subnames.
/// </summary>
/// <returns>The number of subnames in the path.</returns>
- public int GetSubnameCount()
+ public int GetSubNameCount()
{
- return godot_icall_NodePath_get_subname_count(GetPtr(this));
+ var self = (godot_node_path)NativeValue;
+ return NativeFuncs.godotsharp_node_path_get_subname_count(self);
}
/// <summary>
@@ -259,52 +279,14 @@ namespace Godot
/// <returns>If the <see cref="NodePath"/> is an absolute path.</returns>
public bool IsAbsolute()
{
- return godot_icall_NodePath_is_absolute(GetPtr(this));
+ var self = (godot_node_path)NativeValue;
+ return NativeFuncs.godotsharp_node_path_is_absolute(self).ToBool();
}
/// <summary>
/// Returns <see langword="true"/> if the node path is empty.
/// </summary>
/// <returns>If the <see cref="NodePath"/> is empty.</returns>
- public bool IsEmpty()
- {
- return godot_icall_NodePath_is_empty(GetPtr(this));
- }
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern IntPtr godot_icall_NodePath_Ctor(string path);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void godot_icall_NodePath_Dtor(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string godot_icall_NodePath_operator_String(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern IntPtr godot_icall_NodePath_get_as_property_path(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string godot_icall_NodePath_get_concatenated_names(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string godot_icall_NodePath_get_concatenated_subnames(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string godot_icall_NodePath_get_name(IntPtr ptr, int arg1);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern int godot_icall_NodePath_get_name_count(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string godot_icall_NodePath_get_subname(IntPtr ptr, int arg1);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern int godot_icall_NodePath_get_subname_count(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool godot_icall_NodePath_is_absolute(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool godot_icall_NodePath_is_empty(IntPtr ptr);
+ public bool IsEmpty => NativeValue.DangerousSelfRef.IsEmpty;
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs
index 746612477d..5cb678c280 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs
@@ -1,54 +1,78 @@
using System;
-using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Godot.Bridge;
+using Godot.NativeInterop;
namespace Godot
{
public partial class Object : IDisposable
{
private bool _disposed = false;
+ private static readonly Type CachedType = typeof(Object);
- private static StringName nativeName = "Object";
+ internal IntPtr NativePtr;
+ private bool _memoryOwn;
- internal IntPtr ptr;
- internal bool memoryOwn;
+ private WeakReference<Object> _weakReferenceToSelf;
/// <summary>
/// Constructs a new <see cref="Object"/>.
/// </summary>
public Object() : this(false)
{
- if (ptr == IntPtr.Zero)
- ptr = godot_icall_Object_Ctor(this);
- _InitializeGodotScriptInstanceInternals();
+ unsafe
+ {
+ _ConstructAndInitialize(NativeCtor, NativeName, CachedType, refCounted: false);
+ }
}
- internal void _InitializeGodotScriptInstanceInternals()
+ internal unsafe void _ConstructAndInitialize(
+ delegate* unmanaged<IntPtr> nativeCtor,
+ StringName nativeName,
+ Type cachedType,
+ bool refCounted
+ )
{
- godot_icall_Object_ConnectEventSignals(ptr);
+ if (NativePtr == IntPtr.Zero)
+ {
+ NativePtr = nativeCtor();
+
+ InteropUtils.TieManagedToUnmanaged(this, NativePtr,
+ nativeName, refCounted, GetType(), cachedType);
+ }
+ else
+ {
+ InteropUtils.TieManagedToUnmanagedWithPreSetup(this, NativePtr,
+ GetType(), cachedType);
+ }
+
+ _weakReferenceToSelf = DisposablesTracker.RegisterGodotObject(this);
}
internal Object(bool memoryOwn)
{
- this.memoryOwn = memoryOwn;
+ _memoryOwn = memoryOwn;
}
/// <summary>
/// The pointer to the native instance of this <see cref="Object"/>.
/// </summary>
- public IntPtr NativeInstance
- {
- get { return ptr; }
- }
+ public IntPtr NativeInstance => NativePtr;
internal static IntPtr GetPtr(Object instance)
{
if (instance == null)
return IntPtr.Zero;
- if (instance._disposed)
+ // We check if NativePtr is null because this may be called by the debugger.
+ // If the debugger puts a breakpoint in one of the base constructors, before
+ // NativePtr is assigned, that would result in UB or crashes when calling
+ // native functions that receive the pointer, which can happen because the
+ // debugger calls ToString() and tries to get the value of properties.
+ if (instance._disposed || instance.NativePtr == IntPtr.Zero)
throw new ObjectDisposedException(instance.GetType().FullName);
- return instance.ptr;
+ return instance.NativePtr;
}
~Object()
@@ -73,22 +97,35 @@ namespace Godot
if (_disposed)
return;
- if (ptr != IntPtr.Zero)
+ _disposed = true;
+
+ if (NativePtr != IntPtr.Zero)
{
- if (memoryOwn)
+ IntPtr gcHandleToFree = NativeFuncs.godotsharp_internal_object_get_associated_gchandle(NativePtr);
+
+ if (gcHandleToFree != IntPtr.Zero)
+ {
+ object target = GCHandle.FromIntPtr(gcHandleToFree).Target;
+ // The GC handle may have been replaced in another thread. Release it only if
+ // it's associated to this managed instance, or if the target is no longer alive.
+ if (target != this && target != null)
+ gcHandleToFree = IntPtr.Zero;
+ }
+
+ if (_memoryOwn)
{
- memoryOwn = false;
- godot_icall_RefCounted_Disposed(this, ptr, !disposing);
+ NativeFuncs.godotsharp_internal_refcounted_disposed(NativePtr, gcHandleToFree,
+ (!disposing).ToGodotBool());
}
else
{
- godot_icall_Object_Disposed(this, ptr);
+ NativeFuncs.godotsharp_internal_object_disposed(NativePtr, gcHandleToFree);
}
- ptr = IntPtr.Zero;
+ NativePtr = IntPtr.Zero;
}
- _disposed = true;
+ DisposablesTracker.UnregisterGodotObject(this, _weakReferenceToSelf);
}
/// <summary>
@@ -97,7 +134,9 @@ namespace Godot
/// <returns>A string representation of this object.</returns>
public override string ToString()
{
- return godot_icall_Object_ToString(GetPtr(this));
+ NativeFuncs.godotsharp_object_to_string(GetPtr(this), out godot_string str);
+ using (str)
+ return Marshaling.ConvertStringToManaged(str);
}
/// <summary>
@@ -132,33 +171,72 @@ namespace Godot
return new SignalAwaiter(source, signal, this);
}
- /// <summary>
- /// Gets a new <see cref="DynamicGodotObject"/> associated with this instance.
- /// </summary>
- public dynamic DynamicObject => new DynamicGodotObject(this);
+ internal static Type InternalGetClassNativeBase(Type t)
+ {
+ do
+ {
+ var assemblyName = t.Assembly.GetName();
- internal static IntPtr __ClassDB_get_method(StringName type, string method)
+ if (assemblyName.Name == "GodotSharp")
+ return t;
+
+ if (assemblyName.Name == "GodotSharpEditor")
+ return t;
+ } while ((t = t.BaseType) != null);
+
+ return null;
+ }
+
+ // ReSharper disable once VirtualMemberNeverOverridden.Global
+ protected internal virtual bool SetGodotClassPropertyValue(in godot_string_name name, in godot_variant value)
+ {
+ return false;
+ }
+
+ // ReSharper disable once VirtualMemberNeverOverridden.Global
+ protected internal virtual bool GetGodotClassPropertyValue(in godot_string_name name, out godot_variant value)
+ {
+ value = default;
+ return false;
+ }
+
+ // ReSharper disable once VirtualMemberNeverOverridden.Global
+ protected internal virtual void RaiseGodotClassSignalCallbacks(in godot_string_name signal,
+ NativeVariantPtrArgs args, int argCount)
{
- return godot_icall_Object_ClassDB_get_method(StringName.GetPtr(type), method);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Object_Ctor(Object obj);
+ internal static IntPtr ClassDB_get_method(StringName type, StringName method)
+ {
+ var typeSelf = (godot_string_name)type.NativeValue;
+ var methodSelf = (godot_string_name)method.NativeValue;
+ IntPtr methodBind = NativeFuncs.godotsharp_method_bind_get_method(typeSelf, methodSelf);
+
+ if (methodBind == IntPtr.Zero)
+ throw new NativeMethodBindNotFoundException(type + "." + method);
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Object_Disposed(Object obj, IntPtr ptr);
+ return methodBind;
+ }
+
+ internal static unsafe delegate* unmanaged<IntPtr> ClassDB_get_constructor(StringName type)
+ {
+ // for some reason the '??' operator doesn't support 'delegate*'
+ var typeSelf = (godot_string_name)type.NativeValue;
+ var nativeConstructor = NativeFuncs.godotsharp_get_class_constructor(typeSelf);
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_RefCounted_Disposed(Object obj, IntPtr ptr, bool isFinalizer);
+ if (nativeConstructor == null)
+ throw new NativeConstructorNotFoundException(type);
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_Object_ConnectEventSignals(IntPtr obj);
+ return nativeConstructor;
+ }
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_Object_ToString(IntPtr ptr);
+ protected internal virtual void SaveGodotObjectData(GodotSerializationInfo info)
+ {
+ }
- // Used by the generated API
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_Object_ClassDB_get_method(IntPtr type, string method);
+ // TODO: Should this be a constructor overload?
+ protected internal virtual void RestoreGodotObjectData(GodotSerializationInfo info)
+ {
+ }
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.exceptions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.exceptions.cs
new file mode 100644
index 0000000000..eb2811c73d
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.exceptions.cs
@@ -0,0 +1,135 @@
+using System;
+
+#nullable enable
+
+namespace Godot
+{
+ public partial class Object
+ {
+ public class NativeMemberNotFoundException : Exception
+ {
+ public NativeMemberNotFoundException()
+ {
+ }
+
+ public NativeMemberNotFoundException(string? message) : base(message)
+ {
+ }
+
+ public NativeMemberNotFoundException(string? message, Exception? innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+
+ public class NativeConstructorNotFoundException : NativeMemberNotFoundException
+ {
+ private readonly string? _nativeClassName;
+
+ // ReSharper disable once InconsistentNaming
+ private const string Arg_NativeConstructorNotFoundException = "Unable to find the native constructor.";
+
+ public NativeConstructorNotFoundException()
+ : base(Arg_NativeConstructorNotFoundException)
+ {
+ }
+
+ public NativeConstructorNotFoundException(string? nativeClassName)
+ : this(Arg_NativeConstructorNotFoundException, nativeClassName)
+ {
+ }
+
+ public NativeConstructorNotFoundException(string? message, Exception? innerException)
+ : base(message, innerException)
+ {
+ }
+
+ public NativeConstructorNotFoundException(string? message, string? nativeClassName)
+ : base(message)
+ {
+ _nativeClassName = nativeClassName;
+ }
+
+ public NativeConstructorNotFoundException(string? message, string? nativeClassName, Exception? innerException)
+ : base(message, innerException)
+ {
+ _nativeClassName = nativeClassName;
+ }
+
+ public override string Message
+ {
+ get
+ {
+ string s = base.Message;
+
+ if (string.IsNullOrEmpty(s))
+ {
+ s = Arg_NativeConstructorNotFoundException;
+ }
+
+ if (!string.IsNullOrEmpty(_nativeClassName))
+ {
+ s += " " + string.Format("(Class '{0}')", _nativeClassName);
+ }
+
+ return s;
+ }
+ }
+ }
+
+ public class NativeMethodBindNotFoundException : NativeMemberNotFoundException
+ {
+ private readonly string? _nativeMethodName;
+
+ // ReSharper disable once InconsistentNaming
+ private const string Arg_NativeMethodBindNotFoundException = "Unable to find the native method bind.";
+
+ public NativeMethodBindNotFoundException()
+ : base(Arg_NativeMethodBindNotFoundException)
+ {
+ }
+
+ public NativeMethodBindNotFoundException(string? nativeMethodName)
+ : this(Arg_NativeMethodBindNotFoundException, nativeMethodName)
+ {
+ }
+
+ public NativeMethodBindNotFoundException(string? message, Exception? innerException)
+ : base(message, innerException)
+ {
+ }
+
+ public NativeMethodBindNotFoundException(string? message, string? nativeMethodName)
+ : base(message)
+ {
+ _nativeMethodName = nativeMethodName;
+ }
+
+ public NativeMethodBindNotFoundException(string? message, string? nativeMethodName, Exception? innerException)
+ : base(message, innerException)
+ {
+ _nativeMethodName = nativeMethodName;
+ }
+
+ public override string Message
+ {
+ get
+ {
+ string s = base.Message;
+
+ if (string.IsNullOrEmpty(s))
+ {
+ s = Arg_NativeMethodBindNotFoundException;
+ }
+
+ if (!string.IsNullOrEmpty(_nativeMethodName))
+ {
+ s += " " + string.Format("(Method '{0}')", _nativeMethodName);
+ }
+
+ return s;
+ }
+ }
+ }
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
index fd97a71e47..50832d7679 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Projection.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Projection.cs
index d774021131..d62cb6b0fa 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Projection.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Projection.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -44,22 +39,22 @@ namespace Godot
}
/// <summary>
- /// The projections's X column. Also accessible by using the index position <c>[0]</c>.
+ /// The projection's X column. Also accessible by using the index position <c>[0]</c>.
/// </summary>
public Vector4 x;
/// <summary>
- /// The projections's Y column. Also accessible by using the index position <c>[1]</c>.
+ /// The projection's Y column. Also accessible by using the index position <c>[1]</c>.
/// </summary>
public Vector4 y;
/// <summary>
- /// The projections's Z column. Also accessible by using the index position <c>[2]</c>.
+ /// The projection's Z column. Also accessible by using the index position <c>[2]</c>.
/// </summary>
public Vector4 z;
/// <summary>
- /// The projections's W column. Also accessible by using the index position <c>[3]</c>.
+ /// The projection's W column. Also accessible by using the index position <c>[3]</c>.
/// </summary>
public Vector4 w;
@@ -79,18 +74,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a new <see cref="Projection"/> from an existing <see cref="Projection"/>.
- /// </summary>
- /// <param name="proj">The existing <see cref="Projection"/>.</param>
- public Projection(Projection proj)
- {
- x = proj.x;
- y = proj.y;
- z = proj.z;
- w = proj.w;
- }
-
- /// <summary>
/// Constructs a new <see cref="Projection"/> from a <see cref="Transform3D"/>.
/// </summary>
/// <param name="transform">The <see cref="Transform3D"/>.</param>
@@ -360,7 +343,7 @@ namespace Godot
public int GetPixelsPerMeter(int forPixelWidth)
{
- Vector3 result = Xform(new Vector3(1, 0, -1));
+ Vector3 result = this * new Vector3(1, 0, -1);
return (int)((result.x * (real_t)0.5 + (real_t)0.5) * forPixelWidth);
}
@@ -593,19 +576,51 @@ namespace Godot
}
/// <summary>
- /// Returns a vector transformed (multiplied) by this projection.
+ /// Returns a Vector4 transformed (multiplied) by the projection.
+ /// </summary>
+ /// <param name="proj">The projection to apply.</param>
+ /// <param name="vector">A Vector4 to transform.</param>
+ /// <returns>The transformed Vector4.</returns>
+ public static Vector4 operator *(Projection proj, Vector4 vector)
+ {
+ return new Vector4(
+ proj.x.x * vector.x + proj.y.x * vector.y + proj.z.x * vector.z + proj.w.x * vector.w,
+ proj.x.y * vector.x + proj.y.y * vector.y + proj.z.y * vector.z + proj.w.y * vector.w,
+ proj.x.z * vector.x + proj.y.z * vector.y + proj.z.z * vector.z + proj.w.z * vector.w,
+ proj.x.w * vector.x + proj.y.w * vector.y + proj.z.w * vector.z + proj.w.w * vector.w
+ );
+ }
+
+ /// <summary>
+ /// Returns a Vector4 transformed (multiplied) by the inverse projection.
/// </summary>
/// <param name="proj">The projection to apply.</param>
- /// <param name="v">A vector to transform.</param>
- /// <returns>The transformed vector.</returns>
- public static Vector4 operator *(Projection proj, Vector4 v)
+ /// <param name="vector">A Vector4 to transform.</param>
+ /// <returns>The inversely transformed Vector4.</returns>
+ public static Vector4 operator *(Vector4 vector, Projection proj)
{
return new Vector4(
- proj.x.x * v.x + proj.y.x * v.y + proj.z.x * v.z + proj.w.x * v.w,
- proj.x.y * v.x + proj.y.y * v.y + proj.z.y * v.z + proj.w.y * v.w,
- proj.x.z * v.x + proj.y.z * v.y + proj.z.z * v.z + proj.w.z * v.w,
- proj.x.w * v.x + proj.y.w * v.y + proj.z.w * v.z + proj.w.w * v.w
+ proj.x.x * vector.x + proj.x.y * vector.y + proj.x.z * vector.z + proj.x.w * vector.w,
+ proj.y.x * vector.x + proj.y.y * vector.y + proj.y.z * vector.z + proj.y.w * vector.w,
+ proj.z.x * vector.x + proj.z.y * vector.y + proj.z.z * vector.z + proj.z.w * vector.w,
+ proj.w.x * vector.x + proj.w.y * vector.y + proj.w.z * vector.z + proj.w.w * vector.w
+ );
+ }
+
+ /// <summary>
+ /// Returns a Vector3 transformed (multiplied) by the projection.
+ /// </summary>
+ /// <param name="proj">The projection to apply.</param>
+ /// <param name="vector">A Vector3 to transform.</param>
+ /// <returns>The transformed Vector3.</returns>
+ public static Vector3 operator *(Projection proj, Vector3 vector)
+ {
+ Vector3 ret = new Vector3(
+ proj.x.x * vector.x + proj.y.x * vector.y + proj.z.x * vector.z + proj.w.x,
+ proj.x.y * vector.x + proj.y.y * vector.y + proj.z.y * vector.z + proj.w.y,
+ proj.x.z * vector.x + proj.y.z * vector.y + proj.z.z * vector.z + proj.w.z
);
+ return ret / (proj.x.w * vector.x + proj.y.w * vector.y + proj.z.w * vector.z + proj.w.w);
}
/// <summary>
@@ -719,21 +734,6 @@ namespace Godot
}
}
- /// <summary>
- /// Returns a vector transformed (multiplied) by this projection.
- /// </summary>
- /// <param name="v">A vector to transform.</param>
- /// <returns>The transformed vector.</returns>
- private Vector3 Xform(Vector3 v)
- {
- Vector3 ret = new Vector3(
- x.x * v.x + y.x * v.y + z.x * v.z + w.x,
- x.y * v.x + y.y * v.y + z.y * v.z + w.y,
- x.z * v.x + y.z * v.y + z.z * v.z + w.z
- );
- return ret / (x.w * v.x + y.w * v.y + z.w * v.z + w.w);
- }
-
// Constants
private static readonly Projection _zero = new Projection(
new Vector4(0, 0, 0, 0),
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs
index e38dca414f..658a14ca1d 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -73,7 +68,7 @@ namespace Godot
case 3:
return w;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
set
@@ -93,7 +88,7 @@ namespace Godot
w = value;
break;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
@@ -318,24 +313,6 @@ namespace Godot
);
}
- /// <summary>
- /// Returns a vector transformed (multiplied) by this quaternion.
- /// </summary>
- /// <param name="v">A vector to transform.</param>
- /// <returns>The transformed vector.</returns>
- public Vector3 Xform(Vector3 v)
- {
-#if DEBUG
- if (!IsNormalized())
- {
- throw new InvalidOperationException("Quaternion is not normalized");
- }
-#endif
- var u = new Vector3(x, y, z);
- Vector3 uv = u.Cross(v);
- return v + (((uv * w) + u.Cross(uv)) * 2);
- }
-
// Constants
private static readonly Quaternion _identity = new Quaternion(0, 0, 0, 1);
@@ -363,15 +340,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a <see cref="Quaternion"/> from the given <see cref="Quaternion"/>.
- /// </summary>
- /// <param name="q">The existing quaternion.</param>
- public Quaternion(Quaternion q)
- {
- this = q;
- }
-
- /// <summary>
/// Constructs a <see cref="Quaternion"/> from the given <see cref="Basis"/>.
/// </summary>
/// <param name="basis">The <see cref="Basis"/> to construct from.</param>
@@ -466,6 +434,36 @@ namespace Godot
}
/// <summary>
+ /// Returns a Vector3 rotated (multiplied) by the quaternion.
+ /// </summary>
+ /// <param name="quaternion">The quaternion to rotate by.</param>
+ /// <param name="vector">A Vector3 to transform.</param>
+ /// <returns>The rotated Vector3.</returns>
+ public static Vector3 operator *(Quaternion quaternion, Vector3 vector)
+ {
+#if DEBUG
+ if (!quaternion.IsNormalized())
+ {
+ throw new InvalidOperationException("Quaternion is not normalized");
+ }
+#endif
+ var u = new Vector3(quaternion.x, quaternion.y, quaternion.z);
+ Vector3 uv = u.Cross(vector);
+ return vector + (((uv * quaternion.w) + u.Cross(uv)) * 2);
+ }
+
+ /// <summary>
+ /// Returns a Vector3 rotated (multiplied) by the inverse quaternion.
+ /// </summary>
+ /// <param name="vector">A Vector3 to inversely rotate.</param>
+ /// <param name="quaternion">The quaternion to rotate by.</param>
+ /// <returns>The inversely rotated Vector3.</returns>
+ public static Vector3 operator *(Vector3 vector, Quaternion quaternion)
+ {
+ return quaternion.Inverse() * vector;
+ }
+
+ /// <summary>
/// Adds each component of the left <see cref="Quaternion"/>
/// to the right <see cref="Quaternion"/>. This operation is not
/// meaningful on its own, but it can be used as a part of a
@@ -508,38 +506,6 @@ namespace Godot
}
/// <summary>
- /// Rotates (multiplies) the <see cref="Vector3"/>
- /// by the given <see cref="Quaternion"/>.
- /// </summary>
- /// <param name="quat">The quaternion to rotate by.</param>
- /// <param name="vec">The vector to rotate.</param>
- /// <returns>The rotated vector.</returns>
- public static Vector3 operator *(Quaternion quat, Vector3 vec)
- {
-#if DEBUG
- if (!quat.IsNormalized())
- {
- throw new InvalidOperationException("Quaternion is not normalized.");
- }
-#endif
- var u = new Vector3(quat.x, quat.y, quat.z);
- Vector3 uv = u.Cross(vec);
- return vec + (((uv * quat.w) + u.Cross(uv)) * 2);
- }
-
- /// <summary>
- /// Inversely rotates (multiplies) the <see cref="Vector3"/>
- /// by the given <see cref="Quaternion"/>.
- /// </summary>
- /// <param name="vec">The vector to rotate.</param>
- /// <param name="quat">The quaternion to rotate by.</param>
- /// <returns>The inversely rotated vector.</returns>
- public static Vector3 operator *(Vector3 vec, Quaternion quat)
- {
- return quat.Inverse() * vec;
- }
-
- /// <summary>
/// Multiplies each component of the <see cref="Quaternion"/>
/// by the given <see cref="real_t"/>. This operation is not
/// meaningful on its own, but it can be used as a part of a
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/RID.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/RID.cs
index 1588869ec0..a31fef8360 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/RID.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/RID.cs
@@ -1,5 +1,7 @@
using System;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
namespace Godot
{
@@ -9,99 +11,32 @@ namespace Godot
/// resource by themselves. They are used by and with the low-level Server
/// classes such as <see cref="RenderingServer"/>.
/// </summary>
- public sealed partial class RID : IDisposable
+ [StructLayout(LayoutKind.Sequential)]
+ public struct RID
{
- private bool _disposed = false;
+ private ulong _id; // Default is 0
- internal IntPtr ptr;
-
- internal static IntPtr GetPtr(RID instance)
- {
- if (instance == null)
- throw new NullReferenceException($"The instance of type {nameof(RID)} is null.");
-
- if (instance._disposed)
- throw new ObjectDisposedException(instance.GetType().FullName);
-
- return instance.ptr;
- }
-
- ~RID()
- {
- Dispose(false);
- }
-
- /// <summary>
- /// Disposes of this <see cref="RID"/>.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- private void Dispose(bool disposing)
- {
- if (_disposed)
- return;
-
- if (ptr != IntPtr.Zero)
- {
- godot_icall_RID_Dtor(ptr);
- ptr = IntPtr.Zero;
- }
-
- _disposed = true;
- }
-
- internal RID(IntPtr ptr)
+ internal RID(ulong id)
{
- this.ptr = ptr;
- }
-
- /// <summary>
- /// The pointer to the native instance of this <see cref="RID"/>.
- /// </summary>
- public IntPtr NativeInstance
- {
- get { return ptr; }
- }
-
- internal RID()
- {
- this.ptr = IntPtr.Zero;
+ _id = id;
}
/// <summary>
/// Constructs a new <see cref="RID"/> for the given <see cref="Object"/> <paramref name="from"/>.
/// </summary>
public RID(Object from)
- {
- this.ptr = godot_icall_RID_Ctor(Object.GetPtr(from));
- }
+ => _id = from is Resource res ? res.GetRid()._id : default;
/// <summary>
/// Returns the ID of the referenced resource.
/// </summary>
/// <returns>The ID of the referenced resource.</returns>
- public int GetId()
- {
- return godot_icall_RID_get_id(GetPtr(this));
- }
+ public ulong Id => _id;
/// <summary>
/// Converts this <see cref="RID"/> to a string.
/// </summary>
/// <returns>A string representation of this RID.</returns>
- public override string ToString() => "[RID]";
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern IntPtr godot_icall_RID_Ctor(IntPtr from);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern void godot_icall_RID_Dtor(IntPtr ptr);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_RID_get_id(IntPtr ptr);
+ public override string ToString() => $"RID({Id})";
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs
index ec16920fed..d2c9b0ca8b 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/ReflectionUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/ReflectionUtils.cs
new file mode 100644
index 0000000000..ee605f8d8f
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/ReflectionUtils.cs
@@ -0,0 +1,16 @@
+using System;
+using System.Linq;
+
+#nullable enable
+
+namespace Godot;
+
+internal class ReflectionUtils
+{
+ public static Type? FindTypeInLoadedAssemblies(string assemblyName, string typeFullName)
+ {
+ return AppDomain.CurrentDomain.GetAssemblies()
+ .FirstOrDefault(a => a.GetName().Name == assemblyName)?
+ .GetType(typeFullName);
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalAwaiter.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalAwaiter.cs
index 2ba0493002..96fb891086 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalAwaiter.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalAwaiter.cs
@@ -1,50 +1,67 @@
using System;
-using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Godot.NativeInterop;
namespace Godot
{
- public class SignalAwaiter : IAwaiter<object[]>, IAwaitable<object[]>
+ public class SignalAwaiter : IAwaiter<Variant[]>, IAwaitable<Variant[]>
{
private bool _completed;
- private object[] _result;
- private Action _action;
+ private Variant[] _result;
+ private Action _continuation;
public SignalAwaiter(Object source, StringName signal, Object target)
{
- godot_icall_SignalAwaiter_connect(Object.GetPtr(source), StringName.GetPtr(signal), Object.GetPtr(target), this);
+ var awaiterGcHandle = CustomGCHandle.AllocStrong(this);
+ using godot_string_name signalSrc = NativeFuncs.godotsharp_string_name_new_copy(
+ (godot_string_name)(signal?.NativeValue ?? default));
+ NativeFuncs.godotsharp_internal_signal_awaiter_connect(Object.GetPtr(source), in signalSrc,
+ Object.GetPtr(target), GCHandle.ToIntPtr(awaiterGcHandle));
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern Error godot_icall_SignalAwaiter_connect(IntPtr source, IntPtr signal, IntPtr target, SignalAwaiter awaiter);
+ public bool IsCompleted => _completed;
- public bool IsCompleted
+ public void OnCompleted(Action continuation)
{
- get
- {
- return _completed;
- }
+ _continuation = continuation;
}
- public void OnCompleted(Action action)
- {
- this._action = action;
- }
+ public Variant[] GetResult() => _result;
- public object[] GetResult()
- {
- return _result;
- }
+ public IAwaiter<Variant[]> GetAwaiter() => this;
- public IAwaiter<object[]> GetAwaiter()
+ [UnmanagedCallersOnly]
+ internal static unsafe void SignalCallback(IntPtr awaiterGCHandlePtr, godot_variant** args, int argCount,
+ godot_bool* outAwaiterIsNull)
{
- return this;
- }
+ try
+ {
+ var awaiter = (SignalAwaiter)GCHandle.FromIntPtr(awaiterGCHandlePtr).Target;
- internal void SignalCallback(object[] args)
- {
- _completed = true;
- _result = args;
- _action?.Invoke();
+ if (awaiter == null)
+ {
+ *outAwaiterIsNull = godot_bool.True;
+ return;
+ }
+
+ *outAwaiterIsNull = godot_bool.False;
+
+ awaiter._completed = true;
+
+ Variant[] signalArgs = new Variant[argCount];
+
+ for (int i = 0; i < argCount; i++)
+ signalArgs[i] = Variant.CreateCopyingBorrowed(*args[i]);
+
+ awaiter._result = signalArgs;
+
+ awaiter._continuation?.Invoke();
+ }
+ catch (Exception e)
+ {
+ ExceptionUtils.LogException(e);
+ *outAwaiterIsNull = godot_bool.False;
+ }
}
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalInfo.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalInfo.cs
index da01300586..3f50df0a0d 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalInfo.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalInfo.cs
@@ -3,7 +3,7 @@ namespace Godot
/// <summary>
/// Represents a signal defined in an object.
/// </summary>
- public struct SignalInfo
+ public readonly struct SignalInfo
{
private readonly Object _owner;
private readonly StringName _signalName;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
index a1f058ffe5..f0bc5949df 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
@@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.Globalization;
-using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
+using Godot.NativeInterop;
+
+#nullable enable
namespace Godot
{
@@ -177,6 +179,7 @@ namespace Godot
{
return 0;
}
+
if (from == 0 && to == len)
{
str = instance;
@@ -214,7 +217,7 @@ namespace Godot
/// <returns>The escaped string.</returns>
public static string CEscape(this string instance)
{
- var sb = new StringBuilder(string.Copy(instance));
+ var sb = new StringBuilder(instance);
sb.Replace("\\", "\\\\");
sb.Replace("\a", "\\a");
@@ -239,7 +242,7 @@ namespace Godot
/// <returns>The unescaped string.</returns>
public static string CUnescape(this string instance)
{
- var sb = new StringBuilder(string.Copy(instance));
+ var sb = new StringBuilder(instance);
sb.Replace("\\a", "\a");
sb.Replace("\\b", "\b");
@@ -471,7 +474,8 @@ namespace Godot
/// <returns>The starting position of the substring, or -1 if not found.</returns>
public static int Find(this string instance, string what, int from = 0, bool caseSensitive = true)
{
- return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
+ return instance.IndexOf(what, from,
+ caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
/// <summary>
@@ -490,7 +494,8 @@ namespace Godot
{
// TODO: Could be more efficient if we get a char version of `IndexOf`.
// See https://github.com/dotnet/runtime/issues/44116
- return instance.IndexOf(what.ToString(), from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
+ return instance.IndexOf(what.ToString(), from,
+ caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
/// <summary>Find the last occurrence of a substring.</summary>
@@ -519,7 +524,8 @@ namespace Godot
/// <returns>The starting position of the substring, or -1 if not found.</returns>
public static int FindLast(this string instance, string what, int from, bool caseSensitive = true)
{
- return instance.LastIndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
+ return instance.LastIndexOf(what, from,
+ caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
/// <summary>
@@ -804,6 +810,7 @@ namespace Godot
{
match = instance[source] == text[target];
}
+
if (match)
{
source++;
@@ -926,7 +933,7 @@ namespace Godot
/// <returns>The escaped string.</returns>
public static string JSONEscape(this string instance)
{
- var sb = new StringBuilder(string.Copy(instance));
+ var sb = new StringBuilder(instance);
sb.Replace("\\", "\\\\");
sb.Replace("\b", "\\b");
@@ -1015,15 +1022,18 @@ namespace Godot
switch (expr[0])
{
case '*':
- return ExprMatch(instance, expr.Substring(1), caseSensitive) || (instance.Length > 0 && ExprMatch(instance.Substring(1), expr, caseSensitive));
+ return ExprMatch(instance, expr.Substring(1), caseSensitive) || (instance.Length > 0 &&
+ ExprMatch(instance.Substring(1), expr, caseSensitive));
case '?':
- return instance.Length > 0 && instance[0] != '.' && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
+ return instance.Length > 0 && instance[0] != '.' &&
+ ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
default:
if (instance.Length == 0)
return false;
if (caseSensitive)
return instance[0] == expr[0];
- return (char.ToUpper(instance[0]) == char.ToUpper(expr[0])) && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
+ return (char.ToUpper(instance[0]) == char.ToUpper(expr[0])) &&
+ ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
}
}
@@ -1070,12 +1080,12 @@ namespace Godot
/// <returns>The MD5 hash of the string.</returns>
public static byte[] MD5Buffer(this string instance)
{
- return godot_icall_String_md5_buffer(instance);
+ using godot_string instanceStr = Marshaling.ConvertStringToNative(instance);
+ NativeFuncs.godotsharp_string_md5_buffer(instanceStr, out var md5Buffer);
+ using (md5Buffer)
+ return Marshaling.ConvertNativePackedByteArrayToSystemArray(md5Buffer);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern byte[] godot_icall_String_md5_buffer(string str);
-
/// <summary>
/// Returns the MD5 hash of the string as a string.
/// </summary>
@@ -1084,12 +1094,12 @@ namespace Godot
/// <returns>The MD5 hash of the string.</returns>
public static string MD5Text(this string instance)
{
- return godot_icall_String_md5_text(instance);
+ using godot_string instanceStr = Marshaling.ConvertStringToNative(instance);
+ NativeFuncs.godotsharp_string_md5_text(instanceStr, out var md5Text);
+ using (md5Text)
+ return Marshaling.ConvertStringToManaged(md5Text);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_String_md5_text(string str);
-
/// <summary>
/// Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
/// </summary>
@@ -1244,12 +1254,11 @@ namespace Godot
/// <returns>The position at which the substring was found, or -1 if not found.</returns>
public static int RFind(this string instance, string what, int from = -1)
{
- return godot_icall_String_rfind(instance, what, from);
+ using godot_string instanceStr = Marshaling.ConvertStringToNative(instance);
+ using godot_string whatStr = Marshaling.ConvertStringToNative(instance);
+ return NativeFuncs.godotsharp_string_rfind(instanceStr, whatStr, from);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_String_rfind(string str, string what, int from);
-
/// <summary>
/// Perform a search for a substring, but start from the end of the string instead of the beginning.
/// Also search case-insensitive.
@@ -1261,12 +1270,11 @@ namespace Godot
/// <returns>The position at which the substring was found, or -1 if not found.</returns>
public static int RFindN(this string instance, string what, int from = -1)
{
- return godot_icall_String_rfindn(instance, what, from);
+ using godot_string instanceStr = Marshaling.ConvertStringToNative(instance);
+ using godot_string whatStr = Marshaling.ConvertStringToNative(instance);
+ return NativeFuncs.godotsharp_string_rfindn(instanceStr, whatStr, from);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern int godot_icall_String_rfindn(string str, string what, int from);
-
/// <summary>
/// Returns the right side of the string from a given position.
/// </summary>
@@ -1321,12 +1329,12 @@ namespace Godot
/// <returns>The SHA-256 hash of the string.</returns>
public static byte[] SHA256Buffer(this string instance)
{
- return godot_icall_String_sha256_buffer(instance);
+ using godot_string instanceStr = Marshaling.ConvertStringToNative(instance);
+ NativeFuncs.godotsharp_string_sha256_buffer(instanceStr, out var sha256Buffer);
+ using (sha256Buffer)
+ return Marshaling.ConvertNativePackedByteArrayToSystemArray(sha256Buffer);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern byte[] godot_icall_String_sha256_buffer(string str);
-
/// <summary>
/// Returns the SHA-256 hash of the string as a string.
/// </summary>
@@ -1335,12 +1343,12 @@ namespace Godot
/// <returns>The SHA-256 hash of the string.</returns>
public static string SHA256Text(this string instance)
{
- return godot_icall_String_sha256_text(instance);
+ using godot_string instanceStr = Marshaling.ConvertStringToNative(instance);
+ NativeFuncs.godotsharp_string_sha256_text(instanceStr, out var sha256Text);
+ using (sha256Text)
+ return Marshaling.ConvertStringToManaged(sha256Text);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_String_sha256_text(string str);
-
/// <summary>
/// Returns the similarity index of the text compared to this string.
/// 1 means totally similar and 0 means totally dissimilar.
@@ -1355,6 +1363,7 @@ namespace Godot
// Equal strings are totally similar
return 1.0f;
}
+
if (instance.Length < 2 || text.Length < 2)
{
// No way to calculate similarity without a single bigram
@@ -1390,12 +1399,12 @@ namespace Godot
/// </summary>
public static string SimplifyPath(this string instance)
{
- return godot_icall_String_simplify_path(instance);
+ using godot_string instanceStr = Marshaling.ConvertStringToNative(instance);
+ NativeFuncs.godotsharp_string_simplify_path(instanceStr, out godot_string simplifiedPath);
+ using (simplifiedPath)
+ return Marshaling.ConvertStringToManaged(simplifiedPath);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string godot_icall_String_simplify_path(string str);
-
/// <summary>
/// Split the string by a divisor string, return an array of the substrings.
/// Example "One,Two,Three" will return ["One","Two","Three"] if split by ",".
@@ -1409,7 +1418,8 @@ namespace Godot
/// <returns>The array of strings split from the string.</returns>
public static string[] Split(this string instance, string divisor, bool allowEmpty = true)
{
- return instance.Split(new[] { divisor }, allowEmpty ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries);
+ return instance.Split(new[] { divisor },
+ allowEmpty ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
@@ -1605,9 +1615,9 @@ namespace Godot
/// <seealso cref="XMLEscape(string)"/>
/// <param name="instance">The string to unescape.</param>
/// <returns>The unescaped string.</returns>
- public static string XMLUnescape(this string instance)
+ public static string? XMLUnescape(this string instance)
{
- return SecurityElement.FromString(instance).Text;
+ return SecurityElement.FromString(instance)?.Text;
}
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringName.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringName.cs
index b1d504410b..b9ee0bc278 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringName.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringName.cs
@@ -1,5 +1,5 @@
using System;
-using System.Runtime.CompilerServices;
+using Godot.NativeInterop;
namespace Godot
{
@@ -10,20 +10,11 @@ namespace Godot
/// Comparing them is much faster than with regular strings, because only the pointers are compared,
/// not the whole strings.
/// </summary>
- public sealed partial class StringName : IDisposable
+ public sealed class StringName : IDisposable
{
- private IntPtr ptr;
+ internal godot_string_name.movable NativeValue;
- internal static IntPtr GetPtr(StringName instance)
- {
- if (instance == null)
- throw new NullReferenceException($"The instance of type {nameof(StringName)} is null.");
-
- if (instance.ptr == IntPtr.Zero)
- throw new ObjectDisposedException(instance.GetType().FullName);
-
- return instance.ptr;
- }
+ private WeakReference<IDisposable> _weakReferenceToSelf;
~StringName()
{
@@ -39,35 +30,45 @@ namespace Godot
GC.SuppressFinalize(this);
}
- private void Dispose(bool disposing)
+ public void Dispose(bool disposing)
{
- if (ptr != IntPtr.Zero)
+ // Always dispose `NativeValue` even if disposing is true
+ NativeValue.DangerousSelfRef.Dispose();
+
+ if (_weakReferenceToSelf != null)
{
- godot_icall_StringName_Dtor(ptr);
- ptr = IntPtr.Zero;
+ DisposablesTracker.UnregisterDisposable(_weakReferenceToSelf);
}
}
- internal StringName(IntPtr ptr)
+ private StringName(godot_string_name nativeValueToOwn)
{
- this.ptr = ptr;
+ NativeValue = (godot_string_name.movable)nativeValueToOwn;
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
}
+ // Explicit name to make it very clear
+ internal static StringName CreateTakingOwnershipOfDisposableValue(godot_string_name nativeValueToOwn)
+ => new StringName(nativeValueToOwn);
+
/// <summary>
/// Constructs an empty <see cref="StringName"/>.
/// </summary>
public StringName()
{
- ptr = IntPtr.Zero;
}
/// <summary>
- /// Constructs a <see cref="StringName"/> from the given <paramref name="path"/> string.
+ /// Constructs a <see cref="StringName"/> from the given <paramref name="name"/> string.
/// </summary>
- /// <param name="path">String to construct the <see cref="StringName"/> from.</param>
- public StringName(string path)
+ /// <param name="name">String to construct the <see cref="StringName"/> from.</param>
+ public StringName(string name)
{
- ptr = path == null ? IntPtr.Zero : godot_icall_StringName_Ctor(path);
+ if (!string.IsNullOrEmpty(name))
+ {
+ NativeValue = (godot_string_name.movable)NativeFuncs.godotsharp_string_name_new_from_string(name);
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+ }
}
/// <summary>
@@ -80,7 +81,7 @@ namespace Godot
/// Converts a <see cref="StringName"/> to a string.
/// </summary>
/// <param name="from">The <see cref="StringName"/> to convert.</param>
- public static implicit operator string(StringName from) => from.ToString();
+ public static implicit operator string(StringName from) => from?.ToString();
/// <summary>
/// Converts this <see cref="StringName"/> to a string.
@@ -88,28 +89,75 @@ namespace Godot
/// <returns>A string representation of this <see cref="StringName"/>.</returns>
public override string ToString()
{
- return ptr == IntPtr.Zero ? string.Empty : godot_icall_StringName_operator_String(GetPtr(this));
+ if (IsEmpty)
+ return string.Empty;
+
+ var src = (godot_string_name)NativeValue;
+ NativeFuncs.godotsharp_string_name_as_string(out godot_string dest, src);
+ using (dest)
+ return Marshaling.ConvertStringToManaged(dest);
}
/// <summary>
/// Check whether this <see cref="StringName"/> is empty.
/// </summary>
/// <returns>If the <see cref="StringName"/> is empty.</returns>
- public bool IsEmpty()
+ public bool IsEmpty => NativeValue.DangerousSelfRef.IsEmpty;
+
+ public static bool operator ==(StringName left, StringName right)
{
- return ptr == IntPtr.Zero || godot_icall_StringName_is_empty(GetPtr(this));
+ if (left is null)
+ return right is null;
+ return left.Equals(right);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern IntPtr godot_icall_StringName_Ctor(string path);
+ public static bool operator !=(StringName left, StringName right)
+ {
+ return !(left == right);
+ }
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void godot_icall_StringName_Dtor(IntPtr ptr);
+ public bool Equals(StringName other)
+ {
+ if (other is null)
+ return false;
+ return NativeValue.DangerousSelfRef == other.NativeValue.DangerousSelfRef;
+ }
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern string godot_icall_StringName_operator_String(IntPtr ptr);
+ public static bool operator ==(StringName left, in godot_string_name right)
+ {
+ if (left is null)
+ return right.IsEmpty;
+ return left.Equals(right);
+ }
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool godot_icall_StringName_is_empty(IntPtr ptr);
+ public static bool operator !=(StringName left, in godot_string_name right)
+ {
+ return !(left == right);
+ }
+
+ public static bool operator ==(in godot_string_name left, StringName right)
+ {
+ return right == left;
+ }
+
+ public static bool operator !=(in godot_string_name left, StringName right)
+ {
+ return !(right == left);
+ }
+
+ public bool Equals(in godot_string_name other)
+ {
+ return NativeValue.DangerousSelfRef == other;
+ }
+
+ public override bool Equals(object obj)
+ {
+ return ReferenceEquals(this, obj) || (obj is StringName other && Equals(other));
+ }
+
+ public override int GetHashCode()
+ {
+ return NativeValue.GetHashCode();
+ }
}
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs
index 68d097eb4e..70cf8bbe22 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -93,7 +88,7 @@ namespace Godot
case 2:
return origin;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(column));
}
}
set
@@ -110,7 +105,7 @@ namespace Godot
origin = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(column));
}
}
}
@@ -389,31 +384,6 @@ namespace Godot
return copy;
}
- /// <summary>
- /// Returns a vector transformed (multiplied) by this transformation matrix.
- /// </summary>
- /// <seealso cref="XformInv(Vector2)"/>
- /// <param name="v">A vector to transform.</param>
- /// <returns>The transformed vector.</returns>
- [Obsolete("Xform is deprecated. Use the multiplication operator (Transform2D * Vector2) instead.")]
- public Vector2 Xform(Vector2 v)
- {
- return new Vector2(Tdotx(v), Tdoty(v)) + origin;
- }
-
- /// <summary>
- /// Returns a vector transformed (multiplied) by the inverse transformation matrix.
- /// </summary>
- /// <seealso cref="Xform(Vector2)"/>
- /// <param name="v">A vector to inversely transform.</param>
- /// <returns>The inversely transformed vector.</returns>
- [Obsolete("XformInv is deprecated. Use the multiplication operator (Vector2 * Transform2D) instead.")]
- public Vector2 XformInv(Vector2 v)
- {
- Vector2 vInv = v - origin;
- return new Vector2(x.Dot(vInv), y.Dot(vInv));
- }
-
// Constants
private static readonly Transform2D _identity = new Transform2D(1, 0, 0, 1, 0, 0);
private static readonly Transform2D _flipX = new Transform2D(-1, 0, 0, 1, 0, 0);
@@ -507,7 +477,7 @@ namespace Godot
}
/// <summary>
- /// Returns a Vector2 transformed (multiplied) by transformation matrix.
+ /// Returns a Vector2 transformed (multiplied) by the transformation matrix.
/// </summary>
/// <param name="transform">The transformation to apply.</param>
/// <param name="vector">A Vector2 to transform.</param>
@@ -530,7 +500,7 @@ namespace Godot
}
/// <summary>
- /// Returns a Rect2 transformed (multiplied) by transformation matrix.
+ /// Returns a Rect2 transformed (multiplied) by the transformation matrix.
/// </summary>
/// <param name="transform">The transformation to apply.</param>
/// <param name="rect">A Rect2 to transform.</param>
@@ -541,7 +511,7 @@ namespace Godot
Vector2 toX = transform.x * rect.Size.x;
Vector2 toY = transform.y * rect.Size.y;
- return new Rect2(pos, rect.Size).Expand(pos + toX).Expand(pos + toY).Expand(pos + toX + toY);
+ return new Rect2(pos, new Vector2()).Expand(pos + toX).Expand(pos + toY).Expand(pos + toX + toY);
}
/// <summary>
@@ -557,11 +527,11 @@ namespace Godot
Vector2 to2 = new Vector2(rect.Position.x + rect.Size.x, rect.Position.y + rect.Size.y) * transform;
Vector2 to3 = new Vector2(rect.Position.x + rect.Size.x, rect.Position.y) * transform;
- return new Rect2(pos, rect.Size).Expand(to1).Expand(to2).Expand(to3);
+ return new Rect2(pos, new Vector2()).Expand(to1).Expand(to2).Expand(to3);
}
/// <summary>
- /// Returns a copy of the given Vector2[] transformed (multiplied) by transformation matrix.
+ /// Returns a copy of the given Vector2[] transformed (multiplied) by the transformation matrix.
/// </summary>
/// <param name="transform">The transformation to apply.</param>
/// <param name="array">A Vector2[] to transform.</param>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs
index 9eaf4f3252..5481225e3f 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -52,7 +47,7 @@ namespace Godot
case 3:
return origin;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(column));
}
}
set
@@ -72,7 +67,7 @@ namespace Godot
origin = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(column));
}
}
}
@@ -113,7 +108,7 @@ namespace Godot
public Transform3D AffineInverse()
{
Basis basisInv = basis.Inverse();
- return new Transform3D(basisInv, basisInv.Xform(-origin));
+ return new Transform3D(basisInv, basisInv * -origin);
}
/// <summary>
@@ -152,7 +147,7 @@ namespace Godot
public Transform3D Inverse()
{
Basis basisTr = basis.Transposed();
- return new Transform3D(basisTr, basisTr.Xform(-origin));
+ return new Transform3D(basisTr, basisTr * -origin);
}
/// <summary>
@@ -168,7 +163,7 @@ namespace Godot
/// <param name="target">The object to look at.</param>
/// <param name="up">The relative up direction.</param>
/// <returns>The resulting transform.</returns>
- public Transform3D LookingAt(Vector3 target, Vector3 up)
+ public readonly Transform3D LookingAt(Vector3 target, Vector3 up)
{
Transform3D t = this;
t.SetLookAt(origin, target, up);
@@ -194,7 +189,7 @@ namespace Godot
/// <param name="axis">The axis to rotate around. Must be normalized.</param>
/// <param name="angle">The angle to rotate, in radians.</param>
/// <returns>The rotated transformation matrix.</returns>
- public Transform3D Rotated(Vector3 axis, real_t angle)
+ public readonly Transform3D Rotated(Vector3 axis, real_t angle)
{
return new Transform3D(new Basis(axis, angle), new Vector3()) * this;
}
@@ -291,43 +286,6 @@ namespace Godot
));
}
- /// <summary>
- /// Returns a vector transformed (multiplied) by this transformation matrix.
- /// </summary>
- /// <seealso cref="XformInv(Vector3)"/>
- /// <param name="v">A vector to transform.</param>
- /// <returns>The transformed vector.</returns>
- public Vector3 Xform(Vector3 v)
- {
- return new Vector3
- (
- basis.Row0.Dot(v) + origin.x,
- basis.Row1.Dot(v) + origin.y,
- basis.Row2.Dot(v) + origin.z
- );
- }
-
- /// <summary>
- /// Returns a vector transformed (multiplied) by the transposed transformation matrix.
- ///
- /// Note: This results in a multiplication by the inverse of the
- /// transformation matrix only if it represents a rotation-reflection.
- /// </summary>
- /// <seealso cref="Xform(Vector3)"/>
- /// <param name="v">A vector to inversely transform.</param>
- /// <returns>The inversely transformed vector.</returns>
- public Vector3 XformInv(Vector3 v)
- {
- Vector3 vInv = v - origin;
-
- return new Vector3
- (
- (basis.Row0[0] * vInv.x) + (basis.Row1[0] * vInv.y) + (basis.Row2[0] * vInv.z),
- (basis.Row0[1] * vInv.x) + (basis.Row1[1] * vInv.y) + (basis.Row2[1] * vInv.z),
- (basis.Row0[2] * vInv.x) + (basis.Row1[2] * vInv.y) + (basis.Row2[2] * vInv.z)
- );
- }
-
// Constants
private static readonly Transform3D _identity = new Transform3D(Basis.Identity, Vector3.Zero);
private static readonly Transform3D _flipX = new Transform3D(new Basis(-1, 0, 0, 0, 1, 0, 0, 0, 1), Vector3.Zero);
@@ -404,12 +362,188 @@ namespace Godot
/// <returns>The composed transform.</returns>
public static Transform3D operator *(Transform3D left, Transform3D right)
{
- left.origin = left.Xform(right.origin);
+ left.origin = left * right.origin;
left.basis *= right.basis;
return left;
}
/// <summary>
+ /// Returns a Vector3 transformed (multiplied) by the transformation matrix.
+ /// </summary>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <param name="vector">A Vector3 to transform.</param>
+ /// <returns>The transformed Vector3.</returns>
+ public static Vector3 operator *(Transform3D transform, Vector3 vector)
+ {
+ return new Vector3
+ (
+ transform.basis.Row0.Dot(vector) + transform.origin.x,
+ transform.basis.Row1.Dot(vector) + transform.origin.y,
+ transform.basis.Row2.Dot(vector) + transform.origin.z
+ );
+ }
+
+ /// <summary>
+ /// Returns a Vector3 transformed (multiplied) by the transposed transformation matrix.
+ ///
+ /// Note: This results in a multiplication by the inverse of the
+ /// transformation matrix only if it represents a rotation-reflection.
+ /// </summary>
+ /// <param name="vector">A Vector3 to inversely transform.</param>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <returns>The inversely transformed Vector3.</returns>
+ public static Vector3 operator *(Vector3 vector, Transform3D transform)
+ {
+ Vector3 vInv = vector - transform.origin;
+
+ return new Vector3
+ (
+ (transform.basis.Row0[0] * vInv.x) + (transform.basis.Row1[0] * vInv.y) + (transform.basis.Row2[0] * vInv.z),
+ (transform.basis.Row0[1] * vInv.x) + (transform.basis.Row1[1] * vInv.y) + (transform.basis.Row2[1] * vInv.z),
+ (transform.basis.Row0[2] * vInv.x) + (transform.basis.Row1[2] * vInv.y) + (transform.basis.Row2[2] * vInv.z)
+ );
+ }
+
+ /// <summary>
+ /// Returns an AABB transformed (multiplied) by the transformation matrix.
+ /// </summary>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <param name="aabb">An AABB to transform.</param>
+ /// <returns>The transformed AABB.</returns>
+ public static AABB operator *(Transform3D transform, AABB aabb)
+ {
+ Vector3 min = aabb.Position;
+ Vector3 max = aabb.Position + aabb.Size;
+
+ Vector3 tmin = transform.origin;
+ Vector3 tmax = transform.origin;
+ for (int i = 0; i < 3; i++)
+ {
+ for (int j = 0; j < 3; j++)
+ {
+ real_t e = transform.basis[i][j] * min[j];
+ real_t f = transform.basis[i][j] * max[j];
+ if (e < f)
+ {
+ tmin[i] += e;
+ tmax[i] += f;
+ }
+ else
+ {
+ tmin[i] += f;
+ tmax[i] += e;
+ }
+ }
+ }
+
+ return new AABB(tmin, tmax - tmin);
+ }
+
+ /// <summary>
+ /// Returns an AABB transformed (multiplied) by the inverse transformation matrix.
+ /// </summary>
+ /// <param name="aabb">An AABB to inversely transform.</param>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <returns>The inversely transformed AABB.</returns>
+ public static AABB operator *(AABB aabb, Transform3D transform)
+ {
+ Vector3 pos = new Vector3(aabb.Position.x + aabb.Size.x, aabb.Position.y + aabb.Size.y, aabb.Position.z + aabb.Size.z) * transform;
+ Vector3 to1 = new Vector3(aabb.Position.x + aabb.Size.x, aabb.Position.y + aabb.Size.y, aabb.Position.z) * transform;
+ Vector3 to2 = new Vector3(aabb.Position.x + aabb.Size.x, aabb.Position.y, aabb.Position.z + aabb.Size.z) * transform;
+ Vector3 to3 = new Vector3(aabb.Position.x + aabb.Size.x, aabb.Position.y, aabb.Position.z) * transform;
+ Vector3 to4 = new Vector3(aabb.Position.x, aabb.Position.y + aabb.Size.y, aabb.Position.z + aabb.Size.z) * transform;
+ Vector3 to5 = new Vector3(aabb.Position.x, aabb.Position.y + aabb.Size.y, aabb.Position.z) * transform;
+ Vector3 to6 = new Vector3(aabb.Position.x, aabb.Position.y, aabb.Position.z + aabb.Size.z) * transform;
+ Vector3 to7 = new Vector3(aabb.Position.x, aabb.Position.y, aabb.Position.z) * transform;
+
+ return new AABB(pos, new Vector3()).Expand(to1).Expand(to2).Expand(to3).Expand(to4).Expand(to5).Expand(to6).Expand(to7);
+ }
+
+ /// <summary>
+ /// Returns a Plane transformed (multiplied) by the transformation matrix.
+ /// </summary>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <param name="plane">A Plane to transform.</param>
+ /// <returns>The transformed Plane.</returns>
+ public static Plane operator *(Transform3D transform, Plane plane)
+ {
+ Basis bInvTrans = transform.basis.Inverse().Transposed();
+
+ // Transform a single point on the plane.
+ Vector3 point = transform * (plane.Normal * plane.D);
+
+ // Use inverse transpose for correct normals with non-uniform scaling.
+ Vector3 normal = (bInvTrans * plane.Normal).Normalized();
+
+ real_t d = normal.Dot(point);
+ return new Plane(normal, d);
+ }
+
+ /// <summary>
+ /// Returns a Plane transformed (multiplied) by the inverse transformation matrix.
+ /// </summary>
+ /// <param name="plane">A Plane to inversely transform.</param>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <returns>The inversely transformed Plane.</returns>
+ public static Plane operator *(Plane plane, Transform3D transform)
+ {
+ Transform3D tInv = transform.AffineInverse();
+ Basis bTrans = transform.basis.Transposed();
+
+ // Transform a single point on the plane.
+ Vector3 point = tInv * (plane.Normal * plane.D);
+
+ // Note that instead of precalculating the transpose, an alternative
+ // would be to use the transpose for the basis transform.
+ // However that would be less SIMD friendly (requiring a swizzle).
+ // So the cost is one extra precalced value in the calling code.
+ // This is probably worth it, as this could be used in bottleneck areas. And
+ // where it is not a bottleneck, the non-fast method is fine.
+
+ // Use transpose for correct normals with non-uniform scaling.
+ Vector3 normal = (bTrans * plane.Normal).Normalized();
+
+ real_t d = normal.Dot(point);
+ return new Plane(normal, d);
+ }
+
+ /// <summary>
+ /// Returns a copy of the given Vector3[] transformed (multiplied) by the transformation matrix.
+ /// </summary>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <param name="array">A Vector3[] to transform.</param>
+ /// <returns>The transformed copy of the Vector3[].</returns>
+ public static Vector3[] operator *(Transform3D transform, Vector3[] array)
+ {
+ Vector3[] newArray = new Vector3[array.Length];
+
+ for (int i = 0; i < array.Length; i++)
+ {
+ newArray[i] = transform * array[i];
+ }
+
+ return newArray;
+ }
+
+ /// <summary>
+ /// Returns a copy of the given Vector3[] transformed (multiplied) by the inverse transformation matrix.
+ /// </summary>
+ /// <param name="array">A Vector3[] to inversely transform.</param>
+ /// <param name="transform">The transformation to apply.</param>
+ /// <returns>The inversely transformed copy of the Vector3[].</returns>
+ public static Vector3[] operator *(Vector3[] array, Transform3D transform)
+ {
+ Vector3[] newArray = new Vector3[array.Length];
+
+ for (int i = 0; i < array.Length; i++)
+ {
+ newArray[i] = array[i] * transform;
+ }
+
+ return newArray;
+ }
+
+ /// <summary>
/// Returns <see langword="true"/> if the transforms are exactly equal.
/// Note: Due to floating-point precision errors, consider using
/// <see cref="IsEqualApprox"/> instead, which is more reliable.
@@ -443,7 +577,7 @@ namespace Godot
/// </summary>
/// <param name="obj">The object to compare with.</param>
/// <returns>Whether or not the transform and the object are exactly equal.</returns>
- public override bool Equals(object obj)
+ public override readonly bool Equals(object obj)
{
if (obj is Transform3D)
{
@@ -460,7 +594,7 @@ namespace Godot
/// </summary>
/// <param name="other">The other transform to compare.</param>
/// <returns>Whether or not the matrices are exactly equal.</returns>
- public bool Equals(Transform3D other)
+ public readonly bool Equals(Transform3D other)
{
return basis.Equals(other.basis) && origin.Equals(other.origin);
}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/UnhandledExceptionArgs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/UnhandledExceptionArgs.cs
deleted file mode 100644
index eae8927ceb..0000000000
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/UnhandledExceptionArgs.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System;
-
-namespace Godot
-{
- /// <summary>
- /// Event arguments for when unhandled exceptions occur.
- /// </summary>
- public class UnhandledExceptionArgs
- {
- /// <summary>
- /// Exception object.
- /// </summary>
- public Exception Exception { get; private set; }
-
- internal UnhandledExceptionArgs(Exception exception)
- {
- Exception = exception;
- }
- }
-}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
index 67f70390dd..04c2ea7eb9 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -62,7 +57,7 @@ namespace Godot
case 1:
return y;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
set
@@ -76,7 +71,7 @@ namespace Godot
y = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
@@ -644,16 +639,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a new <see cref="Vector2"/> from an existing <see cref="Vector2"/>.
- /// </summary>
- /// <param name="v">The existing <see cref="Vector2"/>.</param>
- public Vector2(Vector2 v)
- {
- x = v.x;
- y = v.y;
- }
-
- /// <summary>
/// Creates a unit Vector2 rotated to the given angle. This is equivalent to doing
/// <c>Vector2(Mathf.Cos(angle), Mathf.Sin(angle))</c> or <c>Vector2.Right.Rotated(angle)</c>.
/// </summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs
index b61954a84c..a8f42972d7 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -62,7 +57,7 @@ namespace Godot
case 1:
return y;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
set
@@ -76,7 +71,7 @@ namespace Godot
y = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
@@ -355,27 +350,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a new <see cref="Vector2i"/> from an existing <see cref="Vector2i"/>.
- /// </summary>
- /// <param name="vi">The existing <see cref="Vector2i"/>.</param>
- public Vector2i(Vector2i vi)
- {
- this.x = vi.x;
- this.y = vi.y;
- }
-
- /// <summary>
- /// Constructs a new <see cref="Vector2i"/> from an existing <see cref="Vector2"/>
- /// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>.
- /// </summary>
- /// <param name="v">The <see cref="Vector2"/> to convert.</param>
- public Vector2i(Vector2 v)
- {
- this.x = Mathf.RoundToInt(v.x);
- this.y = Mathf.RoundToInt(v.y);
- }
-
- /// <summary>
/// Adds each component of the <see cref="Vector2i"/>
/// with the components of the given <see cref="Vector2i"/>.
/// </summary>
@@ -679,7 +653,10 @@ namespace Godot
/// <param name="value">The vector to convert.</param>
public static explicit operator Vector2i(Vector2 value)
{
- return new Vector2i(value);
+ return new Vector2i(
+ Mathf.RoundToInt(value.x),
+ Mathf.RoundToInt(value.y)
+ );
}
/// <summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
index 67a98efc2d..d5941d6b60 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -74,7 +69,7 @@ namespace Godot
case 2:
return z;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
set
@@ -91,7 +86,7 @@ namespace Godot
z = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
@@ -523,7 +518,7 @@ namespace Godot
throw new ArgumentException("Argument is not normalized", nameof(axis));
}
#endif
- return new Basis(axis, angle).Xform(this);
+ return new Basis(axis, angle) * this;
}
/// <summary>
@@ -697,17 +692,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a new <see cref="Vector3"/> from an existing <see cref="Vector3"/>.
- /// </summary>
- /// <param name="v">The existing <see cref="Vector3"/>.</param>
- public Vector3(Vector3 v)
- {
- x = v.x;
- y = v.y;
- z = v.z;
- }
-
- /// <summary>
/// Adds each component of the <see cref="Vector3"/>
/// with the components of the given <see cref="Vector3"/>.
/// </summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs
index 0d4894f206..eb46f36e7c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -74,7 +69,7 @@ namespace Godot
case 2:
return z;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
set
@@ -91,7 +86,7 @@ namespace Godot
z = value;
return;
default:
- throw new IndexOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
@@ -335,29 +330,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3i"/>.
- /// </summary>
- /// <param name="vi">The existing <see cref="Vector3i"/>.</param>
- public Vector3i(Vector3i vi)
- {
- this.x = vi.x;
- this.y = vi.y;
- this.z = vi.z;
- }
-
- /// <summary>
- /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3"/>
- /// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>.
- /// </summary>
- /// <param name="v">The <see cref="Vector3"/> to convert.</param>
- public Vector3i(Vector3 v)
- {
- this.x = Mathf.RoundToInt(v.x);
- this.y = Mathf.RoundToInt(v.y);
- this.z = Mathf.RoundToInt(v.z);
- }
-
- /// <summary>
/// Adds each component of the <see cref="Vector3i"/>
/// with the components of the given <see cref="Vector3i"/>.
/// </summary>
@@ -689,7 +661,11 @@ namespace Godot
/// <param name="value">The vector to convert.</param>
public static explicit operator Vector3i(Vector3 value)
{
- return new Vector3i(value);
+ return new Vector3i(
+ Mathf.RoundToInt(value.x),
+ Mathf.RoundToInt(value.y),
+ Mathf.RoundToInt(value.z)
+ );
}
/// <summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs
index 4af817455c..20a24616ce 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -482,18 +477,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a new <see cref="Vector4"/> from an existing <see cref="Vector4"/>.
- /// </summary>
- /// <param name="v">The existing <see cref="Vector4"/>.</param>
- public Vector4(Vector4 v)
- {
- x = v.x;
- y = v.y;
- z = v.z;
- w = v.w;
- }
-
- /// <summary>
/// Adds each component of the <see cref="Vector4"/>
/// with the components of the given <see cref="Vector4"/>.
/// </summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4i.cs
index 365dcef486..11c2b7234b 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4i.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4i.cs
@@ -1,8 +1,3 @@
-#if REAL_T_IS_DOUBLE
-using real_t = System.Double;
-#else
-using real_t = System.Single;
-#endif
using System;
using System.Runtime.InteropServices;
@@ -263,31 +258,6 @@ namespace Godot
}
/// <summary>
- /// Constructs a new <see cref="Vector4i"/> from an existing <see cref="Vector4i"/>.
- /// </summary>
- /// <param name="vi">The existing <see cref="Vector4i"/>.</param>
- public Vector4i(Vector4i vi)
- {
- this.x = vi.x;
- this.y = vi.y;
- this.z = vi.z;
- this.w = vi.w;
- }
-
- /// <summary>
- /// Constructs a new <see cref="Vector4i"/> from an existing <see cref="Vector4"/>
- /// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>.
- /// </summary>
- /// <param name="v">The <see cref="Vector4"/> to convert.</param>
- public Vector4i(Vector4 v)
- {
- this.x = Mathf.RoundToInt(v.x);
- this.y = Mathf.RoundToInt(v.y);
- this.z = Mathf.RoundToInt(v.z);
- this.w = Mathf.RoundToInt(v.w);
- }
-
- /// <summary>
/// Adds each component of the <see cref="Vector4i"/>
/// with the components of the given <see cref="Vector4i"/>.
/// </summary>
@@ -643,7 +613,12 @@ namespace Godot
/// <param name="value">The vector to convert.</param>
public static explicit operator Vector4i(Vector4 value)
{
- return new Vector4i(value);
+ return new Vector4i(
+ Mathf.RoundToInt(value.x),
+ Mathf.RoundToInt(value.y),
+ Mathf.RoundToInt(value.z),
+ Mathf.RoundToInt(value.w)
+ );
}
/// <summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GlobalUsings.cs b/modules/mono/glue/GodotSharp/GodotSharp/GlobalUsings.cs
new file mode 100644
index 0000000000..263a934fae
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/GlobalUsings.cs
@@ -0,0 +1,5 @@
+#if REAL_T_IS_DOUBLE
+global using real_t = System.Double;
+#else
+global using real_t = System.Single;
+#endif
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
index 4f55ce47e8..aae7a5ebfa 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
+++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
@@ -4,25 +4,71 @@
<OutputPath>bin/$(Configuration)</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<RootNamespace>Godot</RootNamespace>
- <TargetFramework>netstandard2.1</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<DocumentationFile>$(OutputPath)/$(AssemblyName).xml</DocumentationFile>
<EnableDefaultItems>false</EnableDefaultItems>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <LangVersion>10</LangVersion>
+
+ <AnalysisMode>Recommended</AnalysisMode>
+
+ <!-- Disabled temporarily as it pollutes the warnings, but we need to document public APIs. -->
+ <NoWarn>CS1591</NoWarn>
</PropertyGroup>
<PropertyGroup>
+ <Description>Godot C# Core API.</Description>
+ <Authors>Godot Engine contributors</Authors>
+
+ <PackageId>GodotSharp</PackageId>
+ <Version>4.0.0</Version>
+ <PackageVersion>$(PackageVersion_GodotSharp)</PackageVersion>
+ <RepositoryUrl>https://github.com/godotengine/godot/tree/master/modules/mono/glue/GodotSharp/GodotSharp</RepositoryUrl>
+ <PackageProjectUrl>$(RepositoryUrl)</PackageProjectUrl>
+ <PackageLicenseExpression>MIT</PackageLicenseExpression>
+
+ <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+ </PropertyGroup>
+ <ItemGroup>
+ <!-- SdkPackageVersions.props for easy access -->
+ <None Include="$(GodotSdkPackageVersionsFilePath)">
+ <Link>SdkPackageVersions.props</Link>
+ </None>
+ </ItemGroup>
+ <PropertyGroup>
<DefineConstants>$(DefineConstants);GODOT</DefineConstants>
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="ReflectionAnalyzers" Version="0.1.22-dev" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers" />
+ <!--PackageReference Include="IDisposableAnalyzers" Version="3.4.13" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers" /-->
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Godot.SourceGenerators.Internal\Godot.SourceGenerators.Internal.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
+ </ItemGroup>
+ <!-- Sources -->
+ <ItemGroup>
<Compile Include="Core\AABB.cs" />
+ <Compile Include="Core\Bridge\GodotSerializationInfo.cs" />
+ <Compile Include="Core\Bridge\MethodInfo.cs" />
+ <Compile Include="Core\CustomGCHandle.cs" />
<Compile Include="Core\Array.cs" />
<Compile Include="Core\Attributes\AssemblyHasScriptsAttribute.cs" />
- <Compile Include="Core\Attributes\DisableGodotGeneratorsAttribute.cs" />
<Compile Include="Core\Attributes\ExportAttribute.cs" />
- <Compile Include="Core\Attributes\GodotMethodAttribute.cs" />
+ <Compile Include="Core\Attributes\ExportCategoryAttribute.cs" />
+ <Compile Include="Core\Attributes\ExportGroupAttribute.cs" />
+ <Compile Include="Core\Attributes\ExportSubgroupAttribute.cs" />
+ <Compile Include="Core\Attributes\MustBeVariantAttribute.cs" />
<Compile Include="Core\Attributes\RPCAttribute.cs" />
<Compile Include="Core\Attributes\ScriptPathAttribute.cs" />
<Compile Include="Core\Attributes\SignalAttribute.cs" />
<Compile Include="Core\Attributes\ToolAttribute.cs" />
<Compile Include="Core\Basis.cs" />
+ <Compile Include="Core\Bridge\CSharpInstanceBridge.cs" />
+ <Compile Include="Core\Bridge\GCHandleBridge.cs" />
+ <Compile Include="Core\Bridge\AlcReloadCfg.cs" />
+ <Compile Include="Core\Bridge\ManagedCallbacks.cs" />
+ <Compile Include="Core\Bridge\PropertyInfo.cs" />
+ <Compile Include="Core\Bridge\ScriptManagerBridge.cs" />
+ <Compile Include="Core\Bridge\ScriptManagerBridge.types.cs" />
<Compile Include="Core\Callable.cs" />
<Compile Include="Core\Color.cs" />
<Compile Include="Core\Colors.cs" />
@@ -30,45 +76,58 @@
<Compile Include="Core\DelegateUtils.cs" />
<Compile Include="Core\Dictionary.cs" />
<Compile Include="Core\Dispatcher.cs" />
- <Compile Include="Core\DynamicObject.cs" />
<Compile Include="Core\Extensions\NodeExtensions.cs" />
<Compile Include="Core\Extensions\ObjectExtensions.cs" />
<Compile Include="Core\Extensions\PackedSceneExtensions.cs" />
<Compile Include="Core\Extensions\ResourceLoaderExtensions.cs" />
- <Compile Include="Core\Extensions\SceneTreeExtensions.cs" />
<Compile Include="Core\GD.cs" />
<Compile Include="Core\GodotSynchronizationContext.cs" />
<Compile Include="Core\GodotTaskScheduler.cs" />
<Compile Include="Core\GodotTraceListener.cs" />
<Compile Include="Core\GodotUnhandledExceptionEvent.cs" />
+ <Compile Include="Core\DisposablesTracker.cs" />
<Compile Include="Core\Interfaces\IAwaitable.cs" />
<Compile Include="Core\Interfaces\IAwaiter.cs" />
<Compile Include="Core\Interfaces\ISerializationListener.cs" />
- <Compile Include="Core\MarshalUtils.cs" />
<Compile Include="Core\Mathf.cs" />
<Compile Include="Core\MathfEx.cs" />
+ <Compile Include="Core\NativeInterop\CustomUnsafe.cs" />
+ <Compile Include="Core\NativeInterop\ExceptionUtils.cs" />
+ <Compile Include="Core\NativeInterop\GodotDllImportResolver.cs" />
+ <Compile Include="Core\NativeInterop\InteropUtils.cs" />
+ <Compile Include="Core\NativeInterop\NativeFuncs.extended.cs" />
+ <Compile Include="Core\NativeInterop\NativeVariantPtrArgs.cs" />
+ <Compile Include="Core\NativeInterop\VariantConversionCallbacks.cs" />
+ <Compile Include="Core\NativeInterop\VariantSpanHelpers.cs" />
+ <Compile Include="Core\NativeInterop\VariantUtils.cs" />
<Compile Include="Core\NodePath.cs" />
<Compile Include="Core\Object.base.cs" />
+ <Compile Include="Core\Object.exceptions.cs" />
<Compile Include="Core\Plane.cs" />
<Compile Include="Core\Projection.cs" />
<Compile Include="Core\Quaternion.cs" />
<Compile Include="Core\Rect2.cs" />
<Compile Include="Core\Rect2i.cs" />
+ <Compile Include="Core\ReflectionUtils.cs" />
<Compile Include="Core\RID.cs" />
+ <Compile Include="Core\NativeInterop\NativeFuncs.cs" />
+ <Compile Include="Core\NativeInterop\InteropStructs.cs" />
+ <Compile Include="Core\NativeInterop\Marshaling.cs" />
<Compile Include="Core\SignalInfo.cs" />
<Compile Include="Core\SignalAwaiter.cs" />
<Compile Include="Core\StringExtensions.cs" />
<Compile Include="Core\StringName.cs" />
<Compile Include="Core\Transform2D.cs" />
<Compile Include="Core\Transform3D.cs" />
- <Compile Include="Core\UnhandledExceptionArgs.cs" />
<Compile Include="Core\Vector2.cs" />
<Compile Include="Core\Vector2i.cs" />
<Compile Include="Core\Vector3.cs" />
<Compile Include="Core\Vector3i.cs" />
<Compile Include="Core\Vector4.cs" />
<Compile Include="Core\Vector4i.cs" />
+ <Compile Include="GlobalUsings.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Variant.cs" />
</ItemGroup>
<!--
We import a props file with auto-generated includes. This works well with Rider.
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj.DotSettings b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj.DotSettings
new file mode 100644
index 0000000000..1add6cc77e
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj.DotSettings
@@ -0,0 +1,5 @@
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=core/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=generated/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=generated_005Cgodotobjects/@EntryIndexedValue">True</s:Boolean>
+</wpf:ResourceDictionary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Variant.cs b/modules/mono/glue/GodotSharp/GodotSharp/Variant.cs
new file mode 100644
index 0000000000..85ef258922
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Variant.cs
@@ -0,0 +1,841 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+using Godot.NativeInterop;
+
+namespace Godot;
+
+#nullable enable
+
+[SuppressMessage("ReSharper", "RedundantNameQualifier")]
+public partial struct Variant : IDisposable
+{
+ internal godot_variant.movable NativeVar;
+ private object? _obj;
+ private Disposer? _disposer;
+
+ private sealed class Disposer : IDisposable
+ {
+ private godot_variant.movable _native;
+
+ private WeakReference<IDisposable>? _weakReferenceToSelf;
+
+ public Disposer(in godot_variant.movable nativeVar)
+ {
+ _native = nativeVar;
+ _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
+ }
+
+ ~Disposer()
+ {
+ Dispose(false);
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ private void Dispose(bool disposing)
+ {
+ _native.DangerousSelfRef.Dispose();
+
+ if (_weakReferenceToSelf != null)
+ {
+ DisposablesTracker.UnregisterDisposable(_weakReferenceToSelf);
+ }
+ }
+ }
+
+ private Variant(in godot_variant nativeVar)
+ {
+ NativeVar = (godot_variant.movable)nativeVar;
+ _obj = null;
+
+ switch (nativeVar.Type)
+ {
+ case Type.Nil:
+ case Type.Bool:
+ case Type.Int:
+ case Type.Float:
+ case Type.Vector2:
+ case Type.Vector2i:
+ case Type.Rect2:
+ case Type.Rect2i:
+ case Type.Vector3:
+ case Type.Vector3i:
+ case Type.Plane:
+ case Type.Quaternion:
+ case Type.Color:
+ case Type.Rid:
+ _disposer = null;
+ break;
+ default:
+ {
+ _disposer = new Disposer(NativeVar);
+ break;
+ }
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ // Explicit name to make it very clear
+ public static Variant CreateTakingOwnershipOfDisposableValue(in godot_variant nativeValueToOwn) =>
+ new(nativeValueToOwn);
+
+ // Explicit name to make it very clear
+ public static Variant CreateCopyingBorrowed(in godot_variant nativeValueToOwn) =>
+ new(NativeFuncs.godotsharp_variant_new_copy(nativeValueToOwn));
+
+ /// <summary>
+ /// Constructs a new <see cref="Godot.NativeInterop.godot_variant"/> from this instance.
+ /// The caller is responsible of disposing the new instance to avoid memory leaks.
+ /// </summary>
+ public godot_variant CopyNativeVariant() =>
+ NativeFuncs.godotsharp_variant_new_copy((godot_variant)NativeVar);
+
+ public void Dispose()
+ {
+ _disposer?.Dispose();
+ NativeVar = default;
+ _obj = null;
+ }
+
+ // TODO: Consider renaming Variant.Type to VariantType and this property to Type. VariantType would also avoid ambiguity with System.Type.
+ public Type VariantType => NativeVar.DangerousSelfRef.Type;
+
+ public override string ToString() => AsString();
+
+ public object? Obj
+ {
+ get
+ {
+ if (_obj == null)
+ _obj = Marshaling.ConvertVariantToManagedObject((godot_variant)NativeVar);
+
+ return _obj;
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool AsBool() =>
+ VariantUtils.ConvertToBool((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public char AsChar() =>
+ (char)VariantUtils.ConvertToUInt16((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public sbyte AsSByte() =>
+ VariantUtils.ConvertToInt8((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public short AsInt16() =>
+ VariantUtils.ConvertToInt16((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int AsInt32() =>
+ VariantUtils.ConvertToInt32((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public long AsInt64() =>
+ VariantUtils.ConvertToInt64((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public byte AsByte() =>
+ VariantUtils.ConvertToUInt8((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ushort AsUInt16() =>
+ VariantUtils.ConvertToUInt16((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public uint AsUInt32() =>
+ VariantUtils.ConvertToUInt32((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ulong AsUInt64() =>
+ VariantUtils.ConvertToUInt64((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public float AsSingle() =>
+ VariantUtils.ConvertToFloat32((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public double AsDouble() =>
+ VariantUtils.ConvertToFloat64((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public string AsString() =>
+ VariantUtils.ConvertToStringObject((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector2 AsVector2() =>
+ VariantUtils.ConvertToVector2((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector2i AsVector2i() =>
+ VariantUtils.ConvertToVector2i((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Rect2 AsRect2() =>
+ VariantUtils.ConvertToRect2((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Rect2i AsRect2i() =>
+ VariantUtils.ConvertToRect2i((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Transform2D AsTransform2D() =>
+ VariantUtils.ConvertToTransform2D((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector3 AsVector3() =>
+ VariantUtils.ConvertToVector3((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector3i AsVector3i() =>
+ VariantUtils.ConvertToVector3i((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Basis AsBasis() =>
+ VariantUtils.ConvertToBasis((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Quaternion AsQuaternion() =>
+ VariantUtils.ConvertToQuaternion((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Transform3D AsTransform3D() =>
+ VariantUtils.ConvertToTransform3D((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector4 AsVector4() =>
+ VariantUtils.ConvertToVector4((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector4i AsVector4i() =>
+ VariantUtils.ConvertToVector4i((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Projection AsProjection() =>
+ VariantUtils.ConvertToProjection((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public AABB AsAABB() =>
+ VariantUtils.ConvertToAABB((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Color AsColor() =>
+ VariantUtils.ConvertToColor((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Plane AsPlane() =>
+ VariantUtils.ConvertToPlane((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Callable AsCallable() =>
+ VariantUtils.ConvertToCallableManaged((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public SignalInfo AsSignalInfo() =>
+ VariantUtils.ConvertToSignalInfo((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public byte[] AsByteArray() =>
+ VariantUtils.ConvertAsPackedByteArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int[] AsInt32Array() =>
+ VariantUtils.ConvertAsPackedInt32ArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public long[] AsInt64Array() =>
+ VariantUtils.ConvertAsPackedInt64ArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public float[] AsFloat32Array() =>
+ VariantUtils.ConvertAsPackedFloat32ArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public double[] AsFloat64Array() =>
+ VariantUtils.ConvertAsPackedFloat64ArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public string[] AsStringArray() =>
+ VariantUtils.ConvertAsPackedStringArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector2[] AsVector2Array() =>
+ VariantUtils.ConvertAsPackedVector2ArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector3[] AsVector3Array() =>
+ VariantUtils.ConvertAsPackedVector3ArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Color[] AsColorArray() =>
+ VariantUtils.ConvertAsPackedColorArrayToSystemArray((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public T[] AsGodotObjectArray<T>()
+ where T : Godot.Object =>
+ VariantUtils.ConvertToSystemArrayOfGodotObject<T>((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Collections.Dictionary<TKey, TValue> AsGodotDictionary<TKey, TValue>() =>
+ VariantUtils.ConvertToDictionaryObject<TKey, TValue>((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Collections.Array<T> AsGodotArray<T>() =>
+ VariantUtils.ConvertToArrayObject<T>((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public StringName[] AsSystemArrayOfStringName() =>
+ VariantUtils.ConvertToSystemArrayOfStringName((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public NodePath[] AsSystemArrayOfNodePath() =>
+ VariantUtils.ConvertToSystemArrayOfNodePath((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public RID[] AsSystemArrayOfRID() =>
+ VariantUtils.ConvertToSystemArrayOfRID((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Godot.Object AsGodotObject() =>
+ VariantUtils.ConvertToGodotObject((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public StringName AsStringName() =>
+ VariantUtils.ConvertToStringNameObject((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public NodePath AsNodePath() =>
+ VariantUtils.ConvertToNodePathObject((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public RID AsRID() =>
+ VariantUtils.ConvertToRID((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Collections.Dictionary AsGodotDictionary() =>
+ VariantUtils.ConvertToDictionaryObject((godot_variant)NativeVar);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Collections.Array AsGodotArray() =>
+ VariantUtils.ConvertToArrayObject((godot_variant)NativeVar);
+
+ // Explicit conversion operators to supported types
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator bool(Variant from) => from.AsBool();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator char(Variant from) => from.AsChar();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator sbyte(Variant from) => from.AsSByte();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator short(Variant from) => from.AsInt16();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator int(Variant from) => from.AsInt32();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator long(Variant from) => from.AsInt64();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator byte(Variant from) => from.AsByte();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator ushort(Variant from) => from.AsUInt16();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator uint(Variant from) => from.AsUInt32();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator ulong(Variant from) => from.AsUInt64();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator float(Variant from) => from.AsSingle();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator double(Variant from) => from.AsDouble();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator string(Variant from) => from.AsString();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector2(Variant from) => from.AsVector2();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector2i(Variant from) => from.AsVector2i();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Rect2(Variant from) => from.AsRect2();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Rect2i(Variant from) => from.AsRect2i();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Transform2D(Variant from) => from.AsTransform2D();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector3(Variant from) => from.AsVector3();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector3i(Variant from) => from.AsVector3i();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Basis(Variant from) => from.AsBasis();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Quaternion(Variant from) => from.AsQuaternion();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Transform3D(Variant from) => from.AsTransform3D();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector4(Variant from) => from.AsVector4();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector4i(Variant from) => from.AsVector4i();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Projection(Variant from) => from.AsProjection();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator AABB(Variant from) => from.AsAABB();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Color(Variant from) => from.AsColor();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Plane(Variant from) => from.AsPlane();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Callable(Variant from) => from.AsCallable();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator SignalInfo(Variant from) => from.AsSignalInfo();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator byte[](Variant from) => from.AsByteArray();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator int[](Variant from) => from.AsInt32Array();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator long[](Variant from) => from.AsInt64Array();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator float[](Variant from) => from.AsFloat32Array();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator double[](Variant from) => from.AsFloat64Array();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator string[](Variant from) => from.AsStringArray();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector2[](Variant from) => from.AsVector2Array();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Vector3[](Variant from) => from.AsVector3Array();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Color[](Variant from) => from.AsColorArray();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator StringName[](Variant from) => from.AsSystemArrayOfStringName();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator NodePath[](Variant from) => from.AsSystemArrayOfNodePath();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator RID[](Variant from) => from.AsSystemArrayOfRID();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Godot.Object(Variant from) => from.AsGodotObject();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator StringName(Variant from) => from.AsStringName();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator NodePath(Variant from) => from.AsNodePath();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator RID(Variant from) => from.AsRID();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Collections.Dictionary(Variant from) => from.AsGodotDictionary();
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static explicit operator Collections.Array(Variant from) => from.AsGodotArray();
+
+ // While we provide implicit conversion operators, normal methods are still needed for
+ // casts that are not done implicitly (e.g.: raw array to Span, enum to integer, etc).
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(bool from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(char from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(sbyte from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(short from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(int from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(long from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(byte from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(ushort from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(uint from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(ulong from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(float from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(double from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(string from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Vector2 from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Vector2i from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Rect2 from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Rect2i from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Transform2D from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Vector3 from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Vector3i from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Basis from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Quaternion from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Transform3D from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Vector4 from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Vector4i from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Projection from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(AABB from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Color from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Plane from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Callable from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(SignalInfo from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<byte> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<int> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<long> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<float> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<double> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<string> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<Vector2> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<Vector3> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<Color> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Godot.Object[] from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom<TKey, TValue>(Collections.Dictionary<TKey, TValue> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromDictionary(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom<T>(Collections.Array<T> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromArray(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<StringName> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<NodePath> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Span<RID> from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Godot.Object from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(StringName from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(NodePath from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(RID from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Collections.Dictionary from) => from;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Variant CreateFrom(Collections.Array from) => from;
+
+ // Implicit conversion operators
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(bool from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromBool(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(char from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(sbyte from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(short from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(int from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(long from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(byte from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(ushort from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(uint from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(ulong from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromInt(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(float from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromFloat(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(double from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromFloat(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(string from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromString(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Vector2 from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromVector2(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Vector2i from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromVector2i(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Rect2 from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromRect2(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Rect2i from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromRect2i(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Transform2D from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromTransform2D(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Vector3 from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromVector3(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Vector3i from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromVector3i(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Basis from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromBasis(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Quaternion from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromQuaternion(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Transform3D from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromTransform3D(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Vector4 from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromVector4(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Vector4i from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromVector4i(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Projection from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromProjection(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(AABB from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromAABB(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Color from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromColor(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Plane from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPlane(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Callable from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromCallable(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(SignalInfo from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSignalInfo(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<byte> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedByteArray(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<int> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedInt32Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<long> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedInt64Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<float> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedFloat32Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<double> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedFloat64Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<string> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedStringArray(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<Vector2> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedVector2Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<Vector3> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedVector3Array(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<Color> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedColorArray(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Godot.Object[] from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSystemArrayOfGodotObject(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<StringName> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSystemArrayOfStringName(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<NodePath> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSystemArrayOfNodePath(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Span<RID> from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSystemArrayOfRID(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Godot.Object from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromGodotObject(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(StringName from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromStringName(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(NodePath from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromNodePath(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(RID from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromRID(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Collections.Dictionary from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromDictionary(from));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator Variant(Collections.Array from) =>
+ CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromArray(from));
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
index a8c4ba96b5..ebf09aab7b 100644
--- a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
+++ b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
@@ -4,9 +4,24 @@
<OutputPath>bin/$(Configuration)</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<RootNamespace>Godot</RootNamespace>
- <TargetFramework>netstandard2.1</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<DocumentationFile>$(OutputPath)/$(AssemblyName).xml</DocumentationFile>
<EnableDefaultItems>false</EnableDefaultItems>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <LangVersion>10</LangVersion>
+ </PropertyGroup>
+ <PropertyGroup>
+ <Description>Godot C# Editor API.</Description>
+ <Authors>Godot Engine contributors</Authors>
+
+ <PackageId>GodotSharpEditor</PackageId>
+ <Version>4.0.0</Version>
+ <PackageVersion>$(PackageVersion_GodotSharp)</PackageVersion>
+ <RepositoryUrl>https://github.com/godotengine/godot/tree/master/modules/mono/glue/GodotSharp/GodotSharpEditor</RepositoryUrl>
+ <PackageProjectUrl>$(RepositoryUrl)</PackageProjectUrl>
+ <PackageLicenseExpression>MIT</PackageLicenseExpression>
+
+ <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<PropertyGroup>
<DefineConstants>$(DefineConstants);GODOT</DefineConstants>
diff --git a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj.DotSettings b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj.DotSettings
new file mode 100644
index 0000000000..c7ff6fd3ee
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj.DotSettings
@@ -0,0 +1,4 @@
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=generated/@EntryIndexedValue">True</s:Boolean>
+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=generated_005Cgodotobjects/@EntryIndexedValue">True</s:Boolean>
+</wpf:ResourceDictionary>
diff --git a/modules/mono/glue/arguments_vector.h b/modules/mono/glue/arguments_vector.h
deleted file mode 100644
index 4405809887..0000000000
--- a/modules/mono/glue/arguments_vector.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*************************************************************************/
-/* arguments_vector.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 ARGUMENTS_VECTOR_H
-#define ARGUMENTS_VECTOR_H
-
-#include "core/os/memory.h"
-
-template <typename T, int POOL_SIZE = 5>
-struct ArgumentsVector {
-private:
- T pool[POOL_SIZE];
- T *_ptr = nullptr;
- int size;
-
- ArgumentsVector() = delete;
- ArgumentsVector(const ArgumentsVector &) = delete;
-
-public:
- T *ptr() { return _ptr; }
- T &get(int p_idx) { return _ptr[p_idx]; }
- void set(int p_idx, const T &p_value) { _ptr[p_idx] = p_value; }
-
- explicit ArgumentsVector(int p_size) :
- size(p_size) {
- if (p_size <= POOL_SIZE) {
- _ptr = pool;
- } else {
- _ptr = memnew_arr(T, p_size);
- }
- }
-
- ~ArgumentsVector() {
- if (size > POOL_SIZE) {
- memdelete_arr(_ptr);
- }
- }
-};
-
-#endif // ARGUMENTS_VECTOR_H
diff --git a/modules/mono/glue/base_object_glue.cpp b/modules/mono/glue/base_object_glue.cpp
deleted file mode 100644
index 7b9dbc87cf..0000000000
--- a/modules/mono/glue/base_object_glue.cpp
+++ /dev/null
@@ -1,257 +0,0 @@
-/*************************************************************************/
-/* base_object_glue.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 MONO_GLUE_ENABLED
-
-#include "core/object/class_db.h"
-#include "core/object/ref_counted.h"
-#include "core/string/string_name.h"
-
-#include "../csharp_script.h"
-#include "../mono_gd/gd_mono_cache.h"
-#include "../mono_gd/gd_mono_class.h"
-#include "../mono_gd/gd_mono_internals.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "../mono_gd/gd_mono_utils.h"
-#include "../signal_awaiter_utils.h"
-#include "arguments_vector.h"
-
-Object *godot_icall_Object_Ctor(MonoObject *p_obj) {
- Object *instance = memnew(Object);
- GDMonoInternals::tie_managed_to_unmanaged(p_obj, instance);
- return instance;
-}
-
-void godot_icall_Object_Disposed(MonoObject *p_obj, Object *p_ptr) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_ptr == nullptr);
-#endif
-
- if (p_ptr->get_script_instance()) {
- CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(p_ptr->get_script_instance());
- if (cs_instance) {
- if (!cs_instance->is_destructing_script_instance()) {
- cs_instance->mono_object_disposed(p_obj);
- p_ptr->set_script_instance(nullptr);
- }
- return;
- }
- }
-
- void *data = CSharpLanguage::get_existing_instance_binding(p_ptr);
-
- if (data) {
- CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
- if (script_binding.inited) {
- MonoGCHandleData &gchandle = script_binding.gchandle;
- if (!gchandle.is_released()) {
- CSharpLanguage::release_script_gchandle(p_obj, gchandle);
- }
- }
- }
-}
-
-void godot_icall_RefCounted_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolean p_is_finalizer) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_ptr == nullptr);
- // This is only called with RefCounted derived classes
- CRASH_COND(!Object::cast_to<RefCounted>(p_ptr));
-#endif
-
- RefCounted *rc = static_cast<RefCounted *>(p_ptr);
-
- if (rc->get_script_instance()) {
- CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(rc->get_script_instance());
- if (cs_instance) {
- if (!cs_instance->is_destructing_script_instance()) {
- bool delete_owner;
- bool remove_script_instance;
-
- cs_instance->mono_object_disposed_baseref(p_obj, p_is_finalizer, delete_owner, remove_script_instance);
-
- if (delete_owner) {
- memdelete(rc);
- } else if (remove_script_instance) {
- rc->set_script_instance(nullptr);
- }
- }
- return;
- }
- }
-
- // Unsafe refcount decrement. The managed instance also counts as a reference.
- // See: CSharpLanguage::alloc_instance_binding_data(Object *p_object)
- CSharpLanguage::get_singleton()->pre_unsafe_unreference(rc);
- if (rc->unreference()) {
- memdelete(rc);
- } else {
- void *data = CSharpLanguage::get_existing_instance_binding(rc);
-
- if (data) {
- CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
- if (script_binding.inited) {
- MonoGCHandleData &gchandle = script_binding.gchandle;
- if (!gchandle.is_released()) {
- CSharpLanguage::release_script_gchandle(p_obj, gchandle);
- }
- }
- }
- }
-}
-
-void godot_icall_Object_ConnectEventSignals(Object *p_ptr) {
- CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_ptr->get_script_instance());
- if (csharp_instance) {
- csharp_instance->connect_event_signals();
- }
-}
-
-MethodBind *godot_icall_Object_ClassDB_get_method(StringName *p_type, MonoString *p_method) {
- StringName type = p_type ? *p_type : StringName();
- StringName method(GDMonoMarshal::mono_string_to_godot(p_method));
- return ClassDB::get_method(type, method);
-}
-
-MonoObject *godot_icall_Object_weakref(Object *p_ptr) {
- if (!p_ptr) {
- return nullptr;
- }
-
- Ref<WeakRef> wref;
- RefCounted *rc = Object::cast_to<RefCounted>(p_ptr);
-
- if (rc) {
- Ref<RefCounted> r = rc;
- if (!r.is_valid()) {
- return nullptr;
- }
-
- wref.instantiate();
- wref->set_ref(r);
- } else {
- wref.instantiate();
- wref->set_obj(p_ptr);
- }
-
- return GDMonoUtils::unmanaged_get_managed(wref.ptr());
-}
-
-int32_t godot_icall_SignalAwaiter_connect(Object *p_source, StringName *p_signal, Object *p_target, MonoObject *p_awaiter) {
- StringName signal = p_signal ? *p_signal : StringName();
- return (int32_t)gd_mono_connect_signal_awaiter(p_source, signal, p_target, p_awaiter);
-}
-
-MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr) {
- List<PropertyInfo> property_list;
- p_ptr->get_property_list(&property_list);
-
- MonoArray *result = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), property_list.size());
-
- int i = 0;
- for (const PropertyInfo &E : property_list) {
- MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E.name);
- mono_array_setref(result, i, boxed);
- i++;
- }
-
- return result;
-}
-
-MonoBoolean godot_icall_DynamicGodotObject_InvokeMember(Object *p_ptr, MonoString *p_name, MonoArray *p_args, MonoObject **r_result) {
- String name = GDMonoMarshal::mono_string_to_godot(p_name);
-
- int argc = mono_array_length(p_args);
-
- ArgumentsVector<Variant> arg_store(argc);
- ArgumentsVector<const Variant *> args(argc);
-
- for (int i = 0; i < argc; i++) {
- MonoObject *elem = mono_array_get(p_args, MonoObject *, i);
- arg_store.set(i, GDMonoMarshal::mono_object_to_variant(elem));
- args.set(i, &arg_store.get(i));
- }
-
- Callable::CallError error;
- Variant result = p_ptr->callp(StringName(name), args.ptr(), argc, error);
-
- *r_result = GDMonoMarshal::variant_to_mono_object(result);
-
- return error.error == Callable::CallError::CALL_OK;
-}
-
-MonoBoolean godot_icall_DynamicGodotObject_GetMember(Object *p_ptr, MonoString *p_name, MonoObject **r_result) {
- String name = GDMonoMarshal::mono_string_to_godot(p_name);
-
- bool valid;
- Variant value = p_ptr->get(StringName(name), &valid);
-
- if (valid) {
- *r_result = GDMonoMarshal::variant_to_mono_object(value);
- }
-
- return valid;
-}
-
-MonoBoolean godot_icall_DynamicGodotObject_SetMember(Object *p_ptr, MonoString *p_name, MonoObject *p_value) {
- String name = GDMonoMarshal::mono_string_to_godot(p_name);
- Variant value = GDMonoMarshal::mono_object_to_variant(p_value);
-
- bool valid;
- p_ptr->set(StringName(name), value, &valid);
-
- return valid;
-}
-
-MonoString *godot_icall_Object_ToString(Object *p_ptr) {
-#ifdef DEBUG_ENABLED
- // Cannot happen in C#; would get an ObjectDisposedException instead.
- CRASH_COND(p_ptr == nullptr);
-#endif
- // Can't call 'Object::to_string()' here, as that can end up calling 'ToString' again resulting in an endless circular loop.
- String result = "[" + p_ptr->get_class() + ":" + itos(p_ptr->get_instance_id()) + "]";
- return GDMonoMarshal::mono_string_from_godot(result);
-}
-
-void godot_register_object_icalls() {
- GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_Ctor", godot_icall_Object_Ctor);
- GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_Disposed", godot_icall_Object_Disposed);
- GDMonoUtils::add_internal_call("Godot.Object::godot_icall_RefCounted_Disposed", godot_icall_RefCounted_Disposed);
- GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ConnectEventSignals", godot_icall_Object_ConnectEventSignals);
- GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ClassDB_get_method", godot_icall_Object_ClassDB_get_method);
- GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ToString", godot_icall_Object_ToString);
- GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_weakref", godot_icall_Object_weakref);
- GDMonoUtils::add_internal_call("Godot.SignalAwaiter::godot_icall_SignalAwaiter_connect", godot_icall_SignalAwaiter_connect);
- GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMemberList", godot_icall_DynamicGodotObject_SetMemberList);
- GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_InvokeMember", godot_icall_DynamicGodotObject_InvokeMember);
- GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_GetMember", godot_icall_DynamicGodotObject_GetMember);
- GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMember", godot_icall_DynamicGodotObject_SetMember);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/callable_glue.cpp b/modules/mono/glue/callable_glue.cpp
deleted file mode 100644
index 521dc3dff7..0000000000
--- a/modules/mono/glue/callable_glue.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*************************************************************************/
-/* callable_glue.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 MONO_GLUE_ENABLED
-
-#include "../mono_gd/gd_mono_marshal.h"
-#include "arguments_vector.h"
-
-MonoObject *godot_icall_Callable_Call(GDMonoMarshal::M_Callable *p_callable, MonoArray *p_args) {
- Callable callable = GDMonoMarshal::managed_to_callable(*p_callable);
-
- int argc = mono_array_length(p_args);
-
- ArgumentsVector<Variant> arg_store(argc);
- ArgumentsVector<const Variant *> args(argc);
-
- for (int i = 0; i < argc; i++) {
- MonoObject *elem = mono_array_get(p_args, MonoObject *, i);
- arg_store.set(i, GDMonoMarshal::mono_object_to_variant(elem));
- args.set(i, &arg_store.get(i));
- }
-
- Variant result;
- Callable::CallError error;
- callable.callp(args.ptr(), argc, result, error);
-
- return GDMonoMarshal::variant_to_mono_object(result);
-}
-
-void godot_icall_Callable_CallDeferred(GDMonoMarshal::M_Callable *p_callable, MonoArray *p_args) {
- Callable callable = GDMonoMarshal::managed_to_callable(*p_callable);
-
- int argc = mono_array_length(p_args);
-
- ArgumentsVector<Variant> arg_store(argc);
- ArgumentsVector<const Variant *> args(argc);
-
- for (int i = 0; i < argc; i++) {
- MonoObject *elem = mono_array_get(p_args, MonoObject *, i);
- arg_store.set(i, GDMonoMarshal::mono_object_to_variant(elem));
- args.set(i, &arg_store.get(i));
- }
-
- callable.call_deferredp(args.ptr(), argc);
-}
-
-void godot_register_callable_icalls() {
- GDMonoUtils::add_internal_call("Godot.Callable::godot_icall_Callable_Call", godot_icall_Callable_Call);
- GDMonoUtils::add_internal_call("Godot.Callable::godot_icall_Callable_CallDeferred", godot_icall_Callable_CallDeferred);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/collections_glue.cpp b/modules/mono/glue/collections_glue.cpp
deleted file mode 100644
index 8a9f30459c..0000000000
--- a/modules/mono/glue/collections_glue.cpp
+++ /dev/null
@@ -1,374 +0,0 @@
-/*************************************************************************/
-/* collections_glue.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 MONO_GLUE_ENABLED
-
-#include <mono/metadata/exception.h>
-
-#include "core/variant/array.h"
-
-#include "../mono_gd/gd_mono_cache.h"
-#include "../mono_gd/gd_mono_class.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "../mono_gd/gd_mono_utils.h"
-
-Array *godot_icall_Array_Ctor() {
- return memnew(Array);
-}
-
-void godot_icall_Array_Dtor(Array *ptr) {
- memdelete(ptr);
-}
-
-MonoObject *godot_icall_Array_At(Array *ptr, int32_t index) {
- if (index < 0 || index >= ptr->size()) {
- GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
- return nullptr;
- }
- return GDMonoMarshal::variant_to_mono_object(ptr->operator[](index));
-}
-
-MonoObject *godot_icall_Array_At_Generic(Array *ptr, int32_t index, uint32_t type_encoding, GDMonoClass *type_class) {
- if (index < 0 || index >= ptr->size()) {
- GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
- return nullptr;
- }
- return GDMonoMarshal::variant_to_mono_object(ptr->operator[](index), ManagedType(type_encoding, type_class));
-}
-
-void godot_icall_Array_SetAt(Array *ptr, int32_t index, MonoObject *value) {
- if (index < 0 || index >= ptr->size()) {
- GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
- return;
- }
- ptr->operator[](index) = GDMonoMarshal::mono_object_to_variant(value);
-}
-
-int32_t godot_icall_Array_Count(Array *ptr) {
- return ptr->size();
-}
-
-int32_t godot_icall_Array_Add(Array *ptr, MonoObject *item) {
- ptr->append(GDMonoMarshal::mono_object_to_variant(item));
- return ptr->size();
-}
-
-void godot_icall_Array_Clear(Array *ptr) {
- ptr->clear();
-}
-
-MonoBoolean godot_icall_Array_Contains(Array *ptr, MonoObject *item) {
- return ptr->find(GDMonoMarshal::mono_object_to_variant(item)) != -1;
-}
-
-void godot_icall_Array_CopyTo(Array *ptr, MonoArray *array, int32_t array_index) {
- unsigned int count = ptr->size();
-
- if (mono_array_length(array) < (array_index + count)) {
- MonoException *exc = mono_get_exception_argument("", "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
- GDMonoUtils::set_pending_exception(exc);
- return;
- }
-
- for (unsigned int i = 0; i < count; i++) {
- MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(ptr->operator[](i));
- mono_array_setref(array, array_index, boxed);
- array_index++;
- }
-}
-
-Array *godot_icall_Array_Ctor_MonoArray(MonoArray *mono_array) {
- Array *godot_array = memnew(Array);
- unsigned int count = mono_array_length(mono_array);
- godot_array->resize(count);
- for (unsigned int i = 0; i < count; i++) {
- MonoObject *item = mono_array_get(mono_array, MonoObject *, i);
- godot_icall_Array_SetAt(godot_array, i, item);
- }
- return godot_array;
-}
-
-Array *godot_icall_Array_Duplicate(Array *ptr, MonoBoolean deep) {
- return memnew(Array(ptr->duplicate(deep)));
-}
-
-Array *godot_icall_Array_Concatenate(Array *left, Array *right) {
- int count = left->size() + right->size();
- Array *new_array = memnew(Array(left->duplicate(false)));
- new_array->resize(count);
- for (unsigned int i = 0; i < (unsigned int)right->size(); i++) {
- new_array->operator[](i + left->size()) = right->operator[](i);
- }
- return new_array;
-}
-
-int32_t godot_icall_Array_IndexOf(Array *ptr, MonoObject *item) {
- return ptr->find(GDMonoMarshal::mono_object_to_variant(item));
-}
-
-void godot_icall_Array_Insert(Array *ptr, int32_t index, MonoObject *item) {
- if (index < 0 || index > ptr->size()) {
- GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
- return;
- }
- ptr->insert(index, GDMonoMarshal::mono_object_to_variant(item));
-}
-
-MonoBoolean godot_icall_Array_Remove(Array *ptr, MonoObject *item) {
- int idx = ptr->find(GDMonoMarshal::mono_object_to_variant(item));
- if (idx >= 0) {
- ptr->remove_at(idx);
- return true;
- }
- return false;
-}
-
-void godot_icall_Array_RemoveAt(Array *ptr, int32_t index) {
- if (index < 0 || index >= ptr->size()) {
- GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
- return;
- }
- ptr->remove_at(index);
-}
-
-int32_t godot_icall_Array_Resize(Array *ptr, int32_t new_size) {
- return (int32_t)ptr->resize(new_size);
-}
-
-void godot_icall_Array_Shuffle(Array *ptr) {
- ptr->shuffle();
-}
-
-void godot_icall_Array_Generic_GetElementTypeInfo(MonoReflectionType *refltype, uint32_t *type_encoding, GDMonoClass **type_class) {
- MonoType *elem_type = mono_reflection_type_get_type(refltype);
-
- *type_encoding = mono_type_get_type(elem_type);
- MonoClass *type_class_raw = mono_class_from_mono_type(elem_type);
- *type_class = GDMono::get_singleton()->get_class(type_class_raw);
-}
-
-MonoString *godot_icall_Array_ToString(Array *ptr) {
- return GDMonoMarshal::mono_string_from_godot(Variant(*ptr).operator String());
-}
-
-Dictionary *godot_icall_Dictionary_Ctor() {
- return memnew(Dictionary);
-}
-
-void godot_icall_Dictionary_Dtor(Dictionary *ptr) {
- memdelete(ptr);
-}
-
-MonoObject *godot_icall_Dictionary_GetValue(Dictionary *ptr, MonoObject *key) {
- Variant *ret = ptr->getptr(GDMonoMarshal::mono_object_to_variant(key));
- if (ret == nullptr) {
- MonoObject *exc = mono_object_new(mono_domain_get(), CACHED_CLASS(KeyNotFoundException)->get_mono_ptr());
-#ifdef DEBUG_ENABLED
- CRASH_COND(!exc);
-#endif
- GDMonoUtils::runtime_object_init(exc, CACHED_CLASS(KeyNotFoundException));
- GDMonoUtils::set_pending_exception((MonoException *)exc);
- return nullptr;
- }
- return GDMonoMarshal::variant_to_mono_object(ret);
-}
-
-MonoObject *godot_icall_Dictionary_GetValue_Generic(Dictionary *ptr, MonoObject *key, uint32_t type_encoding, GDMonoClass *type_class) {
- Variant *ret = ptr->getptr(GDMonoMarshal::mono_object_to_variant(key));
- if (ret == nullptr) {
- MonoObject *exc = mono_object_new(mono_domain_get(), CACHED_CLASS(KeyNotFoundException)->get_mono_ptr());
-#ifdef DEBUG_ENABLED
- CRASH_COND(!exc);
-#endif
- GDMonoUtils::runtime_object_init(exc, CACHED_CLASS(KeyNotFoundException));
- GDMonoUtils::set_pending_exception((MonoException *)exc);
- return nullptr;
- }
- return GDMonoMarshal::variant_to_mono_object(ret, ManagedType(type_encoding, type_class));
-}
-
-void godot_icall_Dictionary_SetValue(Dictionary *ptr, MonoObject *key, MonoObject *value) {
- ptr->operator[](GDMonoMarshal::mono_object_to_variant(key)) = GDMonoMarshal::mono_object_to_variant(value);
-}
-
-Array *godot_icall_Dictionary_Keys(Dictionary *ptr) {
- return memnew(Array(ptr->keys()));
-}
-
-Array *godot_icall_Dictionary_Values(Dictionary *ptr) {
- return memnew(Array(ptr->values()));
-}
-
-int32_t godot_icall_Dictionary_Count(Dictionary *ptr) {
- return ptr->size();
-}
-
-int32_t godot_icall_Dictionary_KeyValuePairs(Dictionary *ptr, Array **keys, Array **values) {
- *keys = godot_icall_Dictionary_Keys(ptr);
- *values = godot_icall_Dictionary_Values(ptr);
- return godot_icall_Dictionary_Count(ptr);
-}
-
-void godot_icall_Dictionary_KeyValuePairAt(Dictionary *ptr, int index, MonoObject **key, MonoObject **value) {
- *key = GDMonoMarshal::variant_to_mono_object(ptr->get_key_at_index(index));
- *value = GDMonoMarshal::variant_to_mono_object(ptr->get_value_at_index(index));
-}
-
-void godot_icall_Dictionary_KeyValuePairAt_Generic(Dictionary *ptr, int index, MonoObject **key, MonoObject **value, uint32_t value_type_encoding, GDMonoClass *value_type_class) {
- ManagedType type(value_type_encoding, value_type_class);
- *key = GDMonoMarshal::variant_to_mono_object(ptr->get_key_at_index(index));
- *value = GDMonoMarshal::variant_to_mono_object(ptr->get_value_at_index(index), type);
-}
-
-void godot_icall_Dictionary_Add(Dictionary *ptr, MonoObject *key, MonoObject *value) {
- Variant varKey = GDMonoMarshal::mono_object_to_variant(key);
- Variant *ret = ptr->getptr(varKey);
- if (ret != nullptr) {
- GDMonoUtils::set_pending_exception(mono_get_exception_argument("key", "An element with the same key already exists"));
- return;
- }
- ptr->operator[](varKey) = GDMonoMarshal::mono_object_to_variant(value);
-}
-
-void godot_icall_Dictionary_Clear(Dictionary *ptr) {
- ptr->clear();
-}
-
-MonoBoolean godot_icall_Dictionary_Contains(Dictionary *ptr, MonoObject *key, MonoObject *value) {
- // no dupes
- Variant *ret = ptr->getptr(GDMonoMarshal::mono_object_to_variant(key));
- return ret != nullptr && *ret == GDMonoMarshal::mono_object_to_variant(value);
-}
-
-MonoBoolean godot_icall_Dictionary_ContainsKey(Dictionary *ptr, MonoObject *key) {
- return ptr->has(GDMonoMarshal::mono_object_to_variant(key));
-}
-
-Dictionary *godot_icall_Dictionary_Duplicate(Dictionary *ptr, MonoBoolean deep) {
- return memnew(Dictionary(ptr->duplicate(deep)));
-}
-
-MonoBoolean godot_icall_Dictionary_RemoveKey(Dictionary *ptr, MonoObject *key) {
- return ptr->erase(GDMonoMarshal::mono_object_to_variant(key));
-}
-
-MonoBoolean godot_icall_Dictionary_Remove(Dictionary *ptr, MonoObject *key, MonoObject *value) {
- Variant varKey = GDMonoMarshal::mono_object_to_variant(key);
-
- // no dupes
- Variant *ret = ptr->getptr(varKey);
- if (ret != nullptr && *ret == GDMonoMarshal::mono_object_to_variant(value)) {
- ptr->erase(varKey);
- return true;
- }
-
- return false;
-}
-
-MonoBoolean godot_icall_Dictionary_TryGetValue(Dictionary *ptr, MonoObject *key, MonoObject **value) {
- Variant *ret = ptr->getptr(GDMonoMarshal::mono_object_to_variant(key));
- if (ret == nullptr) {
- *value = nullptr;
- return false;
- }
- *value = GDMonoMarshal::variant_to_mono_object(ret);
- return true;
-}
-
-MonoBoolean godot_icall_Dictionary_TryGetValue_Generic(Dictionary *ptr, MonoObject *key, MonoObject **value, uint32_t type_encoding, GDMonoClass *type_class) {
- Variant *ret = ptr->getptr(GDMonoMarshal::mono_object_to_variant(key));
- if (ret == nullptr) {
- *value = nullptr;
- return false;
- }
- *value = GDMonoMarshal::variant_to_mono_object(ret, ManagedType(type_encoding, type_class));
- return true;
-}
-
-void godot_icall_Dictionary_Generic_GetValueTypeInfo(MonoReflectionType *refltype, uint32_t *type_encoding, GDMonoClass **type_class) {
- MonoType *value_type = mono_reflection_type_get_type(refltype);
-
- *type_encoding = mono_type_get_type(value_type);
- MonoClass *type_class_raw = mono_class_from_mono_type(value_type);
- *type_class = GDMono::get_singleton()->get_class(type_class_raw);
-}
-
-MonoString *godot_icall_Dictionary_ToString(Dictionary *ptr) {
- return GDMonoMarshal::mono_string_from_godot(Variant(*ptr).operator String());
-}
-
-void godot_register_collections_icalls() {
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Ctor", godot_icall_Array_Ctor);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Ctor_MonoArray", godot_icall_Array_Ctor_MonoArray);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Dtor", godot_icall_Array_Dtor);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_At", godot_icall_Array_At);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_At_Generic", godot_icall_Array_At_Generic);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_SetAt", godot_icall_Array_SetAt);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Count", godot_icall_Array_Count);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Add", godot_icall_Array_Add);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Clear", godot_icall_Array_Clear);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Concatenate", godot_icall_Array_Concatenate);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Contains", godot_icall_Array_Contains);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_CopyTo", godot_icall_Array_CopyTo);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Duplicate", godot_icall_Array_Duplicate);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_IndexOf", godot_icall_Array_IndexOf);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Insert", godot_icall_Array_Insert);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Remove", godot_icall_Array_Remove);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_RemoveAt", godot_icall_Array_RemoveAt);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Resize", godot_icall_Array_Resize);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Shuffle", godot_icall_Array_Shuffle);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Generic_GetElementTypeInfo", godot_icall_Array_Generic_GetElementTypeInfo);
- GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_ToString", godot_icall_Array_ToString);
-
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Ctor", godot_icall_Dictionary_Ctor);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Dtor", godot_icall_Dictionary_Dtor);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_GetValue", godot_icall_Dictionary_GetValue);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_GetValue_Generic", godot_icall_Dictionary_GetValue_Generic);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_SetValue", godot_icall_Dictionary_SetValue);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Keys", godot_icall_Dictionary_Keys);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Values", godot_icall_Dictionary_Values);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Count", godot_icall_Dictionary_Count);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_KeyValuePairs", godot_icall_Dictionary_KeyValuePairs);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_KeyValuePairAt", godot_icall_Dictionary_KeyValuePairAt);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_KeyValuePairAt_Generic", godot_icall_Dictionary_KeyValuePairAt_Generic);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Add", godot_icall_Dictionary_Add);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Clear", godot_icall_Dictionary_Clear);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Contains", godot_icall_Dictionary_Contains);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ContainsKey", godot_icall_Dictionary_ContainsKey);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Duplicate", godot_icall_Dictionary_Duplicate);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_RemoveKey", godot_icall_Dictionary_RemoveKey);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Remove", godot_icall_Dictionary_Remove);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue", godot_icall_Dictionary_TryGetValue);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue_Generic", godot_icall_Dictionary_TryGetValue_Generic);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Generic_GetValueTypeInfo", godot_icall_Dictionary_Generic_GetValueTypeInfo);
- GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ToString", godot_icall_Dictionary_ToString);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/gd_glue.cpp b/modules/mono/glue/gd_glue.cpp
deleted file mode 100644
index 8b1c2b729e..0000000000
--- a/modules/mono/glue/gd_glue.cpp
+++ /dev/null
@@ -1,348 +0,0 @@
-/*************************************************************************/
-/* gd_glue.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 MONO_GLUE_ENABLED
-
-#include "core/io/marshalls.h"
-#include "core/os/os.h"
-#include "core/string/ustring.h"
-#include "core/variant/array.h"
-#include "core/variant/variant.h"
-#include "core/variant/variant_parser.h"
-
-#include "../mono_gd/gd_mono_cache.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "../mono_gd/gd_mono_utils.h"
-
-MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects) {
- Variant ret;
- PackedByteArray varr = GDMonoMarshal::mono_array_to_PackedByteArray(p_bytes);
- Error err = decode_variant(ret, varr.ptr(), varr.size(), nullptr, p_allow_objects);
- if (err != OK) {
- ret = RTR("Not enough bytes for decoding bytes, or invalid format.");
- }
- return GDMonoMarshal::variant_to_mono_object(ret);
-}
-
-MonoObject *godot_icall_GD_convert(MonoObject *p_what, int32_t p_type) {
- Variant what = GDMonoMarshal::mono_object_to_variant(p_what);
- const Variant *args[1] = { &what };
- Callable::CallError ce;
- Variant ret;
- Variant::construct(Variant::Type(p_type), ret, args, 1, ce);
- ERR_FAIL_COND_V(ce.error != Callable::CallError::CALL_OK, nullptr);
- return GDMonoMarshal::variant_to_mono_object(ret);
-}
-
-int godot_icall_GD_hash(MonoObject *p_var) {
- return GDMonoMarshal::mono_object_to_variant(p_var).hash();
-}
-
-MonoObject *godot_icall_GD_instance_from_id(uint64_t p_instance_id) {
- return GDMonoUtils::unmanaged_get_managed(ObjectDB::get_instance(ObjectID(p_instance_id)));
-}
-
-void godot_icall_GD_print(MonoArray *p_what) {
- String str;
- int length = mono_array_length(p_what);
-
- for (int i = 0; i < length; i++) {
- MonoObject *elem = mono_array_get(p_what, MonoObject *, i);
-
- MonoException *exc = nullptr;
- String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- return;
- }
-
- str += elem_str;
- }
-
- print_line(str);
-}
-
-void godot_icall_GD_print_rich(MonoArray *p_what) {
- String str;
- int length = mono_array_length(p_what);
-
- for (int i = 0; i < length; i++) {
- MonoObject *elem = mono_array_get(p_what, MonoObject *, i);
-
- MonoException *exc = nullptr;
- String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- return;
- }
-
- str += elem_str;
- }
-
- print_line_rich(str);
-}
-
-void godot_icall_GD_printerr(MonoArray *p_what) {
- String str;
- int length = mono_array_length(p_what);
-
- for (int i = 0; i < length; i++) {
- MonoObject *elem = mono_array_get(p_what, MonoObject *, i);
-
- MonoException *exc = nullptr;
- String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- return;
- }
-
- str += elem_str;
- }
-
- print_error(str);
-}
-
-void godot_icall_GD_printraw(MonoArray *p_what) {
- String str;
- int length = mono_array_length(p_what);
-
- for (int i = 0; i < length; i++) {
- MonoObject *elem = mono_array_get(p_what, MonoObject *, i);
-
- MonoException *exc = nullptr;
- String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- return;
- }
-
- str += elem_str;
- }
-
- OS::get_singleton()->print("%s", str.utf8().get_data());
-}
-
-void godot_icall_GD_prints(MonoArray *p_what) {
- String str;
- int length = mono_array_length(p_what);
-
- for (int i = 0; i < length; i++) {
- MonoObject *elem = mono_array_get(p_what, MonoObject *, i);
-
- MonoException *exc = nullptr;
- String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- return;
- }
-
- if (i) {
- str += " ";
- }
-
- str += elem_str;
- }
-
- print_line(str);
-}
-
-void godot_icall_GD_printt(MonoArray *p_what) {
- String str;
- int length = mono_array_length(p_what);
-
- for (int i = 0; i < length; i++) {
- MonoObject *elem = mono_array_get(p_what, MonoObject *, i);
-
- MonoException *exc = nullptr;
- String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- return;
- }
-
- if (i) {
- str += "\t";
- }
-
- str += elem_str;
- }
-
- print_line(str);
-}
-
-void godot_icall_GD_randomize() {
- Math::randomize();
-}
-
-uint32_t godot_icall_GD_randi() {
- return Math::rand();
-}
-
-float godot_icall_GD_randf() {
- return Math::randf();
-}
-
-int32_t godot_icall_GD_randi_range(int32_t from, int32_t to) {
- return Math::random(from, to);
-}
-
-double godot_icall_GD_randf_range(double from, double to) {
- return Math::random(from, to);
-}
-
-double godot_icall_GD_randfn(double mean, double deviation) {
- return Math::randfn(mean, deviation);
-}
-
-uint32_t godot_icall_GD_rand_seed(uint64_t seed, uint64_t *newSeed) {
- uint32_t ret = Math::rand_from_seed(&seed);
- *newSeed = seed;
- return ret;
-}
-
-void godot_icall_GD_seed(uint64_t p_seed) {
- Math::seed(p_seed);
-}
-
-MonoString *godot_icall_GD_str(MonoArray *p_what) {
- String str;
- Array what = GDMonoMarshal::mono_array_to_Array(p_what);
-
- for (int i = 0; i < what.size(); i++) {
- String os = what[i].operator String();
-
- if (i == 0) {
- str = os;
- } else {
- str += os;
- }
- }
-
- return GDMonoMarshal::mono_string_from_godot(str);
-}
-
-MonoObject *godot_icall_GD_str2var(MonoString *p_str) {
- Variant ret;
-
- VariantParser::StreamString ss;
- ss.s = GDMonoMarshal::mono_string_to_godot(p_str);
-
- String errs;
- int line;
- Error err = VariantParser::parse(&ss, ret, errs, line);
- if (err != OK) {
- String err_str = "Parse error at line " + itos(line) + ": " + errs + ".";
- ERR_PRINT(err_str);
- ret = err_str;
- }
-
- return GDMonoMarshal::variant_to_mono_object(ret);
-}
-
-MonoBoolean godot_icall_GD_type_exists(StringName *p_type) {
- StringName type = p_type ? *p_type : StringName();
- return ClassDB::class_exists(type);
-}
-
-void godot_icall_GD_pusherror(MonoString *p_str) {
- ERR_PRINT(GDMonoMarshal::mono_string_to_godot(p_str));
-}
-
-void godot_icall_GD_pushwarning(MonoString *p_str) {
- WARN_PRINT(GDMonoMarshal::mono_string_to_godot(p_str));
-}
-
-MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_objects) {
- Variant var = GDMonoMarshal::mono_object_to_variant(p_var);
-
- PackedByteArray barr;
- int len;
- Error err = encode_variant(var, nullptr, len, p_full_objects);
- ERR_FAIL_COND_V_MSG(err != OK, nullptr, "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).");
-
- barr.resize(len);
- encode_variant(var, barr.ptrw(), len, p_full_objects);
-
- return GDMonoMarshal::PackedByteArray_to_mono_array(barr);
-}
-
-MonoString *godot_icall_GD_var2str(MonoObject *p_var) {
- String vars;
- VariantWriter::write_to_string(GDMonoMarshal::mono_object_to_variant(p_var), vars);
- return GDMonoMarshal::mono_string_from_godot(vars);
-}
-
-uint32_t godot_icall_TypeToVariantType(MonoReflectionType *p_refl_type) {
- return (uint32_t)GDMonoMarshal::managed_to_variant_type(ManagedType::from_reftype(p_refl_type));
-}
-
-MonoObject *godot_icall_DefaultGodotTaskScheduler() {
- return GDMonoCache::cached_data.task_scheduler_handle->get_target();
-}
-
-void godot_register_gd_icalls() {
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_bytes2var", godot_icall_GD_bytes2var);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_convert", godot_icall_GD_convert);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_hash", godot_icall_GD_hash);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", godot_icall_GD_instance_from_id);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_pusherror", godot_icall_GD_pusherror);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_pushwarning", godot_icall_GD_pushwarning);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_print", godot_icall_GD_print);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_print_rich", godot_icall_GD_print_rich);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_printerr", godot_icall_GD_printerr);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_printraw", godot_icall_GD_printraw);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_prints", godot_icall_GD_prints);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_printt", godot_icall_GD_printt);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randomize", godot_icall_GD_randomize);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randi", godot_icall_GD_randi);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randf", godot_icall_GD_randf);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randi_range", godot_icall_GD_randi_range);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randf_range", godot_icall_GD_randf_range);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randfn", godot_icall_GD_randfn);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_rand_seed", godot_icall_GD_rand_seed);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_seed", godot_icall_GD_seed);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_str", godot_icall_GD_str);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_str2var", godot_icall_GD_str2var);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_type_exists", godot_icall_GD_type_exists);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_var2bytes", godot_icall_GD_var2bytes);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_var2str", godot_icall_GD_var2str);
- GDMonoUtils::add_internal_call("Godot.GD::godot_icall_TypeToVariantType", godot_icall_TypeToVariantType);
-
- // Dispatcher
- GDMonoUtils::add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", godot_icall_DefaultGodotTaskScheduler);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/glue_header.h b/modules/mono/glue/glue_header.h
deleted file mode 100644
index f9ad1a9893..0000000000
--- a/modules/mono/glue/glue_header.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*************************************************************************/
-/* glue_header.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 GLUE_HEADER_H
-#define GLUE_HEADER_H
-
-#ifdef MONO_GLUE_ENABLED
-
-#include "../mono_gd/gd_mono_marshal.h"
-
-void godot_register_collections_icalls();
-void godot_register_gd_icalls();
-void godot_register_string_name_icalls();
-void godot_register_nodepath_icalls();
-void godot_register_callable_icalls();
-void godot_register_object_icalls();
-void godot_register_rid_icalls();
-void godot_register_string_icalls();
-void godot_register_scene_tree_icalls();
-
-/**
- * Registers internal calls that were not generated. This function is called
- * from the generated GodotSharpBindings::register_generated_icalls() function.
- */
-void godot_register_glue_header_icalls() {
- godot_register_collections_icalls();
- godot_register_gd_icalls();
- godot_register_string_name_icalls();
- godot_register_nodepath_icalls();
- godot_register_callable_icalls();
- godot_register_object_icalls();
- godot_register_rid_icalls();
- godot_register_string_icalls();
- godot_register_scene_tree_icalls();
-}
-
-// Used by the generated glue
-
-#include "core/config/engine.h"
-#include "core/object/class_db.h"
-#include "core/object/method_bind.h"
-#include "core/object/ref_counted.h"
-#include "core/string/node_path.h"
-#include "core/string/ustring.h"
-#include "core/typedefs.h"
-#include "core/variant/array.h"
-#include "core/variant/dictionary.h"
-
-#include "../mono_gd/gd_mono_class.h"
-#include "../mono_gd/gd_mono_internals.h"
-#include "../mono_gd/gd_mono_utils.h"
-
-#define GODOTSHARP_INSTANCE_OBJECT(m_instance, m_type) \
- static ClassDB::ClassInfo *ci = nullptr; \
- if (!ci) { \
- ci = ClassDB::classes.getptr(m_type); \
- } \
- Object *m_instance = ci->creation_func();
-
-#include "arguments_vector.h"
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // GLUE_HEADER_H
diff --git a/modules/mono/glue/nodepath_glue.cpp b/modules/mono/glue/nodepath_glue.cpp
deleted file mode 100644
index 16e1509eb0..0000000000
--- a/modules/mono/glue/nodepath_glue.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*************************************************************************/
-/* nodepath_glue.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 MONO_GLUE_ENABLED
-
-#include "core/string/node_path.h"
-#include "core/string/ustring.h"
-
-#include "../mono_gd/gd_mono_marshal.h"
-
-NodePath *godot_icall_NodePath_Ctor(MonoString *p_path) {
- return memnew(NodePath(GDMonoMarshal::mono_string_to_godot(p_path)));
-}
-
-void godot_icall_NodePath_Dtor(NodePath *p_ptr) {
- ERR_FAIL_NULL(p_ptr);
- memdelete(p_ptr);
-}
-
-MonoString *godot_icall_NodePath_operator_String(NodePath *p_np) {
- return GDMonoMarshal::mono_string_from_godot(p_np->operator String());
-}
-
-MonoBoolean godot_icall_NodePath_is_absolute(NodePath *p_ptr) {
- return (MonoBoolean)p_ptr->is_absolute();
-}
-
-int32_t godot_icall_NodePath_get_name_count(NodePath *p_ptr) {
- return p_ptr->get_name_count();
-}
-
-MonoString *godot_icall_NodePath_get_name(NodePath *p_ptr, uint32_t p_idx) {
- return GDMonoMarshal::mono_string_from_godot(p_ptr->get_name(p_idx));
-}
-
-int32_t godot_icall_NodePath_get_subname_count(NodePath *p_ptr) {
- return p_ptr->get_subname_count();
-}
-
-MonoString *godot_icall_NodePath_get_subname(NodePath *p_ptr, uint32_t p_idx) {
- return GDMonoMarshal::mono_string_from_godot(p_ptr->get_subname(p_idx));
-}
-
-MonoString *godot_icall_NodePath_get_concatenated_names(NodePath *p_ptr) {
- return GDMonoMarshal::mono_string_from_godot(p_ptr->get_concatenated_names());
-}
-
-MonoString *godot_icall_NodePath_get_concatenated_subnames(NodePath *p_ptr) {
- return GDMonoMarshal::mono_string_from_godot(p_ptr->get_concatenated_subnames());
-}
-
-NodePath *godot_icall_NodePath_get_as_property_path(NodePath *p_ptr) {
- return memnew(NodePath(p_ptr->get_as_property_path()));
-}
-
-MonoBoolean godot_icall_NodePath_is_empty(NodePath *p_ptr) {
- return (MonoBoolean)p_ptr->is_empty();
-}
-
-void godot_register_nodepath_icalls() {
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_Ctor", godot_icall_NodePath_Ctor);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_Dtor", godot_icall_NodePath_Dtor);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_operator_String", godot_icall_NodePath_operator_String);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_as_property_path", godot_icall_NodePath_get_as_property_path);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_concatenated_names", godot_icall_NodePath_get_concatenated_names);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_concatenated_subnames", godot_icall_NodePath_get_concatenated_subnames);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_name", godot_icall_NodePath_get_name);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_name_count", godot_icall_NodePath_get_name_count);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_subname", godot_icall_NodePath_get_subname);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_subname_count", godot_icall_NodePath_get_subname_count);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_is_absolute", godot_icall_NodePath_is_absolute);
- GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_is_empty", godot_icall_NodePath_is_empty);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/rid_glue.cpp b/modules/mono/glue/rid_glue.cpp
deleted file mode 100644
index 3e09564539..0000000000
--- a/modules/mono/glue/rid_glue.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*************************************************************************/
-/* rid_glue.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 MONO_GLUE_ENABLED
-
-#include "core/io/resource.h"
-#include "core/object/class_db.h"
-#include "core/templates/rid.h"
-
-#include "../mono_gd/gd_mono_marshal.h"
-
-RID *godot_icall_RID_Ctor(Object *p_from) {
- Resource *res_from = Object::cast_to<Resource>(p_from);
-
- if (res_from) {
- return memnew(RID(res_from->get_rid()));
- }
-
- return memnew(RID);
-}
-
-void godot_icall_RID_Dtor(RID *p_ptr) {
- ERR_FAIL_NULL(p_ptr);
- memdelete(p_ptr);
-}
-
-uint32_t godot_icall_RID_get_id(RID *p_ptr) {
- return p_ptr->get_id();
-}
-
-void godot_register_rid_icalls() {
- GDMonoUtils::add_internal_call("Godot.RID::godot_icall_RID_Ctor", godot_icall_RID_Ctor);
- GDMonoUtils::add_internal_call("Godot.RID::godot_icall_RID_Dtor", godot_icall_RID_Dtor);
- GDMonoUtils::add_internal_call("Godot.RID::godot_icall_RID_get_id", godot_icall_RID_get_id);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/runtime_interop.cpp b/modules/mono/glue/runtime_interop.cpp
new file mode 100644
index 0000000000..13d4395a64
--- /dev/null
+++ b/modules/mono/glue/runtime_interop.cpp
@@ -0,0 +1,1513 @@
+/*************************************************************************/
+/* runtime_interop.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 "runtime_interop.h"
+
+#include "core/config/engine.h"
+#include "core/debugger/engine_debugger.h"
+#include "core/debugger/script_debugger.h"
+#include "core/io/marshalls.h"
+#include "core/object/class_db.h"
+#include "core/object/method_bind.h"
+#include "core/os/os.h"
+#include "core/string/string_name.h"
+
+#include "../interop_types.h"
+
+#include "modules/mono/csharp_script.h"
+#include "modules/mono/managed_callable.h"
+#include "modules/mono/mono_gd/gd_mono_cache.h"
+#include "modules/mono/signal_awaiter_utils.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// For ArrayPrivate and DictionaryPrivate
+static_assert(sizeof(SafeRefCount) == sizeof(uint32_t));
+
+typedef Object *(*godotsharp_class_creation_func)();
+
+MethodBind *godotsharp_method_bind_get_method(const StringName *p_classname, const StringName *p_methodname) {
+ return ClassDB::get_method(*p_classname, *p_methodname);
+}
+
+godotsharp_class_creation_func godotsharp_get_class_constructor(const StringName *p_classname) {
+ ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(*p_classname);
+ if (class_info) {
+ return class_info->creation_func;
+ }
+ return nullptr;
+}
+
+Object *godotsharp_engine_get_singleton(const String *p_name) {
+ return Engine::get_singleton()->get_singleton_object(*p_name);
+}
+
+int32_t godotsharp_stack_info_vector_resize(
+ Vector<ScriptLanguage::StackInfo> *p_stack_info_vector, int p_size) {
+ return (int32_t)p_stack_info_vector->resize(p_size);
+}
+
+void godotsharp_stack_info_vector_destroy(
+ Vector<ScriptLanguage::StackInfo> *p_stack_info_vector) {
+ p_stack_info_vector->~Vector();
+}
+
+void godotsharp_internal_script_debugger_send_error(const String *p_func,
+ const String *p_file, int32_t p_line, const String *p_err, const String *p_descr,
+ bool p_warning, const Vector<ScriptLanguage::StackInfo> *p_stack_info_vector) {
+ EngineDebugger::get_script_debugger()->send_error(*p_func, *p_file, p_line, *p_err, *p_descr,
+ true, p_warning ? ERR_HANDLER_WARNING : ERR_HANDLER_ERROR, *p_stack_info_vector);
+}
+
+bool godotsharp_internal_script_debugger_is_active() {
+ return EngineDebugger::is_active();
+}
+
+GCHandleIntPtr godotsharp_internal_object_get_associated_gchandle(Object *p_ptr) {
+#ifdef DEBUG_ENABLED
+ CRASH_COND(p_ptr == nullptr);
+#endif
+
+ if (p_ptr->get_script_instance()) {
+ CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(p_ptr->get_script_instance());
+ if (cs_instance) {
+ if (!cs_instance->is_destructing_script_instance()) {
+ return cs_instance->get_gchandle_intptr();
+ }
+ return { nullptr };
+ }
+ }
+
+ void *data = CSharpLanguage::get_existing_instance_binding(p_ptr);
+
+ if (data) {
+ CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
+ if (script_binding.inited) {
+ MonoGCHandleData &gchandle = script_binding.gchandle;
+ return !gchandle.is_released() ? gchandle.get_intptr() : GCHandleIntPtr{ nullptr };
+ }
+ }
+
+ return { nullptr };
+}
+
+void godotsharp_internal_object_disposed(Object *p_ptr, GCHandleIntPtr p_gchandle_to_free) {
+#ifdef DEBUG_ENABLED
+ CRASH_COND(p_ptr == nullptr);
+#endif
+
+ if (p_ptr->get_script_instance()) {
+ CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(p_ptr->get_script_instance());
+ if (cs_instance) {
+ if (!cs_instance->is_destructing_script_instance()) {
+ cs_instance->mono_object_disposed(p_gchandle_to_free);
+ p_ptr->set_script_instance(nullptr);
+ }
+ return;
+ }
+ }
+
+ void *data = CSharpLanguage::get_existing_instance_binding(p_ptr);
+
+ if (data) {
+ CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
+ if (script_binding.inited) {
+ if (!script_binding.gchandle.is_released()) {
+ CSharpLanguage::release_binding_gchandle_thread_safe(p_gchandle_to_free, script_binding);
+ }
+ }
+ }
+}
+
+void godotsharp_internal_refcounted_disposed(Object *p_ptr, GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer) {
+#ifdef DEBUG_ENABLED
+ CRASH_COND(p_ptr == nullptr);
+ // This is only called with RefCounted derived classes
+ CRASH_COND(!Object::cast_to<RefCounted>(p_ptr));
+#endif
+
+ RefCounted *rc = static_cast<RefCounted *>(p_ptr);
+
+ if (rc->get_script_instance()) {
+ CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(rc->get_script_instance());
+ if (cs_instance) {
+ if (!cs_instance->is_destructing_script_instance()) {
+ bool delete_owner;
+ bool remove_script_instance;
+
+ cs_instance->mono_object_disposed_baseref(p_gchandle_to_free, p_is_finalizer,
+ delete_owner, remove_script_instance);
+
+ if (delete_owner) {
+ memdelete(rc);
+ } else if (remove_script_instance) {
+ rc->set_script_instance(nullptr);
+ }
+ }
+ return;
+ }
+ }
+
+ // Unsafe refcount decrement. The managed instance also counts as a reference.
+ // See: CSharpLanguage::alloc_instance_binding_data(Object *p_object)
+ CSharpLanguage::get_singleton()->pre_unsafe_unreference(rc);
+ if (rc->unreference()) {
+ memdelete(rc);
+ } else {
+ void *data = CSharpLanguage::get_existing_instance_binding(rc);
+
+ if (data) {
+ CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
+ if (script_binding.inited) {
+ if (!script_binding.gchandle.is_released()) {
+ CSharpLanguage::release_binding_gchandle_thread_safe(p_gchandle_to_free, script_binding);
+ }
+ }
+ }
+ }
+}
+
+int32_t godotsharp_internal_signal_awaiter_connect(Object *p_source, StringName *p_signal, Object *p_target, GCHandleIntPtr p_awaiter_handle_ptr) {
+ StringName signal = p_signal ? *p_signal : StringName();
+ return (int32_t)gd_mono_connect_signal_awaiter(p_source, signal, p_target, p_awaiter_handle_ptr);
+}
+
+GCHandleIntPtr godotsharp_internal_unmanaged_get_script_instance_managed(Object *p_unmanaged, bool *r_has_cs_script_instance) {
+#ifdef DEBUG_ENABLED
+ CRASH_COND(!p_unmanaged);
+ CRASH_COND(!r_has_cs_script_instance);
+#endif
+
+ if (p_unmanaged->get_script_instance()) {
+ CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(p_unmanaged->get_script_instance());
+
+ if (cs_instance) {
+ *r_has_cs_script_instance = true;
+ return cs_instance->get_gchandle_intptr();
+ }
+ }
+
+ *r_has_cs_script_instance = false;
+ return { nullptr };
+}
+
+GCHandleIntPtr godotsharp_internal_unmanaged_get_instance_binding_managed(Object *p_unmanaged) {
+#ifdef DEBUG_ENABLED
+ CRASH_COND(!p_unmanaged);
+#endif
+
+ void *data = CSharpLanguage::get_instance_binding(p_unmanaged);
+ ERR_FAIL_NULL_V(data, { nullptr });
+ CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->value();
+ ERR_FAIL_COND_V(!script_binding.inited, { nullptr });
+
+ return script_binding.gchandle.get_intptr();
+}
+
+GCHandleIntPtr godotsharp_internal_unmanaged_instance_binding_create_managed(Object *p_unmanaged, GCHandleIntPtr p_old_gchandle) {
+#ifdef DEBUG_ENABLED
+ CRASH_COND(!p_unmanaged);
+#endif
+
+ void *data = CSharpLanguage::get_instance_binding(p_unmanaged);
+ ERR_FAIL_NULL_V(data, { nullptr });
+ CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->value();
+ ERR_FAIL_COND_V(!script_binding.inited, { nullptr });
+
+ MonoGCHandleData &gchandle = script_binding.gchandle;
+
+ // TODO: Possible data race?
+ CRASH_COND(gchandle.get_intptr().value != p_old_gchandle.value);
+
+ CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
+ script_binding.inited = false;
+
+ // Create a new one
+
+#ifdef DEBUG_ENABLED
+ CRASH_COND(script_binding.type_name == StringName());
+#endif
+
+ bool parent_is_object_class = ClassDB::is_parent_class(p_unmanaged->get_class_name(), script_binding.type_name);
+ ERR_FAIL_COND_V_MSG(!parent_is_object_class, { nullptr },
+ "Type inherits from native type '" + script_binding.type_name + "', so it can't be instantiated in object of type: '" + p_unmanaged->get_class() + "'.");
+
+ GCHandleIntPtr strong_gchandle =
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectBinding(
+ &script_binding.type_name, p_unmanaged);
+
+ ERR_FAIL_NULL_V(strong_gchandle.value, { nullptr });
+
+ gchandle = MonoGCHandleData(strong_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
+ script_binding.inited = true;
+
+ // Tie managed to unmanaged
+ RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
+
+ if (rc) {
+ // Unsafe refcount increment. The managed instance also counts as a reference.
+ // This way if the unmanaged world has no references to our owner
+ // but the managed instance is alive, the refcount will be 1 instead of 0.
+ // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
+ rc->reference();
+ CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
+ }
+
+ return gchandle.get_intptr();
+}
+
+void godotsharp_internal_tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted) {
+ CSharpLanguage::tie_native_managed_to_unmanaged(p_gchandle_intptr, p_unmanaged, p_native_name, p_ref_counted);
+}
+
+void godotsharp_internal_tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted) {
+ CSharpLanguage::tie_user_managed_to_unmanaged(p_gchandle_intptr, p_unmanaged, p_script, p_ref_counted);
+}
+
+void godotsharp_internal_tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged) {
+ CSharpLanguage::tie_managed_to_unmanaged_with_pre_setup(p_gchandle_intptr, p_unmanaged);
+}
+
+void godotsharp_internal_new_csharp_script(Ref<CSharpScript> *r_dest) {
+ memnew_placement(r_dest, Ref<CSharpScript>(memnew(CSharpScript)));
+}
+
+bool godotsharp_internal_script_load(const String *p_path, Ref<CSharpScript> *r_dest) {
+ Ref<Resource> res = ResourceLoader::load(*p_path);
+ if (res.is_valid()) {
+ memnew_placement(r_dest, Ref<CSharpScript>(res));
+ return true;
+ } else {
+ memnew_placement(r_dest, Ref<CSharpScript>());
+ return false;
+ }
+}
+
+void godotsharp_internal_reload_registered_script(CSharpScript *p_script) {
+ CRASH_COND(!p_script);
+ CSharpScript::reload_registered_script(Ref<CSharpScript>(p_script));
+}
+
+void godotsharp_array_filter_godot_objects_by_native(StringName *p_native_name, const Array *p_input, Array *r_output) {
+ memnew_placement(r_output, Array);
+
+ for (int i = 0; i < p_input->size(); ++i) {
+ if (ClassDB::is_parent_class(((Object *)(*p_input)[i])->get_class(), *p_native_name)) {
+ r_output->push_back(p_input[i]);
+ }
+ }
+}
+
+void godotsharp_array_filter_godot_objects_by_non_native(const Array *p_input, Array *r_output) {
+ memnew_placement(r_output, Array);
+
+ for (int i = 0; i < p_input->size(); ++i) {
+ CSharpInstance *si = CAST_CSHARP_INSTANCE(((Object *)(*p_input)[i])->get_script_instance());
+
+ if (si != nullptr) {
+ r_output->push_back(p_input[i]);
+ }
+ }
+}
+
+void godotsharp_ref_new_from_ref_counted_ptr(Ref<RefCounted> *r_dest, RefCounted *p_ref_counted_ptr) {
+ memnew_placement(r_dest, Ref<RefCounted>(p_ref_counted_ptr));
+}
+
+void godotsharp_ref_destroy(Ref<RefCounted> *p_instance) {
+ p_instance->~Ref();
+}
+
+void godotsharp_string_name_new_from_string(StringName *r_dest, const String *p_name) {
+ memnew_placement(r_dest, StringName(*p_name));
+}
+
+void godotsharp_node_path_new_from_string(NodePath *r_dest, const String *p_name) {
+ memnew_placement(r_dest, NodePath(*p_name));
+}
+
+void godotsharp_string_name_as_string(String *r_dest, const StringName *p_name) {
+ memnew_placement(r_dest, String(p_name->operator String()));
+}
+
+void godotsharp_node_path_as_string(String *r_dest, const NodePath *p_np) {
+ memnew_placement(r_dest, String(p_np->operator String()));
+}
+
+godot_packed_array godotsharp_packed_byte_array_new_mem_copy(const uint8_t *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedByteArray);
+ PackedByteArray *array = reinterpret_cast<PackedByteArray *>(&ret);
+ array->resize(p_length);
+ uint8_t *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(uint8_t));
+ return ret;
+}
+
+godot_packed_array godotsharp_packed_int32_array_new_mem_copy(const int32_t *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedInt32Array);
+ PackedInt32Array *array = reinterpret_cast<PackedInt32Array *>(&ret);
+ array->resize(p_length);
+ int32_t *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(int32_t));
+ return ret;
+}
+
+godot_packed_array godotsharp_packed_int64_array_new_mem_copy(const int64_t *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedInt64Array);
+ PackedInt64Array *array = reinterpret_cast<PackedInt64Array *>(&ret);
+ array->resize(p_length);
+ int64_t *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(int64_t));
+ return ret;
+}
+
+godot_packed_array godotsharp_packed_float32_array_new_mem_copy(const float *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedFloat32Array);
+ PackedFloat32Array *array = reinterpret_cast<PackedFloat32Array *>(&ret);
+ array->resize(p_length);
+ float *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(float));
+ return ret;
+}
+
+godot_packed_array godotsharp_packed_float64_array_new_mem_copy(const double *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedFloat64Array);
+ PackedFloat64Array *array = reinterpret_cast<PackedFloat64Array *>(&ret);
+ array->resize(p_length);
+ double *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(double));
+ return ret;
+}
+
+godot_packed_array godotsharp_packed_vector2_array_new_mem_copy(const Vector2 *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedVector2Array);
+ PackedVector2Array *array = reinterpret_cast<PackedVector2Array *>(&ret);
+ array->resize(p_length);
+ Vector2 *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(Vector2));
+ return ret;
+}
+
+godot_packed_array godotsharp_packed_vector3_array_new_mem_copy(const Vector3 *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedVector3Array);
+ PackedVector3Array *array = reinterpret_cast<PackedVector3Array *>(&ret);
+ array->resize(p_length);
+ Vector3 *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(Vector3));
+ return ret;
+}
+
+godot_packed_array godotsharp_packed_color_array_new_mem_copy(const Color *p_src, int32_t p_length) {
+ godot_packed_array ret;
+ memnew_placement(&ret, PackedColorArray);
+ PackedColorArray *array = reinterpret_cast<PackedColorArray *>(&ret);
+ array->resize(p_length);
+ Color *dst = array->ptrw();
+ memcpy(dst, p_src, p_length * sizeof(Color));
+ return ret;
+}
+
+void godotsharp_packed_string_array_add(PackedStringArray *r_dest, const String *p_element) {
+ r_dest->append(*p_element);
+}
+
+void godotsharp_callable_new_with_delegate(GCHandleIntPtr p_delegate_handle, Callable *r_callable) {
+ // TODO: Use pooling for ManagedCallable instances.
+ CallableCustom *managed_callable = memnew(ManagedCallable(p_delegate_handle));
+ memnew_placement(r_callable, Callable(managed_callable));
+}
+
+bool godotsharp_callable_get_data_for_marshalling(const Callable *p_callable,
+ GCHandleIntPtr *r_delegate_handle, Object **r_object, StringName *r_name) {
+ if (p_callable->is_custom()) {
+ CallableCustom *custom = p_callable->get_custom();
+ CallableCustom::CompareEqualFunc compare_equal_func = custom->get_compare_equal_func();
+
+ if (compare_equal_func == ManagedCallable::compare_equal_func_ptr) {
+ ManagedCallable *managed_callable = static_cast<ManagedCallable *>(custom);
+ *r_delegate_handle = managed_callable->get_delegate();
+ *r_object = nullptr;
+ memnew_placement(r_name, StringName());
+ return true;
+ } else if (compare_equal_func == SignalAwaiterCallable::compare_equal_func_ptr) {
+ SignalAwaiterCallable *signal_awaiter_callable = static_cast<SignalAwaiterCallable *>(custom);
+ *r_delegate_handle = { nullptr };
+ *r_object = ObjectDB::get_instance(signal_awaiter_callable->get_object());
+ memnew_placement(r_name, StringName(signal_awaiter_callable->get_signal()));
+ return true;
+ } else if (compare_equal_func == EventSignalCallable::compare_equal_func_ptr) {
+ EventSignalCallable *event_signal_callable = static_cast<EventSignalCallable *>(custom);
+ *r_delegate_handle = { nullptr };
+ *r_object = ObjectDB::get_instance(event_signal_callable->get_object());
+ memnew_placement(r_name, StringName(event_signal_callable->get_signal()));
+ return true;
+ }
+
+ // Some other CallableCustom. We only support ManagedCallable.
+ *r_delegate_handle = { nullptr };
+ *r_object = nullptr;
+ memnew_placement(r_name, StringName());
+ return false;
+ } else {
+ *r_delegate_handle = { nullptr };
+ *r_object = ObjectDB::get_instance(p_callable->get_object_id());
+ memnew_placement(r_name, StringName(p_callable->get_method()));
+ return true;
+ }
+}
+
+godot_variant godotsharp_callable_call(Callable *p_callable, const Variant **p_args, const int32_t p_arg_count, Callable::CallError *p_call_error) {
+ godot_variant ret;
+ memnew_placement(&ret, Variant);
+
+ Variant *ret_val = (Variant *)&ret;
+
+ p_callable->callp(p_args, p_arg_count, *ret_val, *p_call_error);
+
+ return ret;
+}
+
+void godotsharp_callable_call_deferred(Callable *p_callable, const Variant **p_args, const int32_t p_arg_count) {
+ p_callable->call_deferredp(p_args, p_arg_count);
+}
+
+// GDNative functions
+
+// gdnative.h
+
+void godotsharp_method_bind_ptrcall(MethodBind *p_method_bind, Object *p_instance, const void **p_args, void *p_ret) {
+ p_method_bind->ptrcall(p_instance, p_args, p_ret);
+}
+
+godot_variant godotsharp_method_bind_call(MethodBind *p_method_bind, Object *p_instance, const godot_variant **p_args, const int32_t p_arg_count, Callable::CallError *p_call_error) {
+ godot_variant ret;
+ memnew_placement(&ret, Variant());
+
+ Variant *ret_val = (Variant *)&ret;
+
+ *ret_val = p_method_bind->call(p_instance, (const Variant **)p_args, p_arg_count, *p_call_error);
+
+ return ret;
+}
+
+// variant.h
+
+void godotsharp_variant_new_copy(godot_variant *r_dest, const Variant *p_src) {
+ memnew_placement(r_dest, Variant(*p_src));
+}
+
+void godotsharp_variant_new_string_name(godot_variant *r_dest, const StringName *p_s) {
+ memnew_placement(r_dest, Variant(*p_s));
+}
+
+void godotsharp_variant_new_node_path(godot_variant *r_dest, const NodePath *p_np) {
+ memnew_placement(r_dest, Variant(*p_np));
+}
+
+void godotsharp_variant_new_object(godot_variant *r_dest, const Object *p_obj) {
+ memnew_placement(r_dest, Variant(p_obj));
+}
+
+void godotsharp_variant_new_transform2d(godot_variant *r_dest, const Transform2D *p_t2d) {
+ memnew_placement(r_dest, Variant(*p_t2d));
+}
+
+void godotsharp_variant_new_vector4(godot_variant *r_dest, const Vector4 *p_vec4) {
+ memnew_placement(r_dest, Variant(*p_vec4));
+}
+
+void godotsharp_variant_new_vector4i(godot_variant *r_dest, const Vector4i *p_vec4i) {
+ memnew_placement(r_dest, Variant(*p_vec4i));
+}
+
+void godotsharp_variant_new_basis(godot_variant *r_dest, const Basis *p_basis) {
+ memnew_placement(r_dest, Variant(*p_basis));
+}
+
+void godotsharp_variant_new_transform3d(godot_variant *r_dest, const Transform3D *p_trans) {
+ memnew_placement(r_dest, Variant(*p_trans));
+}
+
+void godotsharp_variant_new_projection(godot_variant *r_dest, const Projection *p_proj) {
+ memnew_placement(r_dest, Variant(*p_proj));
+}
+
+void godotsharp_variant_new_aabb(godot_variant *r_dest, const AABB *p_aabb) {
+ memnew_placement(r_dest, Variant(*p_aabb));
+}
+
+void godotsharp_variant_new_dictionary(godot_variant *r_dest, const Dictionary *p_dict) {
+ memnew_placement(r_dest, Variant(*p_dict));
+}
+
+void godotsharp_variant_new_array(godot_variant *r_dest, const Array *p_arr) {
+ memnew_placement(r_dest, Variant(*p_arr));
+}
+
+void godotsharp_variant_new_packed_byte_array(godot_variant *r_dest, const PackedByteArray *p_pba) {
+ memnew_placement(r_dest, Variant(*p_pba));
+}
+
+void godotsharp_variant_new_packed_int32_array(godot_variant *r_dest, const PackedInt32Array *p_pia) {
+ memnew_placement(r_dest, Variant(*p_pia));
+}
+
+void godotsharp_variant_new_packed_int64_array(godot_variant *r_dest, const PackedInt64Array *p_pia) {
+ memnew_placement(r_dest, Variant(*p_pia));
+}
+
+void godotsharp_variant_new_packed_float32_array(godot_variant *r_dest, const PackedFloat32Array *p_pra) {
+ memnew_placement(r_dest, Variant(*p_pra));
+}
+
+void godotsharp_variant_new_packed_float64_array(godot_variant *r_dest, const PackedFloat64Array *p_pra) {
+ memnew_placement(r_dest, Variant(*p_pra));
+}
+
+void godotsharp_variant_new_packed_string_array(godot_variant *r_dest, const PackedStringArray *p_psa) {
+ memnew_placement(r_dest, Variant(*p_psa));
+}
+
+void godotsharp_variant_new_packed_vector2_array(godot_variant *r_dest, const PackedVector2Array *p_pv2a) {
+ memnew_placement(r_dest, Variant(*p_pv2a));
+}
+
+void godotsharp_variant_new_packed_vector3_array(godot_variant *r_dest, const PackedVector3Array *p_pv3a) {
+ memnew_placement(r_dest, Variant(*p_pv3a));
+}
+
+void godotsharp_variant_new_packed_color_array(godot_variant *r_dest, const PackedColorArray *p_pca) {
+ memnew_placement(r_dest, Variant(*p_pca));
+}
+
+bool godotsharp_variant_as_bool(const Variant *p_self) {
+ return p_self->operator bool();
+}
+
+int64_t godotsharp_variant_as_int(const Variant *p_self) {
+ return p_self->operator int64_t();
+}
+
+double godotsharp_variant_as_float(const Variant *p_self) {
+ return p_self->operator double();
+}
+
+godot_string godotsharp_variant_as_string(const Variant *p_self) {
+ godot_string raw_dest;
+ String *dest = (String *)&raw_dest;
+ memnew_placement(dest, String(p_self->operator String()));
+ return raw_dest;
+}
+
+godot_vector2 godotsharp_variant_as_vector2(const Variant *p_self) {
+ godot_vector2 raw_dest;
+ Vector2 *dest = (Vector2 *)&raw_dest;
+ memnew_placement(dest, Vector2(p_self->operator Vector2()));
+ return raw_dest;
+}
+
+godot_vector2i godotsharp_variant_as_vector2i(const Variant *p_self) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ memnew_placement(dest, Vector2i(p_self->operator Vector2i()));
+ return raw_dest;
+}
+
+godot_rect2 godotsharp_variant_as_rect2(const Variant *p_self) {
+ godot_rect2 raw_dest;
+ Rect2 *dest = (Rect2 *)&raw_dest;
+ memnew_placement(dest, Rect2(p_self->operator Rect2()));
+ return raw_dest;
+}
+
+godot_rect2i godotsharp_variant_as_rect2i(const Variant *p_self) {
+ godot_rect2i raw_dest;
+ Rect2i *dest = (Rect2i *)&raw_dest;
+ memnew_placement(dest, Rect2i(p_self->operator Rect2i()));
+ return raw_dest;
+}
+
+godot_vector3 godotsharp_variant_as_vector3(const Variant *p_self) {
+ godot_vector3 raw_dest;
+ Vector3 *dest = (Vector3 *)&raw_dest;
+ memnew_placement(dest, Vector3(p_self->operator Vector3()));
+ return raw_dest;
+}
+
+godot_vector3i godotsharp_variant_as_vector3i(const Variant *p_self) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ memnew_placement(dest, Vector3i(p_self->operator Vector3i()));
+ return raw_dest;
+}
+
+godot_transform2d godotsharp_variant_as_transform2d(const Variant *p_self) {
+ godot_transform2d raw_dest;
+ Transform2D *dest = (Transform2D *)&raw_dest;
+ memnew_placement(dest, Transform2D(p_self->operator Transform2D()));
+ return raw_dest;
+}
+
+godot_vector4 godotsharp_variant_as_vector4(const Variant *p_self) {
+ godot_vector4 raw_dest;
+ Vector4 *dest = (Vector4 *)&raw_dest;
+ memnew_placement(dest, Vector4(p_self->operator Vector4()));
+ return raw_dest;
+}
+
+godot_vector4i godotsharp_variant_as_vector4i(const Variant *p_self) {
+ godot_vector4i raw_dest;
+ Vector4i *dest = (Vector4i *)&raw_dest;
+ memnew_placement(dest, Vector4i(p_self->operator Vector4i()));
+ return raw_dest;
+}
+
+godot_plane godotsharp_variant_as_plane(const Variant *p_self) {
+ godot_plane raw_dest;
+ Plane *dest = (Plane *)&raw_dest;
+ memnew_placement(dest, Plane(p_self->operator Plane()));
+ return raw_dest;
+}
+
+godot_quaternion godotsharp_variant_as_quaternion(const Variant *p_self) {
+ godot_quaternion raw_dest;
+ Quaternion *dest = (Quaternion *)&raw_dest;
+ memnew_placement(dest, Quaternion(p_self->operator Quaternion()));
+ return raw_dest;
+}
+
+godot_aabb godotsharp_variant_as_aabb(const Variant *p_self) {
+ godot_aabb raw_dest;
+ AABB *dest = (AABB *)&raw_dest;
+ memnew_placement(dest, AABB(p_self->operator ::AABB()));
+ return raw_dest;
+}
+
+godot_basis godotsharp_variant_as_basis(const Variant *p_self) {
+ godot_basis raw_dest;
+ Basis *dest = (Basis *)&raw_dest;
+ memnew_placement(dest, Basis(p_self->operator Basis()));
+ return raw_dest;
+}
+
+godot_transform3d godotsharp_variant_as_transform3d(const Variant *p_self) {
+ godot_transform3d raw_dest;
+ Transform3D *dest = (Transform3D *)&raw_dest;
+ memnew_placement(dest, Transform3D(p_self->operator Transform3D()));
+ return raw_dest;
+}
+
+godot_projection godotsharp_variant_as_projection(const Variant *p_self) {
+ godot_projection raw_dest;
+ Projection *dest = (Projection *)&raw_dest;
+ memnew_placement(dest, Projection(p_self->operator Projection()));
+ return raw_dest;
+}
+
+godot_color godotsharp_variant_as_color(const Variant *p_self) {
+ godot_color raw_dest;
+ Color *dest = (Color *)&raw_dest;
+ memnew_placement(dest, Color(p_self->operator Color()));
+ return raw_dest;
+}
+
+godot_string_name godotsharp_variant_as_string_name(const Variant *p_self) {
+ godot_string_name raw_dest;
+ StringName *dest = (StringName *)&raw_dest;
+ memnew_placement(dest, StringName(p_self->operator StringName()));
+ return raw_dest;
+}
+
+godot_node_path godotsharp_variant_as_node_path(const Variant *p_self) {
+ godot_node_path raw_dest;
+ NodePath *dest = (NodePath *)&raw_dest;
+ memnew_placement(dest, NodePath(p_self->operator NodePath()));
+ return raw_dest;
+}
+
+godot_rid godotsharp_variant_as_rid(const Variant *p_self) {
+ godot_rid raw_dest;
+ RID *dest = (RID *)&raw_dest;
+ memnew_placement(dest, RID(p_self->operator ::RID()));
+ return raw_dest;
+}
+
+godot_callable godotsharp_variant_as_callable(const Variant *p_self) {
+ godot_callable raw_dest;
+ Callable *dest = (Callable *)&raw_dest;
+ memnew_placement(dest, Callable(p_self->operator Callable()));
+ return raw_dest;
+}
+
+godot_signal godotsharp_variant_as_signal(const Variant *p_self) {
+ godot_signal raw_dest;
+ Signal *dest = (Signal *)&raw_dest;
+ memnew_placement(dest, Signal(p_self->operator Signal()));
+ return raw_dest;
+}
+
+godot_dictionary godotsharp_variant_as_dictionary(const Variant *p_self) {
+ godot_dictionary raw_dest;
+ Dictionary *dest = (Dictionary *)&raw_dest;
+ memnew_placement(dest, Dictionary(p_self->operator Dictionary()));
+ return raw_dest;
+}
+
+godot_array godotsharp_variant_as_array(const Variant *p_self) {
+ godot_array raw_dest;
+ Array *dest = (Array *)&raw_dest;
+ memnew_placement(dest, Array(p_self->operator Array()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_byte_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedByteArray *dest = (PackedByteArray *)&raw_dest;
+ memnew_placement(dest, PackedByteArray(p_self->operator PackedByteArray()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_int32_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedInt32Array *dest = (PackedInt32Array *)&raw_dest;
+ memnew_placement(dest, PackedInt32Array(p_self->operator PackedInt32Array()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_int64_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedInt64Array *dest = (PackedInt64Array *)&raw_dest;
+ memnew_placement(dest, PackedInt64Array(p_self->operator PackedInt64Array()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_float32_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedFloat32Array *dest = (PackedFloat32Array *)&raw_dest;
+ memnew_placement(dest, PackedFloat32Array(p_self->operator PackedFloat32Array()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_float64_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedFloat64Array *dest = (PackedFloat64Array *)&raw_dest;
+ memnew_placement(dest, PackedFloat64Array(p_self->operator PackedFloat64Array()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_string_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedStringArray *dest = (PackedStringArray *)&raw_dest;
+ memnew_placement(dest, PackedStringArray(p_self->operator PackedStringArray()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_vector2_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedVector2Array *dest = (PackedVector2Array *)&raw_dest;
+ memnew_placement(dest, PackedVector2Array(p_self->operator PackedVector2Array()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_vector3_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedVector3Array *dest = (PackedVector3Array *)&raw_dest;
+ memnew_placement(dest, PackedVector3Array(p_self->operator PackedVector3Array()));
+ return raw_dest;
+}
+
+godot_packed_array godotsharp_variant_as_packed_color_array(const Variant *p_self) {
+ godot_packed_array raw_dest;
+ PackedColorArray *dest = (PackedColorArray *)&raw_dest;
+ memnew_placement(dest, PackedColorArray(p_self->operator PackedColorArray()));
+ return raw_dest;
+}
+
+bool godotsharp_variant_equals(const godot_variant *p_a, const godot_variant *p_b) {
+ return *reinterpret_cast<const Variant *>(p_a) == *reinterpret_cast<const Variant *>(p_b);
+}
+
+// string.h
+
+void godotsharp_string_new_with_utf16_chars(String *r_dest, const char16_t *p_contents) {
+ memnew_placement(r_dest, String());
+ r_dest->parse_utf16(p_contents);
+}
+
+// string_name.h
+
+void godotsharp_string_name_new_copy(StringName *r_dest, const StringName *p_src) {
+ memnew_placement(r_dest, StringName(*p_src));
+}
+
+// node_path.h
+
+void godotsharp_node_path_new_copy(NodePath *r_dest, const NodePath *p_src) {
+ memnew_placement(r_dest, NodePath(*p_src));
+}
+
+// array.h
+
+void godotsharp_array_new(Array *r_dest) {
+ memnew_placement(r_dest, Array);
+}
+
+void godotsharp_array_new_copy(Array *r_dest, const Array *p_src) {
+ memnew_placement(r_dest, Array(*p_src));
+}
+
+godot_variant *godotsharp_array_ptrw(godot_array *p_self) {
+ return reinterpret_cast<godot_variant *>(&reinterpret_cast<Array *>(p_self)->operator[](0));
+}
+
+// dictionary.h
+
+void godotsharp_dictionary_new(Dictionary *r_dest) {
+ memnew_placement(r_dest, Dictionary);
+}
+
+void godotsharp_dictionary_new_copy(Dictionary *r_dest, const Dictionary *p_src) {
+ memnew_placement(r_dest, Dictionary(*p_src));
+}
+
+// destroy functions
+
+void godotsharp_packed_byte_array_destroy(PackedByteArray *p_self) {
+ p_self->~PackedByteArray();
+}
+
+void godotsharp_packed_int32_array_destroy(PackedInt32Array *p_self) {
+ p_self->~PackedInt32Array();
+}
+
+void godotsharp_packed_int64_array_destroy(PackedInt64Array *p_self) {
+ p_self->~PackedInt64Array();
+}
+
+void godotsharp_packed_float32_array_destroy(PackedFloat32Array *p_self) {
+ p_self->~PackedFloat32Array();
+}
+
+void godotsharp_packed_float64_array_destroy(PackedFloat64Array *p_self) {
+ p_self->~PackedFloat64Array();
+}
+
+void godotsharp_packed_string_array_destroy(PackedStringArray *p_self) {
+ p_self->~PackedStringArray();
+}
+
+void godotsharp_packed_vector2_array_destroy(PackedVector2Array *p_self) {
+ p_self->~PackedVector2Array();
+}
+
+void godotsharp_packed_vector3_array_destroy(PackedVector3Array *p_self) {
+ p_self->~PackedVector3Array();
+}
+
+void godotsharp_packed_color_array_destroy(PackedColorArray *p_self) {
+ p_self->~PackedColorArray();
+}
+
+void godotsharp_variant_destroy(Variant *p_self) {
+ p_self->~Variant();
+}
+
+void godotsharp_string_destroy(String *p_self) {
+ p_self->~String();
+}
+
+void godotsharp_string_name_destroy(StringName *p_self) {
+ p_self->~StringName();
+}
+
+void godotsharp_node_path_destroy(NodePath *p_self) {
+ p_self->~NodePath();
+}
+
+void godotsharp_signal_destroy(Signal *p_self) {
+ p_self->~Signal();
+}
+
+void godotsharp_callable_destroy(Callable *p_self) {
+ p_self->~Callable();
+}
+
+void godotsharp_array_destroy(Array *p_self) {
+ p_self->~Array();
+}
+
+void godotsharp_dictionary_destroy(Dictionary *p_self) {
+ p_self->~Dictionary();
+}
+
+// Array
+
+int32_t godotsharp_array_add(Array *p_self, const Variant *p_item) {
+ p_self->append(*p_item);
+ return p_self->size();
+}
+
+void godotsharp_array_duplicate(const Array *p_self, bool p_deep, Array *r_dest) {
+ memnew_placement(r_dest, Array(p_self->duplicate(p_deep)));
+}
+
+int32_t godotsharp_array_index_of(const Array *p_self, const Variant *p_item) {
+ return p_self->find(*p_item);
+}
+
+void godotsharp_array_insert(Array *p_self, int32_t p_index, const Variant *p_item) {
+ p_self->insert(p_index, *p_item);
+}
+
+void godotsharp_array_remove_at(Array *p_self, int32_t p_index) {
+ p_self->remove_at(p_index);
+}
+
+int32_t godotsharp_array_resize(Array *p_self, int32_t p_new_size) {
+ return (int32_t)p_self->resize(p_new_size);
+}
+
+void godotsharp_array_shuffle(Array *p_self) {
+ p_self->shuffle();
+}
+
+void godotsharp_array_to_string(const Array *p_self, String *r_str) {
+ *r_str = Variant(*p_self).operator String();
+}
+
+// Dictionary
+
+bool godotsharp_dictionary_try_get_value(const Dictionary *p_self, const Variant *p_key, Variant *r_value) {
+ const Variant *ret = p_self->getptr(*p_key);
+ if (ret == nullptr) {
+ memnew_placement(r_value, Variant());
+ return false;
+ }
+ memnew_placement(r_value, Variant(*ret));
+ return true;
+}
+
+void godotsharp_dictionary_set_value(Dictionary *p_self, const Variant *p_key, const Variant *p_value) {
+ p_self->operator[](*p_key) = *p_value;
+}
+
+void godotsharp_dictionary_keys(const Dictionary *p_self, Array *r_dest) {
+ memnew_placement(r_dest, Array(p_self->keys()));
+}
+
+void godotsharp_dictionary_values(const Dictionary *p_self, Array *r_dest) {
+ memnew_placement(r_dest, Array(p_self->values()));
+}
+
+int32_t godotsharp_dictionary_count(const Dictionary *p_self) {
+ return p_self->size();
+}
+
+void godotsharp_dictionary_key_value_pair_at(const Dictionary *p_self, int32_t p_index, Variant *r_key, Variant *r_value) {
+ memnew_placement(r_key, Variant(p_self->get_key_at_index(p_index)));
+ memnew_placement(r_value, Variant(p_self->get_value_at_index(p_index)));
+}
+
+void godotsharp_dictionary_add(Dictionary *p_self, const Variant *p_key, const Variant *p_value) {
+ p_self->operator[](*p_key) = *p_value;
+}
+
+void godotsharp_dictionary_clear(Dictionary *p_self) {
+ p_self->clear();
+}
+
+bool godotsharp_dictionary_contains_key(const Dictionary *p_self, const Variant *p_key) {
+ return p_self->has(*p_key);
+}
+
+void godotsharp_dictionary_duplicate(const Dictionary *p_self, bool p_deep, Dictionary *r_dest) {
+ memnew_placement(r_dest, Dictionary(p_self->duplicate(p_deep)));
+}
+
+bool godotsharp_dictionary_remove_key(Dictionary *p_self, const Variant *p_key) {
+ return p_self->erase(*p_key);
+}
+
+void godotsharp_dictionary_to_string(const Dictionary *p_self, String *r_str) {
+ *r_str = Variant(*p_self).operator String();
+}
+
+void godotsharp_string_md5_buffer(const String *p_self, PackedByteArray *r_md5_buffer) {
+ memnew_placement(r_md5_buffer, PackedByteArray(p_self->md5_buffer()));
+}
+
+void godotsharp_string_md5_text(const String *p_self, String *r_md5_text) {
+ memnew_placement(r_md5_text, String(p_self->md5_text()));
+}
+
+int32_t godotsharp_string_rfind(const String *p_self, const String *p_what, int32_t p_from) {
+ return p_self->rfind(*p_what, p_from);
+}
+
+int32_t godotsharp_string_rfindn(const String *p_self, const String *p_what, int32_t p_from) {
+ return p_self->rfindn(*p_what, p_from);
+}
+
+void godotsharp_string_sha256_buffer(const String *p_self, PackedByteArray *r_sha256_buffer) {
+ memnew_placement(r_sha256_buffer, PackedByteArray(p_self->sha256_buffer()));
+}
+
+void godotsharp_string_sha256_text(const String *p_self, String *r_sha256_text) {
+ memnew_placement(r_sha256_text, String(p_self->sha256_text()));
+}
+
+void godotsharp_string_simplify_path(const String *p_self, String *r_simplified_path) {
+ memnew_placement(r_simplified_path, String(p_self->simplify_path()));
+}
+
+void godotsharp_node_path_get_as_property_path(const NodePath *p_ptr, NodePath *r_dest) {
+ memnew_placement(r_dest, NodePath(p_ptr->get_as_property_path()));
+}
+
+void godotsharp_node_path_get_concatenated_names(const NodePath *p_self, String *r_subnames) {
+ memnew_placement(r_subnames, String(p_self->get_concatenated_names()));
+}
+
+void godotsharp_node_path_get_concatenated_subnames(const NodePath *p_self, String *r_subnames) {
+ memnew_placement(r_subnames, String(p_self->get_concatenated_subnames()));
+}
+
+void godotsharp_node_path_get_name(const NodePath *p_self, uint32_t p_idx, String *r_name) {
+ memnew_placement(r_name, String(p_self->get_name(p_idx)));
+}
+
+int32_t godotsharp_node_path_get_name_count(const NodePath *p_self) {
+ return p_self->get_name_count();
+}
+
+void godotsharp_node_path_get_subname(const NodePath *p_self, uint32_t p_idx, String *r_subname) {
+ memnew_placement(r_subname, String(p_self->get_subname(p_idx)));
+}
+
+int32_t godotsharp_node_path_get_subname_count(const NodePath *p_self) {
+ return p_self->get_subname_count();
+}
+
+bool godotsharp_node_path_is_absolute(const NodePath *p_self) {
+ return p_self->is_absolute();
+}
+
+void godotsharp_randomize() {
+ Math::randomize();
+}
+
+uint32_t godotsharp_randi() {
+ return Math::rand();
+}
+
+float godotsharp_randf() {
+ return Math::randf();
+}
+
+int32_t godotsharp_randi_range(int32_t p_from, int32_t p_to) {
+ return Math::random(p_from, p_to);
+}
+
+double godotsharp_randf_range(double p_from, double p_to) {
+ return Math::random(p_from, p_to);
+}
+
+double godotsharp_randfn(double p_mean, double p_deviation) {
+ return Math::randfn(p_mean, p_deviation);
+}
+
+void godotsharp_seed(uint64_t p_seed) {
+ Math::seed(p_seed);
+}
+
+uint32_t godotsharp_rand_from_seed(uint64_t p_seed, uint64_t *r_new_seed) {
+ uint32_t ret = Math::rand_from_seed(&p_seed);
+ *r_new_seed = p_seed;
+ return ret;
+}
+
+void godotsharp_weakref(Object *p_ptr, Ref<RefCounted> *r_weak_ref) {
+ if (!p_ptr) {
+ return;
+ }
+
+ Ref<WeakRef> wref;
+ RefCounted *rc = Object::cast_to<RefCounted>(p_ptr);
+
+ if (rc) {
+ Ref<RefCounted> r = rc;
+ if (!r.is_valid()) {
+ return;
+ }
+
+ wref.instantiate();
+ wref->set_ref(r);
+ } else {
+ wref.instantiate();
+ wref->set_obj(p_ptr);
+ }
+
+ memnew_placement(r_weak_ref, Ref<RefCounted>(wref));
+}
+
+void godotsharp_str(const godot_array *p_what, godot_string *r_ret) {
+ String &str = *memnew_placement(r_ret, String);
+ const Array &what = *reinterpret_cast<const Array *>(p_what);
+
+ for (int i = 0; i < what.size(); i++) {
+ String os = what[i].operator String();
+
+ if (i == 0) {
+ str = os;
+ } else {
+ str += os;
+ }
+ }
+}
+
+void godotsharp_print(const godot_string *p_what) {
+ print_line(*reinterpret_cast<const String *>(p_what));
+}
+
+void godotsharp_print_rich(const godot_string *p_what) {
+ print_line_rich(*reinterpret_cast<const String *>(p_what));
+}
+
+void godotsharp_printerr(const godot_string *p_what) {
+ print_error(*reinterpret_cast<const String *>(p_what));
+}
+
+void godotsharp_printt(const godot_string *p_what) {
+ print_line(*reinterpret_cast<const String *>(p_what));
+}
+
+void godotsharp_prints(const godot_string *p_what) {
+ print_line(*reinterpret_cast<const String *>(p_what));
+}
+
+void godotsharp_printraw(const godot_string *p_what) {
+ OS::get_singleton()->print("%s", reinterpret_cast<const String *>(p_what)->utf8().get_data());
+}
+
+void godotsharp_pusherror(const godot_string *p_str) {
+ ERR_PRINT(*reinterpret_cast<const String *>(p_str));
+}
+
+void godotsharp_pushwarning(const godot_string *p_str) {
+ WARN_PRINT(*reinterpret_cast<const String *>(p_str));
+}
+
+void godotsharp_var2str(const godot_variant *p_var, godot_string *r_ret) {
+ const Variant &var = *reinterpret_cast<const Variant *>(p_var);
+ String &vars = *memnew_placement(r_ret, String);
+ VariantWriter::write_to_string(var, vars);
+}
+
+void godotsharp_str2var(const godot_string *p_str, godot_variant *r_ret) {
+ Variant ret;
+
+ VariantParser::StreamString ss;
+ ss.s = *reinterpret_cast<const String *>(p_str);
+
+ String errs;
+ int line;
+ Error err = VariantParser::parse(&ss, ret, errs, line);
+ if (err != OK) {
+ String err_str = "Parse error at line " + itos(line) + ": " + errs + ".";
+ ERR_PRINT(err_str);
+ ret = err_str;
+ }
+ memnew_placement(r_ret, Variant(ret));
+}
+
+void godotsharp_var2bytes(const godot_variant *p_var, bool p_full_objects, godot_packed_array *r_bytes) {
+ const Variant &var = *reinterpret_cast<const Variant *>(p_var);
+ PackedByteArray &bytes = *memnew_placement(r_bytes, PackedByteArray);
+
+ int len;
+ Error err = encode_variant(var, nullptr, len, p_full_objects);
+ ERR_FAIL_COND_MSG(err != OK, "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).");
+
+ bytes.resize(len);
+ encode_variant(var, bytes.ptrw(), len, p_full_objects);
+}
+
+void godotsharp_bytes2var(const godot_packed_array *p_bytes, bool p_allow_objects, godot_variant *r_ret) {
+ const PackedByteArray *bytes = reinterpret_cast<const PackedByteArray *>(p_bytes);
+ Variant ret;
+ Error err = decode_variant(ret, bytes->ptr(), bytes->size(), nullptr, p_allow_objects);
+ if (err != OK) {
+ ret = RTR("Not enough bytes for decoding bytes, or invalid format.");
+ }
+ memnew_placement(r_ret, Variant(ret));
+}
+
+int godotsharp_hash(const godot_variant *p_var) {
+ return reinterpret_cast<const Variant *>(p_var)->hash();
+}
+
+void godotsharp_convert(const godot_variant *p_what, int32_t p_type, godot_variant *r_ret) {
+ const Variant *args[1] = { reinterpret_cast<const Variant *>(p_what) };
+ Callable::CallError ce;
+ Variant ret;
+ Variant::construct(Variant::Type(p_type), ret, args, 1, ce);
+ if (ce.error != Callable::CallError::CALL_OK) {
+ memnew_placement(r_ret, Variant);
+ ERR_FAIL_MSG("Unable to convert parameter from '" +
+ Variant::get_type_name(reinterpret_cast<const Variant *>(p_what)->get_type()) +
+ "' to '" + Variant::get_type_name(Variant::Type(p_type)) + "'.");
+ }
+ memnew_placement(r_ret, Variant(ret));
+}
+
+Object *godotsharp_instance_from_id(uint64_t p_instance_id) {
+ return ObjectDB::get_instance(ObjectID(p_instance_id));
+}
+
+void godotsharp_object_to_string(Object *p_ptr, godot_string *r_str) {
+#ifdef DEBUG_ENABLED
+ // Cannot happen in C#; would get an ObjectDisposedException instead.
+ CRASH_COND(p_ptr == nullptr);
+#endif
+ // Can't call 'Object::to_string()' here, as that can end up calling 'ToString' again resulting in an endless circular loop.
+ memnew_placement(r_str,
+ String("[" + p_ptr->get_class() + ":" + itos(p_ptr->get_instance_id()) + "]"));
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+// The order in this array must match the declaration order of
+// the methods in 'GodotSharp/Core/NativeInterop/NativeFuncs.cs'.
+static const void *unmanaged_callbacks[]{
+ (void *)godotsharp_method_bind_get_method,
+ (void *)godotsharp_get_class_constructor,
+ (void *)godotsharp_engine_get_singleton,
+ (void *)godotsharp_stack_info_vector_resize,
+ (void *)godotsharp_stack_info_vector_destroy,
+ (void *)godotsharp_internal_script_debugger_send_error,
+ (void *)godotsharp_internal_script_debugger_is_active,
+ (void *)godotsharp_internal_object_get_associated_gchandle,
+ (void *)godotsharp_internal_object_disposed,
+ (void *)godotsharp_internal_refcounted_disposed,
+ (void *)godotsharp_internal_signal_awaiter_connect,
+ (void *)godotsharp_internal_tie_native_managed_to_unmanaged,
+ (void *)godotsharp_internal_tie_user_managed_to_unmanaged,
+ (void *)godotsharp_internal_tie_managed_to_unmanaged_with_pre_setup,
+ (void *)godotsharp_internal_unmanaged_get_script_instance_managed,
+ (void *)godotsharp_internal_unmanaged_get_instance_binding_managed,
+ (void *)godotsharp_internal_unmanaged_instance_binding_create_managed,
+ (void *)godotsharp_internal_new_csharp_script,
+ (void *)godotsharp_internal_script_load,
+ (void *)godotsharp_internal_reload_registered_script,
+ (void *)godotsharp_array_filter_godot_objects_by_native,
+ (void *)godotsharp_array_filter_godot_objects_by_non_native,
+ (void *)godotsharp_ref_new_from_ref_counted_ptr,
+ (void *)godotsharp_ref_destroy,
+ (void *)godotsharp_string_name_new_from_string,
+ (void *)godotsharp_node_path_new_from_string,
+ (void *)godotsharp_string_name_as_string,
+ (void *)godotsharp_node_path_as_string,
+ (void *)godotsharp_packed_byte_array_new_mem_copy,
+ (void *)godotsharp_packed_int32_array_new_mem_copy,
+ (void *)godotsharp_packed_int64_array_new_mem_copy,
+ (void *)godotsharp_packed_float32_array_new_mem_copy,
+ (void *)godotsharp_packed_float64_array_new_mem_copy,
+ (void *)godotsharp_packed_vector2_array_new_mem_copy,
+ (void *)godotsharp_packed_vector3_array_new_mem_copy,
+ (void *)godotsharp_packed_color_array_new_mem_copy,
+ (void *)godotsharp_packed_string_array_add,
+ (void *)godotsharp_callable_new_with_delegate,
+ (void *)godotsharp_callable_get_data_for_marshalling,
+ (void *)godotsharp_callable_call,
+ (void *)godotsharp_callable_call_deferred,
+ (void *)godotsharp_method_bind_ptrcall,
+ (void *)godotsharp_method_bind_call,
+ (void *)godotsharp_variant_new_string_name,
+ (void *)godotsharp_variant_new_copy,
+ (void *)godotsharp_variant_new_node_path,
+ (void *)godotsharp_variant_new_object,
+ (void *)godotsharp_variant_new_transform2d,
+ (void *)godotsharp_variant_new_vector4,
+ (void *)godotsharp_variant_new_vector4i,
+ (void *)godotsharp_variant_new_basis,
+ (void *)godotsharp_variant_new_transform3d,
+ (void *)godotsharp_variant_new_projection,
+ (void *)godotsharp_variant_new_aabb,
+ (void *)godotsharp_variant_new_dictionary,
+ (void *)godotsharp_variant_new_array,
+ (void *)godotsharp_variant_new_packed_byte_array,
+ (void *)godotsharp_variant_new_packed_int32_array,
+ (void *)godotsharp_variant_new_packed_int64_array,
+ (void *)godotsharp_variant_new_packed_float32_array,
+ (void *)godotsharp_variant_new_packed_float64_array,
+ (void *)godotsharp_variant_new_packed_string_array,
+ (void *)godotsharp_variant_new_packed_vector2_array,
+ (void *)godotsharp_variant_new_packed_vector3_array,
+ (void *)godotsharp_variant_new_packed_color_array,
+ (void *)godotsharp_variant_as_bool,
+ (void *)godotsharp_variant_as_int,
+ (void *)godotsharp_variant_as_float,
+ (void *)godotsharp_variant_as_string,
+ (void *)godotsharp_variant_as_vector2,
+ (void *)godotsharp_variant_as_vector2i,
+ (void *)godotsharp_variant_as_rect2,
+ (void *)godotsharp_variant_as_rect2i,
+ (void *)godotsharp_variant_as_vector3,
+ (void *)godotsharp_variant_as_vector3i,
+ (void *)godotsharp_variant_as_transform2d,
+ (void *)godotsharp_variant_as_vector4,
+ (void *)godotsharp_variant_as_vector4i,
+ (void *)godotsharp_variant_as_plane,
+ (void *)godotsharp_variant_as_quaternion,
+ (void *)godotsharp_variant_as_aabb,
+ (void *)godotsharp_variant_as_basis,
+ (void *)godotsharp_variant_as_transform3d,
+ (void *)godotsharp_variant_as_projection,
+ (void *)godotsharp_variant_as_color,
+ (void *)godotsharp_variant_as_string_name,
+ (void *)godotsharp_variant_as_node_path,
+ (void *)godotsharp_variant_as_rid,
+ (void *)godotsharp_variant_as_callable,
+ (void *)godotsharp_variant_as_signal,
+ (void *)godotsharp_variant_as_dictionary,
+ (void *)godotsharp_variant_as_array,
+ (void *)godotsharp_variant_as_packed_byte_array,
+ (void *)godotsharp_variant_as_packed_int32_array,
+ (void *)godotsharp_variant_as_packed_int64_array,
+ (void *)godotsharp_variant_as_packed_float32_array,
+ (void *)godotsharp_variant_as_packed_float64_array,
+ (void *)godotsharp_variant_as_packed_string_array,
+ (void *)godotsharp_variant_as_packed_vector2_array,
+ (void *)godotsharp_variant_as_packed_vector3_array,
+ (void *)godotsharp_variant_as_packed_color_array,
+ (void *)godotsharp_variant_equals,
+ (void *)godotsharp_string_new_with_utf16_chars,
+ (void *)godotsharp_string_name_new_copy,
+ (void *)godotsharp_node_path_new_copy,
+ (void *)godotsharp_array_new,
+ (void *)godotsharp_array_new_copy,
+ (void *)godotsharp_array_ptrw,
+ (void *)godotsharp_dictionary_new,
+ (void *)godotsharp_dictionary_new_copy,
+ (void *)godotsharp_packed_byte_array_destroy,
+ (void *)godotsharp_packed_int32_array_destroy,
+ (void *)godotsharp_packed_int64_array_destroy,
+ (void *)godotsharp_packed_float32_array_destroy,
+ (void *)godotsharp_packed_float64_array_destroy,
+ (void *)godotsharp_packed_string_array_destroy,
+ (void *)godotsharp_packed_vector2_array_destroy,
+ (void *)godotsharp_packed_vector3_array_destroy,
+ (void *)godotsharp_packed_color_array_destroy,
+ (void *)godotsharp_variant_destroy,
+ (void *)godotsharp_string_destroy,
+ (void *)godotsharp_string_name_destroy,
+ (void *)godotsharp_node_path_destroy,
+ (void *)godotsharp_signal_destroy,
+ (void *)godotsharp_callable_destroy,
+ (void *)godotsharp_array_destroy,
+ (void *)godotsharp_dictionary_destroy,
+ (void *)godotsharp_array_add,
+ (void *)godotsharp_array_duplicate,
+ (void *)godotsharp_array_index_of,
+ (void *)godotsharp_array_insert,
+ (void *)godotsharp_array_remove_at,
+ (void *)godotsharp_array_resize,
+ (void *)godotsharp_array_shuffle,
+ (void *)godotsharp_array_to_string,
+ (void *)godotsharp_dictionary_try_get_value,
+ (void *)godotsharp_dictionary_set_value,
+ (void *)godotsharp_dictionary_keys,
+ (void *)godotsharp_dictionary_values,
+ (void *)godotsharp_dictionary_count,
+ (void *)godotsharp_dictionary_key_value_pair_at,
+ (void *)godotsharp_dictionary_add,
+ (void *)godotsharp_dictionary_clear,
+ (void *)godotsharp_dictionary_contains_key,
+ (void *)godotsharp_dictionary_duplicate,
+ (void *)godotsharp_dictionary_remove_key,
+ (void *)godotsharp_dictionary_to_string,
+ (void *)godotsharp_string_md5_buffer,
+ (void *)godotsharp_string_md5_text,
+ (void *)godotsharp_string_rfind,
+ (void *)godotsharp_string_rfindn,
+ (void *)godotsharp_string_sha256_buffer,
+ (void *)godotsharp_string_sha256_text,
+ (void *)godotsharp_string_simplify_path,
+ (void *)godotsharp_node_path_get_as_property_path,
+ (void *)godotsharp_node_path_get_concatenated_names,
+ (void *)godotsharp_node_path_get_concatenated_subnames,
+ (void *)godotsharp_node_path_get_name,
+ (void *)godotsharp_node_path_get_name_count,
+ (void *)godotsharp_node_path_get_subname,
+ (void *)godotsharp_node_path_get_subname_count,
+ (void *)godotsharp_node_path_is_absolute,
+ (void *)godotsharp_bytes2var,
+ (void *)godotsharp_convert,
+ (void *)godotsharp_hash,
+ (void *)godotsharp_instance_from_id,
+ (void *)godotsharp_print,
+ (void *)godotsharp_print_rich,
+ (void *)godotsharp_printerr,
+ (void *)godotsharp_printraw,
+ (void *)godotsharp_prints,
+ (void *)godotsharp_printt,
+ (void *)godotsharp_randf,
+ (void *)godotsharp_randi,
+ (void *)godotsharp_randomize,
+ (void *)godotsharp_randf_range,
+ (void *)godotsharp_randfn,
+ (void *)godotsharp_randi_range,
+ (void *)godotsharp_rand_from_seed,
+ (void *)godotsharp_seed,
+ (void *)godotsharp_weakref,
+ (void *)godotsharp_str,
+ (void *)godotsharp_str2var,
+ (void *)godotsharp_var2bytes,
+ (void *)godotsharp_var2str,
+ (void *)godotsharp_pusherror,
+ (void *)godotsharp_pushwarning,
+ (void *)godotsharp_object_to_string,
+};
+
+const void **godotsharp::get_runtime_interop_funcs(int32_t &r_size) {
+ r_size = sizeof(unmanaged_callbacks);
+ return unmanaged_callbacks;
+}
diff --git a/modules/visual_script/register_types.h b/modules/mono/glue/runtime_interop.h
index 90f84de11c..9725ced593 100644
--- a/modules/visual_script/register_types.h
+++ b/modules/mono/glue/runtime_interop.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* register_types.h */
+/* runtime_interop.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,12 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef VISUAL_SCRIPT_REGISTER_TYPES_H
-#define VISUAL_SCRIPT_REGISTER_TYPES_H
+#ifndef RUNTIME_INTEROP_H
+#define RUNTIME_INTEROP_H
-#include "modules/register_module_types.h"
+#include "core/typedefs.h"
-void initialize_visual_script_module(ModuleInitializationLevel p_level);
-void uninitialize_visual_script_module(ModuleInitializationLevel p_level);
+namespace godotsharp {
+const void **get_runtime_interop_funcs(int32_t &r_size);
+}
-#endif // VISUAL_SCRIPT_REGISTER_TYPES_H
+#endif // RUNTIME_INTEROP_H
diff --git a/modules/mono/glue/scene_tree_glue.cpp b/modules/mono/glue/scene_tree_glue.cpp
deleted file mode 100644
index c60e7c4869..0000000000
--- a/modules/mono/glue/scene_tree_glue.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*************************************************************************/
-/* scene_tree_glue.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 MONO_GLUE_ENABLED
-
-#include "core/object/class_db.h"
-#include "core/string/string_name.h"
-#include "core/variant/array.h"
-#include "scene/main/node.h"
-#include "scene/main/scene_tree.h"
-
-#include "../csharp_script.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "../mono_gd/gd_mono_utils.h"
-
-Array *godot_icall_SceneTree_get_nodes_in_group_Generic(SceneTree *ptr, StringName *group, MonoReflectionType *refltype) {
- List<Node *> nodes;
- Array ret;
-
- // Retrieve all the nodes in the group
- ptr->get_nodes_in_group(*group, &nodes);
-
- // No need to bother if the group is empty
- if (!nodes.is_empty()) {
- MonoType *elem_type = mono_reflection_type_get_type(refltype);
- MonoClass *mono_class = mono_class_from_mono_type(elem_type);
- GDMonoClass *klass = GDMono::get_singleton()->get_class(mono_class);
-
- if (klass == GDMonoUtils::get_class_native_base(klass)) {
- // If we're trying to get native objects, just check the inheritance list
- StringName native_class_name = GDMonoUtils::get_native_godot_class_name(klass);
- for (int i = 0; i < nodes.size(); ++i) {
- if (ClassDB::is_parent_class(nodes[i]->get_class(), native_class_name)) {
- ret.push_back(nodes[i]);
- }
- }
- } else {
- // If we're trying to get csharpscript instances, get the mono object and compare the classes
- for (int i = 0; i < nodes.size(); ++i) {
- CSharpInstance *si = CAST_CSHARP_INSTANCE(nodes[i]->get_script_instance());
-
- if (si != nullptr) {
- MonoObject *obj = si->get_mono_object();
- if (obj != nullptr && mono_object_get_class(obj) == mono_class) {
- ret.push_back(nodes[i]);
- }
- }
- }
- }
- }
-
- return memnew(Array(ret));
-}
-
-void godot_register_scene_tree_icalls() {
- GDMonoUtils::add_internal_call("Godot.SceneTree::godot_icall_SceneTree_get_nodes_in_group_Generic", godot_icall_SceneTree_get_nodes_in_group_Generic);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/string_glue.cpp b/modules/mono/glue/string_glue.cpp
deleted file mode 100644
index fc6b13ceb3..0000000000
--- a/modules/mono/glue/string_glue.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/*************************************************************************/
-/* string_glue.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 MONO_GLUE_ENABLED
-
-#include "core/string/ustring.h"
-#include "core/templates/vector.h"
-#include "core/variant/variant.h"
-
-#include "../mono_gd/gd_mono_marshal.h"
-
-MonoArray *godot_icall_String_md5_buffer(MonoString *p_str) {
- Vector<uint8_t> ret = GDMonoMarshal::mono_string_to_godot(p_str).md5_buffer();
- // TODO Check possible Array/Vector<uint8_t> problem?
- return GDMonoMarshal::Array_to_mono_array(Variant(ret));
-}
-
-MonoString *godot_icall_String_md5_text(MonoString *p_str) {
- String ret = GDMonoMarshal::mono_string_to_godot(p_str).md5_text();
- return GDMonoMarshal::mono_string_from_godot(ret);
-}
-
-int godot_icall_String_rfind(MonoString *p_str, MonoString *p_what, int p_from) {
- String what = GDMonoMarshal::mono_string_to_godot(p_what);
- return GDMonoMarshal::mono_string_to_godot(p_str).rfind(what, p_from);
-}
-
-int godot_icall_String_rfindn(MonoString *p_str, MonoString *p_what, int p_from) {
- String what = GDMonoMarshal::mono_string_to_godot(p_what);
- return GDMonoMarshal::mono_string_to_godot(p_str).rfindn(what, p_from);
-}
-
-MonoArray *godot_icall_String_sha256_buffer(MonoString *p_str) {
- Vector<uint8_t> ret = GDMonoMarshal::mono_string_to_godot(p_str).sha256_buffer();
- return GDMonoMarshal::Array_to_mono_array(Variant(ret));
-}
-
-MonoString *godot_icall_String_sha256_text(MonoString *p_str) {
- String ret = GDMonoMarshal::mono_string_to_godot(p_str).sha256_text();
- return GDMonoMarshal::mono_string_from_godot(ret);
-}
-
-MonoString *godot_icall_String_simplify_path(MonoString *p_str) {
- String ret = GDMonoMarshal::mono_string_to_godot(p_str).simplify_path();
- return GDMonoMarshal::mono_string_from_godot(ret);
-}
-
-void godot_register_string_icalls() {
- GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_md5_buffer", godot_icall_String_md5_buffer);
- GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_md5_text", godot_icall_String_md5_text);
- GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_rfind", godot_icall_String_rfind);
- GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_rfindn", godot_icall_String_rfindn);
- GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_buffer", godot_icall_String_sha256_buffer);
- GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_text", godot_icall_String_sha256_text);
- GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_simplify_path", godot_icall_String_simplify_path);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/string_name_glue.cpp b/modules/mono/glue/string_name_glue.cpp
deleted file mode 100644
index 46d15316ba..0000000000
--- a/modules/mono/glue/string_name_glue.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/*************************************************************************/
-/* string_name_glue.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 MONO_GLUE_ENABLED
-
-#include "core/string/string_name.h"
-#include "core/string/ustring.h"
-
-#include "../mono_gd/gd_mono_marshal.h"
-
-StringName *godot_icall_StringName_Ctor(MonoString *p_path) {
- return memnew(StringName(GDMonoMarshal::mono_string_to_godot(p_path)));
-}
-
-void godot_icall_StringName_Dtor(StringName *p_ptr) {
- ERR_FAIL_NULL(p_ptr);
- memdelete(p_ptr);
-}
-
-MonoString *godot_icall_StringName_operator_String(StringName *p_np) {
- return GDMonoMarshal::mono_string_from_godot(p_np->operator String());
-}
-
-MonoBoolean godot_icall_StringName_is_empty(StringName *p_ptr) {
- return (MonoBoolean)(*p_ptr == StringName());
-}
-
-void godot_register_string_name_icalls() {
- GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_Ctor", godot_icall_StringName_Ctor);
- GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_Dtor", godot_icall_StringName_Dtor);
- GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_operator_String", godot_icall_StringName_operator_String);
- GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_is_empty", godot_icall_StringName_is_empty);
-}
-
-#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/godotsharp_defs.h b/modules/mono/godotsharp_defs.h
index e5f1abe8d7..a81a52e4b8 100644
--- a/modules/mono/godotsharp_defs.h
+++ b/modules/mono/godotsharp_defs.h
@@ -33,14 +33,10 @@
#define BINDINGS_NAMESPACE "Godot"
#define BINDINGS_NAMESPACE_COLLECTIONS BINDINGS_NAMESPACE ".Collections"
-#define BINDINGS_GLOBAL_SCOPE_CLASS "GD"
-#define BINDINGS_PTR_FIELD "ptr"
-#define BINDINGS_NATIVE_NAME_FIELD "nativeName"
#define API_SOLUTION_NAME "GodotSharp"
#define CORE_API_ASSEMBLY_NAME "GodotSharp"
#define EDITOR_API_ASSEMBLY_NAME "GodotSharpEditor"
#define TOOLS_ASM_NAME "GodotTools"
-#define TOOLS_PROJECT_EDITOR_ASM_NAME "GodotTools.ProjectEditor"
#define BINDINGS_CLASS_NATIVECALLS "NativeCalls"
#define BINDINGS_CLASS_NATIVECALLS_EDITOR "EditorNativeCalls"
diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp
index f17b24e399..71576c2f80 100644
--- a/modules/mono/godotsharp_dirs.cpp
+++ b/modules/mono/godotsharp_dirs.cpp
@@ -96,8 +96,6 @@ class _GodotSharpDirs {
public:
String res_data_dir;
String res_metadata_dir;
- String res_assemblies_base_dir;
- String res_assemblies_dir;
String res_config_dir;
String res_temp_dir;
String res_temp_assemblies_base_dir;
@@ -105,15 +103,14 @@ public:
String mono_user_dir;
String mono_logs_dir;
+ String api_assemblies_base_dir;
+ String api_assemblies_dir;
+
#ifdef TOOLS_ENABLED
String mono_solutions_dir;
String build_logs_dir;
- String sln_filepath;
- String csproj_filepath;
-
String data_editor_tools_dir;
- String data_editor_prebuilt_api_dir;
#else
// Equivalent of res_assemblies_dir, but in the data directory rather than in 'res://'.
// Only defined on export templates. Used when exporting assemblies outside of PCKs.
@@ -131,8 +128,6 @@ private:
_GodotSharpDirs() {
res_data_dir = ProjectSettings::get_singleton()->get_project_data_path().plus_file("mono");
res_metadata_dir = res_data_dir.plus_file("metadata");
- res_assemblies_base_dir = res_data_dir.plus_file("assemblies");
- res_assemblies_dir = res_assemblies_base_dir.plus_file(GDMono::get_expected_api_build_config());
res_config_dir = res_data_dir.plus_file("etc").plus_file("mono");
// TODO use paths from csproj
@@ -140,6 +135,8 @@ private:
res_temp_assemblies_base_dir = res_temp_dir.plus_file("bin");
res_temp_assemblies_dir = res_temp_assemblies_base_dir.plus_file(_get_expected_build_config());
+ api_assemblies_base_dir = res_data_dir.plus_file("assemblies");
+
#ifdef JAVASCRIPT_ENABLED
mono_user_dir = "user://";
#else
@@ -151,16 +148,7 @@ private:
mono_solutions_dir = mono_user_dir.plus_file("solutions");
build_logs_dir = mono_user_dir.plus_file("build_logs");
- String appname = ProjectSettings::get_singleton()->get("application/config/name");
- String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
- if (appname_safe.is_empty()) {
- appname_safe = "UnnamedProject";
- }
-
String base_path = ProjectSettings::get_singleton()->globalize_path("res://");
-
- sln_filepath = base_path.plus_file(appname_safe + ".sln");
- csproj_filepath = base_path.plus_file(appname_safe + ".csproj");
#endif
String exe_dir = OS::get_singleton()->get_executable_path().get_base_dir();
@@ -169,7 +157,7 @@ private:
String data_dir_root = exe_dir.plus_file("GodotSharp");
data_editor_tools_dir = data_dir_root.plus_file("Tools");
- data_editor_prebuilt_api_dir = data_dir_root.plus_file("Api");
+ api_assemblies_base_dir = data_dir_root.plus_file("Api");
String data_mono_root_dir = data_dir_root.plus_file("Mono");
data_mono_etc_dir = data_mono_root_dir.plus_file("etc");
@@ -189,8 +177,8 @@ private:
data_editor_tools_dir = exe_dir.plus_file("../Resources/GodotSharp/Tools");
}
- if (!DirAccess::exists(data_editor_prebuilt_api_dir)) {
- data_editor_prebuilt_api_dir = exe_dir.plus_file("../Resources/GodotSharp/Api");
+ if (!DirAccess::exists(api_assemblies_base_dir)) {
+ api_assemblies_base_dir = exe_dir.plus_file("../Resources/GodotSharp/Api");
}
if (!DirAccess::exists(data_mono_root_dir)) {
@@ -234,6 +222,12 @@ private:
#endif
#endif
+
+#ifdef TOOLS_ENABLED
+ api_assemblies_dir = api_assemblies_base_dir.plus_file(GDMono::get_expected_api_build_config());
+#else
+ api_assemblies_dir = data_dir_root;
+#endif
}
public:
@@ -251,14 +245,6 @@ String get_res_metadata_dir() {
return _GodotSharpDirs::get_singleton().res_metadata_dir;
}
-String get_res_assemblies_base_dir() {
- return _GodotSharpDirs::get_singleton().res_assemblies_base_dir;
-}
-
-String get_res_assemblies_dir() {
- return _GodotSharpDirs::get_singleton().res_assemblies_dir;
-}
-
String get_res_config_dir() {
return _GodotSharpDirs::get_singleton().res_config_dir;
}
@@ -275,6 +261,14 @@ String get_res_temp_assemblies_dir() {
return _GodotSharpDirs::get_singleton().res_temp_assemblies_dir;
}
+String get_api_assemblies_dir() {
+ return _GodotSharpDirs::get_singleton().api_assemblies_dir;
+}
+
+String get_api_assemblies_base_dir() {
+ return _GodotSharpDirs::get_singleton().api_assemblies_base_dir;
+}
+
String get_mono_user_dir() {
return _GodotSharpDirs::get_singleton().mono_user_dir;
}
@@ -292,21 +286,9 @@ String get_build_logs_dir() {
return _GodotSharpDirs::get_singleton().build_logs_dir;
}
-String get_project_sln_path() {
- return _GodotSharpDirs::get_singleton().sln_filepath;
-}
-
-String get_project_csproj_path() {
- return _GodotSharpDirs::get_singleton().csproj_filepath;
-}
-
String get_data_editor_tools_dir() {
return _GodotSharpDirs::get_singleton().data_editor_tools_dir;
}
-
-String get_data_editor_prebuilt_api_dir() {
- return _GodotSharpDirs::get_singleton().data_editor_prebuilt_api_dir;
-}
#else
String get_data_game_assemblies_dir() {
return _GodotSharpDirs::get_singleton().data_game_assemblies_dir;
diff --git a/modules/mono/godotsharp_dirs.h b/modules/mono/godotsharp_dirs.h
index da25e0778f..03e62ffd82 100644
--- a/modules/mono/godotsharp_dirs.h
+++ b/modules/mono/godotsharp_dirs.h
@@ -37,13 +37,14 @@ namespace GodotSharpDirs {
String get_res_data_dir();
String get_res_metadata_dir();
-String get_res_assemblies_base_dir();
-String get_res_assemblies_dir();
String get_res_config_dir();
String get_res_temp_dir();
String get_res_temp_assemblies_base_dir();
String get_res_temp_assemblies_dir();
+String get_api_assemblies_dir();
+String get_api_assemblies_base_dir();
+
String get_mono_user_dir();
String get_mono_logs_dir();
@@ -51,11 +52,7 @@ String get_mono_logs_dir();
String get_mono_solutions_dir();
String get_build_logs_dir();
-String get_project_sln_path();
-String get_project_csproj_path();
-
String get_data_editor_tools_dir();
-String get_data_editor_prebuilt_api_dir();
#else
String get_data_game_assemblies_dir();
#endif
diff --git a/modules/mono/interop_types.h b/modules/mono/interop_types.h
new file mode 100644
index 0000000000..6942a91559
--- /dev/null
+++ b/modules/mono/interop_types.h
@@ -0,0 +1,208 @@
+/*************************************************************************/
+/* interop_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 INTEROP_TYPES_H
+#define INTEROP_TYPES_H
+
+#include "core/math/math_defs.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdbool.h>
+#include <stdint.h>
+
+// This is taken from the old GDNative, which was removed.
+
+#define GODOT_VARIANT_SIZE (sizeof(real_t) * 4 + sizeof(int64_t))
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VARIANT_SIZE];
+} godot_variant;
+
+#define GODOT_ARRAY_SIZE sizeof(void *)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_ARRAY_SIZE];
+} godot_array;
+
+#define GODOT_DICTIONARY_SIZE sizeof(void *)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_DICTIONARY_SIZE];
+} godot_dictionary;
+
+#define GODOT_STRING_SIZE sizeof(void *)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_STRING_SIZE];
+} godot_string;
+
+#define GODOT_STRING_NAME_SIZE sizeof(void *)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_STRING_NAME_SIZE];
+} godot_string_name;
+
+#define GODOT_PACKED_ARRAY_SIZE (2 * sizeof(void *))
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_ARRAY_SIZE];
+} godot_packed_array;
+
+#define GODOT_VECTOR2_SIZE (sizeof(real_t) * 2)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR2_SIZE];
+} godot_vector2;
+
+#define GODOT_VECTOR2I_SIZE (sizeof(int32_t) * 2)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR2I_SIZE];
+} godot_vector2i;
+
+#define GODOT_RECT2_SIZE (sizeof(real_t) * 4)
+
+typedef struct godot_rect2 {
+ uint8_t _dont_touch_that[GODOT_RECT2_SIZE];
+} godot_rect2;
+
+#define GODOT_RECT2I_SIZE (sizeof(int32_t) * 4)
+
+typedef struct godot_rect2i {
+ uint8_t _dont_touch_that[GODOT_RECT2I_SIZE];
+} godot_rect2i;
+
+#define GODOT_VECTOR3_SIZE (sizeof(real_t) * 3)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR3_SIZE];
+} godot_vector3;
+
+#define GODOT_VECTOR3I_SIZE (sizeof(int32_t) * 3)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR3I_SIZE];
+} godot_vector3i;
+
+#define GODOT_TRANSFORM2D_SIZE (sizeof(real_t) * 6)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_TRANSFORM2D_SIZE];
+} godot_transform2d;
+
+#define GODOT_VECTOR4_SIZE (sizeof(real_t) * 4)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR4_SIZE];
+} godot_vector4;
+
+#define GODOT_VECTOR4I_SIZE (sizeof(int32_t) * 4)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR4I_SIZE];
+} godot_vector4i;
+
+#define GODOT_PLANE_SIZE (sizeof(real_t) * 4)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PLANE_SIZE];
+} godot_plane;
+
+#define GODOT_QUATERNION_SIZE (sizeof(real_t) * 4)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_QUATERNION_SIZE];
+} godot_quaternion;
+
+#define GODOT_AABB_SIZE (sizeof(real_t) * 6)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_AABB_SIZE];
+} godot_aabb;
+
+#define GODOT_BASIS_SIZE (sizeof(real_t) * 9)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_BASIS_SIZE];
+} godot_basis;
+
+#define GODOT_TRANSFORM3D_SIZE (sizeof(real_t) * 12)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_TRANSFORM3D_SIZE];
+} godot_transform3d;
+
+#define GODOT_PROJECTION_SIZE (sizeof(real_t) * 4 * 4)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PROJECTION_SIZE];
+} godot_projection;
+
+// Colors should always use 32-bit floats, so don't use real_t here.
+#define GODOT_COLOR_SIZE (sizeof(float) * 4)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_COLOR_SIZE];
+} godot_color;
+
+#define GODOT_NODE_PATH_SIZE sizeof(void *)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_NODE_PATH_SIZE];
+} godot_node_path;
+
+#define GODOT_RID_SIZE sizeof(uint64_t)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_RID_SIZE];
+} godot_rid;
+
+// Alignment hardcoded in `core/variant/callable.h`.
+#define GODOT_CALLABLE_SIZE (16)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_CALLABLE_SIZE];
+} godot_callable;
+
+// Alignment hardcoded in `core/variant/callable.h`.
+#define GODOT_SIGNAL_SIZE (16)
+
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_SIGNAL_SIZE];
+} godot_signal;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // INTEROP_TYPES_H
diff --git a/modules/mono/managed_callable.cpp b/modules/mono/managed_callable.cpp
index c159bb9eea..9305dc645a 100644
--- a/modules/mono/managed_callable.cpp
+++ b/modules/mono/managed_callable.cpp
@@ -31,8 +31,7 @@
#include "managed_callable.h"
#include "csharp_script.h"
-#include "mono_gd/gd_mono_marshal.h"
-#include "mono_gd/gd_mono_utils.h"
+#include "mono_gd/gd_mono_cache.h"
#ifdef GD_MONO_HOT_RELOAD
SelfList<ManagedCallable>::List ManagedCallable::instances;
@@ -44,18 +43,16 @@ bool ManagedCallable::compare_equal(const CallableCustom *p_a, const CallableCus
const ManagedCallable *a = static_cast<const ManagedCallable *>(p_a);
const ManagedCallable *b = static_cast<const ManagedCallable *>(p_b);
- MonoDelegate *delegate_a = (MonoDelegate *)a->delegate_handle.get_target();
- MonoDelegate *delegate_b = (MonoDelegate *)b->delegate_handle.get_target();
-
- if (!delegate_a || !delegate_b) {
- if (!delegate_a && !delegate_b) {
+ if (!a->delegate_handle.value || !b->delegate_handle.value) {
+ if (!a->delegate_handle.value && !b->delegate_handle.value) {
return true;
}
return false;
}
// Call Delegate's 'Equals'
- return GDMonoUtils::mono_delegate_equal(delegate_a, delegate_b);
+ return GDMonoCache::managed_callbacks.DelegateUtils_DelegateEquals(
+ a->delegate_handle, b->delegate_handle);
}
bool ManagedCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) {
@@ -66,8 +63,7 @@ bool ManagedCallable::compare_less(const CallableCustom *p_a, const CallableCust
}
uint32_t ManagedCallable::hash() const {
- uint32_t hash = delegate_invoke->get_name().hash();
- return hash_murmur3_one_64(delegate_handle.handle, hash);
+ return hash_murmur3_one_64((uint64_t)delegate_handle.value);
}
String ManagedCallable::get_as_text() const {
@@ -91,41 +87,24 @@ void ManagedCallable::call(const Variant **p_arguments, int p_argcount, Variant
r_call_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; // Can't find anything better
r_return_value = Variant();
-#ifdef GD_MONO_HOT_RELOAD
- // Lost during hot-reload
- ERR_FAIL_NULL(delegate_invoke);
- ERR_FAIL_COND(delegate_handle.is_released());
-#endif
-
- ERR_FAIL_COND(delegate_invoke->get_parameters_count() < p_argcount);
-
- MonoObject *delegate = delegate_handle.get_target();
+ ERR_FAIL_COND(delegate_handle.value == nullptr);
- MonoException *exc = nullptr;
- MonoObject *ret = delegate_invoke->invoke(delegate, p_arguments, &exc);
+ GDMonoCache::managed_callbacks.DelegateUtils_InvokeWithVariantArgs(
+ delegate_handle, p_arguments, p_argcount, &r_return_value);
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- } else {
- r_return_value = GDMonoMarshal::mono_object_to_variant(ret);
- r_call_error.error = Callable::CallError::CALL_OK;
- }
+ r_call_error.error = Callable::CallError::CALL_OK;
}
-void ManagedCallable::set_delegate(MonoDelegate *p_delegate) {
- delegate_handle = MonoGCHandleData::new_strong_handle((MonoObject *)p_delegate);
- MonoMethod *delegate_invoke_raw = mono_get_delegate_invoke(mono_object_get_class((MonoObject *)p_delegate));
- const StringName &delegate_invoke_name = CSharpLanguage::get_singleton()->get_string_names().delegate_invoke_method_name;
- delegate_invoke = memnew(GDMonoMethod(delegate_invoke_name, delegate_invoke_raw)); // TODO: Use pooling for this GDMonoMethod instances
+void ManagedCallable::release_delegate_handle() {
+ if (delegate_handle.value) {
+ GDMonoCache::managed_callbacks.GCHandleBridge_FreeGCHandle(delegate_handle);
+ delegate_handle = { nullptr };
+ }
}
-ManagedCallable::ManagedCallable(MonoDelegate *p_delegate) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_delegate == nullptr);
-#endif
-
- set_delegate(p_delegate);
-
+// Why you do this clang-format...
+/* clang-format off */
+ManagedCallable::ManagedCallable(GCHandleIntPtr p_delegate_handle) : delegate_handle(p_delegate_handle) {
#ifdef GD_MONO_HOT_RELOAD
{
MutexLock lock(instances_mutex);
@@ -133,6 +112,7 @@ ManagedCallable::ManagedCallable(MonoDelegate *p_delegate) {
}
#endif
}
+/* clang-format on */
ManagedCallable::~ManagedCallable() {
#ifdef GD_MONO_HOT_RELOAD
@@ -143,5 +123,5 @@ ManagedCallable::~ManagedCallable() {
}
#endif
- delegate_handle.release();
+ release_delegate_handle();
}
diff --git a/modules/mono/managed_callable.h b/modules/mono/managed_callable.h
index 11bee6cf60..aa3344f4d5 100644
--- a/modules/mono/managed_callable.h
+++ b/modules/mono/managed_callable.h
@@ -31,19 +31,15 @@
#ifndef MANAGED_CALLABLE_H
#define MANAGED_CALLABLE_H
-#include <mono/metadata/object.h>
-
#include "core/os/mutex.h"
#include "core/templates/self_list.h"
#include "core/variant/callable.h"
#include "mono_gc_handle.h"
-#include "mono_gd/gd_mono_method.h"
class ManagedCallable : public CallableCustom {
friend class CSharpLanguage;
- MonoGCHandleData delegate_handle;
- GDMonoMethod *delegate_invoke = nullptr;
+ GCHandleIntPtr delegate_handle;
#ifdef GD_MONO_HOT_RELOAD
SelfList<ManagedCallable> self_instance = this;
@@ -60,9 +56,7 @@ public:
ObjectID get_object() const override;
void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override;
- _FORCE_INLINE_ MonoDelegate *get_delegate() { return (MonoDelegate *)delegate_handle.get_target(); }
-
- void set_delegate(MonoDelegate *p_delegate);
+ _FORCE_INLINE_ GCHandleIntPtr get_delegate() const { return delegate_handle; }
static bool compare_equal(const CallableCustom *p_a, const CallableCustom *p_b);
static bool compare_less(const CallableCustom *p_a, const CallableCustom *p_b);
@@ -70,7 +64,9 @@ public:
static constexpr CompareEqualFunc compare_equal_func_ptr = &ManagedCallable::compare_equal;
static constexpr CompareEqualFunc compare_less_func_ptr = &ManagedCallable::compare_less;
- ManagedCallable(MonoDelegate *p_delegate);
+ void release_delegate_handle();
+
+ ManagedCallable(GCHandleIntPtr p_delegate_handle);
~ManagedCallable();
};
diff --git a/modules/mono/mono_gc_handle.cpp b/modules/mono/mono_gc_handle.cpp
index f3dafa6ecf..9cf0a641b9 100644
--- a/modules/mono/mono_gc_handle.cpp
+++ b/modules/mono/mono_gc_handle.cpp
@@ -31,34 +31,20 @@
#include "mono_gc_handle.h"
#include "mono_gd/gd_mono.h"
+#include "mono_gd/gd_mono_cache.h"
void MonoGCHandleData::release() {
#ifdef DEBUG_ENABLED
- CRASH_COND(handle && GDMono::get_singleton() == nullptr);
+ CRASH_COND(handle.value && GDMono::get_singleton() == nullptr);
#endif
- if (handle && GDMono::get_singleton()->is_runtime_initialized()) {
- GDMonoUtils::free_gchandle(handle);
- handle = 0;
+ if (handle.value && GDMonoCache::godot_api_cache_updated &&
+ GDMono::get_singleton()->is_runtime_initialized()) {
+ free_gchandle(handle);
+ handle.value = nullptr;
}
}
-
-MonoGCHandleData MonoGCHandleData::new_strong_handle(MonoObject *p_object) {
- return MonoGCHandleData(GDMonoUtils::new_strong_gchandle(p_object), gdmono::GCHandleType::STRONG_HANDLE);
-}
-
-MonoGCHandleData MonoGCHandleData::new_strong_handle_pinned(MonoObject *p_object) {
- return MonoGCHandleData(GDMonoUtils::new_strong_gchandle_pinned(p_object), gdmono::GCHandleType::STRONG_HANDLE);
-}
-
-MonoGCHandleData MonoGCHandleData::new_weak_handle(MonoObject *p_object) {
- return MonoGCHandleData(GDMonoUtils::new_weak_gchandle(p_object), gdmono::GCHandleType::WEAK_HANDLE);
-}
-
-Ref<MonoGCHandleRef> MonoGCHandleRef::create_strong(MonoObject *p_object) {
- return memnew(MonoGCHandleRef(MonoGCHandleData::new_strong_handle(p_object)));
-}
-
-Ref<MonoGCHandleRef> MonoGCHandleRef::create_weak(MonoObject *p_object) {
- return memnew(MonoGCHandleRef(MonoGCHandleData::new_weak_handle(p_object)));
+void MonoGCHandleData::free_gchandle(GCHandleIntPtr p_gchandle) {
+ CRASH_COND(!GDMonoCache::godot_api_cache_updated);
+ GDMonoCache::managed_callbacks.GCHandleBridge_FreeGCHandle(p_gchandle);
}
diff --git a/modules/mono/mono_gc_handle.h b/modules/mono/mono_gc_handle.h
index e2aff1d19d..4e4c13fee6 100644
--- a/modules/mono/mono_gc_handle.h
+++ b/modules/mono/mono_gc_handle.h
@@ -31,8 +31,6 @@
#ifndef MONO_GC_HANDLE_H
#define MONO_GC_HANDLE_H
-#include <mono/jit/jit.h>
-
#include "core/object/ref_counted.h"
namespace gdmono {
@@ -44,18 +42,32 @@ enum class GCHandleType : char {
};
}
+extern "C" {
+struct GCHandleIntPtr {
+ void *value;
+
+ _FORCE_INLINE_ bool operator==(const GCHandleIntPtr &p_other) { return value == p_other.value; }
+ _FORCE_INLINE_ bool operator!=(const GCHandleIntPtr &p_other) { return value != p_other.value; }
+
+ GCHandleIntPtr() = delete;
+};
+}
+
+static_assert(sizeof(GCHandleIntPtr) == sizeof(void *));
+
// Manual release of the GC handle must be done when using this struct
struct MonoGCHandleData {
- uint32_t handle = 0;
+ GCHandleIntPtr handle = { nullptr };
gdmono::GCHandleType type = gdmono::GCHandleType::NIL;
- _FORCE_INLINE_ bool is_released() const { return !handle; }
+ _FORCE_INLINE_ bool is_released() const { return !handle.value; }
_FORCE_INLINE_ bool is_weak() const { return type == gdmono::GCHandleType::WEAK_HANDLE; }
-
- _FORCE_INLINE_ MonoObject *get_target() const { return handle ? mono_gchandle_get_target(handle) : nullptr; }
+ _FORCE_INLINE_ GCHandleIntPtr get_intptr() const { return handle; }
void release();
+ static void free_gchandle(GCHandleIntPtr p_gchandle);
+
void operator=(const MonoGCHandleData &p_other) {
#ifdef DEBUG_ENABLED
CRASH_COND(!is_released());
@@ -68,40 +80,10 @@ struct MonoGCHandleData {
MonoGCHandleData() {}
- MonoGCHandleData(uint32_t p_handle, gdmono::GCHandleType p_type) :
+ MonoGCHandleData(GCHandleIntPtr p_handle, gdmono::GCHandleType p_type) :
handle(p_handle),
type(p_type) {
}
-
- static MonoGCHandleData new_strong_handle(MonoObject *p_object);
- static MonoGCHandleData new_strong_handle_pinned(MonoObject *p_object);
- static MonoGCHandleData new_weak_handle(MonoObject *p_object);
-};
-
-class MonoGCHandleRef : public RefCounted {
- GDCLASS(MonoGCHandleRef, RefCounted);
-
- MonoGCHandleData data;
-
-public:
- static Ref<MonoGCHandleRef> create_strong(MonoObject *p_object);
- static Ref<MonoGCHandleRef> create_weak(MonoObject *p_object);
-
- _FORCE_INLINE_ bool is_released() const { return data.is_released(); }
- _FORCE_INLINE_ bool is_weak() const { return data.is_weak(); }
-
- _FORCE_INLINE_ MonoObject *get_target() const { return data.get_target(); }
-
- void release() { data.release(); }
-
- _FORCE_INLINE_ void set_handle(uint32_t p_handle, gdmono::GCHandleType p_handle_type) {
- data = MonoGCHandleData(p_handle, p_handle_type);
- }
-
- MonoGCHandleRef(const MonoGCHandleData &p_gc_handle_data) :
- data(p_gc_handle_data) {
- }
- ~MonoGCHandleRef() { release(); }
};
#endif // MONO_GC_HANDLE_H
diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp
index d3d3bb2bef..0532cc915b 100644
--- a/modules/mono/mono_gd/gd_mono.cpp
+++ b/modules/mono/mono_gd/gd_mono.cpp
@@ -30,13 +30,6 @@
#include "gd_mono.h"
-#include <mono/metadata/environment.h>
-#include <mono/metadata/exception.h>
-#include <mono/metadata/mono-config.h>
-#include <mono/metadata/mono-debug.h>
-#include <mono/metadata/mono-gc.h>
-#include <mono/metadata/profiler.h>
-
#include "core/config/project_settings.h"
#include "core/debugger/engine_debugger.h"
#include "core/io/dir_access.h"
@@ -45,1077 +38,519 @@
#include "core/os/thread.h"
#include "../csharp_script.h"
+#include "../glue/runtime_interop.h"
#include "../godotsharp_dirs.h"
#include "../utils/path_utils.h"
#include "gd_mono_cache.h"
-#include "gd_mono_class.h"
-#include "gd_mono_marshal.h"
-#include "gd_mono_utils.h"
+#ifdef TOOLS_ENABLED
+#include <nethost.h>
+#endif
+
+#include <coreclr_delegates.h>
+#include <hostfxr.h>
+#ifdef UNIX_ENABLED
+#include <dlfcn.h>
+#endif
+
+// TODO mobile
+#if 0
#ifdef ANDROID_ENABLED
-#include "android_mono_config.h"
#include "support/android_support.h"
#elif defined(IOS_ENABLED)
#include "support/ios_support.h"
#endif
-
-#if defined(TOOL_ENABLED) && defined(GD_MONO_SINGLE_APPDOMAIN)
-// This will no longer be the case if we replace appdomains with AssemblyLoadContext
-#error "Editor build requires support for multiple appdomains"
-#endif
-
-#if defined(GD_MONO_HOT_RELOAD) && defined(GD_MONO_SINGLE_APPDOMAIN)
-#error "Hot reloading requires multiple appdomains"
#endif
-// TODO:
-// This has turned into a gigantic mess. There's too much going on here. Too much #ifdef as well.
-// It's just painful to read... It needs to be re-structured. Please, clean this up, future me.
-
GDMono *GDMono::singleton = nullptr;
namespace {
-
-#if defined(JAVASCRIPT_ENABLED)
-extern "C" {
-void mono_wasm_load_runtime(const char *managed_path, int enable_debugging);
-}
-#endif
-
-#if !defined(JAVASCRIPT_ENABLED)
-
-void gd_mono_setup_runtime_main_args() {
- CharString execpath = OS::get_singleton()->get_executable_path().utf8();
-
- List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
-
- List<CharString> cmdline_args_utf8;
- Vector<char *> main_args;
- main_args.resize(cmdline_args.size() + 1);
-
- main_args.write[0] = execpath.ptrw();
-
- int i = 1;
- for (const String &E : cmdline_args) {
- CharString &stored = cmdline_args_utf8.push_back(E.utf8())->get();
- main_args.write[i] = stored.ptrw();
- i++;
- }
-
- mono_runtime_set_main_args(main_args.size(), main_args.ptrw());
-}
-
-void gd_mono_profiler_init() {
- String profiler_args = GLOBAL_DEF("mono/profiler/args", "log:calls,alloc,sample,output=output.mlpd");
- bool profiler_enabled = GLOBAL_DEF("mono/profiler/enabled", false);
- if (profiler_enabled) {
- mono_profiler_load(profiler_args.utf8());
- return;
- }
-
- const String env_var_name = "MONO_ENV_OPTIONS";
- if (OS::get_singleton()->has_environment(env_var_name)) {
- const String mono_env_ops = OS::get_singleton()->get_environment(env_var_name);
- // Usually MONO_ENV_OPTIONS looks like: --profile=jb:prof=timeline,ctl=remote,host=127.0.0.1:55467
- const String prefix = "--profile=";
- if (mono_env_ops.begins_with(prefix)) {
- const String ops = mono_env_ops.substr(prefix.length(), mono_env_ops.length());
- mono_profiler_load(ops.utf8());
- }
- }
-}
-
-void gd_mono_debug_init() {
- CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8();
-
- if (da_args.length()) {
- OS::get_singleton()->set_environment("GODOT_MONO_DEBUGGER_AGENT", String());
- }
-
-#ifdef TOOLS_ENABLED
- int da_port = GLOBAL_DEF("mono/debugger_agent/port", 23685);
- bool da_suspend = GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
- int da_timeout = GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
-
- if (Engine::get_singleton()->is_editor_hint() ||
- ProjectSettings::get_singleton()->get_resource_path().is_empty() ||
- Engine::get_singleton()->is_project_manager_hint()) {
- if (da_args.size() == 0) {
- return;
- }
- }
-
- if (da_args.length() == 0) {
- da_args = String("--debugger-agent=transport=dt_socket,address=127.0.0.1:" + itos(da_port) +
- ",embedding=1,server=y,suspend=" + (da_suspend ? "y,timeout=" + itos(da_timeout) : "n"))
- .utf8();
- }
+hostfxr_initialize_for_dotnet_command_line_fn hostfxr_initialize_for_dotnet_command_line = nullptr;
+hostfxr_initialize_for_runtime_config_fn hostfxr_initialize_for_runtime_config = nullptr;
+hostfxr_get_runtime_delegate_fn hostfxr_get_runtime_delegate = nullptr;
+hostfxr_close_fn hostfxr_close = nullptr;
+
+#ifdef _WIN32
+static_assert(sizeof(char_t) == sizeof(char16_t));
+using HostFxrCharString = Char16String;
+#define HOSTFXR_STR(m_str) L##m_str
#else
- if (da_args.length() == 0) {
- return; // Exported games don't use the project settings to setup the debugger agent
- }
+static_assert(sizeof(char_t) == sizeof(char));
+using HostFxrCharString = CharString;
+#define HOSTFXR_STR(m_str) m_str
#endif
- // Debugging enabled
-
- mono_debug_init(MONO_DEBUG_FORMAT_MONO);
-
- // --debugger-agent=help
- const char *options[] = {
- "--soft-breakpoints",
- da_args.get_data()
- };
- mono_jit_parse_options(2, (char **)options);
-}
-
-#endif // !defined(JAVASCRIPT_ENABLED)
-
-#if defined(JAVASCRIPT_ENABLED)
-MonoDomain *gd_initialize_mono_runtime() {
- const char *vfs_prefix = "managed";
- int enable_debugging = 0;
-
- // TODO: Provide a way to enable debugging on WASM release builds.
-#ifdef DEBUG_ENABLED
- enable_debugging = 1;
+HostFxrCharString str_to_hostfxr(const String &p_str) {
+#ifdef _WIN32
+ return p_str.utf16();
+#else
+ return p_str.utf8();
#endif
-
- mono_wasm_load_runtime(vfs_prefix, enable_debugging);
-
- return mono_get_root_domain();
}
-#else
-MonoDomain *gd_initialize_mono_runtime() {
- gd_mono_debug_init();
-#if defined(IOS_ENABLED) || defined(ANDROID_ENABLED)
- // I don't know whether this actually matters or not
- const char *runtime_version = "mobile";
+#ifdef TOOLS_ENABLED
+String str_from_hostfxr(const char_t *p_buffer) {
+#ifdef _WIN32
+ return String::utf16((const char16_t *)p_buffer);
#else
- const char *runtime_version = "v4.0.30319";
+ return String::utf8((const char *)p_buffer);
#endif
-
- return mono_jit_init_version("GodotEngine.RootDomain", runtime_version);
}
#endif
-} // namespace
-
-void GDMono::add_mono_shared_libs_dir_to_path() {
- // TODO: Replace this with a mono_dl_fallback
-
- // By default Mono seems to search shared libraries in the following directories:
- // Current working directory, @executable_path@ and PATH
- // The parent directory of the image file (assembly where the dllimport method is declared)
- // @executable_path@/../lib
- // @executable_path@/../Libraries (__MACH__ only)
- // This does not work when embedding Mono unless we use the same directory structure.
- // To fix this we append the directory containing our shared libraries to PATH.
-
-#if defined(WINDOWS_ENABLED) || defined(UNIX_ENABLED)
- String path_var("PATH");
- String path_value = OS::get_singleton()->get_environment(path_var);
-
-#ifdef WINDOWS_ENABLED
- path_value += ';';
+const char_t *get_data(const HostFxrCharString &p_char_str) {
+ return (const char_t *)p_char_str.get_data();
+}
- String bundled_bin_dir = GodotSharpDirs::get_data_mono_bin_dir();
#ifdef TOOLS_ENABLED
- if (DirAccess::exists(bundled_bin_dir)) {
- path_value += bundled_bin_dir;
- } else {
- path_value += mono_reg_info.bin_dir;
- }
-#else
- if (DirAccess::exists(bundled_bin_dir)) {
- path_value += bundled_bin_dir;
- }
-#endif // TOOLS_ENABLED
+String find_hostfxr(size_t p_known_buffet_size, get_hostfxr_parameters *p_get_hostfxr_params) {
+ // Pre-allocate a large buffer for the path to hostfxr
+ Vector<char_t> buffer;
+ buffer.resize(p_known_buffet_size);
-#else
- path_value += ':';
+ int rc = get_hostfxr_path(buffer.ptrw(), &p_known_buffet_size, p_get_hostfxr_params);
- String bundled_lib_dir = GodotSharpDirs::get_data_mono_lib_dir();
- if (DirAccess::exists(bundled_lib_dir)) {
- path_value += bundled_lib_dir;
- } else {
- // TODO: Do we need to add the lib dir when using the system installed Mono on Unix platforms?
- }
-#endif // WINDOWS_ENABLED
+ ERR_FAIL_COND_V_MSG(rc != 0, String(), "get_hostfxr_path failed with code: " + itos(rc));
- OS::get_singleton()->set_environment(path_var, path_value);
-#endif // WINDOWS_ENABLED || UNIX_ENABLED
+ return str_from_hostfxr(buffer.ptr());
}
+#endif
-void GDMono::determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir) {
- String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir();
- String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir();
-
+String find_hostfxr() {
#ifdef TOOLS_ENABLED
-
-#if defined(WINDOWS_ENABLED)
- mono_reg_info = MonoRegUtils::find_mono();
-
- if (mono_reg_info.assembly_dir.length() && DirAccess::exists(mono_reg_info.assembly_dir)) {
- r_assembly_rootdir = mono_reg_info.assembly_dir;
- }
-
- if (mono_reg_info.config_dir.length() && DirAccess::exists(mono_reg_info.config_dir)) {
- r_config_dir = mono_reg_info.config_dir;
- }
-#elif defined(MACOS_ENABLED)
- const char *c_assembly_rootdir = mono_assembly_getrootdir();
- const char *c_config_dir = mono_get_config_dir();
-
- if (!c_assembly_rootdir || !c_config_dir || !DirAccess::exists(c_assembly_rootdir) || !DirAccess::exists(c_config_dir)) {
- Vector<const char *> locations;
- locations.push_back("/Library/Frameworks/Mono.framework/Versions/Current/");
- locations.push_back("/usr/local/var/homebrew/linked/mono/");
-
- for (int i = 0; i < locations.size(); i++) {
- String hint_assembly_rootdir = path::join(locations[i], "lib");
- String hint_mscorlib_path = path::join(hint_assembly_rootdir, "mono", "4.5", "mscorlib.dll");
- String hint_config_dir = path::join(locations[i], "etc");
-
- if (FileAccess::exists(hint_mscorlib_path) && DirAccess::exists(hint_config_dir)) {
- r_assembly_rootdir = hint_assembly_rootdir;
- r_config_dir = hint_config_dir;
- break;
+ const int CoreHostLibMissingFailure = 0x80008083;
+ const int HostApiBufferTooSmall = 0x80008098;
+
+ size_t buffer_size = 0;
+ int rc = get_hostfxr_path(nullptr, &buffer_size, nullptr);
+
+ if (rc == HostApiBufferTooSmall) {
+ return find_hostfxr(buffer_size, nullptr);
+ }
+
+ if (rc == CoreHostLibMissingFailure) {
+ // Apparently `get_hostfxr_path` doesn't look for dotnet in `PATH`? (I suppose it needs the
+ // `DOTNET_ROOT` environment variable). If it fails, we try to find the dotnet executable
+ // in `PATH` ourselves and pass its location as `dotnet_root` to `get_hostfxr_path`.
+ String dotnet_exe = path::find_executable("dotnet");
+
+ if (!dotnet_exe.is_empty()) {
+ // The file found in PATH may be a symlink
+ dotnet_exe = path::abspath(path::realpath(dotnet_exe));
+
+ // TODO:
+ // Sometimes, the symlink may not point to the dotnet executable in the dotnet root.
+ // That's the case with snaps. The snap install should have been found with the
+ // previous `get_hostfxr_path`, but it would still be better to do this properly
+ // and use something like `dotnet --list-sdks/runtimes` to find the actual location.
+ // This way we could also check if the proper sdk or runtime is installed. This would
+ // allow us to fail gracefully and show some helpful information in the editor.
+
+ HostFxrCharString dotnet_root = str_to_hostfxr(dotnet_exe.get_base_dir());
+
+ get_hostfxr_parameters get_hostfxr_parameters = {
+ sizeof(get_hostfxr_parameters),
+ nullptr,
+ get_data(dotnet_root)
+ };
+
+ buffer_size = 0;
+ rc = get_hostfxr_path(nullptr, &buffer_size, &get_hostfxr_parameters);
+ if (rc == HostApiBufferTooSmall) {
+ return find_hostfxr(buffer_size, &get_hostfxr_parameters);
}
}
}
-#endif
- if (DirAccess::exists(bundled_assembly_rootdir)) {
- r_assembly_rootdir = bundled_assembly_rootdir;
+ if (rc == CoreHostLibMissingFailure) {
+ ERR_PRINT(String() + ".NET: One of the dependent libraries is missing. " +
+ "Typically when the `hostfxr`, `hostpolicy` or `coreclr` dynamic " +
+ "libraries are not present in the expected locations.");
}
- if (DirAccess::exists(bundled_config_dir)) {
- r_config_dir = bundled_config_dir;
- }
-
-#ifdef WINDOWS_ENABLED
- if (r_assembly_rootdir.is_empty() || r_config_dir.is_empty()) {
- ERR_PRINT("Cannot find Mono in the registry.");
- // Assertion: if they are not set, then they weren't found in the registry
- CRASH_COND(mono_reg_info.assembly_dir.length() > 0 || mono_reg_info.config_dir.length() > 0);
- }
-#endif // WINDOWS_ENABLED
-
+ return String();
#else
- // Export templates always use the bundled directories
- r_assembly_rootdir = bundled_assembly_rootdir;
- r_config_dir = bundled_config_dir;
-#endif
-}
-
-void GDMono::initialize() {
- ERR_FAIL_NULL(Engine::get_singleton());
-
- print_verbose("Mono: Initializing module...");
-
- char *runtime_build_info = mono_get_runtime_build_info();
- print_verbose("Mono JIT compiler version " + String(runtime_build_info));
- mono_free(runtime_build_info);
-
- _init_godot_api_hashes();
- _init_exception_policy();
-
- GDMonoLog::get_singleton()->initialize();
-
-#if !defined(JAVASCRIPT_ENABLED)
- String assembly_rootdir;
- String config_dir;
- determine_mono_dirs(assembly_rootdir, config_dir);
-
- // Leak if we call mono_set_dirs more than once
- mono_set_dirs(assembly_rootdir.length() ? assembly_rootdir.utf8().get_data() : nullptr,
- config_dir.length() ? config_dir.utf8().get_data() : nullptr);
- add_mono_shared_libs_dir_to_path();
-#endif
-
-#ifdef ANDROID_ENABLED
- mono_config_parse_memory(get_godot_android_mono_config().utf8().get_data());
+#if defined(WINDOWS_ENABLED)
+ String probe_path = GodotSharpDirs::get_api_assemblies_dir()
+ .plus_file("hostfxr.dll");
+#elif defined(MACOS_ENABLED)
+ String probe_path = GodotSharpDirs::get_api_assemblies_dir()
+ .plus_file("libhostfxr.dylib");
+#elif defined(UNIX_ENABLED)
+ String probe_path = GodotSharpDirs::get_api_assemblies_dir()
+ .plus_file("libhostfxr.so");
#else
- mono_config_parse(nullptr);
+#error "Platform not supported (yet?)"
#endif
-#if defined(ANDROID_ENABLED)
- gdmono::android::support::initialize();
-#elif defined(IOS_ENABLED)
- gdmono::ios::support::initialize();
-#endif
+ if (FileAccess::exists(probe_path)) {
+ return probe_path;
+ }
- GDMonoAssembly::initialize();
+ return String();
-#if !defined(JAVASCRIPT_ENABLED)
- gd_mono_profiler_init();
#endif
+}
- mono_install_unhandled_exception_hook(&unhandled_exception_hook, nullptr);
-
-#ifndef TOOLS_ENABLED
- // Exported games that don't use C# must still work. They likely don't ship with mscorlib.
- // We only initialize the Mono runtime if we can find mscorlib. Otherwise it would crash.
- if (GDMonoAssembly::find_assembly("mscorlib.dll").is_empty()) {
- print_verbose("Mono: Skipping runtime initialization because 'mscorlib.dll' could not be found");
- return;
- }
-#endif
+bool load_hostfxr(void *&r_hostfxr_dll_handle) {
+ String hostfxr_path = find_hostfxr();
-#if !defined(NO_MONO_THREADS_SUSPEND_WORKAROUND)
- // FIXME: Temporary workaround. See: https://github.com/godotengine/godot/issues/29812
- if (!OS::get_singleton()->has_environment("MONO_THREADS_SUSPEND")) {
- OS::get_singleton()->set_environment("MONO_THREADS_SUSPEND", "preemptive");
+ if (hostfxr_path.is_empty()) {
+ return false;
}
-#endif
- // NOTE: Internal calls must be registered after the Mono runtime initialization.
- // Otherwise registration fails with the error: 'assertion 'hash != nullptr' failed'.
+ print_verbose("Found hostfxr: " + hostfxr_path);
- root_domain = gd_initialize_mono_runtime();
- ERR_FAIL_NULL_MSG(root_domain, "Mono: Failed to initialize runtime.");
+ Error err = OS::get_singleton()->open_dynamic_library(hostfxr_path, r_hostfxr_dll_handle);
- GDMonoUtils::set_main_thread(GDMonoUtils::get_current_thread());
-
-#if !defined(JAVASCRIPT_ENABLED)
- gd_mono_setup_runtime_main_args(); // Required for System.Environment.GetCommandLineArgs
-#endif
+ if (err != OK) {
+ return false;
+ }
- runtime_initialized = true;
+ void *lib = r_hostfxr_dll_handle;
- print_verbose("Mono: Runtime initialized");
+ void *symbol = nullptr;
-#if defined(ANDROID_ENABLED)
- gdmono::android::support::register_internal_calls();
-#endif
+ err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_initialize_for_dotnet_command_line", symbol);
+ ERR_FAIL_COND_V(err != OK, false);
+ hostfxr_initialize_for_dotnet_command_line = (hostfxr_initialize_for_dotnet_command_line_fn)symbol;
- // mscorlib assembly MUST be present at initialization
- bool corlib_loaded = _load_corlib_assembly();
- ERR_FAIL_COND_MSG(!corlib_loaded, "Mono: Failed to load mscorlib assembly.");
+ err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_initialize_for_runtime_config", symbol);
+ ERR_FAIL_COND_V(err != OK, false);
+ hostfxr_initialize_for_runtime_config = (hostfxr_initialize_for_runtime_config_fn)symbol;
-#ifndef GD_MONO_SINGLE_APPDOMAIN
- Error domain_load_err = _load_scripts_domain();
- ERR_FAIL_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain.");
-#else
- scripts_domain = root_domain;
-#endif
+ err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_get_runtime_delegate", symbol);
+ ERR_FAIL_COND_V(err != OK, false);
+ hostfxr_get_runtime_delegate = (hostfxr_get_runtime_delegate_fn)symbol;
- _register_internal_calls();
+ err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_close", symbol);
+ ERR_FAIL_COND_V(err != OK, false);
+ hostfxr_close = (hostfxr_close_fn)symbol;
- print_verbose("Mono: INITIALIZED");
+ return (hostfxr_initialize_for_runtime_config &&
+ hostfxr_get_runtime_delegate &&
+ hostfxr_close);
}
-void GDMono::initialize_load_assemblies() {
-#ifndef MONO_GLUE_ENABLED
- CRASH_NOW_MSG("Mono: This binary was built with 'mono_glue=no'; cannot load assemblies.");
-#endif
-
- // Load assemblies. The API and tools assemblies are required,
- // the application is aborted if these assemblies cannot be loaded.
-
- _load_api_assemblies();
-
-#if defined(TOOLS_ENABLED)
- bool tool_assemblies_loaded = _load_tools_assemblies();
- CRASH_COND_MSG(!tool_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies.");
-
- if (Engine::get_singleton()->is_project_manager_hint()) {
- return;
- }
-#endif
-
- // Load the project's main assembly. This doesn't necessarily need to succeed.
- // The game may not be using .NET at all, or if the project does use .NET and
- // we're running in the editor, it may just happen to be it wasn't built yet.
- if (!_load_project_assembly()) {
- if (OS::get_singleton()->is_stdout_verbose()) {
- print_error("Mono: Failed to load project assembly");
- }
- }
-}
-
-bool GDMono::_are_api_assemblies_out_of_sync() {
- bool out_of_sync = core_api_assembly.assembly && (core_api_assembly.out_of_sync || !GDMonoCache::cached_data.godot_api_cache_updated);
#ifdef TOOLS_ENABLED
- if (!out_of_sync) {
- out_of_sync = editor_api_assembly.assembly && editor_api_assembly.out_of_sync;
+load_assembly_and_get_function_pointer_fn initialize_hostfxr_for_config(const char_t *p_config_path) {
+ hostfxr_handle cxt = nullptr;
+ int rc = hostfxr_initialize_for_runtime_config(p_config_path, nullptr, &cxt);
+ if (rc != 0 || cxt == nullptr) {
+ hostfxr_close(cxt);
+ ERR_FAIL_V_MSG(nullptr, "hostfxr_initialize_for_runtime_config failed with code: " + itos(rc));
}
-#endif
- return out_of_sync;
-}
-namespace GodotSharpBindings {
-#ifdef MONO_GLUE_ENABLED
+ void *load_assembly_and_get_function_pointer = nullptr;
-uint64_t get_core_api_hash();
-#ifdef TOOLS_ENABLED
-uint64_t get_editor_api_hash();
-#endif
-uint32_t get_bindings_version();
-uint32_t get_cs_glue_version();
-
-void register_generated_icalls();
+ rc = hostfxr_get_runtime_delegate(cxt,
+ hdt_load_assembly_and_get_function_pointer, &load_assembly_and_get_function_pointer);
+ if (rc != 0 || load_assembly_and_get_function_pointer == nullptr) {
+ ERR_FAIL_V_MSG(nullptr, "hostfxr_get_runtime_delegate failed with code: " + itos(rc));
+ }
-#else
+ hostfxr_close(cxt);
-uint64_t get_core_api_hash() {
- GD_UNREACHABLE();
-}
-#ifdef TOOLS_ENABLED
-uint64_t get_editor_api_hash() {
- GD_UNREACHABLE();
-}
-#endif
-uint32_t get_bindings_version() {
- GD_UNREACHABLE();
-}
-
-uint32_t get_cs_glue_version() {
- GD_UNREACHABLE();
+ return (load_assembly_and_get_function_pointer_fn)load_assembly_and_get_function_pointer;
}
+#else
+load_assembly_and_get_function_pointer_fn initialize_hostfxr_self_contained(
+ const char_t *p_main_assembly_path) {
+ hostfxr_handle cxt = nullptr;
-void register_generated_icalls() {
- /* Fine, just do nothing */
-}
+ List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
-#endif // MONO_GLUE_ENABLED
-} // namespace GodotSharpBindings
+ List<HostFxrCharString> argv_store;
+ Vector<const char_t *> argv;
+ argv.resize(cmdline_args.size() + 1);
-void GDMono::_register_internal_calls() {
- GodotSharpBindings::register_generated_icalls();
-}
+ argv.write[0] = p_main_assembly_path;
-void GDMono::_init_godot_api_hashes() {
-#if defined(MONO_GLUE_ENABLED) && defined(DEBUG_METHODS_ENABLED)
- if (get_api_core_hash() != GodotSharpBindings::get_core_api_hash()) {
- ERR_PRINT("Mono: Core API hash mismatch.");
+ int i = 1;
+ for (const String &E : cmdline_args) {
+ HostFxrCharString &stored = argv_store.push_back(str_to_hostfxr(E))->get();
+ argv.write[i] = stored.ptr();
+ i++;
}
-#ifdef TOOLS_ENABLED
- if (get_api_editor_hash() != GodotSharpBindings::get_editor_api_hash()) {
- ERR_PRINT("Mono: Editor API hash mismatch.");
+ int rc = hostfxr_initialize_for_dotnet_command_line(argv.size(), argv.ptrw(), nullptr, &cxt);
+ if (rc != 0 || cxt == nullptr) {
+ hostfxr_close(cxt);
+ ERR_FAIL_V_MSG(nullptr, "hostfxr_initialize_for_dotnet_command_line failed with code: " + itos(rc));
}
-#endif // TOOLS_ENABLED
-#endif // MONO_GLUE_ENABLED && DEBUG_METHODS_ENABLED
-}
-void GDMono::_init_exception_policy() {
- PropertyInfo exc_policy_prop = PropertyInfo(Variant::INT, "mono/runtime/unhandled_exception_policy", PROPERTY_HINT_ENUM,
- vformat("Terminate Application:%s,Log Error:%s", (int)POLICY_TERMINATE_APP, (int)POLICY_LOG_ERROR));
- unhandled_exception_policy = (UnhandledExceptionPolicy)(int)GLOBAL_DEF(exc_policy_prop.name, (int)POLICY_TERMINATE_APP);
- ProjectSettings::get_singleton()->set_custom_property_info(exc_policy_prop.name, exc_policy_prop);
+ void *load_assembly_and_get_function_pointer = nullptr;
- if (Engine::get_singleton()->is_editor_hint()) {
- // Unhandled exceptions should not terminate the editor
- unhandled_exception_policy = POLICY_LOG_ERROR;
+ rc = hostfxr_get_runtime_delegate(cxt,
+ hdt_load_assembly_and_get_function_pointer, &load_assembly_and_get_function_pointer);
+ if (rc != 0 || load_assembly_and_get_function_pointer == nullptr) {
+ ERR_FAIL_V_MSG(nullptr, "hostfxr_get_runtime_delegate failed with code: " + itos(rc));
}
-}
-
-void GDMono::add_assembly(int32_t p_domain_id, GDMonoAssembly *p_assembly) {
- assemblies[p_domain_id][p_assembly->get_name()] = p_assembly;
-}
-GDMonoAssembly *GDMono::get_loaded_assembly(const String &p_name) {
- if (p_name == "mscorlib" && corlib_assembly) {
- return corlib_assembly;
- }
+ hostfxr_close(cxt);
- MonoDomain *domain = mono_domain_get();
- int32_t domain_id = domain ? mono_domain_get_id(domain) : 0;
- GDMonoAssembly **result = assemblies[domain_id].getptr(p_name);
- return result ? *result : nullptr;
+ return (load_assembly_and_get_function_pointer_fn)load_assembly_and_get_function_pointer;
}
-
-bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(!r_assembly);
#endif
- MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
- bool result = load_assembly(p_name, aname, r_assembly, p_refonly);
- mono_assembly_name_free(aname);
- mono_free(aname);
-
- return result;
-}
-
-bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(!r_assembly);
+#ifdef TOOLS_ENABLED
+using godot_plugins_initialize_fn = bool (*)(void *, bool, gdmono::PluginCallbacks *, GDMonoCache::ManagedCallbacks *, const void **, int32_t);
+#else
+using godot_plugins_initialize_fn = bool (*)(void *, GDMonoCache::ManagedCallbacks *, const void **, int32_t);
#endif
- return load_assembly(p_name, p_aname, r_assembly, p_refonly, GDMonoAssembly::get_default_search_dirs());
-}
+#ifdef TOOLS_ENABLED
+godot_plugins_initialize_fn initialize_hostfxr_and_godot_plugins(bool &r_runtime_initialized) {
+ godot_plugins_initialize_fn godot_plugins_initialize = nullptr;
-bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly, const Vector<String> &p_search_dirs) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(!r_assembly);
-#endif
+ HostFxrCharString godot_plugins_path = str_to_hostfxr(
+ GodotSharpDirs::get_api_assemblies_dir().plus_file("GodotPlugins.dll"));
- print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
+ HostFxrCharString config_path = str_to_hostfxr(
+ GodotSharpDirs::get_api_assemblies_dir().plus_file("GodotPlugins.runtimeconfig.json"));
- GDMonoAssembly *assembly = GDMonoAssembly::load(p_name, p_aname, p_refonly, p_search_dirs);
+ load_assembly_and_get_function_pointer_fn load_assembly_and_get_function_pointer =
+ initialize_hostfxr_for_config(get_data(config_path));
+ ERR_FAIL_NULL_V(load_assembly_and_get_function_pointer, nullptr);
- if (!assembly) {
- return false;
- }
+ r_runtime_initialized = true;
- *r_assembly = assembly;
+ print_verbose(".NET: hostfxr initialized");
- print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path());
+ int rc = load_assembly_and_get_function_pointer(get_data(godot_plugins_path),
+ HOSTFXR_STR("GodotPlugins.Main, GodotPlugins"),
+ HOSTFXR_STR("InitializeFromEngine"),
+ UNMANAGEDCALLERSONLY_METHOD,
+ nullptr,
+ (void **)&godot_plugins_initialize);
+ ERR_FAIL_COND_V_MSG(rc != 0, nullptr, ".NET: Failed to get GodotPlugins initialization function pointer");
- return true;
+ return godot_plugins_initialize;
}
+#else
+static String get_assembly_name() {
+ String assembly_name = ProjectSettings::get_singleton()->get_setting("dotnet/project/assembly_name");
-bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly) {
- CRASH_COND(!r_assembly);
-
- print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
-
- GDMonoAssembly *assembly = GDMonoAssembly::load_from(p_name, p_path, p_refonly);
-
- if (!assembly) {
- return false;
+ if (assembly_name.is_empty()) {
+ assembly_name = ProjectSettings::get_singleton()->get_safe_project_name();
}
- *r_assembly = assembly;
-
- print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path());
-
- return true;
+ return assembly_name;
}
-ApiAssemblyInfo::Version ApiAssemblyInfo::Version::get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, ApiAssemblyInfo::Type p_api_type) {
- ApiAssemblyInfo::Version api_assembly_version;
+godot_plugins_initialize_fn initialize_hostfxr_and_godot_plugins(bool &r_runtime_initialized) {
+ godot_plugins_initialize_fn godot_plugins_initialize = nullptr;
- const char *nativecalls_name = p_api_type == ApiAssemblyInfo::API_CORE
- ? BINDINGS_CLASS_NATIVECALLS
- : BINDINGS_CLASS_NATIVECALLS_EDITOR;
+ String assembly_name = get_assembly_name();
- GDMonoClass *nativecalls_klass = p_api_assembly->get_class(BINDINGS_NAMESPACE, nativecalls_name);
+ HostFxrCharString assembly_path = str_to_hostfxr(GodotSharpDirs::get_api_assemblies_dir()
+ .plus_file(assembly_name + ".dll"));
- if (nativecalls_klass) {
- GDMonoField *api_hash_field = nativecalls_klass->get_field("godot_api_hash");
- if (api_hash_field) {
- api_assembly_version.godot_api_hash = GDMonoMarshal::unbox<uint64_t>(api_hash_field->get_value(nullptr));
- }
+ load_assembly_and_get_function_pointer_fn load_assembly_and_get_function_pointer =
+ initialize_hostfxr_self_contained(get_data(assembly_path));
+ ERR_FAIL_NULL_V(load_assembly_and_get_function_pointer, nullptr);
- GDMonoField *binds_ver_field = nativecalls_klass->get_field("bindings_version");
- if (binds_ver_field) {
- api_assembly_version.bindings_version = GDMonoMarshal::unbox<uint32_t>(binds_ver_field->get_value(nullptr));
- }
+ r_runtime_initialized = true;
- GDMonoField *cs_glue_ver_field = nativecalls_klass->get_field("cs_glue_version");
- if (cs_glue_ver_field) {
- api_assembly_version.cs_glue_version = GDMonoMarshal::unbox<uint32_t>(cs_glue_ver_field->get_value(nullptr));
- }
- }
+ print_verbose(".NET: hostfxr initialized");
- return api_assembly_version;
-}
+ int rc = load_assembly_and_get_function_pointer(get_data(assembly_path),
+ str_to_hostfxr("GodotPlugins.Game.Main, " + assembly_name),
+ HOSTFXR_STR("InitializeFromGameProject"),
+ UNMANAGEDCALLERSONLY_METHOD,
+ nullptr,
+ (void **)&godot_plugins_initialize);
+ ERR_FAIL_COND_V_MSG(rc != 0, nullptr, ".NET: Failed to get GodotPlugins initialization function pointer");
-String ApiAssemblyInfo::to_string(ApiAssemblyInfo::Type p_type) {
- return p_type == ApiAssemblyInfo::API_CORE ? "API_CORE" : "API_EDITOR";
+ return godot_plugins_initialize;
}
-bool GDMono::_load_corlib_assembly() {
- if (corlib_assembly) {
- return true;
- }
-
- bool success = load_assembly("mscorlib", &corlib_assembly);
-
- if (success) {
- GDMonoCache::update_corlib_cache();
- }
-
- return success;
-}
+godot_plugins_initialize_fn try_load_native_aot_library(void *&r_aot_dll_handle) {
+ String assembly_name = get_assembly_name();
-#ifdef TOOLS_ENABLED
-bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config) {
- String src_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
- String dst_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config);
-
- String assembly_name = p_api_type == ApiAssemblyInfo::API_CORE ? CORE_API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME;
+#if defined(WINDOWS_ENABLED)
+ String native_aot_so_path = GodotSharpDirs::get_api_assemblies_dir().plus_file(assembly_name + ".dll");
+#elif defined(MACOS_ENABLED)
+ String native_aot_so_path = GodotSharpDirs::get_api_assemblies_dir().plus_file(assembly_name + ".dylib");
+#elif defined(UNIX_ENABLED)
+ String native_aot_so_path = GodotSharpDirs::get_api_assemblies_dir().plus_file(assembly_name + ".so");
+#else
+#error "Platform not supported (yet?)"
+#endif
- // Create destination directory if needed
- if (!DirAccess::exists(dst_dir)) {
- Ref<DirAccess> da = DirAccess::create_for_path(dst_dir);
- Error err = da->make_dir_recursive(dst_dir);
+ if (FileAccess::exists(native_aot_so_path)) {
+ Error err = OS::get_singleton()->open_dynamic_library(native_aot_so_path, r_aot_dll_handle);
if (err != OK) {
- ERR_PRINT("Failed to create destination directory for the API assemblies. Error: " + itos(err) + ".");
- return false;
+ return nullptr;
}
- }
- Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
+ void *lib = r_aot_dll_handle;
- String xml_file = assembly_name + ".xml";
- if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK) {
- WARN_PRINT("Failed to copy '" + xml_file + "'.");
- }
+ void *symbol = nullptr;
- String pdb_file = assembly_name + ".pdb";
- if (da->copy(src_dir.plus_file(pdb_file), dst_dir.plus_file(pdb_file)) != OK) {
- WARN_PRINT("Failed to copy '" + pdb_file + "'.");
+ err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "godotsharp_game_main_init", symbol);
+ ERR_FAIL_COND_V(err != OK, nullptr);
+ return (godot_plugins_initialize_fn)symbol;
}
- String assembly_file = assembly_name + ".dll";
- if (da->copy(src_dir.plus_file(assembly_file), dst_dir.plus_file(assembly_file)) != OK) {
- ERR_PRINT("Failed to copy '" + assembly_file + "'.");
- return false;
- }
-
- return true;
+ return nullptr;
}
+#endif
-static bool try_get_cached_api_hash_for(const String &p_api_assemblies_dir, bool &r_out_of_sync) {
- String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
- String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
-
- if (!FileAccess::exists(core_api_assembly_path) || !FileAccess::exists(editor_api_assembly_path)) {
- return false;
- }
-
- String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg");
+} // namespace
- if (!FileAccess::exists(cached_api_hash_path)) {
+static bool _on_core_api_assembly_loaded() {
+ if (!GDMonoCache::godot_api_cache_updated) {
return false;
}
- Ref<ConfigFile> cfg;
- cfg.instantiate();
- Error cfg_err = cfg->load(cached_api_hash_path);
- ERR_FAIL_COND_V(cfg_err != OK, false);
-
- // Checking the modified time is good enough
- if (FileAccess::get_modified_time(core_api_assembly_path) != (uint64_t)cfg->get_value("core", "modified_time") ||
- FileAccess::get_modified_time(editor_api_assembly_path) != (uint64_t)cfg->get_value("editor", "modified_time")) {
- return false;
- }
+ bool debug;
+#ifdef DEBUG_ENABLED
+ debug = true;
+#else
+ debug = false;
+#endif
- r_out_of_sync = GodotSharpBindings::get_bindings_version() != (uint32_t)cfg->get_value("core", "bindings_version") ||
- GodotSharpBindings::get_cs_glue_version() != (uint32_t)cfg->get_value("core", "cs_glue_version") ||
- GodotSharpBindings::get_bindings_version() != (uint32_t)cfg->get_value("editor", "bindings_version") ||
- GodotSharpBindings::get_cs_glue_version() != (uint32_t)cfg->get_value("editor", "cs_glue_version") ||
- GodotSharpBindings::get_core_api_hash() != (uint64_t)cfg->get_value("core", "api_hash") ||
- GodotSharpBindings::get_editor_api_hash() != (uint64_t)cfg->get_value("editor", "api_hash");
+ GDMonoCache::managed_callbacks.GD_OnCoreApiAssemblyLoaded(debug);
return true;
}
-static void create_cached_api_hash_for(const String &p_api_assemblies_dir) {
- String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
- String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
- String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg");
-
- Ref<ConfigFile> cfg;
- cfg.instantiate();
-
- cfg->set_value("core", "modified_time", FileAccess::get_modified_time(core_api_assembly_path));
- cfg->set_value("editor", "modified_time", FileAccess::get_modified_time(editor_api_assembly_path));
-
- cfg->set_value("core", "bindings_version", GodotSharpBindings::get_bindings_version());
- cfg->set_value("core", "cs_glue_version", GodotSharpBindings::get_cs_glue_version());
- cfg->set_value("editor", "bindings_version", GodotSharpBindings::get_bindings_version());
- cfg->set_value("editor", "cs_glue_version", GodotSharpBindings::get_cs_glue_version());
-
- // This assumes the prebuilt api assemblies we copied to the project are not out of sync
- cfg->set_value("core", "api_hash", GodotSharpBindings::get_core_api_hash());
- cfg->set_value("editor", "api_hash", GodotSharpBindings::get_editor_api_hash());
-
- Error err = cfg->save(cached_api_hash_path);
- ERR_FAIL_COND(err != OK);
-}
-
-bool GDMono::_temp_domain_load_are_assemblies_out_of_sync(const String &p_config) {
- MonoDomain *temp_domain = GDMonoUtils::create_domain("GodotEngine.Domain.CheckApiAssemblies");
- ERR_FAIL_NULL_V(temp_domain, "Failed to create temporary domain to check API assemblies");
- _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(temp_domain);
-
- _GDMONO_SCOPE_DOMAIN_(temp_domain);
-
- GDMono::LoadedApiAssembly temp_core_api_assembly;
- GDMono::LoadedApiAssembly temp_editor_api_assembly;
-
- if (!_try_load_api_assemblies(temp_core_api_assembly, temp_editor_api_assembly,
- p_config, /* refonly: */ true, /* loaded_callback: */ nullptr)) {
- return temp_core_api_assembly.out_of_sync || temp_editor_api_assembly.out_of_sync;
- }
-
- return true; // Failed to load, assume they're outdated assemblies
-}
-
-String GDMono::update_api_assemblies_from_prebuilt(const String &p_config, const bool *p_core_api_out_of_sync, const bool *p_editor_api_out_of_sync) {
-#define FAIL_REASON(m_out_of_sync, m_prebuilt_exists) \
- ( \
- (m_out_of_sync ? String("The assembly is invalidated ") : String("The assembly was not found ")) + \
- (m_prebuilt_exists ? String("and the prebuilt assemblies are missing.") : String("and we failed to copy the prebuilt assemblies.")))
+void GDMono::initialize() {
+ print_verbose(".NET: Initializing module...");
- String dst_assemblies_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config);
+ _init_godot_api_hashes();
- String core_assembly_path = dst_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
- String editor_assembly_path = dst_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
+ godot_plugins_initialize_fn godot_plugins_initialize = nullptr;
- bool api_assemblies_out_of_sync = false;
+ if (!load_hostfxr(hostfxr_dll_handle)) {
+#if !defined(TOOLS_ENABLED)
+ godot_plugins_initialize = try_load_native_aot_library(hostfxr_dll_handle);
- if (p_core_api_out_of_sync && p_editor_api_out_of_sync) {
- api_assemblies_out_of_sync = p_core_api_out_of_sync || p_editor_api_out_of_sync;
- } else if (FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) {
- // Determine if they're out of sync
- if (!try_get_cached_api_hash_for(dst_assemblies_dir, api_assemblies_out_of_sync)) {
- api_assemblies_out_of_sync = _temp_domain_load_are_assemblies_out_of_sync(p_config);
+ if (godot_plugins_initialize != nullptr) {
+ is_native_aot = true;
+ } else {
+ ERR_FAIL_MSG(".NET: Failed to load hostfxr");
}
+#else
+ ERR_FAIL_MSG(".NET: Failed to load hostfxr");
+#endif
}
- // Note: Even if only one of the assemblies if missing or out of sync, we update both
-
- if (!api_assemblies_out_of_sync && FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) {
- return String(); // No update needed
- }
-
- print_verbose("Updating '" + p_config + "' API assemblies");
-
- String prebuilt_api_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
- String prebuilt_core_dll_path = prebuilt_api_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
- String prebuilt_editor_dll_path = prebuilt_api_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
-
- if (!FileAccess::exists(prebuilt_core_dll_path) || !FileAccess::exists(prebuilt_editor_dll_path)) {
- return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ false);
+ if (!is_native_aot) {
+ godot_plugins_initialize = initialize_hostfxr_and_godot_plugins(runtime_initialized);
+ ERR_FAIL_NULL(godot_plugins_initialize);
}
- // Copy the prebuilt Api
- if (!copy_prebuilt_api_assembly(ApiAssemblyInfo::API_CORE, p_config) ||
- !copy_prebuilt_api_assembly(ApiAssemblyInfo::API_EDITOR, p_config)) {
- return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ true);
- }
+ int32_t interop_funcs_size = 0;
+ const void **interop_funcs = godotsharp::get_runtime_interop_funcs(interop_funcs_size);
- // Cache the api hash of the assemblies we just copied
- create_cached_api_hash_for(dst_assemblies_dir);
+ GDMonoCache::ManagedCallbacks managed_callbacks{};
- return String(); // Updated successfully
+ void *godot_dll_handle = nullptr;
-#undef FAIL_REASON
-}
+#if defined(UNIX_ENABLED) && !defined(MACOS_ENABLED) && !defined(IOS_ENABLED)
+ // Managed code can access it on its own on other platforms
+ godot_dll_handle = dlopen(nullptr, RTLD_NOW);
#endif
-bool GDMono::_load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) {
- if (r_loaded_api_assembly.assembly) {
- return true;
- }
-
#ifdef TOOLS_ENABLED
- // For the editor and the editor player we want to load it from a specific path to make sure we can keep it up to date
-
- // If running the project manager, load it from the prebuilt API directory
- String assembly_dir = !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);
-
- String assembly_path = assembly_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
-
- bool success = FileAccess::exists(assembly_path) &&
- load_assembly_from(CORE_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly);
+ gdmono::PluginCallbacks plugin_callbacks_res;
+ bool init_ok = godot_plugins_initialize(godot_dll_handle,
+ Engine::get_singleton()->is_editor_hint(),
+ &plugin_callbacks_res, &managed_callbacks,
+ interop_funcs, interop_funcs_size);
+ ERR_FAIL_COND_MSG(!init_ok, ".NET: GodotPlugins initialization failed");
+
+ plugin_callbacks = plugin_callbacks_res;
#else
- bool success = load_assembly(CORE_API_ASSEMBLY_NAME, &r_loaded_api_assembly.assembly, p_refonly);
+ bool init_ok = godot_plugins_initialize(godot_dll_handle, &managed_callbacks,
+ interop_funcs, interop_funcs_size);
+ ERR_FAIL_COND_MSG(!init_ok, ".NET: GodotPlugins initialization failed");
#endif
- if (success) {
- ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_CORE);
- r_loaded_api_assembly.out_of_sync = GodotSharpBindings::get_core_api_hash() != api_assembly_ver.godot_api_hash ||
- GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
- GodotSharpBindings::get_cs_glue_version() != api_assembly_ver.cs_glue_version;
- } else {
- r_loaded_api_assembly.out_of_sync = false;
- }
+ GDMonoCache::update_godot_api_cache(managed_callbacks);
- return success;
-}
+ print_verbose(".NET: GodotPlugins initialized");
-#ifdef TOOLS_ENABLED
-bool GDMono::_load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) {
- if (r_loaded_api_assembly.assembly) {
- return true;
- }
-
- // 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 = !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);
-
- String assembly_path = assembly_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
-
- bool success = FileAccess::exists(assembly_path) &&
- load_assembly_from(EDITOR_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly);
-
- if (success) {
- ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_EDITOR);
- r_loaded_api_assembly.out_of_sync = GodotSharpBindings::get_editor_api_hash() != api_assembly_ver.godot_api_hash ||
- GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
- GodotSharpBindings::get_cs_glue_version() != api_assembly_ver.cs_glue_version;
- } else {
- r_loaded_api_assembly.out_of_sync = false;
- }
-
- return success;
+ _on_core_api_assembly_loaded();
}
-#endif
-bool GDMono::_try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly,
- const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback) {
- if (!_load_core_api_assembly(r_core_api_assembly, p_config, p_refonly)) {
- if (OS::get_singleton()->is_stdout_verbose()) {
- print_error("Mono: Failed to load Core API assembly");
- }
- return false;
+#ifdef TOOLS_ENABLED
+void GDMono::initialize_load_assemblies() {
+ if (Engine::get_singleton()->is_project_manager_hint()) {
+ return;
}
-#ifdef TOOLS_ENABLED
- if (!_load_editor_api_assembly(r_editor_api_assembly, p_config, p_refonly)) {
+ // Load the project's main assembly. This doesn't necessarily need to succeed.
+ // The game may not be using .NET at all, or if the project does use .NET and
+ // we're running in the editor, it may just happen to be it wasn't built yet.
+ if (!_load_project_assembly()) {
if (OS::get_singleton()->is_stdout_verbose()) {
- print_error("Mono: Failed to load Editor API assembly");
+ print_error(".NET: Failed to load project assembly");
}
- return false;
}
-
- if (r_editor_api_assembly.out_of_sync) {
- return false;
- }
-#endif
-
- // Check if the core API assembly is out of sync only after trying to load the
- // editor API assembly. Otherwise, if both assemblies are out of sync, we would
- // only update the former as we won't know the latter also needs to be updated.
- if (r_core_api_assembly.out_of_sync) {
- return false;
- }
-
- if (p_callback) {
- return p_callback();
- }
-
- return true;
}
-
-bool GDMono::_on_core_api_assembly_loaded() {
- GDMonoCache::update_godot_api_cache();
-
- if (!GDMonoCache::cached_data.godot_api_cache_updated) {
- return false;
- }
-
- get_singleton()->_install_trace_listener();
-
- return true;
-}
-
-bool GDMono::_try_load_api_assemblies_preset() {
- return _try_load_api_assemblies(core_api_assembly, editor_api_assembly,
- get_expected_api_build_config(), /* refonly: */ false, _on_core_api_assembly_loaded);
-}
-
-void GDMono::_load_api_assemblies() {
- bool api_assemblies_loaded = _try_load_api_assemblies_preset();
-
-#if defined(TOOLS_ENABLED) && !defined(GD_MONO_SINGLE_APPDOMAIN)
- if (!api_assemblies_loaded) {
- // The API assemblies are out of sync or some other error happened. Fine, try one more time, but
- // this time update them from the prebuilt assemblies directory before trying to load them again.
-
- // Shouldn't happen. The project manager loads 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();
- CRASH_COND_MSG(domain_unload_err != OK, "Mono: Failed to unload scripts domain.");
-
- // 2. Update the API assemblies
- String update_error = update_api_assemblies_from_prebuilt("Debug", &core_api_assembly.out_of_sync, &editor_api_assembly.out_of_sync);
- CRASH_COND_MSG(!update_error.is_empty(), update_error);
-
- // 3. Load the scripts domain again
- Error domain_load_err = _load_scripts_domain();
- CRASH_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain.");
-
- // 4. Try loading the updated assemblies
- api_assemblies_loaded = _try_load_api_assemblies_preset();
- }
#endif
- if (!api_assemblies_loaded) {
- // welp... too bad
-
- if (_are_api_assemblies_out_of_sync()) {
- if (core_api_assembly.out_of_sync) {
- ERR_PRINT("The assembly '" CORE_API_ASSEMBLY_NAME "' is out of sync.");
- } else if (!GDMonoCache::cached_data.godot_api_cache_updated) {
- ERR_PRINT("The loaded assembly '" CORE_API_ASSEMBLY_NAME "' is in sync, but the cache update failed.");
- }
+void GDMono::_init_godot_api_hashes() {
+#ifdef DEBUG_METHODS_ENABLED
+ get_api_core_hash();
#ifdef TOOLS_ENABLED
- if (editor_api_assembly.out_of_sync) {
- ERR_PRINT("The assembly '" EDITOR_API_ASSEMBLY_NAME "' is out of sync.");
- }
-#endif
-
- CRASH_NOW();
- } else {
- CRASH_NOW_MSG("Failed to load one of the API assemblies.");
- }
- }
+ get_api_editor_hash();
+#endif // TOOLS_ENABLED
+#endif // DEBUG_METHODS_ENABLED
}
#ifdef TOOLS_ENABLED
-bool GDMono::_load_tools_assemblies() {
- if (tools_assembly && tools_project_editor_assembly) {
- return true;
- }
-
- bool success = load_assembly(TOOLS_ASM_NAME, &tools_assembly) &&
- load_assembly(TOOLS_PROJECT_EDITOR_ASM_NAME, &tools_project_editor_assembly);
-
- return success;
-}
-#endif
-
bool GDMono::_load_project_assembly() {
- if (project_assembly) {
- return true;
- }
-
- String appname = ProjectSettings::get_singleton()->get("application/config/name");
- String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
- if (appname_safe.is_empty()) {
- appname_safe = "UnnamedProject";
- }
-
- bool success = load_assembly(appname_safe, &project_assembly);
-
- if (success) {
- mono_assembly_set_main(project_assembly->get_assembly());
- CSharpLanguage::get_singleton()->lookup_scripts_in_assembly(project_assembly);
- }
-
- return success;
-}
+ String assembly_name = ProjectSettings::get_singleton()->get_setting("dotnet/project/assembly_name");
-void GDMono::_install_trace_listener() {
-#ifdef DEBUG_ENABLED
- // Install the trace listener now before the project assembly is loaded
- GDMonoClass *debug_utils = get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, "DebuggingUtils");
- GDMonoMethod *install_func = debug_utils->get_method("InstallTraceListener");
-
- MonoException *exc = nullptr;
- install_func->invoke_raw(nullptr, nullptr, &exc);
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_PRINT("Failed to install 'System.Diagnostics.Trace' listener.");
+ if (assembly_name.is_empty()) {
+ assembly_name = ProjectSettings::get_singleton()->get_safe_project_name();
}
-#endif
-}
-
-#ifndef GD_MONO_SINGLE_APPDOMAIN
-Error GDMono::_load_scripts_domain() {
- ERR_FAIL_COND_V(scripts_domain != nullptr, ERR_BUG);
-
- print_verbose("Mono: Loading scripts domain...");
-
- scripts_domain = GDMonoUtils::create_domain("GodotEngine.Domain.Scripts");
- ERR_FAIL_NULL_V_MSG(scripts_domain, ERR_CANT_CREATE, "Mono: Could not create scripts app domain.");
-
- mono_domain_set(scripts_domain, true);
-
- return OK;
-}
-
-Error GDMono::_unload_scripts_domain() {
- ERR_FAIL_NULL_V(scripts_domain, ERR_BUG);
-
- print_verbose("Mono: Finalizing scripts domain...");
-
- if (mono_domain_get() != root_domain) {
- mono_domain_set(root_domain, true);
- }
+ String assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir()
+ .plus_file(assembly_name + ".dll");
+ assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
- finalizing_scripts_domain = true;
-
- if (!mono_domain_finalize(scripts_domain, 2000)) {
- ERR_PRINT("Mono: Domain finalization timeout.");
+ if (!FileAccess::exists(assembly_path)) {
+ return false;
}
- finalizing_scripts_domain = false;
-
- mono_gc_collect(mono_gc_max_generation());
-
- GDMonoCache::clear_godot_api_cache();
-
- _domain_assemblies_cleanup(mono_domain_get_id(scripts_domain));
-
- core_api_assembly.assembly = nullptr;
-#ifdef TOOLS_ENABLED
- editor_api_assembly.assembly = nullptr;
-#endif
-
- project_assembly = nullptr;
-#ifdef TOOLS_ENABLED
- tools_assembly = nullptr;
- tools_project_editor_assembly = nullptr;
-#endif
-
- MonoDomain *domain = scripts_domain;
- scripts_domain = nullptr;
-
- print_verbose("Mono: Unloading scripts domain...");
+ String loaded_assembly_path;
+ bool success = plugin_callbacks.LoadProjectAssemblyCallback(assembly_path.utf16(), &loaded_assembly_path);
- MonoException *exc = nullptr;
- mono_domain_try_unload(domain, (MonoObject **)&exc);
-
- if (exc) {
- ERR_PRINT("Exception thrown when unloading scripts domain.");
- GDMonoUtils::debug_unhandled_exception(exc);
- return FAILED;
+ if (success) {
+ project_assembly_path = loaded_assembly_path.simplify_path();
+ project_assembly_modified_time = FileAccess::get_modified_time(loaded_assembly_path);
}
- return OK;
+ return success;
}
#endif
#ifdef GD_MONO_HOT_RELOAD
-Error GDMono::reload_scripts_domain() {
+Error GDMono::reload_project_assemblies() {
ERR_FAIL_COND_V(!runtime_initialized, ERR_BUG);
- if (scripts_domain) {
- Error domain_unload_err = _unload_scripts_domain();
- ERR_FAIL_COND_V_MSG(domain_unload_err != OK, domain_unload_err, "Mono: Failed to unload scripts domain.");
- }
-
- CSharpLanguage::get_singleton()->_on_scripts_domain_unloaded();
-
- Error domain_load_err = _load_scripts_domain();
- ERR_FAIL_COND_V_MSG(domain_load_err != OK, domain_load_err, "Mono: Failed to load scripts domain.");
+ finalizing_scripts_domain = true;
- // Load assemblies. The API and tools assemblies are required,
- // the application is aborted if these assemblies cannot be loaded.
+ CSharpLanguage::get_singleton()->_on_scripts_domain_about_to_unload();
- _load_api_assemblies();
+ if (!get_plugin_callbacks().UnloadProjectPluginCallback()) {
+ ERR_FAIL_V_MSG(Error::FAILED, ".NET: Failed to unload assemblies.");
+ }
-#if defined(TOOLS_ENABLED)
- bool tools_assemblies_loaded = _load_tools_assemblies();
- CRASH_COND_MSG(!tools_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies.");
-#endif
+ finalizing_scripts_domain = false;
// Load the project's main assembly. Here, during hot-reloading, we do
// consider failing to load the project's main assembly to be an error.
- // However, unlike the API and tools assemblies, the application can continue working.
if (!_load_project_assembly()) {
- print_error("Mono: Failed to load project assembly");
+ print_error(".NET: Failed to load project assembly.");
return ERR_CANT_OPEN;
}
@@ -1123,204 +558,38 @@ Error GDMono::reload_scripts_domain() {
}
#endif
-#ifndef GD_MONO_SINGLE_APPDOMAIN
-Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
- CRASH_COND(p_domain == nullptr);
- CRASH_COND(p_domain == GDMono::get_singleton()->get_scripts_domain()); // Should use _unload_scripts_domain() instead
-
- String domain_name = mono_domain_get_friendly_name(p_domain);
-
- print_verbose("Mono: Unloading domain '" + domain_name + "'...");
-
- if (mono_domain_get() == p_domain) {
- mono_domain_set(root_domain, true);
- }
-
- if (!mono_domain_finalize(p_domain, 2000)) {
- ERR_PRINT("Mono: Domain finalization timeout.");
- }
-
- mono_gc_collect(mono_gc_max_generation());
-
- _domain_assemblies_cleanup(mono_domain_get_id(p_domain));
-
- MonoException *exc = nullptr;
- mono_domain_try_unload(p_domain, (MonoObject **)&exc);
-
- if (exc) {
- ERR_PRINT("Exception thrown when unloading domain '" + domain_name + "'.");
- GDMonoUtils::debug_print_unhandled_exception(exc);
- return FAILED;
- }
-
- return OK;
-}
-#endif
-
-GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
- MonoImage *image = mono_class_get_image(p_raw_class);
-
- if (image == corlib_assembly->get_image()) {
- return corlib_assembly->get_class(p_raw_class);
- }
-
- int32_t domain_id = mono_domain_get_id(mono_domain_get());
- HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
-
- for (const KeyValue<String, GDMonoAssembly *> &E : domain_assemblies) {
- GDMonoAssembly *assembly = E.value;
- if (assembly->get_image() == image) {
- GDMonoClass *klass = assembly->get_class(p_raw_class);
- if (klass) {
- return klass;
- }
- }
- }
-
- return nullptr;
-}
-
-GDMonoClass *GDMono::get_class(const StringName &p_namespace, const StringName &p_name) {
- GDMonoClass *klass = corlib_assembly->get_class(p_namespace, p_name);
- if (klass) {
- return klass;
- }
-
- int32_t domain_id = mono_domain_get_id(mono_domain_get());
- HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
-
- for (const KeyValue<String, GDMonoAssembly *> &E : domain_assemblies) {
- GDMonoAssembly *assembly = E.value;
- klass = assembly->get_class(p_namespace, p_name);
- if (klass) {
- return klass;
- }
- }
-
- return nullptr;
-}
-
-void GDMono::_domain_assemblies_cleanup(int32_t p_domain_id) {
- HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id];
-
- for (const KeyValue<String, GDMonoAssembly *> &E : domain_assemblies) {
- memdelete(E.value);
- }
-
- assemblies.erase(p_domain_id);
-}
-
-void GDMono::unhandled_exception_hook(MonoObject *p_exc, void *) {
- // This method will be called by the runtime when a thrown exception is not handled.
- // It won't be called when we manually treat a thrown exception as unhandled.
- // We assume the exception was already printed before calling this hook.
-
-#ifdef DEBUG_ENABLED
- GDMonoUtils::debug_send_unhandled_exception_error((MonoException *)p_exc);
- if (EngineDebugger::is_active()) {
- EngineDebugger::get_singleton()->poll_events(false);
- }
-#endif
-
- exit(mono_environment_exitcode_get());
-
- GD_UNREACHABLE();
-}
-
GDMono::GDMono() {
singleton = this;
- gdmono_log = memnew(GDMonoLog);
-
runtime_initialized = false;
finalizing_scripts_domain = false;
- root_domain = nullptr;
- scripts_domain = nullptr;
-
- corlib_assembly = nullptr;
- project_assembly = nullptr;
-#ifdef TOOLS_ENABLED
- tools_assembly = nullptr;
- tools_project_editor_assembly = nullptr;
-#endif
-
api_core_hash = 0;
#ifdef TOOLS_ENABLED
api_editor_hash = 0;
#endif
-
- unhandled_exception_policy = POLICY_TERMINATE_APP;
}
GDMono::~GDMono() {
- if (is_runtime_initialized()) {
-#ifndef GD_MONO_SINGLE_APPDOMAIN
- if (scripts_domain) {
- Error err = _unload_scripts_domain();
- if (err != OK) {
- ERR_PRINT("Mono: Failed to unload scripts domain.");
- }
- }
-#else
- CRASH_COND(scripts_domain != root_domain);
-
- print_verbose("Mono: Finalizing scripts domain...");
-
- if (mono_domain_get() != root_domain) {
- mono_domain_set(root_domain, true);
- }
-
- finalizing_scripts_domain = true;
-
- if (!mono_domain_finalize(root_domain, 2000)) {
- ERR_PRINT("Mono: Domain finalization timeout.");
- }
-
- finalizing_scripts_domain = false;
-
- mono_gc_collect(mono_gc_max_generation());
-
- GDMonoCache::clear_godot_api_cache();
-
- _domain_assemblies_cleanup(mono_domain_get_id(root_domain));
-
- core_api_assembly.assembly = nullptr;
-
- project_assembly = nullptr;
-
- root_domain = nullptr;
- scripts_domain = nullptr;
-
- // Leave the rest to 'mono_jit_cleanup'
-#endif
-
- for (const KeyValue<int32_t, HashMap<String, GDMonoAssembly *>> &E : assemblies) {
- const HashMap<String, GDMonoAssembly *> &domain_assemblies = E.value;
+ finalizing_scripts_domain = true;
- for (const KeyValue<String, GDMonoAssembly *> &F : domain_assemblies) {
- memdelete(F.value);
- }
+ if (is_runtime_initialized()) {
+ if (GDMonoCache::godot_api_cache_updated) {
+ GDMonoCache::managed_callbacks.DisposablesTracker_OnGodotShuttingDown();
}
- assemblies.clear();
-
- print_verbose("Mono: Runtime cleanup...");
-
- mono_jit_cleanup(root_domain);
-
- print_verbose("Mono: Finalized");
+ }
- runtime_initialized = false;
+ if (hostfxr_dll_handle) {
+ OS::get_singleton()->close_dynamic_library(hostfxr_dll_handle);
}
+ finalizing_scripts_domain = false;
+ runtime_initialized = false;
+
#if defined(ANDROID_ENABLED)
gdmono::android::support::cleanup();
#endif
- if (gdmono_log) {
- memdelete(gdmono_log);
- }
-
singleton = nullptr;
}
@@ -1328,62 +597,7 @@ namespace mono_bind {
GodotSharp *GodotSharp::singleton = nullptr;
-void GodotSharp::attach_thread() {
- GDMonoUtils::attach_current_thread();
-}
-
-void GodotSharp::detach_thread() {
- GDMonoUtils::detach_current_thread();
-}
-
-int32_t GodotSharp::get_domain_id() {
- MonoDomain *domain = mono_domain_get();
- ERR_FAIL_NULL_V(domain, -1);
- return mono_domain_get_id(domain);
-}
-
-int32_t GodotSharp::get_scripts_domain_id() {
- ERR_FAIL_NULL_V_MSG(GDMono::get_singleton(),
- -1, "The Mono runtime is not initialized");
- MonoDomain *domain = GDMono::get_singleton()->get_scripts_domain();
- ERR_FAIL_NULL_V(domain, -1);
- return mono_domain_get_id(domain);
-}
-
-bool GodotSharp::is_scripts_domain_loaded() {
- return GDMono::get_singleton() != nullptr &&
- GDMono::get_singleton()->is_runtime_initialized() &&
- GDMono::get_singleton()->get_scripts_domain() != nullptr;
-}
-
-bool GodotSharp::_is_domain_finalizing_for_unload(int32_t p_domain_id) {
- return is_domain_finalizing_for_unload(p_domain_id);
-}
-
-bool GodotSharp::is_domain_finalizing_for_unload(int32_t p_domain_id) {
- return is_domain_finalizing_for_unload(mono_domain_get_by_id(p_domain_id));
-}
-
-bool GodotSharp::is_domain_finalizing_for_unload(MonoDomain *p_domain) {
- GDMono *gd_mono = GDMono::get_singleton();
-
- ERR_FAIL_COND_V_MSG(!gd_mono || !gd_mono->is_runtime_initialized(),
- false, "The Mono runtime is not initialized");
-
- ERR_FAIL_NULL_V(p_domain, true);
-
- if (p_domain == gd_mono->get_scripts_domain() && gd_mono->is_finalizing_scripts_domain()) {
- return true;
- }
-
- return mono_domain_is_unloading(p_domain);
-}
-
-bool GodotSharp::is_runtime_shutting_down() {
- return mono_runtime_is_shutting_down();
-}
-
-bool GodotSharp::is_runtime_initialized() {
+bool GodotSharp::_is_runtime_initialized() {
return GDMono::get_singleton() != nullptr && GDMono::get_singleton()->is_runtime_initialized();
}
@@ -1399,16 +613,7 @@ void GodotSharp::_reload_assemblies(bool p_soft_reload) {
}
void GodotSharp::_bind_methods() {
- ClassDB::bind_method(D_METHOD("attach_thread"), &GodotSharp::attach_thread);
- ClassDB::bind_method(D_METHOD("detach_thread"), &GodotSharp::detach_thread);
-
- ClassDB::bind_method(D_METHOD("get_domain_id"), &GodotSharp::get_domain_id);
- ClassDB::bind_method(D_METHOD("get_scripts_domain_id"), &GodotSharp::get_scripts_domain_id);
- ClassDB::bind_method(D_METHOD("is_scripts_domain_loaded"), &GodotSharp::is_scripts_domain_loaded);
- ClassDB::bind_method(D_METHOD("is_domain_finalizing_for_unload", "domain_id"), &GodotSharp::_is_domain_finalizing_for_unload);
-
- ClassDB::bind_method(D_METHOD("is_runtime_shutting_down"), &GodotSharp::is_runtime_shutting_down);
- ClassDB::bind_method(D_METHOD("is_runtime_initialized"), &GodotSharp::is_runtime_initialized);
+ ClassDB::bind_method(D_METHOD("is_runtime_initialized"), &GodotSharp::_is_runtime_initialized);
ClassDB::bind_method(D_METHOD("_reload_assemblies"), &GodotSharp::_reload_assemblies);
}
diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h
index 51fd0f8483..43811a4325 100644
--- a/modules/mono/mono_gd/gd_mono.h
+++ b/modules/mono/mono_gd/gd_mono.h
@@ -34,131 +34,54 @@
#include "core/io/config_file.h"
#include "../godotsharp_defs.h"
-#include "gd_mono_assembly.h"
-#include "gd_mono_log.h"
-#ifdef WINDOWS_ENABLED
-#include "../utils/mono_reg_utils.h"
+#ifdef WIN32
+#define GD_CLR_STDCALL __stdcall
+#else
+#define GD_CLR_STDCALL
#endif
-namespace ApiAssemblyInfo {
-enum Type {
- API_CORE,
- API_EDITOR
-};
-
-struct Version {
- uint64_t godot_api_hash = 0;
- uint32_t bindings_version = 0;
- uint32_t cs_glue_version = 0;
-
- bool operator==(const Version &p_other) const {
- return godot_api_hash == p_other.godot_api_hash &&
- bindings_version == p_other.bindings_version &&
- cs_glue_version == p_other.cs_glue_version;
- }
-
- Version() {}
-
- Version(uint64_t p_godot_api_hash,
- uint32_t p_bindings_version,
- uint32_t p_cs_glue_version) :
- godot_api_hash(p_godot_api_hash),
- bindings_version(p_bindings_version),
- cs_glue_version(p_cs_glue_version) {
- }
+namespace gdmono {
- static Version get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, Type p_api_type);
+#ifdef TOOLS_ENABLED
+struct PluginCallbacks {
+ using FuncLoadProjectAssemblyCallback = bool(GD_CLR_STDCALL *)(const char16_t *, String *);
+ using FuncLoadToolsAssemblyCallback = Object *(GD_CLR_STDCALL *)(const char16_t *, const void **, int32_t);
+ using FuncUnloadProjectPluginCallback = bool(GD_CLR_STDCALL *)();
+ FuncLoadProjectAssemblyCallback LoadProjectAssemblyCallback = nullptr;
+ FuncLoadToolsAssemblyCallback LoadToolsAssemblyCallback = nullptr;
+ FuncUnloadProjectPluginCallback UnloadProjectPluginCallback = nullptr;
};
+#endif
-String to_string(Type p_type);
-} // namespace ApiAssemblyInfo
-
-class GDMono {
-public:
- enum UnhandledExceptionPolicy {
- POLICY_TERMINATE_APP,
- POLICY_LOG_ERROR
- };
-
- struct LoadedApiAssembly {
- GDMonoAssembly *assembly = nullptr;
- bool out_of_sync = false;
+} // namespace gdmono
- LoadedApiAssembly() {}
- };
+#undef GD_CLR_STDCALL
-private:
+class GDMono {
bool runtime_initialized;
bool finalizing_scripts_domain;
- UnhandledExceptionPolicy unhandled_exception_policy;
+ void *hostfxr_dll_handle = nullptr;
+ bool is_native_aot = false;
- MonoDomain *root_domain = nullptr;
- MonoDomain *scripts_domain = nullptr;
+ String project_assembly_path;
+ uint64_t project_assembly_modified_time = 0;
- HashMap<int32_t, HashMap<String, GDMonoAssembly *>> assemblies;
-
- GDMonoAssembly *corlib_assembly = nullptr;
- GDMonoAssembly *project_assembly = nullptr;
#ifdef TOOLS_ENABLED
- GDMonoAssembly *tools_assembly = nullptr;
- GDMonoAssembly *tools_project_editor_assembly = nullptr;
-#endif
-
- LoadedApiAssembly core_api_assembly;
- LoadedApiAssembly editor_api_assembly;
-
- typedef bool (*CoreApiAssemblyLoadedCallback)();
-
- bool _are_api_assemblies_out_of_sync();
- bool _temp_domain_load_are_assemblies_out_of_sync(const String &p_config);
-
- bool _load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly);
-#ifdef TOOLS_ENABLED
- bool _load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly);
-#endif
-
- static bool _on_core_api_assembly_loaded();
-
- bool _load_corlib_assembly();
-#ifdef TOOLS_ENABLED
- bool _load_tools_assemblies();
-#endif
bool _load_project_assembly();
-
- bool _try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly,
- const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback);
- bool _try_load_api_assemblies_preset();
- void _load_api_assemblies();
-
- void _install_trace_listener();
-
- void _register_internal_calls();
-
-#ifndef GD_MONO_SINGLE_APPDOMAIN
- Error _load_scripts_domain();
- Error _unload_scripts_domain();
#endif
- void _domain_assemblies_cleanup(int32_t p_domain_id);
-
uint64_t api_core_hash;
#ifdef TOOLS_ENABLED
uint64_t api_editor_hash;
#endif
void _init_godot_api_hashes();
- void _init_exception_policy();
-
- GDMonoLog *gdmono_log = nullptr;
-#if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED)
- MonoRegInfo mono_reg_info;
+#ifdef TOOLS_ENABLED
+ gdmono::PluginCallbacks plugin_callbacks;
#endif
- void add_mono_shared_libs_dir_to_path();
- void determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir);
-
protected:
static GDMono *singleton;
@@ -192,107 +115,43 @@ public:
#endif
}
-#ifdef TOOLS_ENABLED
- bool copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config);
- String update_api_assemblies_from_prebuilt(const String &p_config, const bool *p_core_api_out_of_sync = nullptr, const bool *p_editor_api_out_of_sync = nullptr);
-#endif
-
- static GDMono *get_singleton() { return singleton; }
-
- [[noreturn]] static void unhandled_exception_hook(MonoObject *p_exc, void *p_user_data);
-
- UnhandledExceptionPolicy get_unhandled_exception_policy() const { return unhandled_exception_policy; }
-
- // Do not use these, unless you know what you're doing
- void add_assembly(int32_t p_domain_id, GDMonoAssembly *p_assembly);
- GDMonoAssembly *get_loaded_assembly(const String &p_name);
-
- _FORCE_INLINE_ bool is_runtime_initialized() const { return runtime_initialized && !mono_runtime_is_shutting_down() /* stays true after shutdown finished */; }
+ static GDMono *get_singleton() {
+ return singleton;
+ }
- _FORCE_INLINE_ bool is_finalizing_scripts_domain() { return finalizing_scripts_domain; }
+ _FORCE_INLINE_ bool is_runtime_initialized() const {
+ return runtime_initialized;
+ }
+ _FORCE_INLINE_ bool is_finalizing_scripts_domain() {
+ return finalizing_scripts_domain;
+ }
- _FORCE_INLINE_ MonoDomain *get_scripts_domain() { return scripts_domain; }
+ _FORCE_INLINE_ const String &get_project_assembly_path() const {
+ return project_assembly_path;
+ }
+ _FORCE_INLINE_ uint64_t get_project_assembly_modified_time() const {
+ return project_assembly_modified_time;
+ }
- _FORCE_INLINE_ GDMonoAssembly *get_corlib_assembly() const { return corlib_assembly; }
- _FORCE_INLINE_ GDMonoAssembly *get_core_api_assembly() const { return core_api_assembly.assembly; }
- _FORCE_INLINE_ GDMonoAssembly *get_project_assembly() const { return project_assembly; }
#ifdef TOOLS_ENABLED
- _FORCE_INLINE_ GDMonoAssembly *get_editor_api_assembly() const { return editor_api_assembly.assembly; }
- _FORCE_INLINE_ GDMonoAssembly *get_tools_assembly() const { return tools_assembly; }
- _FORCE_INLINE_ GDMonoAssembly *get_tools_project_editor_assembly() const { return tools_project_editor_assembly; }
-#endif
-
-#if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED)
- const MonoRegInfo &get_mono_reg_info() { return mono_reg_info; }
+ const gdmono::PluginCallbacks &get_plugin_callbacks() {
+ return plugin_callbacks;
+ }
#endif
- GDMonoClass *get_class(MonoClass *p_raw_class);
- GDMonoClass *get_class(const StringName &p_namespace, const StringName &p_name);
-
#ifdef GD_MONO_HOT_RELOAD
- Error reload_scripts_domain();
+ Error reload_project_assemblies();
#endif
- bool load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly = false);
- bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly = false);
- bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly, const Vector<String> &p_search_dirs);
- bool load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly = false);
-
- Error finalize_and_unload_domain(MonoDomain *p_domain);
-
void initialize();
+#ifdef TOOLS_ENABLED
void initialize_load_assemblies();
+#endif
GDMono();
~GDMono();
};
-namespace gdmono {
-
-class ScopeDomain {
- MonoDomain *prev_domain = nullptr;
-
-public:
- ScopeDomain(MonoDomain *p_domain) {
- prev_domain = mono_domain_get();
- if (prev_domain != p_domain) {
- mono_domain_set(p_domain, false);
- } else {
- prev_domain = nullptr;
- }
- }
-
- ~ScopeDomain() {
- if (prev_domain) {
- mono_domain_set(prev_domain, false);
- }
- }
-};
-
-class ScopeExitDomainUnload {
- MonoDomain *domain = nullptr;
-
-public:
- ScopeExitDomainUnload(MonoDomain *p_domain) :
- domain(p_domain) {
- }
-
- ~ScopeExitDomainUnload() {
- if (domain) {
- GDMono::get_singleton()->finalize_and_unload_domain(domain);
- }
- }
-};
-} // namespace gdmono
-
-#define _GDMONO_SCOPE_DOMAIN_(m_mono_domain) \
- gdmono::ScopeDomain __gdmono__scope__domain__(m_mono_domain); \
- (void)__gdmono__scope__domain__;
-
-#define _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(m_mono_domain) \
- gdmono::ScopeExitDomainUnload __gdmono__scope__exit__domain__unload__(m_mono_domain); \
- (void)__gdmono__scope__exit__domain__unload__;
-
namespace mono_bind {
class GodotSharp : public Object {
@@ -300,9 +159,8 @@ class GodotSharp : public Object {
friend class GDMono;
- bool _is_domain_finalizing_for_unload(int32_t p_domain_id);
-
void _reload_assemblies(bool p_soft_reload);
+ bool _is_runtime_initialized();
protected:
static GodotSharp *singleton;
@@ -311,20 +169,6 @@ protected:
public:
static GodotSharp *get_singleton() { return singleton; }
- void attach_thread();
- void detach_thread();
-
- int32_t get_domain_id();
- int32_t get_scripts_domain_id();
-
- bool is_scripts_domain_loaded();
-
- bool is_domain_finalizing_for_unload(int32_t p_domain_id);
- bool is_domain_finalizing_for_unload(MonoDomain *p_domain);
-
- bool is_runtime_shutting_down();
- bool is_runtime_initialized();
-
GodotSharp();
~GodotSharp();
};
diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp
deleted file mode 100644
index 42c6b6305f..0000000000
--- a/modules/mono/mono_gd/gd_mono_assembly.cpp
+++ /dev/null
@@ -1,482 +0,0 @@
-/*************************************************************************/
-/* gd_mono_assembly.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 "gd_mono_assembly.h"
-
-#include <mono/metadata/mono-debug.h>
-#include <mono/metadata/tokentype.h>
-
-#include "core/config/project_settings.h"
-#include "core/io/file_access.h"
-#include "core/io/file_access_pack.h"
-#include "core/os/os.h"
-#include "core/templates/list.h"
-
-#include "../godotsharp_dirs.h"
-#include "gd_mono_cache.h"
-#include "gd_mono_class.h"
-
-Vector<String> GDMonoAssembly::search_dirs;
-
-void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config, const String &p_custom_bcl_dir) {
- String framework_dir;
-
- if (!p_custom_bcl_dir.is_empty()) {
- framework_dir = p_custom_bcl_dir;
- } else if (mono_assembly_getrootdir()) {
- framework_dir = String::utf8(mono_assembly_getrootdir()).plus_file("mono").plus_file("4.5");
- }
-
- if (!framework_dir.is_empty()) {
- r_search_dirs.push_back(framework_dir);
- r_search_dirs.push_back(framework_dir.plus_file("Facades"));
- }
-
-#if !defined(TOOLS_ENABLED)
- String data_game_assemblies_dir = GodotSharpDirs::get_data_game_assemblies_dir();
- if (!data_game_assemblies_dir.is_empty()) {
- r_search_dirs.push_back(data_game_assemblies_dir);
- }
-#endif
-
- if (p_custom_config.length()) {
- r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_base_dir().plus_file(p_custom_config));
- } else {
- r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_dir());
- }
-
- if (p_custom_config.is_empty()) {
- r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir());
- } else {
- String api_config = p_custom_config == "ExportRelease" ? "Release" : "Debug";
- r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir().plus_file(api_config));
- }
-
- r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir());
- r_search_dirs.push_back(OS::get_singleton()->get_resource_dir());
- r_search_dirs.push_back(OS::get_singleton()->get_executable_path().get_base_dir());
-
-#ifdef TOOLS_ENABLED
- r_search_dirs.push_back(GodotSharpDirs::get_data_editor_tools_dir());
-
- // For GodotTools to find the api assemblies
- r_search_dirs.push_back(GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file("Debug"));
-#endif
-}
-
-// This is how these assembly loading hooks work:
-//
-// - The 'search' hook checks if the assembly has already been loaded, to avoid loading again.
-// - The 'preload' hook does the actual loading and is only called if the
-// 'search' hook didn't find the assembly in the list of loaded assemblies.
-// - The 'load' hook is called after the assembly has been loaded. Its job is to add the
-// assembly to the list of loaded assemblies so that the 'search' hook can look it up.
-
-void GDMonoAssembly::assembly_load_hook(MonoAssembly *assembly, [[maybe_unused]] void *user_data) {
- String name = String::utf8(mono_assembly_name_get_name(mono_assembly_get_name(assembly)));
-
- MonoImage *image = mono_assembly_get_image(assembly);
-
- GDMonoAssembly *gdassembly = memnew(GDMonoAssembly(name, image, assembly));
-
-#ifdef GD_MONO_HOT_RELOAD
- String path = String::utf8(mono_image_get_filename(image));
- if (FileAccess::exists(path)) {
- gdassembly->modified_time = FileAccess::get_modified_time(path);
- }
-#endif
-
- MonoDomain *domain = mono_domain_get();
- GDMono::get_singleton()->add_assembly(domain ? mono_domain_get_id(domain) : 0, gdassembly);
-}
-
-MonoAssembly *GDMonoAssembly::assembly_search_hook(MonoAssemblyName *aname, void *user_data) {
- return GDMonoAssembly::_search_hook(aname, user_data, false);
-}
-
-MonoAssembly *GDMonoAssembly::assembly_refonly_search_hook(MonoAssemblyName *aname, void *user_data) {
- return GDMonoAssembly::_search_hook(aname, user_data, true);
-}
-
-MonoAssembly *GDMonoAssembly::assembly_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data) {
- return GDMonoAssembly::_preload_hook(aname, assemblies_path, user_data, false);
-}
-
-MonoAssembly *GDMonoAssembly::assembly_refonly_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data) {
- return GDMonoAssembly::_preload_hook(aname, assemblies_path, user_data, true);
-}
-
-MonoAssembly *GDMonoAssembly::_search_hook(MonoAssemblyName *aname, [[maybe_unused]] void *user_data, bool refonly) {
- String name = String::utf8(mono_assembly_name_get_name(aname));
- bool has_extension = name.ends_with(".dll") || name.ends_with(".exe");
-
- GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(has_extension ? name.get_basename() : name);
- if (loaded_asm) {
- return loaded_asm->get_assembly();
- }
-
- return nullptr;
-}
-
-MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **, [[maybe_unused]] void *user_data, bool refonly) {
- String name = String::utf8(mono_assembly_name_get_name(aname));
- return _load_assembly_search(name, aname, refonly, search_dirs);
-}
-
-MonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs) {
- MonoAssembly *res = nullptr;
- String path;
-
- bool has_extension = p_name.ends_with(".dll") || p_name.ends_with(".exe");
-
- for (int i = 0; i < p_search_dirs.size(); i++) {
- const String &search_dir = p_search_dirs[i];
-
- if (has_extension) {
- path = search_dir.plus_file(p_name);
- if (FileAccess::exists(path)) {
- res = _real_load_assembly_from(path, p_refonly, p_aname);
- if (res != nullptr) {
- return res;
- }
- }
- } else {
- path = search_dir.plus_file(p_name + ".dll");
- if (FileAccess::exists(path)) {
- res = _real_load_assembly_from(path, p_refonly, p_aname);
- if (res != nullptr) {
- return res;
- }
- }
-
- path = search_dir.plus_file(p_name + ".exe");
- if (FileAccess::exists(path)) {
- res = _real_load_assembly_from(path, p_refonly, p_aname);
- if (res != nullptr) {
- return res;
- }
- }
- }
- }
-
- return nullptr;
-}
-
-String GDMonoAssembly::find_assembly(const String &p_name) {
- String path;
-
- bool has_extension = p_name.ends_with(".dll") || p_name.ends_with(".exe");
-
- for (int i = 0; i < search_dirs.size(); i++) {
- const String &search_dir = search_dirs[i];
-
- if (has_extension) {
- path = search_dir.plus_file(p_name);
- if (FileAccess::exists(path)) {
- return path;
- }
- } else {
- path = search_dir.plus_file(p_name + ".dll");
- if (FileAccess::exists(path)) {
- return path;
- }
-
- path = search_dir.plus_file(p_name + ".exe");
- if (FileAccess::exists(path)) {
- return path;
- }
- }
- }
-
- return String();
-}
-
-void GDMonoAssembly::initialize() {
- fill_search_dirs(search_dirs);
-
- mono_install_assembly_search_hook(&assembly_search_hook, nullptr);
- mono_install_assembly_refonly_search_hook(&assembly_refonly_search_hook, nullptr);
- mono_install_assembly_preload_hook(&assembly_preload_hook, nullptr);
- mono_install_assembly_refonly_preload_hook(&assembly_refonly_preload_hook, nullptr);
- mono_install_assembly_load_hook(&assembly_load_hook, nullptr);
-}
-
-MonoAssembly *GDMonoAssembly::_real_load_assembly_from(const String &p_path, bool p_refonly, MonoAssemblyName *p_aname) {
- Vector<uint8_t> data = FileAccess::get_file_as_array(p_path);
- ERR_FAIL_COND_V_MSG(data.is_empty(), nullptr, "Could read the assembly in the specified location");
-
- String image_filename;
-
-#ifdef ANDROID_ENABLED
- if (p_path.begins_with("res://")) {
- image_filename = p_path.substr(6, p_path.length());
- } else {
- image_filename = ProjectSettings::get_singleton()->globalize_path(p_path);
- }
-#else
- // FIXME: globalize_path does not work on exported games
- image_filename = ProjectSettings::get_singleton()->globalize_path(p_path);
-#endif
-
- MonoImageOpenStatus status = MONO_IMAGE_OK;
-
- MonoImage *image = mono_image_open_from_data_with_name(
- (char *)&data[0], data.size(),
- true, &status, p_refonly,
- image_filename.utf8());
-
- ERR_FAIL_COND_V_MSG(status != MONO_IMAGE_OK || !image, nullptr, "Failed to open assembly image from memory: '" + p_path + "'.");
-
- if (p_aname != nullptr) {
- // Check assembly version
- const MonoTableInfo *table = mono_image_get_table_info(image, MONO_TABLE_ASSEMBLY);
-
- ERR_FAIL_NULL_V(table, nullptr);
-
- if (mono_table_info_get_rows(table)) {
- uint32_t cols[MONO_ASSEMBLY_SIZE];
- mono_metadata_decode_row(table, 0, cols, MONO_ASSEMBLY_SIZE);
-
- // Not sure about .NET's policy. We will only ensure major and minor are equal, and ignore build and revision.
- uint16_t major = cols[MONO_ASSEMBLY_MAJOR_VERSION];
- uint16_t minor = cols[MONO_ASSEMBLY_MINOR_VERSION];
-
- uint16_t required_minor;
- uint16_t required_major = mono_assembly_name_get_version(p_aname, &required_minor, nullptr, nullptr);
-
- if (required_major != 0) {
- if (major != required_major && minor != required_minor) {
- mono_image_close(image);
- return nullptr;
- }
- }
- }
- }
-
-#ifdef DEBUG_ENABLED
- Vector<uint8_t> pdb_data;
- String pdb_path(p_path + ".pdb");
-
- if (!FileAccess::exists(pdb_path)) {
- pdb_path = p_path.get_basename() + ".pdb"; // without .dll
-
- if (!FileAccess::exists(pdb_path)) {
- goto no_pdb;
- }
- }
-
- pdb_data = FileAccess::get_file_as_array(pdb_path);
-
- // mono_debug_close_image doesn't seem to be needed
- mono_debug_open_image_from_memory(image, &pdb_data[0], pdb_data.size());
-
-no_pdb:
-
-#endif
-
- bool need_manual_load_hook = mono_image_get_assembly(image) != nullptr; // Re-using an existing image with an assembly loaded
-
- status = MONO_IMAGE_OK;
-
- MonoAssembly *assembly = mono_assembly_load_from_full(image, image_filename.utf8().get_data(), &status, p_refonly);
-
- ERR_FAIL_COND_V_MSG(status != MONO_IMAGE_OK || !assembly, nullptr, "Failed to load assembly for image");
-
- if (need_manual_load_hook) {
- // For some reason if an assembly survived domain reloading (maybe because it's referenced somewhere else),
- // the mono internal search hook don't detect it, yet mono_image_open_from_data_with_name re-uses the image
- // and assembly, and mono_assembly_load_from_full doesn't call the load hook. We need to call it manually.
- String name = String::utf8(mono_assembly_name_get_name(mono_assembly_get_name(assembly)));
- bool has_extension = name.ends_with(".dll") || name.ends_with(".exe");
- GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(has_extension ? name.get_basename() : name);
- if (!loaded_asm) {
- assembly_load_hook(assembly, nullptr);
- }
- }
-
- // Decrement refcount which was previously incremented by mono_image_open_from_data_with_name
- mono_image_close(image);
-
- return assembly;
-}
-
-void GDMonoAssembly::unload() {
- ERR_FAIL_NULL(image); // Should not be called if already unloaded
-
- for (const KeyValue<MonoClass *, GDMonoClass *> &E : cached_raw) {
- memdelete(E.value);
- }
-
- cached_classes.clear();
- cached_raw.clear();
-
- assembly = nullptr;
- image = nullptr;
-}
-
-String GDMonoAssembly::get_path() const {
- return String::utf8(mono_image_get_filename(image));
-}
-
-bool GDMonoAssembly::has_attribute(GDMonoClass *p_attr_class) {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_NULL_V(p_attr_class, false);
-#endif
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return false;
- }
-
- return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-MonoObject *GDMonoAssembly::get_attribute(GDMonoClass *p_attr_class) {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_NULL_V(p_attr_class, nullptr);
-#endif
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return nullptr;
- }
-
- return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-void GDMonoAssembly::fetch_attributes() {
- ERR_FAIL_COND(attributes != nullptr);
-
- attributes = mono_custom_attrs_from_assembly(assembly);
- attrs_fetched = true;
-}
-
-GDMonoClass *GDMonoAssembly::get_class(const StringName &p_namespace, const StringName &p_name) {
- ERR_FAIL_NULL_V(image, nullptr);
-
- ClassKey key(p_namespace, p_name);
-
- GDMonoClass **match = cached_classes.getptr(key);
-
- if (match) {
- return *match;
- }
-
- MonoClass *mono_class = mono_class_from_name(image, String(p_namespace).utf8(), String(p_name).utf8());
-
- if (!mono_class) {
- return nullptr;
- }
-
- GDMonoClass *wrapped_class = memnew(GDMonoClass(p_namespace, p_name, mono_class, this));
-
- cached_classes[key] = wrapped_class;
- cached_raw[mono_class] = wrapped_class;
-
- return wrapped_class;
-}
-
-GDMonoClass *GDMonoAssembly::get_class(MonoClass *p_mono_class) {
- ERR_FAIL_NULL_V(image, nullptr);
-
- HashMap<MonoClass *, GDMonoClass *>::Iterator match = cached_raw.find(p_mono_class);
-
- if (match) {
- return match->value;
- }
-
- StringName namespace_name = String::utf8(mono_class_get_namespace(p_mono_class));
- StringName class_name = String::utf8(mono_class_get_name(p_mono_class));
-
- GDMonoClass *wrapped_class = memnew(GDMonoClass(namespace_name, class_name, p_mono_class, this));
-
- cached_classes[ClassKey(namespace_name, class_name)] = wrapped_class;
- cached_raw[p_mono_class] = wrapped_class;
-
- return wrapped_class;
-}
-
-GDMonoAssembly *GDMonoAssembly::load(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs) {
- if (GDMono::get_singleton()->get_corlib_assembly() && (p_name == "mscorlib" || p_name == "mscorlib.dll")) {
- return GDMono::get_singleton()->get_corlib_assembly();
- }
-
- // We need to manually call the search hook in this case, as it won't be called in the next step
- MonoAssembly *assembly = mono_assembly_invoke_search_hook(p_aname);
-
- if (!assembly) {
- assembly = _load_assembly_search(p_name, p_aname, p_refonly, p_search_dirs);
- if (!assembly) {
- return nullptr;
- }
- }
-
- GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(p_name);
- ERR_FAIL_NULL_V_MSG(loaded_asm, nullptr, "Loaded assembly missing from table. Did we not receive the load hook?");
- ERR_FAIL_COND_V(loaded_asm->get_assembly() != assembly, nullptr);
-
- return loaded_asm;
-}
-
-GDMonoAssembly *GDMonoAssembly::load_from(const String &p_name, const String &p_path, bool p_refonly) {
- if (p_name == "mscorlib" || p_name == "mscorlib.dll") {
- return GDMono::get_singleton()->get_corlib_assembly();
- }
-
- // We need to manually call the search hook in this case, as it won't be called in the next step
- MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
- MonoAssembly *assembly = mono_assembly_invoke_search_hook(aname);
- mono_assembly_name_free(aname);
- mono_free(aname);
-
- if (!assembly) {
- assembly = _real_load_assembly_from(p_path, p_refonly);
- if (!assembly) {
- return nullptr;
- }
- }
-
- GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(p_name);
- ERR_FAIL_NULL_V_MSG(loaded_asm, nullptr, "Loaded assembly missing from table. Did we not receive the load hook?");
-
- return loaded_asm;
-}
-
-GDMonoAssembly::~GDMonoAssembly() {
- if (image) {
- unload();
- }
-}
diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h
deleted file mode 100644
index 0a3ae6c4fe..0000000000
--- a/modules/mono/mono_gd/gd_mono_assembly.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/*************************************************************************/
-/* gd_mono_assembly.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 GD_MONO_ASSEMBLY_H
-#define GD_MONO_ASSEMBLY_H
-
-#include <mono/jit/jit.h>
-#include <mono/metadata/assembly.h>
-
-#include "core/string/ustring.h"
-#include "core/templates/hash_map.h"
-#include "core/templates/rb_map.h"
-#include "gd_mono_utils.h"
-
-class GDMonoAssembly {
- struct ClassKey {
- struct Hasher {
- static _FORCE_INLINE_ uint32_t hash(const ClassKey &p_key) {
- uint32_t hash = 0;
-
- GDMonoUtils::hash_combine(hash, p_key.namespace_name.hash());
- GDMonoUtils::hash_combine(hash, p_key.class_name.hash());
-
- return hash;
- }
- };
-
- _FORCE_INLINE_ bool operator==(const ClassKey &p_a) const {
- return p_a.class_name == class_name && p_a.namespace_name == namespace_name;
- }
-
- ClassKey() {}
-
- ClassKey(const StringName &p_namespace_name, const StringName &p_class_name) {
- namespace_name = p_namespace_name;
- class_name = p_class_name;
- }
-
- StringName namespace_name;
- StringName class_name;
- };
-
- String name;
- MonoImage *image = nullptr;
- MonoAssembly *assembly = nullptr;
-
- bool attrs_fetched = false;
- MonoCustomAttrInfo *attributes = nullptr;
-
-#ifdef GD_MONO_HOT_RELOAD
- uint64_t modified_time = 0;
-#endif
-
- HashMap<ClassKey, GDMonoClass *, ClassKey::Hasher> cached_classes;
- HashMap<MonoClass *, GDMonoClass *> cached_raw;
-
- static Vector<String> search_dirs;
-
- static void assembly_load_hook(MonoAssembly *assembly, void *user_data);
- static MonoAssembly *assembly_search_hook(MonoAssemblyName *aname, void *user_data);
- static MonoAssembly *assembly_refonly_search_hook(MonoAssemblyName *aname, void *user_data);
- static MonoAssembly *assembly_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data);
- static MonoAssembly *assembly_refonly_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data);
-
- static MonoAssembly *_search_hook(MonoAssemblyName *aname, void *user_data, bool refonly);
- static MonoAssembly *_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data, bool refonly);
-
- static MonoAssembly *_real_load_assembly_from(const String &p_path, bool p_refonly, MonoAssemblyName *p_aname = nullptr);
- static MonoAssembly *_load_assembly_search(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs);
-
- friend class GDMono;
- static void initialize();
-
-public:
- void unload();
-
- _FORCE_INLINE_ MonoImage *get_image() const { return image; }
- _FORCE_INLINE_ MonoAssembly *get_assembly() const { return assembly; }
- _FORCE_INLINE_ String get_name() const { return name; }
-
-#ifdef GD_MONO_HOT_RELOAD
- _FORCE_INLINE_ uint64_t get_modified_time() const { return modified_time; }
-#endif
-
- String get_path() const;
-
- bool has_attribute(GDMonoClass *p_attr_class);
- MonoObject *get_attribute(GDMonoClass *p_attr_class);
-
- void fetch_attributes();
-
- GDMonoClass *get_class(const StringName &p_namespace, const StringName &p_name);
- GDMonoClass *get_class(MonoClass *p_mono_class);
-
- static String find_assembly(const String &p_name);
-
- static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String(), const String &p_custom_bcl_dir = String());
- static const Vector<String> &get_default_search_dirs() { return search_dirs; }
-
- static GDMonoAssembly *load(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs);
- static GDMonoAssembly *load_from(const String &p_name, const String &p_path, bool p_refonly);
-
- GDMonoAssembly(const String &p_name, MonoImage *p_image, MonoAssembly *p_assembly) :
- name(p_name),
- image(p_image),
- assembly(p_assembly) {
- }
- ~GDMonoAssembly();
-};
-
-#endif // GD_MONO_ASSEMBLY_H
diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp
index 69d8c7edc9..bfd803f326 100644
--- a/modules/mono/mono_gd/gd_mono_cache.cpp
+++ b/modules/mono/mono_gd/gd_mono_cache.cpp
@@ -30,310 +30,66 @@
#include "gd_mono_cache.h"
-#include "gd_mono.h"
-#include "gd_mono_class.h"
-#include "gd_mono_marshal.h"
-#include "gd_mono_method.h"
-#include "gd_mono_utils.h"
+#include "core/error/error_macros.h"
namespace GDMonoCache {
-CachedData cached_data;
+ManagedCallbacks managed_callbacks;
+bool godot_api_cache_updated = false;
-#define CACHE_AND_CHECK(m_var, m_val) \
- { \
- CRASH_COND(m_var != nullptr); \
- m_var = m_val; \
- ERR_FAIL_COND_MSG(m_var == nullptr, "Mono Cache: Member " #m_var " is null."); \
- }
-
-#define CACHE_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(cached_data.class_##m_class, m_val)
-#define CACHE_NS_CLASS_AND_CHECK(m_ns, m_class, m_val) CACHE_AND_CHECK(cached_data.class_##m_ns##_##m_class, m_val)
-#define CACHE_RAW_MONO_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(cached_data.rawclass_##m_class, m_val)
-#define CACHE_FIELD_AND_CHECK(m_class, m_field, m_val) CACHE_AND_CHECK(cached_data.field_##m_class##_##m_field, m_val)
-#define CACHE_METHOD_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(cached_data.method_##m_class##_##m_method, m_val)
-#define CACHE_PROPERTY_AND_CHECK(m_class, m_property, m_val) CACHE_AND_CHECK(cached_data.property_##m_class##_##m_property, m_val)
+void update_godot_api_cache(const ManagedCallbacks &p_managed_callbacks) {
+ int checked_count = 0;
-#define CACHE_METHOD_THUNK_AND_CHECK_IMPL(m_var, m_val) \
- { \
- CRASH_COND(!m_var.is_null()); \
- ERR_FAIL_COND_MSG(m_val == nullptr, "Mono Cache: Method for member " #m_var " is null."); \
- m_var.set_from_method(m_val); \
- ERR_FAIL_COND_MSG(m_var.is_null(), "Mono Cache: Member " #m_var " is null."); \
+#define CHECK_CALLBACK_NOT_NULL_IMPL(m_var, m_class, m_method) \
+ { \
+ ERR_FAIL_COND_MSG(m_var == nullptr, \
+ "Mono Cache: Managed callback for '" #m_class "_" #m_method "' is null."); \
+ checked_count += 1; \
}
-#define CACHE_METHOD_THUNK_AND_CHECK(m_class, m_method, m_val) CACHE_METHOD_THUNK_AND_CHECK_IMPL(cached_data.methodthunk_##m_class##_##m_method, m_val)
-
-void CachedData::clear_corlib_cache() {
- corlib_cache_updated = false;
-
- class_MonoObject = nullptr;
- class_bool = nullptr;
- class_int8_t = nullptr;
- class_int16_t = nullptr;
- class_int32_t = nullptr;
- class_int64_t = nullptr;
- class_uint8_t = nullptr;
- class_uint16_t = nullptr;
- class_uint32_t = nullptr;
- class_uint64_t = nullptr;
- class_float = nullptr;
- class_double = nullptr;
- class_String = nullptr;
- class_IntPtr = nullptr;
-
- class_System_Collections_IEnumerable = nullptr;
- class_System_Collections_ICollection = nullptr;
- class_System_Collections_IDictionary = nullptr;
-
-#ifdef DEBUG_ENABLED
- class_System_Diagnostics_StackTrace = nullptr;
- methodthunk_System_Diagnostics_StackTrace_GetFrames.nullify();
- method_System_Diagnostics_StackTrace_ctor_bool = nullptr;
- method_System_Diagnostics_StackTrace_ctor_Exception_bool = nullptr;
-#endif
-
- class_KeyNotFoundException = nullptr;
-}
-
-void CachedData::clear_godot_api_cache() {
- godot_api_cache_updated = false;
-
- rawclass_Dictionary = nullptr;
-
- class_Vector2 = nullptr;
- class_Vector2i = nullptr;
- class_Rect2 = nullptr;
- class_Rect2i = nullptr;
- class_Transform2D = nullptr;
- class_Vector3 = nullptr;
- class_Vector3i = nullptr;
- class_Vector4 = nullptr;
- class_Vector4i = nullptr;
- class_Basis = nullptr;
- class_Quaternion = nullptr;
- class_Transform3D = nullptr;
- class_Projection = nullptr;
- class_AABB = nullptr;
- class_Color = nullptr;
- class_Plane = nullptr;
- class_StringName = nullptr;
- class_NodePath = nullptr;
- class_RID = nullptr;
- class_GodotObject = nullptr;
- class_GodotResource = nullptr;
- class_Node = nullptr;
- class_Control = nullptr;
- class_Node3D = nullptr;
- class_WeakRef = nullptr;
- class_Callable = nullptr;
- class_SignalInfo = nullptr;
- class_Array = nullptr;
- class_Dictionary = nullptr;
- class_MarshalUtils = nullptr;
- class_ISerializationListener = nullptr;
-
-#ifdef DEBUG_ENABLED
- class_DebuggingUtils = nullptr;
- methodthunk_DebuggingUtils_GetStackFrameInfo.nullify();
-#endif
-
- class_ExportAttribute = nullptr;
- field_ExportAttribute_hint = nullptr;
- field_ExportAttribute_hintString = nullptr;
- class_SignalAttribute = nullptr;
- class_ToolAttribute = nullptr;
- class_RPCAttribute = nullptr;
- property_RPCAttribute_Mode = nullptr;
- property_RPCAttribute_CallLocal = nullptr;
- property_RPCAttribute_TransferMode = nullptr;
- property_RPCAttribute_TransferChannel = nullptr;
- class_GodotMethodAttribute = nullptr;
- field_GodotMethodAttribute_methodName = nullptr;
- class_ScriptPathAttribute = nullptr;
- field_ScriptPathAttribute_path = nullptr;
- class_AssemblyHasScriptsAttribute = nullptr;
- field_AssemblyHasScriptsAttribute_requiresLookup = nullptr;
- field_AssemblyHasScriptsAttribute_scriptTypes = nullptr;
-
- field_GodotObject_ptr = nullptr;
- field_StringName_ptr = nullptr;
- field_NodePath_ptr = nullptr;
- field_Image_ptr = nullptr;
- field_RID_ptr = nullptr;
-
- methodthunk_GodotObject_Dispose.nullify();
- methodthunk_Array_GetPtr.nullify();
- methodthunk_Dictionary_GetPtr.nullify();
- methodthunk_SignalAwaiter_SignalCallback.nullify();
- methodthunk_GodotTaskScheduler_Activate.nullify();
-
- methodthunk_Delegate_Equals.nullify();
-
- methodthunk_DelegateUtils_TrySerializeDelegate.nullify();
- methodthunk_DelegateUtils_TryDeserializeDelegate.nullify();
-
- // Start of MarshalUtils methods
-
- methodthunk_MarshalUtils_TypeIsGenericArray.nullify();
- methodthunk_MarshalUtils_TypeIsGenericDictionary.nullify();
- methodthunk_MarshalUtils_TypeIsSystemGenericList.nullify();
- methodthunk_MarshalUtils_TypeIsSystemGenericDictionary.nullify();
- methodthunk_MarshalUtils_TypeIsGenericIEnumerable.nullify();
- methodthunk_MarshalUtils_TypeIsGenericICollection.nullify();
- methodthunk_MarshalUtils_TypeIsGenericIDictionary.nullify();
- methodthunk_MarshalUtils_TypeHasFlagsAttribute.nullify();
-
- methodthunk_MarshalUtils_GetGenericTypeDefinition.nullify();
-
- methodthunk_MarshalUtils_ArrayGetElementType.nullify();
- methodthunk_MarshalUtils_DictionaryGetKeyValueTypes.nullify();
-
- methodthunk_MarshalUtils_MakeGenericArrayType.nullify();
- methodthunk_MarshalUtils_MakeGenericDictionaryType.nullify();
-
- // End of MarshalUtils methods
-
- task_scheduler_handle = Ref<MonoGCHandleRef>();
-}
-
-#define GODOT_API_CLASS(m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, #m_class))
-#define GODOT_API_NS_CLASS(m_ns, m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(m_ns, #m_class))
-
-void update_corlib_cache() {
- CACHE_CLASS_AND_CHECK(MonoObject, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_object_class()));
- CACHE_CLASS_AND_CHECK(bool, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_boolean_class()));
- CACHE_CLASS_AND_CHECK(int8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_sbyte_class()));
- CACHE_CLASS_AND_CHECK(int16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int16_class()));
- CACHE_CLASS_AND_CHECK(int32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int32_class()));
- CACHE_CLASS_AND_CHECK(int64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int64_class()));
- CACHE_CLASS_AND_CHECK(uint8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_byte_class()));
- CACHE_CLASS_AND_CHECK(uint16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint16_class()));
- CACHE_CLASS_AND_CHECK(uint32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint32_class()));
- CACHE_CLASS_AND_CHECK(uint64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint64_class()));
- CACHE_CLASS_AND_CHECK(float, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_single_class()));
- CACHE_CLASS_AND_CHECK(double, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_double_class()));
- CACHE_CLASS_AND_CHECK(String, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_string_class()));
- CACHE_CLASS_AND_CHECK(IntPtr, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_intptr_class()));
-
- CACHE_CLASS_AND_CHECK(System_Collections_IEnumerable, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IEnumerable"));
- CACHE_CLASS_AND_CHECK(System_Collections_ICollection, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "ICollection"));
- CACHE_CLASS_AND_CHECK(System_Collections_IDictionary, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IDictionary"));
-
-#ifdef DEBUG_ENABLED
- CACHE_CLASS_AND_CHECK(System_Diagnostics_StackTrace, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Diagnostics", "StackTrace"));
- CACHE_METHOD_THUNK_AND_CHECK(System_Diagnostics_StackTrace, GetFrames, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method("GetFrames"));
- CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(bool)", true));
- CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_Exception_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(System.Exception,bool)", true));
-#endif
-
- CACHE_METHOD_THUNK_AND_CHECK(Delegate, Equals, GDMono::get_singleton()->get_corlib_assembly()->get_class("System", "Delegate")->get_method_with_desc("System.Delegate:Equals(object)", true));
-
- CACHE_CLASS_AND_CHECK(KeyNotFoundException, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections.Generic", "KeyNotFoundException"));
-
- cached_data.corlib_cache_updated = true;
-}
-
-void update_godot_api_cache() {
- CACHE_CLASS_AND_CHECK(Vector2, GODOT_API_CLASS(Vector2));
- CACHE_CLASS_AND_CHECK(Vector2i, GODOT_API_CLASS(Vector2i));
- CACHE_CLASS_AND_CHECK(Rect2, GODOT_API_CLASS(Rect2));
- CACHE_CLASS_AND_CHECK(Rect2i, GODOT_API_CLASS(Rect2i));
- CACHE_CLASS_AND_CHECK(Transform2D, GODOT_API_CLASS(Transform2D));
- CACHE_CLASS_AND_CHECK(Vector3, GODOT_API_CLASS(Vector3));
- CACHE_CLASS_AND_CHECK(Vector3i, GODOT_API_CLASS(Vector3i));
- CACHE_CLASS_AND_CHECK(Vector4, GODOT_API_CLASS(Vector4));
- CACHE_CLASS_AND_CHECK(Vector4i, GODOT_API_CLASS(Vector4i));
- CACHE_CLASS_AND_CHECK(Basis, GODOT_API_CLASS(Basis));
- CACHE_CLASS_AND_CHECK(Quaternion, GODOT_API_CLASS(Quaternion));
- CACHE_CLASS_AND_CHECK(Transform3D, GODOT_API_CLASS(Transform3D));
- CACHE_CLASS_AND_CHECK(Projection, GODOT_API_CLASS(Projection));
- CACHE_CLASS_AND_CHECK(AABB, GODOT_API_CLASS(AABB));
- CACHE_CLASS_AND_CHECK(Color, GODOT_API_CLASS(Color));
- CACHE_CLASS_AND_CHECK(Plane, GODOT_API_CLASS(Plane));
- CACHE_CLASS_AND_CHECK(StringName, GODOT_API_CLASS(StringName));
- CACHE_CLASS_AND_CHECK(NodePath, GODOT_API_CLASS(NodePath));
- CACHE_CLASS_AND_CHECK(RID, GODOT_API_CLASS(RID));
- CACHE_CLASS_AND_CHECK(GodotObject, GODOT_API_CLASS(Object));
- CACHE_CLASS_AND_CHECK(GodotResource, GODOT_API_CLASS(Resource));
- CACHE_CLASS_AND_CHECK(Node, GODOT_API_CLASS(Node));
- CACHE_CLASS_AND_CHECK(Control, GODOT_API_CLASS(Control));
- CACHE_CLASS_AND_CHECK(Node3D, GODOT_API_CLASS(Node3D));
- CACHE_CLASS_AND_CHECK(WeakRef, GODOT_API_CLASS(WeakRef));
- CACHE_CLASS_AND_CHECK(Callable, GODOT_API_CLASS(Callable));
- CACHE_CLASS_AND_CHECK(SignalInfo, GODOT_API_CLASS(SignalInfo));
- CACHE_CLASS_AND_CHECK(Array, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Array));
- CACHE_CLASS_AND_CHECK(Dictionary, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary));
- CACHE_CLASS_AND_CHECK(MarshalUtils, GODOT_API_CLASS(MarshalUtils));
- CACHE_CLASS_AND_CHECK(ISerializationListener, GODOT_API_CLASS(ISerializationListener));
-
-#ifdef DEBUG_ENABLED
- CACHE_CLASS_AND_CHECK(DebuggingUtils, GODOT_API_CLASS(DebuggingUtils));
-#endif
-
- // Attributes
- CACHE_CLASS_AND_CHECK(ExportAttribute, GODOT_API_CLASS(ExportAttribute));
- CACHE_FIELD_AND_CHECK(ExportAttribute, hint, CACHED_CLASS(ExportAttribute)->get_field("hint"));
- CACHE_FIELD_AND_CHECK(ExportAttribute, hintString, CACHED_CLASS(ExportAttribute)->get_field("hintString"));
- CACHE_CLASS_AND_CHECK(SignalAttribute, GODOT_API_CLASS(SignalAttribute));
- CACHE_CLASS_AND_CHECK(ToolAttribute, GODOT_API_CLASS(ToolAttribute));
- CACHE_CLASS_AND_CHECK(RPCAttribute, GODOT_API_CLASS(RPCAttribute));
- CACHE_PROPERTY_AND_CHECK(RPCAttribute, Mode, CACHED_CLASS(RPCAttribute)->get_property("Mode"));
- CACHE_PROPERTY_AND_CHECK(RPCAttribute, CallLocal, CACHED_CLASS(RPCAttribute)->get_property("CallLocal"));
- CACHE_PROPERTY_AND_CHECK(RPCAttribute, TransferMode, CACHED_CLASS(RPCAttribute)->get_property("TransferMode"));
- CACHE_PROPERTY_AND_CHECK(RPCAttribute, TransferChannel, CACHED_CLASS(RPCAttribute)->get_property("TransferChannel"));
- CACHE_CLASS_AND_CHECK(GodotMethodAttribute, GODOT_API_CLASS(GodotMethodAttribute));
- CACHE_FIELD_AND_CHECK(GodotMethodAttribute, methodName, CACHED_CLASS(GodotMethodAttribute)->get_field("methodName"));
- CACHE_CLASS_AND_CHECK(ScriptPathAttribute, GODOT_API_CLASS(ScriptPathAttribute));
- CACHE_FIELD_AND_CHECK(ScriptPathAttribute, path, CACHED_CLASS(ScriptPathAttribute)->get_field("path"));
- CACHE_CLASS_AND_CHECK(AssemblyHasScriptsAttribute, GODOT_API_CLASS(AssemblyHasScriptsAttribute));
- CACHE_FIELD_AND_CHECK(AssemblyHasScriptsAttribute, requiresLookup, CACHED_CLASS(AssemblyHasScriptsAttribute)->get_field("requiresLookup"));
- CACHE_FIELD_AND_CHECK(AssemblyHasScriptsAttribute, scriptTypes, CACHED_CLASS(AssemblyHasScriptsAttribute)->get_field("scriptTypes"));
-
- CACHE_FIELD_AND_CHECK(GodotObject, ptr, CACHED_CLASS(GodotObject)->get_field(BINDINGS_PTR_FIELD));
- CACHE_FIELD_AND_CHECK(StringName, ptr, CACHED_CLASS(StringName)->get_field(BINDINGS_PTR_FIELD));
- CACHE_FIELD_AND_CHECK(NodePath, ptr, CACHED_CLASS(NodePath)->get_field(BINDINGS_PTR_FIELD));
- CACHE_FIELD_AND_CHECK(RID, ptr, CACHED_CLASS(RID)->get_field(BINDINGS_PTR_FIELD));
-
- CACHE_METHOD_THUNK_AND_CHECK(GodotObject, Dispose, CACHED_CLASS(GodotObject)->get_method("Dispose", 0));
- CACHE_METHOD_THUNK_AND_CHECK(Array, GetPtr, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Array)->get_method("GetPtr", 0));
- CACHE_METHOD_THUNK_AND_CHECK(Dictionary, GetPtr, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary)->get_method("GetPtr", 0));
- CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, SignalCallback, GODOT_API_CLASS(SignalAwaiter)->get_method("SignalCallback", 1));
- CACHE_METHOD_THUNK_AND_CHECK(GodotTaskScheduler, Activate, GODOT_API_CLASS(GodotTaskScheduler)->get_method("Activate", 0));
-
- CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, TrySerializeDelegate, GODOT_API_CLASS(DelegateUtils)->get_method("TrySerializeDelegate", 2));
- CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, TryDeserializeDelegate, GODOT_API_CLASS(DelegateUtils)->get_method("TryDeserializeDelegate", 2));
-
- // Start of MarshalUtils methods
-
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericArray, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsGenericArray", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericDictionary, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsGenericDictionary", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsSystemGenericList, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsSystemGenericList", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsSystemGenericDictionary, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsSystemGenericDictionary", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericIEnumerable, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsGenericIEnumerable", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericICollection, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsGenericICollection", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericIDictionary, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsGenericIDictionary", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeHasFlagsAttribute, GODOT_API_CLASS(MarshalUtils)->get_method("TypeHasFlagsAttribute", 1));
-
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GetGenericTypeDefinition, GODOT_API_CLASS(MarshalUtils)->get_method("GetGenericTypeDefinition", 2));
-
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, ArrayGetElementType, GODOT_API_CLASS(MarshalUtils)->get_method("ArrayGetElementType", 2));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, DictionaryGetKeyValueTypes, GODOT_API_CLASS(MarshalUtils)->get_method("DictionaryGetKeyValueTypes", 3));
-
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, MakeGenericArrayType, GODOT_API_CLASS(MarshalUtils)->get_method("MakeGenericArrayType", 1));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, MakeGenericDictionaryType, GODOT_API_CLASS(MarshalUtils)->get_method("MakeGenericDictionaryType", 2));
-
- // End of MarshalUtils methods
-
-#ifdef DEBUG_ENABLED
- CACHE_METHOD_THUNK_AND_CHECK(DebuggingUtils, GetStackFrameInfo, GODOT_API_CLASS(DebuggingUtils)->get_method("GetStackFrameInfo", 4));
-#endif
-
- // TODO Move to CSharpLanguage::init() and do handle disposal
- MonoObject *task_scheduler = mono_object_new(mono_domain_get(), GODOT_API_CLASS(GodotTaskScheduler)->get_mono_ptr());
- GDMonoUtils::runtime_object_init(task_scheduler, GODOT_API_CLASS(GodotTaskScheduler));
- cached_data.task_scheduler_handle = MonoGCHandleRef::create_strong(task_scheduler);
+#define CHECK_CALLBACK_NOT_NULL(m_class, m_method) CHECK_CALLBACK_NOT_NULL_IMPL(p_managed_callbacks.m_class##_##m_method, m_class, m_method)
+
+ CHECK_CALLBACK_NOT_NULL(SignalAwaiter, SignalCallback);
+ CHECK_CALLBACK_NOT_NULL(DelegateUtils, InvokeWithVariantArgs);
+ CHECK_CALLBACK_NOT_NULL(DelegateUtils, DelegateEquals);
+ CHECK_CALLBACK_NOT_NULL(DelegateUtils, TrySerializeDelegateWithGCHandle);
+ CHECK_CALLBACK_NOT_NULL(DelegateUtils, TryDeserializeDelegateWithGCHandle);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, FrameCallback);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, CreateManagedForGodotObjectBinding);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, CreateManagedForGodotObjectScriptInstance);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, GetScriptNativeName);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, SetGodotObjectPtr);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, RaiseEventSignal);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, ScriptIsOrInherits);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, AddScriptBridge);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, GetOrCreateScriptBridgeForPath);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, RemoveScriptBridge);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, TryReloadRegisteredScriptWithClass);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, UpdateScriptClassInfo);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, SwapGCHandleForType);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, GetPropertyInfoList);
+ CHECK_CALLBACK_NOT_NULL(ScriptManagerBridge, GetPropertyDefaultValues);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, Call);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, Set);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, Get);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, CallDispose);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, CallToString);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, HasMethodUnknownParams);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, SerializeState);
+ CHECK_CALLBACK_NOT_NULL(CSharpInstanceBridge, DeserializeState);
+ CHECK_CALLBACK_NOT_NULL(GCHandleBridge, FreeGCHandle);
+ CHECK_CALLBACK_NOT_NULL(DebuggingUtils, GetCurrentStackInfo);
+ CHECK_CALLBACK_NOT_NULL(DisposablesTracker, OnGodotShuttingDown);
+ CHECK_CALLBACK_NOT_NULL(GD, OnCoreApiAssemblyLoaded);
+
+ managed_callbacks = p_managed_callbacks;
+
+ // It's easy to forget to add new callbacks here, so this should help
+ if (checked_count * sizeof(void *) != sizeof(ManagedCallbacks)) {
+ int missing_count = (sizeof(ManagedCallbacks) / sizeof(void *)) - checked_count;
+ WARN_PRINT("The presence of " + itos(missing_count) + " callback(s) was not validated");
+ }
- cached_data.godot_api_cache_updated = true;
+ godot_api_cache_updated = true;
}
} // namespace GDMonoCache
diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h
index e9cc26899e..ca3a6c95a7 100644
--- a/modules/mono/mono_gd/gd_mono_cache.h
+++ b/modules/mono/mono_gd/gd_mono_cache.h
@@ -31,174 +31,120 @@
#ifndef GD_MONO_CACHE_H
#define GD_MONO_CACHE_H
-#include "gd_mono_header.h"
-#include "gd_mono_method_thunk.h"
+#include <stdint.h>
+
+#include "../csharp_script.h"
+#include "../interop_types.h"
+#include "../mono_gc_handle.h"
+#include "core/object/object.h"
+#include "core/string/string_name.h"
+#include "core/string/ustring.h"
+#include "core/variant/callable.h"
+#include "core/variant/dictionary.h"
+#include "core/variant/variant.h"
+
+class CSharpScript;
namespace GDMonoCache {
-struct CachedData {
- // -----------------------------------------------
- // corlib classes
-
- // Let's use the no-namespace format for these too
- GDMonoClass *class_MonoObject = nullptr; // object
- GDMonoClass *class_bool = nullptr; // bool
- GDMonoClass *class_int8_t = nullptr; // sbyte
- GDMonoClass *class_int16_t = nullptr; // short
- GDMonoClass *class_int32_t = nullptr; // int
- GDMonoClass *class_int64_t = nullptr; // long
- GDMonoClass *class_uint8_t = nullptr; // byte
- GDMonoClass *class_uint16_t = nullptr; // ushort
- GDMonoClass *class_uint32_t = nullptr; // uint
- GDMonoClass *class_uint64_t = nullptr; // ulong
- GDMonoClass *class_float = nullptr; // float
- GDMonoClass *class_double = nullptr; // double
- GDMonoClass *class_String = nullptr; // string
- GDMonoClass *class_IntPtr = nullptr; // System.IntPtr
-
- GDMonoClass *class_System_Collections_IEnumerable = nullptr;
- GDMonoClass *class_System_Collections_ICollection = nullptr;
- GDMonoClass *class_System_Collections_IDictionary = nullptr;
-
-#ifdef DEBUG_ENABLED
- GDMonoClass *class_System_Diagnostics_StackTrace = nullptr;
- GDMonoMethodThunkR<MonoArray *, MonoObject *> methodthunk_System_Diagnostics_StackTrace_GetFrames;
- GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_bool = nullptr;
- GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_Exception_bool = nullptr;
+#ifdef WIN32
+#define GD_CLR_STDCALL __stdcall
+#else
+#define GD_CLR_STDCALL
#endif
- GDMonoClass *class_KeyNotFoundException = nullptr;
-
- MonoClass *rawclass_Dictionary = nullptr;
- // -----------------------------------------------
-
- GDMonoClass *class_Vector2 = nullptr;
- GDMonoClass *class_Vector2i = nullptr;
- GDMonoClass *class_Rect2 = nullptr;
- GDMonoClass *class_Rect2i = nullptr;
- GDMonoClass *class_Transform2D = nullptr;
- GDMonoClass *class_Vector3 = nullptr;
- GDMonoClass *class_Vector3i = nullptr;
- GDMonoClass *class_Vector4 = nullptr;
- GDMonoClass *class_Vector4i = nullptr;
- GDMonoClass *class_Basis = nullptr;
- GDMonoClass *class_Quaternion = nullptr;
- GDMonoClass *class_Transform3D = nullptr;
- GDMonoClass *class_Projection = nullptr;
- GDMonoClass *class_AABB = nullptr;
- GDMonoClass *class_Color = nullptr;
- GDMonoClass *class_Plane = nullptr;
- GDMonoClass *class_StringName = nullptr;
- GDMonoClass *class_NodePath = nullptr;
- GDMonoClass *class_RID = nullptr;
- GDMonoClass *class_GodotObject = nullptr;
- GDMonoClass *class_GodotResource = nullptr;
- GDMonoClass *class_Node = nullptr;
- GDMonoClass *class_Control = nullptr;
- GDMonoClass *class_Node3D = nullptr;
- GDMonoClass *class_WeakRef = nullptr;
- GDMonoClass *class_Callable = nullptr;
- GDMonoClass *class_SignalInfo = nullptr;
- GDMonoClass *class_Array = nullptr;
- GDMonoClass *class_Dictionary = nullptr;
- GDMonoClass *class_MarshalUtils = nullptr;
- GDMonoClass *class_ISerializationListener = nullptr;
-
-#ifdef DEBUG_ENABLED
- GDMonoClass *class_DebuggingUtils = nullptr;
- GDMonoMethodThunk<MonoObject *, MonoString **, int *, MonoString **> methodthunk_DebuggingUtils_GetStackFrameInfo;
-#endif
+struct godotsharp_property_info {
+ godot_string_name name; // Not owned
+ godot_string hint_string;
+ Variant::Type type;
+ PropertyHint hint;
+ PropertyUsageFlags usage;
+ bool exported;
+};
- GDMonoClass *class_ExportAttribute = nullptr;
- GDMonoField *field_ExportAttribute_hint = nullptr;
- GDMonoField *field_ExportAttribute_hintString = nullptr;
- GDMonoClass *class_SignalAttribute = nullptr;
- GDMonoClass *class_ToolAttribute = nullptr;
- GDMonoClass *class_RPCAttribute = nullptr;
- GDMonoProperty *property_RPCAttribute_Mode = nullptr;
- GDMonoProperty *property_RPCAttribute_CallLocal = nullptr;
- GDMonoProperty *property_RPCAttribute_TransferMode = nullptr;
- GDMonoProperty *property_RPCAttribute_TransferChannel = nullptr;
- GDMonoClass *class_GodotMethodAttribute = nullptr;
- GDMonoField *field_GodotMethodAttribute_methodName = nullptr;
- GDMonoClass *class_ScriptPathAttribute = nullptr;
- GDMonoField *field_ScriptPathAttribute_path = nullptr;
- GDMonoClass *class_AssemblyHasScriptsAttribute = nullptr;
- GDMonoField *field_AssemblyHasScriptsAttribute_requiresLookup = nullptr;
- GDMonoField *field_AssemblyHasScriptsAttribute_scriptTypes = nullptr;
-
- GDMonoField *field_GodotObject_ptr = nullptr;
- GDMonoField *field_StringName_ptr = nullptr;
- GDMonoField *field_NodePath_ptr = nullptr;
- GDMonoField *field_Image_ptr = nullptr;
- GDMonoField *field_RID_ptr = nullptr;
-
- GDMonoMethodThunk<MonoObject *> methodthunk_GodotObject_Dispose;
- GDMonoMethodThunkR<Array *, MonoObject *> methodthunk_Array_GetPtr;
- GDMonoMethodThunkR<Dictionary *, MonoObject *> methodthunk_Dictionary_GetPtr;
- GDMonoMethodThunk<MonoObject *, MonoArray *> methodthunk_SignalAwaiter_SignalCallback;
- GDMonoMethodThunk<MonoObject *> methodthunk_GodotTaskScheduler_Activate;
-
- GDMonoMethodThunkR<MonoBoolean, MonoObject *, MonoObject *> methodthunk_Delegate_Equals;
-
- GDMonoMethodThunkR<MonoBoolean, MonoDelegate *, MonoObject *> methodthunk_DelegateUtils_TrySerializeDelegate;
- GDMonoMethodThunkR<MonoBoolean, MonoObject *, MonoDelegate **> methodthunk_DelegateUtils_TryDeserializeDelegate;
-
- // Start of MarshalUtils methods
-
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsGenericArray;
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsGenericDictionary;
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsSystemGenericList;
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsSystemGenericDictionary;
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsGenericIEnumerable;
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsGenericICollection;
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsGenericIDictionary;
- GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeHasFlagsAttribute;
-
- GDMonoMethodThunk<MonoReflectionType *, MonoReflectionType **> methodthunk_MarshalUtils_GetGenericTypeDefinition;
-
- GDMonoMethodThunk<MonoReflectionType *, MonoReflectionType **> methodthunk_MarshalUtils_ArrayGetElementType;
- GDMonoMethodThunk<MonoReflectionType *, MonoReflectionType **, MonoReflectionType **> methodthunk_MarshalUtils_DictionaryGetKeyValueTypes;
-
- GDMonoMethodThunkR<MonoReflectionType *, MonoReflectionType *> methodthunk_MarshalUtils_MakeGenericArrayType;
- GDMonoMethodThunkR<MonoReflectionType *, MonoReflectionType *, MonoReflectionType *> methodthunk_MarshalUtils_MakeGenericDictionaryType;
-
- // End of MarshalUtils methods
-
- Ref<MonoGCHandleRef> task_scheduler_handle;
-
- bool corlib_cache_updated;
- bool godot_api_cache_updated;
-
- void clear_corlib_cache();
- void clear_godot_api_cache();
-
- CachedData() {
- clear_corlib_cache();
- clear_godot_api_cache();
- }
+struct godotsharp_property_def_val_pair {
+ godot_string_name name; // Not owned
+ godot_variant value;
};
-extern CachedData cached_data;
+struct ManagedCallbacks {
+ using Callback_ScriptManagerBridge_GetPropertyInfoList_Add = void(GD_CLR_STDCALL *)(CSharpScript *p_script, const String *, godotsharp_property_info *p_props, int32_t p_count);
+ using Callback_ScriptManagerBridge_GetPropertyDefaultValues_Add = void(GD_CLR_STDCALL *)(CSharpScript *p_script, godotsharp_property_def_val_pair *p_def_vals, int32_t p_count);
+
+ using FuncSignalAwaiter_SignalCallback = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Variant **, int32_t, bool *);
+ using FuncDelegateUtils_InvokeWithVariantArgs = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Variant **, uint32_t, const Variant *);
+ using FuncDelegateUtils_DelegateEquals = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, GCHandleIntPtr);
+ using FuncDelegateUtils_TrySerializeDelegateWithGCHandle = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, const Array *);
+ using FuncDelegateUtils_TryDeserializeDelegateWithGCHandle = bool(GD_CLR_STDCALL *)(const Array *, GCHandleIntPtr *);
+ using FuncScriptManagerBridge_FrameCallback = void(GD_CLR_STDCALL *)();
+ using FuncScriptManagerBridge_CreateManagedForGodotObjectBinding = GCHandleIntPtr(GD_CLR_STDCALL *)(const StringName *, Object *);
+ using FuncScriptManagerBridge_CreateManagedForGodotObjectScriptInstance = bool(GD_CLR_STDCALL *)(const CSharpScript *, Object *, const Variant **, int32_t);
+ using FuncScriptManagerBridge_GetScriptNativeName = void(GD_CLR_STDCALL *)(const CSharpScript *, StringName *);
+ using FuncScriptManagerBridge_SetGodotObjectPtr = void(GD_CLR_STDCALL *)(GCHandleIntPtr, Object *);
+ using FuncScriptManagerBridge_RaiseEventSignal = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const StringName *, const Variant **, int32_t, bool *);
+ using FuncScriptManagerBridge_ScriptIsOrInherits = bool(GD_CLR_STDCALL *)(const CSharpScript *, const CSharpScript *);
+ using FuncScriptManagerBridge_AddScriptBridge = bool(GD_CLR_STDCALL *)(const CSharpScript *, const String *);
+ using FuncScriptManagerBridge_GetOrCreateScriptBridgeForPath = void(GD_CLR_STDCALL *)(const String *, Ref<CSharpScript> *);
+ using FuncScriptManagerBridge_RemoveScriptBridge = void(GD_CLR_STDCALL *)(const CSharpScript *);
+ using FuncScriptManagerBridge_TryReloadRegisteredScriptWithClass = bool(GD_CLR_STDCALL *)(const CSharpScript *);
+ using FuncScriptManagerBridge_UpdateScriptClassInfo = void(GD_CLR_STDCALL *)(const CSharpScript *, bool *, Array *, Dictionary *, Dictionary *, Ref<CSharpScript> *);
+ using FuncScriptManagerBridge_SwapGCHandleForType = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, GCHandleIntPtr *, bool);
+ using FuncScriptManagerBridge_GetPropertyInfoList = void(GD_CLR_STDCALL *)(CSharpScript *, Callback_ScriptManagerBridge_GetPropertyInfoList_Add);
+ using FuncScriptManagerBridge_GetPropertyDefaultValues = void(GD_CLR_STDCALL *)(CSharpScript *, Callback_ScriptManagerBridge_GetPropertyDefaultValues_Add);
+ using FuncCSharpInstanceBridge_Call = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, const StringName *, const Variant **, int32_t, Callable::CallError *, Variant *);
+ using FuncCSharpInstanceBridge_Set = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, const StringName *, const Variant *);
+ using FuncCSharpInstanceBridge_Get = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, const StringName *, Variant *);
+ using FuncCSharpInstanceBridge_CallDispose = void(GD_CLR_STDCALL *)(GCHandleIntPtr, bool);
+ using FuncCSharpInstanceBridge_CallToString = void(GD_CLR_STDCALL *)(GCHandleIntPtr, String *, bool *);
+ using FuncCSharpInstanceBridge_HasMethodUnknownParams = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, const StringName *);
+ using FuncCSharpInstanceBridge_SerializeState = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Dictionary *, const Dictionary *);
+ using FuncCSharpInstanceBridge_DeserializeState = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Dictionary *, const Dictionary *);
+ using FuncGCHandleBridge_FreeGCHandle = void(GD_CLR_STDCALL *)(GCHandleIntPtr);
+ using FuncDebuggingUtils_GetCurrentStackInfo = void(GD_CLR_STDCALL *)(Vector<ScriptLanguage::StackInfo> *);
+ using FuncDisposablesTracker_OnGodotShuttingDown = void(GD_CLR_STDCALL *)();
+ using FuncGD_OnCoreApiAssemblyLoaded = void(GD_CLR_STDCALL *)(bool);
+
+ FuncSignalAwaiter_SignalCallback SignalAwaiter_SignalCallback;
+ FuncDelegateUtils_InvokeWithVariantArgs DelegateUtils_InvokeWithVariantArgs;
+ FuncDelegateUtils_DelegateEquals DelegateUtils_DelegateEquals;
+ FuncDelegateUtils_TrySerializeDelegateWithGCHandle DelegateUtils_TrySerializeDelegateWithGCHandle;
+ FuncDelegateUtils_TryDeserializeDelegateWithGCHandle DelegateUtils_TryDeserializeDelegateWithGCHandle;
+ FuncScriptManagerBridge_FrameCallback ScriptManagerBridge_FrameCallback;
+ FuncScriptManagerBridge_CreateManagedForGodotObjectBinding ScriptManagerBridge_CreateManagedForGodotObjectBinding;
+ FuncScriptManagerBridge_CreateManagedForGodotObjectScriptInstance ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance;
+ FuncScriptManagerBridge_GetScriptNativeName ScriptManagerBridge_GetScriptNativeName;
+ FuncScriptManagerBridge_SetGodotObjectPtr ScriptManagerBridge_SetGodotObjectPtr;
+ FuncScriptManagerBridge_RaiseEventSignal ScriptManagerBridge_RaiseEventSignal;
+ FuncScriptManagerBridge_ScriptIsOrInherits ScriptManagerBridge_ScriptIsOrInherits;
+ FuncScriptManagerBridge_AddScriptBridge ScriptManagerBridge_AddScriptBridge;
+ FuncScriptManagerBridge_GetOrCreateScriptBridgeForPath ScriptManagerBridge_GetOrCreateScriptBridgeForPath;
+ FuncScriptManagerBridge_RemoveScriptBridge ScriptManagerBridge_RemoveScriptBridge;
+ FuncScriptManagerBridge_TryReloadRegisteredScriptWithClass ScriptManagerBridge_TryReloadRegisteredScriptWithClass;
+ FuncScriptManagerBridge_UpdateScriptClassInfo ScriptManagerBridge_UpdateScriptClassInfo;
+ FuncScriptManagerBridge_SwapGCHandleForType ScriptManagerBridge_SwapGCHandleForType;
+ FuncScriptManagerBridge_GetPropertyInfoList ScriptManagerBridge_GetPropertyInfoList;
+ FuncScriptManagerBridge_GetPropertyDefaultValues ScriptManagerBridge_GetPropertyDefaultValues;
+ FuncCSharpInstanceBridge_Call CSharpInstanceBridge_Call;
+ FuncCSharpInstanceBridge_Set CSharpInstanceBridge_Set;
+ FuncCSharpInstanceBridge_Get CSharpInstanceBridge_Get;
+ FuncCSharpInstanceBridge_CallDispose CSharpInstanceBridge_CallDispose;
+ FuncCSharpInstanceBridge_CallToString CSharpInstanceBridge_CallToString;
+ FuncCSharpInstanceBridge_HasMethodUnknownParams CSharpInstanceBridge_HasMethodUnknownParams;
+ FuncCSharpInstanceBridge_SerializeState CSharpInstanceBridge_SerializeState;
+ FuncCSharpInstanceBridge_DeserializeState CSharpInstanceBridge_DeserializeState;
+ FuncGCHandleBridge_FreeGCHandle GCHandleBridge_FreeGCHandle;
+ FuncDebuggingUtils_GetCurrentStackInfo DebuggingUtils_GetCurrentStackInfo;
+ FuncDisposablesTracker_OnGodotShuttingDown DisposablesTracker_OnGodotShuttingDown;
+ FuncGD_OnCoreApiAssemblyLoaded GD_OnCoreApiAssemblyLoaded;
+};
-void update_corlib_cache();
-void update_godot_api_cache();
+extern ManagedCallbacks managed_callbacks;
+extern bool godot_api_cache_updated;
-inline void clear_corlib_cache() {
- cached_data.clear_corlib_cache();
-}
+void update_godot_api_cache(const ManagedCallbacks &p_managed_callbacks);
-inline void clear_godot_api_cache() {
- cached_data.clear_godot_api_cache();
-}
} // namespace GDMonoCache
-#define CACHED_CLASS(m_class) (GDMonoCache::cached_data.class_##m_class)
-#define CACHED_CLASS_RAW(m_class) (GDMonoCache::cached_data.class_##m_class->get_mono_ptr())
-#define CACHED_RAW_MONO_CLASS(m_class) (GDMonoCache::cached_data.rawclass_##m_class)
-#define CACHED_FIELD(m_class, m_field) (GDMonoCache::cached_data.field_##m_class##_##m_field)
-#define CACHED_METHOD(m_class, m_method) (GDMonoCache::cached_data.method_##m_class##_##m_method)
-#define CACHED_METHOD_THUNK(m_class, m_method) (GDMonoCache::cached_data.methodthunk_##m_class##_##m_method)
-#define CACHED_PROPERTY(m_class, m_property) (GDMonoCache::cached_data.property_##m_class##_##m_property)
+#undef GD_CLR_STDCALL
#endif // GD_MONO_CACHE_H
diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp
deleted file mode 100644
index 51c5aa3542..0000000000
--- a/modules/mono/mono_gd/gd_mono_class.cpp
+++ /dev/null
@@ -1,576 +0,0 @@
-/*************************************************************************/
-/* gd_mono_class.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 "gd_mono_class.h"
-
-#include <mono/metadata/attrdefs.h>
-#include <mono/metadata/debug-helpers.h>
-
-#include "gd_mono_assembly.h"
-#include "gd_mono_cache.h"
-#include "gd_mono_marshal.h"
-
-String GDMonoClass::get_full_name(MonoClass *p_mono_class) {
- // mono_type_get_full_name is not exposed to embedders, but this seems to do the job
- MonoReflectionType *type_obj = mono_type_get_object(mono_domain_get(), get_mono_type(p_mono_class));
-
- MonoException *exc = nullptr;
- MonoString *str = GDMonoUtils::object_to_string((MonoObject *)type_obj, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- return GDMonoMarshal::mono_string_to_godot(str);
-}
-
-MonoType *GDMonoClass::get_mono_type(MonoClass *p_mono_class) {
- return mono_class_get_type(p_mono_class);
-}
-
-String GDMonoClass::get_full_name() const {
- return get_full_name(mono_class);
-}
-
-String GDMonoClass::get_type_desc() const {
- return GDMonoUtils::get_type_desc(get_mono_type());
-}
-
-MonoType *GDMonoClass::get_mono_type() const {
- // Careful, you cannot compare two MonoType*.
- // There is mono_metadata_type_equal, how is this different from comparing two MonoClass*?
- return get_mono_type(mono_class);
-}
-
-uint32_t GDMonoClass::get_flags() const {
- return mono_class_get_flags(mono_class);
-}
-
-bool GDMonoClass::is_static() const {
- uint32_t static_class_flags = MONO_TYPE_ATTR_ABSTRACT | MONO_TYPE_ATTR_SEALED;
- return (get_flags() & static_class_flags) == static_class_flags;
-}
-
-bool GDMonoClass::is_assignable_from(GDMonoClass *p_from) const {
- return mono_class_is_assignable_from(mono_class, p_from->mono_class);
-}
-
-StringName GDMonoClass::get_namespace() const {
- GDMonoClass *nesting_class = get_nesting_class();
- if (!nesting_class) {
- return namespace_name;
- }
- return nesting_class->get_namespace();
-}
-
-String GDMonoClass::get_name_for_lookup() const {
- GDMonoClass *nesting_class = get_nesting_class();
- if (!nesting_class) {
- return class_name;
- }
- return nesting_class->get_name_for_lookup() + "/" + class_name;
-}
-
-GDMonoClass *GDMonoClass::get_parent_class() const {
- MonoClass *parent_mono_class = mono_class_get_parent(mono_class);
- return parent_mono_class ? GDMono::get_singleton()->get_class(parent_mono_class) : nullptr;
-}
-
-GDMonoClass *GDMonoClass::get_nesting_class() const {
- MonoClass *nesting_type = mono_class_get_nesting_type(mono_class);
- return nesting_type ? GDMono::get_singleton()->get_class(nesting_type) : nullptr;
-}
-
-#ifdef TOOLS_ENABLED
-Vector<MonoClassField *> GDMonoClass::get_enum_fields() {
- bool class_is_enum = mono_class_is_enum(mono_class);
- ERR_FAIL_COND_V(!class_is_enum, Vector<MonoClassField *>());
-
- Vector<MonoClassField *> enum_fields;
-
- void *iter = nullptr;
- MonoClassField *raw_field = nullptr;
- while ((raw_field = mono_class_get_fields(get_mono_ptr(), &iter)) != nullptr) {
- uint32_t field_flags = mono_field_get_flags(raw_field);
-
- // Enums have an instance field named value__ which holds the value of the enum.
- // Enum constants are static, so we will use this to ignore the value__ field.
- if (field_flags & MONO_FIELD_ATTR_PUBLIC && field_flags & MONO_FIELD_ATTR_STATIC) {
- enum_fields.push_back(raw_field);
- }
- }
-
- return enum_fields;
-}
-#endif
-
-bool GDMonoClass::has_attribute(GDMonoClass *p_attr_class) {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_NULL_V(p_attr_class, false);
-#endif
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return false;
- }
-
- return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-MonoObject *GDMonoClass::get_attribute(GDMonoClass *p_attr_class) {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_NULL_V(p_attr_class, nullptr);
-#endif
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return nullptr;
- }
-
- return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-void GDMonoClass::fetch_attributes() {
- ERR_FAIL_COND(attributes != nullptr);
-
- attributes = mono_custom_attrs_from_class(get_mono_ptr());
- attrs_fetched = true;
-}
-
-void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base) {
- CRASH_COND(!CACHED_CLASS(GodotObject)->is_assignable_from(this));
-
- if (methods_fetched) {
- return;
- }
-
- void *iter = nullptr;
- MonoMethod *raw_method = nullptr;
- while ((raw_method = mono_class_get_methods(get_mono_ptr(), &iter)) != nullptr) {
- StringName name = String::utf8(mono_method_get_name(raw_method));
-
- // get_method implicitly fetches methods and adds them to this->methods
- GDMonoMethod *method = get_method(raw_method, name);
- ERR_CONTINUE(!method);
-
- if (method->get_name() != name) {
-#ifdef DEBUG_ENABLED
- String fullname = method->get_ret_type_full_name() + " " + name + "(" + method->get_signature_desc(true) + ")";
- WARN_PRINT("Method '" + fullname + "' is hidden by Godot API method. Should be '" +
- method->get_full_name_no_class() + "'. In class '" + namespace_name + "." + class_name + "'.");
-#endif
- continue;
- }
-
-#ifdef DEBUG_ENABLED
- // For debug builds, we also fetched from native base classes as well before if this is not a native base class.
- // This allows us to warn the user here if they are using snake_case by mistake.
-
- if (p_native_base != this) {
- GDMonoClass *native_top = p_native_base;
- while (native_top) {
- GDMonoMethod *m = native_top->get_method(name, method->get_parameters_count());
-
- if (m && m->get_name() != name) {
- // found
- String fullname = m->get_ret_type_full_name() + " " + name + "(" + m->get_signature_desc(true) + ")";
- WARN_PRINT("Method '" + fullname + "' should be '" + m->get_full_name_no_class() +
- "'. In class '" + namespace_name + "." + class_name + "'.");
- break;
- }
-
- if (native_top == CACHED_CLASS(GodotObject)) {
- break;
- }
-
- native_top = native_top->get_parent_class();
- }
- }
-#endif
-
- uint32_t flags = mono_method_get_flags(method->mono_method, nullptr);
-
- if (!(flags & MONO_METHOD_ATTR_VIRTUAL)) {
- continue;
- }
-
- // Virtual method of Godot Object derived type, let's try to find GodotMethod attribute
-
- GDMonoClass *top = p_native_base;
-
- while (top) {
- GDMonoMethod *base_method = top->get_method(name, method->get_parameters_count());
-
- if (base_method && base_method->has_attribute(CACHED_CLASS(GodotMethodAttribute))) {
- // Found base method with GodotMethod attribute.
- // We get the original API method name from this attribute.
- // This name must point to the virtual method.
-
- MonoObject *attr = base_method->get_attribute(CACHED_CLASS(GodotMethodAttribute));
-
- StringName godot_method_name = CACHED_FIELD(GodotMethodAttribute, methodName)->get_string_value(attr);
-#ifdef DEBUG_ENABLED
- CRASH_COND(godot_method_name == StringName());
-#endif
- MethodKey key = MethodKey(godot_method_name, method->get_parameters_count());
- GDMonoMethod **existing_method = methods.getptr(key);
- if (existing_method) {
- memdelete(*existing_method); // Must delete old one
- }
- methods.insert(key, method);
-
- break;
- }
-
- if (top == CACHED_CLASS(GodotObject)) {
- break;
- }
-
- top = top->get_parent_class();
- }
- }
-
- methods_fetched = true;
-}
-
-GDMonoMethod *GDMonoClass::get_fetched_method_unknown_params(const StringName &p_name) {
- ERR_FAIL_COND_V(!methods_fetched, nullptr);
-
- for (const KeyValue<MethodKey, GDMonoMethod *> &E : methods) {
- if (E.key.name == p_name) {
- return E.value;
- }
- }
-
- return nullptr;
-}
-
-bool GDMonoClass::has_fetched_method_unknown_params(const StringName &p_name) {
- return get_fetched_method_unknown_params(p_name) != nullptr;
-}
-
-bool GDMonoClass::implements_interface(GDMonoClass *p_interface) {
- return mono_class_implements_interface(mono_class, p_interface->get_mono_ptr());
-}
-
-bool GDMonoClass::has_public_parameterless_ctor() {
- GDMonoMethod *ctor = get_method(".ctor", 0);
- return ctor && ctor->get_visibility() == IMonoClassMember::PUBLIC;
-}
-
-GDMonoMethod *GDMonoClass::get_method(const StringName &p_name, uint16_t p_params_count) {
- MethodKey key = MethodKey(p_name, p_params_count);
-
- GDMonoMethod **match = methods.getptr(key);
-
- if (match) {
- return *match;
- }
-
- if (methods_fetched) {
- return nullptr;
- }
-
- MonoMethod *raw_method = mono_class_get_method_from_name(mono_class, String(p_name).utf8().get_data(), p_params_count);
-
- if (raw_method) {
- GDMonoMethod *method = memnew(GDMonoMethod(p_name, raw_method));
- methods.insert(key, method);
-
- return method;
- }
-
- return nullptr;
-}
-
-GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method) {
- MonoMethodSignature *sig = mono_method_signature(p_raw_method);
-
- int params_count = mono_signature_get_param_count(sig);
- StringName method_name = String::utf8(mono_method_get_name(p_raw_method));
-
- return get_method(p_raw_method, method_name, params_count);
-}
-
-GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name) {
- MonoMethodSignature *sig = mono_method_signature(p_raw_method);
- int params_count = mono_signature_get_param_count(sig);
- return get_method(p_raw_method, p_name, params_count);
-}
-
-GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name, uint16_t p_params_count) {
- ERR_FAIL_NULL_V(p_raw_method, nullptr);
-
- MethodKey key = MethodKey(p_name, p_params_count);
-
- GDMonoMethod **match = methods.getptr(key);
-
- if (match) {
- return *match;
- }
-
- GDMonoMethod *method = memnew(GDMonoMethod(p_name, p_raw_method));
- methods.insert(key, method);
-
- return method;
-}
-
-GDMonoMethod *GDMonoClass::get_method_with_desc(const String &p_description, bool p_include_namespace) {
- MonoMethodDesc *desc = mono_method_desc_new(p_description.utf8().get_data(), p_include_namespace);
- MonoMethod *method = mono_method_desc_search_in_class(desc, mono_class);
- mono_method_desc_free(desc);
-
- if (!method) {
- return nullptr;
- }
-
- ERR_FAIL_COND_V(mono_method_get_class(method) != mono_class, nullptr);
-
- return get_method(method);
-}
-
-GDMonoField *GDMonoClass::get_field(const StringName &p_name) {
- HashMap<StringName, GDMonoField *>::Iterator result = fields.find(p_name);
-
- if (result) {
- return result->value;
- }
-
- if (fields_fetched) {
- return nullptr;
- }
-
- MonoClassField *raw_field = mono_class_get_field_from_name(mono_class, String(p_name).utf8().get_data());
-
- if (raw_field) {
- GDMonoField *field = memnew(GDMonoField(raw_field, this));
- fields.insert(p_name, field);
-
- return field;
- }
-
- return nullptr;
-}
-
-const Vector<GDMonoField *> &GDMonoClass::get_all_fields() {
- if (fields_fetched) {
- return fields_list;
- }
-
- void *iter = nullptr;
- MonoClassField *raw_field = nullptr;
- while ((raw_field = mono_class_get_fields(mono_class, &iter)) != nullptr) {
- StringName name = String::utf8(mono_field_get_name(raw_field));
-
- HashMap<StringName, GDMonoField *>::Iterator match = fields.find(name);
-
- if (match) {
- fields_list.push_back(match->value);
- } else {
- GDMonoField *field = memnew(GDMonoField(raw_field, this));
- fields.insert(name, field);
- fields_list.push_back(field);
- }
- }
-
- fields_fetched = true;
-
- return fields_list;
-}
-
-GDMonoProperty *GDMonoClass::get_property(const StringName &p_name) {
- HashMap<StringName, GDMonoProperty *>::Iterator result = properties.find(p_name);
-
- if (result) {
- return result->value;
- }
-
- if (properties_fetched) {
- return nullptr;
- }
-
- MonoProperty *raw_property = mono_class_get_property_from_name(mono_class, String(p_name).utf8().get_data());
-
- if (raw_property) {
- GDMonoProperty *property = memnew(GDMonoProperty(raw_property, this));
- properties.insert(p_name, property);
-
- return property;
- }
-
- return nullptr;
-}
-
-const Vector<GDMonoProperty *> &GDMonoClass::get_all_properties() {
- if (properties_fetched) {
- return properties_list;
- }
-
- void *iter = nullptr;
- MonoProperty *raw_property = nullptr;
- while ((raw_property = mono_class_get_properties(mono_class, &iter)) != nullptr) {
- StringName name = String::utf8(mono_property_get_name(raw_property));
-
- HashMap<StringName, GDMonoProperty *>::Iterator match = properties.find(name);
-
- if (match) {
- properties_list.push_back(match->value);
- } else {
- GDMonoProperty *property = memnew(GDMonoProperty(raw_property, this));
- properties.insert(name, property);
- properties_list.push_back(property);
- }
- }
-
- properties_fetched = true;
-
- return properties_list;
-}
-
-const Vector<GDMonoClass *> &GDMonoClass::get_all_delegates() {
- if (delegates_fetched) {
- return delegates_list;
- }
-
- // If the class is generic we must use the generic type definition.
- MonoClass *klass = mono_class;
- if (mono_type_get_type(get_mono_type()) == MONO_TYPE_GENERICINST) {
- MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), get_mono_type());
- GDMonoUtils::Marshal::get_generic_type_definition(reftype, &reftype);
- MonoType *type = mono_reflection_type_get_type(reftype);
- klass = mono_class_from_mono_type(type);
- }
-
- void *iter = nullptr;
- MonoClass *raw_class = nullptr;
- while ((raw_class = mono_class_get_nested_types(klass, &iter)) != nullptr) {
- if (mono_class_is_delegate(raw_class)) {
- StringName name = String::utf8(mono_class_get_name(raw_class));
-
- HashMap<StringName, GDMonoClass *>::Iterator match = delegates.find(name);
-
- if (match) {
- delegates_list.push_back(match->value);
- } else {
- GDMonoClass *delegate = memnew(GDMonoClass(String::utf8(mono_class_get_namespace(raw_class)), String::utf8(mono_class_get_name(raw_class)), raw_class, assembly));
- delegates.insert(name, delegate);
- delegates_list.push_back(delegate);
- }
- }
- }
-
- delegates_fetched = true;
-
- return delegates_list;
-}
-
-const Vector<GDMonoMethod *> &GDMonoClass::get_all_methods() {
- if (!method_list_fetched) {
- void *iter = nullptr;
- MonoMethod *raw_method = nullptr;
- while ((raw_method = mono_class_get_methods(get_mono_ptr(), &iter)) != nullptr) {
- method_list.push_back(memnew(GDMonoMethod(String::utf8(mono_method_get_name(raw_method)), raw_method)));
- }
-
- method_list_fetched = true;
- }
-
- return method_list;
-}
-
-GDMonoClass::GDMonoClass(const StringName &p_namespace, const StringName &p_name, MonoClass *p_class, GDMonoAssembly *p_assembly) {
- namespace_name = p_namespace;
- class_name = p_name;
- mono_class = p_class;
- assembly = p_assembly;
-
- attrs_fetched = false;
- attributes = nullptr;
-
- methods_fetched = false;
- method_list_fetched = false;
- fields_fetched = false;
- properties_fetched = false;
- delegates_fetched = false;
-}
-
-GDMonoClass::~GDMonoClass() {
- if (attributes) {
- mono_custom_attrs_free(attributes);
- }
-
- for (const KeyValue<StringName, GDMonoField *> &E : fields) {
- memdelete(E.value);
- }
-
- for (const KeyValue<StringName, GDMonoProperty *> &E : properties) {
- memdelete(E.value);
- }
-
- {
- // Ugly workaround...
- // We may have duplicated values, because we redirect snake_case methods to PascalCasel (only Godot API methods).
- // This way, we end with both the snake_case name and the PascalCasel name paired with the same method.
- // Therefore, we must avoid deleting the same pointer twice.
-
- int offset = 0;
- Vector<GDMonoMethod *> deleted_methods;
- deleted_methods.resize(methods.size());
-
- for (const KeyValue<MethodKey, GDMonoMethod *> &E : methods) {
- GDMonoMethod *method = E.value;
-
- if (method) {
- for (int i = 0; i < offset; i++) {
- if (deleted_methods[i] == method) {
- // Already deleted
- goto already_deleted;
- }
- }
-
- deleted_methods.write[offset] = method;
- ++offset;
-
- memdelete(method);
- }
-
- already_deleted:;
- }
-
- methods.clear();
- }
-
- for (int i = 0; i < method_list.size(); ++i) {
- memdelete(method_list[i]);
- }
-}
diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h
deleted file mode 100644
index 6b35da30f9..0000000000
--- a/modules/mono/mono_gd/gd_mono_class.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/*************************************************************************/
-/* gd_mono_class.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 GD_MONO_CLASS_H
-#define GD_MONO_CLASS_H
-
-#include "core/string/ustring.h"
-#include "core/templates/rb_map.h"
-
-#include "gd_mono_field.h"
-#include "gd_mono_header.h"
-#include "gd_mono_method.h"
-#include "gd_mono_property.h"
-#include "gd_mono_utils.h"
-
-class GDMonoClass {
- struct MethodKey {
- struct Hasher {
- static _FORCE_INLINE_ uint32_t hash(const MethodKey &p_key) {
- uint32_t hash = 0;
-
- GDMonoUtils::hash_combine(hash, p_key.name.hash());
- GDMonoUtils::hash_combine(hash, HashMapHasherDefault::hash(p_key.params_count));
-
- return hash;
- }
- };
-
- _FORCE_INLINE_ bool operator==(const MethodKey &p_a) const {
- return p_a.params_count == params_count && p_a.name == name;
- }
-
- MethodKey() {}
-
- MethodKey(const StringName &p_name, uint16_t p_params_count) :
- name(p_name), params_count(p_params_count) {
- }
-
- StringName name;
- uint16_t params_count = 0;
- };
-
- StringName namespace_name;
- StringName class_name;
-
- MonoClass *mono_class = nullptr;
- GDMonoAssembly *assembly = nullptr;
-
- bool attrs_fetched;
- MonoCustomAttrInfo *attributes = nullptr;
-
- // This contains both the original method names and remapped method names from the native Godot identifiers to the C# functions.
- // Most method-related functions refer to this and it's possible this is unintuitive for outside users; this may be a prime location for refactoring or renaming.
- bool methods_fetched;
- HashMap<MethodKey, GDMonoMethod *, MethodKey::Hasher> methods;
-
- bool method_list_fetched;
- Vector<GDMonoMethod *> method_list;
-
- bool fields_fetched;
- HashMap<StringName, GDMonoField *> fields;
- Vector<GDMonoField *> fields_list;
-
- bool properties_fetched;
- HashMap<StringName, GDMonoProperty *> properties;
- Vector<GDMonoProperty *> properties_list;
-
- bool delegates_fetched;
- HashMap<StringName, GDMonoClass *> delegates;
- Vector<GDMonoClass *> delegates_list;
-
- friend class GDMonoAssembly;
- GDMonoClass(const StringName &p_namespace, const StringName &p_name, MonoClass *p_class, GDMonoAssembly *p_assembly);
-
-public:
- static String get_full_name(MonoClass *p_mono_class);
- static MonoType *get_mono_type(MonoClass *p_mono_class);
-
- String get_full_name() const;
- String get_type_desc() const;
- MonoType *get_mono_type() const;
-
- uint32_t get_flags() const;
- bool is_static() const;
-
- bool is_assignable_from(GDMonoClass *p_from) const;
-
- StringName get_namespace() const;
- _FORCE_INLINE_ StringName get_name() const { return class_name; }
- String get_name_for_lookup() const;
-
- _FORCE_INLINE_ MonoClass *get_mono_ptr() const { return mono_class; }
- _FORCE_INLINE_ const GDMonoAssembly *get_assembly() const { return assembly; }
-
- GDMonoClass *get_parent_class() const;
- GDMonoClass *get_nesting_class() const;
-
-#ifdef TOOLS_ENABLED
- Vector<MonoClassField *> get_enum_fields();
-#endif
-
- GDMonoMethod *get_fetched_method_unknown_params(const StringName &p_name);
- bool has_fetched_method_unknown_params(const StringName &p_name);
-
- bool has_attribute(GDMonoClass *p_attr_class);
- MonoObject *get_attribute(GDMonoClass *p_attr_class);
-
- void fetch_attributes();
- void fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base);
-
- bool implements_interface(GDMonoClass *p_interface);
- bool has_public_parameterless_ctor();
-
- GDMonoMethod *get_method(const StringName &p_name, uint16_t p_params_count = 0);
- GDMonoMethod *get_method(MonoMethod *p_raw_method);
- GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name);
- GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name, uint16_t p_params_count);
- GDMonoMethod *get_method_with_desc(const String &p_description, bool p_include_namespace);
-
- GDMonoField *get_field(const StringName &p_name);
- const Vector<GDMonoField *> &get_all_fields();
-
- GDMonoProperty *get_property(const StringName &p_name);
- const Vector<GDMonoProperty *> &get_all_properties();
-
- const Vector<GDMonoClass *> &get_all_delegates();
-
- const Vector<GDMonoMethod *> &get_all_methods();
-
- ~GDMonoClass();
-};
-
-#endif // GD_MONO_CLASS_H
diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp
deleted file mode 100644
index cb025fc67a..0000000000
--- a/modules/mono/mono_gd/gd_mono_field.cpp
+++ /dev/null
@@ -1,556 +0,0 @@
-/*************************************************************************/
-/* gd_mono_field.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 "gd_mono_field.h"
-
-#include <mono/metadata/attrdefs.h>
-
-#include "gd_mono_cache.h"
-#include "gd_mono_class.h"
-#include "gd_mono_marshal.h"
-#include "gd_mono_utils.h"
-
-void GDMonoField::set_value(MonoObject *p_object, MonoObject *p_value) {
- mono_field_set_value(p_object, mono_field, p_value);
-}
-
-void GDMonoField::set_value_raw(MonoObject *p_object, void *p_ptr) {
- mono_field_set_value(p_object, mono_field, &p_ptr);
-}
-
-void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_value) {
- switch (type.type_encoding) {
- case MONO_TYPE_BOOLEAN: {
- MonoBoolean val = p_value.operator bool();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_CHAR: {
- int16_t val = p_value.operator unsigned short();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_I1: {
- int8_t val = p_value.operator signed char();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_I2: {
- int16_t val = p_value.operator signed short();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_I4: {
- int32_t val = p_value.operator signed int();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_I8: {
- int64_t val = p_value.operator int64_t();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_U1: {
- uint8_t val = p_value.operator unsigned char();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_U2: {
- uint16_t val = p_value.operator unsigned short();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_U4: {
- uint32_t val = p_value.operator unsigned int();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_U8: {
- uint64_t val = p_value.operator uint64_t();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_R4: {
- float val = p_value.operator float();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_R8: {
- double val = p_value.operator double();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case MONO_TYPE_VALUETYPE: {
- GDMonoClass *tclass = type.type_class;
-
- if (tclass == CACHED_CLASS(Vector2)) {
- GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_value.operator ::Vector2());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Vector2i)) {
- GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_value.operator ::Vector2i());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Rect2)) {
- GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_value.operator ::Rect2());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Rect2i)) {
- GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_value.operator ::Rect2i());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Transform2D)) {
- GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_value.operator ::Transform2D());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Vector3)) {
- GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_value.operator ::Vector3());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Vector3i)) {
- GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_value.operator ::Vector3i());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Vector4)) {
- GDMonoMarshal::M_Vector4 from = MARSHALLED_OUT(Vector4, p_value.operator ::Vector4());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Vector4i)) {
- GDMonoMarshal::M_Vector4i from = MARSHALLED_OUT(Vector4i, p_value.operator ::Vector4i());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Basis)) {
- GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_value.operator ::Basis());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Quaternion)) {
- GDMonoMarshal::M_Quaternion from = MARSHALLED_OUT(Quaternion, p_value.operator ::Quaternion());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Transform3D)) {
- GDMonoMarshal::M_Transform3D from = MARSHALLED_OUT(Transform3D, p_value.operator ::Transform3D());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Projection)) {
- GDMonoMarshal::M_Projection from = MARSHALLED_OUT(Projection, p_value.operator ::Projection());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(AABB)) {
- GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_value.operator ::AABB());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Color)) {
- GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_value.operator ::Color());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Plane)) {
- GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_value.operator ::Plane());
- mono_field_set_value(p_object, mono_field, &from);
- break;
- }
-
- if (tclass == CACHED_CLASS(Callable)) {
- GDMonoMarshal::M_Callable val = GDMonoMarshal::callable_to_managed(p_value.operator Callable());
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
-
- if (tclass == CACHED_CLASS(SignalInfo)) {
- GDMonoMarshal::M_SignalInfo val = GDMonoMarshal::signal_info_to_managed(p_value.operator Signal());
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
-
- if (mono_class_is_enum(tclass->get_mono_ptr())) {
- MonoType *enum_basetype = mono_class_enum_basetype(tclass->get_mono_ptr());
- switch (mono_type_get_type(enum_basetype)) {
- case MONO_TYPE_BOOLEAN: {
- MonoBoolean val = p_value.operator bool();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_CHAR: {
- uint16_t val = p_value.operator unsigned short();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_I1: {
- int8_t val = p_value.operator signed char();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_I2: {
- int16_t val = p_value.operator signed short();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_I4: {
- int32_t val = p_value.operator signed int();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_I8: {
- int64_t val = p_value.operator int64_t();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_U1: {
- uint8_t val = p_value.operator unsigned char();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_U2: {
- uint16_t val = p_value.operator unsigned short();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_U4: {
- uint32_t val = p_value.operator unsigned int();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- case MONO_TYPE_U8: {
- uint64_t val = p_value.operator uint64_t();
- mono_field_set_value(p_object, mono_field, &val);
- break;
- }
- default: {
- ERR_FAIL_MSG("Attempted to convert Variant to a managed enum value of unmarshallable base type.");
- }
- }
-
- break;
- }
-
- ERR_FAIL_MSG("Attempted to set the value of a field of unmarshallable type: '" + tclass->get_name() + "'.");
- } break;
- case MONO_TYPE_STRING: {
- if (p_value.get_type() == Variant::NIL) {
- // Otherwise, Variant -> String would return the string "Null"
- MonoString *mono_string = nullptr;
- mono_field_set_value(p_object, mono_field, mono_string);
- } else {
- MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value);
- mono_field_set_value(p_object, mono_field, mono_string);
- }
- } break;
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY: {
- MonoArray *managed = GDMonoMarshal::variant_to_mono_array(p_value, type.type_class);
- if (likely(managed != nullptr)) {
- mono_field_set_value(p_object, mono_field, managed);
- }
- } break;
- case MONO_TYPE_CLASS: {
- MonoObject *managed = GDMonoMarshal::variant_to_mono_object_of_class(p_value, type.type_class);
- if (likely(managed != nullptr)) {
- mono_field_set_value(p_object, mono_field, managed);
- }
- } break;
- case MONO_TYPE_GENERICINST: {
- MonoObject *managed = GDMonoMarshal::variant_to_mono_object_of_genericinst(p_value, type.type_class);
- if (likely(managed != nullptr)) {
- mono_field_set_value(p_object, mono_field, managed);
- }
- } break;
- case MONO_TYPE_OBJECT: {
- // Variant
- switch (p_value.get_type()) {
- case Variant::BOOL: {
- MonoBoolean val = p_value.operator bool();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case Variant::INT: {
- int32_t val = p_value.operator signed int();
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case Variant::FLOAT: {
-#ifdef REAL_T_IS_DOUBLE
- double val = p_value.operator double();
- mono_field_set_value(p_object, mono_field, &val);
-#else
- float val = p_value.operator float();
- mono_field_set_value(p_object, mono_field, &val);
-#endif
- } break;
- case Variant::STRING: {
- MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value);
- mono_field_set_value(p_object, mono_field, mono_string);
- } break;
- case Variant::VECTOR2: {
- GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_value.operator ::Vector2());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::VECTOR2I: {
- GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_value.operator ::Vector2i());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::RECT2: {
- GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_value.operator ::Rect2());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::RECT2I: {
- GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_value.operator ::Rect2i());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::VECTOR3: {
- GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_value.operator ::Vector3());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::VECTOR3I: {
- GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_value.operator ::Vector3i());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::VECTOR4: {
- GDMonoMarshal::M_Vector4 from = MARSHALLED_OUT(Vector4, p_value.operator ::Vector4());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::VECTOR4I: {
- GDMonoMarshal::M_Vector4i from = MARSHALLED_OUT(Vector4i, p_value.operator ::Vector4i());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::TRANSFORM2D: {
- GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_value.operator ::Transform2D());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::PLANE: {
- GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_value.operator ::Plane());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::QUATERNION: {
- GDMonoMarshal::M_Quaternion from = MARSHALLED_OUT(Quaternion, p_value.operator ::Quaternion());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::AABB: {
- GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_value.operator ::AABB());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::BASIS: {
- GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_value.operator ::Basis());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::TRANSFORM3D: {
- GDMonoMarshal::M_Transform3D from = MARSHALLED_OUT(Transform3D, p_value.operator ::Transform3D());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::PROJECTION: {
- GDMonoMarshal::M_Projection from = MARSHALLED_OUT(Projection, p_value.operator ::Projection());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::COLOR: {
- GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_value.operator ::Color());
- mono_field_set_value(p_object, mono_field, &from);
- } break;
- case Variant::STRING_NAME: {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator StringName());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::NODE_PATH: {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator NodePath());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::RID: {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator ::RID());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::OBJECT: {
- MonoObject *managed = GDMonoUtils::unmanaged_get_managed(p_value.operator Object *());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::CALLABLE: {
- GDMonoMarshal::M_Callable val = GDMonoMarshal::callable_to_managed(p_value.operator Callable());
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case Variant::SIGNAL: {
- GDMonoMarshal::M_SignalInfo val = GDMonoMarshal::signal_info_to_managed(p_value.operator Signal());
- mono_field_set_value(p_object, mono_field, &val);
- } break;
- case Variant::DICTIONARY: {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), CACHED_CLASS(Dictionary));
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::ARRAY: {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_BYTE_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedByteArray_to_mono_array(p_value.operator ::PackedByteArray());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_INT32_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedInt32Array_to_mono_array(p_value.operator ::PackedInt32Array());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_INT64_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedInt64Array_to_mono_array(p_value.operator ::PackedInt64Array());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_FLOAT32_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedFloat32Array_to_mono_array(p_value.operator ::PackedFloat32Array());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_FLOAT64_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedFloat64Array_to_mono_array(p_value.operator ::PackedFloat64Array());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_STRING_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedStringArray_to_mono_array(p_value.operator ::PackedStringArray());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_VECTOR2_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedVector2Array_to_mono_array(p_value.operator ::PackedVector2Array());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_VECTOR3_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedVector3Array_to_mono_array(p_value.operator ::PackedVector3Array());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- case Variant::PACKED_COLOR_ARRAY: {
- MonoArray *managed = GDMonoMarshal::PackedColorArray_to_mono_array(p_value.operator ::PackedColorArray());
- mono_field_set_value(p_object, mono_field, managed);
- } break;
- default:
- break;
- }
- } break;
- default: {
- ERR_PRINT("Attempted to set the value of a field of unexpected type encoding: " + itos(type.type_encoding) + ".");
- } break;
- }
-}
-
-MonoObject *GDMonoField::get_value(MonoObject *p_object) {
- return mono_field_get_value_object(mono_domain_get(), mono_field, p_object);
-}
-
-bool GDMonoField::get_bool_value(MonoObject *p_object) {
- return (bool)GDMonoMarshal::unbox<MonoBoolean>(get_value(p_object));
-}
-
-int GDMonoField::get_int_value(MonoObject *p_object) {
- return GDMonoMarshal::unbox<int32_t>(get_value(p_object));
-}
-
-String GDMonoField::get_string_value(MonoObject *p_object) {
- MonoObject *val = get_value(p_object);
- return GDMonoMarshal::mono_string_to_godot((MonoString *)val);
-}
-
-bool GDMonoField::has_attribute(GDMonoClass *p_attr_class) {
- ERR_FAIL_NULL_V(p_attr_class, false);
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return false;
- }
-
- return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-MonoObject *GDMonoField::get_attribute(GDMonoClass *p_attr_class) {
- ERR_FAIL_NULL_V(p_attr_class, nullptr);
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return nullptr;
- }
-
- return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-void GDMonoField::fetch_attributes() {
- ERR_FAIL_COND(attributes != nullptr);
- attributes = mono_custom_attrs_from_field(owner->get_mono_ptr(), mono_field);
- attrs_fetched = true;
-}
-
-bool GDMonoField::is_static() {
- return mono_field_get_flags(mono_field) & MONO_FIELD_ATTR_STATIC;
-}
-
-IMonoClassMember::Visibility GDMonoField::get_visibility() {
- switch (mono_field_get_flags(mono_field) & MONO_FIELD_ATTR_FIELD_ACCESS_MASK) {
- case MONO_FIELD_ATTR_PRIVATE:
- return IMonoClassMember::PRIVATE;
- case MONO_FIELD_ATTR_FAM_AND_ASSEM:
- return IMonoClassMember::PROTECTED_AND_INTERNAL;
- case MONO_FIELD_ATTR_ASSEMBLY:
- return IMonoClassMember::INTERNAL;
- case MONO_FIELD_ATTR_FAMILY:
- return IMonoClassMember::PROTECTED;
- case MONO_FIELD_ATTR_PUBLIC:
- return IMonoClassMember::PUBLIC;
- default:
- ERR_FAIL_V(IMonoClassMember::PRIVATE);
- }
-}
-
-GDMonoField::GDMonoField(MonoClassField *p_mono_field, GDMonoClass *p_owner) {
- owner = p_owner;
- mono_field = p_mono_field;
- name = String::utf8(mono_field_get_name(mono_field));
- MonoType *field_type = mono_field_get_type(mono_field);
- type.type_encoding = mono_type_get_type(field_type);
- MonoClass *field_type_class = mono_class_from_mono_type(field_type);
- type.type_class = GDMono::get_singleton()->get_class(field_type_class);
-
- attrs_fetched = false;
- attributes = nullptr;
-}
-
-GDMonoField::~GDMonoField() {
- if (attributes) {
- mono_custom_attrs_free(attributes);
- }
-}
diff --git a/modules/mono/mono_gd/gd_mono_field.h b/modules/mono/mono_gd/gd_mono_field.h
deleted file mode 100644
index 1d30f7a369..0000000000
--- a/modules/mono/mono_gd/gd_mono_field.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*************************************************************************/
-/* gd_mono_field.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 GD_MONO_FIELD_H
-#define GD_MONO_FIELD_H
-
-#include "gd_mono.h"
-#include "gd_mono_header.h"
-#include "i_mono_class_member.h"
-
-class GDMonoField : public IMonoClassMember {
- GDMonoClass *owner = nullptr;
- MonoClassField *mono_field = nullptr;
-
- StringName name;
- ManagedType type;
-
- bool attrs_fetched;
- MonoCustomAttrInfo *attributes = nullptr;
-
-public:
- virtual GDMonoClass *get_enclosing_class() const final { return owner; }
-
- virtual MemberType get_member_type() const final { return MEMBER_TYPE_FIELD; }
-
- virtual StringName get_name() const final { return name; }
-
- virtual bool is_static() final;
- virtual Visibility get_visibility() final;
-
- virtual bool has_attribute(GDMonoClass *p_attr_class) final;
- virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) final;
- void fetch_attributes();
-
- _FORCE_INLINE_ ManagedType get_type() const { return type; }
-
- void set_value(MonoObject *p_object, MonoObject *p_value);
- void set_value_raw(MonoObject *p_object, void *p_ptr);
- void set_value_from_variant(MonoObject *p_object, const Variant &p_value);
-
- MonoObject *get_value(MonoObject *p_object);
-
- bool get_bool_value(MonoObject *p_object);
- int get_int_value(MonoObject *p_object);
- String get_string_value(MonoObject *p_object);
-
- GDMonoField(MonoClassField *p_mono_field, GDMonoClass *p_owner);
- ~GDMonoField();
-};
-
-#endif // GD_MONO_FIELD_H
diff --git a/modules/mono/mono_gd/gd_mono_header.h b/modules/mono/mono_gd/gd_mono_header.h
deleted file mode 100644
index bf21283080..0000000000
--- a/modules/mono/mono_gd/gd_mono_header.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*************************************************************************/
-/* gd_mono_header.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 GD_MONO_HEADER_H
-#define GD_MONO_HEADER_H
-
-#include <cstdint>
-
-#ifdef WIN32
-#define GD_MONO_STDCALL __stdcall
-#else
-#define GD_MONO_STDCALL
-#endif
-
-class GDMonoAssembly;
-class GDMonoClass;
-class GDMonoField;
-class GDMonoMethod;
-class GDMonoProperty;
-
-class IMonoClassMember;
-
-#include "managed_type.h"
-
-#endif // GD_MONO_HEADER_H
diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp
deleted file mode 100644
index d206b0dfc3..0000000000
--- a/modules/mono/mono_gd/gd_mono_internals.cpp
+++ /dev/null
@@ -1,145 +0,0 @@
-/*************************************************************************/
-/* gd_mono_internals.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 "gd_mono_internals.h"
-
-#include "../csharp_script.h"
-#include "../mono_gc_handle.h"
-#include "../utils/macros.h"
-#include "gd_mono_class.h"
-#include "gd_mono_marshal.h"
-#include "gd_mono_utils.h"
-
-#include "core/debugger/engine_debugger.h"
-#include "core/debugger/script_debugger.h"
-
-#include <mono/metadata/exception.h>
-
-namespace GDMonoInternals {
-void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) {
- // This method should not fail
-
- CRASH_COND(!unmanaged);
-
- // All mono objects created from the managed world (e.g.: 'new Player()')
- // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
-
- RefCounted *rc = Object::cast_to<RefCounted>(unmanaged);
-
- GDMonoClass *klass = GDMonoUtils::get_object_class(managed);
-
- CRASH_COND(!klass);
-
- GDMonoClass *native = GDMonoUtils::get_class_native_base(klass);
-
- CRASH_COND(native == nullptr);
-
- if (native == klass) {
- // If it's just a wrapper Godot class and not a custom inheriting class, then attach a
- // script binding instead. One of the advantages of this is that if a script is attached
- // later and it's not a C# script, then the managed object won't have to be disposed.
- // Another reason for doing this is that this instance could outlive CSharpLanguage, which would
- // be problematic when using a script. See: https://github.com/godotengine/godot/issues/25621
-
- CSharpScriptBinding script_binding;
-
- script_binding.inited = true;
- script_binding.type_name = NATIVE_GDMONOCLASS_NAME(klass);
- script_binding.wrapper_class = klass;
- script_binding.gchandle = rc ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed);
- script_binding.owner = unmanaged;
-
- if (rc) {
- // Unsafe refcount increment. The managed instance also counts as a reference.
- // This way if the unmanaged world has no references to our owner
- // but the managed instance is alive, the refcount will be 1 instead of 0.
- // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
-
- // May not me referenced yet, so we must use init_ref() instead of reference()
- if (rc->init_ref()) {
- CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
- }
- }
-
- // The object was just created, no script instance binding should have been attached
- CRASH_COND(CSharpLanguage::has_instance_binding(unmanaged));
-
- void *data;
- {
- MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
- data = (void *)CSharpLanguage::get_singleton()->insert_script_binding(unmanaged, script_binding);
- }
-
- // Should be thread safe because the object was just created and nothing else should be referencing it
- CSharpLanguage::set_instance_binding(unmanaged, data);
-
- return;
- }
-
- MonoGCHandleData gchandle = rc ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed);
-
- Ref<CSharpScript> script = CSharpScript::create_for_managed_type(klass, native);
-
- CRASH_COND(script.is_null());
-
- CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(unmanaged, script.ptr(), gchandle);
-
- unmanaged->set_script_and_instance(script, csharp_instance);
-}
-
-void unhandled_exception(MonoException *p_exc) {
- mono_print_unhandled_exception((MonoObject *)p_exc);
- gd_unhandled_exception_event(p_exc);
-
- if (GDMono::get_singleton()->get_unhandled_exception_policy() == GDMono::POLICY_TERMINATE_APP) {
- // Too bad 'mono_invoke_unhandled_exception_hook' is not exposed to embedders
- mono_unhandled_exception((MonoObject *)p_exc);
- GDMono::unhandled_exception_hook((MonoObject *)p_exc, nullptr);
- GD_UNREACHABLE();
- } else {
-#ifdef DEBUG_ENABLED
- GDMonoUtils::debug_send_unhandled_exception_error(p_exc);
- if (EngineDebugger::is_active()) {
- EngineDebugger::get_singleton()->poll_events(false);
- }
-#endif
- }
-}
-
-void gd_unhandled_exception_event(MonoException *p_exc) {
- MonoImage *mono_image = GDMono::get_singleton()->get_core_api_assembly()->get_image();
-
- MonoClass *gd_klass = mono_class_from_name(mono_image, "Godot", "GD");
- MonoMethod *unhandled_exception_method = mono_class_get_method_from_name(gd_klass, "OnUnhandledException", -1);
- void *args[1];
- args[0] = p_exc;
- mono_runtime_invoke(unhandled_exception_method, nullptr, (void **)args, nullptr);
-}
-} // namespace GDMonoInternals
diff --git a/modules/mono/mono_gd/gd_mono_internals.h b/modules/mono/mono_gd/gd_mono_internals.h
deleted file mode 100644
index a8f9cfa3ca..0000000000
--- a/modules/mono/mono_gd/gd_mono_internals.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*************************************************************************/
-/* gd_mono_internals.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 GD_MONO_INTERNALS_H
-#define GD_MONO_INTERNALS_H
-
-#include <mono/jit/jit.h>
-
-#include "../utils/macros.h"
-
-#include "core/object/class_db.h"
-
-namespace GDMonoInternals {
-void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged);
-
-/**
- * Do not call this function directly.
- * Use GDMonoUtils::debug_unhandled_exception(MonoException *) instead.
- */
-void unhandled_exception(MonoException *p_exc);
-
-void gd_unhandled_exception_event(MonoException *p_exc);
-} // namespace GDMonoInternals
-
-#endif // GD_MONO_INTERNALS_H
diff --git a/modules/mono/mono_gd/gd_mono_log.cpp b/modules/mono/mono_gd/gd_mono_log.cpp
deleted file mode 100644
index 6ea3c5539e..0000000000
--- a/modules/mono/mono_gd/gd_mono_log.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-/*************************************************************************/
-/* gd_mono_log.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 "gd_mono_log.h"
-
-#include <stdlib.h> // abort
-
-#include "core/io/dir_access.h"
-#include "core/os/os.h"
-
-#include "../godotsharp_dirs.h"
-#include "../utils/string_utils.h"
-
-static CharString get_default_log_level() {
-#ifdef DEBUG_ENABLED
- return String("info").utf8();
-#else
- return String("warning").utf8();
-#endif
-}
-
-GDMonoLog *GDMonoLog::singleton = nullptr;
-
-#ifdef GD_MONO_LOG_ENABLED
-
-static int get_log_level_id(const char *p_log_level) {
- const char *valid_log_levels[] = { "error", "critical", "warning", "message", "info", "debug", nullptr };
-
- int i = 0;
- while (valid_log_levels[i]) {
- if (!strcmp(valid_log_levels[i], p_log_level)) {
- return i;
- }
- i++;
- }
-
- return -1;
-}
-
-static String make_text(const char *log_domain, const char *log_level, const char *message) {
- String text(message);
- text += " (in domain ";
- text += log_domain;
- if (log_level) {
- text += ", ";
- text += log_level;
- }
- text += ")";
- return text;
-}
-
-void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *) {
- if (GDMonoLog::get_singleton()->log_level_id >= get_log_level_id(log_level)) {
- String text = make_text(log_domain, log_level, message);
- text += "\n";
-
- GDMonoLog::get_singleton()->log_file->seek_end();
- GDMonoLog::get_singleton()->log_file->store_string(text);
- }
-
- if (fatal) {
- String text = make_text(log_domain, log_level, message);
- ERR_PRINT("Mono: FATAL ERROR '" + text + "', ABORTING! Logfile: '" + GDMonoLog::get_singleton()->log_file_path + "'.");
- // Make sure to flush before aborting
- GDMonoLog::get_singleton()->log_file->flush();
- GDMonoLog::get_singleton()->log_file.unref();
-
- abort();
- }
-}
-
-bool GDMonoLog::_try_create_logs_dir(const String &p_logs_dir) {
- if (!DirAccess::exists(p_logs_dir)) {
- Ref<DirAccess> diraccess = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- ERR_FAIL_COND_V(diraccess.is_null(), false);
- Error logs_mkdir_err = diraccess->make_dir_recursive(p_logs_dir);
- ERR_FAIL_COND_V_MSG(logs_mkdir_err != OK, false, "Failed to create mono logs directory.");
- }
-
- return true;
-}
-
-void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) {
- static const uint64_t MAX_SECS = 5 * 86400; // 5 days
-
- Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- ERR_FAIL_COND(da.is_null());
-
- Error err = da->change_dir(p_logs_dir);
- ERR_FAIL_COND_MSG(err != OK, "Cannot change directory to '" + p_logs_dir + "'.");
-
- ERR_FAIL_COND(da->list_dir_begin() != OK);
-
- String current = da->get_next();
- while (!current.is_empty()) {
- if (da->current_is_dir() || !current.ends_with(".txt")) {
- current = da->get_next();
- continue;
- }
-
- uint64_t modified_time = FileAccess::get_modified_time(da->get_current_dir().plus_file(current));
-
- if (OS::get_singleton()->get_unix_time() - modified_time > MAX_SECS) {
- da->remove(current);
- }
- current = da->get_next();
- }
-
- da->list_dir_end();
-}
-
-void GDMonoLog::initialize() {
- CharString log_level = OS::get_singleton()->get_environment("GODOT_MONO_LOG_LEVEL").utf8();
-
- if (log_level.length() != 0 && get_log_level_id(log_level.get_data()) == -1) {
- ERR_PRINT(String() + "Mono: Ignoring invalid log level (GODOT_MONO_LOG_LEVEL): '" + log_level.get_data() + "'.");
- log_level = CharString();
- }
-
- if (log_level.length() == 0) {
- log_level = get_default_log_level();
- }
-
- String logs_dir = GodotSharpDirs::get_mono_logs_dir();
-
- if (_try_create_logs_dir(logs_dir)) {
- _delete_old_log_files(logs_dir);
-
- OS::Date date_now = OS::get_singleton()->get_date();
- OS::Time time_now = OS::get_singleton()->get_time();
-
- String log_file_name = str_format("%04d-%02d-%02d_%02d.%02d.%02d",
- (int)date_now.year, (int)date_now.month, (int)date_now.day,
- (int)time_now.hour, (int)time_now.minute, (int)time_now.second);
-
- log_file_name += str_format("_%d", OS::get_singleton()->get_process_id());
-
- log_file_name += ".log";
-
- log_file_path = logs_dir.plus_file(log_file_name);
-
- log_file = FileAccess::open(log_file_path, FileAccess::WRITE);
- if (log_file.is_null()) {
- ERR_PRINT("Mono: Cannot create log file at: " + log_file_path);
- }
- }
-
- mono_trace_set_level_string(log_level.get_data());
- log_level_id = get_log_level_id(log_level.get_data());
-
- if (log_file.is_valid()) {
- OS::get_singleton()->print("Mono: Log file is: '%s'\n", log_file_path.utf8().get_data());
- mono_trace_set_log_handler(mono_log_callback, this);
- } else {
- OS::get_singleton()->printerr("Mono: No log file, using default log handler\n");
- }
-}
-
-GDMonoLog::GDMonoLog() {
- singleton = this;
-}
-
-GDMonoLog::~GDMonoLog() {
- singleton = nullptr;
-}
-
-#else
-
-void GDMonoLog::initialize() {
- CharString log_level = get_default_log_level();
- mono_trace_set_level_string(log_level.get_data());
-}
-
-GDMonoLog::GDMonoLog() {
- singleton = this;
-}
-
-GDMonoLog::~GDMonoLog() {
- singleton = nullptr;
-}
-
-#endif // !defined(JAVASCRIPT_ENABLED)
diff --git a/modules/mono/mono_gd/gd_mono_log.h b/modules/mono/mono_gd/gd_mono_log.h
deleted file mode 100644
index 93ba6a410e..0000000000
--- a/modules/mono/mono_gd/gd_mono_log.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*************************************************************************/
-/* gd_mono_log.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 GD_MONO_LOG_H
-#define GD_MONO_LOG_H
-
-#include <mono/utils/mono-logger.h>
-
-#include "core/typedefs.h"
-
-#if !defined(JAVASCRIPT_ENABLED) && !defined(IOS_ENABLED)
-// We have custom mono log callbacks for WASM and iOS
-#define GD_MONO_LOG_ENABLED
-#endif
-
-#ifdef GD_MONO_LOG_ENABLED
-#include "core/io/file_access.h"
-#endif
-
-class GDMonoLog {
-#ifdef GD_MONO_LOG_ENABLED
- int log_level_id = -1;
-
- Ref<FileAccess> log_file;
- String log_file_path;
-
- bool _try_create_logs_dir(const String &p_logs_dir);
- void _delete_old_log_files(const String &p_logs_dir);
-
- static void mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data);
-#endif
-
- static GDMonoLog *singleton;
-
-public:
- _FORCE_INLINE_ static GDMonoLog *get_singleton() { return singleton; }
-
- void initialize();
-
- GDMonoLog();
- ~GDMonoLog();
-};
-
-#endif // GD_MONO_LOG_H
diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp
deleted file mode 100644
index a860442764..0000000000
--- a/modules/mono/mono_gd/gd_mono_marshal.cpp
+++ /dev/null
@@ -1,1824 +0,0 @@
-/*************************************************************************/
-/* gd_mono_marshal.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 "gd_mono_marshal.h"
-
-#include "../signal_awaiter_utils.h"
-#include "gd_mono.h"
-#include "gd_mono_cache.h"
-#include "gd_mono_class.h"
-
-namespace GDMonoMarshal {
-
-Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_variant) {
- switch (p_type.type_encoding) {
- case MONO_TYPE_BOOLEAN:
- return Variant::BOOL;
-
- case MONO_TYPE_I1:
- return Variant::INT;
- case MONO_TYPE_I2:
- return Variant::INT;
- case MONO_TYPE_I4:
- return Variant::INT;
- case MONO_TYPE_I8:
- return Variant::INT;
-
- case MONO_TYPE_U1:
- return Variant::INT;
- case MONO_TYPE_U2:
- return Variant::INT;
- case MONO_TYPE_U4:
- return Variant::INT;
- case MONO_TYPE_U8:
- return Variant::INT;
-
- case MONO_TYPE_R4:
- return Variant::FLOAT;
- case MONO_TYPE_R8:
- return Variant::FLOAT;
-
- case MONO_TYPE_STRING: {
- return Variant::STRING;
- } break;
-
- case MONO_TYPE_VALUETYPE: {
- GDMonoClass *vtclass = p_type.type_class;
-
- if (vtclass == CACHED_CLASS(Vector2)) {
- return Variant::VECTOR2;
- }
-
- if (vtclass == CACHED_CLASS(Vector2i)) {
- return Variant::VECTOR2I;
- }
-
- if (vtclass == CACHED_CLASS(Rect2)) {
- return Variant::RECT2;
- }
-
- if (vtclass == CACHED_CLASS(Rect2i)) {
- return Variant::RECT2I;
- }
-
- if (vtclass == CACHED_CLASS(Transform2D)) {
- return Variant::TRANSFORM2D;
- }
-
- if (vtclass == CACHED_CLASS(Vector3)) {
- return Variant::VECTOR3;
- }
-
- if (vtclass == CACHED_CLASS(Vector3i)) {
- return Variant::VECTOR3I;
- }
- if (vtclass == CACHED_CLASS(Vector4)) {
- return Variant::VECTOR4;
- }
-
- if (vtclass == CACHED_CLASS(Vector4i)) {
- return Variant::VECTOR4I;
- }
-
- if (vtclass == CACHED_CLASS(Basis)) {
- return Variant::BASIS;
- }
-
- if (vtclass == CACHED_CLASS(Quaternion)) {
- return Variant::QUATERNION;
- }
-
- if (vtclass == CACHED_CLASS(Transform3D)) {
- return Variant::TRANSFORM3D;
- }
- if (vtclass == CACHED_CLASS(Projection)) {
- return Variant::PROJECTION;
- }
- if (vtclass == CACHED_CLASS(AABB)) {
- return Variant::AABB;
- }
-
- if (vtclass == CACHED_CLASS(Color)) {
- return Variant::COLOR;
- }
-
- if (vtclass == CACHED_CLASS(Plane)) {
- return Variant::PLANE;
- }
-
- if (vtclass == CACHED_CLASS(Callable)) {
- return Variant::CALLABLE;
- }
-
- if (vtclass == CACHED_CLASS(SignalInfo)) {
- return Variant::SIGNAL;
- }
-
- if (mono_class_is_enum(vtclass->get_mono_ptr())) {
- return Variant::INT;
- }
- } break;
-
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY: {
- MonoClass *elem_class = mono_class_get_element_class(p_type.type_class->get_mono_ptr());
-
- if (elem_class == CACHED_CLASS_RAW(MonoObject)) {
- return Variant::ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(uint8_t)) {
- return Variant::PACKED_BYTE_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(int32_t)) {
- return Variant::PACKED_INT32_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(int64_t)) {
- return Variant::PACKED_INT64_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(float)) {
- return Variant::PACKED_FLOAT32_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(double)) {
- return Variant::PACKED_FLOAT64_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(String)) {
- return Variant::PACKED_STRING_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(Vector2)) {
- return Variant::PACKED_VECTOR2_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(Vector3)) {
- return Variant::PACKED_VECTOR3_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(Color)) {
- return Variant::PACKED_COLOR_ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(StringName)) {
- return Variant::ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(NodePath)) {
- return Variant::ARRAY;
- }
-
- if (elem_class == CACHED_CLASS_RAW(RID)) {
- return Variant::ARRAY;
- }
-
- if (mono_class_is_enum(elem_class)) {
- return Variant::ARRAY;
- }
-
- GDMonoClass *array_type_class = GDMono::get_singleton()->get_class(elem_class);
- if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class)) {
- return Variant::ARRAY;
- }
- } break;
-
- case MONO_TYPE_CLASS: {
- GDMonoClass *type_class = p_type.type_class;
-
- // GodotObject
- if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) {
- return Variant::OBJECT;
- }
-
- if (CACHED_CLASS(StringName) == type_class) {
- return Variant::STRING_NAME;
- }
-
- if (CACHED_CLASS(NodePath) == type_class) {
- return Variant::NODE_PATH;
- }
-
- if (CACHED_CLASS(RID) == type_class) {
- return Variant::RID;
- }
-
- if (CACHED_CLASS(Dictionary) == type_class) {
- return Variant::DICTIONARY;
- }
-
- if (CACHED_CLASS(Array) == type_class) {
- return Variant::ARRAY;
- }
-
- // IDictionary
- if (p_type.type_class == CACHED_CLASS(System_Collections_IDictionary)) {
- return Variant::DICTIONARY;
- }
-
- // ICollection or IEnumerable
- if (p_type.type_class == CACHED_CLASS(System_Collections_ICollection) ||
- p_type.type_class == CACHED_CLASS(System_Collections_IEnumerable)) {
- return Variant::ARRAY;
- }
- } break;
-
- case MONO_TYPE_OBJECT: {
- if (r_nil_is_variant) {
- *r_nil_is_variant = true;
- }
- return Variant::NIL;
- } break;
-
- case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type());
-
- // Godot.Collections.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
- return Variant::DICTIONARY;
- }
-
- // Godot.Collections.Array<T>
- if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
- return Variant::ARRAY;
- }
-
- // System.Collections.Generic.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_system_generic_dictionary(reftype)) {
- return Variant::DICTIONARY;
- }
-
- // System.Collections.Generic.List<T>
- if (GDMonoUtils::Marshal::type_is_system_generic_list(reftype)) {
- return Variant::ARRAY;
- }
-
- // IDictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_idictionary(reftype)) {
- return Variant::DICTIONARY;
- }
-
- // ICollection<T> or IEnumerable<T>
- if (GDMonoUtils::Marshal::type_is_generic_icollection(reftype) || GDMonoUtils::Marshal::type_is_generic_ienumerable(reftype)) {
- return Variant::ARRAY;
- }
-
- // GodotObject
- GDMonoClass *type_class = p_type.type_class;
- if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) {
- return Variant::OBJECT;
- }
- } break;
-
- default: {
- } break;
- }
-
- if (r_nil_is_variant) {
- *r_nil_is_variant = false;
- }
-
- // Unknown
- return Variant::NIL;
-}
-
-bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type) {
- switch (p_array_type.type_encoding) {
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY: {
- MonoClass *elem_class = mono_class_get_element_class(p_array_type.type_class->get_mono_ptr());
- r_elem_type = ManagedType::from_class(elem_class);
- return true;
- } break;
- case MONO_TYPE_GENERICINST: {
- MonoReflectionType *array_reftype = mono_type_get_object(mono_domain_get(), p_array_type.type_class->get_mono_type());
-
- if (GDMonoUtils::Marshal::type_is_generic_array(array_reftype) ||
- GDMonoUtils::Marshal::type_is_system_generic_list(array_reftype) ||
- GDMonoUtils::Marshal::type_is_generic_icollection(array_reftype) ||
- GDMonoUtils::Marshal::type_is_generic_ienumerable(array_reftype)) {
- MonoReflectionType *elem_reftype;
-
- GDMonoUtils::Marshal::array_get_element_type(array_reftype, &elem_reftype);
-
- r_elem_type = ManagedType::from_reftype(elem_reftype);
- return true;
- }
- } break;
- default: {
- } break;
- }
-
- return false;
-}
-
-MonoString *variant_to_mono_string(const Variant &p_var) {
- if (p_var.get_type() == Variant::NIL) {
- return nullptr; // Otherwise, Variant -> String would return the string "Null"
- }
- return mono_string_from_godot(p_var.operator String());
-}
-
-MonoArray *variant_to_mono_array(const Variant &p_var, GDMonoClass *p_type_class) {
- MonoArrayType *array_type = mono_type_get_array_type(p_type_class->get_mono_type());
-
- if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) {
- return Array_to_mono_array(p_var.operator Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(uint8_t)) {
- return PackedByteArray_to_mono_array(p_var.operator PackedByteArray());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(int32_t)) {
- return PackedInt32Array_to_mono_array(p_var.operator PackedInt32Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(int64_t)) {
- return PackedInt64Array_to_mono_array(p_var.operator PackedInt64Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(float)) {
- return PackedFloat32Array_to_mono_array(p_var.operator PackedFloat32Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(double)) {
- return PackedFloat64Array_to_mono_array(p_var.operator PackedFloat64Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(String)) {
- return PackedStringArray_to_mono_array(p_var.operator PackedStringArray());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector2)) {
- return PackedVector2Array_to_mono_array(p_var.operator PackedVector2Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector3)) {
- return PackedVector3Array_to_mono_array(p_var.operator PackedVector3Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Color)) {
- return PackedColorArray_to_mono_array(p_var.operator PackedColorArray());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(StringName)) {
- return Array_to_mono_array(p_var.operator Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(NodePath)) {
- return Array_to_mono_array(p_var.operator Array());
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(RID)) {
- return Array_to_mono_array(p_var.operator Array());
- }
-
- if (mono_class_is_assignable_from(CACHED_CLASS(GodotObject)->get_mono_ptr(), array_type->eklass)) {
- return Array_to_mono_array(p_var.operator ::Array(), array_type->eklass);
- }
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to array of unsupported element type:" + GDMonoClass::get_full_name(array_type->eklass) + "'.");
-}
-
-MonoObject *variant_to_mono_object_of_class(const Variant &p_var, GDMonoClass *p_type_class) {
- // GodotObject
- if (CACHED_CLASS(GodotObject)->is_assignable_from(p_type_class)) {
- return GDMonoUtils::unmanaged_get_managed(p_var.operator Object *());
- }
-
- if (CACHED_CLASS(StringName) == p_type_class) {
- return GDMonoUtils::create_managed_from(p_var.operator StringName());
- }
-
- if (CACHED_CLASS(NodePath) == p_type_class) {
- return GDMonoUtils::create_managed_from(p_var.operator NodePath());
- }
-
- if (CACHED_CLASS(RID) == p_type_class) {
- return GDMonoUtils::create_managed_from(p_var.operator ::RID());
- }
-
- // Godot.Collections.Dictionary or IDictionary
- if (CACHED_CLASS(Dictionary) == p_type_class || CACHED_CLASS(System_Collections_IDictionary) == p_type_class) {
- return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), CACHED_CLASS(Dictionary));
- }
-
- // Godot.Collections.Array or ICollection or IEnumerable
- if (CACHED_CLASS(Array) == p_type_class ||
- CACHED_CLASS(System_Collections_ICollection) == p_type_class ||
- CACHED_CLASS(System_Collections_IEnumerable) == p_type_class) {
- return GDMonoUtils::create_managed_from(p_var.operator Array(), CACHED_CLASS(Array));
- }
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported type: '" + p_type_class->get_full_name() + "'.");
-}
-
-MonoObject *variant_to_mono_object_of_genericinst(const Variant &p_var, GDMonoClass *p_type_class) {
- MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type_class->get_mono_type());
-
- // Godot.Collections.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
- return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), p_type_class);
- }
-
- // Godot.Collections.Array<T>
- if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
- return GDMonoUtils::create_managed_from(p_var.operator Array(), p_type_class);
- }
-
- // System.Collections.Generic.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_system_generic_dictionary(reftype)) {
- MonoReflectionType *key_reftype = nullptr;
- MonoReflectionType *value_reftype = nullptr;
- GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
- return Dictionary_to_system_generic_dict(p_var.operator Dictionary(), p_type_class, key_reftype, value_reftype);
- }
-
- // System.Collections.Generic.List<T>
- if (GDMonoUtils::Marshal::type_is_system_generic_list(reftype)) {
- MonoReflectionType *elem_reftype = nullptr;
- GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
- return Array_to_system_generic_list(p_var.operator Array(), p_type_class, elem_reftype);
- }
-
- // IDictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_idictionary(reftype)) {
- MonoReflectionType *key_reftype;
- MonoReflectionType *value_reftype;
- GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
- GDMonoClass *godot_dict_class = GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype);
-
- return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), godot_dict_class);
- }
-
- // ICollection<T> or IEnumerable<T>
- if (GDMonoUtils::Marshal::type_is_generic_icollection(reftype) || GDMonoUtils::Marshal::type_is_generic_ienumerable(reftype)) {
- MonoReflectionType *elem_reftype;
- GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
- GDMonoClass *godot_array_class = GDMonoUtils::Marshal::make_generic_array_type(elem_reftype);
-
- return GDMonoUtils::create_managed_from(p_var.operator Array(), godot_array_class);
- }
-
- // GodotObject
- if (CACHED_CLASS(GodotObject)->is_assignable_from(p_type_class)) {
- return GDMonoUtils::unmanaged_get_managed(p_var.operator Object *());
- }
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported generic type: '" + p_type_class->get_full_name() + "'.");
-}
-
-MonoObject *variant_to_mono_object(const Variant &p_var) {
- // Variant
- switch (p_var.get_type()) {
- case Variant::BOOL: {
- MonoBoolean val = p_var.operator bool();
- return BOX_BOOLEAN(val);
- }
- case Variant::INT: {
- int64_t val = p_var.operator int64_t();
- return BOX_INT64(val);
- }
- case Variant::FLOAT: {
-#ifdef REAL_T_IS_DOUBLE
- double val = p_var.operator double();
- return BOX_DOUBLE(val);
-#else
- float val = p_var.operator float();
- return BOX_FLOAT(val);
-#endif
- }
- case Variant::STRING:
- return (MonoObject *)mono_string_from_godot(p_var.operator String());
- case Variant::VECTOR2: {
- GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_var.operator ::Vector2());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2), &from);
- }
- case Variant::VECTOR2I: {
- GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_var.operator ::Vector2i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2i), &from);
- }
- case Variant::RECT2: {
- GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_var.operator ::Rect2());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2), &from);
- }
- case Variant::RECT2I: {
- GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_var.operator ::Rect2i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2i), &from);
- }
- case Variant::VECTOR3: {
- GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_var.operator ::Vector3());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3), &from);
- }
- case Variant::VECTOR3I: {
- GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_var.operator ::Vector3i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3i), &from);
- }
- case Variant::TRANSFORM2D: {
- GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_var.operator ::Transform2D());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform2D), &from);
- }
- case Variant::VECTOR4: {
- GDMonoMarshal::M_Vector4 from = MARSHALLED_OUT(Vector4, p_var.operator ::Vector4());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector4), &from);
- }
- case Variant::VECTOR4I: {
- GDMonoMarshal::M_Vector4i from = MARSHALLED_OUT(Vector4i, p_var.operator ::Vector4i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector4i), &from);
- }
- case Variant::PLANE: {
- GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_var.operator ::Plane());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Plane), &from);
- }
- case Variant::QUATERNION: {
- GDMonoMarshal::M_Quaternion from = MARSHALLED_OUT(Quaternion, p_var.operator ::Quaternion());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Quaternion), &from);
- }
- case Variant::AABB: {
- GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_var.operator ::AABB());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(AABB), &from);
- }
- case Variant::BASIS: {
- GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_var.operator ::Basis());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Basis), &from);
- }
- case Variant::TRANSFORM3D: {
- GDMonoMarshal::M_Transform3D from = MARSHALLED_OUT(Transform3D, p_var.operator ::Transform3D());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform3D), &from);
- }
- case Variant::PROJECTION: {
- GDMonoMarshal::M_Projection from = MARSHALLED_OUT(Projection, p_var.operator ::Projection());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Projection), &from);
- }
- case Variant::COLOR: {
- GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_var.operator ::Color());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Color), &from);
- }
- case Variant::STRING_NAME:
- return GDMonoUtils::create_managed_from(p_var.operator StringName());
- case Variant::NODE_PATH:
- return GDMonoUtils::create_managed_from(p_var.operator NodePath());
- case Variant::RID:
- return GDMonoUtils::create_managed_from(p_var.operator ::RID());
- case Variant::OBJECT:
- return GDMonoUtils::unmanaged_get_managed(p_var.operator Object *());
- case Variant::CALLABLE: {
- GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var.operator Callable());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Callable), &from);
- }
- case Variant::SIGNAL: {
- GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var.operator Signal());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(SignalInfo), &from);
- }
- case Variant::DICTIONARY:
- return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), CACHED_CLASS(Dictionary));
- case Variant::ARRAY:
- return GDMonoUtils::create_managed_from(p_var.operator Array(), CACHED_CLASS(Array));
- case Variant::PACKED_BYTE_ARRAY:
- return (MonoObject *)PackedByteArray_to_mono_array(p_var.operator PackedByteArray());
- case Variant::PACKED_INT32_ARRAY:
- return (MonoObject *)PackedInt32Array_to_mono_array(p_var.operator PackedInt32Array());
- case Variant::PACKED_INT64_ARRAY:
- return (MonoObject *)PackedInt64Array_to_mono_array(p_var.operator PackedInt64Array());
- case Variant::PACKED_FLOAT32_ARRAY:
- return (MonoObject *)PackedFloat32Array_to_mono_array(p_var.operator PackedFloat32Array());
- case Variant::PACKED_FLOAT64_ARRAY:
- return (MonoObject *)PackedFloat64Array_to_mono_array(p_var.operator PackedFloat64Array());
- case Variant::PACKED_STRING_ARRAY:
- return (MonoObject *)PackedStringArray_to_mono_array(p_var.operator PackedStringArray());
- case Variant::PACKED_VECTOR2_ARRAY:
- return (MonoObject *)PackedVector2Array_to_mono_array(p_var.operator PackedVector2Array());
- case Variant::PACKED_VECTOR3_ARRAY:
- return (MonoObject *)PackedVector3Array_to_mono_array(p_var.operator PackedVector3Array());
- case Variant::PACKED_COLOR_ARRAY:
- return (MonoObject *)PackedColorArray_to_mono_array(p_var.operator PackedColorArray());
- default:
- return nullptr;
- }
-}
-
-size_t variant_get_managed_unboxed_size(const ManagedType &p_type) {
- // This method prints no errors for unsupported types. It's called on all methods, not only
- // those that end up being invoked with Variant parameters.
-
- // For MonoObject* we return 0, as it doesn't need to be stored.
- constexpr size_t zero_for_mono_object = 0;
-
- switch (p_type.type_encoding) {
- case MONO_TYPE_BOOLEAN:
- return sizeof(MonoBoolean);
- case MONO_TYPE_CHAR:
- return sizeof(uint16_t);
- case MONO_TYPE_I1:
- return sizeof(int8_t);
- case MONO_TYPE_I2:
- return sizeof(int16_t);
- case MONO_TYPE_I4:
- return sizeof(int32_t);
- case MONO_TYPE_I8:
- return sizeof(int64_t);
- case MONO_TYPE_U1:
- return sizeof(uint8_t);
- case MONO_TYPE_U2:
- return sizeof(uint16_t);
- case MONO_TYPE_U4:
- return sizeof(uint32_t);
- case MONO_TYPE_U8:
- return sizeof(uint64_t);
- case MONO_TYPE_R4:
- return sizeof(float);
- case MONO_TYPE_R8:
- return sizeof(double);
- case MONO_TYPE_VALUETYPE: {
- GDMonoClass *vtclass = p_type.type_class;
-
-#define RETURN_CHECK_FOR_STRUCT(m_struct) \
- if (vtclass == CACHED_CLASS(m_struct)) { \
- return sizeof(M_##m_struct); \
- }
-
- RETURN_CHECK_FOR_STRUCT(Vector2);
- RETURN_CHECK_FOR_STRUCT(Vector2i);
- RETURN_CHECK_FOR_STRUCT(Rect2);
- RETURN_CHECK_FOR_STRUCT(Rect2i);
- RETURN_CHECK_FOR_STRUCT(Transform2D);
- RETURN_CHECK_FOR_STRUCT(Vector3);
- RETURN_CHECK_FOR_STRUCT(Vector3i);
- RETURN_CHECK_FOR_STRUCT(Basis);
- RETURN_CHECK_FOR_STRUCT(Quaternion);
- RETURN_CHECK_FOR_STRUCT(Transform3D);
- RETURN_CHECK_FOR_STRUCT(AABB);
- RETURN_CHECK_FOR_STRUCT(Color);
- RETURN_CHECK_FOR_STRUCT(Plane);
- RETURN_CHECK_FOR_STRUCT(Callable);
- RETURN_CHECK_FOR_STRUCT(SignalInfo);
-
-#undef RETURN_CHECK_FOR_STRUCT
-
- if (mono_class_is_enum(vtclass->get_mono_ptr())) {
- MonoType *enum_basetype = mono_class_enum_basetype(vtclass->get_mono_ptr());
- switch (mono_type_get_type(enum_basetype)) {
- case MONO_TYPE_BOOLEAN:
- return sizeof(MonoBoolean);
- case MONO_TYPE_CHAR:
- return sizeof(uint16_t);
- case MONO_TYPE_I1:
- return sizeof(int8_t);
- case MONO_TYPE_I2:
- return sizeof(int16_t);
- case MONO_TYPE_I4:
- return sizeof(int32_t);
- case MONO_TYPE_I8:
- return sizeof(int64_t);
- case MONO_TYPE_U1:
- return sizeof(uint8_t);
- case MONO_TYPE_U2:
- return sizeof(uint16_t);
- case MONO_TYPE_U4:
- return sizeof(uint32_t);
- case MONO_TYPE_U8:
- return sizeof(uint64_t);
- default: {
- // Enum with unsupported base type. We return nullptr MonoObject* on error.
- return zero_for_mono_object;
- }
- }
- }
-
- // Enum with unsupported value type. We return nullptr MonoObject* on error.
- } break;
- case MONO_TYPE_STRING:
- return zero_for_mono_object;
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY:
- case MONO_TYPE_CLASS:
- case MONO_TYPE_GENERICINST:
- return zero_for_mono_object;
- case MONO_TYPE_OBJECT:
- return zero_for_mono_object;
- }
-
- // Unsupported type encoding. We return nullptr MonoObject* on error.
- return zero_for_mono_object;
-}
-
-void *variant_to_managed_unboxed(const Variant &p_var, const ManagedType &p_type, void *r_buffer, unsigned int &r_offset) {
-#define RETURN_TYPE_VAL(m_type, m_val) \
- *reinterpret_cast<m_type *>(r_buffer) = m_val; \
- r_offset += sizeof(m_type); \
- return r_buffer;
-
- switch (p_type.type_encoding) {
- case MONO_TYPE_BOOLEAN:
- RETURN_TYPE_VAL(MonoBoolean, (MonoBoolean)p_var.operator bool());
- case MONO_TYPE_CHAR:
- RETURN_TYPE_VAL(uint16_t, p_var.operator unsigned short());
- case MONO_TYPE_I1:
- RETURN_TYPE_VAL(int8_t, p_var.operator signed char());
- case MONO_TYPE_I2:
- RETURN_TYPE_VAL(int16_t, p_var.operator signed short());
- case MONO_TYPE_I4:
- RETURN_TYPE_VAL(int32_t, p_var.operator signed int());
- case MONO_TYPE_I8:
- RETURN_TYPE_VAL(int64_t, p_var.operator int64_t());
- case MONO_TYPE_U1:
- RETURN_TYPE_VAL(uint8_t, p_var.operator unsigned char());
- case MONO_TYPE_U2:
- RETURN_TYPE_VAL(uint16_t, p_var.operator unsigned short());
- case MONO_TYPE_U4:
- RETURN_TYPE_VAL(uint32_t, p_var.operator unsigned int());
- case MONO_TYPE_U8:
- RETURN_TYPE_VAL(uint64_t, p_var.operator uint64_t());
- case MONO_TYPE_R4:
- RETURN_TYPE_VAL(float, p_var.operator float());
- case MONO_TYPE_R8:
- RETURN_TYPE_VAL(double, p_var.operator double());
- case MONO_TYPE_VALUETYPE: {
- GDMonoClass *vtclass = p_type.type_class;
-
-#define RETURN_CHECK_FOR_STRUCT(m_struct) \
- if (vtclass == CACHED_CLASS(m_struct)) { \
- GDMonoMarshal::M_##m_struct from = MARSHALLED_OUT(m_struct, p_var.operator ::m_struct()); \
- RETURN_TYPE_VAL(M_##m_struct, from); \
- }
-
- RETURN_CHECK_FOR_STRUCT(Vector2);
- RETURN_CHECK_FOR_STRUCT(Vector2i);
- RETURN_CHECK_FOR_STRUCT(Rect2);
- RETURN_CHECK_FOR_STRUCT(Rect2i);
- RETURN_CHECK_FOR_STRUCT(Transform2D);
- RETURN_CHECK_FOR_STRUCT(Vector3);
- RETURN_CHECK_FOR_STRUCT(Vector3i);
- RETURN_CHECK_FOR_STRUCT(Basis);
- RETURN_CHECK_FOR_STRUCT(Quaternion);
- RETURN_CHECK_FOR_STRUCT(Transform3D);
- RETURN_CHECK_FOR_STRUCT(AABB);
- RETURN_CHECK_FOR_STRUCT(Color);
- RETURN_CHECK_FOR_STRUCT(Plane);
-
-#undef RETURN_CHECK_FOR_STRUCT
-
- if (vtclass == CACHED_CLASS(Callable)) {
- GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var.operator Callable());
- RETURN_TYPE_VAL(M_Callable, from);
- }
-
- if (vtclass == CACHED_CLASS(SignalInfo)) {
- GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var.operator Signal());
- RETURN_TYPE_VAL(M_SignalInfo, from);
- }
-
- if (mono_class_is_enum(vtclass->get_mono_ptr())) {
- MonoType *enum_basetype = mono_class_enum_basetype(vtclass->get_mono_ptr());
- switch (mono_type_get_type(enum_basetype)) {
- case MONO_TYPE_BOOLEAN: {
- MonoBoolean val = p_var.operator bool();
- RETURN_TYPE_VAL(MonoBoolean, val);
- }
- case MONO_TYPE_CHAR: {
- uint16_t val = p_var.operator unsigned short();
- RETURN_TYPE_VAL(uint16_t, val);
- }
- case MONO_TYPE_I1: {
- int8_t val = p_var.operator signed char();
- RETURN_TYPE_VAL(int8_t, val);
- }
- case MONO_TYPE_I2: {
- int16_t val = p_var.operator signed short();
- RETURN_TYPE_VAL(int16_t, val);
- }
- case MONO_TYPE_I4: {
- int32_t val = p_var.operator signed int();
- RETURN_TYPE_VAL(int32_t, val);
- }
- case MONO_TYPE_I8: {
- int64_t val = p_var.operator int64_t();
- RETURN_TYPE_VAL(int64_t, val);
- }
- case MONO_TYPE_U1: {
- uint8_t val = p_var.operator unsigned char();
- RETURN_TYPE_VAL(uint8_t, val);
- }
- case MONO_TYPE_U2: {
- uint16_t val = p_var.operator unsigned short();
- RETURN_TYPE_VAL(uint16_t, val);
- }
- case MONO_TYPE_U4: {
- uint32_t val = p_var.operator unsigned int();
- RETURN_TYPE_VAL(uint32_t, val);
- }
- case MONO_TYPE_U8: {
- uint64_t val = p_var.operator uint64_t();
- RETURN_TYPE_VAL(uint64_t, val);
- }
- default: {
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to enum value of unsupported base type: '" + GDMonoClass::get_full_name(mono_class_from_mono_type(enum_basetype)) + "'.");
- }
- }
- }
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported value type: '" + p_type.type_class->get_full_name() + "'.");
- } break;
-#undef RETURN_TYPE_VAL
- case MONO_TYPE_STRING:
- return variant_to_mono_string(p_var);
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY:
- return variant_to_mono_array(p_var, p_type.type_class);
- case MONO_TYPE_CLASS:
- return variant_to_mono_object_of_class(p_var, p_type.type_class);
- case MONO_TYPE_GENERICINST:
- return variant_to_mono_object_of_genericinst(p_var, p_type.type_class);
- case MONO_TYPE_OBJECT:
- return variant_to_mono_object(p_var);
- }
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported type with encoding: " + itos(p_type.type_encoding) + ".");
-}
-
-MonoObject *variant_to_mono_object(const Variant &p_var, const ManagedType &p_type) {
- switch (p_type.type_encoding) {
- case MONO_TYPE_BOOLEAN: {
- MonoBoolean val = p_var.operator bool();
- return BOX_BOOLEAN(val);
- }
- case MONO_TYPE_CHAR: {
- uint16_t val = p_var.operator unsigned short();
- return BOX_UINT16(val);
- }
- case MONO_TYPE_I1: {
- int8_t val = p_var.operator signed char();
- return BOX_INT8(val);
- }
- case MONO_TYPE_I2: {
- int16_t val = p_var.operator signed short();
- return BOX_INT16(val);
- }
- case MONO_TYPE_I4: {
- int32_t val = p_var.operator signed int();
- return BOX_INT32(val);
- }
- case MONO_TYPE_I8: {
- int64_t val = p_var.operator int64_t();
- return BOX_INT64(val);
- }
- case MONO_TYPE_U1: {
- uint8_t val = p_var.operator unsigned char();
- return BOX_UINT8(val);
- }
- case MONO_TYPE_U2: {
- uint16_t val = p_var.operator unsigned short();
- return BOX_UINT16(val);
- }
- case MONO_TYPE_U4: {
- uint32_t val = p_var.operator unsigned int();
- return BOX_UINT32(val);
- }
- case MONO_TYPE_U8: {
- uint64_t val = p_var.operator uint64_t();
- return BOX_UINT64(val);
- }
- case MONO_TYPE_R4: {
- float val = p_var.operator float();
- return BOX_FLOAT(val);
- }
- case MONO_TYPE_R8: {
- double val = p_var.operator double();
- return BOX_DOUBLE(val);
- }
- case MONO_TYPE_VALUETYPE: {
- GDMonoClass *vtclass = p_type.type_class;
-
-#define RETURN_CHECK_FOR_STRUCT(m_struct) \
- if (vtclass == CACHED_CLASS(m_struct)) { \
- GDMonoMarshal::M_##m_struct from = MARSHALLED_OUT(m_struct, p_var.operator ::m_struct()); \
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(m_struct), &from); \
- }
-
- RETURN_CHECK_FOR_STRUCT(Vector2);
- RETURN_CHECK_FOR_STRUCT(Vector2i);
- RETURN_CHECK_FOR_STRUCT(Rect2);
- RETURN_CHECK_FOR_STRUCT(Rect2i);
- RETURN_CHECK_FOR_STRUCT(Transform2D);
- RETURN_CHECK_FOR_STRUCT(Vector3);
- RETURN_CHECK_FOR_STRUCT(Vector3i);
- RETURN_CHECK_FOR_STRUCT(Basis);
- RETURN_CHECK_FOR_STRUCT(Quaternion);
- RETURN_CHECK_FOR_STRUCT(Transform3D);
- RETURN_CHECK_FOR_STRUCT(AABB);
- RETURN_CHECK_FOR_STRUCT(Color);
- RETURN_CHECK_FOR_STRUCT(Plane);
-
-#undef RETURN_CHECK_FOR_STRUCT
-
- if (vtclass == CACHED_CLASS(Callable)) {
- GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var.operator Callable());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Callable), &from);
- }
-
- if (vtclass == CACHED_CLASS(SignalInfo)) {
- GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var.operator Signal());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(SignalInfo), &from);
- }
-
- if (mono_class_is_enum(vtclass->get_mono_ptr())) {
- MonoType *enum_basetype = mono_class_enum_basetype(vtclass->get_mono_ptr());
- MonoClass *enum_baseclass = mono_class_from_mono_type(enum_basetype);
- switch (mono_type_get_type(enum_basetype)) {
- case MONO_TYPE_BOOLEAN: {
- MonoBoolean val = p_var.operator bool();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_CHAR: {
- uint16_t val = p_var.operator unsigned short();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_I1: {
- int8_t val = p_var.operator signed char();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_I2: {
- int16_t val = p_var.operator signed short();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_I4: {
- int32_t val = p_var.operator signed int();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_I8: {
- int64_t val = p_var.operator int64_t();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_U1: {
- uint8_t val = p_var.operator unsigned char();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_U2: {
- uint16_t val = p_var.operator unsigned short();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_U4: {
- uint32_t val = p_var.operator unsigned int();
- return BOX_ENUM(enum_baseclass, val);
- }
- case MONO_TYPE_U8: {
- uint64_t val = p_var.operator uint64_t();
- return BOX_ENUM(enum_baseclass, val);
- }
- default: {
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to enum value of unsupported base type: '" + GDMonoClass::get_full_name(enum_baseclass) + "'.");
- }
- }
- }
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported value type: '" + p_type.type_class->get_full_name() + "'.");
- } break;
- case MONO_TYPE_STRING:
- return (MonoObject *)variant_to_mono_string(p_var);
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY:
- return (MonoObject *)variant_to_mono_array(p_var, p_type.type_class);
- case MONO_TYPE_CLASS:
- return variant_to_mono_object_of_class(p_var, p_type.type_class);
- case MONO_TYPE_GENERICINST:
- return variant_to_mono_object_of_genericinst(p_var, p_type.type_class);
- case MONO_TYPE_OBJECT:
- return variant_to_mono_object(p_var);
- }
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported type with encoding: " + itos(p_type.type_encoding) + ".");
-}
-
-Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type, bool p_fail_with_err = true) {
- ERR_FAIL_COND_V(!p_type.type_class, Variant());
-
-#ifdef DEBUG_ENABLED
- CRASH_COND_MSG(p_type.type_encoding == MONO_TYPE_OBJECT, "Type of object should be known.");
-#endif
-
- switch (p_type.type_encoding) {
- case MONO_TYPE_BOOLEAN:
- return (bool)unbox<MonoBoolean>(p_obj);
- case MONO_TYPE_CHAR:
- return unbox<uint16_t>(p_obj);
- case MONO_TYPE_I1:
- return unbox<int8_t>(p_obj);
- case MONO_TYPE_I2:
- return unbox<int16_t>(p_obj);
- case MONO_TYPE_I4:
- return unbox<int32_t>(p_obj);
- case MONO_TYPE_I8:
- return unbox<int64_t>(p_obj);
- case MONO_TYPE_U1:
- return unbox<uint8_t>(p_obj);
- case MONO_TYPE_U2:
- return unbox<uint16_t>(p_obj);
- case MONO_TYPE_U4:
- return unbox<uint32_t>(p_obj);
- case MONO_TYPE_U8:
- return unbox<uint64_t>(p_obj);
- case MONO_TYPE_R4:
- return unbox<float>(p_obj);
- case MONO_TYPE_R8:
- return unbox<double>(p_obj);
- case MONO_TYPE_VALUETYPE: {
- GDMonoClass *vtclass = p_type.type_class;
-
- if (vtclass == CACHED_CLASS(Vector2)) {
- return MARSHALLED_IN(Vector2, unbox_addr<GDMonoMarshal::M_Vector2>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Vector2i)) {
- return MARSHALLED_IN(Vector2i, unbox_addr<GDMonoMarshal::M_Vector2i>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Rect2)) {
- return MARSHALLED_IN(Rect2, unbox_addr<GDMonoMarshal::M_Rect2>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Rect2i)) {
- return MARSHALLED_IN(Rect2i, unbox_addr<GDMonoMarshal::M_Rect2i>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Transform2D)) {
- return MARSHALLED_IN(Transform2D, unbox_addr<GDMonoMarshal::M_Transform2D>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Vector3)) {
- return MARSHALLED_IN(Vector3, unbox_addr<GDMonoMarshal::M_Vector3>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Vector3i)) {
- return MARSHALLED_IN(Vector3i, unbox_addr<GDMonoMarshal::M_Vector3i>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Basis)) {
- return MARSHALLED_IN(Basis, unbox_addr<GDMonoMarshal::M_Basis>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Quaternion)) {
- return MARSHALLED_IN(Quaternion, unbox_addr<GDMonoMarshal::M_Quaternion>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Transform3D)) {
- return MARSHALLED_IN(Transform3D, unbox_addr<GDMonoMarshal::M_Transform3D>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(AABB)) {
- return MARSHALLED_IN(AABB, unbox_addr<GDMonoMarshal::M_AABB>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Color)) {
- return MARSHALLED_IN(Color, unbox_addr<GDMonoMarshal::M_Color>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Plane)) {
- return MARSHALLED_IN(Plane, unbox_addr<GDMonoMarshal::M_Plane>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(Callable)) {
- return managed_to_callable(unbox<GDMonoMarshal::M_Callable>(p_obj));
- }
-
- if (vtclass == CACHED_CLASS(SignalInfo)) {
- return managed_to_signal_info(unbox<GDMonoMarshal::M_SignalInfo>(p_obj));
- }
-
- if (mono_class_is_enum(vtclass->get_mono_ptr())) {
- return unbox<int32_t>(p_obj);
- }
- } break;
- case MONO_TYPE_STRING: {
- if (p_obj == nullptr) {
- return Variant(); // NIL
- }
- return mono_string_to_godot_not_null((MonoString *)p_obj);
- } break;
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY: {
- MonoArrayType *array_type = mono_type_get_array_type(p_type.type_class->get_mono_type());
-
- if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) {
- return mono_array_to_Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(uint8_t)) {
- return mono_array_to_PackedByteArray((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(int32_t)) {
- return mono_array_to_PackedInt32Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(int64_t)) {
- return mono_array_to_PackedInt64Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(float)) {
- return mono_array_to_PackedFloat32Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(double)) {
- return mono_array_to_PackedFloat64Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(String)) {
- return mono_array_to_PackedStringArray((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector2)) {
- return mono_array_to_PackedVector2Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector3)) {
- return mono_array_to_PackedVector3Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Color)) {
- return mono_array_to_PackedColorArray((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(StringName)) {
- return mono_array_to_Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(NodePath)) {
- return mono_array_to_Array((MonoArray *)p_obj);
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(RID)) {
- return mono_array_to_Array((MonoArray *)p_obj);
- }
-
- GDMonoClass *array_type_class = GDMono::get_singleton()->get_class(array_type->eklass);
- if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class)) {
- return mono_array_to_Array((MonoArray *)p_obj);
- }
-
- if (p_fail_with_err) {
- ERR_FAIL_V_MSG(Variant(), "Attempted to convert a managed array of unmarshallable element type to Variant.");
- } else {
- return Variant();
- }
- } break;
- case MONO_TYPE_CLASS: {
- GDMonoClass *type_class = p_type.type_class;
-
- // GodotObject
- if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) {
- Object *ptr = unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_obj));
- if (ptr != nullptr) {
- RefCounted *rc = Object::cast_to<RefCounted>(ptr);
- return rc ? Variant(Ref<RefCounted>(rc)) : Variant(ptr);
- }
- return Variant();
- }
-
- if (CACHED_CLASS(StringName) == type_class) {
- StringName *ptr = unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(p_obj));
- return ptr ? Variant(*ptr) : Variant();
- }
-
- if (CACHED_CLASS(NodePath) == type_class) {
- NodePath *ptr = unbox<NodePath *>(CACHED_FIELD(NodePath, ptr)->get_value(p_obj));
- return ptr ? Variant(*ptr) : Variant();
- }
-
- if (CACHED_CLASS(RID) == type_class) {
- RID *ptr = unbox<RID *>(CACHED_FIELD(RID, ptr)->get_value(p_obj));
- return ptr ? Variant(*ptr) : Variant();
- }
-
- // Godot.Collections.Dictionary
- if (CACHED_CLASS(Dictionary) == type_class) {
- MonoException *exc = nullptr;
- Dictionary *ptr = CACHED_METHOD_THUNK(Dictionary, GetPtr).invoke(p_obj, &exc);
- UNHANDLED_EXCEPTION(exc);
- return ptr ? Variant(*ptr) : Variant();
- }
-
- // Godot.Collections.Array
- if (CACHED_CLASS(Array) == type_class) {
- MonoException *exc = nullptr;
- Array *ptr = CACHED_METHOD_THUNK(Array, GetPtr).invoke(p_obj, &exc);
- UNHANDLED_EXCEPTION(exc);
- return ptr ? Variant(*ptr) : Variant();
- }
- } break;
- case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type());
-
- // Godot.Collections.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
- MonoException *exc = nullptr;
- MonoObject *ret = p_type.type_class->get_method("GetPtr")->invoke(p_obj, &exc);
- UNHANDLED_EXCEPTION(exc);
- return *unbox<Dictionary *>(ret);
- }
-
- // Godot.Collections.Array<T>
- if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
- MonoException *exc = nullptr;
- MonoObject *ret = p_type.type_class->get_method("GetPtr")->invoke(p_obj, &exc);
- UNHANDLED_EXCEPTION(exc);
- return *unbox<Array *>(ret);
- }
-
- // System.Collections.Generic.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_system_generic_dictionary(reftype)) {
- MonoReflectionType *key_reftype = nullptr;
- MonoReflectionType *value_reftype = nullptr;
- GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
- return system_generic_dict_to_Dictionary(p_obj, p_type.type_class, key_reftype, value_reftype);
- }
-
- // System.Collections.Generic.List<T>
- if (GDMonoUtils::Marshal::type_is_system_generic_list(reftype)) {
- MonoReflectionType *elem_reftype = nullptr;
- GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
- return system_generic_list_to_Array_variant(p_obj, p_type.type_class, elem_reftype);
- }
-
- // GodotObject
- GDMonoClass *type_class = p_type.type_class;
- if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) {
- Object *ptr = unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_obj));
- if (ptr != nullptr) {
- RefCounted *rc = Object::cast_to<RefCounted>(ptr);
- return rc ? Variant(Ref<RefCounted>(rc)) : Variant(ptr);
- }
- return Variant();
- }
- } break;
- }
-
- if (p_fail_with_err) {
- ERR_FAIL_V_MSG(Variant(), "Attempted to convert an unmarshallable managed type to Variant. Name: '" + p_type.type_class->get_name() + "' Encoding: " + itos(p_type.type_encoding) + ".");
- } else {
- return Variant();
- }
-}
-
-Variant mono_object_to_variant(MonoObject *p_obj) {
- if (!p_obj) {
- return Variant();
- }
-
- ManagedType type = ManagedType::from_class(mono_object_get_class(p_obj));
-
- return mono_object_to_variant_impl(p_obj, type);
-}
-
-Variant mono_object_to_variant(MonoObject *p_obj, const ManagedType &p_type) {
- if (!p_obj) {
- return Variant();
- }
-
- return mono_object_to_variant_impl(p_obj, p_type);
-}
-
-Variant mono_object_to_variant_no_err(MonoObject *p_obj, const ManagedType &p_type) {
- if (!p_obj) {
- return Variant();
- }
-
- return mono_object_to_variant_impl(p_obj, p_type, /* fail_with_err: */ false);
-}
-
-String mono_object_to_variant_string(MonoObject *p_obj, MonoException **r_exc) {
- if (p_obj == nullptr) {
- return String("null");
- }
-
- ManagedType type = ManagedType::from_class(mono_object_get_class(p_obj));
- Variant var = GDMonoMarshal::mono_object_to_variant_no_err(p_obj, type);
-
- if (var.get_type() == Variant::NIL) { // `&& p_obj != nullptr` but omitted because always true
- // Cannot convert MonoObject* to Variant; fallback to 'ToString()'.
- MonoException *exc = nullptr;
- MonoString *mono_str = GDMonoUtils::object_to_string(p_obj, &exc);
-
- if (exc) {
- if (r_exc) {
- *r_exc = exc;
- }
- return String();
- }
-
- return GDMonoMarshal::mono_string_to_godot(mono_str);
- } else {
- return var.operator String();
- }
-}
-
-MonoObject *Dictionary_to_system_generic_dict(const Dictionary &p_dict, GDMonoClass *p_class, MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype) {
- String ctor_desc = ":.ctor(System.Collections.Generic.IDictionary`2<" + GDMonoUtils::get_type_desc(p_key_reftype) +
- ", " + GDMonoUtils::get_type_desc(p_value_reftype) + ">)";
- GDMonoMethod *ctor = p_class->get_method_with_desc(ctor_desc, true);
- CRASH_COND(ctor == nullptr);
-
- MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- GDMonoClass *godot_dict_class = GDMonoUtils::Marshal::make_generic_dictionary_type(p_key_reftype, p_value_reftype);
- MonoObject *godot_dict = GDMonoUtils::create_managed_from(p_dict, godot_dict_class);
-
- void *ctor_args[1] = { godot_dict };
-
- MonoException *exc = nullptr;
- ctor->invoke_raw(mono_object, ctor_args, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- return mono_object;
-}
-
-Dictionary system_generic_dict_to_Dictionary(MonoObject *p_obj, [[maybe_unused]] GDMonoClass *p_class, MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype) {
- GDMonoClass *godot_dict_class = GDMonoUtils::Marshal::make_generic_dictionary_type(p_key_reftype, p_value_reftype);
- String ctor_desc = ":.ctor(System.Collections.Generic.IDictionary`2<" + GDMonoUtils::get_type_desc(p_key_reftype) +
- ", " + GDMonoUtils::get_type_desc(p_value_reftype) + ">)";
- GDMonoMethod *godot_dict_ctor = godot_dict_class->get_method_with_desc(ctor_desc, true);
- CRASH_COND(godot_dict_ctor == nullptr);
-
- MonoObject *godot_dict = mono_object_new(mono_domain_get(), godot_dict_class->get_mono_ptr());
- ERR_FAIL_NULL_V(godot_dict, Dictionary());
-
- void *ctor_args[1] = { p_obj };
-
- MonoException *exc = nullptr;
- godot_dict_ctor->invoke_raw(godot_dict, ctor_args, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- exc = nullptr;
- MonoObject *ret = godot_dict_class->get_method("GetPtr")->invoke(godot_dict, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- return *unbox<Dictionary *>(ret);
-}
-
-MonoObject *Array_to_system_generic_list(const Array &p_array, GDMonoClass *p_class, MonoReflectionType *p_elem_reftype) {
- MonoType *elem_type = mono_reflection_type_get_type(p_elem_reftype);
-
- String ctor_desc = ":.ctor(System.Collections.Generic.IEnumerable`1<" + GDMonoUtils::get_type_desc(elem_type) + ">)";
- GDMonoMethod *ctor = p_class->get_method_with_desc(ctor_desc, true);
- CRASH_COND(ctor == nullptr);
-
- MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- GDMonoClass *godot_array_class = GDMonoUtils::Marshal::make_generic_array_type(p_elem_reftype);
- MonoObject *godot_array = GDMonoUtils::create_managed_from(p_array, godot_array_class);
-
- void *ctor_args[1] = { godot_array };
-
- MonoException *exc = nullptr;
- ctor->invoke_raw(mono_object, ctor_args, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- return mono_object;
-}
-
-Variant system_generic_list_to_Array_variant(MonoObject *p_obj, GDMonoClass *p_class, [[maybe_unused]] MonoReflectionType *p_elem_reftype) {
- GDMonoMethod *to_array = p_class->get_method("ToArray", 0);
- CRASH_COND(to_array == nullptr);
-
- MonoException *exc = nullptr;
- MonoObject *array = to_array->invoke_raw(p_obj, nullptr, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- ERR_FAIL_NULL_V(array, Variant());
-
- ManagedType type = ManagedType::from_class(mono_object_get_class(array));
-
- bool result_is_array = type.type_encoding != MONO_TYPE_SZARRAY && type.type_encoding != MONO_TYPE_ARRAY;
- ERR_FAIL_COND_V(result_is_array, Variant());
-
- return mono_object_to_variant(array, type);
-}
-
-MonoArray *Array_to_mono_array(const Array &p_array) {
- int length = p_array.size();
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), length);
-
- for (int i = 0; i < length; i++) {
- MonoObject *boxed = variant_to_mono_object(p_array[i]);
- mono_array_setref(ret, i, boxed);
- }
-
- return ret;
-}
-
-MonoArray *Array_to_mono_array(const Array &p_array, MonoClass *p_array_type_class) {
- int length = p_array.size();
- MonoArray *ret = mono_array_new(mono_domain_get(), p_array_type_class, length);
-
- for (int i = 0; i < length; i++) {
- MonoObject *boxed = variant_to_mono_object(p_array[i]);
- mono_array_setref(ret, i, boxed);
- }
-
- return ret;
-}
-
-Array mono_array_to_Array(MonoArray *p_array) {
- Array ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
-
- for (int i = 0; i < length; i++) {
- MonoObject *elem = mono_array_get(p_array, MonoObject *, i);
- ret[i] = mono_object_to_variant(elem);
- }
-
- return ret;
-}
-
-MonoArray *PackedInt32Array_to_mono_array(const PackedInt32Array &p_array) {
- const int32_t *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(int32_t), length);
-
- int32_t *dst = mono_array_addr(ret, int32_t, 0);
- memcpy(dst, src, length * sizeof(int32_t));
-
- return ret;
-}
-
-PackedInt32Array mono_array_to_PackedInt32Array(MonoArray *p_array) {
- PackedInt32Array ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- int32_t *dst = ret.ptrw();
-
- const int32_t *src = mono_array_addr(p_array, int32_t, 0);
- memcpy(dst, src, length * sizeof(int32_t));
-
- return ret;
-}
-
-MonoArray *PackedInt64Array_to_mono_array(const PackedInt64Array &p_array) {
- const int64_t *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(int64_t), length);
-
- int64_t *dst = mono_array_addr(ret, int64_t, 0);
- memcpy(dst, src, length * sizeof(int64_t));
-
- return ret;
-}
-
-PackedInt64Array mono_array_to_PackedInt64Array(MonoArray *p_array) {
- PackedInt64Array ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- int64_t *dst = ret.ptrw();
-
- const int64_t *src = mono_array_addr(p_array, int64_t, 0);
- memcpy(dst, src, length * sizeof(int64_t));
-
- return ret;
-}
-
-MonoArray *PackedByteArray_to_mono_array(const PackedByteArray &p_array) {
- const uint8_t *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), length);
-
- uint8_t *dst = mono_array_addr(ret, uint8_t, 0);
- memcpy(dst, src, length * sizeof(uint8_t));
-
- return ret;
-}
-
-PackedByteArray mono_array_to_PackedByteArray(MonoArray *p_array) {
- PackedByteArray ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- uint8_t *dst = ret.ptrw();
-
- const uint8_t *src = mono_array_addr(p_array, uint8_t, 0);
- memcpy(dst, src, length * sizeof(uint8_t));
-
- return ret;
-}
-
-MonoArray *PackedFloat32Array_to_mono_array(const PackedFloat32Array &p_array) {
- const float *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(float), length);
-
- float *dst = mono_array_addr(ret, float, 0);
- memcpy(dst, src, length * sizeof(float));
-
- return ret;
-}
-
-PackedFloat32Array mono_array_to_PackedFloat32Array(MonoArray *p_array) {
- PackedFloat32Array ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- float *dst = ret.ptrw();
-
- const float *src = mono_array_addr(p_array, float, 0);
- memcpy(dst, src, length * sizeof(float));
-
- return ret;
-}
-
-MonoArray *PackedFloat64Array_to_mono_array(const PackedFloat64Array &p_array) {
- const double *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(double), length);
-
- double *dst = mono_array_addr(ret, double, 0);
- memcpy(dst, src, length * sizeof(double));
-
- return ret;
-}
-
-PackedFloat64Array mono_array_to_PackedFloat64Array(MonoArray *p_array) {
- PackedFloat64Array ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- double *dst = ret.ptrw();
-
- const double *src = mono_array_addr(p_array, double, 0);
- memcpy(dst, src, length * sizeof(double));
-
- return ret;
-}
-
-MonoArray *PackedStringArray_to_mono_array(const PackedStringArray &p_array) {
- const String *r = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), length);
-
- for (int i = 0; i < length; i++) {
- MonoString *boxed = mono_string_from_godot(r[i]);
- mono_array_setref(ret, i, boxed);
- }
-
- return ret;
-}
-
-PackedStringArray mono_array_to_PackedStringArray(MonoArray *p_array) {
- PackedStringArray ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- String *w = ret.ptrw();
-
- for (int i = 0; i < length; i++) {
- MonoString *elem = mono_array_get(p_array, MonoString *, i);
- w[i] = mono_string_to_godot(elem);
- }
-
- return ret;
-}
-
-MonoArray *PackedColorArray_to_mono_array(const PackedColorArray &p_array) {
- const Color *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(Color), length);
-
- if constexpr (InteropLayout::MATCHES_Color) {
- Color *dst = mono_array_addr(ret, Color, 0);
- memcpy(dst, src, length * sizeof(Color));
- } else {
- for (int i = 0; i < length; i++) {
- M_Color *raw = (M_Color *)mono_array_addr_with_size(ret, sizeof(M_Color), i);
- *raw = MARSHALLED_OUT(Color, src[i]);
- }
- }
-
- return ret;
-}
-
-PackedColorArray mono_array_to_PackedColorArray(MonoArray *p_array) {
- PackedColorArray ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- Color *dst = ret.ptrw();
-
- if constexpr (InteropLayout::MATCHES_Color) {
- const Color *src = mono_array_addr(p_array, Color, 0);
- memcpy(dst, src, length * sizeof(Color));
- } else {
- for (int i = 0; i < length; i++) {
- dst[i] = MARSHALLED_IN(Color, (M_Color *)mono_array_addr_with_size(p_array, sizeof(M_Color), i));
- }
- }
-
- return ret;
-}
-
-MonoArray *PackedVector2Array_to_mono_array(const PackedVector2Array &p_array) {
- const Vector2 *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(Vector2), length);
-
- if constexpr (InteropLayout::MATCHES_Vector2) {
- Vector2 *dst = mono_array_addr(ret, Vector2, 0);
- memcpy(dst, src, length * sizeof(Vector2));
- } else {
- for (int i = 0; i < length; i++) {
- M_Vector2 *raw = (M_Vector2 *)mono_array_addr_with_size(ret, sizeof(M_Vector2), i);
- *raw = MARSHALLED_OUT(Vector2, src[i]);
- }
- }
-
- return ret;
-}
-
-PackedVector2Array mono_array_to_PackedVector2Array(MonoArray *p_array) {
- PackedVector2Array ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- Vector2 *dst = ret.ptrw();
-
- if constexpr (InteropLayout::MATCHES_Vector2) {
- const Vector2 *src = mono_array_addr(p_array, Vector2, 0);
- memcpy(dst, src, length * sizeof(Vector2));
- } else {
- for (int i = 0; i < length; i++) {
- dst[i] = MARSHALLED_IN(Vector2, (M_Vector2 *)mono_array_addr_with_size(p_array, sizeof(M_Vector2), i));
- }
- }
-
- return ret;
-}
-
-MonoArray *PackedVector3Array_to_mono_array(const PackedVector3Array &p_array) {
- const Vector3 *src = p_array.ptr();
- int length = p_array.size();
-
- MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(Vector3), length);
-
- if constexpr (InteropLayout::MATCHES_Vector3) {
- Vector3 *dst = mono_array_addr(ret, Vector3, 0);
- memcpy(dst, src, length * sizeof(Vector3));
- } else {
- for (int i = 0; i < length; i++) {
- M_Vector3 *raw = (M_Vector3 *)mono_array_addr_with_size(ret, sizeof(M_Vector3), i);
- *raw = MARSHALLED_OUT(Vector3, src[i]);
- }
- }
-
- return ret;
-}
-
-PackedVector3Array mono_array_to_PackedVector3Array(MonoArray *p_array) {
- PackedVector3Array ret;
- if (!p_array) {
- return ret;
- }
- int length = mono_array_length(p_array);
- ret.resize(length);
- Vector3 *dst = ret.ptrw();
-
- if constexpr (InteropLayout::MATCHES_Vector3) {
- const Vector3 *src = mono_array_addr(p_array, Vector3, 0);
- memcpy(dst, src, length * sizeof(Vector3));
- } else {
- for (int i = 0; i < length; i++) {
- dst[i] = MARSHALLED_IN(Vector3, (M_Vector3 *)mono_array_addr_with_size(p_array, sizeof(M_Vector3), i));
- }
- }
-
- return ret;
-}
-
-Callable managed_to_callable(const M_Callable &p_managed_callable) {
- if (p_managed_callable.delegate) {
- // TODO: Use pooling for ManagedCallable instances.
- CallableCustom *managed_callable = memnew(ManagedCallable(p_managed_callable.delegate));
- return Callable(managed_callable);
- } else {
- Object *target = p_managed_callable.target
- ? unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_managed_callable.target))
- : nullptr;
- StringName *method_ptr = p_managed_callable.method_string_name
- ? unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(p_managed_callable.method_string_name))
- : nullptr;
- StringName method = method_ptr ? *method_ptr : StringName();
- return Callable(target, method);
- }
-}
-
-M_Callable callable_to_managed(const Callable &p_callable) {
- if (p_callable.is_custom()) {
- CallableCustom *custom = p_callable.get_custom();
- CallableCustom::CompareEqualFunc compare_equal_func = custom->get_compare_equal_func();
-
- if (compare_equal_func == ManagedCallable::compare_equal_func_ptr) {
- ManagedCallable *managed_callable = static_cast<ManagedCallable *>(custom);
- return {
- nullptr, nullptr,
- managed_callable->get_delegate()
- };
- } else if (compare_equal_func == SignalAwaiterCallable::compare_equal_func_ptr) {
- SignalAwaiterCallable *signal_awaiter_callable = static_cast<SignalAwaiterCallable *>(custom);
- return {
- GDMonoUtils::unmanaged_get_managed(ObjectDB::get_instance(signal_awaiter_callable->get_object())),
- GDMonoUtils::create_managed_from(signal_awaiter_callable->get_signal()),
- nullptr
- };
- } else if (compare_equal_func == EventSignalCallable::compare_equal_func_ptr) {
- EventSignalCallable *event_signal_callable = static_cast<EventSignalCallable *>(custom);
- return {
- GDMonoUtils::unmanaged_get_managed(ObjectDB::get_instance(event_signal_callable->get_object())),
- GDMonoUtils::create_managed_from(event_signal_callable->get_signal()),
- nullptr
- };
- }
-
- // Some other CallableCustom. We only support ManagedCallable.
- return { nullptr, nullptr, nullptr };
- } else {
- MonoObject *target_managed = GDMonoUtils::unmanaged_get_managed(p_callable.get_object());
- MonoObject *method_string_name_managed = GDMonoUtils::create_managed_from(p_callable.get_method());
- return { target_managed, method_string_name_managed, nullptr };
- }
-}
-
-Signal managed_to_signal_info(const M_SignalInfo &p_managed_signal) {
- Object *owner = p_managed_signal.owner
- ? unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_managed_signal.owner))
- : nullptr;
- StringName *name_ptr = p_managed_signal.name_string_name
- ? unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(p_managed_signal.name_string_name))
- : nullptr;
- StringName name = name_ptr ? *name_ptr : StringName();
- return Signal(owner, name);
-}
-
-M_SignalInfo signal_info_to_managed(const Signal &p_signal) {
- Object *owner = p_signal.get_object();
- MonoObject *owner_managed = GDMonoUtils::unmanaged_get_managed(owner);
- MonoObject *name_string_name_managed = GDMonoUtils::create_managed_from(p_signal.get_name());
- return { owner_managed, name_string_name_managed };
-}
-} // namespace GDMonoMarshal
diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h
deleted file mode 100644
index 51f11ab18a..0000000000
--- a/modules/mono/mono_gd/gd_mono_marshal.h
+++ /dev/null
@@ -1,605 +0,0 @@
-/*************************************************************************/
-/* gd_mono_marshal.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 GD_MONO_MARSHAL_H
-#define GD_MONO_MARSHAL_H
-
-#include "core/variant/variant.h"
-
-#include "../managed_callable.h"
-#include "gd_mono.h"
-#include "gd_mono_utils.h"
-
-namespace GDMonoMarshal {
-
-template <typename T>
-T unbox(MonoObject *p_obj) {
- return *(T *)mono_object_unbox(p_obj);
-}
-
-template <typename T>
-T *unbox_addr(MonoObject *p_obj) {
- return (T *)mono_object_unbox(p_obj);
-}
-
-#define BOX_DOUBLE(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(double), &x)
-#define BOX_FLOAT(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(float), &x)
-#define BOX_INT64(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(int64_t), &x)
-#define BOX_INT32(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(int32_t), &x)
-#define BOX_INT16(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(int16_t), &x)
-#define BOX_INT8(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(int8_t), &x)
-#define BOX_UINT64(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(uint64_t), &x)
-#define BOX_UINT32(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(uint32_t), &x)
-#define BOX_UINT16(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(uint16_t), &x)
-#define BOX_UINT8(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), &x)
-#define BOX_BOOLEAN(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(bool), &x)
-#define BOX_PTR(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(IntPtr), x)
-#define BOX_ENUM(m_enum_class, x) mono_value_box(mono_domain_get(), m_enum_class, &x)
-
-Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_variant = nullptr);
-
-bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type);
-
-// String
-
-_FORCE_INLINE_ String mono_string_to_godot_not_null(MonoString *p_mono_string) {
- char32_t *utf32 = (char32_t *)mono_string_to_utf32(p_mono_string);
- String ret = String(utf32);
- mono_free(utf32);
- return ret;
-}
-
-_FORCE_INLINE_ String mono_string_to_godot(MonoString *p_mono_string) {
- if (p_mono_string == nullptr) {
- return String();
- }
-
- return mono_string_to_godot_not_null(p_mono_string);
-}
-
-_FORCE_INLINE_ MonoString *mono_string_from_godot(const String &p_string) {
- return mono_string_from_utf32((mono_unichar4 *)(p_string.get_data()));
-}
-
-// Variant
-
-size_t variant_get_managed_unboxed_size(const ManagedType &p_type);
-void *variant_to_managed_unboxed(const Variant &p_var, const ManagedType &p_type, void *r_buffer, unsigned int &r_offset);
-MonoObject *variant_to_mono_object(const Variant &p_var, const ManagedType &p_type);
-
-MonoObject *variant_to_mono_object(const Variant &p_var);
-MonoArray *variant_to_mono_array(const Variant &p_var, GDMonoClass *p_type_class);
-MonoObject *variant_to_mono_object_of_class(const Variant &p_var, GDMonoClass *p_type_class);
-MonoObject *variant_to_mono_object_of_genericinst(const Variant &p_var, GDMonoClass *p_type_class);
-MonoString *variant_to_mono_string(const Variant &p_var);
-
-// These overloads were added to avoid passing a `const Variant *` to the `const Variant &`
-// parameter. That would result in the `Variant(bool)` copy constructor being called as
-// pointers are implicitly converted to bool. Implicit conversions are f-ing evil.
-
-_FORCE_INLINE_ void *variant_to_managed_unboxed(const Variant *p_var, const ManagedType &p_type, void *r_buffer, unsigned int &r_offset) {
- return variant_to_managed_unboxed(*p_var, p_type, r_buffer, r_offset);
-}
-_FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_type) {
- return variant_to_mono_object(*p_var, p_type);
-}
-_FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant *p_var) {
- return variant_to_mono_object(*p_var);
-}
-_FORCE_INLINE_ MonoArray *variant_to_mono_array(const Variant *p_var, GDMonoClass *p_type_class) {
- return variant_to_mono_array(*p_var, p_type_class);
-}
-_FORCE_INLINE_ MonoObject *variant_to_mono_object_of_class(const Variant *p_var, GDMonoClass *p_type_class) {
- return variant_to_mono_object_of_class(*p_var, p_type_class);
-}
-_FORCE_INLINE_ MonoObject *variant_to_mono_object_of_genericinst(const Variant *p_var, GDMonoClass *p_type_class) {
- return variant_to_mono_object_of_genericinst(*p_var, p_type_class);
-}
-_FORCE_INLINE_ MonoString *variant_to_mono_string(const Variant *p_var) {
- return variant_to_mono_string(*p_var);
-}
-
-Variant mono_object_to_variant(MonoObject *p_obj);
-Variant mono_object_to_variant(MonoObject *p_obj, const ManagedType &p_type);
-Variant mono_object_to_variant_no_err(MonoObject *p_obj, const ManagedType &p_type);
-
-/// Tries to convert the MonoObject* to Variant and then convert the Variant to String.
-/// If the MonoObject* cannot be converted to Variant, then 'ToString()' is called instead.
-String mono_object_to_variant_string(MonoObject *p_obj, MonoException **r_exc);
-
-// System.Collections.Generic
-
-MonoObject *Dictionary_to_system_generic_dict(const Dictionary &p_dict, GDMonoClass *p_class, MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype);
-Dictionary system_generic_dict_to_Dictionary(MonoObject *p_obj, GDMonoClass *p_class, MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype);
-
-MonoObject *Array_to_system_generic_list(const Array &p_array, GDMonoClass *p_class, MonoReflectionType *p_elem_reftype);
-Variant system_generic_list_to_Array_variant(MonoObject *p_obj, GDMonoClass *p_class, MonoReflectionType *p_elem_reftype);
-
-// Array
-
-MonoArray *Array_to_mono_array(const Array &p_array);
-MonoArray *Array_to_mono_array(const Array &p_array, MonoClass *p_array_type_class);
-Array mono_array_to_Array(MonoArray *p_array);
-
-// PackedInt32Array
-
-MonoArray *PackedInt32Array_to_mono_array(const PackedInt32Array &p_array);
-PackedInt32Array mono_array_to_PackedInt32Array(MonoArray *p_array);
-
-// PackedInt64Array
-
-MonoArray *PackedInt64Array_to_mono_array(const PackedInt64Array &p_array);
-PackedInt64Array mono_array_to_PackedInt64Array(MonoArray *p_array);
-
-// PackedByteArray
-
-MonoArray *PackedByteArray_to_mono_array(const PackedByteArray &p_array);
-PackedByteArray mono_array_to_PackedByteArray(MonoArray *p_array);
-
-// PackedFloat32Array
-
-MonoArray *PackedFloat32Array_to_mono_array(const PackedFloat32Array &p_array);
-PackedFloat32Array mono_array_to_PackedFloat32Array(MonoArray *p_array);
-
-// PackedFloat64Array
-
-MonoArray *PackedFloat64Array_to_mono_array(const PackedFloat64Array &p_array);
-PackedFloat64Array mono_array_to_PackedFloat64Array(MonoArray *p_array);
-
-// PackedStringArray
-
-MonoArray *PackedStringArray_to_mono_array(const PackedStringArray &p_array);
-PackedStringArray mono_array_to_PackedStringArray(MonoArray *p_array);
-
-// PackedColorArray
-
-MonoArray *PackedColorArray_to_mono_array(const PackedColorArray &p_array);
-PackedColorArray mono_array_to_PackedColorArray(MonoArray *p_array);
-
-// PackedVector2Array
-
-MonoArray *PackedVector2Array_to_mono_array(const PackedVector2Array &p_array);
-PackedVector2Array mono_array_to_PackedVector2Array(MonoArray *p_array);
-
-// PackedVector3Array
-
-MonoArray *PackedVector3Array_to_mono_array(const PackedVector3Array &p_array);
-PackedVector3Array mono_array_to_PackedVector3Array(MonoArray *p_array);
-
-#pragma pack(push, 1)
-
-struct M_Callable {
- MonoObject *target = nullptr;
- MonoObject *method_string_name = nullptr;
- MonoDelegate *delegate = nullptr;
-};
-
-struct M_SignalInfo {
- MonoObject *owner = nullptr;
- MonoObject *name_string_name = nullptr;
-};
-
-#pragma pack(pop)
-
-// Callable
-Callable managed_to_callable(const M_Callable &p_managed_callable);
-M_Callable callable_to_managed(const Callable &p_callable);
-
-// SignalInfo
-Signal managed_to_signal_info(const M_SignalInfo &p_managed_signal);
-M_SignalInfo signal_info_to_managed(const Signal &p_signal);
-
-// Structures
-
-namespace InteropLayout {
-
-enum {
- MATCHES_int = (sizeof(int32_t) == sizeof(uint32_t)),
-
- MATCHES_float = (sizeof(float) == sizeof(uint32_t)),
-
- MATCHES_double = (sizeof(double) == sizeof(uint64_t)),
-
-#ifdef REAL_T_IS_DOUBLE
- MATCHES_real_t = (sizeof(real_t) == sizeof(uint64_t)),
-#else
- MATCHES_real_t = (sizeof(real_t) == sizeof(uint32_t)),
-#endif
-
- MATCHES_Vector2 = (MATCHES_real_t && (sizeof(Vector2) == (sizeof(real_t) * 2)) &&
- offsetof(Vector2, x) == (sizeof(real_t) * 0) &&
- offsetof(Vector2, y) == (sizeof(real_t) * 1)),
-
- MATCHES_Vector2i = (MATCHES_int && (sizeof(Vector2i) == (sizeof(int32_t) * 2)) &&
- offsetof(Vector2i, x) == (sizeof(int32_t) * 0) &&
- offsetof(Vector2i, y) == (sizeof(int32_t) * 1)),
-
- MATCHES_Rect2 = (MATCHES_Vector2 && (sizeof(Rect2) == (sizeof(Vector2) * 2)) &&
- offsetof(Rect2, position) == (sizeof(Vector2) * 0) &&
- offsetof(Rect2, size) == (sizeof(Vector2) * 1)),
-
- MATCHES_Rect2i = (MATCHES_Vector2i && (sizeof(Rect2i) == (sizeof(Vector2i) * 2)) &&
- offsetof(Rect2i, position) == (sizeof(Vector2i) * 0) &&
- offsetof(Rect2i, size) == (sizeof(Vector2i) * 1)),
-
- MATCHES_Transform2D = (MATCHES_Vector2 && (sizeof(Transform2D) == (sizeof(Vector2) * 3))), // No field offset required, it stores an array
-
- MATCHES_Vector3 = (MATCHES_real_t && (sizeof(Vector3) == (sizeof(real_t) * 3)) &&
- offsetof(Vector3, x) == (sizeof(real_t) * 0) &&
- offsetof(Vector3, y) == (sizeof(real_t) * 1) &&
- offsetof(Vector3, z) == (sizeof(real_t) * 2)),
-
- MATCHES_Vector4 = (MATCHES_real_t && (sizeof(Vector4) == (sizeof(real_t) * 4)) &&
- offsetof(Vector4, x) == (sizeof(real_t) * 0) &&
- offsetof(Vector4, y) == (sizeof(real_t) * 1) &&
- offsetof(Vector4, z) == (sizeof(real_t) * 2) &&
- offsetof(Vector4, w) == (sizeof(real_t) * 3)),
-
- MATCHES_Vector4i = (MATCHES_int && (sizeof(Vector4i) == (sizeof(int32_t) * 4)) &&
- offsetof(Vector4i, x) == (sizeof(int32_t) * 0) &&
- offsetof(Vector4i, y) == (sizeof(int32_t) * 1) &&
- offsetof(Vector4i, z) == (sizeof(int32_t) * 2) &&
- offsetof(Vector4i, w) == (sizeof(int32_t) * 3)),
-
- MATCHES_Vector3i = (MATCHES_int && (sizeof(Vector3i) == (sizeof(int32_t) * 3)) &&
- offsetof(Vector3i, x) == (sizeof(int32_t) * 0) &&
- offsetof(Vector3i, y) == (sizeof(int32_t) * 1) &&
- offsetof(Vector3i, z) == (sizeof(int32_t) * 2)),
-
- MATCHES_Basis = (MATCHES_Vector3 && (sizeof(Basis) == (sizeof(Vector3) * 3))), // No field offset required, it stores an array
-
- MATCHES_Quaternion = (MATCHES_real_t && (sizeof(Quaternion) == (sizeof(real_t) * 4)) &&
- offsetof(Quaternion, x) == (sizeof(real_t) * 0) &&
- offsetof(Quaternion, y) == (sizeof(real_t) * 1) &&
- offsetof(Quaternion, z) == (sizeof(real_t) * 2) &&
- offsetof(Quaternion, w) == (sizeof(real_t) * 3)),
-
- MATCHES_Transform3D = (MATCHES_Basis && MATCHES_Vector3 && (sizeof(Transform3D) == (sizeof(Basis) + sizeof(Vector3))) &&
- offsetof(Transform3D, basis) == 0 &&
- offsetof(Transform3D, origin) == sizeof(Basis)),
-
- MATCHES_Projection = (MATCHES_Vector4 && (sizeof(Projection) == (sizeof(Vector4) * 4))),
-
- MATCHES_AABB = (MATCHES_Vector3 && (sizeof(AABB) == (sizeof(Vector3) * 2)) &&
- offsetof(AABB, position) == (sizeof(Vector3) * 0) &&
- offsetof(AABB, size) == (sizeof(Vector3) * 1)),
-
- MATCHES_Color = (MATCHES_float && (sizeof(Color) == (sizeof(float) * 4)) &&
- offsetof(Color, r) == (sizeof(float) * 0) &&
- offsetof(Color, g) == (sizeof(float) * 1) &&
- offsetof(Color, b) == (sizeof(float) * 2) &&
- offsetof(Color, a) == (sizeof(float) * 3)),
-
- MATCHES_Plane = (MATCHES_Vector3 && MATCHES_real_t && (sizeof(Plane) == (sizeof(Vector3) + sizeof(real_t))) &&
- offsetof(Plane, normal) == 0 &&
- offsetof(Plane, d) == sizeof(Vector3))
-};
-
-// In the future we may force this if we want to ref return these structs
-#ifdef GD_MONO_FORCE_INTEROP_STRUCT_COPY
-/* clang-format off */
-static_assert(MATCHES_Vector2 && MATCHES_Rect2 && MATCHES_Transform2D && MATCHES_Vector3 && MATCHES_Vector4 &&
- MATCHES_Basis && MATCHES_Quaternion && MATCHES_Transform3D && MATCHES_Projection && MATCHES_AABB && MATCHES_Color &&
- MATCHES_Plane && MATCHES_Vector2i && MATCHES_Rect2i && MATCHES_Vector3i && MATCHES_Vector4i);
-/* clang-format on */
-#endif
-} // namespace InteropLayout
-
-#pragma pack(push, 1)
-
-struct M_Vector2 {
- real_t x, y;
-
- static _FORCE_INLINE_ Vector2 convert_to(const M_Vector2 &p_from) {
- return Vector2(p_from.x, p_from.y);
- }
-
- static _FORCE_INLINE_ M_Vector2 convert_from(const Vector2 &p_from) {
- M_Vector2 ret = { p_from.x, p_from.y };
- return ret;
- }
-};
-
-struct M_Vector2i {
- int32_t x, y;
-
- static _FORCE_INLINE_ Vector2i convert_to(const M_Vector2i &p_from) {
- return Vector2i(p_from.x, p_from.y);
- }
-
- static _FORCE_INLINE_ M_Vector2i convert_from(const Vector2i &p_from) {
- M_Vector2i ret = { p_from.x, p_from.y };
- return ret;
- }
-};
-
-struct M_Rect2 {
- M_Vector2 position;
- M_Vector2 size;
-
- static _FORCE_INLINE_ Rect2 convert_to(const M_Rect2 &p_from) {
- return Rect2(M_Vector2::convert_to(p_from.position),
- M_Vector2::convert_to(p_from.size));
- }
-
- static _FORCE_INLINE_ M_Rect2 convert_from(const Rect2 &p_from) {
- M_Rect2 ret = { M_Vector2::convert_from(p_from.position), M_Vector2::convert_from(p_from.size) };
- return ret;
- }
-};
-
-struct M_Rect2i {
- M_Vector2i position;
- M_Vector2i size;
-
- static _FORCE_INLINE_ Rect2i convert_to(const M_Rect2i &p_from) {
- return Rect2i(M_Vector2i::convert_to(p_from.position),
- M_Vector2i::convert_to(p_from.size));
- }
-
- static _FORCE_INLINE_ M_Rect2i convert_from(const Rect2i &p_from) {
- M_Rect2i ret = { M_Vector2i::convert_from(p_from.position), M_Vector2i::convert_from(p_from.size) };
- return ret;
- }
-};
-
-struct M_Transform2D {
- M_Vector2 elements[3];
-
- static _FORCE_INLINE_ Transform2D convert_to(const M_Transform2D &p_from) {
- return Transform2D(p_from.elements[0].x, p_from.elements[0].y,
- p_from.elements[1].x, p_from.elements[1].y,
- p_from.elements[2].x, p_from.elements[2].y);
- }
-
- static _FORCE_INLINE_ M_Transform2D convert_from(const Transform2D &p_from) {
- M_Transform2D ret = {
- M_Vector2::convert_from(p_from.columns[0]),
- M_Vector2::convert_from(p_from.columns[1]),
- M_Vector2::convert_from(p_from.columns[2])
- };
- return ret;
- }
-};
-
-struct M_Vector3 {
- real_t x, y, z;
-
- static _FORCE_INLINE_ Vector3 convert_to(const M_Vector3 &p_from) {
- return Vector3(p_from.x, p_from.y, p_from.z);
- }
-
- static _FORCE_INLINE_ M_Vector3 convert_from(const Vector3 &p_from) {
- M_Vector3 ret = { p_from.x, p_from.y, p_from.z };
- return ret;
- }
-};
-
-struct M_Vector3i {
- int32_t x, y, z;
-
- static _FORCE_INLINE_ Vector3i convert_to(const M_Vector3i &p_from) {
- return Vector3i(p_from.x, p_from.y, p_from.z);
- }
-
- static _FORCE_INLINE_ M_Vector3i convert_from(const Vector3i &p_from) {
- M_Vector3i ret = { p_from.x, p_from.y, p_from.z };
- return ret;
- }
-};
-
-struct M_Vector4 {
- real_t x, y, z, w;
-
- static _FORCE_INLINE_ Vector4 convert_to(const M_Vector4 &p_from) {
- return Vector4(p_from.x, p_from.y, p_from.z, p_from.w);
- }
-
- static _FORCE_INLINE_ M_Vector4 convert_from(const Vector4 &p_from) {
- M_Vector4 ret = { p_from.x, p_from.y, p_from.z, p_from.w };
- return ret;
- }
-};
-
-struct M_Vector4i {
- int32_t x, y, z, w;
-
- static _FORCE_INLINE_ Vector4i convert_to(const M_Vector4i &p_from) {
- return Vector4i(p_from.x, p_from.y, p_from.z, p_from.w);
- }
-
- static _FORCE_INLINE_ M_Vector4i convert_from(const Vector4i &p_from) {
- M_Vector4i ret = { p_from.x, p_from.y, p_from.z, p_from.w };
- return ret;
- }
-};
-
-struct M_Basis {
- M_Vector3 elements[3];
-
- static _FORCE_INLINE_ Basis convert_to(const M_Basis &p_from) {
- return Basis(M_Vector3::convert_to(p_from.elements[0]),
- M_Vector3::convert_to(p_from.elements[1]),
- M_Vector3::convert_to(p_from.elements[2]));
- }
-
- static _FORCE_INLINE_ M_Basis convert_from(const Basis &p_from) {
- M_Basis ret = {
- M_Vector3::convert_from(p_from.rows[0]),
- M_Vector3::convert_from(p_from.rows[1]),
- M_Vector3::convert_from(p_from.rows[2])
- };
- return ret;
- }
-};
-
-struct M_Quaternion {
- real_t x, y, z, w;
-
- static _FORCE_INLINE_ Quaternion convert_to(const M_Quaternion &p_from) {
- return Quaternion(p_from.x, p_from.y, p_from.z, p_from.w);
- }
-
- static _FORCE_INLINE_ M_Quaternion convert_from(const Quaternion &p_from) {
- M_Quaternion ret = { p_from.x, p_from.y, p_from.z, p_from.w };
- return ret;
- }
-};
-
-struct M_Transform3D {
- M_Basis basis;
- M_Vector3 origin;
-
- static _FORCE_INLINE_ Transform3D convert_to(const M_Transform3D &p_from) {
- return Transform3D(M_Basis::convert_to(p_from.basis), M_Vector3::convert_to(p_from.origin));
- }
-
- static _FORCE_INLINE_ M_Transform3D convert_from(const Transform3D &p_from) {
- M_Transform3D ret = { M_Basis::convert_from(p_from.basis), M_Vector3::convert_from(p_from.origin) };
- return ret;
- }
-};
-
-struct M_Projection {
- M_Vector4 vec1;
- M_Vector4 vec2;
- M_Vector4 vec3;
- M_Vector4 vec4;
-
- static _FORCE_INLINE_ Projection convert_to(const M_Projection &p_from) {
- return Projection(M_Vector4::convert_to(p_from.vec1), M_Vector4::convert_to(p_from.vec2), M_Vector4::convert_to(p_from.vec3), M_Vector4::convert_to(p_from.vec4));
- }
-
- static _FORCE_INLINE_ M_Projection convert_from(const Projection &p_from) {
- M_Projection ret = { M_Vector4::convert_from(p_from.matrix[0]), M_Vector4::convert_from(p_from.matrix[1]), M_Vector4::convert_from(p_from.matrix[2]), M_Vector4::convert_from(p_from.matrix[3]) };
- return ret;
- }
-};
-
-struct M_AABB {
- M_Vector3 position;
- M_Vector3 size;
-
- static _FORCE_INLINE_ AABB convert_to(const M_AABB &p_from) {
- return AABB(M_Vector3::convert_to(p_from.position), M_Vector3::convert_to(p_from.size));
- }
-
- static _FORCE_INLINE_ M_AABB convert_from(const AABB &p_from) {
- M_AABB ret = { M_Vector3::convert_from(p_from.position), M_Vector3::convert_from(p_from.size) };
- return ret;
- }
-};
-
-struct M_Color {
- float r, g, b, a;
-
- static _FORCE_INLINE_ Color convert_to(const M_Color &p_from) {
- return Color(p_from.r, p_from.g, p_from.b, p_from.a);
- }
-
- static _FORCE_INLINE_ M_Color convert_from(const Color &p_from) {
- M_Color ret = { p_from.r, p_from.g, p_from.b, p_from.a };
- return ret;
- }
-};
-
-struct M_Plane {
- M_Vector3 normal;
- real_t d;
-
- static _FORCE_INLINE_ Plane convert_to(const M_Plane &p_from) {
- return Plane(M_Vector3::convert_to(p_from.normal), p_from.d);
- }
-
- static _FORCE_INLINE_ M_Plane convert_from(const Plane &p_from) {
- M_Plane ret = { M_Vector3::convert_from(p_from.normal), p_from.d };
- return ret;
- }
-};
-
-#pragma pack(pop)
-
-#define DECL_TYPE_MARSHAL_TEMPLATES(m_type) \
- template <int> \
- _FORCE_INLINE_ m_type marshalled_in_##m_type##_impl(const M_##m_type *p_from); \
- \
- template <> \
- _FORCE_INLINE_ m_type marshalled_in_##m_type##_impl<0>(const M_##m_type *p_from) { \
- return M_##m_type::convert_to(*p_from); \
- } \
- \
- template <> \
- _FORCE_INLINE_ m_type marshalled_in_##m_type##_impl<1>(const M_##m_type *p_from) { \
- return *reinterpret_cast<const m_type *>(p_from); \
- } \
- \
- _FORCE_INLINE_ m_type marshalled_in_##m_type(const M_##m_type *p_from) { \
- return marshalled_in_##m_type##_impl<InteropLayout::MATCHES_##m_type>(p_from); \
- } \
- \
- template <int> \
- _FORCE_INLINE_ M_##m_type marshalled_out_##m_type##_impl(const m_type &p_from); \
- \
- template <> \
- _FORCE_INLINE_ M_##m_type marshalled_out_##m_type##_impl<0>(const m_type &p_from) { \
- return M_##m_type::convert_from(p_from); \
- } \
- \
- template <> \
- _FORCE_INLINE_ M_##m_type marshalled_out_##m_type##_impl<1>(const m_type &p_from) { \
- return *reinterpret_cast<const M_##m_type *>(&p_from); \
- } \
- \
- _FORCE_INLINE_ M_##m_type marshalled_out_##m_type(const m_type &p_from) { \
- return marshalled_out_##m_type##_impl<InteropLayout::MATCHES_##m_type>(p_from); \
- }
-
-DECL_TYPE_MARSHAL_TEMPLATES(Vector2)
-DECL_TYPE_MARSHAL_TEMPLATES(Vector2i)
-DECL_TYPE_MARSHAL_TEMPLATES(Rect2)
-DECL_TYPE_MARSHAL_TEMPLATES(Rect2i)
-DECL_TYPE_MARSHAL_TEMPLATES(Transform2D)
-DECL_TYPE_MARSHAL_TEMPLATES(Vector3)
-DECL_TYPE_MARSHAL_TEMPLATES(Vector3i)
-DECL_TYPE_MARSHAL_TEMPLATES(Basis)
-DECL_TYPE_MARSHAL_TEMPLATES(Vector4)
-DECL_TYPE_MARSHAL_TEMPLATES(Vector4i)
-DECL_TYPE_MARSHAL_TEMPLATES(Quaternion)
-DECL_TYPE_MARSHAL_TEMPLATES(Transform3D)
-DECL_TYPE_MARSHAL_TEMPLATES(Projection)
-DECL_TYPE_MARSHAL_TEMPLATES(AABB)
-DECL_TYPE_MARSHAL_TEMPLATES(Color)
-DECL_TYPE_MARSHAL_TEMPLATES(Plane)
-
-#define MARSHALLED_IN(m_type, m_from_ptr) (GDMonoMarshal::marshalled_in_##m_type(m_from_ptr))
-#define MARSHALLED_OUT(m_type, m_from) (GDMonoMarshal::marshalled_out_##m_type(m_from))
-} // namespace GDMonoMarshal
-
-#endif // GD_MONO_MARSHAL_H
diff --git a/modules/mono/mono_gd/gd_mono_method.cpp b/modules/mono/mono_gd/gd_mono_method.cpp
deleted file mode 100644
index 6734b44783..0000000000
--- a/modules/mono/mono_gd/gd_mono_method.cpp
+++ /dev/null
@@ -1,296 +0,0 @@
-/*************************************************************************/
-/* gd_mono_method.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 "gd_mono_method.h"
-
-#include <mono/metadata/attrdefs.h>
-#include <mono/metadata/debug-helpers.h>
-
-#include "gd_mono_cache.h"
-#include "gd_mono_class.h"
-#include "gd_mono_marshal.h"
-#include "gd_mono_utils.h"
-
-void GDMonoMethod::_update_signature() {
- // Apparently MonoMethodSignature needs not to be freed.
- // mono_method_signature caches the result, we don't need to cache it ourselves.
-
- MonoMethodSignature *method_sig = mono_method_signature(mono_method);
- _update_signature(method_sig);
-}
-
-void GDMonoMethod::_update_signature(MonoMethodSignature *p_method_sig) {
- params_count = mono_signature_get_param_count(p_method_sig);
-
- MonoType *ret_type = mono_signature_get_return_type(p_method_sig);
- if (ret_type) {
- return_type.type_encoding = mono_type_get_type(ret_type);
-
- if (return_type.type_encoding != MONO_TYPE_VOID) {
- MonoClass *ret_type_class = mono_class_from_mono_type(ret_type);
- return_type.type_class = GDMono::get_singleton()->get_class(ret_type_class);
- }
- }
-
- void *iter = nullptr;
- MonoType *param_raw_type;
- while ((param_raw_type = mono_signature_get_params(p_method_sig, &iter)) != nullptr) {
- ManagedType param_type;
-
- param_type.type_encoding = mono_type_get_type(param_raw_type);
-
- MonoClass *param_type_class = mono_class_from_mono_type(param_raw_type);
- param_type.type_class = GDMono::get_singleton()->get_class(param_type_class);
-
- param_types.push_back(param_type);
- }
-
- // clear the cache
- method_info_fetched = false;
- method_info = MethodInfo();
-
- for (int i = 0; i < params_count; i++) {
- params_buffer_size += GDMonoMarshal::variant_get_managed_unboxed_size(param_types[i]);
- }
-}
-
-GDMonoClass *GDMonoMethod::get_enclosing_class() const {
- return GDMono::get_singleton()->get_class(mono_method_get_class(mono_method));
-}
-
-bool GDMonoMethod::is_static() {
- return mono_method_get_flags(mono_method, nullptr) & MONO_METHOD_ATTR_STATIC;
-}
-
-IMonoClassMember::Visibility GDMonoMethod::get_visibility() {
- switch (mono_method_get_flags(mono_method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK) {
- case MONO_METHOD_ATTR_PRIVATE:
- return IMonoClassMember::PRIVATE;
- case MONO_METHOD_ATTR_FAM_AND_ASSEM:
- return IMonoClassMember::PROTECTED_AND_INTERNAL;
- case MONO_METHOD_ATTR_ASSEM:
- return IMonoClassMember::INTERNAL;
- case MONO_METHOD_ATTR_FAMILY:
- return IMonoClassMember::PROTECTED;
- case MONO_METHOD_ATTR_PUBLIC:
- return IMonoClassMember::PUBLIC;
- default:
- ERR_FAIL_V(IMonoClassMember::PRIVATE);
- }
-}
-
-MonoObject *GDMonoMethod::invoke(MonoObject *p_object, const Variant **p_params, MonoException **r_exc) const {
- MonoException *exc = nullptr;
- MonoObject *ret;
-
- if (params_count > 0) {
- void **params = (void **)alloca(params_count * sizeof(void *));
- uint8_t *buffer = (uint8_t *)alloca(params_buffer_size);
- unsigned int offset = 0;
-
- for (int i = 0; i < params_count; i++) {
- params[i] = GDMonoMarshal::variant_to_managed_unboxed(p_params[i], param_types[i], buffer + offset, offset);
- }
-
- ret = GDMonoUtils::runtime_invoke(mono_method, p_object, params, &exc);
- } else {
- ret = GDMonoUtils::runtime_invoke(mono_method, p_object, nullptr, &exc);
- }
-
- if (exc) {
- ret = nullptr;
- if (r_exc) {
- *r_exc = exc;
- } else {
- GDMonoUtils::set_pending_exception(exc);
- }
- }
-
- return ret;
-}
-
-MonoObject *GDMonoMethod::invoke(MonoObject *p_object, MonoException **r_exc) const {
- ERR_FAIL_COND_V(get_parameters_count() > 0, nullptr);
- return invoke_raw(p_object, nullptr, r_exc);
-}
-
-MonoObject *GDMonoMethod::invoke_raw(MonoObject *p_object, void **p_params, MonoException **r_exc) const {
- MonoException *exc = nullptr;
- MonoObject *ret = GDMonoUtils::runtime_invoke(mono_method, p_object, p_params, &exc);
-
- if (exc) {
- ret = nullptr;
- if (r_exc) {
- *r_exc = exc;
- } else {
- GDMonoUtils::set_pending_exception(exc);
- }
- }
-
- return ret;
-}
-
-bool GDMonoMethod::has_attribute(GDMonoClass *p_attr_class) {
- ERR_FAIL_NULL_V(p_attr_class, false);
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return false;
- }
-
- return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-MonoObject *GDMonoMethod::get_attribute(GDMonoClass *p_attr_class) {
- ERR_FAIL_NULL_V(p_attr_class, nullptr);
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return nullptr;
- }
-
- return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-void GDMonoMethod::fetch_attributes() {
- ERR_FAIL_COND(attributes != nullptr);
- attributes = mono_custom_attrs_from_method(mono_method);
- attrs_fetched = true;
-}
-
-String GDMonoMethod::get_full_name(bool p_signature) const {
- char *res = mono_method_full_name(mono_method, p_signature);
- String full_name(res);
- mono_free(res);
- return full_name;
-}
-
-String GDMonoMethod::get_full_name_no_class() const {
- String res;
-
- MonoMethodSignature *method_sig = mono_method_signature(mono_method);
-
- char *ret_str = mono_type_full_name(mono_signature_get_return_type(method_sig));
- res += ret_str;
- mono_free(ret_str);
-
- res += " ";
- res += name;
- res += "(";
-
- char *sig_desc = mono_signature_get_desc(method_sig, true);
- res += sig_desc;
- mono_free(sig_desc);
-
- res += ")";
-
- return res;
-}
-
-String GDMonoMethod::get_ret_type_full_name() const {
- MonoMethodSignature *method_sig = mono_method_signature(mono_method);
- char *ret_str = mono_type_full_name(mono_signature_get_return_type(method_sig));
- String res = ret_str;
- mono_free(ret_str);
- return res;
-}
-
-String GDMonoMethod::get_signature_desc(bool p_namespaces) const {
- MonoMethodSignature *method_sig = mono_method_signature(mono_method);
- char *sig_desc = mono_signature_get_desc(method_sig, p_namespaces);
- String res = sig_desc;
- mono_free(sig_desc);
- return res;
-}
-
-void GDMonoMethod::get_parameter_names(Vector<StringName> &names) const {
- if (params_count > 0) {
- const char **_names = memnew_arr(const char *, params_count);
- mono_method_get_param_names(mono_method, _names);
- for (int i = 0; i < params_count; ++i) {
- names.push_back(StringName(_names[i]));
- }
- memdelete_arr(_names);
- }
-}
-
-void GDMonoMethod::get_parameter_types(Vector<ManagedType> &types) const {
- for (int i = 0; i < params_count; ++i) {
- types.push_back(param_types[i]);
- }
-}
-
-const MethodInfo &GDMonoMethod::get_method_info() {
- if (!method_info_fetched) {
- method_info.name = name;
-
- bool nil_is_variant = false;
- method_info.return_val = PropertyInfo(GDMonoMarshal::managed_to_variant_type(return_type, &nil_is_variant), "");
- if (method_info.return_val.type == Variant::NIL && nil_is_variant) {
- method_info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- }
-
- Vector<StringName> names;
- get_parameter_names(names);
-
- for (int i = 0; i < params_count; ++i) {
- nil_is_variant = false;
- PropertyInfo arg_info = PropertyInfo(GDMonoMarshal::managed_to_variant_type(param_types[i], &nil_is_variant), names[i]);
- if (arg_info.type == Variant::NIL && nil_is_variant) {
- arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- }
-
- method_info.arguments.push_back(arg_info);
- }
-
- // TODO: default arguments
-
- method_info_fetched = true;
- }
-
- return method_info;
-}
-
-GDMonoMethod::GDMonoMethod(StringName p_name, MonoMethod *p_method) :
- name(p_name), mono_method(p_method) {
- _update_signature();
-}
-
-GDMonoMethod::~GDMonoMethod() {
- if (attributes) {
- mono_custom_attrs_free(attributes);
- }
-}
diff --git a/modules/mono/mono_gd/gd_mono_method.h b/modules/mono/mono_gd/gd_mono_method.h
deleted file mode 100644
index be11ef5bfe..0000000000
--- a/modules/mono/mono_gd/gd_mono_method.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*************************************************************************/
-/* gd_mono_method.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 GD_MONO_METHOD_H
-#define GD_MONO_METHOD_H
-
-#include "gd_mono.h"
-#include "gd_mono_header.h"
-#include "i_mono_class_member.h"
-
-class GDMonoMethod : public IMonoClassMember {
- StringName name;
-
- uint16_t params_count;
- unsigned int params_buffer_size = 0;
- ManagedType return_type;
- Vector<ManagedType> param_types;
-
- bool method_info_fetched = false;
- MethodInfo method_info;
-
- bool attrs_fetched = false;
- MonoCustomAttrInfo *attributes = nullptr;
-
- void _update_signature();
- void _update_signature(MonoMethodSignature *p_method_sig);
-
- friend class GDMonoClass;
-
- MonoMethod *mono_method = nullptr;
-
-public:
- virtual GDMonoClass *get_enclosing_class() const final;
-
- virtual MemberType get_member_type() const final { return MEMBER_TYPE_METHOD; }
-
- virtual StringName get_name() const final { return name; }
-
- virtual bool is_static() final;
-
- virtual Visibility get_visibility() final;
-
- virtual bool has_attribute(GDMonoClass *p_attr_class) final;
- virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) final;
- void fetch_attributes();
-
- _FORCE_INLINE_ MonoMethod *get_mono_ptr() const { return mono_method; }
-
- _FORCE_INLINE_ uint16_t get_parameters_count() const { return params_count; }
- _FORCE_INLINE_ ManagedType get_return_type() const { return return_type; }
-
- MonoObject *invoke(MonoObject *p_object, const Variant **p_params, MonoException **r_exc = nullptr) const;
- MonoObject *invoke(MonoObject *p_object, MonoException **r_exc = nullptr) const;
- MonoObject *invoke_raw(MonoObject *p_object, void **p_params, MonoException **r_exc = nullptr) const;
-
- String get_full_name(bool p_signature = false) const;
- String get_full_name_no_class() const;
- String get_ret_type_full_name() const;
- String get_signature_desc(bool p_namespaces = false) const;
-
- void get_parameter_names(Vector<StringName> &names) const;
- void get_parameter_types(Vector<ManagedType> &types) const;
-
- const MethodInfo &get_method_info();
-
- GDMonoMethod(StringName p_name, MonoMethod *p_method);
- ~GDMonoMethod();
-};
-
-#endif // GD_MONO_METHOD_H
diff --git a/modules/mono/mono_gd/gd_mono_method_thunk.h b/modules/mono/mono_gd/gd_mono_method_thunk.h
deleted file mode 100644
index 0180dee3ea..0000000000
--- a/modules/mono/mono_gd/gd_mono_method_thunk.h
+++ /dev/null
@@ -1,320 +0,0 @@
-/*************************************************************************/
-/* gd_mono_method_thunk.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 GD_MONO_METHOD_THUNK_H
-#define GD_MONO_METHOD_THUNK_H
-
-#include <type_traits>
-
-#include "gd_mono_class.h"
-#include "gd_mono_header.h"
-#include "gd_mono_marshal.h"
-#include "gd_mono_method.h"
-#include "gd_mono_utils.h"
-
-#if !defined(JAVASCRIPT_ENABLED) && !defined(IOS_ENABLED)
-#define HAVE_METHOD_THUNKS
-#endif
-
-#ifdef HAVE_METHOD_THUNKS
-
-template <class... ParamTypes>
-struct GDMonoMethodThunk {
- typedef void(GD_MONO_STDCALL *M)(ParamTypes... p_args, MonoException **);
-
- M mono_method_thunk = nullptr;
-
-public:
- _FORCE_INLINE_ void invoke(ParamTypes... p_args, MonoException **r_exc) {
- GD_MONO_BEGIN_RUNTIME_INVOKE;
- mono_method_thunk(p_args..., r_exc);
- GD_MONO_END_RUNTIME_INVOKE;
- }
-
- _FORCE_INLINE_ bool is_null() {
- return mono_method_thunk == nullptr;
- }
-
- _FORCE_INLINE_ void nullify() {
- mono_method_thunk = nullptr;
- }
-
- _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_mono_method == nullptr);
- CRASH_COND(p_mono_method->get_return_type().type_encoding != MONO_TYPE_VOID);
-
- if (p_mono_method->is_static()) {
- CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes));
- } else {
- CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1));
- }
-#endif
- mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr());
- }
-
- GDMonoMethodThunk() {}
-
- explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) {
- set_from_method(p_mono_method);
- }
-};
-
-template <class R, class... ParamTypes>
-struct GDMonoMethodThunkR {
- typedef R(GD_MONO_STDCALL *M)(ParamTypes... p_args, MonoException **);
-
- M mono_method_thunk = nullptr;
-
-public:
- _FORCE_INLINE_ R invoke(ParamTypes... p_args, MonoException **r_exc) {
- GD_MONO_BEGIN_RUNTIME_INVOKE;
- R r = mono_method_thunk(p_args..., r_exc);
- GD_MONO_END_RUNTIME_INVOKE;
- return r;
- }
-
- _FORCE_INLINE_ bool is_null() {
- return mono_method_thunk == nullptr;
- }
-
- _FORCE_INLINE_ void nullify() {
- mono_method_thunk = nullptr;
- }
-
- _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_mono_method == nullptr);
- CRASH_COND(p_mono_method->get_return_type().type_encoding == MONO_TYPE_VOID);
-
- if (p_mono_method->is_static()) {
- CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes));
- } else {
- CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1));
- }
-#endif
- mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr());
- }
-
- GDMonoMethodThunkR() {}
-
- explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_mono_method == nullptr);
-#endif
- mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr());
- }
-};
-
-#else
-
-template <unsigned int ThunkParamCount, class P1, class... ParamTypes>
-struct VariadicInvokeMonoMethodImpl {
- static void invoke(GDMonoMethod *p_mono_method, P1 p_arg1, ParamTypes... p_args, MonoException **r_exc) {
- if (p_mono_method->is_static()) {
- void *args[ThunkParamCount] = { p_arg1, p_args... };
- p_mono_method->invoke_raw(nullptr, args, r_exc);
- } else {
- void *args[ThunkParamCount] = { p_args... };
- p_mono_method->invoke_raw((MonoObject *)p_arg1, args, r_exc);
- }
- }
-};
-
-template <unsigned int ThunkParamCount, class... ParamTypes>
-struct VariadicInvokeMonoMethod {
- static void invoke(GDMonoMethod *p_mono_method, ParamTypes... p_args, MonoException **r_exc) {
- VariadicInvokeMonoMethodImpl<ThunkParamCount, ParamTypes...>::invoke(p_mono_method, p_args..., r_exc);
- }
-};
-
-template <>
-struct VariadicInvokeMonoMethod<0> {
- static void invoke(GDMonoMethod *p_mono_method, MonoException **r_exc) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(!p_mono_method->is_static());
-#endif
- p_mono_method->invoke_raw(nullptr, nullptr, r_exc);
- }
-};
-
-template <class P1>
-struct VariadicInvokeMonoMethod<1, P1> {
- static void invoke(GDMonoMethod *p_mono_method, P1 p_arg1, MonoException **r_exc) {
- if (p_mono_method->is_static()) {
- void *args[1] = { p_arg1 };
- p_mono_method->invoke_raw(nullptr, args, r_exc);
- } else {
- p_mono_method->invoke_raw((MonoObject *)p_arg1, nullptr, r_exc);
- }
- }
-};
-
-template <class R>
-R unbox_if_needed(MonoObject *p_val, const ManagedType &, typename std::enable_if<!std::is_pointer<R>::value>::type * = 0) {
- return GDMonoMarshal::unbox<R>(p_val);
-}
-
-template <class R>
-R unbox_if_needed(MonoObject *p_val, const ManagedType &p_type, typename std::enable_if<std::is_pointer<R>::value>::type * = 0) {
- if (mono_class_is_valuetype(p_type.type_class->get_mono_ptr())) {
- return GDMonoMarshal::unbox<R>(p_val);
- } else {
- // If it's not a value type, we assume 'R' is a pointer to 'MonoObject' or a compatible type, like 'MonoException'.
- return (R)p_val;
- }
-}
-
-template <unsigned int ThunkParamCount, class R, class P1, class... ParamTypes>
-struct VariadicInvokeMonoMethodRImpl {
- static R invoke(GDMonoMethod *p_mono_method, P1 p_arg1, ParamTypes... p_args, MonoException **r_exc) {
- if (p_mono_method->is_static()) {
- void *args[ThunkParamCount] = { p_arg1, p_args... };
- MonoObject *r = p_mono_method->invoke_raw(nullptr, args, r_exc);
- return unbox_if_needed<R>(r, p_mono_method->get_return_type());
- } else {
- void *args[ThunkParamCount] = { p_args... };
- MonoObject *r = p_mono_method->invoke_raw((MonoObject *)p_arg1, args, r_exc);
- return unbox_if_needed<R>(r, p_mono_method->get_return_type());
- }
- }
-};
-
-template <unsigned int ThunkParamCount, class R, class... ParamTypes>
-struct VariadicInvokeMonoMethodR {
- static R invoke(GDMonoMethod *p_mono_method, ParamTypes... p_args, MonoException **r_exc) {
- return VariadicInvokeMonoMethodRImpl<ThunkParamCount, R, ParamTypes...>::invoke(p_mono_method, p_args..., r_exc);
- }
-};
-
-template <class R>
-struct VariadicInvokeMonoMethodR<0, R> {
- static R invoke(GDMonoMethod *p_mono_method, MonoException **r_exc) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(!p_mono_method->is_static());
-#endif
- MonoObject *r = p_mono_method->invoke_raw(nullptr, nullptr, r_exc);
- return unbox_if_needed<R>(r, p_mono_method->get_return_type());
- }
-};
-
-template <class R, class P1>
-struct VariadicInvokeMonoMethodR<1, R, P1> {
- static R invoke(GDMonoMethod *p_mono_method, P1 p_arg1, MonoException **r_exc) {
- if (p_mono_method->is_static()) {
- void *args[1] = { p_arg1 };
- MonoObject *r = p_mono_method->invoke_raw(nullptr, args, r_exc);
- return unbox_if_needed<R>(r, p_mono_method->get_return_type());
- } else {
- MonoObject *r = p_mono_method->invoke_raw((MonoObject *)p_arg1, nullptr, r_exc);
- return unbox_if_needed<R>(r, p_mono_method->get_return_type());
- }
- }
-};
-
-template <class... ParamTypes>
-struct GDMonoMethodThunk {
- GDMonoMethod *mono_method = nullptr;
-
-public:
- _FORCE_INLINE_ void invoke(ParamTypes... p_args, MonoException **r_exc) {
- VariadicInvokeMonoMethod<sizeof...(ParamTypes), ParamTypes...>::invoke(mono_method, p_args..., r_exc);
- }
-
- _FORCE_INLINE_ bool is_null() {
- return mono_method == nullptr;
- }
-
- _FORCE_INLINE_ void nullify() {
- mono_method = nullptr;
- }
-
- _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_mono_method == nullptr);
- CRASH_COND(p_mono_method->get_return_type().type_encoding != MONO_TYPE_VOID);
-
- if (p_mono_method->is_static()) {
- CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes));
- } else {
- CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1));
- }
-#endif
- mono_method = p_mono_method;
- }
-
- GDMonoMethodThunk() {}
-
- explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) {
- set_from_method(p_mono_method);
- }
-};
-
-template <class R, class... ParamTypes>
-struct GDMonoMethodThunkR {
- GDMonoMethod *mono_method = nullptr;
-
-public:
- _FORCE_INLINE_ R invoke(ParamTypes... p_args, MonoException **r_exc) {
- return VariadicInvokeMonoMethodR<sizeof...(ParamTypes), R, ParamTypes...>::invoke(mono_method, p_args..., r_exc);
- }
-
- _FORCE_INLINE_ bool is_null() {
- return mono_method == nullptr;
- }
-
- _FORCE_INLINE_ void nullify() {
- mono_method = nullptr;
- }
-
- _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) {
-#ifdef DEBUG_ENABLED
- CRASH_COND(p_mono_method == nullptr);
- CRASH_COND(p_mono_method->get_return_type().type_encoding == MONO_TYPE_VOID);
-
- if (p_mono_method->is_static()) {
- CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes));
- } else {
- CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1));
- }
-#endif
- mono_method = p_mono_method;
- }
-
- GDMonoMethodThunkR() {}
-
- explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) {
- set_from_method(p_mono_method);
- }
-};
-
-#endif
-
-#endif // GD_MONO_METHOD_THUNK_H
diff --git a/modules/mono/mono_gd/gd_mono_property.cpp b/modules/mono/mono_gd/gd_mono_property.cpp
deleted file mode 100644
index c9775ae9cb..0000000000
--- a/modules/mono/mono_gd/gd_mono_property.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/*************************************************************************/
-/* gd_mono_property.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 "gd_mono_property.h"
-
-#include "gd_mono_cache.h"
-#include "gd_mono_class.h"
-#include "gd_mono_marshal.h"
-#include "gd_mono_utils.h"
-
-#include <mono/metadata/attrdefs.h>
-
-GDMonoProperty::GDMonoProperty(MonoProperty *p_mono_property, GDMonoClass *p_owner) {
- owner = p_owner;
- mono_property = p_mono_property;
- name = String::utf8(mono_property_get_name(mono_property));
-
- MonoMethod *prop_method = mono_property_get_get_method(mono_property);
-
- if (prop_method) {
- MonoMethodSignature *getter_sig = mono_method_signature(prop_method);
-
- MonoType *ret_type = mono_signature_get_return_type(getter_sig);
-
- type.type_encoding = mono_type_get_type(ret_type);
- MonoClass *ret_type_class = mono_class_from_mono_type(ret_type);
- type.type_class = GDMono::get_singleton()->get_class(ret_type_class);
- } else {
- prop_method = mono_property_get_set_method(mono_property);
-
- MonoMethodSignature *setter_sig = mono_method_signature(prop_method);
-
- void *iter = nullptr;
- MonoType *param_raw_type = mono_signature_get_params(setter_sig, &iter);
-
- type.type_encoding = mono_type_get_type(param_raw_type);
- MonoClass *param_type_class = mono_class_from_mono_type(param_raw_type);
- type.type_class = GDMono::get_singleton()->get_class(param_type_class);
- }
-
- param_buffer_size = GDMonoMarshal::variant_get_managed_unboxed_size(type);
-
- attrs_fetched = false;
- attributes = nullptr;
-}
-
-GDMonoProperty::~GDMonoProperty() {
- if (attributes) {
- mono_custom_attrs_free(attributes);
- }
-}
-
-bool GDMonoProperty::is_static() {
- MonoMethod *prop_method = mono_property_get_get_method(mono_property);
- if (prop_method == nullptr) {
- prop_method = mono_property_get_set_method(mono_property);
- }
- return mono_method_get_flags(prop_method, nullptr) & MONO_METHOD_ATTR_STATIC;
-}
-
-IMonoClassMember::Visibility GDMonoProperty::get_visibility() {
- MonoMethod *prop_method = mono_property_get_get_method(mono_property);
- if (prop_method == nullptr) {
- prop_method = mono_property_get_set_method(mono_property);
- }
-
- switch (mono_method_get_flags(prop_method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK) {
- case MONO_METHOD_ATTR_PRIVATE:
- return IMonoClassMember::PRIVATE;
- case MONO_METHOD_ATTR_FAM_AND_ASSEM:
- return IMonoClassMember::PROTECTED_AND_INTERNAL;
- case MONO_METHOD_ATTR_ASSEM:
- return IMonoClassMember::INTERNAL;
- case MONO_METHOD_ATTR_FAMILY:
- return IMonoClassMember::PROTECTED;
- case MONO_METHOD_ATTR_PUBLIC:
- return IMonoClassMember::PUBLIC;
- default:
- ERR_FAIL_V(IMonoClassMember::PRIVATE);
- }
-}
-
-bool GDMonoProperty::has_attribute(GDMonoClass *p_attr_class) {
- ERR_FAIL_NULL_V(p_attr_class, false);
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return false;
- }
-
- return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-MonoObject *GDMonoProperty::get_attribute(GDMonoClass *p_attr_class) {
- ERR_FAIL_NULL_V(p_attr_class, nullptr);
-
- if (!attrs_fetched) {
- fetch_attributes();
- }
-
- if (!attributes) {
- return nullptr;
- }
-
- return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
-}
-
-void GDMonoProperty::fetch_attributes() {
- ERR_FAIL_COND(attributes != nullptr);
- attributes = mono_custom_attrs_from_property(owner->get_mono_ptr(), mono_property);
- attrs_fetched = true;
-}
-
-bool GDMonoProperty::has_getter() {
- return mono_property_get_get_method(mono_property) != nullptr;
-}
-
-bool GDMonoProperty::has_setter() {
- return mono_property_get_set_method(mono_property) != nullptr;
-}
-
-void GDMonoProperty::set_value_from_variant(MonoObject *p_object, const Variant &p_value, MonoException **r_exc) {
- uint8_t *buffer = (uint8_t *)alloca(param_buffer_size);
- unsigned int offset = 0;
-
- void *params[1] = {
- GDMonoMarshal::variant_to_managed_unboxed(p_value, type, buffer, offset)
- };
-
-#ifdef DEBUG_ENABLED
- CRASH_COND(offset != param_buffer_size);
-#endif
-
- MonoException *exc = nullptr;
- GDMonoUtils::property_set_value(mono_property, p_object, params, &exc);
- if (exc) {
- if (r_exc) {
- *r_exc = exc;
- } else {
- GDMonoUtils::set_pending_exception(exc);
- }
- }
-}
-
-MonoObject *GDMonoProperty::get_value(MonoObject *p_object, MonoException **r_exc) {
- MonoException *exc = nullptr;
- MonoObject *ret = GDMonoUtils::property_get_value(mono_property, p_object, nullptr, &exc);
-
- if (exc) {
- ret = nullptr;
- if (r_exc) {
- *r_exc = exc;
- } else {
- GDMonoUtils::set_pending_exception(exc);
- }
- }
-
- return ret;
-}
-
-bool GDMonoProperty::get_bool_value(MonoObject *p_object) {
- return (bool)GDMonoMarshal::unbox<MonoBoolean>(get_value(p_object));
-}
-
-int GDMonoProperty::get_int_value(MonoObject *p_object) {
- return GDMonoMarshal::unbox<int32_t>(get_value(p_object));
-}
-
-String GDMonoProperty::get_string_value(MonoObject *p_object) {
- MonoObject *val = get_value(p_object);
- return GDMonoMarshal::mono_string_to_godot((MonoString *)val);
-}
diff --git a/modules/mono/mono_gd/gd_mono_property.h b/modules/mono/mono_gd/gd_mono_property.h
deleted file mode 100644
index 6fc681aeb5..0000000000
--- a/modules/mono/mono_gd/gd_mono_property.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*************************************************************************/
-/* gd_mono_property.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 GD_MONO_PROPERTY_H
-#define GD_MONO_PROPERTY_H
-
-#include "gd_mono.h"
-#include "gd_mono_header.h"
-#include "i_mono_class_member.h"
-
-class GDMonoProperty : public IMonoClassMember {
- GDMonoClass *owner = nullptr;
- MonoProperty *mono_property = nullptr;
-
- StringName name;
- ManagedType type;
-
- bool attrs_fetched;
- MonoCustomAttrInfo *attributes = nullptr;
-
- unsigned int param_buffer_size;
-
-public:
- virtual GDMonoClass *get_enclosing_class() const final { return owner; }
-
- virtual MemberType get_member_type() const final { return MEMBER_TYPE_PROPERTY; }
-
- virtual StringName get_name() const final { return name; }
-
- virtual bool is_static() final;
- virtual Visibility get_visibility() final;
-
- virtual bool has_attribute(GDMonoClass *p_attr_class) final;
- virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) final;
- void fetch_attributes();
-
- bool has_getter();
- bool has_setter();
-
- _FORCE_INLINE_ ManagedType get_type() const { return type; }
-
- void set_value_from_variant(MonoObject *p_object, const Variant &p_value, MonoException **r_exc = nullptr);
- MonoObject *get_value(MonoObject *p_object, MonoException **r_exc = nullptr);
-
- bool get_bool_value(MonoObject *p_object);
- int get_int_value(MonoObject *p_object);
- String get_string_value(MonoObject *p_object);
-
- GDMonoProperty(MonoProperty *p_mono_property, GDMonoClass *p_owner);
- ~GDMonoProperty();
-};
-
-#endif // GD_MONO_PROPERTY_H
diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp
deleted file mode 100644
index 1983d6ebe2..0000000000
--- a/modules/mono/mono_gd/gd_mono_utils.cpp
+++ /dev/null
@@ -1,677 +0,0 @@
-/*************************************************************************/
-/* gd_mono_utils.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 "gd_mono_utils.h"
-
-#include <mono/metadata/debug-helpers.h>
-#include <mono/metadata/exception.h>
-
-#include "core/debugger/engine_debugger.h"
-#include "core/debugger/script_debugger.h"
-#include "core/io/dir_access.h"
-#include "core/object/ref_counted.h"
-#include "core/os/mutex.h"
-#include "core/os/os.h"
-
-#ifdef TOOLS_ENABLED
-#include "editor/debugger/editor_debugger_node.h"
-#endif
-
-#include "../csharp_script.h"
-#include "../utils/macros.h"
-#include "gd_mono.h"
-#include "gd_mono_cache.h"
-#include "gd_mono_class.h"
-#include "gd_mono_marshal.h"
-
-namespace GDMonoUtils {
-
-MonoObject *unmanaged_get_managed(Object *unmanaged) {
- if (!unmanaged) {
- return nullptr;
- }
-
- if (unmanaged->get_script_instance()) {
- CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(unmanaged->get_script_instance());
-
- if (cs_instance) {
- return cs_instance->get_mono_object();
- }
- }
-
- // If the owner does not have a CSharpInstance...
-
- void *data = CSharpLanguage::get_instance_binding(unmanaged);
- ERR_FAIL_NULL_V(data, nullptr);
- CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->value();
- ERR_FAIL_COND_V(!script_binding.inited, nullptr);
-
- MonoGCHandleData &gchandle = script_binding.gchandle;
-
- MonoObject *target = gchandle.get_target();
-
- if (target) {
- return target;
- }
-
- CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
-
- // Create a new one
-
-#ifdef DEBUG_ENABLED
- CRASH_COND(script_binding.type_name == StringName());
- CRASH_COND(script_binding.wrapper_class == nullptr);
-#endif
-
- MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(script_binding.wrapper_class, script_binding.type_name, unmanaged);
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- gchandle = MonoGCHandleData::new_strong_handle(mono_object);
-
- // Tie managed to unmanaged
- RefCounted *rc = Object::cast_to<RefCounted>(unmanaged);
-
- if (rc) {
- // Unsafe refcount increment. The managed instance also counts as a reference.
- // This way if the unmanaged world has no references to our owner
- // but the managed instance is alive, the refcount will be 1 instead of 0.
- // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
- rc->reference();
- CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
- }
-
- return mono_object;
-}
-
-void set_main_thread(MonoThread *p_thread) {
- mono_thread_set_main(p_thread);
-}
-
-MonoThread *attach_current_thread() {
- ERR_FAIL_COND_V(!GDMono::get_singleton()->is_runtime_initialized(), nullptr);
- MonoDomain *scripts_domain = GDMono::get_singleton()->get_scripts_domain();
-#ifndef GD_MONO_SINGLE_APPDOMAIN
- MonoThread *mono_thread = mono_thread_attach(scripts_domain ? scripts_domain : mono_get_root_domain());
-#else
- // The scripts domain is the root domain
- MonoThread *mono_thread = mono_thread_attach(scripts_domain);
-#endif
- ERR_FAIL_NULL_V(mono_thread, nullptr);
- return mono_thread;
-}
-
-void detach_current_thread() {
- ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized());
- MonoThread *mono_thread = mono_thread_current();
- ERR_FAIL_NULL(mono_thread);
- mono_thread_detach(mono_thread);
-}
-
-void detach_current_thread(MonoThread *p_mono_thread) {
- ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized());
- ERR_FAIL_NULL(p_mono_thread);
- mono_thread_detach(p_mono_thread);
-}
-
-MonoThread *get_current_thread() {
- return mono_thread_current();
-}
-
-bool is_thread_attached() {
- return mono_domain_get() != nullptr;
-}
-
-uint32_t new_strong_gchandle(MonoObject *p_object) {
- return mono_gchandle_new(p_object, /* pinned: */ false);
-}
-
-uint32_t new_strong_gchandle_pinned(MonoObject *p_object) {
- return mono_gchandle_new(p_object, /* pinned: */ true);
-}
-
-uint32_t new_weak_gchandle(MonoObject *p_object) {
- return mono_gchandle_new_weakref(p_object, /* track_resurrection: */ false);
-}
-
-void free_gchandle(uint32_t p_gchandle) {
- mono_gchandle_free(p_gchandle);
-}
-
-void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc) {
- GDMonoMethod *ctor = p_class->get_method(".ctor", 0);
- ERR_FAIL_NULL(ctor);
- ctor->invoke_raw(p_this_obj, nullptr, r_exc);
-}
-
-bool mono_delegate_equal(MonoDelegate *p_a, MonoDelegate *p_b) {
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(Delegate, Equals).invoke((MonoObject *)p_a, (MonoObject *)p_b, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-GDMonoClass *get_object_class(MonoObject *p_object) {
- return GDMono::get_singleton()->get_class(mono_object_get_class(p_object));
-}
-
-GDMonoClass *type_get_proxy_class(const StringName &p_type) {
- String class_name = p_type;
-
- if (class_name[0] == '_') {
- class_name = class_name.substr(1, class_name.length());
- }
-
- GDMonoClass *klass = GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, class_name);
-
- if (klass && klass->is_static()) {
- // A static class means this is a Godot singleton class. If an instance is needed we use Godot.Object.
- return GDMonoCache::cached_data.class_GodotObject;
- }
-
-#ifdef TOOLS_ENABLED
- if (!klass) {
- return GDMono::get_singleton()->get_editor_api_assembly()->get_class(BINDINGS_NAMESPACE, class_name);
- }
-#endif
-
- return klass;
-}
-
-GDMonoClass *get_class_native_base(GDMonoClass *p_class) {
- GDMonoClass *klass = p_class;
-
- do {
- const GDMonoAssembly *assembly = klass->get_assembly();
-
- if (assembly == GDMono::get_singleton()->get_core_api_assembly()) {
- return klass;
- }
-#ifdef TOOLS_ENABLED
- if (assembly == GDMono::get_singleton()->get_editor_api_assembly()) {
- return klass;
- }
-#endif
- } while ((klass = klass->get_parent_class()) != nullptr);
-
- return nullptr;
-}
-
-MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object) {
- bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), p_native);
- ERR_FAIL_COND_V_MSG(!parent_is_object_class, nullptr,
- "Type inherits from native type '" + p_native + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'.");
-
- MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, p_object);
-
- // Construct
- GDMonoUtils::runtime_object_init(mono_object, p_class);
-
- return mono_object;
-}
-
-MonoObject *create_managed_from(const StringName &p_from) {
- MonoObject *mono_object = mono_object_new(mono_domain_get(), CACHED_CLASS_RAW(StringName));
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- // Construct
- GDMonoUtils::runtime_object_init(mono_object, CACHED_CLASS(StringName));
-
- CACHED_FIELD(StringName, ptr)->set_value_raw(mono_object, memnew(StringName(p_from)));
-
- return mono_object;
-}
-
-MonoObject *create_managed_from(const NodePath &p_from) {
- MonoObject *mono_object = mono_object_new(mono_domain_get(), CACHED_CLASS_RAW(NodePath));
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- // Construct
- GDMonoUtils::runtime_object_init(mono_object, CACHED_CLASS(NodePath));
-
- CACHED_FIELD(NodePath, ptr)->set_value_raw(mono_object, memnew(NodePath(p_from)));
-
- return mono_object;
-}
-
-MonoObject *create_managed_from(const RID &p_from) {
- MonoObject *mono_object = mono_object_new(mono_domain_get(), CACHED_CLASS_RAW(RID));
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- // Construct
- GDMonoUtils::runtime_object_init(mono_object, CACHED_CLASS(RID));
-
- CACHED_FIELD(RID, ptr)->set_value_raw(mono_object, memnew(RID(p_from)));
-
- return mono_object;
-}
-
-MonoObject *create_managed_from(const Array &p_from, GDMonoClass *p_class) {
- MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- // Search constructor that takes a pointer as parameter
- MonoMethod *m;
- void *iter = nullptr;
- while ((m = mono_class_get_methods(p_class->get_mono_ptr(), &iter))) {
- if (strcmp(mono_method_get_name(m), ".ctor") == 0) {
- MonoMethodSignature *sig = mono_method_signature(m);
- void *front = nullptr;
- if (mono_signature_get_param_count(sig) == 1 &&
- mono_class_from_mono_type(mono_signature_get_params(sig, &front)) == CACHED_CLASS(IntPtr)->get_mono_ptr()) {
- break;
- }
- }
- }
-
- CRASH_COND(m == nullptr);
-
- Array *new_array = memnew(Array(p_from));
- void *args[1] = { &new_array };
-
- MonoException *exc = nullptr;
- GDMonoUtils::runtime_invoke(m, mono_object, args, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- return mono_object;
-}
-
-MonoObject *create_managed_from(const Dictionary &p_from, GDMonoClass *p_class) {
- MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
- ERR_FAIL_NULL_V(mono_object, nullptr);
-
- // Search constructor that takes a pointer as parameter
- MonoMethod *m;
- void *iter = nullptr;
- while ((m = mono_class_get_methods(p_class->get_mono_ptr(), &iter))) {
- if (strcmp(mono_method_get_name(m), ".ctor") == 0) {
- MonoMethodSignature *sig = mono_method_signature(m);
- void *front = nullptr;
- if (mono_signature_get_param_count(sig) == 1 &&
- mono_class_from_mono_type(mono_signature_get_params(sig, &front)) == CACHED_CLASS(IntPtr)->get_mono_ptr()) {
- break;
- }
- }
- }
-
- CRASH_COND(m == nullptr);
-
- Dictionary *new_dict = memnew(Dictionary(p_from));
- void *args[1] = { &new_dict };
-
- MonoException *exc = nullptr;
- GDMonoUtils::runtime_invoke(m, mono_object, args, &exc);
- UNHANDLED_EXCEPTION(exc);
-
- return mono_object;
-}
-
-MonoDomain *create_domain(const String &p_friendly_name) {
- print_verbose("Mono: Creating domain '" + p_friendly_name + "'...");
-
- MonoDomain *domain = mono_domain_create_appdomain((char *)p_friendly_name.utf8().get_data(), nullptr);
-
- if (domain) {
- // Workaround to avoid this exception:
- // System.Configuration.ConfigurationErrorsException: Error Initializing the configuration system.
- // ---> System.ArgumentException: The 'ExeConfigFilename' argument cannot be null.
- mono_domain_set_config(domain, ".", "");
- }
-
- return domain;
-}
-
-String get_type_desc(MonoType *p_type) {
- return mono_type_full_name(p_type);
-}
-
-String get_type_desc(MonoReflectionType *p_reftype) {
- return get_type_desc(mono_reflection_type_get_type(p_reftype));
-}
-
-String get_exception_name_and_message(MonoException *p_exc) {
- String res;
-
- MonoClass *klass = mono_object_get_class((MonoObject *)p_exc);
- MonoType *type = mono_class_get_type(klass);
-
- char *full_name = mono_type_full_name(type);
- res += full_name;
- mono_free(full_name);
-
- res += ": ";
-
- MonoProperty *prop = mono_class_get_property_from_name(klass, "Message");
- MonoString *msg = (MonoString *)property_get_value(prop, (MonoObject *)p_exc, nullptr, nullptr);
- res += GDMonoMarshal::mono_string_to_godot(msg);
-
- return res;
-}
-
-void debug_print_unhandled_exception(MonoException *p_exc) {
- print_unhandled_exception(p_exc);
- debug_send_unhandled_exception_error(p_exc);
-}
-
-void debug_send_unhandled_exception_error(MonoException *p_exc) {
-#ifdef DEBUG_ENABLED
- if (!EngineDebugger::is_active()) {
-#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
- ERR_PRINT(GDMonoUtils::get_exception_name_and_message(p_exc));
- }
-#endif
- return;
- }
-
- static thread_local bool _recursion_flag_ = false;
- if (_recursion_flag_) {
- return;
- }
- _recursion_flag_ = true;
- SCOPE_EXIT { _recursion_flag_ = false; };
-
- ScriptLanguage::StackInfo separator;
- separator.file = String();
- separator.func = "--- " + RTR("End of inner exception stack trace") + " ---";
- separator.line = 0;
-
- Vector<ScriptLanguage::StackInfo> si;
- String exc_msg;
-
- while (p_exc != nullptr) {
- GDMonoClass *st_klass = CACHED_CLASS(System_Diagnostics_StackTrace);
- MonoObject *stack_trace = mono_object_new(mono_domain_get(), st_klass->get_mono_ptr());
-
- MonoBoolean need_file_info = true;
- void *ctor_args[2] = { p_exc, &need_file_info };
-
- MonoException *unexpected_exc = nullptr;
- CACHED_METHOD(System_Diagnostics_StackTrace, ctor_Exception_bool)->invoke_raw(stack_trace, ctor_args, &unexpected_exc);
-
- if (unexpected_exc) {
- GDMonoInternals::unhandled_exception(unexpected_exc);
- return;
- }
-
- Vector<ScriptLanguage::StackInfo> _si;
- if (stack_trace != nullptr) {
- _si = CSharpLanguage::get_singleton()->stack_trace_get_info(stack_trace);
- for (int i = _si.size() - 1; i >= 0; i--) {
- si.insert(0, _si[i]);
- }
- }
-
- exc_msg += (exc_msg.length() > 0 ? " ---> " : "") + GDMonoUtils::get_exception_name_and_message(p_exc);
-
- GDMonoClass *exc_class = GDMono::get_singleton()->get_class(mono_get_exception_class());
- GDMonoProperty *inner_exc_prop = exc_class->get_property("InnerException");
- CRASH_COND(inner_exc_prop == nullptr);
-
- MonoObject *inner_exc = inner_exc_prop->get_value((MonoObject *)p_exc);
- if (inner_exc != nullptr) {
- si.insert(0, separator);
- }
-
- p_exc = (MonoException *)inner_exc;
- }
-
- String file = si.size() ? si[0].file : __FILE__;
- String func = si.size() ? si[0].func : FUNCTION_STR;
- int line = si.size() ? si[0].line : __LINE__;
- String error_msg = "Unhandled exception";
-
- EngineDebugger::get_script_debugger()->send_error(func, file, line, error_msg, exc_msg, true, ERR_HANDLER_ERROR, si);
-#endif
-}
-
-void debug_unhandled_exception(MonoException *p_exc) {
- GDMonoInternals::unhandled_exception(p_exc); // prints the exception as well
-}
-
-void print_unhandled_exception(MonoException *p_exc) {
- mono_print_unhandled_exception((MonoObject *)p_exc);
-}
-
-void set_pending_exception(MonoException *p_exc) {
-#ifdef NO_PENDING_EXCEPTIONS
- debug_unhandled_exception(p_exc);
-#else
- if (get_runtime_invoke_count() == 0) {
- debug_unhandled_exception(p_exc);
- return;
- }
-
- if (!mono_runtime_set_pending_exception(p_exc, false)) {
- ERR_PRINT("Exception thrown from managed code, but it could not be set as pending:");
- GDMonoUtils::debug_print_unhandled_exception(p_exc);
- }
-#endif
-}
-
-thread_local int current_invoke_count = 0;
-
-MonoObject *runtime_invoke(MonoMethod *p_method, void *p_obj, void **p_params, MonoException **r_exc) {
- GD_MONO_BEGIN_RUNTIME_INVOKE;
- MonoObject *ret = mono_runtime_invoke(p_method, p_obj, p_params, (MonoObject **)r_exc);
- GD_MONO_END_RUNTIME_INVOKE;
- return ret;
-}
-
-MonoString *object_to_string(MonoObject *p_obj, MonoException **r_exc) {
- GD_MONO_BEGIN_RUNTIME_INVOKE;
- MonoString *ret = mono_object_to_string(p_obj, (MonoObject **)r_exc);
- GD_MONO_END_RUNTIME_INVOKE;
- return ret;
-}
-
-void property_set_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc) {
- GD_MONO_BEGIN_RUNTIME_INVOKE;
- mono_property_set_value(p_prop, p_obj, p_params, (MonoObject **)r_exc);
- GD_MONO_END_RUNTIME_INVOKE;
-}
-
-MonoObject *property_get_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc) {
- GD_MONO_BEGIN_RUNTIME_INVOKE;
- MonoObject *ret = mono_property_get_value(p_prop, p_obj, p_params, (MonoObject **)r_exc);
- GD_MONO_END_RUNTIME_INVOKE;
- return ret;
-}
-
-uint64_t unbox_enum_value(MonoObject *p_boxed, MonoType *p_enum_basetype, bool &r_error) {
- r_error = false;
- switch (mono_type_get_type(p_enum_basetype)) {
- case MONO_TYPE_BOOLEAN:
- return (bool)GDMonoMarshal::unbox<MonoBoolean>(p_boxed) ? 1 : 0;
- case MONO_TYPE_CHAR:
- return GDMonoMarshal::unbox<uint16_t>(p_boxed);
- case MONO_TYPE_U1:
- return GDMonoMarshal::unbox<uint8_t>(p_boxed);
- case MONO_TYPE_U2:
- return GDMonoMarshal::unbox<uint16_t>(p_boxed);
- case MONO_TYPE_U4:
- return GDMonoMarshal::unbox<uint32_t>(p_boxed);
- case MONO_TYPE_U8:
- return GDMonoMarshal::unbox<uint64_t>(p_boxed);
- case MONO_TYPE_I1:
- return GDMonoMarshal::unbox<int8_t>(p_boxed);
- case MONO_TYPE_I2:
- return GDMonoMarshal::unbox<int16_t>(p_boxed);
- case MONO_TYPE_I4:
- return GDMonoMarshal::unbox<int32_t>(p_boxed);
- case MONO_TYPE_I8:
- return GDMonoMarshal::unbox<int64_t>(p_boxed);
- default:
- r_error = true;
- return 0;
- }
-}
-
-void dispose(MonoObject *p_mono_object, MonoException **r_exc) {
- CACHED_METHOD_THUNK(GodotObject, Dispose).invoke(p_mono_object, r_exc);
-}
-
-namespace Marshal {
-
-#ifdef MONO_GLUE_ENABLED
-#ifdef TOOLS_ENABLED
-#define NO_GLUE_RET(m_ret) \
- { \
- if (!GDMonoCache::cached_data.godot_api_cache_updated) \
- return m_ret; \
- }
-#else
-#define NO_GLUE_RET(m_ret) \
- {}
-#endif
-#else
-#define NO_GLUE_RET(m_ret) \
- { return m_ret; }
-#endif
-
-bool type_is_generic_array(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericArray).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-bool type_is_generic_dictionary(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericDictionary).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-bool type_is_system_generic_list(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsSystemGenericList).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-bool type_is_system_generic_dictionary(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsSystemGenericDictionary).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-bool type_is_generic_ienumerable(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericIEnumerable).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-bool type_is_generic_icollection(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericICollection).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-bool type_is_generic_idictionary(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericIDictionary).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-bool type_has_flags_attribute(MonoReflectionType *p_reftype) {
- NO_GLUE_RET(false);
- MonoException *exc = nullptr;
- MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeHasFlagsAttribute).invoke(p_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return (bool)res;
-}
-
-void get_generic_type_definition(MonoReflectionType *p_reftype, MonoReflectionType **r_generic_reftype) {
- MonoException *exc = nullptr;
- CACHED_METHOD_THUNK(MarshalUtils, GetGenericTypeDefinition).invoke(p_reftype, r_generic_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
-}
-
-void array_get_element_type(MonoReflectionType *p_array_reftype, MonoReflectionType **r_elem_reftype) {
- MonoException *exc = nullptr;
- CACHED_METHOD_THUNK(MarshalUtils, ArrayGetElementType).invoke(p_array_reftype, r_elem_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
-}
-
-void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype) {
- MonoException *exc = nullptr;
- CACHED_METHOD_THUNK(MarshalUtils, DictionaryGetKeyValueTypes).invoke(p_dict_reftype, r_key_reftype, r_value_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
-}
-
-GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype) {
- NO_GLUE_RET(nullptr);
- MonoException *exc = nullptr;
- MonoReflectionType *reftype = CACHED_METHOD_THUNK(MarshalUtils, MakeGenericArrayType).invoke(p_elem_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype)));
-}
-
-GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype) {
- NO_GLUE_RET(nullptr);
- MonoException *exc = nullptr;
- MonoReflectionType *reftype = CACHED_METHOD_THUNK(MarshalUtils, MakeGenericDictionaryType).invoke(p_key_reftype, p_value_reftype, &exc);
- UNHANDLED_EXCEPTION(exc);
- return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype)));
-}
-} // namespace Marshal
-
-ScopeThreadAttach::ScopeThreadAttach() {
- if (likely(GDMono::get_singleton()->is_runtime_initialized()) && unlikely(!mono_domain_get())) {
- mono_thread = GDMonoUtils::attach_current_thread();
- }
-}
-
-ScopeThreadAttach::~ScopeThreadAttach() {
- if (unlikely(mono_thread)) {
- GDMonoUtils::detach_current_thread(mono_thread);
- }
-}
-
-StringName get_native_godot_class_name(GDMonoClass *p_class) {
- MonoObject *native_name_obj = p_class->get_field(BINDINGS_NATIVE_NAME_FIELD)->get_value(nullptr);
- StringName *ptr = GDMonoMarshal::unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(native_name_obj));
- return ptr ? *ptr : StringName();
-}
-} // namespace GDMonoUtils
diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h
deleted file mode 100644
index 300cacfa4b..0000000000
--- a/modules/mono/mono_gd/gd_mono_utils.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/*************************************************************************/
-/* gd_mono_utils.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 GD_MONO_UTILS_H
-#define GD_MONO_UTILS_H
-
-#include <mono/metadata/threads.h>
-
-#include "../mono_gc_handle.h"
-#include "../utils/macros.h"
-#include "gd_mono_header.h"
-#ifdef JAVASCRIPT_ENABLED
-#include "gd_mono_wasm_m2n.h"
-#endif
-
-#include "core/object/class_db.h"
-#include "core/object/ref_counted.h"
-
-#define UNHANDLED_EXCEPTION(m_exc) \
- if (unlikely(m_exc != nullptr)) { \
- GDMonoUtils::debug_unhandled_exception(m_exc); \
- GD_UNREACHABLE(); \
- } else \
- ((void)0)
-
-namespace GDMonoUtils {
-
-namespace Marshal {
-
-bool type_is_generic_array(MonoReflectionType *p_reftype);
-bool type_is_generic_dictionary(MonoReflectionType *p_reftype);
-bool type_is_system_generic_list(MonoReflectionType *p_reftype);
-bool type_is_system_generic_dictionary(MonoReflectionType *p_reftype);
-bool type_is_generic_ienumerable(MonoReflectionType *p_reftype);
-bool type_is_generic_icollection(MonoReflectionType *p_reftype);
-bool type_is_generic_idictionary(MonoReflectionType *p_reftype);
-bool type_has_flags_attribute(MonoReflectionType *p_reftype);
-
-void get_generic_type_definition(MonoReflectionType *p_reftype, MonoReflectionType **r_generic_reftype);
-
-void array_get_element_type(MonoReflectionType *p_array_reftype, MonoReflectionType **r_elem_reftype);
-void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype);
-
-GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype);
-GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype);
-} // namespace Marshal
-
-_FORCE_INLINE_ void hash_combine(uint32_t &p_hash, const uint32_t &p_with_hash) {
- p_hash ^= p_with_hash + 0x9e3779b9 + (p_hash << 6) + (p_hash >> 2);
-}
-
-/**
- * If the object has a csharp script, returns the target of the gchandle stored in the script instance
- * Otherwise returns a newly constructed MonoObject* which is attached to the object
- * Returns nullptr on error
- */
-MonoObject *unmanaged_get_managed(Object *unmanaged);
-
-void set_main_thread(MonoThread *p_thread);
-MonoThread *attach_current_thread();
-void detach_current_thread();
-void detach_current_thread(MonoThread *p_mono_thread);
-MonoThread *get_current_thread();
-bool is_thread_attached();
-
-uint32_t new_strong_gchandle(MonoObject *p_object);
-uint32_t new_strong_gchandle_pinned(MonoObject *p_object);
-uint32_t new_weak_gchandle(MonoObject *p_object);
-void free_gchandle(uint32_t p_gchandle);
-
-void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc = nullptr);
-
-bool mono_delegate_equal(MonoDelegate *p_a, MonoDelegate *p_b);
-
-GDMonoClass *get_object_class(MonoObject *p_object);
-GDMonoClass *type_get_proxy_class(const StringName &p_type);
-GDMonoClass *get_class_native_base(GDMonoClass *p_class);
-
-MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object);
-
-MonoObject *create_managed_from(const StringName &p_from);
-MonoObject *create_managed_from(const NodePath &p_from);
-MonoObject *create_managed_from(const RID &p_from);
-MonoObject *create_managed_from(const Array &p_from, GDMonoClass *p_class);
-MonoObject *create_managed_from(const Dictionary &p_from, GDMonoClass *p_class);
-
-MonoDomain *create_domain(const String &p_friendly_name);
-
-String get_type_desc(MonoType *p_type);
-String get_type_desc(MonoReflectionType *p_reftype);
-
-String get_exception_name_and_message(MonoException *p_exc);
-
-void debug_print_unhandled_exception(MonoException *p_exc);
-void debug_send_unhandled_exception_error(MonoException *p_exc);
-void debug_unhandled_exception(MonoException *p_exc);
-void print_unhandled_exception(MonoException *p_exc);
-
-/**
- * Sets the exception as pending. The exception will be thrown when returning to managed code.
- * If no managed method is being invoked by the runtime, the exception will be treated as
- * an unhandled exception and the method will not return.
- */
-void set_pending_exception(MonoException *p_exc);
-
-extern thread_local int current_invoke_count;
-
-_FORCE_INLINE_ int get_runtime_invoke_count() {
- return current_invoke_count;
-}
-
-_FORCE_INLINE_ int &get_runtime_invoke_count_ref() {
- return current_invoke_count;
-}
-
-MonoObject *runtime_invoke(MonoMethod *p_method, void *p_obj, void **p_params, MonoException **r_exc);
-
-MonoString *object_to_string(MonoObject *p_obj, MonoException **r_exc);
-
-void property_set_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc);
-MonoObject *property_get_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc);
-
-uint64_t unbox_enum_value(MonoObject *p_boxed, MonoType *p_enum_basetype, bool &r_error);
-
-void dispose(MonoObject *p_mono_object, MonoException **r_exc);
-
-struct ScopeThreadAttach {
- ScopeThreadAttach();
- ~ScopeThreadAttach();
-
-private:
- MonoThread *mono_thread = nullptr;
-};
-
-StringName get_native_godot_class_name(GDMonoClass *p_class);
-
-template <typename... P>
-void add_internal_call(const char *p_name, void (*p_func)(P...)) {
-#ifdef JAVASCRIPT_ENABLED
- GDMonoWasmM2n::ICallTrampolines<P...>::add();
-#endif
- mono_add_internal_call(p_name, (void *)p_func);
-}
-
-template <typename R, typename... P>
-void add_internal_call(const char *p_name, R (*p_func)(P...)) {
-#ifdef JAVASCRIPT_ENABLED
- GDMonoWasmM2n::ICallTrampolinesR<R, P...>::add();
-#endif
- mono_add_internal_call(p_name, (void *)p_func);
-}
-} // namespace GDMonoUtils
-
-#define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoUtils::get_native_godot_class_name(m_class))
-
-#define GD_MONO_BEGIN_RUNTIME_INVOKE \
- int &_runtime_invoke_count_ref = GDMonoUtils::get_runtime_invoke_count_ref(); \
- _runtime_invoke_count_ref += 1; \
- ((void)0)
-
-#define GD_MONO_END_RUNTIME_INVOKE \
- _runtime_invoke_count_ref -= 1; \
- ((void)0)
-
-#define GD_MONO_SCOPE_THREAD_ATTACH \
- GDMonoUtils::ScopeThreadAttach __gdmono__scope__thread__attach__; \
- (void)__gdmono__scope__thread__attach__; \
- ((void)0)
-
-#ifdef DEBUG_ENABLED
-#define GD_MONO_ASSERT_THREAD_ATTACHED \
- CRASH_COND(!GDMonoUtils::is_thread_attached()); \
- ((void)0)
-#else
-#define GD_MONO_ASSERT_THREAD_ATTACHED ((void)0)
-#endif
-
-#endif // GD_MONO_UTILS_H
diff --git a/modules/mono/mono_gd/gd_mono_wasm_m2n.cpp b/modules/mono/mono_gd/gd_mono_wasm_m2n.cpp
deleted file mode 100644
index dbfca2dc0c..0000000000
--- a/modules/mono/mono_gd/gd_mono_wasm_m2n.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*************************************************************************/
-/* gd_mono_wasm_m2n.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 "gd_mono_wasm_m2n.h"
-
-#ifdef JAVASCRIPT_ENABLED
-
-#include "core/templates/oa_hash_map.h"
-
-typedef mono_bool (*GodotMonoM2nIcallTrampolineDispatch)(const char *cookie, void *target_func, Mono_InterpMethodArguments *margs);
-
-// This extern function is implemented in our patched version of Mono
-MONO_API void godot_mono_register_m2n_icall_trampoline_dispatch_hook(GodotMonoM2nIcallTrampolineDispatch hook);
-
-namespace GDMonoWasmM2n {
-
-struct HashMapCookieComparator {
- static bool compare(const char *p_lhs, const char *p_rhs) {
- return strcmp(p_lhs, p_rhs) == 0;
- }
-};
-
-// The default hasher supports 'const char *' C Strings, but we need a custom comparator
-OAHashMap<const char *, TrampolineFunc, HashMapHasherDefault, HashMapCookieComparator> trampolines;
-
-void set_trampoline(const char *cookies, GDMonoWasmM2n::TrampolineFunc trampoline_func) {
- trampolines.set(cookies, trampoline_func);
-}
-
-mono_bool trampoline_dispatch_hook(const char *cookie, void *target_func, Mono_InterpMethodArguments *margs) {
- TrampolineFunc *trampoline_func = trampolines.lookup_ptr(cookie);
-
- if (!trampoline_func) {
- return false;
- }
-
- (*trampoline_func)(target_func, margs);
- return true;
-}
-
-bool initialized = false;
-
-void lazy_initialize() {
- // Doesn't need to be thread safe
- if (!initialized) {
- initialized = true;
- godot_mono_register_m2n_icall_trampoline_dispatch_hook(&trampoline_dispatch_hook);
- }
-}
-} // namespace GDMonoWasmM2n
-
-#endif
diff --git a/modules/mono/mono_gd/gd_mono_wasm_m2n.h b/modules/mono/mono_gd/gd_mono_wasm_m2n.h
deleted file mode 100644
index 83e2750e5a..0000000000
--- a/modules/mono/mono_gd/gd_mono_wasm_m2n.h
+++ /dev/null
@@ -1,263 +0,0 @@
-/*************************************************************************/
-/* gd_mono_wasm_m2n.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 GD_MONO_WASM_M2N_H
-#define GD_MONO_WASM_M2N_H
-
-#ifdef JAVASCRIPT_ENABLED
-
-#include "core/string/ustring.h"
-#include "core/typedefs.h"
-
-#include <mono/metadata/loader.h>
-#include <mono/utils/mono-publib.h>
-#include <stdexcept>
-#include <type_traits>
-
-extern "C" {
-
-struct Mono_InterpMethodArguments {
- size_t ilen;
- void **iargs;
- size_t flen;
- double *fargs = nullptr;
- void **retval;
- size_t is_float_ret;
- //#ifdef TARGET_WASM
- void *sig = nullptr;
- //#endif
-};
-} // extern "C"
-
-namespace GDMonoWasmM2n {
-
-template <typename T, size_t Size>
-struct array {
- T elems[Size];
-};
-
-template <typename T>
-constexpr char get_m2n_cookie_impl() {
-#define M2N_REG_COOKIE(m_type, m_cookie) \
- if constexpr (std::is_same_v<m_type, T>) { \
- return m_cookie; \
- }
-
- M2N_REG_COOKIE(MonoBoolean, 'I');
- M2N_REG_COOKIE(int8_t, 'I');
- M2N_REG_COOKIE(uint8_t, 'I');
- M2N_REG_COOKIE(int16_t, 'I');
- M2N_REG_COOKIE(uint16_t, 'I');
- M2N_REG_COOKIE(int32_t, 'I');
- M2N_REG_COOKIE(uint32_t, 'I');
- M2N_REG_COOKIE(int64_t, 'L');
- M2N_REG_COOKIE(uint64_t, 'L');
- M2N_REG_COOKIE(float, 'F');
- M2N_REG_COOKIE(double, 'D');
-
- if constexpr (std::is_pointer_v<T>) {
- if constexpr (sizeof(void *) == 4) {
- return 'I';
- } else {
- return 'L';
- }
- }
-
- if constexpr (std::is_void_v<T>) {
- return 'V';
- }
-
- return 'X';
-
-#undef M2N_REG_COOKIE
-}
-
-template <typename T>
-constexpr char get_m2n_cookie() {
- constexpr char cookie = get_m2n_cookie_impl<T>();
- static_assert(cookie != 'X', "Type not supported in internal call signature.");
- return cookie;
-}
-
-template <typename... T>
-constexpr array<const char, sizeof...(T) + 2> get_m2n_cookies() {
- return array<const char, sizeof...(T) + 2>{ 'V', get_m2n_cookie<T>()..., '\0' };
-}
-
-template <typename R, typename... T>
-constexpr array<const char, sizeof...(T) + 2> get_m2n_cookies_r() {
- return array<const char, sizeof...(T) + 2>{ get_m2n_cookie<R>(), get_m2n_cookie<T>()..., '\0' };
-}
-
-template <typename T>
-constexpr size_t calc_m2n_index(size_t &r_int_idx, size_t &r_float_idx) {
- constexpr char cookie = get_m2n_cookie<T>();
-
- static_assert(cookie == 'I' || cookie == 'L' || cookie == 'F' || cookie == 'D');
-
- if constexpr (cookie == 'I' || cookie == 'L') {
- size_t ret = r_int_idx;
- r_int_idx += cookie == 'I' ? 1 : 2;
- return ret;
- } else {
- size_t ret = r_float_idx;
- r_float_idx += cookie == 'F' ? 1 : 2;
- return ret;
- }
-}
-
-template <typename... P>
-constexpr array<size_t, sizeof...(P)> get_indices_for_type() {
- size_t int_idx = 0;
- size_t float_idx = 0;
- return array<size_t, sizeof...(P)>{ calc_m2n_index<P>(int_idx, float_idx)... };
-}
-
-constexpr size_t fidx(size_t p_x) {
- if constexpr (sizeof(void *) == 4) {
- return p_x * 2;
- } else {
- return p_x;
- }
-}
-
-template <typename T>
-T m2n_arg_cast(Mono_InterpMethodArguments *p_margs, size_t p_idx) {
- constexpr char cookie = get_m2n_cookie<T>();
-
- static_assert(cookie == 'I' || cookie == 'L' || cookie == 'F' || cookie == 'D');
-
- if constexpr (cookie == 'I') {
- return (T)(size_t)p_margs->iargs[p_idx];
- } else if constexpr (cookie == 'L') {
- static_assert(std::is_same_v<T, int64_t> || std::is_same_v<T, uint64_t> ||
- (sizeof(void *) == 8 && std::is_pointer_v<T>),
- "Invalid type for cookie 'L'.");
-
- union {
- T l;
- struct {
- int32_t lo;
- int32_t hi;
- } pair;
- } p;
-
- p.pair.lo = (int32_t)(size_t)p_margs->iargs[p_idx];
- p.pair.hi = (int32_t)(size_t)p_margs->iargs[p_idx + 1];
-
- return p.l;
- } else if constexpr (cookie == 'F') {
- return *reinterpret_cast<float *>(&p_margs->fargs[fidx(p_idx)]);
- } else if constexpr (cookie == 'D') {
- return (T)p_margs->fargs[p_idx];
- }
-}
-
-template <typename... P, size_t... Is>
-void m2n_trampoline_with_idx_seq(void *p_target_func, Mono_InterpMethodArguments *p_margs, IndexSequence<Is...>) {
- constexpr array<size_t, sizeof...(P)> indices = get_indices_for_type<P...>();
- typedef void (*Func)(P...);
- Func func = (Func)p_target_func;
- func(m2n_arg_cast<P>(p_margs, indices.elems[Is])...);
-}
-
-template <typename R, typename... P, size_t... Is>
-void m2n_trampoline_with_idx_seq_r(void *p_target_func, Mono_InterpMethodArguments *p_margs, IndexSequence<Is...>) {
- constexpr array<size_t, sizeof...(P)> indices = get_indices_for_type<P...>();
- typedef R (*Func)(P...);
- Func func = (Func)p_target_func;
- R res = func(m2n_arg_cast<P>(p_margs, indices.elems[Is])...);
- *reinterpret_cast<R *>(p_margs->retval) = res;
-}
-
-inline void m2n_trampoline_with_idx_seq_0(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
- typedef void (*Func)();
- Func func = (Func)p_target_func;
- func();
-}
-
-template <typename R>
-void m2n_trampoline_with_idx_seq_r0(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
- typedef R (*Func)();
- Func func = (Func)p_target_func;
- R res = func();
- *reinterpret_cast<R *>(p_margs->retval) = res;
-}
-
-template <typename... P>
-void m2n_trampoline(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
- if constexpr (sizeof...(P) == 0) {
- m2n_trampoline_with_idx_seq_0(p_target_func, p_margs);
- } else {
- m2n_trampoline_with_idx_seq<P...>(p_target_func, p_margs, BuildIndexSequence<sizeof...(P)>{});
- }
-}
-
-template <typename R, typename... P>
-void m2n_trampoline_r(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
- if constexpr (sizeof...(P) == 0) {
- m2n_trampoline_with_idx_seq_r0<R>(p_target_func, p_margs);
- } else {
- m2n_trampoline_with_idx_seq_r<R, P...>(p_target_func, p_margs, BuildIndexSequence<sizeof...(P)>{});
- }
-}
-
-typedef void (*TrampolineFunc)(void *p_target_func, Mono_InterpMethodArguments *p_margs);
-
-void set_trampoline(const char *cookies, TrampolineFunc trampoline_func);
-
-void lazy_initialize();
-
-template <typename... P>
-struct ICallTrampolines {
- static constexpr auto cookies = get_m2n_cookies<P...>();
-
- static void add() {
- lazy_initialize();
- set_trampoline(cookies.elems, &m2n_trampoline<P...>);
- }
-};
-
-template <typename R, typename... P>
-struct ICallTrampolinesR {
- static constexpr auto cookies = get_m2n_cookies_r<R, P...>();
-
- static void add() {
- lazy_initialize();
- set_trampoline(cookies.elems, &m2n_trampoline_r<R, P...>);
- }
-};
-
-void initialize();
-} // namespace GDMonoWasmM2n
-
-#endif
-
-#endif // GD_MONO_WASM_M2N_H
diff --git a/modules/mono/mono_gd/i_mono_class_member.h b/modules/mono/mono_gd/i_mono_class_member.h
deleted file mode 100644
index 14e8ca82b9..0000000000
--- a/modules/mono/mono_gd/i_mono_class_member.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*************************************************************************/
-/* i_mono_class_member.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 I_MONO_CLASS_MEMBER_H
-#define I_MONO_CLASS_MEMBER_H
-
-#include "gd_mono_header.h"
-
-#include <mono/metadata/object.h>
-
-class IMonoClassMember {
-public:
- enum Visibility {
- PRIVATE,
- PROTECTED_AND_INTERNAL, // FAM_AND_ASSEM
- INTERNAL, // ASSEMBLY
- PROTECTED, // FAMILY
- PUBLIC
- };
-
- enum MemberType {
- MEMBER_TYPE_FIELD,
- MEMBER_TYPE_PROPERTY,
- MEMBER_TYPE_METHOD
- };
-
- virtual ~IMonoClassMember() {}
-
- virtual GDMonoClass *get_enclosing_class() const = 0;
-
- virtual MemberType get_member_type() const = 0;
-
- virtual StringName get_name() const = 0;
-
- virtual bool is_static() = 0;
-
- virtual Visibility get_visibility() = 0;
-
- virtual bool has_attribute(GDMonoClass *p_attr_class) = 0;
- virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) = 0;
-};
-
-#endif // I_MONO_CLASS_MEMBER_H
diff --git a/modules/mono/mono_gd/managed_type.cpp b/modules/mono/mono_gd/managed_type.cpp
deleted file mode 100644
index 5860d7db1e..0000000000
--- a/modules/mono/mono_gd/managed_type.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*************************************************************************/
-/* managed_type.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 "managed_type.h"
-
-#include "gd_mono.h"
-#include "gd_mono_class.h"
-
-ManagedType ManagedType::from_class(GDMonoClass *p_class) {
- return ManagedType(mono_type_get_type(p_class->get_mono_type()), p_class);
-}
-
-ManagedType ManagedType::from_class(MonoClass *p_mono_class) {
- GDMonoClass *tclass = GDMono::get_singleton()->get_class(p_mono_class);
- ERR_FAIL_COND_V(!tclass, ManagedType());
-
- return ManagedType(mono_type_get_type(tclass->get_mono_type()), tclass);
-}
-
-ManagedType ManagedType::from_type(MonoType *p_mono_type) {
- MonoClass *mono_class = mono_class_from_mono_type(p_mono_type);
- GDMonoClass *tclass = GDMono::get_singleton()->get_class(mono_class);
- ERR_FAIL_COND_V(!tclass, ManagedType());
-
- return ManagedType(mono_type_get_type(p_mono_type), tclass);
-}
-
-ManagedType ManagedType::from_reftype(MonoReflectionType *p_mono_reftype) {
- MonoType *mono_type = mono_reflection_type_get_type(p_mono_reftype);
- return from_type(mono_type);
-}
diff --git a/modules/mono/mono_gd/managed_type.h b/modules/mono/mono_gd/managed_type.h
deleted file mode 100644
index 603ff3aca1..0000000000
--- a/modules/mono/mono_gd/managed_type.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*************************************************************************/
-/* managed_type.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 MANAGED_TYPE_H
-#define MANAGED_TYPE_H
-
-#include <mono/metadata/object.h>
-
-#include "gd_mono_header.h"
-
-struct ManagedType {
- int type_encoding = 0;
- GDMonoClass *type_class = nullptr;
-
- static ManagedType from_class(GDMonoClass *p_class);
- static ManagedType from_class(MonoClass *p_mono_class);
- static ManagedType from_type(MonoType *p_mono_type);
- static ManagedType from_reftype(MonoReflectionType *p_mono_reftype);
-
- ManagedType() {}
-
- ManagedType(int p_type_encoding, GDMonoClass *p_type_class) :
- type_encoding(p_type_encoding),
- type_class(p_type_class) {
- }
-};
-
-#endif // MANAGED_TYPE_H
diff --git a/modules/mono/mono_gd/support/android_support.cpp b/modules/mono/mono_gd/support/android_support.cpp
index 4797d5dae1..7fb983cd37 100644
--- a/modules/mono/mono_gd/support/android_support.cpp
+++ b/modules/mono/mono_gd/support/android_support.cpp
@@ -359,7 +359,7 @@ MonoArray *_gd_mono_android_cert_store_lookup(MonoString *p_alias) {
ScopedLocalRef<jbyteArray> encoded(env, (jbyteArray)env->CallObjectMethod(certificate, getEncoded));
jsize encodedLength = env->GetArrayLength(encoded);
- MonoArray *encoded_ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), encodedLength);
+ MonoArray *encoded_ret = mono_array_new(mono_domain_get(), mono_get_byte_class(), encodedLength);
uint8_t *dest = (uint8_t *)mono_array_addr(encoded_ret, uint8_t, 0);
env->GetByteArrayRegion(encoded, 0, encodedLength, reinterpret_cast<jbyte *>(dest));
diff --git a/modules/mono/signal_awaiter_utils.cpp b/modules/mono/signal_awaiter_utils.cpp
index 437c4ca54a..55d2138674 100644
--- a/modules/mono/signal_awaiter_utils.cpp
+++ b/modules/mono/signal_awaiter_utils.cpp
@@ -32,16 +32,14 @@
#include "csharp_script.h"
#include "mono_gd/gd_mono_cache.h"
-#include "mono_gd/gd_mono_class.h"
-#include "mono_gd/gd_mono_marshal.h"
-#include "mono_gd/gd_mono_utils.h"
-Error gd_mono_connect_signal_awaiter(Object *p_source, const StringName &p_signal, Object *p_target, MonoObject *p_awaiter) {
+Error gd_mono_connect_signal_awaiter(Object *p_source, const StringName &p_signal, Object *p_target, GCHandleIntPtr p_awaiter_handle_ptr) {
ERR_FAIL_NULL_V(p_source, ERR_INVALID_DATA);
ERR_FAIL_NULL_V(p_target, ERR_INVALID_DATA);
// TODO: Use pooling for ManagedCallable instances.
- SignalAwaiterCallable *awaiter_callable = memnew(SignalAwaiterCallable(p_target, p_awaiter, p_signal));
+ MonoGCHandleData awaiter_handle(p_awaiter_handle_ptr, gdmono::GCHandleType::STRONG_HANDLE);
+ SignalAwaiterCallable *awaiter_callable = memnew(SignalAwaiterCallable(p_target, awaiter_handle, p_signal));
Callable callable = Callable(awaiter_callable);
return p_source->connect(p_signal, callable, Object::CONNECT_ONESHOT);
@@ -51,7 +49,7 @@ bool SignalAwaiterCallable::compare_equal(const CallableCustom *p_a, const Calla
// Only called if both instances are of type SignalAwaiterCallable. Static cast is safe.
const SignalAwaiterCallable *a = static_cast<const SignalAwaiterCallable *>(p_a);
const SignalAwaiterCallable *b = static_cast<const SignalAwaiterCallable *>(p_b);
- return a->awaiter_handle.handle == b->awaiter_handle.handle;
+ return a->awaiter_handle.handle.value == b->awaiter_handle.handle.value;
}
bool SignalAwaiterCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) {
@@ -92,6 +90,10 @@ ObjectID SignalAwaiterCallable::get_object() const {
return target_id;
}
+StringName SignalAwaiterCallable::get_signal() const {
+ return signal;
+}
+
void SignalAwaiterCallable::call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const {
r_call_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; // Can't find anything better
r_return_value = Variant();
@@ -101,38 +103,20 @@ void SignalAwaiterCallable::call(const Variant **p_arguments, int p_argcount, Va
"Resumed after await, but class instance is gone.");
#endif
- MonoArray *signal_args = nullptr;
-
- if (p_argcount > 0) {
- signal_args = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), p_argcount);
-
- for (int i = 0; i < p_argcount; i++) {
- MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(*p_arguments[i]);
- mono_array_setref(signal_args, i, boxed);
- }
- }
+ bool awaiter_is_null = false;
+ GDMonoCache::managed_callbacks.SignalAwaiter_SignalCallback(awaiter_handle.get_intptr(), p_arguments, p_argcount, &awaiter_is_null);
- MonoObject *awaiter = awaiter_handle.get_target();
-
- if (!awaiter) {
+ if (awaiter_is_null) {
r_call_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
return;
}
- MonoException *exc = nullptr;
- CACHED_METHOD_THUNK(SignalAwaiter, SignalCallback).invoke(awaiter, signal_args, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- ERR_FAIL();
- } else {
- r_call_error.error = Callable::CallError::CALL_OK;
- }
+ r_call_error.error = Callable::CallError::CALL_OK;
}
-SignalAwaiterCallable::SignalAwaiterCallable(Object *p_target, MonoObject *p_awaiter, const StringName &p_signal) :
+SignalAwaiterCallable::SignalAwaiterCallable(Object *p_target, MonoGCHandleData p_awaiter_handle, const StringName &p_signal) :
target_id(p_target->get_instance_id()),
- awaiter_handle(MonoGCHandleData::new_strong_handle(p_awaiter)),
+ awaiter_handle(p_awaiter_handle),
signal(p_signal) {
}
@@ -148,7 +132,7 @@ bool EventSignalCallable::compare_equal(const CallableCustom *p_a, const Callabl
return false;
}
- if (a->event_signal != b->event_signal) {
+ if (a->event_signal_name != b->event_signal_name) {
return false;
}
@@ -163,7 +147,7 @@ bool EventSignalCallable::compare_less(const CallableCustom *p_a, const Callable
}
uint32_t EventSignalCallable::hash() const {
- uint32_t hash = event_signal->field->get_name().hash();
+ uint32_t hash = event_signal_name.hash();
return hash_murmur3_one_64(owner->get_instance_id(), hash);
}
@@ -173,8 +157,7 @@ String EventSignalCallable::get_as_text() const {
if (script.is_valid() && script->get_path().is_resource_file()) {
class_name += "(" + script->get_path().get_file() + ")";
}
- StringName signal = event_signal->field->get_name();
- return class_name + "::EventSignalMiddleman::" + String(signal);
+ return class_name + "::EventSignalMiddleman::" + String(event_signal_name);
}
CallableCustom::CompareEqualFunc EventSignalCallable::get_compare_equal_func() const {
@@ -190,39 +173,32 @@ ObjectID EventSignalCallable::get_object() const {
}
StringName EventSignalCallable::get_signal() const {
- return event_signal->field->get_name();
+ return event_signal_name;
}
void EventSignalCallable::call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const {
r_call_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; // Can't find anything better
r_return_value = Variant();
- ERR_FAIL_COND(p_argcount < event_signal->invoke_method->get_parameters_count());
-
CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(owner->get_script_instance());
ERR_FAIL_NULL(csharp_instance);
- MonoObject *owner_managed = csharp_instance->get_mono_object();
- ERR_FAIL_NULL(owner_managed);
+ GCHandleIntPtr owner_gchandle_intptr = csharp_instance->get_gchandle_intptr();
+
+ bool awaiter_is_null = false;
+ GDMonoCache::managed_callbacks.ScriptManagerBridge_RaiseEventSignal(
+ owner_gchandle_intptr, &event_signal_name,
+ p_arguments, p_argcount, &awaiter_is_null);
- MonoObject *delegate_field_value = event_signal->field->get_value(owner_managed);
- if (!delegate_field_value) {
- r_call_error.error = Callable::CallError::CALL_OK;
+ if (awaiter_is_null) {
+ r_call_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
return;
}
- MonoException *exc = nullptr;
- event_signal->invoke_method->invoke(delegate_field_value, p_arguments, &exc);
-
- if (exc) {
- GDMonoUtils::set_pending_exception(exc);
- ERR_FAIL();
- } else {
- r_call_error.error = Callable::CallError::CALL_OK;
- }
+ r_call_error.error = Callable::CallError::CALL_OK;
}
-EventSignalCallable::EventSignalCallable(Object *p_owner, const CSharpScript::EventSignal *p_event_signal) :
+EventSignalCallable::EventSignalCallable(Object *p_owner, const StringName &p_event_signal_name) :
owner(p_owner),
- event_signal(p_event_signal) {
+ event_signal_name(p_event_signal_name) {
}
diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h
index 532aa3e327..a53ae56bf5 100644
--- a/modules/mono/signal_awaiter_utils.h
+++ b/modules/mono/signal_awaiter_utils.h
@@ -36,9 +36,14 @@
#include "csharp_script.h"
#include "mono_gc_handle.h"
-Error gd_mono_connect_signal_awaiter(Object *p_source, const StringName &p_signal, Object *p_target, MonoObject *p_awaiter);
+Error gd_mono_connect_signal_awaiter(Object *p_source, const StringName &p_signal, Object *p_target, GCHandleIntPtr p_awaiter_handle_ptr);
-class SignalAwaiterCallable : public CallableCustom {
+class BaseSignalCallable : public CallableCustom {
+public:
+ virtual StringName get_signal() const = 0;
+};
+
+class SignalAwaiterCallable : public BaseSignalCallable {
ObjectID target_id;
MonoGCHandleData awaiter_handle;
StringName signal;
@@ -59,17 +64,17 @@ public:
ObjectID get_object() const override;
- _FORCE_INLINE_ StringName get_signal() const { return signal; }
+ StringName get_signal() const override;
void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override;
- SignalAwaiterCallable(Object *p_target, MonoObject *p_awaiter, const StringName &p_signal);
+ SignalAwaiterCallable(Object *p_target, MonoGCHandleData p_awaiter_handle, const StringName &p_signal);
~SignalAwaiterCallable();
};
-class EventSignalCallable : public CallableCustom {
+class EventSignalCallable : public BaseSignalCallable {
Object *owner = nullptr;
- const CSharpScript::EventSignal *event_signal;
+ StringName event_signal_name;
public:
static bool compare_equal(const CallableCustom *p_a, const CallableCustom *p_b);
@@ -87,11 +92,11 @@ public:
ObjectID get_object() const override;
- StringName get_signal() const;
+ StringName get_signal() const override;
void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override;
- EventSignalCallable(Object *p_owner, const CSharpScript::EventSignal *p_event_signal);
+ EventSignalCallable(Object *p_owner, const StringName &p_event_signal_name);
};
#endif // SIGNAL_AWAITER_UTILS_H
diff --git a/modules/mono/utils/mono_reg_utils.cpp b/modules/mono/utils/mono_reg_utils.cpp
deleted file mode 100644
index 8e37e6943c..0000000000
--- a/modules/mono/utils/mono_reg_utils.cpp
+++ /dev/null
@@ -1,242 +0,0 @@
-/*************************************************************************/
-/* mono_reg_utils.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 "mono_reg_utils.h"
-#include "core/io/dir_access.h"
-
-#ifdef WINDOWS_ENABLED
-
-#include "core/os/os.h"
-
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-
-namespace MonoRegUtils {
-
-template <int>
-REGSAM bitness_sam_impl();
-
-template <>
-REGSAM bitness_sam_impl<4>() {
- return KEY_WOW64_64KEY;
-}
-
-template <>
-REGSAM bitness_sam_impl<8>() {
- return KEY_WOW64_32KEY;
-}
-
-REGSAM _get_bitness_sam() {
- return bitness_sam_impl<sizeof(size_t)>();
-}
-
-LONG _RegOpenKey(HKEY hKey, LPCWSTR lpSubKey, PHKEY phkResult) {
- LONG res = RegOpenKeyExW(hKey, lpSubKey, 0, KEY_READ, phkResult);
-
- if (res != ERROR_SUCCESS) {
- res = RegOpenKeyExW(hKey, lpSubKey, 0, KEY_READ | _get_bitness_sam(), phkResult);
- }
-
- return res;
-}
-
-LONG _RegKeyQueryString(HKEY hKey, const String &p_value_name, String &r_value) {
- Vector<WCHAR> buffer;
- buffer.resize(512);
- DWORD dwBufferSize = buffer.size();
-
- LONG res = RegQueryValueExW(hKey, (LPCWSTR)(p_value_name.utf16().get_data()), 0, nullptr, (LPBYTE)buffer.ptr(), &dwBufferSize);
-
- if (res == ERROR_MORE_DATA) {
- // dwBufferSize now contains the actual size
- buffer.resize(dwBufferSize);
- res = RegQueryValueExW(hKey, (LPCWSTR)(p_value_name.utf16().get_data()), 0, nullptr, (LPBYTE)buffer.ptr(), &dwBufferSize);
- }
-
- if (res == ERROR_SUCCESS) {
- r_value = String(buffer.ptr(), buffer.size());
- } else {
- r_value = String();
- }
-
- return res;
-}
-
-LONG _find_mono_in_reg(const String &p_subkey, MonoRegInfo &r_info, bool p_old_reg = false) {
- HKEY hKey;
- LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, (LPCWSTR)(p_subkey.utf16().get_data()), &hKey);
-
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
-
- if (!p_old_reg) {
- res = _RegKeyQueryString(hKey, "Version", r_info.version);
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
- }
-
- res = _RegKeyQueryString(hKey, "SdkInstallRoot", r_info.install_root_dir);
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
-
- res = _RegKeyQueryString(hKey, "FrameworkAssemblyDirectory", r_info.assembly_dir);
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
-
- res = _RegKeyQueryString(hKey, "MonoConfigDir", r_info.config_dir);
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
-
- if (r_info.install_root_dir.ends_with("\\")) {
- r_info.bin_dir = r_info.install_root_dir + "bin";
- } else {
- r_info.bin_dir = r_info.install_root_dir + "\\bin";
- }
-
-cleanup:
- RegCloseKey(hKey);
- return res;
-}
-
-LONG _find_mono_in_reg_old(const String &p_subkey, MonoRegInfo &r_info) {
- String default_clr;
-
- HKEY hKey;
- LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, (LPCWSTR)(p_subkey.utf16().get_data()), &hKey);
-
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
-
- res = _RegKeyQueryString(hKey, "DefaultCLR", default_clr);
-
- if (res == ERROR_SUCCESS && default_clr.length()) {
- r_info.version = default_clr;
- res = _find_mono_in_reg(p_subkey + "\\" + default_clr, r_info, true);
- }
-
-cleanup:
- RegCloseKey(hKey);
- return res;
-}
-
-MonoRegInfo find_mono() {
- MonoRegInfo info;
-
- if (_find_mono_in_reg("Software\\Mono", info) == ERROR_SUCCESS) {
- return info;
- }
-
- if (_find_mono_in_reg_old("Software\\Novell\\Mono", info) == ERROR_SUCCESS) {
- return info;
- }
-
- return MonoRegInfo();
-}
-
-String find_msbuild_tools_path() {
- String msbuild_tools_path;
-
- // Try to find 15.0 with vswhere
-
- String vswhere_path = OS::get_singleton()->get_environment(sizeof(size_t) == 8 ? "ProgramFiles(x86)" : "ProgramFiles");
- vswhere_path += "\\Microsoft Visual Studio\\Installer\\vswhere.exe";
-
- List<String> vswhere_args;
- vswhere_args.push_back("-latest");
- vswhere_args.push_back("-products");
- vswhere_args.push_back("*");
- vswhere_args.push_back("-requires");
- vswhere_args.push_back("Microsoft.Component.MSBuild");
-
- String output;
- int exit_code;
- OS::get_singleton()->execute(vswhere_path, vswhere_args, &output, &exit_code);
-
- if (exit_code == 0) {
- Vector<String> lines = output.split("\n");
-
- for (int i = 0; i < lines.size(); i++) {
- const String &line = lines[i];
- int sep_idx = line.find(":");
-
- if (sep_idx > 0) {
- String key = line.substr(0, sep_idx); // No need to trim
-
- if (key == "installationPath") {
- String val = line.substr(sep_idx + 1, line.length()).strip_edges();
-
- ERR_BREAK(val.is_empty());
-
- if (!val.ends_with("\\")) {
- val += "\\";
- }
-
- // Since VS2019, the directory is simply named "Current"
- String msbuild_dir = val + "MSBuild\\Current\\Bin";
- if (DirAccess::exists(msbuild_dir)) {
- return msbuild_dir;
- }
-
- // Directory name "15.0" is used in VS 2017
- return val + "MSBuild\\15.0\\Bin";
- }
- }
- }
- }
-
- // Try to find 14.0 in the Registry
-
- HKEY hKey;
- LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\14.0", &hKey);
-
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
-
- res = _RegKeyQueryString(hKey, "MSBuildToolsPath", msbuild_tools_path);
-
- if (res != ERROR_SUCCESS) {
- goto cleanup;
- }
-
-cleanup:
- RegCloseKey(hKey);
-
- return msbuild_tools_path;
-}
-} // namespace MonoRegUtils
-
-#endif // WINDOWS_ENABLED
diff --git a/modules/mono/utils/mono_reg_utils.h b/modules/mono/utils/mono_reg_utils.h
deleted file mode 100644
index 5be60d4930..0000000000
--- a/modules/mono/utils/mono_reg_utils.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*************************************************************************/
-/* mono_reg_utils.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 MONO_REG_UTILS_H
-#define MONO_REG_UTILS_H
-
-#ifdef WINDOWS_ENABLED
-
-#include "core/string/ustring.h"
-
-struct MonoRegInfo {
- String version;
- String install_root_dir;
- String assembly_dir;
- String config_dir;
- String bin_dir;
-};
-
-namespace MonoRegUtils {
-
-MonoRegInfo find_mono();
-String find_msbuild_tools_path();
-} // namespace MonoRegUtils
-
-#endif // WINDOWS_ENABLED
-
-#endif // MONO_REG_UTILS_H
diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp
index a1905dfcfe..19ad59a1bc 100644
--- a/modules/mono/utils/path_utils.cpp
+++ b/modules/mono/utils/path_utils.cpp
@@ -51,6 +51,37 @@
namespace path {
+String find_executable(const String &p_name) {
+#ifdef WINDOWS_ENABLED
+ Vector<String> exts = OS::get_singleton()->get_environment("PATHEXT").split(ENV_PATH_SEP, false);
+#endif
+ Vector<String> env_path = OS::get_singleton()->get_environment("PATH").split(ENV_PATH_SEP, false);
+
+ if (env_path.is_empty()) {
+ return String();
+ }
+
+ for (int i = 0; i < env_path.size(); i++) {
+ String p = path::join(env_path[i], p_name);
+
+#ifdef WINDOWS_ENABLED
+ for (int j = 0; j < exts.size(); j++) {
+ String p2 = p + exts[j].to_lower(); // lowercase to reduce risk of case mismatch warning
+
+ if (FileAccess::exists(p2)) {
+ return p2;
+ }
+ }
+#else
+ if (FileAccess::exists(p)) {
+ return p;
+ }
+#endif
+ }
+
+ return String();
+}
+
String cwd() {
#ifdef WINDOWS_ENABLED
const DWORD expected_size = ::GetCurrentDirectoryW(0, nullptr);
diff --git a/modules/mono/utils/path_utils.h b/modules/mono/utils/path_utils.h
index 9a2c757361..d1c3d3ccfd 100644
--- a/modules/mono/utils/path_utils.h
+++ b/modules/mono/utils/path_utils.h
@@ -36,6 +36,8 @@
namespace path {
+String find_executable(const String &p_name);
+
String join(const String &p_a, const String &p_b);
String join(const String &p_a, const String &p_b, const String &p_c);
String join(const String &p_a, const String &p_b, const String &p_c, const String &p_d);
diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp
index 975f2d8332..b0f94310b8 100644
--- a/modules/mono/utils/string_utils.cpp
+++ b/modules/mono/utils/string_utils.cpp
@@ -65,7 +65,7 @@ int sfind(const String &p_text, int p_from) {
break;
case 1: {
char32_t c = src[read_pos];
- found = src[read_pos] == 's' || (c >= '0' && c <= '4');
+ found = src[read_pos] == 's' || (c >= '0' && c <= '5');
break;
}
default:
@@ -86,32 +86,13 @@ int sfind(const String &p_text, int p_from) {
}
} // namespace
-String sformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) {
+String sformat(const String &p_text, const String &p1, const String &p2,
+ const String &p3, const String &p4, const String &p5, const String &p6) {
if (p_text.length() < 2) {
return p_text;
}
- Array args;
-
- if (p1.get_type() != Variant::NIL) {
- args.push_back(p1);
-
- if (p2.get_type() != Variant::NIL) {
- args.push_back(p2);
-
- if (p3.get_type() != Variant::NIL) {
- args.push_back(p3);
-
- if (p4.get_type() != Variant::NIL) {
- args.push_back(p4);
-
- if (p5.get_type() != Variant::NIL) {
- args.push_back(p5);
- }
- }
- }
- }
- }
+ String args[6] = { p1, p2, p3, p4, p5, p6 };
String new_string;
@@ -125,7 +106,7 @@ String sformat(const String &p_text, const Variant &p1, const Variant &p2, const
int req_index = (c == 's' ? findex++ : c - '0');
new_string += p_text.substr(search_from, result - search_from);
- new_string += args[req_index].operator String();
+ new_string += args[req_index];
search_from = result + 2;
}
diff --git a/modules/mono/utils/string_utils.h b/modules/mono/utils/string_utils.h
index fa4c5e89f4..b00dd9dde8 100644
--- a/modules/mono/utils/string_utils.h
+++ b/modules/mono/utils/string_utils.h
@@ -36,7 +36,8 @@
#include <stdarg.h>
-String sformat(const String &p_text, const Variant &p1 = Variant(), const Variant &p2 = Variant(), const Variant &p3 = Variant(), const Variant &p4 = Variant(), const Variant &p5 = Variant());
+String sformat(const String &p_text, const String &p1 = String(), const String &p2 = String(),
+ const String &p3 = String(), const String &p4 = String(), const String &p5 = String(), const String &p6 = String());
#ifdef TOOLS_ENABLED
bool is_csharp_keyword(const String &p_name);
diff --git a/modules/multiplayer/editor/replication_editor_plugin.cpp b/modules/multiplayer/editor/replication_editor_plugin.cpp
index 50f1434ad8..f045018f25 100644
--- a/modules/multiplayer/editor/replication_editor_plugin.cpp
+++ b/modules/multiplayer/editor/replication_editor_plugin.cpp
@@ -33,6 +33,7 @@
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
+#include "editor/editor_undo_redo_manager.h"
#include "editor/inspector_dock.h"
#include "editor/scene_tree_editor.h"
#include "modules/multiplayer/multiplayer_synchronizer.h"
@@ -139,7 +140,7 @@ void ReplicationEditor::_add_sync_property(String p_path) {
return;
}
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(TTR("Add property to synchronizer"));
if (config.is_null()) {
@@ -354,7 +355,7 @@ void ReplicationEditor::_tree_item_edited() {
int column = tree->get_edited_column();
ERR_FAIL_COND(column < 1 || column > 2);
const NodePath prop = ti->get_metadata(0);
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
bool value = ti->is_checked(column);
String method;
if (column == 1) {
@@ -394,7 +395,7 @@ void ReplicationEditor::_dialog_closed(bool p_confirmed) {
int idx = config->property_get_index(prop);
bool spawn = config->property_get_spawn(prop);
bool sync = config->property_get_sync(prop);
- UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo();
undo_redo->create_action(TTR("Remove Property"));
undo_redo->add_do_method(config.ptr(), "remove_property", prop);
undo_redo->add_undo_method(config.ptr(), "add_property", prop, idx);
diff --git a/modules/navigation/godot_navigation_server.cpp b/modules/navigation/godot_navigation_server.cpp
index 2cdb5b7cb4..4191e46f62 100644
--- a/modules/navigation/godot_navigation_server.cpp
+++ b/modules/navigation/godot_navigation_server.cpp
@@ -123,8 +123,8 @@ void GodotNavigationServer::add_command(SetCommand *command) const {
}
}
-Array GodotNavigationServer::get_maps() const {
- Array all_map_rids;
+TypedArray<RID> GodotNavigationServer::get_maps() const {
+ TypedArray<RID> all_map_rids;
List<RID> maps_owned;
map_owner.get_owned_list(&maps_owned);
if (maps_owned.size()) {
@@ -245,8 +245,8 @@ RID GodotNavigationServer::map_get_closest_point_owner(RID p_map, const Vector3
return map->get_closest_point_owner(p_point);
}
-Array GodotNavigationServer::map_get_regions(RID p_map) const {
- Array regions_rids;
+TypedArray<RID> GodotNavigationServer::map_get_regions(RID p_map) const {
+ TypedArray<RID> regions_rids;
const NavMap *map = map_owner.get_or_null(p_map);
ERR_FAIL_COND_V(map == nullptr, regions_rids);
const LocalVector<NavRegion *> regions = map->get_regions();
@@ -257,8 +257,8 @@ Array GodotNavigationServer::map_get_regions(RID p_map) const {
return regions_rids;
}
-Array GodotNavigationServer::map_get_agents(RID p_map) const {
- Array agents_rids;
+TypedArray<RID> GodotNavigationServer::map_get_agents(RID p_map) const {
+ TypedArray<RID> agents_rids;
const NavMap *map = map_owner.get_or_null(p_map);
ERR_FAIL_COND_V(map == nullptr, agents_rids);
const LocalVector<RvoAgent *> agents = map->get_agents();
@@ -453,11 +453,11 @@ COMMAND_2(agent_set_map, RID, p_agent, RID, p_map) {
}
}
-COMMAND_2(agent_set_neighbor_dist, RID, p_agent, real_t, p_dist) {
+COMMAND_2(agent_set_neighbor_distance, RID, p_agent, real_t, p_distance) {
RvoAgent *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_COND(agent == nullptr);
- agent->get_agent()->neighborDist_ = p_dist;
+ agent->get_agent()->neighborDist_ = p_distance;
}
COMMAND_2(agent_set_max_neighbors, RID, p_agent, int, p_count) {
diff --git a/modules/navigation/godot_navigation_server.h b/modules/navigation/godot_navigation_server.h
index da1f8cba0b..05ba46ede1 100644
--- a/modules/navigation/godot_navigation_server.h
+++ b/modules/navigation/godot_navigation_server.h
@@ -85,7 +85,7 @@ public:
void add_command(SetCommand *command) const;
- virtual Array get_maps() const override;
+ virtual TypedArray<RID> get_maps() const override;
virtual RID map_create() const override;
COMMAND_2(map_set_active, RID, p_map, bool, p_active);
@@ -107,8 +107,8 @@ public:
virtual Vector3 map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const override;
virtual RID map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const override;
- virtual Array map_get_regions(RID p_map) const override;
- virtual Array map_get_agents(RID p_map) const override;
+ virtual TypedArray<RID> map_get_regions(RID p_map) const override;
+ virtual TypedArray<RID> map_get_agents(RID p_map) const override;
virtual void map_force_update(RID p_map) override;
@@ -135,7 +135,7 @@ public:
virtual RID agent_create() const override;
COMMAND_2(agent_set_map, RID, p_agent, RID, p_map);
virtual RID agent_get_map(RID p_agent) const override;
- COMMAND_2(agent_set_neighbor_dist, RID, p_agent, real_t, p_dist);
+ COMMAND_2(agent_set_neighbor_distance, RID, p_agent, real_t, p_distance);
COMMAND_2(agent_set_max_neighbors, RID, p_agent, int, p_count);
COMMAND_2(agent_set_time_horizon, RID, p_agent, real_t, p_time);
COMMAND_2(agent_set_radius, RID, p_agent, real_t, p_radius);
diff --git a/modules/noise/fastnoise_lite.cpp b/modules/noise/fastnoise_lite.cpp
index b21e3247d7..06d97838f6 100644
--- a/modules/noise/fastnoise_lite.cpp
+++ b/modules/noise/fastnoise_lite.cpp
@@ -476,24 +476,24 @@ void FastNoiseLite::_bind_methods() {
BIND_ENUM_CONSTANT(DOMAIN_WARP_FRACTAL_INDEPENDENT);
}
-void FastNoiseLite::_validate_property(PropertyInfo &property) const {
- if (property.name.begins_with("cellular") && get_noise_type() != TYPE_CELLULAR) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void FastNoiseLite::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name.begins_with("cellular") && get_noise_type() != TYPE_CELLULAR) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
return;
}
- if (property.name != "fractal_type" && property.name.begins_with("fractal") && get_fractal_type() == FRACTAL_NONE) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name != "fractal_type" && p_property.name.begins_with("fractal") && get_fractal_type() == FRACTAL_NONE) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
return;
}
- if (property.name == "fractal_ping_pong_strength" && get_fractal_type() != FRACTAL_PING_PONG) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "fractal_ping_pong_strength" && get_fractal_type() != FRACTAL_PING_PONG) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
return;
}
- if (property.name != "domain_warp_enabled" && property.name.begins_with("domain_warp") && !domain_warp_enabled) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name != "domain_warp_enabled" && p_property.name.begins_with("domain_warp") && !domain_warp_enabled) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
return;
}
}
diff --git a/modules/noise/fastnoise_lite.h b/modules/noise/fastnoise_lite.h
index fe8cd7ce6e..50c633b923 100644
--- a/modules/noise/fastnoise_lite.h
+++ b/modules/noise/fastnoise_lite.h
@@ -92,7 +92,7 @@ public:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
private:
_FastNoiseLite _noise;
diff --git a/modules/noise/noise_texture.cpp b/modules/noise/noise_texture.cpp
index ca55d3b96d..923b420581 100644
--- a/modules/noise/noise_texture.cpp
+++ b/modules/noise/noise_texture.cpp
@@ -94,16 +94,16 @@ void NoiseTexture::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "Noise"), "set_noise", "get_noise");
}
-void NoiseTexture::_validate_property(PropertyInfo &property) const {
- if (property.name == "bump_strength") {
+void NoiseTexture::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "bump_strength") {
if (!as_normal_map) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- if (property.name == "seamless_blend_skirt") {
+ if (p_property.name == "seamless_blend_skirt") {
if (!seamless) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
diff --git a/modules/noise/noise_texture.h b/modules/noise/noise_texture.h
index 6c088562a1..83fbcc2d10 100644
--- a/modules/noise/noise_texture.h
+++ b/modules/noise/noise_texture.h
@@ -75,7 +75,7 @@ private:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_noise(Ref<Noise> p_noise);
diff --git a/modules/raycast/SCsub b/modules/raycast/SCsub
index ef4c598194..074795759a 100644
--- a/modules/raycast/SCsub
+++ b/modules/raycast/SCsub
@@ -66,7 +66,7 @@ if env["builtin_embree"]:
env_raycast.Append(CPPDEFINES=["EMBREE_TARGET_SSE2", "EMBREE_LOWEST_ISA", "TASKING_INTERNAL", "NDEBUG"])
if not env.msvc:
- if env["arch"] in ["x86", "x86_64"]:
+ if env["arch"] == "x86_64":
env_raycast.Append(CPPFLAGS=["-msse2", "-mxsave"])
if env["platform"] == "windows":
@@ -83,7 +83,7 @@ if env["builtin_embree"]:
env_thirdparty.disable_warnings()
env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
- if not env["arch"] in ["x86", "x86_64"] or env.msvc:
+ if env["arch"] == "arm64" or env.msvc:
# Embree needs those, it will automatically use SSE2NEON in ARM
env_thirdparty.Append(CPPDEFINES=["__SSE2__", "__SSE__"])
diff --git a/modules/raycast/config.py b/modules/raycast/config.py
index 7e8b3e9840..438779343e 100644
--- a/modules/raycast/config.py
+++ b/modules/raycast/config.py
@@ -1,18 +1,6 @@
def can_build(env, platform):
- # Depends on Embree library, which only supports x86_64 and aarch64.
- if env["arch"].startswith("rv") or env["arch"].startswith("ppc"):
- return False
-
- if platform == "android":
- return env["android_arch"] in ["arm64v8", "x86_64"]
-
- if platform == "javascript":
- return False # No SIMD support yet
-
- if env["bits"] == "32":
- return False
-
- return True
+ # Depends on Embree library, which only supports x86_64 and arm64.
+ return env["arch"] in ["x86_64", "arm64"]
def configure(env):
diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml
index 9adb6acd9c..56404f796c 100644
--- a/modules/regex/doc_classes/RegEx.xml
+++ b/modules/regex/doc_classes/RegEx.xml
@@ -76,7 +76,7 @@
</description>
</method>
<method name="get_names" qualifiers="const">
- <return type="Array" />
+ <return type="PackedStringArray" />
<description>
Returns an array of names of named capturing groups in the compiled pattern. They are ordered by appearance.
</description>
diff --git a/modules/regex/regex.cpp b/modules/regex/regex.cpp
index 569066867a..b2e6ea1004 100644
--- a/modules/regex/regex.cpp
+++ b/modules/regex/regex.cpp
@@ -351,8 +351,8 @@ int RegEx::get_group_count() const {
return count;
}
-Array RegEx::get_names() const {
- Array result;
+PackedStringArray RegEx::get_names() const {
+ PackedStringArray result;
ERR_FAIL_COND_V(!is_valid(), result);
diff --git a/modules/regex/regex.h b/modules/regex/regex.h
index 9296de929f..6920d2634d 100644
--- a/modules/regex/regex.h
+++ b/modules/regex/regex.h
@@ -94,7 +94,7 @@ public:
bool is_valid() const;
String get_pattern() const;
int get_group_count() const;
- Array get_names() const;
+ PackedStringArray get_names() const;
RegEx();
RegEx(const String &p_pattern);
diff --git a/modules/regex/tests/test_regex.h b/modules/regex/tests/test_regex.h
index 91af393db1..c81094d3ae 100644
--- a/modules/regex/tests/test_regex.h
+++ b/modules/regex/tests/test_regex.h
@@ -46,7 +46,7 @@ TEST_CASE("[RegEx] Initialization") {
CHECK(re1.get_pattern() == pattern);
CHECK(re1.get_group_count() == 1);
- Array names = re1.get_names();
+ PackedStringArray names = re1.get_names();
CHECK(names.size() == 1);
CHECK(names[0] == "vowel");
diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp
index 87e2fae2d0..5f839bd979 100644
--- a/modules/svg/image_loader_svg.cpp
+++ b/modules/svg/image_loader_svg.cpp
@@ -35,13 +35,13 @@
#include <thorvg.h>
-void ImageLoaderSVG::_replace_color_property(const String &p_prefix, String &r_string) {
- // Replace colors in the SVG based on what is configured in `replace_colors`.
+void ImageLoaderSVG::_replace_color_property(const HashMap<Color, Color> &p_color_map, const String &p_prefix, String &r_string) {
+ // Replace colors in the SVG based on what is passed in `p_color_map`.
// Used to change the colors of editor icons based on the used theme.
// The strings being replaced are typically of the form:
// fill="#5abbef"
// But can also be 3-letter codes, include alpha, be "none" or a named color
- // string ("blue"). So we convert to Godot Color to compare with `replace_colors`.
+ // string ("blue"). So we convert to Godot Color to compare with `p_color_map`.
const int prefix_len = p_prefix.length();
int pos = r_string.find(p_prefix);
@@ -52,8 +52,8 @@ void ImageLoaderSVG::_replace_color_property(const String &p_prefix, String &r_s
const String color_code = r_string.substr(pos, end_pos - pos);
if (color_code != "none" && !color_code.begins_with("url(")) {
const Color color = Color(color_code); // Handles both HTML codes and named colors.
- if (replace_colors.has(color)) {
- r_string = r_string.left(pos) + "#" + replace_colors[color].operator Color().to_html(false) + r_string.substr(end_pos);
+ if (p_color_map.has(color)) {
+ r_string = r_string.left(pos) + "#" + p_color_map[color].to_html(false) + r_string.substr(end_pos);
}
}
// Search for other occurrences.
@@ -61,13 +61,13 @@ void ImageLoaderSVG::_replace_color_property(const String &p_prefix, String &r_s
}
}
-void ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, bool p_convert_color) {
+void ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, const HashMap<Color, Color> &p_color_map) {
ERR_FAIL_COND(Math::is_zero_approx(p_scale));
- if (p_convert_color) {
- _replace_color_property("stop-color=\"", p_string);
- _replace_color_property("fill=\"", p_string);
- _replace_color_property("stroke=\"", p_string);
+ if (p_color_map.size()) {
+ _replace_color_property(p_color_map, "stop-color=\"", p_string);
+ _replace_color_property(p_color_map, "fill=\"", p_string);
+ _replace_color_property(p_color_map, "stroke=\"", p_string);
}
std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
@@ -136,11 +136,11 @@ void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const
p_extensions->push_back("svg");
}
-Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) {
+Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, uint32_t p_flags, float p_scale) {
String svg = p_fileaccess->get_as_utf8_string();
- create_image_from_string(p_image, svg, p_scale, false, false);
+ create_image_from_string(p_image, svg, p_scale, false, HashMap<Color, Color>());
ERR_FAIL_COND_V(p_image->is_empty(), FAILED);
- if (p_force_linear) {
+ if (p_flags & FLAG_FORCE_LINEAR) {
p_image->srgb_to_linear();
}
return OK;
diff --git a/modules/svg/image_loader_svg.h b/modules/svg/image_loader_svg.h
index 94c17fda43..fc89b63edb 100644
--- a/modules/svg/image_loader_svg.h
+++ b/modules/svg/image_loader_svg.h
@@ -34,15 +34,12 @@
#include "core/io/image_loader.h"
class ImageLoaderSVG : public ImageFormatLoader {
- Dictionary replace_colors;
- void _replace_color_property(const String &p_prefix, String &r_string);
+ void _replace_color_property(const HashMap<Color, Color> &p_color_map, const String &p_prefix, String &r_string);
public:
- // Called by the editor to handle theme icon colors.
- void set_replace_colors(Dictionary p_replace_colors) { replace_colors = p_replace_colors; }
- void create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, bool p_convert_color);
+ void create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, const HashMap<Color, Color> &p_color_map);
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) override;
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, uint32_t p_flags, float p_scale) override;
virtual void get_recognized_extensions(List<String> *p_extensions) const override;
};
diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp
index 73dbf2f443..e80eb43369 100644
--- a/modules/text_server_adv/text_server_adv.cpp
+++ b/modules/text_server_adv/text_server_adv.cpp
@@ -1313,12 +1313,14 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f
fargs.stream = &fd->stream;
int max_index = 0;
- FT_Face tmp_face;
+ FT_Face tmp_face = nullptr;
error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face);
- if (error == 0) {
+ if (tmp_face && error == 0) {
max_index = tmp_face->num_faces - 1;
}
- FT_Done_Face(tmp_face);
+ if (tmp_face) {
+ FT_Done_Face(tmp_face);
+ }
error = FT_Open_Face(ft_library, &fargs, CLAMP(p_font_data->face_index, 0, max_index), &fd->face);
if (error) {
@@ -2168,12 +2170,12 @@ double TextServerAdvanced::font_get_oversampling(const RID &p_font_rid) const {
return fd->oversampling;
}
-Array TextServerAdvanced::font_get_size_cache_list(const RID &p_font_rid) const {
+TypedArray<Vector2i> TextServerAdvanced::font_get_size_cache_list(const RID &p_font_rid) const {
FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
- ERR_FAIL_COND_V(!fd, Array());
+ ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>());
MutexLock lock(fd->mutex);
- Array ret;
+ TypedArray<Vector2i> ret;
for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
ret.push_back(E.key);
}
@@ -2452,15 +2454,15 @@ PackedInt32Array TextServerAdvanced::font_get_texture_offsets(const RID &p_font_
return tex.offsets;
}
-Array TextServerAdvanced::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
+PackedInt32Array TextServerAdvanced::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
- ERR_FAIL_COND_V(!fd, Array());
+ ERR_FAIL_COND_V(!fd, PackedInt32Array());
MutexLock lock(fd->mutex);
Vector2i size = _get_size_outline(fd, p_size);
- ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Array());
+ ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), PackedInt32Array());
- Array ret;
+ PackedInt32Array ret;
const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
for (const KeyValue<int32_t, FontGlyph> &E : gl) {
ret.push_back(E.key);
@@ -2809,16 +2811,16 @@ Dictionary TextServerAdvanced::font_get_glyph_contours(const RID &p_font_rid, in
#endif
}
-Array TextServerAdvanced::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
+TypedArray<Vector2i> TextServerAdvanced::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
- ERR_FAIL_COND_V(!fd, Array());
+ ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>());
MutexLock lock(fd->mutex);
Vector2i size = _get_size(fd, p_size);
- ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Array());
+ ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), TypedArray<Vector2i>());
- Array ret;
+ TypedArray<Vector2i> ret;
for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
ret.push_back(E.key);
}
@@ -3063,7 +3065,7 @@ void TextServerAdvanced::font_draw_glyph(const RID &p_font_rid, const RID &p_can
if (gl.texture_idx != -1) {
Color modulate = p_color;
#ifdef MODULE_FREETYPE_ENABLED
- if (fd->cache[size]->face && FT_HAS_COLOR(fd->cache[size]->face)) {
+ if (fd->cache[size]->face && fd->cache[size]->textures[gl.texture_idx].format == Image::FORMAT_RGBA8) {
modulate.r = modulate.g = modulate.b = 1.0;
}
#endif
diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h
index 7ae329d616..6c3e8dbdcb 100644
--- a/modules/text_server_adv/text_server_adv.h
+++ b/modules/text_server_adv/text_server_adv.h
@@ -537,7 +537,7 @@ public:
virtual void font_set_oversampling(const RID &p_font_rid, double p_oversampling) override;
virtual double font_get_oversampling(const RID &p_font_rid) const override;
- virtual Array font_get_size_cache_list(const RID &p_font_rid) const override;
+ virtual TypedArray<Vector2i> font_get_size_cache_list(const RID &p_font_rid) const override;
virtual void font_clear_size_cache(const RID &p_font_rid) override;
virtual void font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) override;
@@ -566,7 +566,7 @@ public:
virtual void font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) override;
virtual PackedInt32Array font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const override;
- virtual Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override;
+ virtual PackedInt32Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override;
virtual void font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) override;
virtual void font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) override;
@@ -590,7 +590,7 @@ public:
virtual Dictionary font_get_glyph_contours(const RID &p_font, int64_t p_size, int64_t p_index) const override;
- virtual Array font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override;
+ virtual TypedArray<Vector2i> font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override;
virtual void font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) override;
virtual void font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) override;
diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp
index 55d912a10a..016bcfc886 100644
--- a/modules/text_server_fb/text_server_fb.cpp
+++ b/modules/text_server_fb/text_server_fb.cpp
@@ -733,12 +733,14 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f
fargs.stream = &fd->stream;
int max_index = 0;
- FT_Face tmp_face;
+ FT_Face tmp_face = nullptr;
error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face);
- if (error == 0) {
+ if (tmp_face && error == 0) {
max_index = tmp_face->num_faces - 1;
}
- FT_Done_Face(tmp_face);
+ if (tmp_face) {
+ FT_Done_Face(tmp_face);
+ }
error = FT_Open_Face(ft_library, &fargs, CLAMP(p_font_data->face_index, 0, max_index), &fd->face);
if (error) {
@@ -1257,12 +1259,12 @@ double TextServerFallback::font_get_oversampling(const RID &p_font_rid) const {
return fd->oversampling;
}
-Array TextServerFallback::font_get_size_cache_list(const RID &p_font_rid) const {
+TypedArray<Vector2i> TextServerFallback::font_get_size_cache_list(const RID &p_font_rid) const {
FontFallback *fd = font_owner.get_or_null(p_font_rid);
- ERR_FAIL_COND_V(!fd, Array());
+ ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>());
MutexLock lock(fd->mutex);
- Array ret;
+ TypedArray<Vector2i> ret;
for (const KeyValue<Vector2i, FontForSizeFallback *> &E : fd->cache) {
ret.push_back(E.key);
}
@@ -1541,15 +1543,15 @@ PackedInt32Array TextServerFallback::font_get_texture_offsets(const RID &p_font_
return tex.offsets;
}
-Array TextServerFallback::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
+PackedInt32Array TextServerFallback::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
FontFallback *fd = font_owner.get_or_null(p_font_rid);
- ERR_FAIL_COND_V(!fd, Array());
+ ERR_FAIL_COND_V(!fd, PackedInt32Array());
MutexLock lock(fd->mutex);
Vector2i size = _get_size_outline(fd, p_size);
- ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Array());
+ ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), PackedInt32Array());
- Array ret;
+ PackedInt32Array ret;
const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
for (const KeyValue<int32_t, FontGlyph> &E : gl) {
ret.push_back(E.key);
@@ -1884,16 +1886,16 @@ Dictionary TextServerFallback::font_get_glyph_contours(const RID &p_font_rid, in
#endif
}
-Array TextServerFallback::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
+TypedArray<Vector2i> TextServerFallback::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
FontFallback *fd = font_owner.get_or_null(p_font_rid);
- ERR_FAIL_COND_V(!fd, Array());
+ ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>());
MutexLock lock(fd->mutex);
Vector2i size = _get_size(fd, p_size);
- ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Array());
+ ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), TypedArray<Vector2i>());
- Array ret;
+ TypedArray<Vector2i> ret;
for (const KeyValue<Vector2i, Vector2> &E : fd->cache[size]->kerning_map) {
ret.push_back(E.key);
}
@@ -2120,7 +2122,7 @@ void TextServerFallback::font_draw_glyph(const RID &p_font_rid, const RID &p_can
if (gl.texture_idx != -1) {
Color modulate = p_color;
#ifdef MODULE_FREETYPE_ENABLED
- if (fd->cache[size]->face && FT_HAS_COLOR(fd->cache[size]->face)) {
+ if (fd->cache[size]->face && fd->cache[size]->textures[gl.texture_idx].format == Image::FORMAT_RGBA8) {
modulate.r = modulate.g = modulate.b = 1.0;
}
#endif
diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h
index fef19d442b..8e81433a2a 100644
--- a/modules/text_server_fb/text_server_fb.h
+++ b/modules/text_server_fb/text_server_fb.h
@@ -417,7 +417,7 @@ public:
virtual void font_set_oversampling(const RID &p_font_rid, double p_oversampling) override;
virtual double font_get_oversampling(const RID &p_font_rid) const override;
- virtual Array font_get_size_cache_list(const RID &p_font_rid) const override;
+ virtual TypedArray<Vector2i> font_get_size_cache_list(const RID &p_font_rid) const override;
virtual void font_clear_size_cache(const RID &p_font_rid) override;
virtual void font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) override;
@@ -446,7 +446,7 @@ public:
virtual void font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) override;
virtual PackedInt32Array font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const override;
- virtual Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override;
+ virtual PackedInt32Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override;
virtual void font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) override;
virtual void font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) override;
@@ -469,7 +469,7 @@ public:
virtual Dictionary font_get_glyph_contours(const RID &p_font, int64_t p_size, int64_t p_index) const override;
- virtual Array font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override;
+ virtual TypedArray<Vector2i> font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override;
virtual void font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) override;
virtual void font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) override;
diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp
index 08ad1ef9f8..16d9bf7b93 100644
--- a/modules/tga/image_loader_tga.cpp
+++ b/modules/tga/image_loader_tga.cpp
@@ -230,7 +230,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff
return OK;
}
-Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) {
+Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) {
Vector<uint8_t> src_image;
uint64_t src_image_len = f->get_length();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
diff --git a/modules/tga/image_loader_tga.h b/modules/tga/image_loader_tga.h
index 9b7cbbac77..d95c5ff30b 100644
--- a/modules/tga/image_loader_tga.h
+++ b/modules/tga/image_loader_tga.h
@@ -73,7 +73,7 @@ class ImageLoaderTGA : public ImageFormatLoader {
static Error convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const tga_header_s &p_header, const uint8_t *p_palette, const bool p_is_monochrome, size_t p_input_size);
public:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale);
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderTGA();
};
diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp
index 864df765ee..6f61251f9b 100644
--- a/modules/tinyexr/image_loader_tinyexr.cpp
+++ b/modules/tinyexr/image_loader_tinyexr.cpp
@@ -37,7 +37,7 @@
#include "thirdparty/tinyexr/tinyexr.h"
-Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) {
+Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) {
Vector<uint8_t> src_image;
uint64_t src_image_len = f->get_length();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
@@ -229,7 +229,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool
color.a = *a_channel++;
}
- if (p_force_linear) {
+ if (p_flags & FLAG_FORCE_LINEAR) {
color = color.srgb_to_linear();
}
@@ -260,7 +260,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool
color.a = *a_channel++;
}
- if (p_force_linear) {
+ if (p_flags & FLAG_FORCE_LINEAR) {
color = color.srgb_to_linear();
}
diff --git a/modules/tinyexr/image_loader_tinyexr.h b/modules/tinyexr/image_loader_tinyexr.h
index 0d3de93956..8da2a0d4af 100644
--- a/modules/tinyexr/image_loader_tinyexr.h
+++ b/modules/tinyexr/image_loader_tinyexr.h
@@ -35,7 +35,7 @@
class ImageLoaderTinyEXR : public ImageFormatLoader {
public:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale);
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderTinyEXR();
};
diff --git a/modules/visual_script/SCsub b/modules/visual_script/SCsub
deleted file mode 100644
index b91cceae09..0000000000
--- a/modules/visual_script/SCsub
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-Import("env")
-Import("env_modules")
-
-env_vs = env_modules.Clone()
-
-env_vs.add_source_files(env.modules_sources, "*.cpp")
-
-if env["tools"]:
- env_vs.add_source_files(env.modules_sources, "editor/*.cpp")
diff --git a/modules/visual_script/config.py b/modules/visual_script/config.py
deleted file mode 100644
index e8990c43c8..0000000000
--- a/modules/visual_script/config.py
+++ /dev/null
@@ -1,63 +0,0 @@
-def can_build(env, platform):
- return True
-
-
-def configure(env):
- pass
-
-
-def get_doc_classes():
- return [
- "VisualScriptBasicTypeConstant",
- "VisualScriptBuiltinFunc",
- "VisualScriptClassConstant",
- "VisualScriptComment",
- "VisualScriptComposeArray",
- "VisualScriptCondition",
- "VisualScriptConstant",
- "VisualScriptConstructor",
- "VisualScriptCustomNode",
- "VisualScriptCustomNodes",
- "VisualScriptDeconstruct",
- "VisualScriptEditor",
- "VisualScriptEmitSignal",
- "VisualScriptEngineSingleton",
- "VisualScriptExpression",
- "VisualScriptFunctionCall",
- "VisualScriptFunctionState",
- "VisualScriptFunction",
- "VisualScriptGlobalConstant",
- "VisualScriptIndexGet",
- "VisualScriptIndexSet",
- "VisualScriptInputAction",
- "VisualScriptIterator",
- "VisualScriptLists",
- "VisualScriptLocalVarSet",
- "VisualScriptLocalVar",
- "VisualScriptMathConstant",
- "VisualScriptNode",
- "VisualScriptOperator",
- "VisualScriptPreload",
- "VisualScriptPropertyGet",
- "VisualScriptPropertySet",
- "VisualScriptResourcePath",
- "VisualScriptReturn",
- "VisualScriptSceneNode",
- "VisualScriptSceneTree",
- "VisualScriptSelect",
- "VisualScriptSelf",
- "VisualScriptSequence",
- "VisualScriptSubCall",
- "VisualScriptSwitch",
- "VisualScriptTypeCast",
- "VisualScriptVariableGet",
- "VisualScriptVariableSet",
- "VisualScriptWhile",
- "VisualScript",
- "VisualScriptYieldSignal",
- "VisualScriptYield",
- ]
-
-
-def get_doc_path():
- return "doc_classes"
diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml
deleted file mode 100644
index ff6b7a8b5f..0000000000
--- a/modules/visual_script/doc_classes/VisualScript.xml
+++ /dev/null
@@ -1,357 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A script implemented in the Visual Script programming environment. The script extends the functionality of all objects that instance it.
- [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes.
- You are most likely to use this class via the Visual Script editor or when writing plugins for it.
- </description>
- <tutorials>
- <link title="VisualScript documentation index">$DOCS_URL/tutorials/scripting/visual_script/index.html</link>
- </tutorials>
- <methods>
- <method name="add_custom_signal">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <description>
- Add a custom signal with the specified name to the VisualScript.
- </description>
- </method>
- <method name="add_function">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="func_node_id" type="int" />
- <description>
- Add a function with the specified name to the VisualScript, and assign the root [VisualScriptFunction] node's id as [code]func_node_id[/code].
- </description>
- </method>
- <method name="add_node">
- <return type="void" />
- <param index="0" name="id" type="int" />
- <param index="1" name="node" type="VisualScriptNode" />
- <param index="2" name="position" type="Vector2" default="Vector2(0, 0)" />
- <description>
- Add a node to the VisualScript.
- </description>
- </method>
- <method name="add_variable">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="default_value" type="Variant" default="null" />
- <param index="2" name="export" type="bool" default="false" />
- <description>
- Add a variable to the VisualScript, optionally giving it a default value or marking it as exported.
- </description>
- </method>
- <method name="custom_signal_add_argument">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="type" type="int" enum="Variant.Type" />
- <param index="2" name="argname" type="String" />
- <param index="3" name="index" type="int" default="-1" />
- <description>
- Add an argument to a custom signal added with [method add_custom_signal].
- </description>
- </method>
- <method name="custom_signal_get_argument_count" qualifiers="const">
- <return type="int" />
- <param index="0" name="name" type="StringName" />
- <description>
- Get the count of a custom signal's arguments.
- </description>
- </method>
- <method name="custom_signal_get_argument_name" qualifiers="const">
- <return type="String" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="argidx" type="int" />
- <description>
- Get the name of a custom signal's argument.
- </description>
- </method>
- <method name="custom_signal_get_argument_type" qualifiers="const">
- <return type="int" enum="Variant.Type" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="argidx" type="int" />
- <description>
- Get the type of a custom signal's argument.
- </description>
- </method>
- <method name="custom_signal_remove_argument">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="argidx" type="int" />
- <description>
- Remove a specific custom signal's argument.
- </description>
- </method>
- <method name="custom_signal_set_argument_name">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="argidx" type="int" />
- <param index="2" name="argname" type="String" />
- <description>
- Rename a custom signal's argument.
- </description>
- </method>
- <method name="custom_signal_set_argument_type">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="argidx" type="int" />
- <param index="2" name="type" type="int" enum="Variant.Type" />
- <description>
- Change the type of a custom signal's argument.
- </description>
- </method>
- <method name="custom_signal_swap_argument">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="argidx" type="int" />
- <param index="2" name="withidx" type="int" />
- <description>
- Swap two of the arguments of a custom signal.
- </description>
- </method>
- <method name="data_connect">
- <return type="void" />
- <param index="0" name="from_node" type="int" />
- <param index="1" name="from_port" type="int" />
- <param index="2" name="to_node" type="int" />
- <param index="3" name="to_port" type="int" />
- <description>
- Connect two data ports. The value of [code]from_node[/code]'s [code]from_port[/code] would be fed into [code]to_node[/code]'s [code]to_port[/code].
- </description>
- </method>
- <method name="data_disconnect">
- <return type="void" />
- <param index="0" name="from_node" type="int" />
- <param index="1" name="from_port" type="int" />
- <param index="2" name="to_node" type="int" />
- <param index="3" name="to_port" type="int" />
- <description>
- Disconnect two data ports previously connected with [method data_connect].
- </description>
- </method>
- <method name="get_function_node_id" qualifiers="const">
- <return type="int" />
- <param index="0" name="name" type="StringName" />
- <description>
- Returns the id of a function's entry point node.
- </description>
- </method>
- <method name="get_node" qualifiers="const">
- <return type="VisualScriptNode" />
- <param index="0" name="id" type="int" />
- <description>
- Returns a node given its id.
- </description>
- </method>
- <method name="get_node_position" qualifiers="const">
- <return type="Vector2" />
- <param index="0" name="id" type="int" />
- <description>
- Returns a node's position in pixels.
- </description>
- </method>
- <method name="get_scroll" qualifiers="const">
- <return type="Vector2" />
- <description>
- Returns the current position of the center of the screen.
- </description>
- </method>
- <method name="get_variable_default_value" qualifiers="const">
- <return type="Variant" />
- <param index="0" name="name" type="StringName" />
- <description>
- Returns the default (initial) value of a variable.
- </description>
- </method>
- <method name="get_variable_export" qualifiers="const">
- <return type="bool" />
- <param index="0" name="name" type="StringName" />
- <description>
- Returns whether a variable is exported.
- </description>
- </method>
- <method name="get_variable_info" qualifiers="const">
- <return type="Dictionary" />
- <param index="0" name="name" type="StringName" />
- <description>
- Returns the information for a given variable as a dictionary. The information includes its name, type, hint and usage.
- </description>
- </method>
- <method name="has_custom_signal" qualifiers="const">
- <return type="bool" />
- <param index="0" name="name" type="StringName" />
- <description>
- Returns whether a signal exists with the specified name.
- </description>
- </method>
- <method name="has_data_connection" qualifiers="const">
- <return type="bool" />
- <param index="0" name="from_node" type="int" />
- <param index="1" name="from_port" type="int" />
- <param index="2" name="to_node" type="int" />
- <param index="3" name="to_port" type="int" />
- <description>
- Returns whether the specified data ports are connected.
- </description>
- </method>
- <method name="has_function" qualifiers="const">
- <return type="bool" />
- <param index="0" name="name" type="StringName" />
- <description>
- Returns whether a function exists with the specified name.
- </description>
- </method>
- <method name="has_node" qualifiers="const">
- <return type="bool" />
- <param index="0" name="id" type="int" />
- <description>
- Returns whether a node exists with the given id.
- </description>
- </method>
- <method name="has_sequence_connection" qualifiers="const">
- <return type="bool" />
- <param index="0" name="from_node" type="int" />
- <param index="1" name="from_output" type="int" />
- <param index="2" name="to_node" type="int" />
- <description>
- Returns whether the specified sequence ports are connected.
- </description>
- </method>
- <method name="has_variable" qualifiers="const">
- <return type="bool" />
- <param index="0" name="name" type="StringName" />
- <description>
- Returns whether a variable exists with the specified name.
- </description>
- </method>
- <method name="remove_custom_signal">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <description>
- Remove a custom signal with the given name.
- </description>
- </method>
- <method name="remove_function">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <description>
- Remove a specific function and its nodes from the script.
- </description>
- </method>
- <method name="remove_node">
- <return type="void" />
- <param index="0" name="id" type="int" />
- <description>
- Remove the node with the specified id.
- </description>
- </method>
- <method name="remove_variable">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <description>
- Remove a variable with the given name.
- </description>
- </method>
- <method name="rename_custom_signal">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="new_name" type="StringName" />
- <description>
- Change the name of a custom signal.
- </description>
- </method>
- <method name="rename_function">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="new_name" type="StringName" />
- <description>
- Change the name of a function.
- </description>
- </method>
- <method name="rename_variable">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="new_name" type="StringName" />
- <description>
- Change the name of a variable.
- </description>
- </method>
- <method name="sequence_connect">
- <return type="void" />
- <param index="0" name="from_node" type="int" />
- <param index="1" name="from_output" type="int" />
- <param index="2" name="to_node" type="int" />
- <description>
- Connect two sequence ports. The execution will flow from of [code]from_node[/code]'s [code]from_output[/code] into [code]to_node[/code].
- Unlike [method data_connect], there isn't a [code]to_port[/code], since the target node can have only one sequence port.
- </description>
- </method>
- <method name="sequence_disconnect">
- <return type="void" />
- <param index="0" name="from_node" type="int" />
- <param index="1" name="from_output" type="int" />
- <param index="2" name="to_node" type="int" />
- <description>
- Disconnect two sequence ports previously connected with [method sequence_connect].
- </description>
- </method>
- <method name="set_instance_base_type">
- <return type="void" />
- <param index="0" name="type" type="StringName" />
- <description>
- Set the base type of the script.
- </description>
- </method>
- <method name="set_node_position">
- <return type="void" />
- <param index="0" name="id" type="int" />
- <param index="1" name="position" type="Vector2" />
- <description>
- Set the node position in the VisualScript graph.
- </description>
- </method>
- <method name="set_scroll">
- <return type="void" />
- <param index="0" name="offset" type="Vector2" />
- <description>
- Set the screen center to the given position.
- </description>
- </method>
- <method name="set_variable_default_value">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="value" type="Variant" />
- <description>
- Change the default (initial) value of a variable.
- </description>
- </method>
- <method name="set_variable_export">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="enable" type="bool" />
- <description>
- Change whether a variable is exported.
- </description>
- </method>
- <method name="set_variable_info">
- <return type="void" />
- <param index="0" name="name" type="StringName" />
- <param index="1" name="value" type="Dictionary" />
- <description>
- Set a variable's info, using the same format as [method get_variable_info].
- </description>
- </method>
- </methods>
- <signals>
- <signal name="node_ports_changed">
- <param index="0" name="id" type="int" />
- <description>
- Emitted when the ports of a node are changed.
- </description>
- </signal>
- </signals>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml b/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml
deleted file mode 100644
index 0ed66f44e1..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node representing a constant from base types, such as [constant Vector3.AXIS_X].
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type" default="0">
- The type to get the constant from.
- </member>
- <member name="constant" type="StringName" setter="set_basic_type_constant" getter="get_basic_type_constant">
- The name of the constant to return.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
deleted file mode 100644
index 647b627d25..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
+++ /dev/null
@@ -1,221 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A built-in function used inside a [VisualScript]. It is usually a math function or an utility function.
- See also [@GDScript], for the same functions in the GDScript language.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="function" type="int" setter="set_func" getter="get_func" enum="VisualScriptBuiltinFunc.BuiltinFunc" default="0">
- The function to be executed.
- </member>
- </members>
- <constants>
- <constant name="MATH_SIN" value="0" enum="BuiltinFunc">
- Returns the sine of the input.
- </constant>
- <constant name="MATH_COS" value="1" enum="BuiltinFunc">
- Returns the cosine of the input.
- </constant>
- <constant name="MATH_TAN" value="2" enum="BuiltinFunc">
- Returns the tangent of the input.
- </constant>
- <constant name="MATH_SINH" value="3" enum="BuiltinFunc">
- Returns the hyperbolic sine of the input.
- </constant>
- <constant name="MATH_COSH" value="4" enum="BuiltinFunc">
- Returns the hyperbolic cosine of the input.
- </constant>
- <constant name="MATH_TANH" value="5" enum="BuiltinFunc">
- Returns the hyperbolic tangent of the input.
- </constant>
- <constant name="MATH_ASIN" value="6" enum="BuiltinFunc">
- Returns the arc sine of the input.
- </constant>
- <constant name="MATH_ACOS" value="7" enum="BuiltinFunc">
- Returns the arc cosine of the input.
- </constant>
- <constant name="MATH_ATAN" value="8" enum="BuiltinFunc">
- Returns the arc tangent of the input.
- </constant>
- <constant name="MATH_ATAN2" value="9" enum="BuiltinFunc">
- Returns the arc tangent of the input, using the signs of both parameters to determine the exact angle.
- </constant>
- <constant name="MATH_SQRT" value="10" enum="BuiltinFunc">
- Returns the square root of the input.
- </constant>
- <constant name="MATH_FMOD" value="11" enum="BuiltinFunc">
- Returns the remainder of one input divided by the other, using floating-point numbers.
- </constant>
- <constant name="MATH_FPOSMOD" value="12" enum="BuiltinFunc">
- Returns the positive remainder of one input divided by the other, using floating-point numbers.
- </constant>
- <constant name="MATH_FLOOR" value="13" enum="BuiltinFunc">
- Returns the input rounded down.
- </constant>
- <constant name="MATH_CEIL" value="14" enum="BuiltinFunc">
- Returns the input rounded up.
- </constant>
- <constant name="MATH_ROUND" value="15" enum="BuiltinFunc">
- Returns the input rounded to the nearest integer.
- </constant>
- <constant name="MATH_ABS" value="16" enum="BuiltinFunc">
- Returns the absolute value of the input.
- </constant>
- <constant name="MATH_SIGN" value="17" enum="BuiltinFunc">
- Returns the sign of the input, turning it into 1, -1, or 0. Useful to determine if the input is positive or negative.
- </constant>
- <constant name="MATH_POW" value="18" enum="BuiltinFunc">
- Returns the input raised to a given power.
- </constant>
- <constant name="MATH_LOG" value="19" enum="BuiltinFunc">
- Returns the natural logarithm of the input. Note that this is not the typical base-10 logarithm function calculators use.
- </constant>
- <constant name="MATH_EXP" value="20" enum="BuiltinFunc">
- Returns the mathematical constant [b]e[/b] raised to the specified power of the input. [b]e[/b] has an approximate value of 2.71828.
- </constant>
- <constant name="MATH_ISNAN" value="21" enum="BuiltinFunc">
- Returns whether the input is NaN (Not a Number) or not. NaN is usually produced by dividing 0 by 0, though other ways exist.
- </constant>
- <constant name="MATH_ISINF" value="22" enum="BuiltinFunc">
- Returns whether the input is an infinite floating-point number or not. Infinity is usually produced by dividing a number by 0, though other ways exist.
- </constant>
- <constant name="MATH_EASE" value="23" enum="BuiltinFunc">
- Easing function, based on exponent. 0 is constant, 1 is linear, 0 to 1 is ease-in, 1+ is ease out. Negative values are in-out/out in.
- </constant>
- <constant name="MATH_STEP_DECIMALS" value="24" enum="BuiltinFunc">
- Returns the number of digit places after the decimal that the first non-zero digit occurs.
- </constant>
- <constant name="MATH_SNAPPED" value="25" enum="BuiltinFunc">
- Returns the input snapped to a given step.
- </constant>
- <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_CUBIC_INTERPOLATE" value="27" enum="BuiltinFunc">
- </constant>
- <constant name="MATH_INVERSE_LERP" value="28" enum="BuiltinFunc">
- </constant>
- <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="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="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="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="34" enum="BuiltinFunc">
- Returns a random 32-bit integer value between the two inputs.
- </constant>
- <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="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="37" enum="BuiltinFunc">
- Set the seed for the random number generator.
- </constant>
- <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="39" enum="BuiltinFunc">
- Convert the input from degrees to radians.
- </constant>
- <constant name="MATH_RAD2DEG" value="40" enum="BuiltinFunc">
- Convert the input from radians to degrees.
- </constant>
- <constant name="MATH_LINEAR2DB" value="41" enum="BuiltinFunc">
- Convert the input from linear volume to decibel volume.
- </constant>
- <constant name="MATH_DB2LINEAR" value="42" enum="BuiltinFunc">
- Convert the input from decibel volume to linear volume.
- </constant>
- <constant name="MATH_WRAP" value="43" enum="BuiltinFunc">
- </constant>
- <constant name="MATH_WRAPF" value="44" enum="BuiltinFunc">
- </constant>
- <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="46" enum="BuiltinFunc">
- Returns the greater of the two numbers, also known as their maximum.
- </constant>
- <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="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="49" enum="BuiltinFunc">
- Returns the nearest power of 2 to the input.
- </constant>
- <constant name="OBJ_WEAKREF" value="50" enum="BuiltinFunc">
- Create a [WeakRef] from the input.
- </constant>
- <constant name="TYPE_CONVERT" value="51" enum="BuiltinFunc">
- Convert between types.
- </constant>
- <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="53" enum="BuiltinFunc">
- Checks if a type is registered in the [ClassDB].
- </constant>
- <constant name="TEXT_CHAR" value="54" enum="BuiltinFunc">
- Returns a character with the given ascii value.
- </constant>
- <constant name="TEXT_STR" value="55" enum="BuiltinFunc">
- Convert the input to a string.
- </constant>
- <constant name="TEXT_PRINT" value="56" enum="BuiltinFunc">
- Print the given string to the output window.
- </constant>
- <constant name="TEXT_PRINTERR" value="57" enum="BuiltinFunc">
- Print the given string to the standard error output.
- </constant>
- <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="59" enum="BuiltinFunc">
- </constant>
- <constant name="VAR_TO_STR" value="60" enum="BuiltinFunc">
- Serialize a [Variant] to a string.
- </constant>
- <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="62" enum="BuiltinFunc">
- Serialize a [Variant] to a [PackedByteArray].
- </constant>
- <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="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="65" enum="BuiltinFunc">
- </constant>
- <constant name="MATH_LERP_ANGLE" value="66" enum="BuiltinFunc">
- </constant>
- <constant name="TEXT_ORD" value="67" enum="BuiltinFunc">
- </constant>
- <constant name="FUNC_MAX" value="68" enum="BuiltinFunc">
- Represents the size of the [enum BuiltinFunc] enum.
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml
deleted file mode 100644
index 2509084f0e..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- This node returns a constant from a given class, such as [constant TYPE_INT]. See the given class' documentation for available constants.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data (variant): [code]value[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&amp;&quot;Object&quot;">
- The constant's parent class.
- </member>
- <member name="constant" type="StringName" setter="set_class_constant" getter="get_class_constant" default="&amp;&quot;&quot;">
- The constant to return. See the given class for its available constants.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptComment.xml b/modules/visual_script/doc_classes/VisualScriptComment.xml
deleted file mode 100644
index cf4b57ca19..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptComment.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node used to display annotations in the script, so that code may be documented.
- Comment nodes can be resized so they encompass a group of nodes.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="description" type="String" setter="set_description" getter="get_description" default="&quot;&quot;">
- The text inside the comment node.
- </member>
- <member name="size" type="Vector2" setter="set_size" getter="get_size" default="Vector2(150, 150)">
- The comment node's size (in pixels).
- </member>
- <member name="title" type="String" setter="set_title" getter="get_title" default="&quot;Comment&quot;">
- The comment node's title.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptComposeArray.xml b/modules/visual_script/doc_classes/VisualScriptComposeArray.xml
deleted file mode 100644
index ea73867c4b..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptComposeArray.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script Node used to compose array from the list of elements provided with custom in-graph UI hard coded in the VisualScript Editor.
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptCondition.xml b/modules/visual_script/doc_classes/VisualScriptCondition.xml
deleted file mode 100644
index a29388569f..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptCondition.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node that checks a [bool] input port. If [code]true[/code], it will exit via the "true" sequence port. If [code]false[/code], it will exit via the "false" sequence port. After exiting either, it exits via the "done" port. Sequence ports may be left disconnected.
- [b]Input Ports:[/b]
- - Sequence: [code]if (cond) is[/code]
- - Data (boolean): [code]cond[/code]
- [b]Output Ports:[/b]
- - Sequence: [code]true[/code]
- - Sequence: [code]false[/code]
- - Sequence: [code]done[/code]
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptConstant.xml b/modules/visual_script/doc_classes/VisualScriptConstant.xml
deleted file mode 100644
index 645ede9001..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptConstant.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- This node returns a constant's value.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data (variant): [code]get[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="type" type="int" setter="set_constant_type" getter="get_constant_type" enum="Variant.Type" default="0">
- The constant's type.
- </member>
- <member name="value" type="Variant" setter="set_constant_value" getter="get_constant_value">
- The constant's value.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptConstructor.xml b/modules/visual_script/doc_classes/VisualScriptConstructor.xml
deleted file mode 100644
index a003f21ab9..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptConstructor.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node which calls a base type constructor. It can be used for type conversion as well.
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="get_constructor" qualifiers="const">
- <return type="Dictionary" />
- <description>
- </description>
- </method>
- <method name="get_constructor_type" qualifiers="const">
- <return type="int" enum="Variant.Type" />
- <description>
- </description>
- </method>
- <method name="set_constructor">
- <return type="void" />
- <param index="0" name="constructor" type="Dictionary" />
- <description>
- </description>
- </method>
- <method name="set_constructor_type">
- <return type="void" />
- <param index="0" name="type" type="int" enum="Variant.Type" />
- <description>
- </description>
- </method>
- </methods>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
deleted file mode 100644
index 6e522b2f84..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
+++ /dev/null
@@ -1,166 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A custom Visual Script node which can be scripted in powerful ways.
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="_get_caption" qualifiers="virtual const">
- <return type="String" />
- <description>
- Returns the node's title.
- </description>
- </method>
- <method name="_get_category" qualifiers="virtual const">
- <return type="String" />
- <description>
- Returns the node's category.
- </description>
- </method>
- <method name="_get_input_value_port_count" qualifiers="virtual const">
- <return type="int" />
- <description>
- Returns the count of input value ports.
- </description>
- </method>
- <method name="_get_input_value_port_hint" qualifiers="virtual const">
- <return type="int" />
- <param index="0" name="input_idx" type="int" />
- <description>
- Returns the specified input port's hint. See the [enum @GlobalScope.PropertyHint] hints.
- </description>
- </method>
- <method name="_get_input_value_port_hint_string" qualifiers="virtual const">
- <return type="String" />
- <param index="0" name="input_idx" type="int" />
- <description>
- Returns the specified input port's hint string.
- </description>
- </method>
- <method name="_get_input_value_port_name" qualifiers="virtual const">
- <return type="String" />
- <param index="0" name="input_idx" type="int" />
- <description>
- Returns the specified input port's name.
- </description>
- </method>
- <method name="_get_input_value_port_type" qualifiers="virtual const">
- <return type="int" />
- <param index="0" name="input_idx" type="int" />
- <description>
- Returns the specified input port's type. See the [enum Variant.Type] values.
- </description>
- </method>
- <method name="_get_output_sequence_port_count" qualifiers="virtual const">
- <return type="int" />
- <description>
- Returns the amount of output [b]sequence[/b] ports.
- </description>
- </method>
- <method name="_get_output_sequence_port_text" qualifiers="virtual const">
- <return type="String" />
- <param index="0" name="seq_idx" type="int" />
- <description>
- Returns the specified [b]sequence[/b] output's name.
- </description>
- </method>
- <method name="_get_output_value_port_count" qualifiers="virtual const">
- <return type="int" />
- <description>
- Returns the amount of output value ports.
- </description>
- </method>
- <method name="_get_output_value_port_hint" qualifiers="virtual const">
- <return type="int" />
- <param index="0" name="output_idx" type="int" />
- <description>
- Returns the specified output port's hint. See the [enum @GlobalScope.PropertyHint] hints.
- </description>
- </method>
- <method name="_get_output_value_port_hint_string" qualifiers="virtual const">
- <return type="String" />
- <param index="0" name="output_idx" type="int" />
- <description>
- Returns the specified output port's hint string.
- </description>
- </method>
- <method name="_get_output_value_port_name" qualifiers="virtual const">
- <return type="String" />
- <param index="0" name="output_idx" type="int" />
- <description>
- Returns the specified output port's name.
- </description>
- </method>
- <method name="_get_output_value_port_type" qualifiers="virtual const">
- <return type="int" />
- <param index="0" name="output_idx" type="int" />
- <description>
- Returns the specified output port's type. See the [enum Variant.Type] values.
- </description>
- </method>
- <method name="_get_text" qualifiers="virtual const">
- <return type="String" />
- <description>
- Returns the custom node's text, which is shown right next to the input [b]sequence[/b] port (if there is none, on the place that is usually taken by it).
- </description>
- </method>
- <method name="_get_working_memory_size" qualifiers="virtual const">
- <return type="int" />
- <description>
- Returns the size of the custom node's working memory. See [method _step] for more details.
- </description>
- </method>
- <method name="_has_input_sequence_port" qualifiers="virtual const">
- <return type="bool" />
- <description>
- Returns whether the custom node has an input [b]sequence[/b] port.
- </description>
- </method>
- <method name="_step" qualifiers="virtual const">
- <return type="Variant" />
- <param index="0" name="inputs" type="Array" />
- <param index="1" name="outputs" type="Array" />
- <param index="2" name="start_mode" type="int" />
- <param index="3" name="working_mem" type="Array" />
- <description>
- Execute the custom node's logic, returning the index of the output sequence port to use or a [String] when there is an error.
- The [code]inputs[/code] array contains the values of the input ports.
- [code]outputs[/code] is an array whose indices should be set to the respective outputs.
- The [code]start_mode[/code] is usually [constant START_MODE_BEGIN_SEQUENCE], unless you have used the [code]STEP_*[/code] constants.
- [code]working_mem[/code] is an array which can be used to persist information between runs of the custom node. The size needs to be predefined using [method _get_working_memory_size].
- When returning, you can mask the returned value with one of the [code]STEP_*[/code] constants.
- </description>
- </method>
- </methods>
- <constants>
- <constant name="START_MODE_BEGIN_SEQUENCE" value="0" enum="StartMode">
- The start mode used the first time when [method _step] is called.
- </constant>
- <constant name="START_MODE_CONTINUE_SEQUENCE" value="1" enum="StartMode">
- The start mode used when [method _step] is called after coming back from a [constant STEP_PUSH_STACK_BIT].
- </constant>
- <constant name="START_MODE_RESUME_YIELD" value="2" enum="StartMode">
- The start mode used when [method _step] is called after resuming from [constant STEP_YIELD_BIT].
- </constant>
- <constant name="STEP_PUSH_STACK_BIT" value="16777216">
- Hint used by [method _step] to tell that control should return to it when there is no other node left to execute.
- This is used by [VisualScriptCondition] to redirect the sequence to the "Done" port after the [code]true[/code]/[code]false[/code] branch has finished execution.
- </constant>
- <constant name="STEP_GO_BACK_BIT" value="33554432">
- Hint used by [method _step] to tell that control should return back, either hitting a previous [constant STEP_PUSH_STACK_BIT] or exiting the function.
- </constant>
- <constant name="STEP_NO_ADVANCE_BIT" value="67108864">
- </constant>
- <constant name="STEP_EXIT_FUNCTION_BIT" value="134217728">
- Hint used by [method _step] to tell that control should stop and exit the function.
- </constant>
- <constant name="STEP_YIELD_BIT" value="268435456">
- Hint used by [method _step] to tell that the function should be yielded.
- Using this requires you to have at least one working memory slot, which is used for the [VisualScriptFunctionState].
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml b/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml
deleted file mode 100644
index 48d7975051..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- This singleton can be used to manage (i.e., add or remove) custom nodes for the Visual Script editor.
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="add_custom_node">
- <return type="void" />
- <param index="0" name="name" type="String" />
- <param index="1" name="category" type="String" />
- <param index="2" name="script" type="Script" />
- <description>
- Add a custom Visual Script node to the editor. It'll be placed under "Custom Nodes" with the [code]category[/code] as the parameter.
- </description>
- </method>
- <method name="remove_custom_node">
- <return type="void" />
- <param index="0" name="name" type="String" />
- <param index="1" name="category" type="String" />
- <description>
- Remove a custom Visual Script node from the editor. Custom nodes already placed on scripts won't be removed.
- </description>
- </method>
- </methods>
- <signals>
- <signal name="custom_nodes_updated">
- <description>
- Emitted when a custom Visual Script node is added or removed.
- </description>
- </signal>
- </signals>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml b/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml
deleted file mode 100644
index b544fd9d90..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node which deconstructs a base type instance into its parts.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="type" type="int" setter="set_deconstruct_type" getter="get_deconstruct_type" enum="Variant.Type" default="0">
- The type to deconstruct.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml
deleted file mode 100644
index c0cefa0ab7..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Emits a specified signal when it is executed.
- [b]Input Ports:[/b]
- - Sequence: [code]emit[/code]
- [b]Output Ports:[/b]
- - Sequence
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="signal" type="StringName" setter="set_signal" getter="get_signal" default="&amp;&quot;&quot;">
- The signal to emit.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml b/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml
deleted file mode 100644
index f60a048845..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node returning a singleton from [@GlobalScope].
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="constant" type="String" setter="set_singleton" getter="get_singleton" default="&quot;&quot;">
- The singleton's name.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptExpression.xml b/modules/visual_script/doc_classes/VisualScriptExpression.xml
deleted file mode 100644
index 14750e7c8d..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptExpression.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node that can execute a custom expression. Values can be provided for the input and the expression result can be retrieved from the output.
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptFunction.xml b/modules/visual_script/doc_classes/VisualScriptFunction.xml
deleted file mode 100644
index 74d9f194eb..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptFunction.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptFunction] represents a function header. It is the starting point for the function body and can be used to tweak the function's properties (e.g. RPC mode).
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml
deleted file mode 100644
index 543263ff8e..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml
+++ /dev/null
@@ -1,75 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptFunctionCall] is created when you add or drag and drop a function onto the Visual Script graph. It allows to tweak parameters of the call, e.g. what object the function is called on.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="base_script" type="String" setter="set_base_script" getter="get_base_script">
- The script to be used when [member call_mode] is set to [constant CALL_MODE_INSTANCE].
- </member>
- <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&amp;&quot;Object&quot;">
- The base type to be used when [member call_mode] is set to [constant CALL_MODE_INSTANCE].
- </member>
- <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type">
- The type to be used when [member call_mode] is set to [constant CALL_MODE_BASIC_TYPE].
- </member>
- <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptFunctionCall.CallMode" default="0">
- [code]call_mode[/code] determines the target object on which the method will be called. See [enum CallMode] for options.
- </member>
- <member name="function" type="StringName" setter="set_function" getter="get_function" default="&amp;&quot;&quot;">
- The name of the function to be called.
- </member>
- <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
- The node path to use when [member call_mode] is set to [constant CALL_MODE_NODE_PATH].
- </member>
- <member name="rpc_call_mode" type="int" setter="set_rpc_call_mode" getter="get_rpc_call_mode" enum="VisualScriptFunctionCall.RPCCallMode" default="0">
- The mode for RPC calls. See [method Node.rpc] for more details and [enum RPCCallMode] for available options.
- </member>
- <member name="singleton" type="StringName" setter="set_singleton" getter="get_singleton">
- The singleton to call the method on. Used when [member call_mode] is set to [constant CALL_MODE_SINGLETON].
- </member>
- <member name="use_default_args" type="int" setter="set_use_default_args" getter="get_use_default_args">
- Number of default arguments that will be used when calling the function. Can't be higher than the number of available default arguments in the method's declaration.
- </member>
- <member name="validate" type="bool" setter="set_validate" getter="get_validate" default="true">
- If [code]false[/code], call errors (e.g. wrong number of arguments) will be ignored.
- </member>
- </members>
- <constants>
- <constant name="CALL_MODE_SELF" value="0" enum="CallMode">
- The method will be called on this [Object].
- </constant>
- <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode">
- The method will be called on the given [Node] in the scene tree.
- </constant>
- <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode">
- The method will be called on an instanced node with the given type and script.
- </constant>
- <constant name="CALL_MODE_BASIC_TYPE" value="3" enum="CallMode">
- The method will be called on a GDScript basic type (e.g. [Vector2]).
- </constant>
- <constant name="CALL_MODE_SINGLETON" value="4" enum="CallMode">
- The method will be called on a singleton.
- </constant>
- <constant name="RPC_DISABLED" value="0" enum="RPCCallMode">
- The method will be called locally.
- </constant>
- <constant name="RPC_RELIABLE" value="1" enum="RPCCallMode">
- The method will be called remotely.
- </constant>
- <constant name="RPC_UNRELIABLE" value="2" enum="RPCCallMode">
- The method will be called remotely using an unreliable protocol.
- </constant>
- <constant name="RPC_RELIABLE_TO_ID" value="3" enum="RPCCallMode">
- The method will be called remotely for the given peer.
- </constant>
- <constant name="RPC_UNRELIABLE_TO_ID" value="4" enum="RPCCallMode">
- The method will be called remotely for the given peer, using an unreliable protocol.
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml b/modules/visual_script/doc_classes/VisualScriptFunctionState.xml
deleted file mode 100644
index 03fef9c13b..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptFunctionState] is returned from [VisualScriptYield] and can be used to resume a paused function call.
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="connect_to_signal">
- <return type="void" />
- <param index="0" name="obj" type="Object" />
- <param index="1" name="signals" type="String" />
- <param index="2" name="args" type="Array" />
- <description>
- Connects this [VisualScriptFunctionState] to a signal in the given object to automatically resume when it's emitted.
- </description>
- </method>
- <method name="is_valid" qualifiers="const">
- <return type="bool" />
- <description>
- Returns whether the function state is valid.
- </description>
- </method>
- <method name="resume">
- <return type="Variant" />
- <param index="0" name="args" type="Array" default="[]" />
- <description>
- Resumes the function to run from the point it was yielded.
- </description>
- </method>
- </methods>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml
deleted file mode 100644
index 42ada99257..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node returning a constant from [@GlobalScope].
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="constant" type="int" setter="set_global_constant" getter="get_global_constant" default="0">
- The constant to be used.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml b/modules/visual_script/doc_classes/VisualScriptIndexGet.xml
deleted file mode 100644
index 8828bf9039..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptIndexGet] will return the value stored in an array or a dictionary under the given index.
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml b/modules/visual_script/doc_classes/VisualScriptIndexSet.xml
deleted file mode 100644
index 5c81dcd339..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptIndexSet] will set the value stored in an array or a dictionary under the given index to the provided new value.
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptInputAction.xml b/modules/visual_script/doc_classes/VisualScriptInputAction.xml
deleted file mode 100644
index 51c2eaf353..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptInputAction.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptInputAction] can be used to check if an action is pressed or released.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="action" type="StringName" setter="set_action_name" getter="get_action_name" default="&amp;&quot;&quot;">
- Name of the action.
- </member>
- <member name="mode" type="int" setter="set_action_mode" getter="get_action_mode" enum="VisualScriptInputAction.Mode" default="0">
- State of the action to check. See [enum Mode] for options.
- </member>
- </members>
- <constants>
- <constant name="MODE_PRESSED" value="0" enum="Mode">
- [code]True[/code] if action is pressed.
- </constant>
- <constant name="MODE_RELEASED" value="1" enum="Mode">
- [code]True[/code] if action is released (i.e. not pressed).
- </constant>
- <constant name="MODE_JUST_PRESSED" value="2" enum="Mode">
- [code]True[/code] on the frame the action was pressed.
- </constant>
- <constant name="MODE_JUST_RELEASED" value="3" enum="Mode">
- [code]True[/code] on the frame the action was released.
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptIterator.xml b/modules/visual_script/doc_classes/VisualScriptIterator.xml
deleted file mode 100644
index ef6846deba..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptIterator.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- This node steps through each item in a given input. Input can be any sequence data type, such as an [Array] or [String]. When each item has been processed, execution passed out the [code]exit[/code] Sequence port.
- [b]Input Ports:[/b]
- - Sequence: [code]for (elem) in (input)[/code]
- - Data (variant): [code]input[/code]
- [b]Output Ports:[/b]
- - Sequence: [code]each[/code]
- - Sequence: [code]exit[/code]
- - Data (variant): [code]elem[/code]
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptLists.xml b/modules/visual_script/doc_classes/VisualScriptLists.xml
deleted file mode 100644
index 607965bf71..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptLists.xml
+++ /dev/null
@@ -1,77 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script virtual class that defines the shape and the default behavior of the nodes that have to be in-graph editable nodes.
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="add_input_data_port">
- <return type="void" />
- <param index="0" name="type" type="int" enum="Variant.Type" />
- <param index="1" name="name" type="String" />
- <param index="2" name="index" type="int" />
- <description>
- Adds an input port to the Visual Script node.
- </description>
- </method>
- <method name="add_output_data_port">
- <return type="void" />
- <param index="0" name="type" type="int" enum="Variant.Type" />
- <param index="1" name="name" type="String" />
- <param index="2" name="index" type="int" />
- <description>
- Adds an output port to the Visual Script node.
- </description>
- </method>
- <method name="remove_input_data_port">
- <return type="void" />
- <param index="0" name="index" type="int" />
- <description>
- Removes an input port from the Visual Script node.
- </description>
- </method>
- <method name="remove_output_data_port">
- <return type="void" />
- <param index="0" name="index" type="int" />
- <description>
- Removes an output port from the Visual Script node.
- </description>
- </method>
- <method name="set_input_data_port_name">
- <return type="void" />
- <param index="0" name="index" type="int" />
- <param index="1" name="name" type="String" />
- <description>
- Sets the name of an input port.
- </description>
- </method>
- <method name="set_input_data_port_type">
- <return type="void" />
- <param index="0" name="index" type="int" />
- <param index="1" name="type" type="int" enum="Variant.Type" />
- <description>
- Sets the type of an input port.
- </description>
- </method>
- <method name="set_output_data_port_name">
- <return type="void" />
- <param index="0" name="index" type="int" />
- <param index="1" name="name" type="String" />
- <description>
- Sets the name of an output port.
- </description>
- </method>
- <method name="set_output_data_port_type">
- <return type="void" />
- <param index="0" name="index" type="int" />
- <param index="1" name="type" type="int" enum="Variant.Type" />
- <description>
- Sets the type of an output port.
- </description>
- </method>
- </methods>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml
deleted file mode 100644
index dbf9049f0a..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Returns a local variable's value. "Var Name" must be supplied, with an optional type.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data (variant): [code]get[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0">
- The local variable's type.
- </member>
- <member name="var_name" type="StringName" setter="set_var_name" getter="get_var_name" default="&amp;&quot;new_local&quot;">
- The local variable's name.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml
deleted file mode 100644
index 1ae4e20f97..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Changes a local variable's value to the given input. The new value is also provided on an output Data port.
- [b]Input Ports:[/b]
- - Sequence
- - Data (variant): [code]set[/code]
- [b]Output Ports:[/b]
- - Sequence
- - Data (variant): [code]get[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0">
- The local variable's type.
- </member>
- <member name="var_name" type="StringName" setter="set_var_name" getter="get_var_name" default="&amp;&quot;new_local&quot;">
- The local variable's name.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml b/modules/visual_script/doc_classes/VisualScriptMathConstant.xml
deleted file mode 100644
index 01c36e763b..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Provides common math constants, such as Pi, on an output Data port.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data (variant): [code]get[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="constant" type="int" setter="set_math_constant" getter="get_math_constant" enum="VisualScriptMathConstant.MathConstant" default="0">
- The math constant.
- </member>
- </members>
- <constants>
- <constant name="MATH_CONSTANT_ONE" value="0" enum="MathConstant">
- Unity: [code]1[/code].
- </constant>
- <constant name="MATH_CONSTANT_PI" value="1" enum="MathConstant">
- Pi: [code]3.141593[/code].
- </constant>
- <constant name="MATH_CONSTANT_HALF_PI" value="2" enum="MathConstant">
- Pi divided by two: [code]1.570796[/code].
- </constant>
- <constant name="MATH_CONSTANT_TAU" value="3" enum="MathConstant">
- Tau: [code]6.283185[/code].
- </constant>
- <constant name="MATH_CONSTANT_E" value="4" enum="MathConstant">
- Mathematical constant [code]e[/code], the natural log base: [code]2.718282[/code].
- </constant>
- <constant name="MATH_CONSTANT_SQRT2" value="5" enum="MathConstant">
- Square root of two: [code]1.414214[/code].
- </constant>
- <constant name="MATH_CONSTANT_INF" value="6" enum="MathConstant">
- Infinity: [code]inf[/code].
- </constant>
- <constant name="MATH_CONSTANT_NAN" value="7" enum="MathConstant">
- Not a number: [code]nan[/code].
- </constant>
- <constant name="MATH_CONSTANT_MAX" value="8" enum="MathConstant">
- Represents the size of the [enum MathConstant] enum.
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptNode.xml b/modules/visual_script/doc_classes/VisualScriptNode.xml
deleted file mode 100644
index 97c4f8ce76..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptNode.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A node which is part of a [VisualScript]. Not to be confused with [Node], which is a part of a [SceneTree].
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="get_default_input_value" qualifiers="const">
- <return type="Variant" />
- <param index="0" name="port_idx" type="int" />
- <description>
- Returns the default value of a given port. The default value is used when nothing is connected to the port.
- </description>
- </method>
- <method name="get_visual_script" qualifiers="const">
- <return type="VisualScript" />
- <description>
- Returns the [VisualScript] instance the node is bound to.
- </description>
- </method>
- <method name="ports_changed_notify">
- <return type="void" />
- <description>
- Notify that the node's ports have changed. Usually used in conjunction with [VisualScriptCustomNode] .
- </description>
- </method>
- <method name="set_default_input_value">
- <return type="void" />
- <param index="0" name="port_idx" type="int" />
- <param index="1" name="value" type="Variant" />
- <description>
- Change the default value of a given port.
- </description>
- </method>
- </methods>
- <signals>
- <signal name="ports_changed">
- <description>
- Emitted when the available input/output ports are changed.
- </description>
- </signal>
- </signals>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptOperator.xml b/modules/visual_script/doc_classes/VisualScriptOperator.xml
deleted file mode 100644
index 47ca6ddb90..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptOperator.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [b]Input Ports:[/b]
- - Data (variant): [code]A[/code]
- - Data (variant): [code]B[/code]
- [b]Output Ports:[/b]
- - Data (variant): [code]result[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="operator" type="int" setter="set_operator" getter="get_operator" enum="Variant.Operator" default="6">
- The operation to be performed. See [enum Variant.Operator] for available options.
- </member>
- <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type" default="0">
- The type of the values for this operation. See [enum Variant.Type] for available options.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptPreload.xml b/modules/visual_script/doc_classes/VisualScriptPreload.xml
deleted file mode 100644
index 146d6cd9c3..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptPreload.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Creates a new [Resource] or loads one from the filesystem.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data (object): [code]res[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="resource" type="Resource" setter="set_preload" getter="get_preload">
- The [Resource] to load.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
deleted file mode 100644
index 77cd6393a9..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptPropertyGet] can return a value of any property from the current object or other objects.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="base_script" type="String" setter="set_base_script" getter="get_base_script">
- The script to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE].
- </member>
- <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&amp;&quot;Object&quot;">
- The base type to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE].
- </member>
- <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type">
- The type to be used when [member set_mode] is set to [constant CALL_MODE_BASIC_TYPE].
- </member>
- <member name="index" type="StringName" setter="set_index" getter="get_index">
- The indexed name of the property to retrieve. See [method Object.get_indexed] for details.
- </member>
- <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
- The node path to use when [member set_mode] is set to [constant CALL_MODE_NODE_PATH].
- </member>
- <member name="property" type="StringName" setter="set_property" getter="get_property" default="&amp;&quot;&quot;">
- The name of the property to retrieve. Changing this will clear [member index].
- </member>
- <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertyGet.CallMode" default="0">
- [code]set_mode[/code] determines the target object from which the property will be retrieved. See [enum CallMode] for options.
- </member>
- </members>
- <constants>
- <constant name="CALL_MODE_SELF" value="0" enum="CallMode">
- The property will be retrieved from this [Object].
- </constant>
- <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode">
- The property will be retrieved from the given [Node] in the scene tree.
- </constant>
- <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode">
- The property will be retrieved from an instanced node with the given type and script.
- </constant>
- <constant name="CALL_MODE_BASIC_TYPE" value="3" enum="CallMode">
- The property will be retrieved from a GDScript basic type (e.g. [Vector2]).
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml
deleted file mode 100644
index 6cffa328c7..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml
+++ /dev/null
@@ -1,84 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptPropertySet] can set the value of any property from the current object or other objects.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="assign_op" type="int" setter="set_assign_op" getter="get_assign_op" enum="VisualScriptPropertySet.AssignOp" default="0">
- The additional operation to perform when assigning. See [enum AssignOp] for options.
- </member>
- <member name="base_script" type="String" setter="set_base_script" getter="get_base_script">
- The script to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE].
- </member>
- <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&amp;&quot;Object&quot;">
- The base type to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE].
- </member>
- <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type">
- The type to be used when [member set_mode] is set to [constant CALL_MODE_BASIC_TYPE].
- </member>
- <member name="index" type="StringName" setter="set_index" getter="get_index">
- The indexed name of the property to set. See [method Object.set_indexed] for details.
- </member>
- <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
- The node path to use when [member set_mode] is set to [constant CALL_MODE_NODE_PATH].
- </member>
- <member name="property" type="StringName" setter="set_property" getter="get_property" default="&amp;&quot;&quot;">
- The name of the property to set. Changing this will clear [member index].
- </member>
- <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertySet.CallMode" default="0">
- [code]set_mode[/code] determines the target object on which the property will be set. See [enum CallMode] for options.
- </member>
- </members>
- <constants>
- <constant name="CALL_MODE_SELF" value="0" enum="CallMode">
- The property will be set on this [Object].
- </constant>
- <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode">
- The property will be set on the given [Node] in the scene tree.
- </constant>
- <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode">
- The property will be set on an instanced node with the given type and script.
- </constant>
- <constant name="CALL_MODE_BASIC_TYPE" value="3" enum="CallMode">
- The property will be set on a GDScript basic type (e.g. [Vector2]).
- </constant>
- <constant name="ASSIGN_OP_NONE" value="0" enum="AssignOp">
- The property will be assigned regularly.
- </constant>
- <constant name="ASSIGN_OP_ADD" value="1" enum="AssignOp">
- The value will be added to the property. Equivalent of doing [code]+=[/code].
- </constant>
- <constant name="ASSIGN_OP_SUB" value="2" enum="AssignOp">
- The value will be subtracted from the property. Equivalent of doing [code]-=[/code].
- </constant>
- <constant name="ASSIGN_OP_MUL" value="3" enum="AssignOp">
- The property will be multiplied by the value. Equivalent of doing [code]*=[/code].
- </constant>
- <constant name="ASSIGN_OP_DIV" value="4" enum="AssignOp">
- The property will be divided by the value. Equivalent of doing [code]/=[/code].
- </constant>
- <constant name="ASSIGN_OP_MOD" value="5" enum="AssignOp">
- A modulo operation will be performed on the property and the value. Equivalent of doing [code]%=[/code].
- </constant>
- <constant name="ASSIGN_OP_SHIFT_LEFT" value="6" enum="AssignOp">
- The property will be binarly shifted to the left by the given value. Equivalent of doing [code]&lt;&lt;[/code].
- </constant>
- <constant name="ASSIGN_OP_SHIFT_RIGHT" value="7" enum="AssignOp">
- The property will be binarly shifted to the right by the given value. Equivalent of doing [code]&gt;&gt;[/code].
- </constant>
- <constant name="ASSIGN_OP_BIT_AND" value="8" enum="AssignOp">
- A binary [code]AND[/code] operation will be performed on the property. Equivalent of doing [code]&amp;=[/code].
- </constant>
- <constant name="ASSIGN_OP_BIT_OR" value="9" enum="AssignOp">
- A binary [code]OR[/code] operation will be performed on the property. Equivalent of doing [code]|=[/code].
- </constant>
- <constant name="ASSIGN_OP_BIT_XOR" value="10" enum="AssignOp">
- A binary [code]XOR[/code] operation will be performed on the property. Equivalent of doing [code]^=[/code].
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml b/modules/visual_script/doc_classes/VisualScriptResourcePath.xml
deleted file mode 100644
index 6ca8260ade..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="path" type="String" setter="set_resource_path" getter="get_resource_path" default="&quot;&quot;">
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptReturn.xml b/modules/visual_script/doc_classes/VisualScriptReturn.xml
deleted file mode 100644
index 1d59392782..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptReturn.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Ends the execution of a function and returns control to the calling function. Optionally, it can return a [Variant] value.
- [b]Input Ports:[/b]
- - Sequence
- - Data (variant): [code]result[/code] (optional)
- [b]Output Ports:[/b]
- none
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="return_enabled" type="bool" setter="set_enable_return_value" getter="is_return_value_enabled" default="false">
- If [code]true[/code], the [code]return[/code] input port is available.
- </member>
- <member name="return_type" type="int" setter="set_return_type" getter="get_return_type" enum="Variant.Type" default="0">
- The return value's data type.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml b/modules/visual_script/doc_classes/VisualScriptSceneNode.xml
deleted file mode 100644
index a769d11d94..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A direct reference to a node.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data: [code]node[/code] (obj)
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="node_path" type="NodePath" setter="set_node_path" getter="get_node_path" default="NodePath(&quot;.&quot;)">
- The node's path in the scene tree.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml b/modules/visual_script/doc_classes/VisualScriptSceneTree.xml
deleted file mode 100644
index 84ab90892f..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- A Visual Script node for accessing [SceneTree] methods.
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptSelect.xml b/modules/visual_script/doc_classes/VisualScriptSelect.xml
deleted file mode 100644
index 1aa916f779..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptSelect.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Chooses between two input values based on a Boolean condition.
- [b]Input Ports:[/b]
- - Data (boolean): [code]cond[/code]
- - Data (variant): [code]a[/code]
- - Data (variant): [code]b[/code]
- [b]Output Ports:[/b]
- - Data (variant): [code]out[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type" default="0">
- The input variables' type.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptSelf.xml b/modules/visual_script/doc_classes/VisualScriptSelf.xml
deleted file mode 100644
index 8cc59dbccd..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptSelf.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Provides a reference to the node running the visual script.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data (object): [code]instance[/code]
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptSequence.xml b/modules/visual_script/doc_classes/VisualScriptSequence.xml
deleted file mode 100644
index 9adbc30e0d..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptSequence.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Steps through a series of one or more output Sequence ports. The [code]current[/code] data port outputs the currently executing item.
- [b]Input Ports:[/b]
- - Sequence: [code]in order[/code]
- [b]Output Ports:[/b]
- - Sequence: [code]1[/code]
- - Sequence: [code]2 - n[/code] (optional)
- - Data (int): [code]current[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="steps" type="int" setter="set_steps" getter="get_steps" default="1">
- The number of steps in the sequence.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptSubCall.xml b/modules/visual_script/doc_classes/VisualScriptSubCall.xml
deleted file mode 100644
index 535e89fc82..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptSubCall.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptSubCall] will call method named [code]_subcall[/code] in the current script. It will fail if the method doesn't exist or the provided arguments are wrong.
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptSwitch.xml b/modules/visual_script/doc_classes/VisualScriptSwitch.xml
deleted file mode 100644
index 7befe89f50..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptSwitch.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Branches the flow based on an input's value. Use [b]Case Count[/b] in the Inspector to set the number of branches and each comparison's optional type.
- [b]Input Ports:[/b]
- - Sequence: [code]'input' is[/code]
- - Data (variant): [code]=[/code]
- - Data (variant): [code]=[/code] (optional)
- - Data (variant): [code]input[/code]
- [b]Output Ports:[/b]
- - Sequence
- - Sequence (optional)
- - Sequence: [code]done[/code]
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml
deleted file mode 100644
index ec84a75601..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptTypeCast] will perform a type conversion to an [Object]-derived type.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="base_script" type="String" setter="set_base_script" getter="get_base_script" default="&quot;&quot;">
- The target script class to be converted to. If none, only the [member base_type] will be used.
- </member>
- <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&amp;&quot;Object&quot;">
- The target type to be converted to.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml
deleted file mode 100644
index 8d99b4b9d0..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Returns a variable's value. "Var Name" must be supplied, with an optional type.
- [b]Input Ports:[/b]
- none
- [b]Output Ports:[/b]
- - Data (variant): [code]value[/code]
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="var_name" type="StringName" setter="set_variable" getter="get_variable" default="&amp;&quot;&quot;">
- The variable's name.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml
deleted file mode 100644
index 4f568cc0f6..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Changes a variable's value to the given input.
- [b]Input Ports:[/b]
- - Sequence
- - Data (variant): [code]set[/code]
- [b]Output Ports:[/b]
- - Sequence
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="var_name" type="StringName" setter="set_variable" getter="get_variable" default="&amp;&quot;&quot;">
- The variable's name.
- </member>
- </members>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptWhile.xml b/modules/visual_script/doc_classes/VisualScriptWhile.xml
deleted file mode 100644
index 4e7cccef17..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptWhile.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- Loops while a condition is [code]true[/code]. Execution continues out the [code]exit[/code] Sequence port when the loop terminates.
- [b]Input Ports:[/b]
- - Sequence: [code]while(cond)[/code]
- - Data (bool): [code]cond[/code]
- [b]Output Ports:[/b]
- - Sequence: [code]repeat[/code]
- - Sequence: [code]exit[/code]
- </description>
- <tutorials>
- </tutorials>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptYield.xml b/modules/visual_script/doc_classes/VisualScriptYield.xml
deleted file mode 100644
index ec757a3ac4..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptYield.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptYield] will pause the function call and return [VisualScriptFunctionState], which can be used to resume the function.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="mode" type="int" setter="set_yield_mode" getter="get_yield_mode" enum="VisualScriptYield.YieldMode" default="1">
- The mode to use for yielding. See [enum YieldMode] for available options.
- </member>
- <member name="wait_time" type="float" setter="set_wait_time" getter="get_wait_time">
- The time to wait when [member mode] is set to [constant YIELD_WAIT].
- </member>
- </members>
- <constants>
- <constant name="YIELD_FRAME" value="1" enum="YieldMode">
- Yields during an idle frame.
- </constant>
- <constant name="YIELD_PHYSICS_FRAME" value="2" enum="YieldMode">
- Yields during a physics frame.
- </constant>
- <constant name="YIELD_WAIT" value="3" enum="YieldMode">
- Yields a function and waits the given time.
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml
deleted file mode 100644
index c3f4bc49c5..0000000000
--- a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<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>
- <description>
- [VisualScriptYieldSignal] will pause the function execution until the provided signal is emitted.
- </description>
- <tutorials>
- </tutorials>
- <members>
- <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&amp;&quot;Object&quot;">
- The base type to be used when [member call_mode] is set to [constant CALL_MODE_INSTANCE].
- </member>
- <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptYieldSignal.CallMode" default="0">
- [code]call_mode[/code] determines the target object to wait for the signal emission. See [enum CallMode] for options.
- </member>
- <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
- The node path to use when [member call_mode] is set to [constant CALL_MODE_NODE_PATH].
- </member>
- <member name="signal" type="StringName" setter="set_signal" getter="get_signal" default="&amp;&quot;&quot;">
- The signal name to be waited for.
- </member>
- </members>
- <constants>
- <constant name="CALL_MODE_SELF" value="0" enum="CallMode">
- A signal from this [Object] will be used.
- </constant>
- <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode">
- A signal from the given [Node] in the scene tree will be used.
- </constant>
- <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode">
- A signal from an instanced node with the given type will be used.
- </constant>
- </constants>
-</class>
diff --git a/modules/visual_script/editor/visual_script_editor.cpp b/modules/visual_script/editor/visual_script_editor.cpp
deleted file mode 100644
index 7f8e9d8254..0000000000
--- a/modules/visual_script/editor/visual_script_editor.cpp
+++ /dev/null
@@ -1,4979 +0,0 @@
-/*************************************************************************/
-/* visual_script_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. */
-/*************************************************************************/
-
-#include "visual_script_editor.h"
-
-#include "../visual_script_expression.h"
-#include "../visual_script_flow_control.h"
-#include "../visual_script_func_nodes.h"
-#include "../visual_script_nodes.h"
-#include "core/input/input.h"
-#include "core/object/class_db.h"
-#include "core/object/script_language.h"
-#include "core/os/keyboard.h"
-#include "core/variant/variant.h"
-#include "editor/editor_node.h"
-#include "editor/editor_resource_preview.h"
-#include "editor/editor_scale.h"
-#include "editor/editor_settings.h"
-#include "scene/gui/check_button.h"
-#include "scene/gui/graph_edit.h"
-#include "scene/gui/separator.h"
-#include "scene/gui/view_panner.h"
-#include "scene/main/window.h"
-
-#ifdef TOOLS_ENABLED
-
-void VisualScriptEditedProperty::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_edited_property", "value"), &VisualScriptEditedProperty::set_edited_property);
- ClassDB::bind_method(D_METHOD("get_edited_property"), &VisualScriptEditedProperty::get_edited_property);
-
- ADD_PROPERTY(PropertyInfo(Variant::NIL, "edited_property", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NIL_IS_VARIANT), "set_edited_property", "get_edited_property");
-}
-
-void VisualScriptEditedProperty::set_edited_property(Variant p_variant) {
- edited_property = p_variant;
-}
-
-Variant VisualScriptEditedProperty::get_edited_property() const {
- return edited_property;
-}
-
-/////////////////
-
-class VisualScriptEditorSignalEdit : public Object {
- GDCLASS(VisualScriptEditorSignalEdit, Object);
-
- StringName sig;
-
-public:
- UndoRedo *undo_redo;
- Ref<VisualScript> script;
-
-protected:
- static void _bind_methods() {
- ClassDB::bind_method("_sig_changed", &VisualScriptEditorSignalEdit::_sig_changed);
- ADD_SIGNAL(MethodInfo("changed"));
- }
-
- void _sig_changed() {
- notify_property_list_changed();
- emit_signal(SNAME("changed"));
- }
-
- bool _set(const StringName &p_name, const Variant &p_value) {
- if (sig == StringName()) {
- return false;
- }
-
- if (p_name == "argument_count") {
- int new_argc = p_value;
- int argc = script->custom_signal_get_argument_count(sig);
- if (argc == new_argc) {
- return true;
- }
-
- undo_redo->create_action(TTR("Change Signal Arguments"));
-
- if (new_argc < argc) {
- for (int i = new_argc; i < argc; i++) {
- undo_redo->add_do_method(script.ptr(), "custom_signal_remove_argument", sig, new_argc);
- undo_redo->add_undo_method(script.ptr(), "custom_signal_add_argument", sig, script->custom_signal_get_argument_name(sig, i), script->custom_signal_get_argument_type(sig, i), -1);
- }
- } else if (new_argc > argc) {
- for (int i = argc; i < new_argc; i++) {
- undo_redo->add_do_method(script.ptr(), "custom_signal_add_argument", sig, Variant::NIL, "arg" + itos(i + 1), -1);
- undo_redo->add_undo_method(script.ptr(), "custom_signal_remove_argument", sig, argc);
- }
- }
-
- undo_redo->add_do_method(this, "_sig_changed");
- undo_redo->add_undo_method(this, "_sig_changed");
-
- undo_redo->commit_action();
-
- return true;
- }
- if (String(p_name).begins_with("argument/")) {
- int idx = String(p_name).get_slice("/", 1).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, script->custom_signal_get_argument_count(sig), false);
- String what = String(p_name).get_slice("/", 2);
- if (what == "type") {
- int old_type = script->custom_signal_get_argument_type(sig, idx);
- int new_type = p_value;
- undo_redo->create_action(TTR("Change Argument Type"));
- undo_redo->add_do_method(script.ptr(), "custom_signal_set_argument_type", sig, idx, new_type);
- undo_redo->add_undo_method(script.ptr(), "custom_signal_set_argument_type", sig, idx, old_type);
- undo_redo->commit_action();
-
- return true;
- }
-
- if (what == "name") {
- String old_name = script->custom_signal_get_argument_name(sig, idx);
- String new_name = p_value;
- undo_redo->create_action(TTR("Change Argument name"));
- undo_redo->add_do_method(script.ptr(), "custom_signal_set_argument_name", sig, idx, new_name);
- undo_redo->add_undo_method(script.ptr(), "custom_signal_set_argument_name", sig, idx, old_name);
- undo_redo->commit_action();
- return true;
- }
- }
-
- return false;
- }
-
- bool _get(const StringName &p_name, Variant &r_ret) const {
- if (sig == StringName()) {
- return false;
- }
-
- if (p_name == "argument_count") {
- r_ret = script->custom_signal_get_argument_count(sig);
- return true;
- }
- if (String(p_name).begins_with("argument/")) {
- int idx = String(p_name).get_slice("/", 1).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, script->custom_signal_get_argument_count(sig), false);
- String what = String(p_name).get_slice("/", 2);
- if (what == "type") {
- r_ret = script->custom_signal_get_argument_type(sig, idx);
- return true;
- }
- if (what == "name") {
- r_ret = script->custom_signal_get_argument_name(sig, idx);
- return true;
- }
- }
-
- return false;
- }
- void _get_property_list(List<PropertyInfo> *p_list) const {
- if (sig == StringName()) {
- return;
- }
-
- p_list->push_back(PropertyInfo(Variant::INT, "argument_count", PROPERTY_HINT_RANGE, "0,256"));
- String argt = "Variant";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- for (int i = 0; i < script->custom_signal_get_argument_count(sig); i++) {
- p_list->push_back(PropertyInfo(Variant::INT, "argument/" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt));
- p_list->push_back(PropertyInfo(Variant::STRING, "argument/" + itos(i + 1) + "/name"));
- }
- }
-
-public:
- void edit(const StringName &p_sig) {
- sig = p_sig;
- notify_property_list_changed();
- }
-
- VisualScriptEditorSignalEdit() { undo_redo = nullptr; }
-};
-
-class VisualScriptEditorVariableEdit : public Object {
- GDCLASS(VisualScriptEditorVariableEdit, Object);
-
- StringName var;
-
-public:
- UndoRedo *undo_redo;
- Ref<VisualScript> script;
-
-protected:
- static void _bind_methods() {
- ClassDB::bind_method("_var_changed", &VisualScriptEditorVariableEdit::_var_changed);
- ClassDB::bind_method("_var_value_changed", &VisualScriptEditorVariableEdit::_var_value_changed);
- ADD_SIGNAL(MethodInfo("changed"));
- }
-
- void _var_changed() {
- notify_property_list_changed();
- emit_signal(SNAME("changed"));
- }
- void _var_value_changed() {
- emit_signal(SNAME("changed"));
- }
-
- bool _set(const StringName &p_name, const Variant &p_value) {
- if (var == StringName()) {
- return false;
- }
-
- if (String(p_name) == "value") {
- undo_redo->create_action(TTR("Set Variable Default Value"));
- Variant current = script->get_variable_default_value(var);
- undo_redo->add_do_method(script.ptr(), "set_variable_default_value", var, p_value);
- undo_redo->add_undo_method(script.ptr(), "set_variable_default_value", var, current);
- undo_redo->add_do_method(this, "_var_value_changed");
- undo_redo->add_undo_method(this, "_var_value_changed");
- undo_redo->commit_action();
- return true;
- }
-
- Dictionary d = script->call("get_variable_info", var);
-
- if (String(p_name) == "type") {
- Dictionary dc = d.duplicate();
- dc["type"] = p_value;
- undo_redo->create_action(TTR("Set Variable Type"));
- undo_redo->add_do_method(script.ptr(), "set_variable_info", var, dc);
- undo_redo->add_undo_method(script.ptr(), "set_variable_info", var, d);
-
- // Setting the default value.
- Variant::Type type = (Variant::Type)(int)p_value;
- if (type != Variant::NIL) {
- Variant default_value;
- Callable::CallError ce;
- Variant::construct(type, default_value, nullptr, 0, ce);
- if (ce.error == Callable::CallError::CALL_OK) {
- undo_redo->add_do_method(script.ptr(), "set_variable_default_value", var, default_value);
- undo_redo->add_undo_method(script.ptr(), "set_variable_default_value", var, dc["value"]);
- }
- }
-
- undo_redo->add_do_method(this, "_var_changed");
- undo_redo->add_undo_method(this, "_var_changed");
- undo_redo->commit_action();
- return true;
- }
-
- if (String(p_name) == "hint") {
- Dictionary dc = d.duplicate();
- dc["hint"] = p_value;
- undo_redo->create_action(TTR("Set Variable Type"));
- undo_redo->add_do_method(script.ptr(), "set_variable_info", var, dc);
- undo_redo->add_undo_method(script.ptr(), "set_variable_info", var, d);
- undo_redo->add_do_method(this, "_var_changed");
- undo_redo->add_undo_method(this, "_var_changed");
- undo_redo->commit_action();
- return true;
- }
-
- if (String(p_name) == "hint_string") {
- Dictionary dc = d.duplicate();
- dc["hint_string"] = p_value;
- undo_redo->create_action(TTR("Set Variable Type"));
- undo_redo->add_do_method(script.ptr(), "set_variable_info", var, dc);
- undo_redo->add_undo_method(script.ptr(), "set_variable_info", var, d);
- undo_redo->add_do_method(this, "_var_changed");
- undo_redo->add_undo_method(this, "_var_changed");
- undo_redo->commit_action();
- return true;
- }
-
- if (String(p_name) == "export") {
- script->set_variable_export(var, p_value);
- InspectorDock::get_inspector_singleton()->update_tree();
- return true;
- }
-
- return false;
- }
-
- bool _get(const StringName &p_name, Variant &r_ret) const {
- if (var == StringName()) {
- return false;
- }
-
- if (String(p_name) == "value") {
- r_ret = script->get_variable_default_value(var);
- return true;
- }
-
- PropertyInfo pinfo = script->get_variable_info(var);
-
- if (String(p_name) == "type") {
- r_ret = pinfo.type;
- return true;
- }
- if (String(p_name) == "hint") {
- r_ret = pinfo.hint;
- return true;
- }
- if (String(p_name) == "hint_string") {
- r_ret = pinfo.hint_string;
- return true;
- }
-
- if (String(p_name) == "export") {
- r_ret = script->get_variable_export(var);
- return true;
- }
-
- return false;
- }
- void _get_property_list(List<PropertyInfo> *p_list) const {
- if (var == StringName()) {
- return;
- }
-
- String argt = "Variant";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
- p_list->push_back(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt));
- p_list->push_back(PropertyInfo(script->get_variable_info(var).type, "value", script->get_variable_info(var).hint, script->get_variable_info(var).hint_string, PROPERTY_USAGE_DEFAULT));
- // Update this when PropertyHint changes.
- p_list->push_back(PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_ENUM, "None,Range,ExpRange,Enum,ExpEasing,Length,SpriteFrame,KeyAccel,Flags,Layers2dRender,Layers2dPhysics,Layer3dRender,Layer3dPhysics,File,Dir,GlobalFile,GlobalDir,ResourceType,MultilineText,PlaceholderText,ColorNoAlpha,ImageCompressLossy,ImageCompressLossLess,ObjectId,String,NodePathToEditedNode,MethodOfVariantType,MethodOfBaseType,MethodOfInstance,MethodOfScript,PropertyOfVariantType,PropertyOfBaseType,PropertyOfInstance,PropertyOfScript,ObjectTooBig,NodePathValidTypes"));
- p_list->push_back(PropertyInfo(Variant::STRING, "hint_string"));
- p_list->push_back(PropertyInfo(Variant::BOOL, "export"));
- }
-
-public:
- void edit(const StringName &p_var) {
- var = p_var;
- notify_property_list_changed();
- }
-
- VisualScriptEditorVariableEdit() { undo_redo = nullptr; }
-};
-
-static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) {
- Color color;
- if (dark_theme) {
- switch (p_type) {
- case Variant::NIL:
- color = Color(0.41, 0.93, 0.74);
- break;
-
- case Variant::BOOL:
- color = Color(0.55, 0.65, 0.94);
- break;
- case Variant::INT:
- color = Color(0.49, 0.78, 0.94);
- break;
- case Variant::FLOAT:
- color = Color(0.38, 0.85, 0.96);
- break;
- case Variant::STRING:
- color = Color(0.42, 0.65, 0.93);
- break;
-
- case Variant::VECTOR2:
- color = Color(0.74, 0.57, 0.95);
- break;
- case Variant::VECTOR2I:
- color = Color(0.74, 0.57, 0.95);
- break;
- case Variant::RECT2:
- color = Color(0.95, 0.57, 0.65);
- break;
- case Variant::RECT2I:
- color = Color(0.95, 0.57, 0.65);
- break;
- case Variant::VECTOR3:
- color = Color(0.84, 0.49, 0.93);
- break;
- case Variant::VECTOR3I:
- color = Color(0.84, 0.49, 0.93);
- break;
- case Variant::VECTOR4:
- color = Color(0.84, 0.49, 0.94);
- break;
- case Variant::VECTOR4I:
- color = Color(0.84, 0.49, 0.94);
- break;
- case Variant::TRANSFORM2D:
- color = Color(0.77, 0.93, 0.41);
- break;
- case Variant::PLANE:
- color = Color(0.97, 0.44, 0.44);
- break;
- case Variant::QUATERNION:
- color = Color(0.93, 0.41, 0.64);
- break;
- case Variant::AABB:
- color = Color(0.93, 0.47, 0.57);
- break;
- case Variant::BASIS:
- color = Color(0.89, 0.93, 0.41);
- break;
- case Variant::TRANSFORM3D:
- color = Color(0.96, 0.66, 0.43);
- break;
-
- case Variant::COLOR:
- color = Color(0.62, 1.0, 0.44);
- break;
- case Variant::NODE_PATH:
- color = Color(0.41, 0.58, 0.93);
- break;
- case Variant::RID:
- color = Color(0.41, 0.93, 0.6);
- break;
- case Variant::OBJECT:
- color = Color(0.47, 0.95, 0.91);
- break;
- case Variant::DICTIONARY:
- color = Color(0.47, 0.93, 0.69);
- break;
-
- case Variant::ARRAY:
- color = Color(0.88, 0.88, 0.88);
- break;
- case Variant::PACKED_BYTE_ARRAY:
- color = Color(0.67, 0.96, 0.78);
- break;
- case Variant::PACKED_INT32_ARRAY:
- color = Color(0.69, 0.86, 0.96);
- break;
- case Variant::PACKED_FLOAT32_ARRAY:
- color = Color(0.59, 0.91, 0.97);
- break;
- case Variant::PACKED_INT64_ARRAY:
- color = Color(0.69, 0.86, 0.96);
- break;
- case Variant::PACKED_FLOAT64_ARRAY:
- color = Color(0.59, 0.91, 0.97);
- break;
- case Variant::PACKED_STRING_ARRAY:
- color = Color(0.62, 0.77, 0.95);
- break;
- case Variant::PACKED_VECTOR2_ARRAY:
- color = Color(0.82, 0.7, 0.96);
- break;
- case Variant::PACKED_VECTOR3_ARRAY:
- color = Color(0.87, 0.61, 0.95);
- break;
- case Variant::PACKED_COLOR_ARRAY:
- color = Color(0.91, 1.0, 0.59);
- break;
-
- default:
- color.set_hsv(p_type / float(Variant::VARIANT_MAX), 0.7, 0.7);
- }
- } else {
- switch (p_type) {
- case Variant::NIL:
- color = Color(0.15, 0.89, 0.63);
- break;
-
- case Variant::BOOL:
- color = Color(0.43, 0.56, 0.92);
- break;
- case Variant::INT:
- color = Color(0.31, 0.7, 0.91);
- break;
- case Variant::FLOAT:
- color = Color(0.15, 0.8, 0.94);
- break;
- case Variant::STRING:
- color = Color(0.27, 0.56, 0.91);
- break;
-
- case Variant::VECTOR2:
- color = Color(0.68, 0.46, 0.93);
- break;
- case Variant::VECTOR2I:
- color = Color(0.68, 0.46, 0.93);
- break;
- case Variant::RECT2:
- color = Color(0.93, 0.46, 0.56);
- break;
- case Variant::RECT2I:
- color = Color(0.93, 0.46, 0.56);
- break;
- case Variant::VECTOR3:
- color = Color(0.86, 0.42, 0.93);
- break;
- case Variant::VECTOR3I:
- color = Color(0.86, 0.42, 0.93);
- break;
- case Variant::TRANSFORM2D:
- color = Color(0.59, 0.81, 0.1);
- break;
- case Variant::PLANE:
- color = Color(0.97, 0.44, 0.44);
- break;
- case Variant::QUATERNION:
- color = Color(0.93, 0.41, 0.64);
- break;
- case Variant::AABB:
- color = Color(0.93, 0.47, 0.57);
- break;
- case Variant::BASIS:
- color = Color(0.7, 0.73, 0.1);
- break;
- case Variant::TRANSFORM3D:
- color = Color(0.96, 0.56, 0.28);
- break;
-
- case Variant::COLOR:
- color = Color(0.24, 0.75, 0.0);
- break;
- case Variant::NODE_PATH:
- color = Color(0.41, 0.58, 0.93);
- break;
- case Variant::RID:
- color = Color(0.17, 0.9, 0.45);
- break;
- case Variant::OBJECT:
- color = Color(0.07, 0.84, 0.76);
- break;
- case Variant::DICTIONARY:
- color = Color(0.34, 0.91, 0.62);
- break;
-
- case Variant::ARRAY:
- color = Color(0.45, 0.45, 0.45);
- break;
- case Variant::PACKED_BYTE_ARRAY:
- color = Color(0.38, 0.92, 0.6);
- break;
- case Variant::PACKED_INT32_ARRAY:
- color = Color(0.38, 0.73, 0.92);
- break;
- case Variant::PACKED_FLOAT32_ARRAY:
- color = Color(0.25, 0.83, 0.95);
- break;
- case Variant::PACKED_INT64_ARRAY:
- color = Color(0.38, 0.73, 0.92);
- break;
- case Variant::PACKED_FLOAT64_ARRAY:
- color = Color(0.25, 0.83, 0.95);
- break;
- case Variant::PACKED_STRING_ARRAY:
- color = Color(0.38, 0.62, 0.92);
- break;
- case Variant::PACKED_VECTOR2_ARRAY:
- color = Color(0.62, 0.36, 0.92);
- break;
- case Variant::PACKED_VECTOR3_ARRAY:
- color = Color(0.79, 0.35, 0.92);
- break;
- case Variant::PACKED_COLOR_ARRAY:
- color = Color(0.57, 0.73, 0.0);
- break;
-
- default:
- color.set_hsv(p_type / float(Variant::VARIANT_MAX), 0.3, 0.3);
- }
- }
-
- return color;
-}
-
-void VisualScriptEditor::_update_graph_connections() {
- graph->clear_connections();
-
- List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(&sequence_conns);
-
- for (const VisualScript::SequenceConnection &E : sequence_conns) {
- graph->connect_node(itos(E.from_node), E.from_output, itos(E.to_node), 0);
- }
-
- List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(&data_conns);
-
- for (VisualScript::DataConnection &dc : data_conns) {
- Ref<VisualScriptNode> from_node = script->get_node(dc.from_node);
- Ref<VisualScriptNode> to_node = script->get_node(dc.to_node);
-
- if (to_node->has_input_sequence_port()) {
- dc.to_port++;
- }
-
- dc.from_port += from_node->get_output_sequence_port_count();
-
- graph->connect_node(itos(dc.from_node), dc.from_port, itos(dc.to_node), dc.to_port);
- }
-}
-
-void VisualScriptEditor::_update_graph(int p_only_id) {
- if (updating_graph) {
- return;
- }
-
- updating_graph = true;
-
- //byebye all nodes
- if (p_only_id >= 0) {
- if (graph->has_node(itos(p_only_id))) {
- Node *gid = graph->get_node(itos(p_only_id));
- if (gid) {
- memdelete(gid);
- }
- }
- } else {
- for (int i = 0; i < graph->get_child_count(); i++) {
- if (Object::cast_to<GraphNode>(graph->get_child(i))) {
- memdelete(graph->get_child(i));
- i--;
- }
- }
- }
- graph->show();
- select_func_text->hide();
-
- Ref<Texture2D> type_icons[Variant::VARIANT_MAX] = {
- Control::get_theme_icon(SNAME("Variant"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("bool"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("int"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("float"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("String"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector2"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector2i"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Rect2"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Rect2i"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector3"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector3i"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Transform2D"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Plane"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Quaternion"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("AABB"), SNAME("EditorIcons")),
- 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")),
- Control::get_theme_icon(SNAME("Callable"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Signal"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Dictionary"), SNAME("EditorIcons")),
- 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")),
- Control::get_theme_icon(SNAME("PackedColorArray"), SNAME("EditorIcons"))
- };
-
- // Visual script specific theme for MSDF font.
- Ref<Theme> vstheme;
- vstheme.instantiate();
- Ref<Font> label_font = EditorNode::get_singleton()->get_editor_theme()->get_font("main_msdf", "EditorFonts");
- vstheme->set_font("font", "Label", label_font);
- vstheme->set_font("font", "LineEdit", label_font);
- vstheme->set_font("font", "Button", label_font);
-
- Ref<Texture2D> seq_port = Control::get_theme_icon(SNAME("VisualShaderPort"), SNAME("EditorIcons"));
- List<int> node_ids;
- script->get_node_list(&node_ids);
-
- List<int> ids;
- script->get_node_list(&ids);
-
- for (int &E : ids) {
- if (p_only_id >= 0 && p_only_id != E) {
- continue;
- }
-
- Ref<VisualScriptNode> node = script->get_node(E);
- Vector2 pos = script->get_node_position(E);
-
- GraphNode *gnode = memnew(GraphNode);
- gnode->set_title(node->get_caption());
- gnode->set_position_offset(pos * EDSCALE);
- if (error_line == E) {
- gnode->set_overlay(GraphNode::OVERLAY_POSITION);
- } else if (node->is_breakpoint()) {
- gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT);
- }
-
- gnode->set_meta("__vnode", node);
- gnode->set_name(itos(E));
- gnode->connect("dragged", callable_mp(this, &VisualScriptEditor::_node_moved).bind(E));
- gnode->connect("close_request", callable_mp(this, &VisualScriptEditor::_remove_node).bind(E), CONNECT_DEFERRED);
-
- {
- Ref<VisualScriptFunction> v = node;
- if (!v.is_valid()) {
- gnode->set_show_close_button(true);
- }
- }
-
- bool has_gnode_text = false;
-
- Ref<VisualScriptLists> nd_list = node;
- bool is_vslist = nd_list.is_valid();
- if (is_vslist) {
- HBoxContainer *hbnc = memnew(HBoxContainer);
- if (nd_list->is_input_port_editable()) {
- has_gnode_text = true;
- Button *btn = memnew(Button);
- btn->set_text(TTR("Add Input Port"));
- hbnc->add_child(btn);
- btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_input_port).bind(E), CONNECT_DEFERRED);
- }
- if (nd_list->is_output_port_editable()) {
- if (nd_list->is_input_port_editable()) {
- hbnc->add_spacer();
- }
- has_gnode_text = true;
- Button *btn = memnew(Button);
- btn->set_text(TTR("Add Output Port"));
- hbnc->add_child(btn);
- btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_output_port).bind(E), CONNECT_DEFERRED);
- }
- gnode->add_child(hbnc);
- } else if (Object::cast_to<VisualScriptExpression>(node.ptr())) {
- has_gnode_text = true;
- LineEdit *line_edit = memnew(LineEdit);
- line_edit->set_text(node->get_text());
- line_edit->set_expand_to_text_length_enabled(true);
- line_edit->add_theme_font_override("font", get_theme_font(SNAME("source"), SNAME("EditorFonts")));
- gnode->add_child(line_edit);
- line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed).bind(E));
- } else {
- String text = node->get_text();
- if (!text.is_empty()) {
- has_gnode_text = true;
- Label *label = memnew(Label);
- label->set_text(text);
- gnode->add_child(label);
- }
- }
-
- if (Object::cast_to<VisualScriptComment>(node.ptr())) {
- Ref<VisualScriptComment> vsc = node;
- gnode->set_comment(true);
- gnode->set_resizable(true);
- gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE);
- gnode->connect("resize_request", callable_mp(this, &VisualScriptEditor::_comment_node_resized).bind(E));
- }
-
- if (node_styles.has(node->get_category())) {
- Ref<StyleBoxFlat> sbf = node_styles[node->get_category()];
- if (gnode->is_comment()) {
- sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox(SNAME("comment"), SNAME("GraphNode"));
- }
-
- Color c = sbf->get_border_color();
- c = ((c.r + c.g + c.b) / 3) < 0.7 ? Color(1.0, 1.0, 1.0, 0.85) : Color(0.0, 0.0, 0.0, 0.85);
- Color ic = c;
- gnode->add_theme_color_override("title_color", c);
- c.a = 1;
- gnode->add_theme_color_override("close_color", c);
- gnode->add_theme_color_override("resizer_color", ic);
- gnode->add_theme_style_override("frame", sbf);
- }
-
- const Color mono_color = get_theme_color(SNAME("mono_color"), SNAME("Editor"));
-
- int slot_idx = 0;
-
- bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String();
- if ((node->has_input_sequence_port() || single_seq_output) || has_gnode_text) {
- // IF has_gnode_text is true BUT we have no sequence ports to draw (in here),
- // we still draw the disabled default ones to shift up the slots by one,
- // so the slots DON'T start with the content text.
-
- // IF has_gnode_text is false, but we DO want to draw default sequence ports,
- // we draw a dummy text to take up the position of the sequence nodes, so all the other ports are still aligned correctly.
- if (!has_gnode_text) {
- Label *dummy = memnew(Label);
- dummy->set_text(" ");
- gnode->add_child(dummy);
- }
- gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, mono_color, single_seq_output, TYPE_SEQUENCE, mono_color, seq_port, seq_port);
- slot_idx++;
- }
-
- int mixed_seq_ports = 0;
-
- if (!single_seq_output) {
- if (node->has_mixed_input_and_sequence_ports()) {
- mixed_seq_ports = node->get_output_sequence_port_count();
- } else {
- for (int i = 0; i < node->get_output_sequence_port_count(); i++) {
- Label *text2 = memnew(Label);
- text2->set_text(node->get_output_sequence_port_text(i));
- text2->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);
- gnode->add_child(text2);
- gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, mono_color, seq_port, seq_port);
- slot_idx++;
- }
- }
- }
-
- for (int i = 0; i < MAX(node->get_output_value_port_count(), MAX(mixed_seq_ports, node->get_input_value_port_count())); i++) {
- bool left_ok = false;
- Variant::Type left_type = Variant::NIL;
- String left_name;
-
- if (i < node->get_input_value_port_count()) {
- PropertyInfo pi = node->get_input_value_port_info(i);
- left_ok = true;
- left_type = pi.type;
- left_name = pi.name;
- }
-
- bool right_ok = false;
- Variant::Type right_type = Variant::NIL;
- String right_name;
-
- if (i >= mixed_seq_ports && i < node->get_output_value_port_count() + mixed_seq_ports) {
- PropertyInfo pi = node->get_output_value_port_info(i - mixed_seq_ports);
- right_ok = true;
- right_type = pi.type;
- right_name = pi.name;
- }
- VBoxContainer *vbc = memnew(VBoxContainer);
- HBoxContainer *hbc = memnew(HBoxContainer);
- HBoxContainer *hbc2 = memnew(HBoxContainer);
- vbc->add_child(hbc);
- vbc->add_child(hbc2);
- if (left_ok) {
- Ref<Texture2D> t;
- if (left_type >= 0 && left_type < Variant::VARIANT_MAX) {
- t = type_icons[left_type];
- }
- if (t.is_valid()) {
- TextureRect *tf = memnew(TextureRect);
- tf->set_texture(t);
- tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
- hbc->add_child(tf);
- }
-
- if (is_vslist) {
- if (nd_list->is_input_port_name_editable()) {
- LineEdit *name_box = memnew(LineEdit);
- hbc->add_child(name_box);
- name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0));
- name_box->set_text(left_name);
- name_box->set_expand_to_text_length_enabled(true);
- name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size).bind(E));
- name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out).bind(name_box, E, i, true));
- } else {
- hbc->add_child(memnew(Label(left_name)));
- }
-
- if (nd_list->is_input_port_type_editable()) {
- OptionButton *opbtn = memnew(OptionButton);
- for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) {
- opbtn->add_item(Variant::get_type_name(Variant::Type(j)));
- }
- opbtn->select(left_type);
- opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
- hbc->add_child(opbtn);
- opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type).bind(E, i, true), CONNECT_DEFERRED);
- }
-
- Button *rmbtn = memnew(Button);
- rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
- hbc->add_child(rmbtn);
- rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_input_port).bind(E, i), CONNECT_DEFERRED);
- } else {
- hbc->add_child(memnew(Label(left_name)));
- }
-
- if (left_type != Variant::NIL && !script->is_input_value_port_connected(E, i)) {
- PropertyInfo pi = node->get_input_value_port_info(i);
- Button *button = memnew(Button);
- Variant value = node->get_default_input_value(i);
- if (value.get_type() != left_type) {
- //different type? for now convert
- //not the same, reconvert
- Callable::CallError ce;
- const Variant *existingp = &value;
- Variant::construct(left_type, value, &existingp, 1, ce);
- }
-
- if (left_type == Variant::COLOR) {
- button->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
- button->connect("draw", callable_mp(this, &VisualScriptEditor::_draw_color_over_button).bind(button, value));
- } else if (left_type == Variant::OBJECT && Ref<Resource>(value).is_valid()) {
- Ref<Resource> res = value;
- Array arr;
- arr.push_back(button->get_instance_id());
- arr.push_back(String(value));
- EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr);
-
- } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) {
- bool found = false;
- const Vector<String> options = pi.hint_string.split(",");
- int64_t current_val = 0;
- for (const String &option : options) {
- Vector<String> text_split = option.split(":");
- if (text_split.size() != 1) {
- current_val = text_split[1].to_int();
- }
- if (value.operator int() == current_val) {
- button->set_text(text_split[0]);
- found = true;
- break;
- }
- current_val += 1;
- }
- if (!found) {
- button->set_text(value);
- }
- } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_FLAGS) {
- Vector<String> value_texts;
- const Vector<String> options = pi.hint_string.split(",");
- uint32_t v = value;
- for (const String &option : options) {
- uint32_t current_val;
- Vector<String> text_split = option.split(":");
- if (text_split.size() != -1) {
- current_val = text_split[1].to_int();
- } else {
- current_val = 1 << i;
- }
- if ((v & current_val) == current_val) {
- value_texts.push_back(text_split[0]);
- }
- }
- if (value_texts.size() != 0) {
- String value_text = value_texts[0];
- for (const String &text : value_texts) {
- value_text += " | " + text;
- }
- button->set_text(value_text);
- } else {
- button->set_text(value);
- }
- } else {
- button->set_text(value);
- }
- button->connect("pressed", callable_mp(this, &VisualScriptEditor::_default_value_edited).bind(button, E, i));
- hbc2->add_child(button);
- }
- } else {
- Control *c = memnew(Control);
- c->set_custom_minimum_size(Size2(10, 0) * EDSCALE);
- hbc->add_child(c);
- }
-
- hbc->add_spacer();
- hbc2->add_spacer();
-
- if (i < mixed_seq_ports) {
- Label *text2 = memnew(Label);
- text2->set_text(node->get_output_sequence_port_text(i));
- text2->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);
- hbc->add_child(text2);
- }
-
- if (right_ok) {
- if (is_vslist) {
- Button *rmbtn = memnew(Button);
- rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
- hbc->add_child(rmbtn);
- rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_output_port).bind(E, i), CONNECT_DEFERRED);
-
- if (nd_list->is_output_port_type_editable()) {
- OptionButton *opbtn = memnew(OptionButton);
- for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) {
- opbtn->add_item(Variant::get_type_name(Variant::Type(j)));
- }
- opbtn->select(right_type);
- opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
- hbc->add_child(opbtn);
- opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type).bind(E, i, false), CONNECT_DEFERRED);
- }
-
- if (nd_list->is_output_port_name_editable()) {
- LineEdit *name_box = memnew(LineEdit);
- hbc->add_child(name_box);
- name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0));
- name_box->set_text(right_name);
- name_box->set_expand_to_text_length_enabled(true);
- name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size).bind(E));
- name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out).bind(name_box, E, i, false));
- } else {
- hbc->add_child(memnew(Label(right_name)));
- }
- } else {
- hbc->add_child(memnew(Label(right_name)));
- }
-
- Ref<Texture2D> t;
- if (right_type >= 0 && right_type < Variant::VARIANT_MAX) {
- t = type_icons[right_type];
- }
- if (t.is_valid()) {
- TextureRect *tf = memnew(TextureRect);
- tf->set_texture(t);
- tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
- hbc->add_child(tf);
- }
- }
-
- gnode->add_child(vbc);
-
- bool dark_theme = get_theme_constant(SNAME("dark_theme"), SNAME("Editor"));
- if (i < mixed_seq_ports) {
- gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture2D>(), seq_port);
- } else {
- gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), right_ok, right_type, _color_from_type(right_type, dark_theme));
- }
-
- slot_idx++;
- }
- graph->add_child(gnode);
- gnode->set_theme(vstheme);
- if (gnode->is_comment()) {
- graph->move_child(gnode, 0);
- }
- }
-
- _update_graph_connections();
-
- float graph_minimap_opacity = EditorSettings::get_singleton()->get("editors/visual_editors/minimap_opacity");
- graph->set_minimap_opacity(graph_minimap_opacity);
-
- float graph_lines_curvature = EditorSettings::get_singleton()->get("editors/visual_editors/lines_curvature");
- graph->set_connection_lines_curvature(graph_lines_curvature);
-
- // Use default_func instead of default_func for now I think that should be good stop gap solution to ensure not breaking anything.
- graph->call_deferred(SNAME("set_scroll_ofs"), script->get_scroll() * EDSCALE);
- updating_graph = false;
-}
-
-void VisualScriptEditor::_change_port_type(int p_select, int p_id, int p_port, bool is_input) {
- Ref<VisualScriptLists> vsn = script->get_node(p_id);
- if (!vsn.is_valid()) {
- return;
- }
-
- undo_redo->create_action(TTR("Change Port Type"));
- if (is_input) {
- undo_redo->add_do_method(vsn.ptr(), "set_input_data_port_type", p_port, Variant::Type(p_select));
- undo_redo->add_undo_method(vsn.ptr(), "set_input_data_port_type", p_port, vsn->get_input_value_port_info(p_port).type);
- } else {
- undo_redo->add_do_method(vsn.ptr(), "set_output_data_port_type", p_port, Variant::Type(p_select));
- undo_redo->add_undo_method(vsn.ptr(), "set_output_data_port_type", p_port, vsn->get_output_value_port_info(p_port).type);
- }
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_update_node_size(int p_id) {
- Node *node = graph->get_node(itos(p_id));
- if (Object::cast_to<Control>(node)) {
- Object::cast_to<Control>(node)->reset_size(); // Shrink if text is smaller.
- }
-}
-
-void VisualScriptEditor::_port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input) {
- Ref<VisualScriptLists> vsn = script->get_node(p_id);
- if (!vsn.is_valid()) {
- return;
- }
-
- String text;
-
- if (Object::cast_to<LineEdit>(p_name_box)) {
- text = Object::cast_to<LineEdit>(p_name_box)->get_text();
- } else {
- return;
- }
-
- undo_redo->create_action(TTR("Change Port Name"));
- if (is_input) {
- undo_redo->add_do_method(vsn.ptr(), "set_input_data_port_name", p_port, text);
- undo_redo->add_undo_method(vsn.ptr(), "set_input_data_port_name", p_port, vsn->get_input_value_port_info(p_port).name);
- } else {
- undo_redo->add_do_method(vsn.ptr(), "set_output_data_port_name", p_port, text);
- undo_redo->add_undo_method(vsn.ptr(), "set_output_data_port_name", p_port, vsn->get_output_value_port_info(p_port).name);
- }
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_update_members() {
- ERR_FAIL_COND(!script.is_valid());
-
- updating_members = true;
-
- members->clear();
- TreeItem *root = members->create_item();
-
- TreeItem *functions = members->create_item(root);
- functions->set_selectable(0, false);
- functions->set_text(0, TTR("Functions:"));
- functions->add_button(0, Control::get_theme_icon(SNAME("Override"), SNAME("EditorIcons")), 1, false, TTR("Override an existing built-in function."));
- functions->add_button(0, Control::get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), 0, false, TTR("Create a new function."));
- functions->set_custom_color(0, Control::get_theme_color(SNAME("mono_color"), SNAME("Editor")));
-
- List<StringName> func_names;
- script->get_function_list(&func_names);
- func_names.sort_custom<StringName::AlphCompare>();
- for (const StringName &E : func_names) {
- TreeItem *ti = members->create_item(functions);
- ti->set_text(0, E);
- ti->set_selectable(0, true);
- ti->set_metadata(0, E);
- ti->add_button(0, Control::get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")), 0);
- if (selected == E) {
- ti->select(0);
- }
- }
-
- TreeItem *variables = members->create_item(root);
- variables->set_selectable(0, false);
- variables->set_text(0, TTR("Variables:"));
- variables->add_button(0, Control::get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), -1, false, TTR("Create a new variable."));
- variables->set_custom_color(0, Control::get_theme_color(SNAME("mono_color"), SNAME("Editor")));
-
- Ref<Texture2D> type_icons[Variant::VARIANT_MAX] = {
- Control::get_theme_icon(SNAME("Variant"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("bool"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("int"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("float"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("String"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector2"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector2i"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Rect2"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Rect2i"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector3"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Vector3i"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Transform2D"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Plane"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Quaternion"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("AABB"), SNAME("EditorIcons")),
- 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")),
- Control::get_theme_icon(SNAME("Callable"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Signal"), SNAME("EditorIcons")),
- Control::get_theme_icon(SNAME("Dictionary"), SNAME("EditorIcons")),
- 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")),
- Control::get_theme_icon(SNAME("PackedColorArray"), SNAME("EditorIcons"))
- };
-
- 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);
-
- ti->set_text(0, E);
-
- ti->set_suffix(0, "= " + _sanitized_variant_text(E));
- ti->set_icon(0, type_icons[script->get_variable_info(E).type]);
-
- ti->set_selectable(0, true);
- ti->set_editable(0, true);
- ti->set_metadata(0, E);
- if (selected == E) {
- ti->select(0);
- }
- }
-
- TreeItem *_signals = members->create_item(root);
- _signals->set_selectable(0, false);
- _signals->set_text(0, TTR("Signals:"));
- _signals->add_button(0, Control::get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), -1, false, TTR("Create a new signal."));
- _signals->set_custom_color(0, Control::get_theme_color(SNAME("mono_color"), SNAME("Editor")));
-
- List<StringName> signal_names;
- script->get_custom_signal_list(&signal_names);
- for (const StringName &E : signal_names) {
- TreeItem *ti = members->create_item(_signals);
- ti->set_text(0, E);
- ti->set_selectable(0, true);
- ti->set_editable(0, true);
- ti->set_metadata(0, E);
- if (selected == E) {
- ti->select(0);
- }
- }
-
- String base_type = script->get_instance_base_type();
- String icon_type = base_type;
- if (!Control::has_theme_icon(base_type, SNAME("EditorIcons"))) {
- icon_type = "Object";
- }
-
- base_type_select->set_text(base_type);
- base_type_select->set_icon(Control::get_theme_icon(icon_type, SNAME("EditorIcons")));
-
- updating_members = false;
-}
-
-String VisualScriptEditor::_sanitized_variant_text(const StringName &property_name) {
- Variant var = script->get_variable_default_value(property_name);
-
- if (script->get_variable_info(property_name).type != Variant::NIL) {
- Callable::CallError ce;
- const Variant *converted = &var;
- Variant n;
- Variant::construct(script->get_variable_info(property_name).type, n, &converted, 1, ce);
- var = n;
- }
-
- return String(var);
-}
-
-void VisualScriptEditor::_member_selected() {
- if (updating_members) {
- return;
- }
-
- TreeItem *ti = members->get_selected();
- ERR_FAIL_COND(!ti);
-
- selected = ti->get_metadata(0);
-
- if (ti->get_parent() == members->get_root()->get_first_child()) {
-#ifdef MACOS_ENABLED
- bool held_ctrl = Input::get_singleton()->is_key_pressed(Key::META);
-#else
- bool held_ctrl = Input::get_singleton()->is_key_pressed(Key::CTRL);
-#endif
- if (held_ctrl) {
- ERR_FAIL_COND(!script->has_function(selected));
- _center_on_node(script->get_function_node_id(selected));
- }
- }
-}
-
-void VisualScriptEditor::_member_edited() {
- if (updating_members) {
- return;
- }
-
- TreeItem *ti = members->get_edited();
- ERR_FAIL_COND(!ti);
-
- String name = ti->get_metadata(0);
- String new_name = ti->get_text(0);
-
- if (name == new_name) {
- return;
- }
-
- if (!new_name.is_valid_identifier()) {
- EditorNode::get_singleton()->show_warning(TTR("Name is not a valid identifier:") + " " + new_name);
- updating_members = true;
- ti->set_text(0, name);
- updating_members = false;
- return;
- }
-
- if (script->has_function(new_name) || script->has_variable(new_name) || script->has_custom_signal(new_name)) {
- EditorNode::get_singleton()->show_warning(TTR("Name already in use by another func/var/signal:") + " " + new_name);
- updating_members = true;
- ti->set_text(0, name);
- updating_members = false;
- return;
- }
-
- TreeItem *root = members->get_root();
-
- if (ti->get_parent() == root->get_first_child()) {
- selected = new_name;
-
- int node_id = script->get_function_node_id(name);
- Ref<VisualScriptFunction> func;
- if (script->has_node(node_id)) {
- func = script->get_node(node_id);
- }
- undo_redo->create_action(TTR("Rename Function"));
- undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name);
- undo_redo->add_undo_method(script.ptr(), "rename_function", new_name, name);
- if (func.is_valid()) {
- undo_redo->add_do_method(func.ptr(), "set_name", new_name);
- undo_redo->add_undo_method(func.ptr(), "set_name", name);
- }
-
- // Also fix all function calls.
- List<int> lst;
- script->get_node_list(&lst);
- for (int &F : lst) {
- Ref<VisualScriptFunctionCall> fncall = script->get_node(F);
- if (!fncall.is_valid()) {
- continue;
- }
- if (fncall->get_function() == name) {
- undo_redo->add_do_method(fncall.ptr(), "set_function", new_name);
- undo_redo->add_undo_method(fncall.ptr(), "set_function", name);
- }
- }
-
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
-
- return; // Or crash because it will become invalid.
- }
-
- if (ti->get_parent() == root->get_first_child()->get_next()) {
- selected = new_name;
- undo_redo->create_action(TTR("Rename Variable"));
- undo_redo->add_do_method(script.ptr(), "rename_variable", name, new_name);
- undo_redo->add_undo_method(script.ptr(), "rename_variable", new_name, name);
-
- // Also fix all variable setter & getter calls
- List<int> lst;
- script->get_node_list(&lst);
- for (int &P : lst) {
- Ref<VisualScriptPropertySet> pset = script->get_node(P);
- if (pset.is_valid() && pset->get_property() == name) {
- undo_redo->add_do_method(pset.ptr(), "set_property", new_name);
- undo_redo->add_undo_method(pset.ptr(), "set_property", name);
- }
- Ref<VisualScriptPropertyGet> pget = script->get_node(P);
- if (pget.is_valid() && pget->get_property() == name) {
- undo_redo->add_do_method(pget.ptr(), "set_property", new_name);
- undo_redo->add_undo_method(pget.ptr(), "set_property", name);
- }
- }
-
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
-
- return; // Or crash because it will become invalid.
- }
-
- if (ti->get_parent() == root->get_first_child()->get_next()->get_next()) {
- selected = new_name;
- undo_redo->create_action(TTR("Rename Signal"));
- undo_redo->add_do_method(script.ptr(), "rename_custom_signal", name, new_name);
- undo_redo->add_undo_method(script.ptr(), "rename_custom_signal", new_name, name);
-
- // Also fix all signal emitting nodes
- List<int> lst;
- script->get_node_list(&lst);
- for (int &P : lst) {
- Ref<VisualScriptEmitSignal> psig = script->get_node(P);
- if (psig.is_valid() && psig->get_signal() == name) {
- undo_redo->add_do_method(psig.ptr(), "set_signal", new_name);
- undo_redo->add_undo_method(psig.ptr(), "set_signal", name);
- }
- }
-
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
-
- return; // Or crash because it will become invalid.
- }
-}
-
-void VisualScriptEditor::_create_function_dialog() {
- function_create_dialog->popup_centered();
- func_name_box->set_text("");
- func_name_box->grab_focus();
- for (int i = 0; i < func_input_vbox->get_child_count(); i++) {
- Node *nd = func_input_vbox->get_child(i);
- nd->queue_delete();
- }
-}
-
-void VisualScriptEditor::_create_function() {
- String name = _validate_name((func_name_box->get_text().is_empty()) ? "new_func" : func_name_box->get_text());
- selected = name;
- Vector2 pos = _get_available_pos();
-
- Ref<VisualScriptFunction> func_node;
- func_node.instantiate();
- func_node->set_name(name);
-
- for (int i = 0; i < func_input_vbox->get_child_count(); i++) {
- OptionButton *opbtn = Object::cast_to<OptionButton>(func_input_vbox->get_child(i)->get_child(3));
- LineEdit *lne = Object::cast_to<LineEdit>(func_input_vbox->get_child(i)->get_child(1));
- if (!opbtn || !lne) {
- continue;
- }
- Variant::Type arg_type = Variant::Type(opbtn->get_selected());
- String arg_name = lne->get_text();
- func_node->add_argument(arg_type, arg_name);
- }
-
- int func_node_id = script->get_available_id();
-
- undo_redo->create_action(TTR("Add Function"));
- undo_redo->add_do_method(script.ptr(), "add_function", name, func_node_id);
- undo_redo->add_undo_method(script.ptr(), "remove_function", name);
- undo_redo->add_do_method(script.ptr(), "add_node", func_node_id, func_node, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", func_node_id);
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
-
- _update_graph();
-}
-
-void VisualScriptEditor::_add_node_dialog() {
- _generic_search(graph->get_global_position() + Vector2(55, 80), true);
-}
-
-void VisualScriptEditor::_add_func_input() {
- HBoxContainer *hbox = memnew(HBoxContainer);
- hbox->set_h_size_flags(SIZE_EXPAND_FILL);
-
- Label *name_label = memnew(Label);
- name_label->set_text(TTR("Name:"));
- hbox->add_child(name_label);
-
- LineEdit *name_box = memnew(LineEdit);
- name_box->set_h_size_flags(SIZE_EXPAND_FILL);
- name_box->set_text("input");
- name_box->connect("focus_entered", callable_mp(this, &VisualScriptEditor::_deselect_input_names));
- hbox->add_child(name_box);
-
- Label *type_label = memnew(Label);
- type_label->set_text(TTR("Type:"));
- hbox->add_child(type_label);
-
- OptionButton *type_box = memnew(OptionButton);
- type_box->set_custom_minimum_size(Size2(120 * EDSCALE, 0));
- for (int i = Variant::NIL; i < Variant::VARIANT_MAX; i++) {
- type_box->add_item(Variant::get_type_name(Variant::Type(i)));
- }
- type_box->select(1);
- hbox->add_child(type_box);
-
- Button *delete_button = memnew(Button);
- delete_button->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
- delete_button->set_tooltip(vformat(TTR("Delete input port")));
- hbox->add_child(delete_button);
-
- for (int i = 0; i < func_input_vbox->get_child_count(); i++) {
- LineEdit *line_edit = (LineEdit *)func_input_vbox->get_child(i)->get_child(1);
- line_edit->deselect();
- }
-
- func_input_vbox->add_child(hbox);
- hbox->set_meta("id", hbox->get_index());
-
- delete_button->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_func_input).bind(hbox));
-
- name_box->select_all();
- name_box->grab_focus();
-}
-
-void VisualScriptEditor::_remove_func_input(Node *p_node) {
- func_input_vbox->remove_child(p_node);
- p_node->queue_delete();
-}
-
-void VisualScriptEditor::_deselect_input_names() {
- int cn = func_input_vbox->get_child_count();
- for (int i = 0; i < cn; i++) {
- LineEdit *lne = Object::cast_to<LineEdit>(func_input_vbox->get_child(i)->get_child(1));
- if (lne) {
- lne->deselect();
- }
- }
-}
-
-void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_button, MouseButton p_mouse_button) {
- if (p_mouse_button != MouseButton::LEFT) {
- return;
- }
-
- TreeItem *ti = Object::cast_to<TreeItem>(p_item);
-
- TreeItem *root = members->get_root();
-
- if (ti->get_parent() == root) {
- //main buttons
- if (ti == root->get_first_child()) {
- // Add function, this one uses menu.
-
- if (p_button == 1) {
- // Ensure script base exists otherwise use custom base type.
- ERR_FAIL_COND(script.is_null());
- new_virtual_method_select->select_method_from_base_type(script->get_instance_base_type(), true);
- return;
- } else if (p_button == 0) {
- String name = _validate_name("new_function");
- selected = name;
- Vector2 pos = _get_available_pos();
-
- Ref<VisualScriptFunction> func_node;
- func_node.instantiate();
- func_node->set_name(name);
- int fn_id = script->get_available_id();
-
- undo_redo->create_action(TTR("Add Function"));
- undo_redo->add_do_method(script.ptr(), "add_function", name, fn_id);
- undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_function", name);
- undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id);
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
-
- _update_graph();
- }
-
- return; // Or crash because it will become invalid.
- }
-
- if (ti == root->get_first_child()->get_next()) {
- // Add variable.
- String name = _validate_name("new_variable");
- selected = name;
-
- undo_redo->create_action(TTR("Add Variable"));
- undo_redo->add_do_method(script.ptr(), "add_variable", name);
- undo_redo->add_undo_method(script.ptr(), "remove_variable", name);
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
- return; // Or crash because it will become invalid.
- }
-
- if (ti == root->get_first_child()->get_next()->get_next()) {
- // Add variable.
- String name = _validate_name("new_signal");
- selected = name;
-
- undo_redo->create_action(TTR("Add Signal"));
- undo_redo->add_do_method(script.ptr(), "add_custom_signal", name);
- undo_redo->add_undo_method(script.ptr(), "remove_custom_signal", name);
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
- return; // Or crash because it will become invalid.
- }
- } else if (ti->get_parent() == root->get_first_child()) {
- selected = ti->get_text(0);
- function_name_edit->set_position(get_screen_position() + get_local_mouse_position() - Vector2(60, -10));
- function_name_edit->popup();
- function_name_box->set_text(selected);
- function_name_box->select_all();
- function_name_box->grab_focus();
- }
-}
-
-void VisualScriptEditor::_add_input_port(int p_id) {
- Ref<VisualScriptLists> vsn = script->get_node(p_id);
- if (!vsn.is_valid()) {
- return;
- }
-
- updating_graph = true;
-
- undo_redo->create_action(TTR("Add Input Port"), UndoRedo::MERGE_ENDS);
- undo_redo->add_do_method(vsn.ptr(), "add_input_data_port", Variant::NIL, "arg", -1);
- undo_redo->add_do_method(this, "_update_graph", p_id);
-
- undo_redo->add_undo_method(vsn.ptr(), "remove_input_data_port", vsn->get_input_value_port_count());
- undo_redo->add_undo_method(this, "_update_graph", p_id);
-
- updating_graph = false;
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_add_output_port(int p_id) {
- Ref<VisualScriptLists> vsn = script->get_node(p_id);
- if (!vsn.is_valid()) {
- return;
- }
-
- updating_graph = true;
-
- undo_redo->create_action(TTR("Add Output Port"), UndoRedo::MERGE_ENDS);
- undo_redo->add_do_method(vsn.ptr(), "add_output_data_port", Variant::NIL, "arg", -1);
- undo_redo->add_do_method(this, "_update_graph", p_id);
-
- undo_redo->add_undo_method(vsn.ptr(), "remove_output_data_port", vsn->get_output_value_port_count());
- undo_redo->add_undo_method(this, "_update_graph", p_id);
-
- updating_graph = false;
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_remove_input_port(int p_id, int p_port) {
- Ref<VisualScriptLists> vsn = script->get_node(p_id);
- if (!vsn.is_valid()) {
- return;
- }
-
- updating_graph = true;
-
- undo_redo->create_action(TTR("Remove Input Port"), UndoRedo::MERGE_ENDS);
-
- int conn_from = -1, conn_port = -1;
- script->get_input_value_port_connection_source(p_id, p_port, &conn_from, &conn_port);
-
- if (conn_from != -1) {
- undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_id, p_port);
- }
-
- undo_redo->add_do_method(vsn.ptr(), "remove_input_data_port", p_port);
- undo_redo->add_do_method(this, "_update_graph", p_id);
-
- if (conn_from != -1) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_id, p_port);
- }
-
- undo_redo->add_undo_method(vsn.ptr(), "add_input_data_port", vsn->get_input_value_port_info(p_port).type, vsn->get_input_value_port_info(p_port).name, p_port);
- undo_redo->add_undo_method(this, "_update_graph", p_id);
-
- updating_graph = false;
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_remove_output_port(int p_id, int p_port) {
- Ref<VisualScriptLists> vsn = script->get_node(p_id);
- if (!vsn.is_valid()) {
- return;
- }
-
- updating_graph = true;
-
- undo_redo->create_action(TTR("Remove Output Port"), UndoRedo::MERGE_ENDS);
-
- List<VisualScript::DataConnection> data_connections;
- script->get_data_connection_list(&data_connections);
-
- HashMap<int, RBSet<int>> conn_map;
- for (const VisualScript::DataConnection &E : data_connections) {
- if (E.from_node == p_id && E.from_port == p_port) {
- // Push into the connections map.
- if (!conn_map.has(E.to_node)) {
- conn_map.insert(E.to_node, RBSet<int>());
- }
- conn_map[E.to_node].insert(E.to_port);
- }
- }
-
- undo_redo->add_do_method(vsn.ptr(), "remove_output_data_port", p_port);
- undo_redo->add_do_method(this, "_update_graph", p_id);
-
- for (const KeyValue<int, RBSet<int>> &E : conn_map) {
- for (const int &F : E.value) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", p_id, p_port, E.key, F);
- }
- }
-
- undo_redo->add_undo_method(vsn.ptr(), "add_output_data_port", vsn->get_output_value_port_info(p_port).type, vsn->get_output_value_port_info(p_port).name, p_port);
- undo_redo->add_undo_method(this, "_update_graph", p_id);
-
- updating_graph = false;
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id) {
- Ref<VisualScriptExpression> vse = script->get_node(p_id);
- if (!vse.is_valid()) {
- return;
- }
-
- updating_graph = true;
-
- undo_redo->create_action(TTR("Change Expression"), UndoRedo::MERGE_ENDS);
- undo_redo->add_do_property(vse.ptr(), "expression", p_text);
- undo_redo->add_undo_property(vse.ptr(), "expression", vse->get("expression"));
- undo_redo->add_do_method(this, "_update_graph", p_id);
- undo_redo->add_undo_method(this, "_update_graph", p_id);
- undo_redo->commit_action();
-
- Node *node = graph->get_node(itos(p_id));
- if (Object::cast_to<Control>(node)) {
- Object::cast_to<Control>(node)->reset_size(); // Shrink if text is smaller.
- }
-
- updating_graph = false;
-}
-
-Vector2 VisualScriptEditor::_get_pos_in_graph(Vector2 p_point) const {
- Vector2 pos = (graph->get_scroll_ofs() + p_point) / (graph->get_zoom() * EDSCALE);
- if (graph->is_using_snap()) {
- int snap = graph->get_snap();
- pos = pos.snapped(Vector2(snap, snap));
- }
- return pos;
-}
-
-Vector2 VisualScriptEditor::_get_available_pos(bool p_centered, Vector2 p_pos) const {
- if (p_centered) {
- p_pos = _get_pos_in_graph(graph->get_size() * 0.5);
- }
-
- while (true) {
- bool exists = false;
- List<int> existing;
- script->get_node_list(&existing);
- for (int &E : existing) {
- Point2 pos = script->get_node_position(E);
- if (pos.distance_to(p_pos) < 50) {
- p_pos += Vector2(graph->get_snap(), graph->get_snap());
- exists = true;
- break;
- }
- }
- if (exists) {
- continue;
- }
- break;
- }
-
- return p_pos;
-}
-
-String VisualScriptEditor::_validate_name(const String &p_name) const {
- String valid = p_name;
-
- int counter = 1;
- while (true) {
- bool exists = script->has_function(valid) || script->has_variable(valid) || script->has_custom_signal(valid);
-
- if (exists) {
- counter++;
- valid = p_name + "_" + itos(counter);
- continue;
- }
-
- break;
- }
-
- return valid;
-}
-
-void VisualScriptEditor::_on_nodes_copy() {
- clipboard->nodes.clear();
- clipboard->data_connections.clear();
- clipboard->sequence_connections.clear();
-
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn) {
- if (gn->is_selected()) {
- int id = gn->get_name().operator String().to_int();
- Ref<VisualScriptNode> node = script->get_node(id);
- if (Object::cast_to<VisualScriptFunction>(*node)) {
- EditorNode::get_singleton()->show_warning(TTR("Can't copy the function node."));
- return;
- }
- if (node.is_valid()) {
- clipboard->nodes[id] = node->duplicate(true);
- clipboard->nodes_positions[id] = script->get_node_position(id);
- }
- }
- }
- }
-
- if (clipboard->nodes.is_empty()) {
- return;
- }
-
- List<VisualScript::SequenceConnection> sequence_connections;
- script->get_sequence_connection_list(&sequence_connections);
-
- for (const VisualScript::SequenceConnection &E : sequence_connections) {
- if (clipboard->nodes.has(E.from_node) && clipboard->nodes.has(E.to_node)) {
- clipboard->sequence_connections.insert(E);
- }
- }
-
- List<VisualScript::DataConnection> data_connections;
- script->get_data_connection_list(&data_connections);
-
- for (const VisualScript::DataConnection &E : data_connections) {
- if (clipboard->nodes.has(E.from_node) && clipboard->nodes.has(E.to_node)) {
- clipboard->data_connections.insert(E);
- }
- }
-}
-
-void VisualScriptEditor::_on_nodes_paste() {
- if (clipboard->nodes.is_empty()) {
- EditorNode::get_singleton()->show_warning(TTR("Clipboard is empty!"));
- return;
- }
-
- HashMap<int, int> remap;
-
- undo_redo->create_action(TTR("Paste VisualScript Nodes"));
- int idc = script->get_available_id() + 1;
-
- RBSet<int> to_select;
-
- RBSet<Vector2> existing_positions;
-
- {
- List<int> nodes;
- script->get_node_list(&nodes);
- for (int &E : nodes) {
- Vector2 pos = script->get_node_position(E).snapped(Vector2(2, 2));
- existing_positions.insert(pos);
- }
- }
-
- bool first_paste = true;
- Vector2 position_offset = Vector2(0, 0);
-
- for (KeyValue<int, Ref<VisualScriptNode>> &E : clipboard->nodes) {
- Ref<VisualScriptNode> node = E.value->duplicate();
-
- int new_id = idc++;
- to_select.insert(new_id);
-
- remap[E.key] = new_id;
-
- Vector2 paste_pos = clipboard->nodes_positions[E.key];
-
- if (first_paste) {
- position_offset = _get_pos_in_graph(mouse_up_position - graph->get_global_position()) - paste_pos;
- first_paste = false;
- }
-
- paste_pos += position_offset;
-
- while (existing_positions.has(paste_pos.snapped(Vector2(2, 2)))) {
- paste_pos += Vector2(20, 20) * EDSCALE;
- }
-
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, node, paste_pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- }
-
- for (const VisualScript::SequenceConnection &E : clipboard->sequence_connections) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E.from_node], E.from_output, remap[E.to_node]);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", remap[E.from_node], E.from_output, remap[E.to_node]);
- }
-
- for (const VisualScript::DataConnection &E : clipboard->data_connections) {
- undo_redo->add_do_method(script.ptr(), "data_connect", remap[E.from_node], E.from_port, remap[E.to_node], E.to_port);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", remap[E.from_node], E.from_port, remap[E.to_node], E.to_port);
- }
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
-
- undo_redo->commit_action();
-
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn) {
- int id = gn->get_name().operator String().to_int();
- gn->set_selected(to_select.has(id));
- }
- }
-}
-
-void VisualScriptEditor::_on_nodes_delete() {
- // Delete all the selected nodes.
-
- List<int> to_erase;
-
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn) {
- if (gn->is_selected() && gn->is_close_button_visible()) {
- to_erase.push_back(gn->get_name().operator String().to_int());
- }
- }
- }
-
- if (to_erase.is_empty()) {
- return;
- }
-
- undo_redo->create_action(TTR("Remove VisualScript Nodes"));
-
- for (int &F : to_erase) {
- int cr_node = F;
-
- undo_redo->add_do_method(script.ptr(), "remove_node", cr_node);
- undo_redo->add_undo_method(script.ptr(), "add_node", cr_node, script->get_node(cr_node), script->get_node_position(cr_node));
-
- List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(&sequence_conns);
-
- for (const VisualScript::SequenceConnection &E : sequence_conns) {
- if (E.from_node == cr_node || E.to_node == cr_node) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", E.from_node, E.from_output, E.to_node);
- }
- }
-
- List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(&data_conns);
-
- for (const VisualScript::DataConnection &E : data_conns) {
- if (E.from_node == F || E.to_node == F) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", E.from_node, E.from_port, E.to_node, E.to_port);
- }
- }
- }
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_on_nodes_duplicate() {
- RBSet<int> to_duplicate;
-
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn) {
- if (gn->is_selected() && gn->is_close_button_visible()) {
- int id = gn->get_name().operator String().to_int();
- to_duplicate.insert(id);
- }
- }
- }
-
- if (to_duplicate.is_empty()) {
- return;
- }
-
- undo_redo->create_action(TTR("Duplicate VisualScript Nodes"));
- int idc = script->get_available_id() + 1;
-
- RBSet<int> to_select;
- HashMap<int, int> remap;
-
- for (const int &F : to_duplicate) {
- // Duplicate from the specific function but place it into the default func as it would lack the connections.
- Ref<VisualScriptNode> node = script->get_node(F);
-
- Ref<VisualScriptNode> dupe = node->duplicate(true);
-
- int new_id = idc++;
- remap.insert(F, new_id);
-
- to_select.insert(new_id);
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, dupe, script->get_node_position(F) + Vector2(20, 20));
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- }
-
- List<VisualScript::SequenceConnection> seqs;
- script->get_sequence_connection_list(&seqs);
- for (const VisualScript::SequenceConnection &E : seqs) {
- if (to_duplicate.has(E.from_node) && to_duplicate.has(E.to_node)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E.from_node], E.from_output, remap[E.to_node]);
- }
- }
-
- List<VisualScript::DataConnection> data;
- script->get_data_connection_list(&data);
- for (const VisualScript::DataConnection &E : data) {
- if (to_duplicate.has(E.from_node) && to_duplicate.has(E.to_node)) {
- undo_redo->add_do_method(script.ptr(), "data_connect", remap[E.from_node], E.from_port, remap[E.to_node], E.to_port);
- }
- }
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
-
- undo_redo->commit_action();
-
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn) {
- int id = gn->get_name().operator String().to_int();
- gn->set_selected(to_select.has(id));
- }
- }
-
- if (to_select.size()) {
- EditorNode::get_singleton()->push_item(script->get_node(to_select.front()->get()).ptr());
- }
-}
-
-void VisualScriptEditor::_generic_search(Vector2 pos, bool node_centered) {
- if (node_centered) {
- port_action_pos = graph->get_size() / 2.0f;
- } else {
- port_action_pos = graph->get_viewport()->get_mouse_position() - graph->get_global_position();
- }
-
- new_connect_node_select->select_from_visual_script(script, false); // do not reset text
-}
-
-void VisualScriptEditor::input(const Ref<InputEvent> &p_event) {
- ERR_FAIL_COND(p_event.is_null());
-
- // GUI input for VS Editor Plugin
- Ref<InputEventMouseButton> key = p_event;
-
- if (key.is_valid() && key->is_pressed()) {
- mouse_up_position = get_screen_position() + get_local_mouse_position();
- }
-}
-
-void VisualScriptEditor::_graph_gui_input(const Ref<InputEvent> &p_event) {
- Ref<InputEventMouseButton> key = p_event;
-
- if (key.is_valid() && key->is_pressed() && key->get_button_mask() == MouseButton::RIGHT) {
- bool is_empty_selection = true;
-
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn && gn->is_selected()) {
- is_empty_selection = false;
- break;
- }
- }
- if (is_empty_selection && clipboard->nodes.is_empty()) {
- _generic_search();
- } else {
- popup_menu->set_item_disabled(int(EDIT_CUT_NODES), is_empty_selection);
- popup_menu->set_item_disabled(int(EDIT_COPY_NODES), is_empty_selection);
- popup_menu->set_item_disabled(int(EDIT_PASTE_NODES), clipboard->nodes.is_empty());
- popup_menu->set_item_disabled(int(EDIT_DELETE_NODES), is_empty_selection);
- popup_menu->set_item_disabled(int(EDIT_DUPLICATE_NODES), is_empty_selection);
- popup_menu->set_item_disabled(int(EDIT_CLEAR_COPY_BUFFER), clipboard->nodes.is_empty());
-
- popup_menu->set_position(mouse_up_position);
- popup_menu->popup();
- }
- }
-}
-
-void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) {
- Ref<InputEventKey> key = p_event;
- if (key.is_valid() && key->is_pressed() && !key->is_echo()) {
- if (members->has_focus()) {
- TreeItem *ti = members->get_selected();
- if (ti) {
- TreeItem *root = members->get_root();
- if (ti->get_parent() == root->get_first_child()) {
- member_type = MEMBER_FUNCTION;
- }
- if (ti->get_parent() == root->get_first_child()->get_next()) {
- member_type = MEMBER_VARIABLE;
- }
- if (ti->get_parent() == root->get_first_child()->get_next()->get_next()) {
- member_type = MEMBER_SIGNAL;
- }
- member_name = ti->get_text(0);
- }
- if (ED_IS_SHORTCUT("ui_graph_delete", p_event)) {
- _member_option(MEMBER_REMOVE);
- }
- if (ED_IS_SHORTCUT("visual_script_editor/edit_member", p_event)) {
- _member_option(MEMBER_EDIT);
- }
- }
- }
-
- Ref<InputEventMouseButton> btn = p_event;
- if (btn.is_valid() && btn->is_double_click()) {
- TreeItem *ti = members->get_selected();
- if (ti && ti->get_parent() == members->get_root()->get_first_child()) { // to check if it's a function
- _center_on_node(script->get_function_node_id(ti->get_metadata(0)));
- }
- }
-}
-
-void VisualScriptEditor::_rename_function(const String &name, const String &new_name) {
- if (!new_name.is_valid_identifier()) {
- EditorNode::get_singleton()->show_warning(TTR("Name is not a valid identifier:") + " " + new_name);
- return;
- }
-
- if (script->has_function(new_name) || script->has_variable(new_name) || script->has_custom_signal(new_name)) {
- EditorNode::get_singleton()->show_warning(TTR("Name already in use by another func/var/signal:") + " " + new_name);
- return;
- }
-
- int node_id = script->get_function_node_id(name);
- Ref<VisualScriptFunction> func;
- if (script->has_node(node_id)) {
- func = script->get_node(node_id);
- }
- undo_redo->create_action(TTR("Rename Function"));
- undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name);
- undo_redo->add_undo_method(script.ptr(), "rename_function", new_name, name);
- if (func.is_valid()) {
- undo_redo->add_do_method(func.ptr(), "set_name", new_name);
- undo_redo->add_undo_method(func.ptr(), "set_name", name);
- }
-
- // Also fix all function calls.
- List<int> lst;
- script->get_node_list(&lst);
- for (int &F : lst) {
- Ref<VisualScriptFunctionCall> fncall = script->get_node(F);
- if (!fncall.is_valid()) {
- continue;
- }
- if (fncall->get_function() == name) {
- undo_redo->add_do_method(fncall.ptr(), "set_function", new_name);
- undo_redo->add_undo_method(fncall.ptr(), "set_function", name);
- }
- }
-
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_fn_name_box_input(const Ref<InputEvent> &p_event) {
- if (!function_name_edit->is_visible()) {
- return;
- }
-
- Ref<InputEventKey> key = p_event;
- if (key.is_valid() && key->is_pressed() && key->get_keycode() == Key::ENTER) {
- function_name_edit->hide();
- _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);
- if (!it) {
- return Variant();
- }
-
- String type = it->get_metadata(0);
-
- if (type.is_empty()) {
- return Variant();
- }
-
- Dictionary dd;
- TreeItem *root = members->get_root();
-
- if (it->get_parent() == root->get_first_child()) {
- dd["type"] = "visual_script_function_drag";
- dd["function"] = type;
- } else if (it->get_parent() == root->get_first_child()->get_next()) {
- dd["type"] = "visual_script_variable_drag";
- dd["variable"] = type;
- } else if (it->get_parent() == root->get_first_child()->get_next()->get_next()) {
- dd["type"] = "visual_script_signal_drag";
- dd["signal"] = type;
-
- } else {
- return Variant();
- }
-
- Label *label = memnew(Label);
- label->set_text(it->get_text(0));
- set_drag_preview(label);
- return dd;
- }
- return Variant();
-}
-
-bool VisualScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
- if (p_from == graph) {
- Dictionary d = p_data;
- if (d.has("type") &&
- (String(d["type"]) == "visual_script_node_drag" ||
- String(d["type"]) == "visual_script_function_drag" ||
- String(d["type"]) == "visual_script_variable_drag" ||
- String(d["type"]) == "visual_script_signal_drag" ||
- String(d["type"]) == "obj_property" ||
- String(d["type"]) == "resource" ||
- String(d["type"]) == "files" ||
- String(d["type"]) == "nodes")) {
- if (String(d["type"]) == "obj_property") {
-#ifdef MACOS_ENABLED
- const_cast<VisualScriptEditor *>(this)->_show_hint(vformat(TTR("Hold %s to drop a Getter. Hold Shift to drop a generic signature."), find_keycode_name(Key::META)));
-#else
- const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Ctrl to drop a Getter. Hold Shift to drop a generic signature."));
-#endif
- }
-
- if (String(d["type"]) == "nodes") {
-#ifdef MACOS_ENABLED
- const_cast<VisualScriptEditor *>(this)->_show_hint(vformat(TTR("Hold %s to drop a simple reference to the node."), find_keycode_name(Key::META)));
-#else
- const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Ctrl to drop a simple reference to the node."));
-#endif
- }
-
- if (String(d["type"]) == "visual_script_variable_drag") {
-#ifdef MACOS_ENABLED
- const_cast<VisualScriptEditor *>(this)->_show_hint(vformat(TTR("Hold %s to drop a Variable Setter."), find_keycode_name(Key::META)));
-#else
- const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Ctrl to drop a Variable Setter."));
-#endif
- }
-
- return true;
- }
- }
-
- return false;
-}
-
-static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
- return nullptr;
- }
-
- Ref<Script> scr = p_current_node->get_script();
-
- if (scr.is_valid() && scr == script) {
- return p_current_node;
- }
-
- for (int i = 0; i < p_current_node->get_child_count(); i++) {
- Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n) {
- return n;
- }
- }
-
- return nullptr;
-}
-
-void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
- if (p_from != graph) {
- return;
- }
-
- Dictionary d = p_data;
-
- if (!d.has("type")) {
- return;
- }
-
- if (String(d["type"]) == "visual_script_node_drag") {
- if (!d.has("node_type") || String(d["node_type"]) == "Null") {
- return;
- }
-
- Vector2 pos = _get_pos_in_graph(p_point);
-
- int new_id = _create_new_node_from_name(d["node_type"], pos);
-
- Node *node = graph->get_node(itos(new_id));
- if (node) {
- graph->set_selected(node);
- _node_selected(node);
- }
- }
-
- if (String(d["type"]) == "visual_script_variable_drag") {
-#ifdef MACOS_ENABLED
- bool use_set = Input::get_singleton()->is_key_pressed(Key::META);
-#else
- bool use_set = Input::get_singleton()->is_key_pressed(Key::CTRL);
-#endif
- Vector2 pos = _get_pos_in_graph(p_point);
-
- Ref<VisualScriptNode> vnode;
- if (use_set) {
- Ref<VisualScriptPropertySet> pset;
- pset.instantiate();
- vnode = pset;
- } else {
- Ref<VisualScriptPropertyGet> pget;
- pget.instantiate();
- vnode = pget;
- }
-
- int new_id = script->get_available_id();
- undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(vnode.ptr(), "set_property", d["variable"]);
- undo_redo->add_do_method(vnode.ptr(), "set_base_script", script->get_path());
-
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
-
- Node *node = graph->get_node(itos(new_id));
- if (node) {
- graph->set_selected(node);
- _node_selected(node);
- }
- }
-
- if (String(d["type"]) == "visual_script_function_drag") {
- Vector2 pos = _get_pos_in_graph(p_point);
-
- Ref<VisualScriptFunctionCall> vnode;
- vnode.instantiate();
- vnode->set_call_mode(VisualScriptFunctionCall::CALL_MODE_SELF);
-
- int new_id = script->get_available_id();
-
- undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos);
- undo_redo->add_do_method(vnode.ptr(), "set_base_type", script->get_instance_base_type());
- undo_redo->add_do_method(vnode.ptr(), "set_function", d["function"]);
-
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
-
- Node *node = graph->get_node(itos(new_id));
- if (node) {
- graph->set_selected(node);
- _node_selected(node);
- }
- }
-
- if (String(d["type"]) == "visual_script_signal_drag") {
- Vector2 pos = _get_pos_in_graph(p_point);
-
- Ref<VisualScriptEmitSignal> vnode;
- vnode.instantiate();
- vnode->set_signal(d["signal"]);
-
- int new_id = script->get_available_id();
-
- undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
-
- Node *node = graph->get_node(itos(new_id));
- if (node) {
- graph->set_selected(node);
- _node_selected(node);
- }
- }
-
- if (String(d["type"]) == "resource") {
- Vector2 pos = _get_pos_in_graph(p_point);
-
- Ref<VisualScriptPreload> prnode;
- prnode.instantiate();
- prnode->set_preload(d["resource"]);
-
- int new_id = script->get_available_id();
-
- undo_redo->create_action(TTR("Add Preload Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
-
- Node *node = graph->get_node(itos(new_id));
- if (node) {
- graph->set_selected(node);
- _node_selected(node);
- }
- }
-
- if (String(d["type"]) == "files") {
-#ifdef MACOS_ENABLED
- bool use_preload = Input::get_singleton()->is_key_pressed(Key::META);
-#else
- bool use_preload = Input::get_singleton()->is_key_pressed(Key::CTRL);
-#endif
- Vector2 pos = _get_pos_in_graph(p_point);
-
- Array files = d["files"];
-
- List<int> new_ids;
- int new_id = script->get_available_id();
-
- if (files.size()) {
- undo_redo->create_action(TTR("Add Node(s)"));
-
- for (int i = 0; i < files.size(); i++) {
- Ref<Resource> res = ResourceLoader::load(files[i]);
- if (!res.is_valid()) {
- continue;
- }
- Ref<Script> drop_script = ResourceLoader::load(files[i]);
- if (drop_script.is_valid() && drop_script->is_tool() && drop_script->get_instance_base_type() == "VisualScriptCustomNode" && !use_preload) {
- Ref<VisualScriptCustomNode> vscn;
- vscn.instantiate();
- vscn->set_script(drop_script);
-
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, vscn, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- } else {
- Ref<VisualScriptPreload> prnode;
- prnode.instantiate();
- prnode->set_preload(res);
-
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- }
- new_ids.push_back(new_id);
- new_id++;
- pos += Vector2(20, 20);
- }
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
- }
-
- for (int &E : new_ids) {
- Node *node = graph->get_node(itos(E));
- if (node) {
- graph->set_selected(node);
- _node_selected(node);
- }
- }
- }
-
- if (String(d["type"]) == "nodes") {
- Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script);
-
- if (!sn) {
- EditorNode::get_singleton()->show_warning(vformat(TTR("Can't drop nodes because script '%s' is not used in this scene."), get_name()));
- return;
- }
-
-#ifdef MACOS_ENABLED
- bool use_node = Input::get_singleton()->is_key_pressed(Key::META);
-#else
- bool use_node = Input::get_singleton()->is_key_pressed(Key::CTRL);
-#endif
-
- Array nodes = d["nodes"];
-
- Vector2 pos = _get_pos_in_graph(p_point);
-
- undo_redo->create_action(TTR("Add Node(s) From Tree"));
- int base_id = script->get_available_id();
-
- if (use_node || nodes.size() > 1) {
- for (int i = 0; i < nodes.size(); i++) {
- NodePath np = nodes[i];
- Node *node = get_node(np);
- if (!node) {
- continue;
- }
-
- Ref<VisualScriptNode> n;
-
- Ref<VisualScriptSceneNode> scene_node;
- scene_node.instantiate();
- scene_node->set_node_path(sn->get_path_to(node));
- n = scene_node;
-
- undo_redo->add_do_method(script.ptr(), "add_node", base_id, n, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", base_id);
-
- base_id++;
- pos += Vector2(25, 25);
- }
-
- } else {
- NodePath np = nodes[0];
- Node *node = get_node(np);
- drop_position = pos;
- drop_node = node;
- drop_path = sn->get_path_to(node);
- new_connect_node_select->select_from_instance(node, false);
- }
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
- }
-
- if (String(d["type"]) == "obj_property") {
- Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script);
-
- if (!sn && !Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
- EditorNode::get_singleton()->show_warning(vformat(TTR("Can't drop properties because script '%s' is not used in this scene.\nDrop holding 'Shift' to just copy the signature."), get_name()));
- return;
- }
-
- Object *obj = d["object"];
-
- if (!obj) {
- return;
- }
-
- Node *node = Object::cast_to<Node>(obj);
- Vector2 pos = _get_pos_in_graph(p_point);
-
-#ifdef MACOS_ENABLED
- bool use_get = Input::get_singleton()->is_key_pressed(Key::META);
-#else
- bool use_get = Input::get_singleton()->is_key_pressed(Key::CTRL);
-#endif
-
- if (!node || Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
- if (use_get) {
- undo_redo->create_action(TTR("Add Getter Property"));
- } else {
- undo_redo->create_action(TTR("Add Setter Property"));
- }
-
- int base_id = script->get_available_id();
-
- Ref<VisualScriptNode> vnode;
-
- if (!use_get) {
- Ref<VisualScriptPropertySet> pset;
- pset.instantiate();
- pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE);
- pset->set_base_type(obj->get_class());
- vnode = pset;
- } else {
- Ref<VisualScriptPropertyGet> pget;
- pget.instantiate();
- pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE);
- pget->set_base_type(obj->get_class());
- vnode = pget;
- }
-
- undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, pos);
- undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]);
- if (!obj->get_script().is_null()) {
- undo_redo->add_do_method(vnode.ptr(), "set_base_script", Ref<Script>(obj->get_script())->get_path());
- }
- if (!use_get) {
- undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]);
- }
-
- undo_redo->add_undo_method(script.ptr(), "remove_node", base_id);
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
-
- } else {
- if (use_get) {
- undo_redo->create_action(TTR("Add Getter Property"));
- } else {
- undo_redo->create_action(TTR("Add Setter Property"));
- }
-
- int base_id = script->get_available_id();
-
- Ref<VisualScriptNode> vnode;
-
- if (!use_get) {
- Ref<VisualScriptPropertySet> pset;
- pset.instantiate();
- if (sn == node) {
- pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_SELF);
- } else {
- pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_NODE_PATH);
- pset->set_base_path(sn->get_path_to(node));
- }
- vnode = pset;
- } else {
- Ref<VisualScriptPropertyGet> pget;
- pget.instantiate();
- if (sn == node) {
- pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_SELF);
- } else {
- pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_NODE_PATH);
- pget->set_base_path(sn->get_path_to(node));
- }
- vnode = pget;
- }
- undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, pos);
- undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]);
- if (!obj->get_script().is_null()) {
- undo_redo->add_do_method(vnode.ptr(), "set_base_script", Ref<Script>(obj->get_script())->get_path());
- }
- if (!use_get) {
- undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]);
- }
-
- undo_redo->add_undo_method(script.ptr(), "remove_node", base_id);
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
- }
- }
-}
-
-void VisualScriptEditor::_draw_color_over_button(Object *obj, Color p_color) {
- Button *button = Object::cast_to<Button>(obj);
- if (!button) {
- return;
- }
-
- Ref<StyleBox> normal = get_theme_stylebox(SNAME("normal"), SNAME("Button"));
- button->draw_rect(Rect2(normal->get_offset(), button->get_size() - normal->get_minimum_size()), p_color);
-}
-
-void VisualScriptEditor::_button_resource_previewed(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, Variant p_ud) {
- Array ud = p_ud;
- ERR_FAIL_COND(ud.size() != 2);
-
- ObjectID id = ud[0];
- Object *obj = ObjectDB::get_instance(id);
-
- if (!obj) {
- return;
- }
-
- Button *b = Object::cast_to<Button>(obj);
- ERR_FAIL_COND(!b);
-
- if (p_preview.is_null()) {
- b->set_text(ud[1]);
- } else {
- b->set_icon(p_preview);
- }
-}
-
-/////////////////////////
-
-void VisualScriptEditor::apply_code() {
-}
-
-Ref<Resource> VisualScriptEditor::get_edited_resource() const {
- return script;
-}
-
-void VisualScriptEditor::set_edited_resource(const Ref<Resource> &p_res) {
- ERR_FAIL_COND(script.is_valid());
- ERR_FAIL_COND(p_res.is_null());
- script = p_res;
- signal_editor->script = script;
- signal_editor->undo_redo = undo_redo;
- variable_editor->script = script;
- variable_editor->undo_redo = undo_redo;
-
- script->connect("node_ports_changed", callable_mp(this, &VisualScriptEditor::_node_ports_changed));
-
- _update_graph();
- call_deferred(SNAME("_update_members"));
-}
-
-void VisualScriptEditor::enable_editor() {
-}
-
-Vector<String> VisualScriptEditor::get_functions() {
- return Vector<String>();
-}
-
-void VisualScriptEditor::reload_text() {
-}
-
-String VisualScriptEditor::get_name() {
- String name;
-
- name = script->get_path().get_file();
- if (name.is_empty()) {
- // This appears for newly created built-in scripts before saving the scene.
- name = TTR("[unsaved]");
- } else if (script->is_built_in()) {
- const String &script_name = script->get_name();
- if (!script_name.is_empty()) {
- // If the built-in script has a custom resource name defined,
- // display the built-in script name as follows: `ResourceName (scene_file.tscn)`
- name = vformat("%s (%s)", script_name, name.get_slice("::", 0));
- }
- }
-
- if (is_unsaved()) {
- name += "(*)";
- }
-
- return name;
-}
-
-Ref<Texture2D> VisualScriptEditor::get_theme_icon() {
- String icon_name = "VisualScript";
- if (script->is_built_in()) {
- icon_name += "Internal";
- }
-
- if (Control::has_theme_icon(icon_name, "EditorIcons")) {
- return Control::get_theme_icon(icon_name, SNAME("EditorIcons"));
- }
-
- return Control::get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons"));
-}
-
-bool VisualScriptEditor::is_unsaved() {
- bool unsaved =
- script->is_edited() ||
- script->are_subnodes_edited() ||
- script->get_path().is_empty(); // In memory.
- return unsaved;
-}
-
-Variant VisualScriptEditor::get_edit_state() {
- Dictionary d;
- d["scroll"] = graph->get_scroll_ofs();
- d["zoom"] = graph->get_zoom();
- d["using_snap"] = graph->is_using_snap();
- d["snap"] = graph->get_snap();
- return d;
-}
-
-void VisualScriptEditor::set_edit_state(const Variant &p_state) {
- Dictionary d = p_state;
-
- _update_graph();
- _update_members();
-
- if (d.has("scroll")) {
- graph->set_scroll_ofs(d["scroll"]);
- }
- if (d.has("zoom")) {
- graph->set_zoom(d["zoom"]);
- }
- if (d.has("snap")) {
- graph->set_snap(d["snap"]);
- }
- if (d.has("snap_enabled")) {
- graph->set_use_snap(d["snap_enabled"]);
- }
-}
-
-void VisualScriptEditor::_center_on_node(int p_id) {
- Node *n = graph->get_node(itos(p_id));
- GraphNode *gn = Object::cast_to<GraphNode>(n);
-
- // Clear selection.
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gnd = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gnd) {
- gnd->set_selected(false);
- }
- }
-
- if (gn) {
- gn->set_selected(true);
- Vector2 new_scroll = gn->get_position_offset() * graph->get_zoom() - graph->get_size() * 0.5 + gn->get_size() * 0.5;
- graph->set_scroll_ofs(new_scroll);
- script->set_scroll(new_scroll / EDSCALE);
- script->set_edited(true);
- }
-}
-
-void VisualScriptEditor::goto_line(int p_line, bool p_with_error) {
- p_line += 1; // Add one because script lines begin from 0.
-
- if (p_with_error) {
- error_line = p_line;
- }
-
- if (script->has_node(p_line)) {
- _update_graph();
- _update_members();
-
- call_deferred(SNAME("call_deferred"), "_center_on_node", p_line); // The editor might be just created and size might not exist yet.
- }
-}
-
-void VisualScriptEditor::set_executing_line(int p_line) {
- // todo: add a way to show which node is executing right now.
-}
-
-void VisualScriptEditor::clear_executing_line() {
- // todo: add a way to show which node is executing right now.
-}
-
-void VisualScriptEditor::trim_trailing_whitespace() {
-}
-
-void VisualScriptEditor::insert_final_newline() {
-}
-
-void VisualScriptEditor::convert_indent_to_spaces() {
-}
-
-void VisualScriptEditor::convert_indent_to_tabs() {
-}
-
-void VisualScriptEditor::ensure_focus() {
- graph->grab_focus();
-}
-
-void VisualScriptEditor::tag_saved_version() {
-}
-
-void VisualScriptEditor::reload(bool p_soft) {
- _update_graph();
-}
-
-Array VisualScriptEditor::get_breakpoints() {
- Array breakpoints;
- List<StringName> functions;
- script->get_function_list(&functions);
- for (int i = 0; i < functions.size(); i++) {
- List<int> nodes;
- script->get_node_list(&nodes);
- for (int &F : nodes) {
- Ref<VisualScriptNode> vsn = script->get_node(F);
- if (vsn->is_breakpoint()) {
- breakpoints.push_back(F - 1); // Subtract 1 because breakpoints in text start from zero.
- }
- }
- }
- return breakpoints;
-}
-
-void VisualScriptEditor::add_callback(const String &p_function, PackedStringArray p_args) {
- if (script->has_function(p_function)) {
- _update_members();
- _update_graph();
- _center_on_node(script->get_function_node_id(p_function));
- return;
- }
-
- Ref<VisualScriptFunction> func;
- func.instantiate();
- for (int i = 0; i < p_args.size(); i++) {
- String name = p_args[i];
- Variant::Type type = Variant::NIL;
-
- if (name.contains(":")) {
- String tt = name.get_slice(":", 1);
- name = name.get_slice(":", 0);
- for (int j = 0; j < Variant::VARIANT_MAX; j++) {
- String tname = Variant::get_type_name(Variant::Type(j));
- if (tname == tt) {
- type = Variant::Type(j);
- break;
- }
- }
- }
-
- func->add_argument(type, name);
- }
- int fn_id = script->get_available_id();
- func->set_name(p_function);
- script->add_function(p_function, fn_id);
- script->add_node(fn_id, func);
-
- _update_members();
- _update_graph();
-
- _center_on_node(script->get_function_node_id(p_function));
-}
-
-bool VisualScriptEditor::show_members_overview() {
- return false;
-}
-
-void VisualScriptEditor::update_settings() {
- _update_graph();
-}
-
-void VisualScriptEditor::set_debugger_active(bool p_active) {
- if (!p_active) {
- error_line = -1;
- _update_graph(); //clear line break
- }
-}
-
-Control *VisualScriptEditor::get_base_editor() const {
- return graph;
-}
-
-void VisualScriptEditor::set_tooltip_request_func(const Callable &p_toolip_callback) {
-}
-
-Control *VisualScriptEditor::get_edit_menu() {
- return edit_menu;
-}
-
-void VisualScriptEditor::_change_base_type() {
- select_base_type->popup_create(true, true);
-}
-
-void VisualScriptEditor::_toggle_tool_script() {
- script->set_tool_enabled(!script->is_tool());
-}
-
-void VisualScriptEditor::clear_edit_menu() {
- memdelete(edit_menu);
- memdelete(members_section);
-}
-
-void VisualScriptEditor::_change_base_type_callback() {
- String bt = select_base_type->get_selected_type();
-
- ERR_FAIL_COND(bt.is_empty());
- undo_redo->create_action(TTR("Change Base Type"));
- undo_redo->add_do_method(script.ptr(), "set_instance_base_type", bt);
- undo_redo->add_undo_method(script.ptr(), "set_instance_base_type", script->get_instance_base_type());
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_node_selected(Node *p_node) {
- Ref<VisualScriptNode> vnode = p_node->get_meta("__vnode");
- if (vnode.is_null()) {
- return;
- }
-
- EditorNode::get_singleton()->push_item(vnode.ptr()); //edit node in inspector
-}
-
-static bool _get_out_slot(const Ref<VisualScriptNode> &p_node, int p_slot, int &r_real_slot, bool &r_sequence) {
- if (p_slot < p_node->get_output_sequence_port_count()) {
- r_sequence = true;
- r_real_slot = p_slot;
-
- return true;
- }
-
- r_real_slot = p_slot - p_node->get_output_sequence_port_count();
- r_sequence = false;
-
- return (r_real_slot < p_node->get_output_value_port_count());
-}
-
-static bool _get_in_slot(const Ref<VisualScriptNode> &p_node, int p_slot, int &r_real_slot, bool &r_sequence) {
- if (p_slot == 0 && p_node->has_input_sequence_port()) {
- r_sequence = true;
- r_real_slot = 0;
- return true;
- }
-
- r_real_slot = p_slot - (p_node->has_input_sequence_port() ? 1 : 0);
- r_sequence = false;
-
- return r_real_slot < p_node->get_input_value_port_count();
-}
-
-void VisualScriptEditor::_begin_node_move() {
- undo_redo->create_action(TTR("Move Node(s)"));
-}
-
-void VisualScriptEditor::_end_node_move() {
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_move_node(int p_id, const Vector2 &p_to) {
- if (!script->has_node(p_id)) {
- return;
- }
-
- Node *node = graph->get_node(itos(p_id));
-
- if (Object::cast_to<GraphNode>(node)) {
- Object::cast_to<GraphNode>(node)->set_position_offset(p_to);
- }
-
- script->set_node_position(p_id, p_to / EDSCALE);
-}
-
-void VisualScriptEditor::_node_moved(Vector2 p_from, Vector2 p_to, int p_id) {
- undo_redo->add_do_method(this, "_move_node", p_id, p_to);
- undo_redo->add_undo_method(this, "_move_node", p_id, p_from);
-}
-
-void VisualScriptEditor::_remove_node(int p_id) {
- undo_redo->create_action(TTR("Remove VisualScript Node"));
-
- undo_redo->add_do_method(script.ptr(), "remove_node", p_id);
- undo_redo->add_undo_method(script.ptr(), "add_node", p_id, script->get_node(p_id), script->get_node_position(p_id));
-
- List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(&sequence_conns);
-
- for (const VisualScript::SequenceConnection &E : sequence_conns) {
- if (E.from_node == p_id || E.to_node == p_id) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", E.from_node, E.from_output, E.to_node);
- }
- }
-
- List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(&data_conns);
-
- for (const VisualScript::DataConnection &E : data_conns) {
- if (E.from_node == p_id || E.to_node == p_id) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", E.from_node, E.from_port, E.to_node, E.to_port);
- }
- }
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_node_ports_changed(int p_id) {
- _update_graph(p_id);
-}
-
-bool VisualScriptEditor::node_has_sequence_connections(int p_id) {
- List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(&sequence_conns);
-
- for (const VisualScript::SequenceConnection &E : sequence_conns) {
- int from = E.from_node;
- int to = E.to_node;
-
- if (to == p_id || from == p_id) {
- return true;
- }
- }
-
- return false;
-}
-
-void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) {
- Ref<VisualScriptNode> from_node = script->get_node(p_from.to_int());
- ERR_FAIL_COND(!from_node.is_valid());
-
- bool from_seq;
- int from_port;
-
- if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq)) {
- return; //can't connect this, it's invalid
- }
-
- Ref<VisualScriptNode> to_node = script->get_node(p_to.to_int());
- ERR_FAIL_COND(!to_node.is_valid());
-
- bool to_seq;
- int to_port;
-
- if (!_get_in_slot(to_node, p_to_slot, to_port, to_seq)) {
- return; //can't connect this, it's invalid
- }
-
- ERR_FAIL_COND(from_seq != to_seq);
-
- // Checking to prevent warnings.
- if (from_seq) {
- if (script->has_sequence_connection(p_from.to_int(), from_port, p_to.to_int())) {
- return;
- }
- } else if (script->has_data_connection(p_from.to_int(), from_port, p_to.to_int(), to_port)) {
- return;
- }
-
- // Preventing connection to itself.
- if (p_from.to_int() == p_to.to_int()) {
- return;
- }
-
- // Do all the checks here.
- StringName func; // This the func where we store the one the nodes at the end of the resolution on having multiple nodes.
-
- undo_redo->create_action(TTR("Connect Nodes"));
-
- if (from_seq) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", p_from.to_int(), from_port, p_to.to_int());
- // This undo error on undo after move can't be removed without painful gymnastics
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", p_from.to_int(), from_port, p_to.to_int());
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- } else {
- bool converted = false;
-
- Ref<VisualScriptOperator> oper = to_node;
- if (oper.is_valid() && oper->get_typed() == Variant::NIL) {
- // It's an operator Node and if the type is already nil
- if (from_node->get_output_value_port_info(from_port).type != Variant::NIL) {
- oper->set_typed(from_node->get_output_value_port_info(from_port).type);
- }
- }
-
- Ref<VisualScriptOperator> operf = from_node;
- if (operf.is_valid() && operf->get_typed() == Variant::NIL) {
- // It's an operator Node and if the type is already nil
- if (to_node->get_input_value_port_info(to_port).type != Variant::NIL) {
- operf->set_typed(to_node->get_input_value_port_info(to_port).type);
- }
- }
-
- // Disconnect current, and connect the new one
- if (script->is_input_value_port_connected(p_to.to_int(), to_port)) {
- if (can_swap && data_disconnect_node == p_to.to_int()) {
- int conn_from;
- int conn_port;
- script->get_input_value_port_connection_source(p_to.to_int(), to_port, &conn_from, &conn_port);
- undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_to.to_int(), to_port);
- undo_redo->add_do_method(script.ptr(), "data_connect", conn_from, conn_port, data_disconnect_node, data_disconnect_port);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", conn_from, conn_port, data_disconnect_node, data_disconnect_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_to.to_int(), to_port);
- can_swap = false; // swapped
- } else {
- int conn_from;
- int conn_port;
- script->get_input_value_port_connection_source(p_to.to_int(), to_port, &conn_from, &conn_port);
- undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_to.to_int(), to_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_to.to_int(), to_port);
- }
- }
- if (!converted) {
- undo_redo->add_do_method(script.ptr(), "data_connect", p_from.to_int(), from_port, p_to.to_int(), to_port);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", p_from.to_int(), from_port, p_to.to_int(), to_port);
-
- // Update nodes in graph
- undo_redo->add_do_method(this, "_update_graph", p_from.to_int());
- undo_redo->add_do_method(this, "_update_graph", p_to.to_int());
- undo_redo->add_undo_method(this, "_update_graph", p_from.to_int());
- undo_redo->add_undo_method(this, "_update_graph", p_to.to_int());
- } else {
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- }
- }
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) {
- Ref<VisualScriptNode> from_node = script->get_node(p_from.to_int());
- ERR_FAIL_COND(!from_node.is_valid());
-
- bool from_seq;
- int from_port;
-
- if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq)) {
- return; // Can't connect this, it's invalid.
- }
-
- Ref<VisualScriptNode> to_node = script->get_node(p_to.to_int());
- ERR_FAIL_COND(!to_node.is_valid());
-
- bool to_seq;
- int to_port;
-
- if (!_get_in_slot(to_node, p_to_slot, to_port, to_seq)) {
- return; // Can't connect this, it's invalid.
- }
-
- ERR_FAIL_COND(from_seq != to_seq);
-
- undo_redo->create_action(TTR("Disconnect Nodes"));
-
- if (from_seq) {
- undo_redo->add_do_method(script.ptr(), "sequence_disconnect", p_from.to_int(), from_port, p_to.to_int());
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_from.to_int(), from_port, p_to.to_int());
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- } else {
- can_swap = true;
- data_disconnect_node = p_to.to_int();
- data_disconnect_port = to_port;
-
- undo_redo->add_do_method(script.ptr(), "data_disconnect", p_from.to_int(), from_port, p_to.to_int(), to_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", p_from.to_int(), from_port, p_to.to_int(), to_port);
- // Update relevant nodes in the graph.
- undo_redo->add_do_method(this, "_update_graph", p_from.to_int());
- undo_redo->add_do_method(this, "_update_graph", p_to.to_int());
- undo_redo->add_undo_method(this, "_update_graph", p_from.to_int());
- undo_redo->add_undo_method(this, "_update_graph", p_to.to_int());
- }
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos) {
- Node *node = graph->get_node(p_from);
- GraphNode *gn = Object::cast_to<GraphNode>(node);
- if (!gn) {
- return;
- }
-
- Ref<VisualScriptNode> vsn = script->get_node(p_from.to_int());
- if (!vsn.is_valid()) {
- return;
- }
- if (vsn->get_output_value_port_count() || vsn->get_output_sequence_port_count()) {
- port_action_pos = p_release_pos;
- }
-
- if (p_from_slot < vsn->get_output_sequence_port_count()) {
- port_action_node = p_from.to_int();
- port_action_output = p_from_slot;
- _port_action_menu(CREATE_ACTION);
- } else {
- port_action_output = p_from_slot - vsn->get_output_sequence_port_count();
- port_action_node = p_from.to_int();
- _port_action_menu(CREATE_CALL_SET_GET);
- }
-}
-
-VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_action_node, int p_port_action_output, RBSet<int> &visited_nodes) {
- VisualScriptNode::TypeGuess tg;
- tg.type = Variant::NIL;
-
- if (visited_nodes.has(p_port_action_node)) {
- return tg; //no loop
- }
-
- visited_nodes.insert(p_port_action_node);
-
- Ref<VisualScriptNode> node = script->get_node(p_port_action_node);
-
- if (!node.is_valid() || node->get_output_value_port_count() <= p_port_action_output) {
- return tg;
- }
-
- Vector<VisualScriptNode::TypeGuess> in_guesses;
-
- for (int i = 0; i < node->get_input_value_port_count(); i++) {
- PropertyInfo pi = node->get_input_value_port_info(i);
- VisualScriptNode::TypeGuess g;
- g.type = pi.type;
-
- if (g.type == Variant::NIL || g.type == Variant::OBJECT) {
- // Any or object input, must further guess what this is.
- int from_node;
- int from_port;
-
- if (script->get_input_value_port_connection_source(p_port_action_node, i, &from_node, &from_port)) {
- g = _guess_output_type(from_node, from_port, visited_nodes);
- } else {
- Variant defval = node->get_default_input_value(i);
- if (defval.get_type() == Variant::OBJECT) {
- Object *obj = defval;
-
- if (obj) {
- g.type = Variant::OBJECT;
- g.gdclass = obj->get_class();
- g.script = obj->get_script();
- }
- }
- }
- }
-
- in_guesses.push_back(g);
- }
-
- return node->guess_output_type(in_guesses.ptrw(), p_port_action_output);
-}
-
-void VisualScriptEditor::_port_action_menu(int p_option) {
- RBSet<int> vn;
-
- switch (p_option) {
- case CREATE_CALL_SET_GET: {
- Ref<VisualScriptFunctionCall> n;
- n.instantiate();
-
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
-
- if (tg.gdclass != StringName()) {
- n->set_base_type(tg.gdclass);
- } else {
- n->set_base_type("Object");
- }
- String type_string;
- String base_script = "";
- if (script->get_node(port_action_node)->get_output_value_port_count() > 0) {
- type_string = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
- VisualScriptFunctionCall *vsfc = Object::cast_to<VisualScriptFunctionCall>(*script->get_node(port_action_node));
- if (vsfc) {
- base_script = vsfc->get_base_script();
- } else {
- VisualScriptPropertyGet *vspg = Object::cast_to<VisualScriptPropertyGet>(*script->get_node(port_action_node));
- if (vspg) {
- base_script = vspg->get_base_script();
- } else {
- VisualScriptPropertySet *vsps = Object::cast_to<VisualScriptPropertySet>(*script->get_node(port_action_node));
- if (vsps) {
- base_script = vsps->get_base_script();
- }
- }
- }
- }
- if (tg.type == Variant::OBJECT) {
- if (tg.script.is_valid()) {
- new_connect_node_select->select_from_script(tg.script);
- } else if (type_string != String()) {
- new_connect_node_select->select_from_base_type(type_string, base_script);
- } else {
- new_connect_node_select->select_from_base_type(n->get_base_type(), base_script);
- }
- } else if (tg.type == Variant::NIL) {
- new_connect_node_select->select_from_base_type("", base_script);
- } else {
- new_connect_node_select->select_from_basic_type(tg.type);
- }
- // Ensure that the dialog fits inside the graph.
- Vector2 pos = mouse_up_position;
- Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size();
- pos.x = pos.x > bounds.x ? bounds.x : pos.x;
- pos.y = pos.y > bounds.y ? bounds.y : pos.y;
- new_connect_node_select->set_position(pos);
- } break;
- case CREATE_ACTION: {
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
- PropertyInfo property_info;
- if (script->get_node(port_action_node)->get_output_value_port_count() > 0) {
- property_info = script->get_node(port_action_node)->get_output_value_port_info(port_action_output);
- }
- if (tg.type == Variant::OBJECT) {
- if (property_info.type == Variant::OBJECT && !property_info.hint_string.is_empty()) {
- new_connect_node_select->select_from_action(property_info.hint_string);
- } else {
- new_connect_node_select->select_from_action("");
- }
- } else if (tg.type == Variant::NIL) {
- new_connect_node_select->select_from_action("");
- } else {
- new_connect_node_select->select_from_action(Variant::get_type_name(tg.type));
- }
- // Ensure that the dialog fits inside the graph.
- Vector2 pos = mouse_up_position;
- Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size();
- pos.x = pos.x > bounds.x ? bounds.x : pos.x;
- pos.y = pos.y > bounds.y ? bounds.y : pos.y;
- new_connect_node_select->set_position(pos);
- } break;
- }
-}
-
-void VisualScriptEditor::connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id) {
- undo_redo->create_action(TTR("Connect Node Data"));
- VisualScriptReturn *vnode_return = Object::cast_to<VisualScriptReturn>(vnode.ptr());
- if (vnode_return != nullptr && vnode_old->get_output_value_port_count() > 0) {
- vnode_return->set_enable_return_value(true);
- }
- if (vnode_old->get_output_value_port_count() <= 0) {
- undo_redo->commit_action();
- return;
- }
- if (vnode->get_input_value_port_count() <= 0) {
- undo_redo->commit_action();
- return;
- }
- int port = port_action_output;
- int value_count = vnode_old->get_output_value_port_count();
- if (port >= value_count) {
- port = 0;
- }
- undo_redo->add_do_method(script.ptr(), "data_connect", port_action_node, port, new_id, 0);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", port_action_node, port, new_id, 0);
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_selected_connect_node(const String &p_text, const String &p_category, const bool p_connecting) {
-#ifdef MACOS_ENABLED
- bool held_ctrl = Input::get_singleton()->is_key_pressed(Key::META);
-#else
- bool held_ctrl = Input::get_singleton()->is_key_pressed(Key::CTRL);
-#endif
- Vector2 pos = _get_pos_in_graph(port_action_pos);
-
- RBSet<int> vn;
- bool port_node_exists = true;
-
- if (drop_position != Vector2()) {
- pos = drop_position;
- }
- drop_position = Vector2();
-
- Ref<VisualScriptNode> vnode;
- Ref<VisualScriptNode> vnode_old;
- if (port_node_exists && p_connecting) {
- vnode_old = script->get_node(port_action_node);
- }
-
- if (p_category.begins_with("VisualScriptNode")) {
- Ref<VisualScriptNode> n = VisualScriptLanguage::singleton->create_node_from_name(p_text);
-
- if (Object::cast_to<VisualScriptTypeCast>(n.ptr()) && vnode_old.is_valid()) {
- Variant::Type type = vnode_old->get_output_value_port_info(port_action_output).type;
- String hint_name = vnode_old->get_output_value_port_info(port_action_output).hint_string;
-
- if (type == Variant::OBJECT) {
- Object::cast_to<VisualScriptTypeCast>(n.ptr())->set_base_type(hint_name);
- } else if (type == Variant::NIL) {
- Object::cast_to<VisualScriptTypeCast>(n.ptr())->set_base_type("");
- } else {
- Object::cast_to<VisualScriptTypeCast>(n.ptr())->set_base_type(Variant::get_type_name(type));
- }
- }
- vnode = n;
- }
-
- if (p_category == String("Class") && !p_connecting) {
- Ref<VisualScriptFunctionCall> n;
- n.instantiate();
- n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_SINGLETON);
- n->set_singleton("ClassDB");
- n->set_function("instantiate");
- // Did not find a way to edit the input port value
- vnode = n;
- } else if (p_category == String("class_method")) {
- Ref<VisualScriptFunctionCall> n;
- n.instantiate();
- if (!drop_path.is_empty()) {
- if (drop_path == ".") {
- n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_SELF);
- } else {
- n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_NODE_PATH);
- n->set_base_path(drop_path);
- }
- } else {
- n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE);
- }
- if (drop_node) {
- n->set_base_type(drop_node->get_class());
- if (drop_node->get_script_instance()) {
- n->set_base_script(drop_node->get_script_instance()->get_script()->get_path());
- }
- }
- vnode = n;
- } else if (p_category == String("class_property")) {
- Vector<String> property_path = p_text.split(":");
- if (held_ctrl) {
- Ref<VisualScriptPropertySet> n;
- n.instantiate();
- n->set_property(property_path[1]);
- if (!drop_path.is_empty()) {
- if (drop_path == ".") {
- n->set_call_mode(VisualScriptPropertySet::CALL_MODE_SELF);
- } else {
- n->set_call_mode(VisualScriptPropertySet::CALL_MODE_NODE_PATH);
- n->set_base_path(drop_path);
- }
- }
- if (drop_node) {
- n->set_base_type(drop_node->get_class());
- if (drop_node->get_script_instance()) {
- n->set_base_script(drop_node->get_script_instance()->get_script()->get_path());
- }
- }
- vnode = n;
- } else {
- Ref<VisualScriptPropertyGet> n;
- n.instantiate();
- n->set_property(property_path[1]);
- if (!drop_path.is_empty()) {
- if (drop_path == ".") {
- n->set_call_mode(VisualScriptPropertyGet::CALL_MODE_SELF);
- } else {
- n->set_call_mode(VisualScriptPropertyGet::CALL_MODE_NODE_PATH);
- n->set_base_path(drop_path);
- }
- }
- if (drop_node) {
- n->set_base_type(drop_node->get_class());
- if (drop_node->get_script_instance()) {
- n->set_base_script(drop_node->get_script_instance()->get_script()->get_path());
- }
- }
- vnode = n;
- }
- } else if (p_category == String("class_constant")) {
- Vector<String> property_path = p_text.split(":");
- if (ClassDB::class_exists(property_path[0])) {
- Ref<VisualScriptClassConstant> n;
- n.instantiate();
- n->set_base_type(property_path[0]);
- n->set_class_constant(property_path[1]);
- vnode = n;
- } else {
- Ref<VisualScriptBasicTypeConstant> n;
- n.instantiate();
- if (property_path[0] == "Nil") {
- n->set_basic_type(Variant::NIL);
- } else if (property_path[0] == "bool") {
- n->set_basic_type(Variant::BOOL);
- } else if (property_path[0] == "int") {
- n->set_basic_type(Variant::INT);
- } else if (property_path[0] == "float") {
- n->set_basic_type(Variant::FLOAT);
- } else if (property_path[0] == "String") {
- n->set_basic_type(Variant::STRING);
- } else if (property_path[0] == "Vector2") {
- n->set_basic_type(Variant::VECTOR2);
- } else if (property_path[0] == "Vector2i") {
- n->set_basic_type(Variant::VECTOR2I);
- } else if (property_path[0] == "Rect2") {
- n->set_basic_type(Variant::RECT2);
- } else if (property_path[0] == "Rect2i") {
- n->set_basic_type(Variant::RECT2I);
- } else if (property_path[0] == "Transform2D") {
- n->set_basic_type(Variant::TRANSFORM2D);
- } else if (property_path[0] == "Vector3") {
- n->set_basic_type(Variant::VECTOR3);
- } else if (property_path[0] == "Vector3i") {
- n->set_basic_type(Variant::VECTOR3I);
- } else if (property_path[0] == "Plane") {
- n->set_basic_type(Variant::PLANE);
- } else if (property_path[0] == "ABB") {
- n->set_basic_type(Variant::AABB);
- } else if (property_path[0] == "Quaternion") {
- n->set_basic_type(Variant::QUATERNION);
- } else if (property_path[0] == "Basis") {
- n->set_basic_type(Variant::BASIS);
- } else if (property_path[0] == "Transform3D") {
- n->set_basic_type(Variant::TRANSFORM3D);
- } else if (property_path[0] == "Color") {
- n->set_basic_type(Variant::COLOR);
- } else if (property_path[0] == "RID") {
- n->set_basic_type(Variant::RID);
- } else if (property_path[0] == "Object") {
- n->set_basic_type(Variant::OBJECT);
- } else if (property_path[0] == "Callable") {
- n->set_basic_type(Variant::CALLABLE);
- } else if (property_path[0] == "Signal") {
- n->set_basic_type(Variant::SIGNAL);
- } else if (property_path[0] == "StringName") {
- n->set_basic_type(Variant::STRING_NAME);
- } else if (property_path[0] == "NodePath") {
- n->set_basic_type(Variant::NODE_PATH);
- } else if (property_path[0] == "Dictionary") {
- n->set_basic_type(Variant::DICTIONARY);
- } else if (property_path[0] == "Array") {
- n->set_basic_type(Variant::ARRAY);
- } else if (property_path[0] == "PackedByteArray") {
- n->set_basic_type(Variant::PACKED_BYTE_ARRAY);
- } else if (property_path[0] == "PackedInt32Array") {
- n->set_basic_type(Variant::PACKED_INT32_ARRAY);
- } else if (property_path[0] == "PackedInt64Array") {
- n->set_basic_type(Variant::PACKED_INT64_ARRAY);
- } else if (property_path[0] == "PackedFloat32Array") {
- n->set_basic_type(Variant::PACKED_FLOAT32_ARRAY);
- } else if (property_path[0] == "PackedStringArray") {
- n->set_basic_type(Variant::PACKED_STRING_ARRAY);
- } else if (property_path[0] == "PackedVector2Array") {
- n->set_basic_type(Variant::PACKED_VECTOR2_ARRAY);
- } else if (property_path[0] == "PackedVector3Array") {
- n->set_basic_type(Variant::PACKED_VECTOR3_ARRAY);
- } else if (property_path[0] == "PackedColorArray") {
- n->set_basic_type(Variant::PACKED_COLOR_ARRAY);
- }
- n->set_basic_type_constant(property_path[1]);
- vnode = n;
- }
-
- } else if (p_category == String("class_signal")) {
- Vector<String> property_path = p_text.split(":");
- ERR_FAIL_COND(!(script->has_custom_signal(property_path[1]) || ClassDB::has_signal(script->get_instance_base_type(), property_path[1])));
-
- Ref<VisualScriptEmitSignal> n;
- n.instantiate();
- n->set_signal(property_path[1]);
- vnode = n;
- }
- if (vnode == nullptr) {
- print_error("Category not handled: " + p_category.quote());
- }
-
- 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];
-
- Ref<VisualScriptFunctionCall> vsfc = vnode;
- vsfc->set_function(method_name);
-
- if (port_node_exists && p_connecting) {
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
-
- if (tg.type == Variant::OBJECT) {
- vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE);
- vsfc->set_base_type(String(""));
- if (tg.gdclass != StringName()) {
- vsfc->set_base_type(tg.gdclass);
- } else if (script->get_node(port_action_node).is_valid()) {
- PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint;
- String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
-
- if (!base_type.is_empty() && hint == PROPERTY_HINT_TYPE_STRING) {
- vsfc->set_base_type(base_type);
- }
- if (method_name == "call" || method_name == "call_deferred") {
- vsfc->set_function(String(""));
- }
- }
- if (tg.script.is_valid()) {
- vsfc->set_base_script(tg.script->get_path());
- }
- } else if (tg.type == Variant::NIL) {
- vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE);
- vsfc->set_base_type(String(""));
- } else {
- vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE);
- vsfc->set_basic_type(tg.type);
- }
- }
- }
-
- if (port_node_exists && p_connecting) {
- if (Object::cast_to<VisualScriptPropertySet>(vnode.ptr())) {
- Ref<VisualScriptPropertySet> vsp = vnode;
-
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
- if (tg.type == Variant::OBJECT) {
- vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE);
- vsp->set_base_type(String(""));
- if (tg.gdclass != StringName()) {
- vsp->set_base_type(tg.gdclass);
-
- } else if (script->get_node(port_action_node).is_valid()) {
- PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint;
- String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
-
- if (!base_type.is_empty() && hint == PROPERTY_HINT_TYPE_STRING) {
- vsp->set_base_type(base_type);
- }
- }
- if (tg.script.is_valid()) {
- vsp->set_base_script(tg.script->get_path());
- }
- } else if (tg.type == Variant::NIL) {
- vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE);
- vsp->set_base_type(String(""));
- } else {
- vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_BASIC_TYPE);
- vsp->set_basic_type(tg.type);
- }
- }
-
- if (Object::cast_to<VisualScriptPropertyGet>(vnode.ptr())) {
- Ref<VisualScriptPropertyGet> vsp = vnode;
-
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
- if (tg.type == Variant::OBJECT) {
- vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE);
- vsp->set_base_type(String(""));
- if (tg.gdclass != StringName()) {
- vsp->set_base_type(tg.gdclass);
-
- } else if (script->get_node(port_action_node).is_valid()) {
- PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint;
- String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
- if (!base_type.is_empty() && hint == PROPERTY_HINT_TYPE_STRING) {
- vsp->set_base_type(base_type);
- }
- }
- if (tg.script.is_valid()) {
- vsp->set_base_script(tg.script->get_path());
- }
- } else if (tg.type == Variant::NIL) {
- vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE);
- vsp->set_base_type(String(""));
- } else {
- vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_BASIC_TYPE);
- vsp->set_basic_type(tg.type);
- }
- }
- }
- if (vnode == nullptr) {
- print_error("Not able to create node from category: \"" + p_category + "\" and text \"" + p_text + "\" Not created");
- return;
- }
-
- int new_id = script->get_available_id();
- undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- undo_redo->add_do_method(this, "_update_graph", new_id);
- undo_redo->add_undo_method(this, "_update_graph", new_id);
- undo_redo->commit_action();
-
- port_action_new_node = new_id;
-
- String base_script = "";
- String base_type = "";
- if (port_node_exists) {
- if (vnode_old.is_valid()) {
- if (Object::cast_to<VisualScriptTypeCast>(vnode_old.ptr())) {
- base_type = Object::cast_to<VisualScriptTypeCast>(vnode_old.ptr())->get_base_type();
- base_script = Object::cast_to<VisualScriptTypeCast>(vnode_old.ptr())->get_base_script();
- } else if (Object::cast_to<VisualScriptFunctionCall>(vnode_old.ptr())) {
- base_type = Object::cast_to<VisualScriptFunctionCall>(vnode_old.ptr())->get_base_type();
- base_script = Object::cast_to<VisualScriptFunctionCall>(vnode_old.ptr())->get_base_script();
- } else if (Object::cast_to<VisualScriptPropertySet>(vnode_old.ptr())) {
- base_type = Object::cast_to<VisualScriptPropertySet>(vnode_old.ptr())->get_base_type();
- base_script = Object::cast_to<VisualScriptPropertySet>(vnode_old.ptr())->get_base_script();
- } else if (Object::cast_to<VisualScriptPropertyGet>(vnode_old.ptr())) {
- base_type = Object::cast_to<VisualScriptPropertyGet>(vnode_old.ptr())->get_base_type();
- base_script = Object::cast_to<VisualScriptPropertyGet>(vnode_old.ptr())->get_base_script();
- }
- }
-
- Vector<String> property_path = p_text.split(":");
- if (ClassDB::is_parent_class(script->get_instance_base_type(), property_path[0]) || script->get_path().ends_with(property_path[0].unquote())) {
- if (!p_connecting) {
- base_type = script->get_instance_base_type();
- base_script = script->get_path();
- }
- } else {
- base_type = property_path[0];
- base_script = "";
- }
-
- if (drop_node) {
- Ref<Script> script = drop_node->get_script();
- if (script != nullptr) {
- base_script = script->get_path();
- }
- }
-
- if (vnode_old.is_valid() && p_connecting) {
- if (base_type == "") {
- base_type = property_path[0];
- } else if (ClassDB::is_parent_class(property_path[0], base_type)) {
- base_type = property_path[0];
- }
- connect_seq(vnode_old, vnode, port_action_new_node);
- connect_data(vnode_old, vnode, port_action_new_node);
- }
- }
- if (Object::cast_to<VisualScriptTypeCast>(vnode.ptr())) {
- Object::cast_to<VisualScriptTypeCast>(vnode.ptr())->set_base_type(base_type);
- Object::cast_to<VisualScriptTypeCast>(vnode.ptr())->set_base_script(base_script);
- } else if (Object::cast_to<VisualScriptFunctionCall>(vnode.ptr())) {
- if (base_type_map.has(base_type)) {
- Object::cast_to<VisualScriptFunctionCall>(vnode.ptr())->set_basic_type(base_type_map[base_type]);
- Object::cast_to<VisualScriptFunctionCall>(vnode.ptr())->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE);
- } else {
- Object::cast_to<VisualScriptFunctionCall>(vnode.ptr())->set_base_type(base_type);
- Object::cast_to<VisualScriptFunctionCall>(vnode.ptr())->set_base_script(base_script);
- }
- } else if (Object::cast_to<VisualScriptPropertySet>(vnode.ptr())) {
- Object::cast_to<VisualScriptPropertySet>(vnode.ptr())->set_base_type(base_type);
- Object::cast_to<VisualScriptPropertySet>(vnode.ptr())->set_base_script(base_script);
- } else if (Object::cast_to<VisualScriptPropertyGet>(vnode.ptr())) {
- Object::cast_to<VisualScriptPropertyGet>(vnode.ptr())->set_base_type(base_type);
- Object::cast_to<VisualScriptPropertyGet>(vnode.ptr())->set_base_script(base_script);
- }
-
- drop_path = String();
- drop_node = nullptr;
-
- _update_graph(port_action_new_node);
-}
-
-void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id) {
- VisualScriptOperator *vnode_operator = Object::cast_to<VisualScriptOperator>(vnode_new.ptr());
- if (vnode_operator != nullptr && !vnode_operator->has_input_sequence_port()) {
- return;
- }
- VisualScriptConstructor *vnode_constructor = Object::cast_to<VisualScriptConstructor>(vnode_new.ptr());
- if (vnode_constructor != nullptr) {
- return;
- }
- if (vnode_old->get_output_sequence_port_count() <= 0) {
- return;
- }
- if (!vnode_new->has_input_sequence_port()) {
- return;
- }
-
- undo_redo->create_action(TTR("Connect Node Sequence"));
- int pass_port = -vnode_old->get_output_sequence_port_count() + 1;
- int return_port = port_action_output - 1;
- if (vnode_old->get_output_value_port_info(port_action_output).name == String("pass") &&
- !script->get_output_sequence_ports_connected(port_action_node).has(pass_port)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, pass_port, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, pass_port, new_id);
- } else if (vnode_old->get_output_value_port_info(port_action_output).name == String("return") &&
- !script->get_output_sequence_ports_connected(port_action_node).has(return_port)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, return_port, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, return_port, new_id);
- } else {
- for (int port = 0; port < vnode_old->get_output_sequence_port_count(); port++) {
- int count = vnode_old->get_output_sequence_port_count();
- if (port_action_output < count && !script->get_output_sequence_ports_connected(port_action_node).has(port_action_output)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, port_action_output, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, port_action_output, new_id);
- break;
- } else if (!script->get_output_sequence_ports_connected(port_action_node).has(port)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, port, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, port, new_id);
- break;
- }
- }
- }
-
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, const String &p_category, const bool p_connecting) {
- String name = p_text.substr(p_text.find_char(':') + 1);
- if (script->has_function(name)) {
- EditorNode::get_singleton()->show_warning(vformat(TTR("Script already has function '%s'"), name));
- return;
- }
-
- MethodInfo minfo;
- {
- List<MethodInfo> methods;
- bool found = false;
- ClassDB::get_virtual_methods(script->get_instance_base_type(), &methods);
- for (const MethodInfo &E : methods) {
- if (E.name == name) {
- minfo = E;
- found = true;
- }
- }
-
- ERR_FAIL_COND(!found);
- }
-
- selected = name;
- Ref<VisualScriptFunction> func_node;
- func_node.instantiate();
- func_node->set_name(name);
- int fn_id = script->get_available_id();
- undo_redo->create_action(TTR("Add Function"));
- undo_redo->add_do_method(script.ptr(), "add_function", name, fn_id);
-
- for (int i = 0; i < minfo.arguments.size(); i++) {
- func_node->add_argument(minfo.arguments[i].type, minfo.arguments[i].name, -1, minfo.arguments[i].hint, minfo.arguments[i].hint_string);
- }
-
- Vector2 pos = _get_available_pos();
-
- undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id);
- if (minfo.return_val.type != Variant::NIL || minfo.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
- Ref<VisualScriptReturn> ret_node;
- ret_node.instantiate();
- ret_node->set_return_type(minfo.return_val.type);
- ret_node->set_enable_return_value(true);
- ret_node->set_name(name);
- int nid = script->get_available_id() + 1;
- undo_redo->add_do_method(script.ptr(), "add_node", nid, ret_node, _get_available_pos(false, pos + Vector2(500, 0)));
- undo_redo->add_undo_method(script.ptr(), "remove_node", nid);
- }
-
- undo_redo->add_undo_method(script.ptr(), "remove_function", name);
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
-
- undo_redo->commit_action();
-
- _update_graph();
-}
-
-void VisualScriptEditor::_cancel_connect_node() {
- // Ensure the cancel is done.
- port_action_new_node = -1;
-}
-
-int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const Vector2 &p_point) {
- Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(p_text);
- int new_id = script->get_available_id();
- undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, p_point);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
- return new_id;
-}
-
-void VisualScriptEditor::_default_value_changed(const StringName &p_property, const Variant &p_value, const String &p_field, bool p_changing) {
- Ref<VisualScriptNode> vsn = script->get_node(editing_id);
- if (vsn.is_null()) {
- return;
- }
-
- undo_redo->create_action(TTR("Change Input Value"));
- undo_redo->add_do_method(vsn.ptr(), "set_default_input_value", editing_input, p_value);
- undo_redo->add_undo_method(vsn.ptr(), "set_default_input_value", editing_input, vsn->get_default_input_value(editing_input));
-
- undo_redo->add_do_method(this, "_update_graph", editing_id);
- undo_redo->add_undo_method(this, "_update_graph", editing_id);
- undo_redo->commit_action();
-}
-
-void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_input_port) {
- Ref<VisualScriptNode> vsn = script->get_node(p_id);
- if (vsn.is_null()) {
- return;
- }
-
- PropertyInfo pinfo = vsn->get_input_value_port_info(p_input_port);
- Variant existing = vsn->get_default_input_value(p_input_port);
- if (pinfo.type != Variant::NIL && existing.get_type() != pinfo.type) {
- Callable::CallError ce;
- Variant e = existing;
- const Variant *existingp = &e;
- Variant::construct(pinfo.type, existing, &existingp, 1, ce);
- }
-
- if (pinfo.type == Variant::NODE_PATH) {
- Node *edited_scene = get_tree()->get_edited_scene_root();
- if (edited_scene) { // Fixing an old crash bug ( Visual Script Crashes on editing NodePath with an empty scene open).
- Node *script_node = _find_script_node(edited_scene, edited_scene, script);
-
- if (script_node) {
- // Pick a node relative to the script, IF the script exists.
- pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE;
- pinfo.hint_string = script_node->get_path();
- } else {
- // Pick a path relative to edited scene.
- pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE;
- pinfo.hint_string = get_tree()->get_edited_scene_root()->get_path();
- }
- }
- }
-
- edited_default_property_holder->set_edited_property(existing);
-
- if (default_property_editor) {
- default_property_editor->disconnect("property_changed", callable_mp(this, &VisualScriptEditor::_default_value_changed));
- default_property_editor_popup->remove_child(default_property_editor);
- }
-
- default_property_editor = EditorInspector::instantiate_property_editor(edited_default_property_holder.ptr(), pinfo.type, "edited_property", pinfo.hint, pinfo.hint_string, PROPERTY_USAGE_NONE);
- if (default_property_editor) {
- default_property_editor->set_object_and_property(edited_default_property_holder.ptr(), "edited_property");
- default_property_editor->update_property();
- default_property_editor->set_name_split_ratio(0);
- default_property_editor_popup->add_child(default_property_editor);
-
- default_property_editor->connect("property_changed", callable_mp(this, &VisualScriptEditor::_default_value_changed));
-
- Button *button = Object::cast_to<Button>(p_button);
- if (button) {
- default_property_editor_popup->set_position(button->get_screen_position() + Vector2(0, button->get_size().height) * graph->get_zoom());
- }
-
- default_property_editor_popup->reset_size();
-
- if (pinfo.hint == PROPERTY_HINT_MULTILINE_TEXT || !button) {
- default_property_editor_popup->popup_centered_ratio();
- } else {
- default_property_editor_popup->popup();
- }
- }
-
- editing_id = p_id;
- editing_input = p_input_port;
-}
-
-void VisualScriptEditor::_show_hint(const String &p_hint) {
- hint_text->set_text(p_hint);
- hint_text->show();
- hint_text_timer->start();
-}
-
-void VisualScriptEditor::_hide_timer() {
- hint_text->hide();
-}
-
-void VisualScriptEditor::_toggle_scripts_pressed() {
- ScriptEditor::get_singleton()->toggle_scripts_panel();
- update_toggle_scripts_button();
-}
-
-void VisualScriptEditor::_notification(int p_what) {
- switch (p_what) {
- case NOTIFICATION_ENTER_TREE:
- case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
- graph->get_panner()->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/sub_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EditorSettings::get_singleton()->get("editors/panning/simple_panning")));
- graph->set_warped_panning(bool(EditorSettings::get_singleton()->get("editors/panning/warped_mouse_panning")));
- graph->set_minimap_opacity(EditorSettings::get_singleton()->get("editors/visual_editors/minimap_opacity"));
- graph->set_connection_lines_curvature(EditorSettings::get_singleton()->get("editors/visual_editors/lines_curvature"));
- _update_graph();
- } break;
-
- case NOTIFICATION_READY: {
- variable_editor->connect("changed", callable_mp(this, &VisualScriptEditor::_update_members));
- variable_editor->connect("changed", callable_mp(this, &VisualScriptEditor::_update_graph).bind(-1), CONNECT_DEFERRED);
- signal_editor->connect("changed", callable_mp(this, &VisualScriptEditor::_update_members));
- signal_editor->connect("changed", callable_mp(this, &VisualScriptEditor::_update_graph).bind(-1), CONNECT_DEFERRED);
- [[fallthrough]];
- }
- case NOTIFICATION_THEME_CHANGED: {
- if (p_what != NOTIFICATION_READY && !is_visible_in_tree()) {
- return;
- }
-
- update_toggle_scripts_button();
-
- edit_variable_edit->add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree")));
- edit_signal_edit->add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree")));
- func_input_scroll->add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree")));
-
- Ref<Theme> tm = EditorNode::get_singleton()->get_theme_base()->get_theme();
-
- bool dark_theme = tm->get_constant("dark_theme", "Editor");
-
- if (dark_theme) {
- node_colors["flow_control"] = Color(0.96, 0.96, 0.96);
- node_colors["functions"] = Color(0.96, 0.52, 0.51);
- node_colors["data"] = Color(0.5, 0.96, 0.81);
- node_colors["operators"] = Color(0.67, 0.59, 0.87);
- node_colors["custom"] = Color(0.5, 0.73, 0.96);
- node_colors["constants"] = Color(0.96, 0.5, 0.69);
- } else {
- node_colors["flow_control"] = Color(0.26, 0.26, 0.26);
- node_colors["functions"] = Color(0.95, 0.4, 0.38);
- node_colors["data"] = Color(0.07, 0.73, 0.51);
- node_colors["operators"] = Color(0.51, 0.4, 0.82);
- node_colors["custom"] = Color(0.31, 0.63, 0.95);
- node_colors["constants"] = Color(0.94, 0.18, 0.49);
- }
-
- for (const KeyValue<StringName, Color> &E : node_colors) {
- const Ref<StyleBoxFlat> sb = tm->get_stylebox(SNAME("frame"), SNAME("GraphNode"));
-
- if (!sb.is_null()) {
- Ref<StyleBoxFlat> frame_style = sb->duplicate();
- // Adjust the border color to be close to the GraphNode's background color.
- // This keeps the node's title area from being too distracting.
- Color color = dark_theme ? E.value.darkened(0.75) : E.value.lightened(0.75);
- color.a = 0.9;
- frame_style->set_border_color(color);
- node_styles[E.key] = frame_style;
- }
- }
-
- if (is_visible_in_tree() && script.is_valid()) {
- _update_members();
- _update_graph();
- }
- } break;
-
- case NOTIFICATION_VISIBILITY_CHANGED: {
- update_toggle_scripts_button();
- members_section->set_visible(is_visible_in_tree());
- } break;
- }
-}
-
-void VisualScriptEditor::_graph_ofs_changed(const Vector2 &p_ofs) {
- if (updating_graph || !script.is_valid()) {
- return;
- }
-
- updating_graph = true;
-
- script->set_scroll(graph->get_scroll_ofs() / EDSCALE);
- script->set_edited(true);
- updating_graph = false;
-}
-
-void VisualScriptEditor::_comment_node_resized(const Vector2 &p_new_size, int p_node) {
- if (updating_graph) {
- return;
- }
- Ref<VisualScriptComment> vsc = script->get_node(p_node);
- if (vsc.is_null()) {
- return;
- }
-
- Node *node = graph->get_node(itos(p_node));
- GraphNode *gn = Object::cast_to<GraphNode>(node);
- if (!gn) {
- return;
- }
-
- Vector2 new_size = p_new_size;
- if (graph->is_using_snap()) {
- Vector2 snap = Vector2(graph->get_snap(), graph->get_snap());
- Vector2 min_size = (gn->get_minimum_size() + (snap * 0.5)).snapped(snap);
- new_size = new_size.snapped(snap).max(min_size);
- }
-
- updating_graph = true;
-
- graph->set_block_minimum_size_adjust(true); //faster resize
-
- undo_redo->create_action(TTR("Resize Comment"), UndoRedo::MERGE_ENDS);
- undo_redo->add_do_method(vsc.ptr(), "set_size", new_size / EDSCALE);
- undo_redo->add_undo_method(vsc.ptr(), "set_size", vsc->get_size());
- undo_redo->commit_action();
-
- gn->set_custom_minimum_size(new_size);
- gn->reset_size();
- graph->set_block_minimum_size_adjust(false);
- updating_graph = false;
-}
-
-void VisualScriptEditor::_menu_option(int p_what) {
- switch (p_what) {
- case EDIT_ADD_NODE: {
- _generic_search();
- } break;
- case EDIT_DELETE_NODES: {
- _on_nodes_delete();
- } break;
- case EDIT_TOGGLE_BREAKPOINT: {
- List<String> reselect;
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn) {
- if (gn->is_selected()) {
- int id = String(gn->get_name()).to_int();
- Ref<VisualScriptNode> vsn = script->get_node(id);
- if (vsn.is_valid()) {
- vsn->set_breakpoint(!vsn->is_breakpoint());
- reselect.push_back(gn->get_name());
- }
- }
- }
- }
-
- _update_graph();
-
- for (const String &E : reselect) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_node(E));
- gn->set_selected(true);
- }
-
- } break;
- case EDIT_FIND_NODE_TYPE: {
- _generic_search();
- } break;
- case EDIT_COPY_NODES: {
- _on_nodes_copy();
- } break;
- case EDIT_CUT_NODES: {
- _on_nodes_copy();
- _on_nodes_delete();
- } break;
- case EDIT_PASTE_NODES: {
- _on_nodes_paste();
- } break;
- case EDIT_DUPLICATE_NODES: {
- _on_nodes_duplicate();
- } break;
- case EDIT_CREATE_FUNCTION: {
- // Create Function.
- HashMap<int, Ref<VisualScriptNode>> nodes;
- RBSet<int> selections;
- for (int i = 0; i < graph->get_child_count(); i++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gn) {
- if (gn->is_selected()) {
- int id = String(gn->get_name()).to_int();
- Ref<VisualScriptNode> node = script->get_node(id);
- if (Object::cast_to<VisualScriptFunction>(*node)) {
- EditorNode::get_singleton()->show_warning(TTR("Can't create function with a function node."));
- return;
- }
- if (node.is_valid()) {
- nodes.insert(id, node);
- selections.insert(id);
- }
- }
- }
- }
-
- if (nodes.size() == 0) {
- return; // nothing to be done if there are no valid nodes selected
- }
-
- RBSet<VisualScript::SequenceConnection> seqmove;
- RBSet<VisualScript::DataConnection> datamove;
-
- RBSet<VisualScript::SequenceConnection> seqext;
- RBSet<VisualScript::DataConnection> dataext;
-
- int start_node = -1;
- RBSet<int> end_nodes;
- if (nodes.size() == 1) {
- Ref<VisualScriptNode> nd = script->get_node(nodes.begin()->key);
- if (nd.is_valid() && nd->has_input_sequence_port()) {
- start_node = nodes.begin()->key;
- } else {
- EditorNode::get_singleton()->show_warning(TTR("Select at least one node with sequence port."));
- return;
- }
- } else {
- List<VisualScript::SequenceConnection> seqs;
- script->get_sequence_connection_list(&seqs);
-
- if (seqs.size() == 0) {
- // In case there are no sequence connections,
- // select the top most node cause that's probably how,
- // the user wants to connect the nodes.
- int top_nd = -1;
- Vector2 top;
- for (const KeyValue<int, Ref<VisualScriptNode>> &E : nodes) {
- Ref<VisualScriptNode> nd = script->get_node(E.key);
- if (nd.is_valid() && nd->has_input_sequence_port()) {
- if (top_nd < 0) {
- top_nd = E.key;
- top = script->get_node_position(top_nd);
- }
- Vector2 pos = script->get_node_position(E.key);
- if (top.y > pos.y) {
- top_nd = E.key;
- top = pos;
- }
- }
- }
- Ref<VisualScriptNode> nd = script->get_node(top_nd);
- if (nd.is_valid() && nd->has_input_sequence_port()) {
- start_node = top_nd;
- } else {
- EditorNode::get_singleton()->show_warning(TTR("Select at least one node with sequence port."));
- return;
- }
- } else {
- // Pick the node with input sequence.
- RBSet<int> nodes_from;
- RBSet<int> nodes_to;
- for (const VisualScript::SequenceConnection &E : seqs) {
- if (nodes.has(E.from_node) && nodes.has(E.to_node)) {
- seqmove.insert(E);
- nodes_from.insert(E.from_node);
- } else if (nodes.has(E.from_node) && !nodes.has(E.to_node)) {
- seqext.insert(E);
- } else if (!nodes.has(E.from_node) && nodes.has(E.to_node)) {
- if (start_node == -1) {
- seqext.insert(E);
- start_node = E.to_node;
- } else {
- EditorNode::get_singleton()->show_warning(TTR("Try to only have one sequence input in selection."));
- return;
- }
- }
- nodes_to.insert(E.to_node);
- }
-
- // To use to add return nodes.
- _get_ends(start_node, seqs, selections, end_nodes);
-
- if (start_node == -1) {
- // If we still don't have a start node then,
- // run through the nodes and select the first tree node,
- // i.e. node without any input sequence but output sequence.
- for (const int &E : nodes_from) {
- if (!nodes_to.has(E)) {
- start_node = E;
- }
- }
- }
- }
- }
-
- if (start_node == -1) {
- return; // This should not happen, but just in case something goes wrong.
- }
-
- List<Variant::Type> inputs; // input types
- List<Pair<int, int>> input_connections;
- {
- List<VisualScript::DataConnection> dats;
- script->get_data_connection_list(&dats);
- for (const VisualScript::DataConnection &E : dats) {
- if (nodes.has(E.from_node) && nodes.has(E.to_node)) {
- datamove.insert(E);
- } else if (!nodes.has(E.from_node) && nodes.has(E.to_node)) {
- // Add all these as inputs for the Function.
- Ref<VisualScriptNode> node = script->get_node(E.to_node);
- if (node.is_valid()) {
- dataext.insert(E);
- PropertyInfo pi = node->get_input_value_port_info(E.to_port);
- inputs.push_back(pi.type);
- input_connections.push_back(Pair<int, int>(E.to_node, E.to_port));
- }
- } else if (nodes.has(E.from_node) && !nodes.has(E.to_node)) {
- dataext.insert(E);
- }
- }
- }
- int fn_id = script->get_available_id();
- {
- String new_fn = _validate_name("new_function");
-
- Vector2 pos = _get_available_pos(false, script->get_node_position(start_node) - Vector2(80, 150));
-
- Ref<VisualScriptFunction> func_node;
- func_node.instantiate();
- func_node->set_name(new_fn);
-
- undo_redo->create_action(TTR("Create Function"));
-
- undo_redo->add_do_method(script.ptr(), "add_function", new_fn, fn_id);
- undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, pos);
- undo_redo->add_undo_method(script.ptr(), "remove_function", new_fn);
- undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id);
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
- // Might make the system more intelligent by checking port from info.
- int i = 0;
- List<Pair<int, int>>::Element *F = input_connections.front();
- for (List<Variant::Type>::Element *E = inputs.front(); E && F; E = E->next(), F = F->next()) {
- func_node->add_argument(E->get(), "arg_" + String::num_int64(i), i);
- undo_redo->add_do_method(script.ptr(), "data_connect", fn_id, i, F->get().first, F->get().second);
- i++; // increment i
- }
- // Ensure Preview Selection is of newly created function node.
- if (selections.size()) {
- EditorNode::get_singleton()->push_item(func_node.ptr());
- }
- }
- // Move the nodes.
-
- // Handles reconnection of sequence connections on undo, start here in case of issues.
- for (const VisualScript::SequenceConnection &E : seqext) {
- undo_redo->add_do_method(script.ptr(), "sequence_disconnect", E.from_node, E.from_output, E.to_node);
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", E.from_node, E.from_output, E.to_node);
- }
- for (const VisualScript::DataConnection &E : dataext) {
- undo_redo->add_do_method(script.ptr(), "data_disconnect", E.from_node, E.from_port, E.to_node, E.to_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", E.from_node, E.from_port, E.to_node, E.to_port);
- }
-
- // I don't really think we need support for non sequenced functions at this moment.
- undo_redo->add_do_method(script.ptr(), "sequence_connect", fn_id, 0, start_node);
-
- // Could fail with the new changes, start here when searching for bugs in create function shortcut.
- int m = 1;
- for (const int &G : end_nodes) {
- Ref<VisualScriptReturn> ret_node;
- ret_node.instantiate();
-
- int ret_id = fn_id + (m++);
- selections.insert(ret_id);
- Vector2 posi = _get_available_pos(false, script->get_node_position(G) + Vector2(80, -100));
- undo_redo->add_do_method(script.ptr(), "add_node", ret_id, ret_node, posi);
- undo_redo->add_undo_method(script.ptr(), "remove_node", ret_id);
-
- undo_redo->add_do_method(script.ptr(), "sequence_connect", G, 0, ret_id);
- // Add data outputs from each of the end_nodes.
- Ref<VisualScriptNode> vsn = script->get_node(G);
- if (vsn.is_valid() && vsn->get_output_value_port_count() > 0) {
- ret_node->set_enable_return_value(true);
- // Use the zeroth data port cause that's the likely one that is planned to be used.
- ret_node->set_return_type(vsn->get_output_value_port_info(0).type);
- undo_redo->add_do_method(script.ptr(), "data_connect", G, 0, ret_id, 0);
- }
- }
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
-
- undo_redo->commit_action();
-
- // Make sure all Nodes get marked for selection so that they can be moved together.
- selections.insert(fn_id);
- for (int k = 0; k < graph->get_child_count(); k++) {
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(k));
- if (gn) {
- int id = gn->get_name().operator String().to_int();
- gn->set_selected(selections.has(id));
- }
- }
-
- } break;
- case REFRESH_GRAPH: {
- _update_graph();
- } break;
- case EDIT_CLEAR_COPY_BUFFER: {
- clipboard->nodes.clear();
- clipboard->nodes_positions.clear();
- clipboard->data_connections.clear();
- clipboard->sequence_connections.clear();
- } break;
- }
-}
-
-// This is likely going to be very slow and I am not sure if I should keep it,
-// but I hope that it will not be a problem considering that we won't be creating functions so frequently,
-// and cyclic connections would be a problem but hopefully we won't let them get to this point.
-void VisualScriptEditor::_get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const RBSet<int> &p_selected, RBSet<int> &r_end_nodes) {
- for (const VisualScript::SequenceConnection &E : p_seqs) {
- int from = E.from_node;
- int to = E.to_node;
-
- if (from == p_node && p_selected.has(to)) {
- // This is an interior connection move forward to the to node.
- _get_ends(to, p_seqs, p_selected, r_end_nodes);
- } else if (from == p_node && !p_selected.has(to)) {
- r_end_nodes.insert(from);
- }
- }
-}
-
-void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos, MouseButton p_button) {
- if (p_button != MouseButton::RIGHT) {
- return;
- }
-
- TreeItem *ti = members->get_selected();
- ERR_FAIL_COND(!ti);
-
- member_popup->clear();
- member_popup->set_position(members->get_screen_position() + p_pos);
- member_popup->reset_size();
-
- function_name_edit->set_position(members->get_screen_position() + p_pos);
- function_name_edit->reset_size();
-
- TreeItem *root = members->get_root();
-
- Ref<Texture2D> del_icon = Control::get_theme_icon(SNAME("Remove"), SNAME("EditorIcons"));
-
- Ref<Texture2D> edit_icon = Control::get_theme_icon(SNAME("Edit"), SNAME("EditorIcons"));
-
- if (ti->get_parent() == root->get_first_child()) {
- member_type = MEMBER_FUNCTION;
- member_name = ti->get_text(0);
- member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT);
- member_popup->add_separator();
- member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("ui_graph_delete"), MEMBER_REMOVE);
- member_popup->popup();
- return;
- }
-
- if (ti->get_parent() == root->get_first_child()->get_next()) {
- member_type = MEMBER_VARIABLE;
- member_name = ti->get_text(0);
- member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT);
- member_popup->add_separator();
- member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("ui_graph_delete"), MEMBER_REMOVE);
- member_popup->popup();
- return;
- }
-
- if (ti->get_parent() == root->get_first_child()->get_next()->get_next()) {
- member_type = MEMBER_SIGNAL;
- member_name = ti->get_text(0);
- member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT);
- member_popup->add_separator();
- member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("ui_graph_delete"), MEMBER_REMOVE);
- member_popup->popup();
- return;
- }
-}
-
-void VisualScriptEditor::_member_option(int p_option) {
- switch (member_type) {
- case MEMBER_FUNCTION: {
- if (p_option == MEMBER_REMOVE) {
- // Delete the function.
- String name = member_name;
- List<String> lst;
- int fn_node = script->get_function_node_id(name);
- undo_redo->create_action(TTR("Remove Function"));
- undo_redo->add_do_method(script.ptr(), "remove_function", name);
- undo_redo->add_do_method(script.ptr(), "remove_node", fn_node);
- undo_redo->add_undo_method(script.ptr(), "add_function", name, fn_node);
- undo_redo->add_undo_method(script.ptr(), "add_node", fn_node, script->get_node(fn_node), script->get_node_position(fn_node));
- List<VisualScript::SequenceConnection> seqcons;
- script->get_sequence_connection_list(&seqcons);
- for (const VisualScript::SequenceConnection &E : seqcons) {
- if (E.from_node == fn_node) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", fn_node, E.from_output, E.to_node);
- }
- }
- List<VisualScript::DataConnection> datcons;
- script->get_data_connection_list(&datcons);
- for (const VisualScript::DataConnection &E : datcons) {
- if (E.from_node == fn_node) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", fn_node, E.from_port, E.to_node, E.to_port);
- }
- }
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
- undo_redo->commit_action();
- } else if (p_option == MEMBER_EDIT) {
- selected = members->get_selected()->get_text(0);
- function_name_edit->popup();
- function_name_box->set_text(selected);
- function_name_box->select_all();
- function_name_box->grab_focus();
- }
- } break;
- case MEMBER_VARIABLE: {
- String name = member_name;
-
- if (p_option == MEMBER_REMOVE) {
- undo_redo->create_action(TTR("Remove Variable"));
- undo_redo->add_do_method(script.ptr(), "remove_variable", name);
- undo_redo->add_undo_method(script.ptr(), "add_variable", name, script->get_variable_default_value(name));
- undo_redo->add_undo_method(script.ptr(), "set_variable_info", name, script->call("get_variable_info", name)); //return as dict
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->commit_action();
- } else if (p_option == MEMBER_EDIT) {
- variable_editor->edit(name);
- edit_variable_dialog->set_title(TTR("Editing Variable:") + " " + name);
- edit_variable_dialog->popup_centered(Size2(400, 200) * EDSCALE);
- }
- } break;
- case MEMBER_SIGNAL: {
- String name = member_name;
-
- if (p_option == MEMBER_REMOVE) {
- undo_redo->create_action(TTR("Remove Signal"));
- undo_redo->add_do_method(script.ptr(), "remove_custom_signal", name);
- undo_redo->add_undo_method(script.ptr(), "add_custom_signal", name);
-
- for (int i = 0; i < script->custom_signal_get_argument_count(name); i++) {
- undo_redo->add_undo_method(script.ptr(), "custom_signal_add_argument", name, script->custom_signal_get_argument_name(name, i), script->custom_signal_get_argument_type(name, i));
- }
-
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->commit_action();
- } else if (p_option == MEMBER_EDIT) {
- signal_editor->edit(name);
- edit_signal_dialog->set_title(TTR("Editing Signal:") + " " + name);
- edit_signal_dialog->popup_centered(Size2(400, 300) * EDSCALE);
- }
- } break;
- }
-}
-
-void VisualScriptEditor::add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
-}
-
-void VisualScriptEditor::set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
-}
-
-void VisualScriptEditor::update_toggle_scripts_button() {
- if (is_layout_rtl()) {
- toggle_scripts_button->set_icon(Control::get_theme_icon(ScriptEditor::get_singleton()->is_scripts_panel_toggled() ? SNAME("Forward") : SNAME("Back"), SNAME("EditorIcons")));
- } else {
- toggle_scripts_button->set_icon(Control::get_theme_icon(ScriptEditor::get_singleton()->is_scripts_panel_toggled() ? SNAME("Back") : SNAME("Forward"), SNAME("EditorIcons")));
- }
- toggle_scripts_button->set_tooltip(vformat("%s (%s)", TTR("Toggle Scripts Panel"), ED_GET_SHORTCUT("script_editor/toggle_scripts_panel")->get_as_text()));
-}
-
-void VisualScriptEditor::_bind_methods() {
- ClassDB::bind_method("_move_node", &VisualScriptEditor::_move_node);
- ClassDB::bind_method("_update_graph", &VisualScriptEditor::_update_graph, DEFVAL(-1));
-
- ClassDB::bind_method("_center_on_node", &VisualScriptEditor::_center_on_node);
- ClassDB::bind_method("_button_resource_previewed", &VisualScriptEditor::_button_resource_previewed);
- ClassDB::bind_method("_port_action_menu", &VisualScriptEditor::_port_action_menu);
-
- ClassDB::bind_method("_create_new_node_from_name", &VisualScriptEditor::_create_new_node_from_name);
-
- ClassDB::bind_method("_get_drag_data_fw", &VisualScriptEditor::get_drag_data_fw);
- ClassDB::bind_method("_can_drop_data_fw", &VisualScriptEditor::can_drop_data_fw);
- ClassDB::bind_method("_drop_data_fw", &VisualScriptEditor::drop_data_fw);
-
- ClassDB::bind_method("_update_graph_connections", &VisualScriptEditor::_update_graph_connections);
- ClassDB::bind_method("_update_members", &VisualScriptEditor::_update_members);
-
- ClassDB::bind_method("_generic_search", &VisualScriptEditor::_generic_search);
-}
-
-VisualScriptEditor::VisualScriptEditor() {
- if (!clipboard) {
- clipboard = memnew(Clipboard);
- }
-
- edit_menu = memnew(MenuButton);
- edit_menu->set_shortcut_context(this);
- edit_menu->set_text(TTR("Edit"));
- edit_menu->set_switch_on_hover(true);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_graph_delete"), EDIT_DELETE_NODES);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/toggle_breakpoint"), EDIT_TOGGLE_BREAKPOINT);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/find_node_type"), EDIT_FIND_NODE_TYPE);
- edit_menu->get_popup()->add_separator();
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY_NODES);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT_NODES);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE_NODES);
- edit_menu->get_popup()->add_separator();
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/create_function"), EDIT_CREATE_FUNCTION);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/refresh_nodes"), REFRESH_GRAPH);
- edit_menu->get_popup()->connect("id_pressed", callable_mp(this, &VisualScriptEditor::_menu_option));
-
- members_section = memnew(VBoxContainer);
- // Add but wait until done setting up this.
- ScriptEditor::get_singleton()->get_left_list_split()->call_deferred(SNAME("add_child"), members_section);
- members_section->set_v_size_flags(SIZE_EXPAND_FILL);
-
- CheckButton *tool_script_check = memnew(CheckButton);
- tool_script_check->set_text(TTR("Make Tool:"));
- members_section->add_child(tool_script_check);
- tool_script_check->connect("pressed", callable_mp(this, &VisualScriptEditor::_toggle_tool_script));
-
- /// Members ///
-
- members = memnew(Tree);
- members_section->add_margin_child(TTR("Members:"), members, true);
- members->set_custom_minimum_size(Size2(0, 50 * EDSCALE));
- members->set_hide_root(true);
- members->connect("button_clicked", callable_mp(this, &VisualScriptEditor::_member_button));
- members->connect("item_edited", callable_mp(this, &VisualScriptEditor::_member_edited));
- members->connect("cell_selected", callable_mp(this, &VisualScriptEditor::_member_selected), CONNECT_DEFERRED);
- members->connect("gui_input", callable_mp(this, &VisualScriptEditor::_members_gui_input));
- members->connect("item_mouse_selected", callable_mp(this, &VisualScriptEditor::_member_rmb_selected));
- members->set_allow_rmb_select(true);
- members->set_allow_reselect(true);
- members->set_hide_folding(true);
- members->set_drag_forwarding(this);
-
- member_popup = memnew(PopupMenu);
- add_child(member_popup);
- 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);
-
- /// Actual Graph ///
-
- graph = memnew(GraphEdit);
- add_child(graph);
- graph->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- graph->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
- graph->set_show_zoom_label(true);
- graph->connect("node_selected", callable_mp(this, &VisualScriptEditor::_node_selected));
- graph->connect("begin_node_move", callable_mp(this, &VisualScriptEditor::_begin_node_move));
- graph->connect("end_node_move", callable_mp(this, &VisualScriptEditor::_end_node_move));
- graph->connect("copy_nodes_request", callable_mp(this, &VisualScriptEditor::_on_nodes_copy));
- graph->connect("paste_nodes_request", callable_mp(this, &VisualScriptEditor::_on_nodes_paste));
- graph->connect("delete_nodes_request", callable_mp(this, &VisualScriptEditor::_on_nodes_delete));
- graph->connect("duplicate_nodes_request", callable_mp(this, &VisualScriptEditor::_on_nodes_duplicate));
- graph->connect("gui_input", callable_mp(this, &VisualScriptEditor::_graph_gui_input));
- graph->set_drag_forwarding(this);
- float graph_minimap_opacity = EditorSettings::get_singleton()->get("editors/visual_editors/minimap_opacity");
- graph->set_minimap_opacity(graph_minimap_opacity);
- float graph_lines_curvature = EditorSettings::get_singleton()->get("editors/visual_editors/lines_curvature");
- graph->set_connection_lines_curvature(graph_lines_curvature);
- graph->hide();
- graph->connect("scroll_offset_changed", callable_mp(this, &VisualScriptEditor::_graph_ofs_changed));
-
- status_bar = memnew(HBoxContainer);
- add_child(status_bar);
- status_bar->set_h_size_flags(SIZE_EXPAND_FILL);
- status_bar->set_custom_minimum_size(Size2(0, 24 * EDSCALE));
-
- toggle_scripts_button = memnew(Button);
- toggle_scripts_button->set_flat(true);
- toggle_scripts_button->connect("pressed", callable_mp(this, &VisualScriptEditor::_toggle_scripts_pressed));
- status_bar->add_child(toggle_scripts_button);
-
- /// Add Buttons to Top Bar/Zoom bar.
- HBoxContainer *graph_hbc = graph->get_zoom_hbox();
-
- Label *base_lbl = memnew(Label);
- base_lbl->set_text(TTR("Change Base Type:") + " ");
- graph_hbc->add_child(base_lbl);
-
- base_type_select = memnew(Button);
- base_type_select->connect("pressed", callable_mp(this, &VisualScriptEditor::_change_base_type));
- graph_hbc->add_child(base_type_select);
-
- Button *add_nds = memnew(Button);
- add_nds->set_text(TTR("Add Nodes..."));
- graph_hbc->add_child(add_nds);
- add_nds->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_node_dialog));
-
- Button *fn_btn = memnew(Button);
- fn_btn->set_text(TTR("Add Function..."));
- graph_hbc->add_child(fn_btn);
- fn_btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_create_function_dialog));
-
- // Add Function Dialog.
- VBoxContainer *function_vb = memnew(VBoxContainer);
- function_vb->set_v_size_flags(SIZE_EXPAND_FILL);
- function_vb->set_custom_minimum_size(Size2(450, 300) * EDSCALE);
-
- HBoxContainer *func_name_hbox = memnew(HBoxContainer);
- function_vb->add_child(func_name_hbox);
-
- Label *func_name_label = memnew(Label);
- func_name_label->set_text(TTR("Name:"));
- func_name_hbox->add_child(func_name_label);
-
- func_name_box = memnew(LineEdit);
- func_name_box->set_h_size_flags(SIZE_EXPAND_FILL);
- func_name_box->set_placeholder(TTR("function_name"));
- func_name_box->set_text("");
- func_name_box->connect("focus_entered", callable_mp(this, &VisualScriptEditor::_deselect_input_names));
- func_name_hbox->add_child(func_name_box);
-
- // Add minor setting for function if needed, here!
-
- function_vb->add_child(memnew(HSeparator));
-
- Button *add_input_button = memnew(Button);
- add_input_button->set_h_size_flags(SIZE_EXPAND_FILL);
- add_input_button->set_text(TTR("Add Input"));
- add_input_button->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_func_input));
- function_vb->add_child(add_input_button);
-
- func_input_scroll = memnew(ScrollContainer);
- func_input_scroll->set_v_size_flags(SIZE_EXPAND_FILL);
- function_vb->add_child(func_input_scroll);
-
- func_input_vbox = memnew(VBoxContainer);
- func_input_vbox->set_h_size_flags(SIZE_EXPAND_FILL);
- func_input_scroll->add_child(func_input_vbox);
-
- function_create_dialog = memnew(ConfirmationDialog);
- function_create_dialog->set_title(TTR("Create Function"));
- function_create_dialog->add_child(function_vb);
- function_create_dialog->set_ok_button_text(TTR("Create"));
- function_create_dialog->get_ok_button()->connect("pressed", callable_mp(this, &VisualScriptEditor::_create_function));
- add_child(function_create_dialog);
-
- select_func_text = memnew(Label);
- select_func_text->set_text(TTR("Select or create a function to edit its graph."));
- select_func_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
- select_func_text->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
- select_func_text->set_h_size_flags(SIZE_EXPAND_FILL);
- add_child(select_func_text);
-
- hint_text = memnew(Label);
- hint_text->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -100);
- hint_text->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
- hint_text->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
- hint_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
- hint_text->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
- graph->add_child(hint_text);
-
- hint_text_timer = memnew(Timer);
- hint_text_timer->set_wait_time(4);
- hint_text_timer->connect("timeout", callable_mp(this, &VisualScriptEditor::_hide_timer));
- add_child(hint_text_timer);
-
- // Allowed casts (connections).
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- graph->add_valid_connection_type(Variant::NIL, i);
- graph->add_valid_connection_type(i, Variant::NIL);
- for (int j = 0; j < Variant::VARIANT_MAX; j++) {
- if (Variant::can_convert(Variant::Type(i), Variant::Type(j))) {
- graph->add_valid_connection_type(i, j);
- }
- }
-
- graph->add_valid_right_disconnect_type(i);
- }
-
- graph->add_valid_left_disconnect_type(TYPE_SEQUENCE);
-
- graph->connect("connection_request", callable_mp(this, &VisualScriptEditor::_graph_connected));
- graph->connect("disconnection_request", callable_mp(this, &VisualScriptEditor::_graph_disconnected));
- graph->connect("connection_to_empty", callable_mp(this, &VisualScriptEditor::_graph_connect_to_empty));
-
- edit_signal_dialog = memnew(AcceptDialog);
- edit_signal_dialog->set_ok_button_text(TTR("Close"));
- add_child(edit_signal_dialog);
-
- signal_editor = memnew(VisualScriptEditorSignalEdit);
- edit_signal_edit = memnew(EditorInspector);
- edit_signal_dialog->add_child(edit_signal_edit);
-
- edit_signal_edit->edit(signal_editor);
-
- edit_variable_dialog = memnew(AcceptDialog);
- edit_variable_dialog->set_ok_button_text(TTR("Close"));
- add_child(edit_variable_dialog);
-
- variable_editor = memnew(VisualScriptEditorVariableEdit);
- edit_variable_edit = memnew(EditorInspector);
- edit_variable_dialog->add_child(edit_variable_edit);
-
- edit_variable_edit->edit(variable_editor);
-
- select_base_type = memnew(CreateDialog);
- select_base_type->set_base_type("Object"); // Anything goes.
- select_base_type->connect("create", callable_mp(this, &VisualScriptEditor::_change_base_type_callback));
- add_child(select_base_type);
-
- undo_redo = EditorNode::get_singleton()->get_undo_redo();
-
- set_process_input(true);
-
- default_property_editor_popup = memnew(PopupPanel);
- default_property_editor_popup->set_min_size(Size2i(180, 0) * EDSCALE);
- add_child(default_property_editor_popup);
-
- edited_default_property_holder.instantiate();
-
- new_connect_node_select = memnew(VisualScriptPropertySelector);
- add_child(new_connect_node_select);
- new_connect_node_select->connect("selected", callable_mp(this, &VisualScriptEditor::_selected_connect_node));
- new_connect_node_select->get_cancel_button()->connect("pressed", callable_mp(this, &VisualScriptEditor::_cancel_connect_node));
-
- new_virtual_method_select = memnew(VisualScriptPropertySelector);
- add_child(new_virtual_method_select);
- new_virtual_method_select->connect("selected", callable_mp(this, &VisualScriptEditor::_selected_new_virtual_method));
-
- popup_menu = memnew(PopupMenu);
- add_child(popup_menu);
- popup_menu->add_item(TTR("Add Node"), EDIT_ADD_NODE);
- popup_menu->add_separator();
- popup_menu->add_item(TTR("Cut"), EDIT_CUT_NODES);
- popup_menu->add_item(TTR("Copy"), EDIT_COPY_NODES);
- popup_menu->add_item(TTR("Paste"), EDIT_PASTE_NODES);
- popup_menu->add_item(TTR("Delete"), EDIT_DELETE_NODES);
- popup_menu->add_item(TTR("Duplicate"), EDIT_DUPLICATE_NODES);
- popup_menu->add_item(TTR("Clear Copy Buffer"), EDIT_CLEAR_COPY_BUFFER);
- popup_menu->connect("id_pressed", callable_mp(this, &VisualScriptEditor::_menu_option));
-
- base_type_map.insert("String", Variant::STRING);
- base_type_map.insert("Vector2", Variant::VECTOR2);
- base_type_map.insert("Vector2i", Variant::VECTOR2I);
- base_type_map.insert("Rect2", Variant::RECT2);
- base_type_map.insert("Rect2i", Variant::RECT2I);
- base_type_map.insert("Vector3", Variant::VECTOR3);
- base_type_map.insert("Vector3i", Variant::VECTOR3I);
- base_type_map.insert("Vector4", Variant::VECTOR4);
- base_type_map.insert("Vector4i", Variant::VECTOR4I);
- base_type_map.insert("Transform2D", Variant::TRANSFORM2D);
- base_type_map.insert("Plane", Variant::PLANE);
- base_type_map.insert("Quaternion", Variant::QUATERNION);
- base_type_map.insert("AABB", Variant::AABB);
- base_type_map.insert("Basis", Variant::BASIS);
- base_type_map.insert("Transform3D", Variant::TRANSFORM3D);
- base_type_map.insert("Projection", Variant::PROJECTION);
- base_type_map.insert("Color", Variant::COLOR);
- base_type_map.insert("NodePath", Variant::NODE_PATH);
- base_type_map.insert("RID", Variant::RID);
- base_type_map.insert("Callable", Variant::CALLABLE);
- base_type_map.insert("Dictionary", Variant::DICTIONARY);
- base_type_map.insert("Array", Variant::ARRAY);
- base_type_map.insert("PackedByteArray", Variant::PACKED_BYTE_ARRAY);
- base_type_map.insert("PackedInt32Array", Variant::PACKED_INT32_ARRAY);
- base_type_map.insert("PackedFloat32Array", Variant::PACKED_FLOAT32_ARRAY);
- base_type_map.insert("PackedInt64Array", Variant::PACKED_INT64_ARRAY);
- base_type_map.insert("PackedFloat64Array", Variant::PACKED_FLOAT64_ARRAY);
- base_type_map.insert("PackedStringArray", Variant::PACKED_STRING_ARRAY);
- base_type_map.insert("PackedVector2Array", Variant::PACKED_VECTOR2_ARRAY);
- base_type_map.insert("PackedVector3Array", Variant::PACKED_VECTOR3_ARRAY);
- base_type_map.insert("PackedColorArray", Variant::PACKED_COLOR_ARRAY);
-}
-
-VisualScriptEditor::~VisualScriptEditor() {
- undo_redo->clear_history(); // Avoid crashes.
- memdelete(signal_editor);
- memdelete(variable_editor);
-}
-
-static ScriptEditorBase *create_editor(const Ref<Resource> &p_resource) {
- if (Object::cast_to<VisualScript>(*p_resource)) {
- return memnew(VisualScriptEditor);
- }
-
- return nullptr;
-}
-
-VisualScriptEditor::Clipboard *VisualScriptEditor::clipboard = nullptr;
-
-void VisualScriptEditor::free_clipboard() {
- if (clipboard) {
- memdelete(clipboard);
- }
-}
-
-static void register_editor_callback() {
- ScriptEditor::register_create_script_editor_function(create_editor);
-
- ED_SHORTCUT("visual_script_editor/toggle_breakpoint", TTR("Toggle Breakpoint"), Key::F9);
- ED_SHORTCUT("visual_script_editor/find_node_type", TTR("Find Node Type"), KeyModifierMask::CMD + Key::F);
- ED_SHORTCUT("visual_script_editor/create_function", TTR("Make Function"), KeyModifierMask::CMD + Key::G);
- ED_SHORTCUT("visual_script_editor/refresh_nodes", TTR("Refresh Graph"), KeyModifierMask::CMD + Key::R);
- ED_SHORTCUT("visual_script_editor/edit_member", TTR("Edit Member"), KeyModifierMask::CMD + Key::E);
-}
-
-void VisualScriptEditor::register_editor() {
- // Too early to register stuff here, request a callback.
- EditorNode::add_plugin_init_callback(register_editor_callback);
-}
-
-void VisualScriptEditor::validate() {
-}
-
-// VisualScriptCustomNodes
-
-Ref<VisualScriptNode> VisualScriptCustomNodes::create_node_custom(const String &p_name) {
- Ref<VisualScriptCustomNode> node;
- node.instantiate();
- node->set_script(singleton->custom_nodes[p_name]);
- return node;
-}
-
-VisualScriptCustomNodes *VisualScriptCustomNodes::singleton = nullptr;
-HashMap<String, Ref<RefCounted>> VisualScriptCustomNodes::custom_nodes;
-
-VisualScriptCustomNodes::VisualScriptCustomNodes() {
- singleton = this;
-}
-
-VisualScriptCustomNodes::~VisualScriptCustomNodes() {
- custom_nodes.clear();
-}
-
-void VisualScriptCustomNodes::add_custom_node(const String &p_name, const String &p_category, const Ref<Script> &p_script) {
- String node_name = "custom/" + p_category + "/" + p_name;
- custom_nodes.insert(node_name, p_script);
- VisualScriptLanguage::singleton->add_register_func(node_name, &VisualScriptCustomNodes::create_node_custom);
- emit_signal(SNAME("custom_nodes_updated"));
-}
-
-void VisualScriptCustomNodes::remove_custom_node(const String &p_name, const String &p_category) {
- String node_name = "custom/" + p_category + "/" + p_name;
- custom_nodes.erase(node_name);
- VisualScriptLanguage::singleton->remove_register_func(node_name);
- emit_signal(SNAME("custom_nodes_updated"));
-}
-
-void VisualScriptCustomNodes::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_custom_node", "name", "category", "script"), &VisualScriptCustomNodes::add_custom_node);
- ClassDB::bind_method(D_METHOD("remove_custom_node", "name", "category"), &VisualScriptCustomNodes::remove_custom_node);
- ADD_SIGNAL(MethodInfo("custom_nodes_updated"));
-}
-
-#endif
diff --git a/modules/visual_script/editor/visual_script_editor.h b/modules/visual_script/editor/visual_script_editor.h
deleted file mode 100644
index 6b337e52f6..0000000000
--- a/modules/visual_script/editor/visual_script_editor.h
+++ /dev/null
@@ -1,395 +0,0 @@
-/*************************************************************************/
-/* visual_script_editor.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 VISUAL_SCRIPT_EDITOR_H
-#define VISUAL_SCRIPT_EDITOR_H
-
-#include "../visual_script.h"
-#include "editor/create_dialog.h"
-#include "editor/plugins/script_editor_plugin.h"
-#include "visual_script_property_selector.h"
-
-class GraphEdit;
-
-class VisualScriptEditorSignalEdit;
-class VisualScriptEditorVariableEdit;
-
-#ifdef TOOLS_ENABLED
-
-class VisualScriptEditedProperty : public RefCounted {
- GDCLASS(VisualScriptEditedProperty, RefCounted);
-
-private:
- Variant edited_property;
-
-protected:
- static void _bind_methods();
-
-public:
- void set_edited_property(Variant p_variant);
- Variant get_edited_property() const;
-
- VisualScriptEditedProperty() {}
-};
-
-// TODO: Maybe this class should be refactored.
-// See https://github.com/godotengine/godot/issues/51913
-class VisualScriptEditor : public ScriptEditorBase {
- GDCLASS(VisualScriptEditor, ScriptEditorBase);
-
- enum {
- TYPE_SEQUENCE = 1000,
- INDEX_BASE_SEQUENCE = 1024
- };
-
- enum {
- EDIT_ADD_NODE,
- EDIT_SEPARATOR, // popup menu separator - ignored
- EDIT_CUT_NODES,
- EDIT_COPY_NODES,
- EDIT_PASTE_NODES,
- EDIT_DELETE_NODES,
- EDIT_DUPLICATE_NODES,
- EDIT_CLEAR_COPY_BUFFER,
-
- EDIT_CREATE_FUNCTION,
- EDIT_TOGGLE_BREAKPOINT,
- EDIT_FIND_NODE_TYPE,
- REFRESH_GRAPH,
- };
-
- enum PortAction {
- CREATE_CALL_SET_GET,
- CREATE_ACTION,
- };
-
- enum MemberAction {
- MEMBER_EDIT,
- MEMBER_REMOVE
- };
-
- enum MemberType {
- MEMBER_FUNCTION,
- MEMBER_VARIABLE,
- MEMBER_SIGNAL
- };
-
- VBoxContainer *members_section = nullptr;
- MenuButton *edit_menu = nullptr;
-
- Ref<VisualScript> script;
-
- Button *base_type_select = nullptr;
-
- LineEdit *func_name_box = nullptr;
- ScrollContainer *func_input_scroll = nullptr;
- VBoxContainer *func_input_vbox = nullptr;
- ConfirmationDialog *function_create_dialog = nullptr;
-
- GraphEdit *graph = nullptr;
- HBoxContainer *status_bar = nullptr;
- Button *toggle_scripts_button = nullptr;
-
- VisualScriptEditorSignalEdit *signal_editor = nullptr;
-
- AcceptDialog *edit_signal_dialog = nullptr;
- EditorInspector *edit_signal_edit = nullptr;
-
- VisualScriptPropertySelector *method_select = nullptr;
- VisualScriptPropertySelector *new_connect_node_select = nullptr;
- VisualScriptPropertySelector *new_virtual_method_select = nullptr;
-
- VisualScriptEditorVariableEdit *variable_editor = nullptr;
-
- AcceptDialog *edit_variable_dialog = nullptr;
- EditorInspector *edit_variable_edit = nullptr;
-
- PopupPanel *default_property_editor_popup = nullptr;
- EditorProperty *default_property_editor = nullptr;
- Ref<VisualScriptEditedProperty> edited_default_property_holder;
-
- UndoRedo *undo_redo = nullptr;
-
- Tree *members = nullptr;
- AcceptDialog *function_name_edit = nullptr;
- LineEdit *function_name_box = nullptr;
-
- Label *hint_text = nullptr;
- Timer *hint_text_timer = nullptr;
-
- Label *select_func_text = nullptr;
-
- bool updating_graph = false;
-
- void _show_hint(const String &p_hint);
- void _hide_timer();
-
- CreateDialog *select_base_type = nullptr;
-
- struct VirtualInMenu {
- String name;
- Variant::Type ret;
- bool ret_variant;
- Vector<Pair<Variant::Type, String>> args;
- };
-
- HashMap<StringName, Color> node_colors;
- HashMap<StringName, Ref<StyleBox>> node_styles;
- HashMap<StringName, Variant::Type> base_type_map;
-
- void _update_graph_connections();
- void _update_graph(int p_only_id = -1);
-
- bool updating_members = false;
-
- void _update_members();
- String _sanitized_variant_text(const StringName &property_name);
-
- StringName selected;
-
- String _validate_name(const String &p_name) const;
-
- struct Clipboard {
- HashMap<int, Ref<VisualScriptNode>> nodes;
- HashMap<int, Vector2> nodes_positions;
-
- RBSet<VisualScript::SequenceConnection> sequence_connections;
- RBSet<VisualScript::DataConnection> data_connections;
- };
-
- static Clipboard *clipboard;
-
- PopupMenu *popup_menu = nullptr;
- PopupMenu *member_popup = nullptr;
- MemberType member_type;
- String member_name;
-
- PortAction port_action;
- int port_action_node = 0;
- int port_action_output = 0;
- Vector2 port_action_pos;
- int port_action_new_node = 0;
-
- bool saved_pos_dirty = false;
-
- Vector2 mouse_up_position;
-
- void _port_action_menu(int p_option);
-
- void connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id);
-
- NodePath drop_path;
- Node *drop_node = nullptr;
- Vector2 drop_position;
- void _selected_connect_node(const String &p_text, const String &p_category, const bool p_connecting = true);
- void connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id);
-
- void _cancel_connect_node();
- int _create_new_node_from_name(const String &p_text, const Vector2 &p_point);
- void _selected_new_virtual_method(const String &p_text, const String &p_category, const bool p_connecting);
-
- int error_line = -1;
-
- void _node_selected(Node *p_node);
- void _center_on_node(int p_id);
-
- void _node_filter_changed(const String &p_text);
- void _change_base_type_callback();
- void _change_base_type();
- void _toggle_tool_script();
- void _member_selected();
- void _member_edited();
-
- void _begin_node_move();
- void _end_node_move();
- void _move_node(int p_id, const Vector2 &p_to);
-
- void _get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const RBSet<int> &p_selected, RBSet<int> &r_end_nodes);
-
- void _node_moved(Vector2 p_from, Vector2 p_to, int p_id);
- void _remove_node(int p_id);
- void _graph_connected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot);
- void _graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot);
- void _graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos);
-
- void _node_ports_changed(int p_id);
- void _node_create();
-
- void _update_available_nodes();
-
- void _member_button(Object *p_item, int p_column, int p_button, MouseButton p_mouse_button);
-
- void _expression_text_changed(const String &p_text, int p_id);
- void _add_input_port(int p_id);
- void _add_output_port(int p_id);
- void _remove_input_port(int p_id, int p_port);
- void _remove_output_port(int p_id, int p_port);
- void _change_port_type(int p_select, int p_id, int p_port, bool is_input);
- void _update_node_size(int p_id);
- void _port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input);
-
- Vector2 _get_pos_in_graph(Vector2 p_point) const;
- Vector2 _get_available_pos(bool p_centered = true, Vector2 p_pos = Vector2()) const;
-
- bool node_has_sequence_connections(int p_id);
-
- void _generic_search(Vector2 pos = Vector2(), bool node_centered = false);
-
- virtual void input(const Ref<InputEvent> &p_event) override;
- 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();
- void _create_function();
- void _add_func_input();
- void _remove_func_input(Node *p_node);
- void _deselect_input_names();
- void _add_node_dialog();
- void _node_item_selected();
- void _node_item_unselected();
-
- void _on_nodes_copy();
- void _on_nodes_paste();
- void _on_nodes_delete();
- void _on_nodes_duplicate();
-
- Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
- bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
- void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
-
- int editing_id = 0;
- int editing_input = 0;
-
- bool can_swap = false;
- int data_disconnect_node = 0;
- int data_disconnect_port = 0;
-
- void _default_value_changed(const StringName &p_property, const Variant &p_value, const String &p_field, bool p_changing);
- void _default_value_edited(Node *p_button, int p_id, int p_input_port);
-
- void _menu_option(int p_what);
-
- void _graph_ofs_changed(const Vector2 &p_ofs);
- void _comment_node_resized(const Vector2 &p_new_size, int p_node);
-
- void _draw_color_over_button(Object *obj, Color p_color);
- void _button_resource_previewed(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, Variant p_ud);
-
- VisualScriptNode::TypeGuess _guess_output_type(int p_port_action_node, int p_port_action_output, RBSet<int> &p_visited_nodes);
-
- void _member_rmb_selected(const Vector2 &p_pos, MouseButton p_button);
- void _member_option(int p_option);
-
- void _toggle_scripts_pressed();
-
-protected:
- void _notification(int p_what);
- static void _bind_methods();
-
-public:
- virtual void add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override;
- virtual void set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override;
-
- virtual void apply_code() override;
- virtual Ref<Resource> get_edited_resource() const override;
- virtual void set_edited_resource(const Ref<Resource> &p_res) override;
- virtual void enable_editor() override;
- virtual Vector<String> get_functions() override;
- virtual void reload_text() override;
- virtual String get_name() override;
- virtual Ref<Texture2D> get_theme_icon() override;
- virtual bool is_unsaved() override;
- virtual Variant get_edit_state() override;
- virtual void set_edit_state(const Variant &p_state) override;
- virtual void goto_line(int p_line, bool p_with_error = false) override;
- virtual void set_executing_line(int p_line) override;
- virtual void clear_executing_line() override;
- virtual void trim_trailing_whitespace() override;
- virtual void insert_final_newline() override;
- virtual void convert_indent_to_spaces() override;
- virtual void convert_indent_to_tabs() override;
- virtual void ensure_focus() override;
- virtual void tag_saved_version() override;
- virtual void reload(bool p_soft) override;
- virtual Array get_breakpoints() override;
- virtual void set_breakpoint(int p_line, bool p_enable) override{};
- virtual void clear_breakpoints() override{};
- virtual void add_callback(const String &p_function, PackedStringArray p_args) override;
- virtual void update_settings() override;
- virtual bool show_members_overview() override;
- virtual void set_debugger_active(bool p_active) override;
- virtual void set_tooltip_request_func(const Callable &p_toolip_callback) override;
- virtual Control *get_edit_menu() override;
- virtual void clear_edit_menu() override;
- virtual void set_find_replace_bar(FindReplaceBar *p_bar) override { p_bar->hide(); }; // Not needed here.
- virtual bool can_lose_focus_on_node_selection() override { return false; }
- virtual void validate() override;
-
- virtual Control *get_base_editor() const override;
-
- static void register_editor();
-
- static void free_clipboard();
-
- void update_toggle_scripts_button() override;
-
- VisualScriptEditor();
- ~VisualScriptEditor();
-};
-
-// Singleton
-class VisualScriptCustomNodes : public Object {
- GDCLASS(VisualScriptCustomNodes, Object);
-
- friend class VisualScriptLanguage;
-
-protected:
- static void _bind_methods();
- static VisualScriptCustomNodes *singleton;
-
- static HashMap<String, Ref<RefCounted>> custom_nodes;
- static Ref<VisualScriptNode> create_node_custom(const String &p_name);
-
-public:
- static VisualScriptCustomNodes *get_singleton() { return singleton; }
-
- void add_custom_node(const String &p_name, const String &p_category, const Ref<Script> &p_script);
- void remove_custom_node(const String &p_name, const String &p_category);
-
- VisualScriptCustomNodes();
- ~VisualScriptCustomNodes();
-};
-
-#endif
-
-#endif // VISUAL_SCRIPT_EDITOR_H
diff --git a/modules/visual_script/editor/visual_script_property_selector.cpp b/modules/visual_script/editor/visual_script_property_selector.cpp
deleted file mode 100644
index 712c89368b..0000000000
--- a/modules/visual_script/editor/visual_script_property_selector.cpp
+++ /dev/null
@@ -1,1277 +0,0 @@
-/*************************************************************************/
-/* visual_script_property_selector.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 "visual_script_property_selector.h"
-
-#include "../visual_script.h"
-#include "../visual_script_builtin_funcs.h"
-#include "../visual_script_flow_control.h"
-#include "../visual_script_func_nodes.h"
-#include "../visual_script_nodes.h"
-#include "core/os/keyboard.h"
-#include "editor/doc_tools.h"
-#include "editor/editor_feature_profile.h"
-#include "editor/editor_scale.h"
-#include "editor/editor_settings.h"
-#include "scene/main/node.h"
-#include "scene/main/window.h"
-
-void VisualScriptPropertySelector::_update_icons() {
- search_box->set_right_icon(results_tree->get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
- search_box->set_clear_button_enabled(true);
- search_box->add_theme_icon_override("right_icon", results_tree->get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
-
- search_visual_script_nodes->set_icon(results_tree->get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons")));
- search_classes->set_icon(results_tree->get_theme_icon(SNAME("Object"), SNAME("EditorIcons")));
- search_methods->set_icon(results_tree->get_theme_icon(SNAME("MemberMethod"), SNAME("EditorIcons")));
- search_operators->set_icon(results_tree->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
- search_signals->set_icon(results_tree->get_theme_icon(SNAME("MemberSignal"), SNAME("EditorIcons")));
- search_constants->set_icon(results_tree->get_theme_icon(SNAME("MemberConstant"), SNAME("EditorIcons")));
- search_properties->set_icon(results_tree->get_theme_icon(SNAME("MemberProperty"), SNAME("EditorIcons")));
- search_theme_items->set_icon(results_tree->get_theme_icon(SNAME("MemberTheme"), SNAME("EditorIcons")));
-
- case_sensitive_button->set_icon(results_tree->get_theme_icon(SNAME("MatchCase"), SNAME("EditorIcons")));
- hierarchy_button->set_icon(results_tree->get_theme_icon(SNAME("ClassList"), SNAME("EditorIcons")));
-}
-
-void VisualScriptPropertySelector::_sbox_input(const Ref<InputEvent> &p_ie) {
- Ref<InputEventKey> k = p_ie;
-
- if (k.is_valid()) {
- switch (k->get_keycode()) {
- case Key::UP:
- case Key::DOWN:
- case Key::PAGEUP:
- case Key::PAGEDOWN: {
- results_tree->gui_input(k);
- search_box->accept_event();
- } break;
- default:
- break;
- }
- }
-}
-
-void VisualScriptPropertySelector::_update_results_i(int p_int) {
- _update_results();
-}
-
-void VisualScriptPropertySelector::_update_results_s(String p_string) {
- _update_results();
-}
-
-void VisualScriptPropertySelector::_update_results_search_all() {
- if (search_classes->is_pressed()) {
- scope_combo->select(COMBO_ALL);
- }
- _update_results();
-}
-
-void VisualScriptPropertySelector::_update_results() {
- _update_icons();
- search_runner = Ref<SearchRunner>(memnew(SearchRunner(this, results_tree)));
- set_process(true);
-}
-
-void VisualScriptPropertySelector::_confirmed() {
- TreeItem *ti = results_tree->get_selected();
- if (!ti) {
- return;
- }
- emit_signal(SNAME("selected"), ti->get_metadata(0), ti->get_metadata(1), connecting);
- set_visible(false);
-}
-
-void VisualScriptPropertySelector::_item_selected() {
- help_bit->set_text(results_tree->get_selected()->get_meta("description", "No description available"));
-}
-
-void VisualScriptPropertySelector::_hide_requested() {
- _cancel_pressed(); // From AcceptDialog.
-}
-
-void VisualScriptPropertySelector::_notification(int p_what) {
- switch (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()) {
- if (search_runner->work()) {
- // Search done.
- get_ok_button()->set_disabled(!results_tree->get_selected());
-
- search_runner = Ref<SearchRunner>();
- set_process(false);
- }
- } else {
- // if one is valid
- set_process(false);
- }
- } break;
- }
-}
-
-void VisualScriptPropertySelector::select_method_from_base_type(const String &p_base, const bool p_virtuals_only, const bool p_connecting, bool clear_text) {
- set_title(TTR("Select method from base type"));
- base_type = p_base;
- base_script = "";
- type = Variant::NIL;
- connecting = p_connecting;
-
- if (clear_text) {
- if (p_virtuals_only) {
- search_box->set_text("._"); // show all _methods
- search_box->set_caret_column(2);
- } else {
- search_box->set_text("."); // show all methods
- search_box->set_caret_column(1);
- }
- }
-
- search_visual_script_nodes->set_pressed(false);
- search_classes->set_pressed(false);
- search_methods->set_pressed(true);
- search_operators->set_pressed(false);
- search_signals->set_pressed(false);
- search_constants->set_pressed(false);
- search_properties->set_pressed(false);
- search_theme_items->set_pressed(false);
-
- scope_combo->select(COMBO_BASE);
-
- results_tree->clear();
- show_window(.5f);
- search_box->grab_focus();
-
- _update_results();
-}
-
-void VisualScriptPropertySelector::select_from_base_type(const String &p_base, const String &p_base_script, bool p_virtuals_only, const bool p_connecting, bool clear_text) {
- set_title(TTR("Select from base type"));
- base_type = p_base;
- base_script = p_base_script.trim_prefix("res://").quote(); // filepath to EditorHelp::get_doc_data().name
- type = Variant::NIL;
- connecting = p_connecting;
-
- if (clear_text) {
- if (p_virtuals_only) {
- search_box->set_text("_");
- } else {
- search_box->set_text(" ");
- }
- }
- search_box->select_all();
-
- search_visual_script_nodes->set_pressed(false);
- search_classes->set_pressed(false);
- search_methods->set_pressed(true);
- search_operators->set_pressed(false);
- search_signals->set_pressed(true);
- search_constants->set_pressed(false);
- search_properties->set_pressed(true);
- search_theme_items->set_pressed(false);
-
- scope_combo->select(COMBO_RELATED);
-
- results_tree->clear();
- show_window(.5f);
- search_box->grab_focus();
- _update_results();
-}
-
-void VisualScriptPropertySelector::select_from_script(const Ref<Script> &p_script, const bool p_connecting, bool clear_text) {
- set_title(TTR("Select from script"));
- ERR_FAIL_COND(p_script.is_null());
-
- base_type = p_script->get_instance_base_type();
- base_script = p_script->get_path().trim_prefix("res://").quote(); // filepath to EditorHelp::get_doc_data().name
- type = Variant::NIL;
- script = p_script->get_instance_id();
- connecting = p_connecting;
-
- if (clear_text) {
- search_box->set_text("");
- }
- search_box->select_all();
-
- search_visual_script_nodes->set_pressed(false);
- search_classes->set_pressed(true);
- search_methods->set_pressed(true);
- search_operators->set_pressed(true);
- search_signals->set_pressed(true);
- search_constants->set_pressed(true);
- search_properties->set_pressed(true);
- search_theme_items->set_pressed(false);
-
- scope_combo->select(COMBO_BASE);
-
- results_tree->clear();
- show_window(.5f);
- search_box->grab_focus();
- _update_results();
-}
-
-void VisualScriptPropertySelector::select_from_basic_type(Variant::Type p_type, const bool p_connecting, bool clear_text) {
- set_title(TTR("Select from basic type"));
- ERR_FAIL_COND(p_type == Variant::NIL);
- base_type = Variant::get_type_name(p_type);
- base_script = "";
- type = p_type;
- connecting = p_connecting;
-
- if (clear_text) {
- search_box->set_text(" ");
- }
- search_box->select_all();
-
- search_visual_script_nodes->set_pressed(false);
- search_classes->set_pressed(false);
- search_methods->set_pressed(true);
- search_operators->set_pressed(true);
- search_signals->set_pressed(false);
- search_constants->set_pressed(true);
- search_properties->set_pressed(true);
- search_theme_items->set_pressed(false);
-
- scope_combo->select(COMBO_BASE);
-
- results_tree->clear();
- show_window(.5f);
- search_box->grab_focus();
-
- _update_results();
-}
-
-void VisualScriptPropertySelector::select_from_action(const String &p_type, const bool p_connecting, bool clear_text) {
- set_title(TTR("Select from action"));
- base_type = p_type;
- base_script = "";
- type = Variant::NIL;
- connecting = p_connecting;
-
- if (clear_text) {
- search_box->set_text("");
- }
- search_box->select_all();
-
- search_visual_script_nodes->set_pressed(true);
- search_classes->set_pressed(false);
- search_methods->set_pressed(false);
- search_operators->set_pressed(false);
- search_signals->set_pressed(false);
- search_constants->set_pressed(false);
- search_properties->set_pressed(false);
- search_theme_items->set_pressed(false);
-
- scope_combo->select(COMBO_RELATED);
-
- results_tree->clear();
- show_window(.5f);
- search_box->grab_focus();
- _update_results();
-}
-
-void VisualScriptPropertySelector::select_from_instance(Object *p_instance, const bool p_connecting, bool clear_text) {
- set_title(TTR("Select from instance"));
- base_type = p_instance->get_class();
-
- const Ref<Script> &p_script = p_instance->get_script();
- if (p_script == nullptr) {
- base_script = "";
- } else {
- base_script = p_script->get_path().trim_prefix("res://").quote(); // filepath to EditorHelp::get_doc_data().name
- }
-
- type = Variant::NIL;
- connecting = p_connecting;
-
- if (clear_text) {
- search_box->set_text(" ");
- }
- search_box->select_all();
-
- search_visual_script_nodes->set_pressed(false);
- search_classes->set_pressed(false);
- search_methods->set_pressed(true);
- search_operators->set_pressed(false);
- search_signals->set_pressed(true);
- search_constants->set_pressed(true);
- search_properties->set_pressed(true);
- search_theme_items->set_pressed(false);
-
- scope_combo->select(COMBO_BASE);
-
- results_tree->clear();
- show_window(.5f);
- search_box->grab_focus();
- _update_results();
-}
-
-void VisualScriptPropertySelector::select_from_visual_script(const Ref<Script> &p_script, bool clear_text) {
- set_title(TTR("Select from visual script"));
- base_type = p_script->get_instance_base_type();
- if (p_script == nullptr) {
- base_script = "";
- } else {
- base_script = p_script->get_path().trim_prefix("res://").quote(); // filepath to EditorHelp::get_doc_data().name
- }
- type = Variant::NIL;
- connecting = false;
-
- if (clear_text) {
- search_box->set_text(" ");
- }
- search_box->select_all();
-
- search_visual_script_nodes->set_pressed(true);
- search_classes->set_pressed(false);
- search_methods->set_pressed(true);
- search_operators->set_pressed(false);
- search_signals->set_pressed(true);
- search_constants->set_pressed(true);
- search_properties->set_pressed(true);
- search_theme_items->set_pressed(false);
-
- scope_combo->select(COMBO_BASE);
-
- results_tree->clear();
- show_window(.5f);
- search_box->grab_focus();
- _update_results();
-}
-
-void VisualScriptPropertySelector::show_window(float p_screen_ratio) {
- popup_centered_ratio(p_screen_ratio);
-}
-
-void VisualScriptPropertySelector::_bind_methods() {
- ADD_SIGNAL(MethodInfo("selected", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "category"), PropertyInfo(Variant::BOOL, "connecting")));
-}
-
-VisualScriptPropertySelector::VisualScriptPropertySelector() {
- vbox = memnew(VBoxContainer);
- add_child(vbox);
-
- HBoxContainer *hbox = memnew(HBoxContainer);
- hbox->set_alignment(hbox->ALIGNMENT_CENTER);
- vbox->add_child(hbox);
-
- case_sensitive_button = memnew(Button);
- case_sensitive_button->set_flat(true);
- case_sensitive_button->set_tooltip(TTR("Case Sensitive"));
- case_sensitive_button->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- case_sensitive_button->set_toggle_mode(true);
- case_sensitive_button->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(case_sensitive_button);
-
- hierarchy_button = memnew(Button);
- hierarchy_button->set_flat(true);
- hierarchy_button->set_tooltip(TTR("Show Hierarchy"));
- hierarchy_button->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- hierarchy_button->set_toggle_mode(true);
- hierarchy_button->set_pressed(true);
- hierarchy_button->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(hierarchy_button);
-
- hbox->add_child(memnew(VSeparator));
-
- search_visual_script_nodes = memnew(Button);
- search_visual_script_nodes->set_flat(true);
- search_visual_script_nodes->set_tooltip(TTR("Search Visual Script Nodes"));
- search_visual_script_nodes->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- search_visual_script_nodes->set_toggle_mode(true);
- search_visual_script_nodes->set_pressed(true);
- search_visual_script_nodes->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_visual_script_nodes);
-
- search_classes = memnew(Button);
- search_classes->set_flat(true);
- search_classes->set_tooltip(TTR("Search Classes"));
- search_classes->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results_search_all));
- search_classes->set_toggle_mode(true);
- search_classes->set_pressed(true);
- search_classes->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_classes);
-
- search_operators = memnew(Button);
- search_operators->set_flat(true);
- search_operators->set_tooltip(TTR("Search Operators"));
- search_operators->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- search_operators->set_toggle_mode(true);
- search_operators->set_pressed(true);
- search_operators->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_operators);
-
- hbox->add_child(memnew(VSeparator));
-
- search_methods = memnew(Button);
- search_methods->set_flat(true);
- search_methods->set_tooltip(TTR("Search Methods"));
- search_methods->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- search_methods->set_toggle_mode(true);
- search_methods->set_pressed(true);
- search_methods->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_methods);
-
- search_signals = memnew(Button);
- search_signals->set_flat(true);
- search_signals->set_tooltip(TTR("Search Signals"));
- search_signals->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- search_signals->set_toggle_mode(true);
- search_signals->set_pressed(true);
- search_signals->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_signals);
-
- search_constants = memnew(Button);
- search_constants->set_flat(true);
- search_constants->set_tooltip(TTR("Search Constants"));
- search_constants->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- search_constants->set_toggle_mode(true);
- search_constants->set_pressed(true);
- search_constants->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_constants);
-
- search_properties = memnew(Button);
- search_properties->set_flat(true);
- search_properties->set_tooltip(TTR("Search Properties"));
- search_properties->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- search_properties->set_toggle_mode(true);
- search_properties->set_pressed(true);
- search_properties->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_properties);
-
- search_theme_items = memnew(Button);
- search_theme_items->set_flat(true);
- search_theme_items->set_tooltip(TTR("Search Theme Items"));
- search_theme_items->connect("pressed", callable_mp(this, &VisualScriptPropertySelector::_update_results));
- search_theme_items->set_toggle_mode(true);
- search_theme_items->set_pressed(true);
- search_theme_items->set_focus_mode(Control::FOCUS_NONE);
- hbox->add_child(search_theme_items);
-
- scope_combo = memnew(OptionButton);
- scope_combo->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
- scope_combo->set_tooltip(TTR("Select the search limits"));
- scope_combo->set_stretch_ratio(0); // Fixed width.
- scope_combo->add_item(TTR("Search Related"), SCOPE_RELATED);
- scope_combo->add_separator();
- scope_combo->add_item(TTR("Search Base"), SCOPE_BASE);
- scope_combo->add_item(TTR("Search Inheriters"), SCOPE_INHERITERS);
- scope_combo->add_item(TTR("Search Unrelated"), SCOPE_UNRELATED);
- scope_combo->add_item(TTR("Search All"), SCOPE_ALL);
- scope_combo->connect("item_selected", callable_mp(this, &VisualScriptPropertySelector::_update_results_i));
- hbox->add_child(scope_combo);
-
- search_box = memnew(LineEdit);
- 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));
- search_box->connect("gui_input", callable_mp(this, &VisualScriptPropertySelector::_sbox_input));
- register_text_enter(search_box);
- vbox->add_child(search_box);
-
- results_tree = memnew(Tree);
- results_tree->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- results_tree->set_hide_root(true);
- results_tree->set_hide_folding(false);
- results_tree->set_columns(2);
- results_tree->set_column_title(0, TTR("Name"));
- results_tree->set_column_clip_content(0, true);
- results_tree->set_column_title(1, TTR("Member Type"));
- results_tree->set_column_expand(1, false);
- results_tree->set_column_custom_minimum_width(1, 150 * EDSCALE);
- results_tree->set_column_clip_content(1, true);
- results_tree->set_custom_minimum_size(Size2(0, 100) * EDSCALE);
- results_tree->set_select_mode(Tree::SELECT_ROW);
- results_tree->connect("item_activated", callable_mp(this, &VisualScriptPropertySelector::_confirmed));
- results_tree->connect("item_selected", callable_mp(this, &VisualScriptPropertySelector::_item_selected));
- vbox->add_child(results_tree);
-
- ScrollContainer *scroller = memnew(ScrollContainer);
- scroller->set_horizontal_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
- scroller->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- scroller->set_custom_minimum_size(Size2(600, 400) * EDSCALE);
- vbox->add_child(scroller);
-
- help_bit = memnew(EditorHelpBit);
- help_bit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
- help_bit->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- scroller->add_child(help_bit);
-
- help_bit->connect("request_hide", callable_mp(this, &VisualScriptPropertySelector::_hide_requested));
- set_ok_button_text(TTR("Open"));
- get_ok_button()->set_disabled(true);
- set_hide_on_ok(false);
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_is_class_disabled_by_feature_profile(const StringName &p_class) {
- Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
- if (profile.is_null()) {
- return false;
- }
-
- StringName class_name = p_class;
- while (class_name != StringName()) {
- if (!ClassDB::class_exists(class_name)) {
- return false;
- }
-
- if (profile->is_class_disabled(class_name)) {
- return true;
- }
- class_name = ClassDB::get_parent_class(class_name);
- }
-
- return false;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_is_class_disabled_by_scope(const StringName &p_class) {
- bool is_base_script = false;
- if (p_class == selector_ui->base_script) {
- is_base_script = true;
- }
- bool is_base = false;
- if (selector_ui->base_type == p_class) {
- is_base = true;
- }
- bool is_parent = false;
- if ((ClassDB::is_parent_class(selector_ui->base_type, p_class)) && !is_base) {
- is_parent = true;
- }
-
- bool is_inheriter = false;
- List<StringName> inheriters;
- ClassDB::get_inheriters_from_class(selector_ui->base_type, &inheriters);
- if (inheriters.find(p_class)) {
- is_inheriter = true;
- }
-
- if (scope_flags & SCOPE_BASE) {
- if (is_base_script || is_base || is_parent) {
- return false;
- }
- }
- if (scope_flags & SCOPE_INHERITERS) {
- if (is_base_script || is_base || is_inheriter) {
- return false;
- }
- }
- // if (scope_flags & SCOPE_RELATED) {
- // /* code */
- // }
- if (scope_flags & SCOPE_UNRELATED) {
- if (!is_base_script && !is_base && !is_inheriter) {
- return false;
- }
- }
- return true;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_slice() {
- bool phase_done = false;
- switch (phase) {
- case PHASE_INIT:
- phase_done = _phase_init();
- break;
- case PHASE_MATCH_CLASSES_INIT:
- phase_done = _phase_match_classes_init();
- break;
- case PHASE_NODE_CLASSES_INIT:
- phase_done = _phase_node_classes_init();
- break;
- case PHASE_NODE_CLASSES_BUILD:
- phase_done = _phase_node_classes_build();
- break;
- case PHASE_MATCH_CLASSES:
- phase_done = _phase_match_classes();
- break;
- case PHASE_CLASS_ITEMS_INIT:
- phase_done = _phase_class_items_init();
- break;
- case PHASE_CLASS_ITEMS:
- phase_done = _phase_class_items();
- break;
- case PHASE_MEMBER_ITEMS_INIT:
- phase_done = _phase_member_items_init();
- break;
- case PHASE_MEMBER_ITEMS:
- phase_done = _phase_member_items();
- break;
- case PHASE_SELECT_MATCH:
- phase_done = _phase_select_match();
- break;
- case PHASE_MAX:
- return true;
- default:
- WARN_PRINT("Invalid or unhandled phase in EditorHelpSearch::Runner, aborting search.");
- return true;
- };
-
- if (phase_done) {
- phase++;
- }
- return false;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_init() {
- search_flags = 0; // selector_ui->filter_combo->get_selected_id();
- if (selector_ui->search_visual_script_nodes->is_pressed()) {
- search_flags |= SEARCH_VISUAL_SCRIPT_NODES;
- }
- if (selector_ui->search_classes->is_pressed()) {
- search_flags |= SEARCH_CLASSES;
- }
- // if (selector_ui->search_constructors->is_pressed()) {
- search_flags |= SEARCH_CONSTRUCTORS;
- // }
- if (selector_ui->search_methods->is_pressed()) {
- search_flags |= SEARCH_METHODS;
- }
- if (selector_ui->search_operators->is_pressed()) {
- search_flags |= SEARCH_OPERATORS;
- }
- if (selector_ui->search_signals->is_pressed()) {
- search_flags |= SEARCH_SIGNALS;
- }
- if (selector_ui->search_constants->is_pressed()) {
- search_flags |= SEARCH_CONSTANTS;
- }
- if (selector_ui->search_properties->is_pressed()) {
- search_flags |= SEARCH_PROPERTIES;
- }
- if (selector_ui->search_theme_items->is_pressed()) {
- search_flags |= SEARCH_THEME_ITEMS;
- }
- if (selector_ui->case_sensitive_button->is_pressed()) {
- search_flags |= SEARCH_CASE_SENSITIVE;
- }
- if (selector_ui->hierarchy_button->is_pressed()) {
- search_flags |= SEARCH_SHOW_HIERARCHY;
- }
- scope_flags = selector_ui->scope_combo->get_selected_id();
-
- return true;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_match_classes_init() {
- combined_docs = EditorHelp::get_doc_data()->class_list;
- matches.clear();
- matched_item = nullptr;
- match_highest_score = 0;
-
- if (
- (selector_ui->base_script.unquote() != "") &&
- (selector_ui->base_script.unquote() != ".") &&
- !combined_docs.has(selector_ui->base_script)) {
- String file_path = "res://" + selector_ui->base_script.unquote(); // EditorHelp::get_doc_data().name to filepath
- Ref<Script> script;
- script = ResourceLoader::load(file_path);
- if (!script.is_null()) {
- DocData::ClassDoc class_doc = DocData::ClassDoc();
-
- class_doc.name = selector_ui->base_script;
-
- class_doc.inherits = script->get_instance_base_type();
- 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());
- if (Object::cast_to<Script>(obj)) {
- List<MethodInfo> methods;
- Object::cast_to<Script>(obj)->get_script_method_list(&methods);
- for (List<MethodInfo>::Element *M = methods.front(); M; M = M->next()) {
- class_doc.methods.push_back(_get_method_doc(M->get()));
- }
-
- List<MethodInfo> signals;
- Object::cast_to<Script>(obj)->get_script_signal_list(&signals);
- for (List<MethodInfo>::Element *S = signals.front(); S; S = S->next()) {
- class_doc.signals.push_back(_get_method_doc(S->get()));
- }
-
- 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);
- class_doc.properties.push_back(pd);
- }
- }
- combined_docs.insert(class_doc.name, class_doc);
- }
- }
- iterator_doc = combined_docs.begin();
- return true;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_node_classes_init() {
- VisualScriptLanguage::singleton->get_registered_node_names(&vs_nodes);
- _add_class_doc("functions", "", "");
- _add_class_doc("operators", "", "");
- return true;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_node_classes_build() {
- if (vs_nodes.is_empty()) {
- return true;
- }
- String registered_node_name = vs_nodes[0];
- vs_nodes.pop_front();
-
- Vector<String> path = registered_node_name.split("/");
- if (path[0] == "constants") {
- _add_class_doc(registered_node_name, "", "constants");
- } else if (path[0] == "custom") {
- _add_class_doc(registered_node_name, "", "custom");
- } else if (path[0] == "data") {
- _add_class_doc(registered_node_name, "", "data");
- } else if (path[0] == "flow_control") {
- _add_class_doc(registered_node_name, "", "flow_control");
- } else if (path[0] == "functions") {
- if (path[1] == "built_in") {
- _add_class_doc(registered_node_name, "functions", "built_in");
- } else if (path[1] == "by_type") {
- // No action is required.
- // Using function references from ClassDB to remove confusion for users.
- } else if (path[1] == "constructors") {
- _add_class_doc(registered_node_name, "", "constructors");
- } else if (path[1] == "deconstruct") {
- _add_class_doc(registered_node_name, "", "deconstruct");
- } else if (path[1] == "wait") {
- _add_class_doc(registered_node_name, "functions", "yield");
- } else {
- _add_class_doc(registered_node_name, "functions", "");
- }
- } else if (path[0] == "index") {
- _add_class_doc(registered_node_name, "", "index");
- } else if (path[0] == "operators") {
- if (path[1] == "bitwise") {
- _add_class_doc(registered_node_name, "operators", "bitwise");
- } else if (path[1] == "compare") {
- _add_class_doc(registered_node_name, "operators", "compare");
- } else if (path[1] == "logic") {
- _add_class_doc(registered_node_name, "operators", "logic");
- } else if (path[1] == "math") {
- _add_class_doc(registered_node_name, "operators", "math");
- } else {
- _add_class_doc(registered_node_name, "operators", "");
- }
- }
- return false;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_match_classes() {
- DocData::ClassDoc &class_doc = iterator_doc->value;
- if (
- (!_is_class_disabled_by_feature_profile(class_doc.name) && !_is_class_disabled_by_scope(class_doc.name)) ||
- _match_visual_script(class_doc)) {
- if (class_doc.inherits == "VisualScriptCustomNode") {
- class_doc.script_path = "res://" + class_doc.name.unquote();
- Ref<Script> script = ResourceLoader::load(class_doc.script_path);
- Ref<VisualScriptCustomNode> vsn;
- vsn.instantiate();
- vsn->set_script(script);
- class_doc.name = vsn->get_caption();
- if (combined_docs.has(vsn->get_category())) {
- class_doc.inherits = vsn->get_category();
- } else if (combined_docs.has("VisualScriptNode/" + vsn->get_category())) {
- class_doc.inherits = "VisualScriptNode/" + vsn->get_category();
- } else if (combined_docs.has("VisualScriptCustomNode/" + vsn->get_category())) {
- class_doc.inherits = "VisualScriptCustomNode/" + vsn->get_category();
- } else {
- class_doc.inherits = "";
- }
- class_doc.category = "VisualScriptCustomNode/" + vsn->get_category();
- class_doc.brief_description = "";
- class_doc.constructors.clear();
- class_doc.methods.clear();
- class_doc.operators.clear();
- class_doc.signals.clear();
- class_doc.constants.clear();
- class_doc.enums.clear();
- class_doc.properties.clear();
- class_doc.theme_properties.clear();
- }
-
- matches[class_doc.name] = ClassMatch();
- ClassMatch &match = matches[class_doc.name];
-
- match.category = class_doc.category;
- match.doc = &class_doc;
- // Match class name.
- if (search_flags & SEARCH_CLASSES || _match_visual_script(class_doc)) {
- if (term == "") {
- match.name = !_match_is_hidden(class_doc);
- } else {
- match.name = _match_string(term, class_doc.name);
- }
- // match.name = term == "" || _match_string(term, class_doc.name);
- }
-
- // Match members if the term is long enough.
- if (term.length() >= 0) {
- if (search_flags & SEARCH_CONSTRUCTORS) {
- for (int i = 0; i < class_doc.constructors.size(); i++) {
- String method_name = (search_flags & SEARCH_CASE_SENSITIVE) ? class_doc.constructors[i].name : class_doc.constructors[i].name.to_lower();
- if (method_name.find(term) > -1 ||
- term == " " ||
- (term.begins_with(".") && method_name.begins_with(term.substr(1))) ||
- (term.ends_with("(") && method_name.ends_with(term.left(term.length() - 1).strip_edges())) ||
- (term.begins_with(".") && term.ends_with("(") && method_name == term.substr(1, term.length() - 2).strip_edges())) {
- match.constructors.push_back(const_cast<DocData::MethodDoc *>(&class_doc.constructors[i]));
- }
- }
- }
- if (search_flags & SEARCH_METHODS) {
- for (int i = 0; i < class_doc.methods.size(); i++) {
- String method_name = (search_flags & SEARCH_CASE_SENSITIVE) ? class_doc.methods[i].name : class_doc.methods[i].name.to_lower();
- if (method_name.find(term) > -1 ||
- term == " " ||
- (term.begins_with(".") && method_name.begins_with(term.substr(1))) ||
- (term.ends_with("(") && method_name.ends_with(term.left(term.length() - 1).strip_edges())) ||
- (term.begins_with(".") && term.ends_with("(") && method_name == term.substr(1, term.length() - 2).strip_edges())) {
- match.methods.push_back(const_cast<DocData::MethodDoc *>(&class_doc.methods[i]));
- }
- }
- }
- if (search_flags & SEARCH_OPERATORS) {
- for (int i = 0; i < class_doc.operators.size(); i++) {
- String method_name = (search_flags & SEARCH_CASE_SENSITIVE) ? class_doc.operators[i].name : class_doc.operators[i].name.to_lower();
- if (method_name.find(term) > -1 ||
- term == " " ||
- (term.begins_with(".") && method_name.begins_with(term.substr(1))) ||
- (term.ends_with("(") && method_name.ends_with(term.left(term.length() - 1).strip_edges())) ||
- (term.begins_with(".") && term.ends_with("(") && method_name == term.substr(1, term.length() - 2).strip_edges())) {
- match.operators.push_back(const_cast<DocData::MethodDoc *>(&class_doc.operators[i]));
- }
- }
- }
- if (search_flags & SEARCH_SIGNALS) {
- for (int i = 0; i < class_doc.signals.size(); i++) {
- if (_match_string(term, class_doc.signals[i].name) ||
- term == " ") {
- match.signals.push_back(const_cast<DocData::MethodDoc *>(&class_doc.signals[i]));
- }
- }
- }
- if (search_flags & SEARCH_CONSTANTS) {
- for (int i = 0; i < class_doc.constants.size(); i++) {
- if (_match_string(term, class_doc.constants[i].name) ||
- term == " ") {
- match.constants.push_back(const_cast<DocData::ConstantDoc *>(&class_doc.constants[i]));
- }
- }
- }
- if (search_flags & SEARCH_PROPERTIES) {
- for (int i = 0; i < class_doc.properties.size(); i++) {
- if (_match_string(term, class_doc.properties[i].name) ||
- term == " " ||
- _match_string(term, class_doc.properties[i].getter) ||
- _match_string(term, class_doc.properties[i].setter)) {
- match.properties.push_back(const_cast<DocData::PropertyDoc *>(&class_doc.properties[i]));
- }
- }
- }
- if (search_flags & SEARCH_THEME_ITEMS) {
- for (int i = 0; i < class_doc.theme_properties.size(); i++) {
- if (_match_string(term, class_doc.theme_properties[i].name) ||
- term == " ") {
- match.theme_properties.push_back(const_cast<DocData::ThemeItemDoc *>(&class_doc.theme_properties[i]));
- }
- }
- }
- }
- }
-
- ++iterator_doc;
- return !iterator_doc;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_class_items_init() {
- results_tree->clear();
- iterator_match = matches.begin();
-
- root_item = results_tree->create_item();
- class_items.clear();
-
- return true;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_class_items() {
- if (!iterator_match) {
- return true;
- }
-
- ClassMatch &match = iterator_match->value;
-
- if (search_flags & SEARCH_SHOW_HIERARCHY) {
- if (match.required()) {
- _create_class_hierarchy(match);
- }
- } else {
- if (match.name) {
- _create_class_item(root_item, match.doc, true);
- }
- }
-
- ++iterator_match;
- return !iterator_match;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_member_items_init() {
- iterator_match = matches.begin();
-
- return true;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_member_items() {
- if (!iterator_match) {
- return true;
- }
-
- ClassMatch &match = iterator_match->value;
-
- TreeItem *parent = (search_flags & SEARCH_SHOW_HIERARCHY) ? class_items[match.doc->name] : root_item;
- bool constructor_created = false;
- for (int i = 0; i < match.methods.size(); i++) {
- String text = match.methods[i]->name;
- if (!constructor_created) {
- if (match.doc->name == match.methods[i]->name) {
- text += " " + TTR("(constructors)");
- constructor_created = true;
- }
- } else {
- if (match.doc->name == match.methods[i]->name) {
- continue;
- }
- }
- _create_method_item(parent, match.doc, text, match.methods[i]);
- }
- for (int i = 0; i < match.signals.size(); i++) {
- _create_signal_item(parent, match.doc, match.signals[i]);
- }
- for (int i = 0; i < match.constants.size(); i++) {
- _create_constant_item(parent, match.doc, match.constants[i]);
- }
- for (int i = 0; i < match.properties.size(); i++) {
- _create_property_item(parent, match.doc, match.properties[i]);
- }
- for (int i = 0; i < match.theme_properties.size(); i++) {
- _create_theme_property_item(parent, match.doc, match.theme_properties[i]);
- }
-
- ++iterator_match;
- return !iterator_match;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_phase_select_match() {
- if (matched_item) {
- matched_item->select(0);
- }
- return true;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_match_string(const String &p_term, const String &p_string) const {
- if (search_flags & SEARCH_CASE_SENSITIVE) {
- return p_string.find(p_term) > -1;
- } else {
- return p_string.findn(p_term) > -1;
- }
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_match_visual_script(DocData::ClassDoc &class_doc) {
- if (class_doc.category.ends_with("_class")) {
- if (class_doc.category.begins_with("VisualScript") && search_flags & SEARCH_CLASSES) {
- if (matches.has(class_doc.inherits)) {
- return true;
- }
- }
- return false;
- }
- if (class_doc.category.begins_with("VisualScript") && search_flags & SEARCH_VISUAL_SCRIPT_NODES) {
- return true;
- }
- if (class_doc.name.begins_with("operators") && search_flags & SEARCH_OPERATORS) {
- return true;
- }
- if (class_doc.category.begins_with("VisualScriptNode/deconstruct")) {
- if (class_doc.name.find(selector_ui->base_type, 0) > -1) {
- return true;
- }
- }
-
- return false;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::_match_is_hidden(DocData::ClassDoc &class_doc) {
- if (class_doc.category.begins_with("VisualScript")) {
- if (class_doc.name.begins_with("flow_control")) {
- return false;
- } else if (class_doc.name.begins_with("operators")) {
- return !(search_flags & SEARCH_OPERATORS);
- } else if (class_doc.name.begins_with("functions/built_in/print")) {
- return false;
- }
- return true;
- }
- return false;
-}
-
-void VisualScriptPropertySelector::SearchRunner::_match_item(TreeItem *p_item, const String &p_text) {
- float inverse_length = 1.f / float(p_text.length());
-
- // Favor types where search term is a substring close to the start of the type.
- float w = 0.5f;
- int pos = p_text.findn(term);
- float score = (pos > -1) ? 1.0f - w * MIN(1, 3 * pos * inverse_length) : MAX(0.f, .9f - w);
-
- // Favor shorter items: they resemble the search term more.
- w = 0.1f;
- score *= (1 - w) + w * (term.length() * inverse_length);
-
- if (match_highest_score == 0 || score > match_highest_score) {
- matched_item = p_item;
- match_highest_score = score;
- }
-}
-
-void VisualScriptPropertySelector::SearchRunner::_add_class_doc(String class_name, String inherits, String category) {
- DocData::ClassDoc class_doc = DocData::ClassDoc();
- class_doc.name = class_name;
- class_doc.inherits = inherits;
- class_doc.category = "VisualScriptNode/" + category;
- class_doc.brief_description = category;
- combined_docs.insert(class_doc.name, class_doc);
-}
-
-DocData::MethodDoc VisualScriptPropertySelector::SearchRunner::_get_method_doc(MethodInfo method_info) {
- DocData::MethodDoc method_doc = DocData::MethodDoc();
- method_doc.name = method_info.name;
- method_doc.return_type = Variant::get_type_name(method_info.return_val.type);
- method_doc.description = "No description available";
- for (List<PropertyInfo>::Element *P = method_info.arguments.front(); P; P = P->next()) {
- DocData::ArgumentDoc argument_doc = DocData::ArgumentDoc();
- argument_doc.name = P->get().name;
- argument_doc.type = Variant::get_type_name(P->get().type);
- method_doc.arguments.push_back(argument_doc);
- }
- return method_doc;
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_class_hierarchy(const ClassMatch &p_match) {
- if (class_items.has(p_match.doc->name)) {
- return class_items[p_match.doc->name];
- }
-
- // Ensure parent nodes are created first.
- TreeItem *parent = root_item;
- if (p_match.doc->inherits != "") {
- if (class_items.has(p_match.doc->inherits)) {
- parent = class_items[p_match.doc->inherits];
- } else if (matches.has(p_match.doc->inherits)) {
- ClassMatch &base_match = matches[p_match.doc->inherits];
- parent = _create_class_hierarchy(base_match);
- }
- }
-
- TreeItem *class_item = _create_class_item(parent, p_match.doc, !p_match.name);
- class_items[p_match.doc->name] = class_item;
- return class_item;
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_class_item(TreeItem *p_parent, const DocData::ClassDoc *p_doc, bool p_gray) {
- Ref<Texture2D> icon = empty_icon;
- String text_0 = p_doc->name;
- String text_1 = "Class";
-
- String what = "Class";
- String details = p_doc->name;
- if (p_doc->category.begins_with("VisualScriptCustomNode/")) {
- Vector<String> path = p_doc->name.split("/");
- icon = ui_service->get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons"));
- text_0 = path[path.size() - 1];
- text_1 = "VisualScriptCustomNode";
- what = "VisualScriptCustomNode";
- details = "CustomNode";
- } else if (p_doc->category.begins_with("VisualScriptNode/")) {
- Vector<String> path = p_doc->name.split("/");
- icon = ui_service->get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons"));
- text_0 = path[path.size() - 1];
- if (p_doc->category.begins_with("VisualScriptNode/deconstruct")) {
- text_0 = "deconstruct " + text_0;
- }
- text_1 = "VisualScriptNode";
- what = "VisualScriptNode";
- details = p_doc->name;
-
- if (path.size() == 1) {
- if (path[0] == "functions" || path[0] == "operators") {
- text_1 = "VisualScript";
- p_gray = true;
- what = "no_result";
- details = "";
- }
- }
-
- } else {
- if (p_doc->name.is_quoted()) {
- text_0 = p_doc->name.unquote().get_file();
- if (ui_service->has_theme_icon(p_doc->inherits, "EditorIcons")) {
- icon = ui_service->get_theme_icon(p_doc->inherits, "EditorIcons");
- }
- } else if (ui_service->has_theme_icon(p_doc->name, "EditorIcons")) {
- icon = ui_service->get_theme_icon(p_doc->name, "EditorIcons");
- } else if (ClassDB::class_exists(p_doc->name) && ClassDB::is_parent_class(p_doc->name, "Object")) {
- icon = ui_service->get_theme_icon(SNAME("Object"), SNAME("EditorIcons"));
- }
- }
- String tooltip = p_doc->brief_description.strip_edges();
-
- TreeItem *item = results_tree->create_item(p_parent);
- item->set_icon(0, icon);
- item->set_text(0, text_0);
- item->set_text(1, TTR(text_1));
- item->set_tooltip(0, tooltip);
- item->set_tooltip(1, tooltip);
- item->set_metadata(0, details);
- item->set_metadata(1, what);
- if (p_gray) {
- item->set_custom_color(0, disabled_color);
- item->set_custom_color(1, disabled_color);
- }
-
- _match_item(item, p_doc->name);
-
- return item;
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_method_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const String &p_text, const DocData::MethodDoc *p_doc) {
- String tooltip = p_doc->return_type + " " + p_class_doc->name + "." + p_doc->name + "(";
- for (int i = 0; i < p_doc->arguments.size(); i++) {
- const DocData::ArgumentDoc &arg = p_doc->arguments[i];
- tooltip += arg.type + " " + arg.name;
- if (arg.default_value != "") {
- tooltip += " = " + arg.default_value;
- }
- if (i < p_doc->arguments.size() - 1) {
- tooltip += ", ";
- }
- }
- tooltip += ")";
- return _create_member_item(p_parent, p_class_doc->name, "MemberMethod", p_doc->name, p_text, TTRC("Method"), "method", tooltip, p_doc->description);
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_signal_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::MethodDoc *p_doc) {
- String tooltip = p_doc->return_type + " " + p_class_doc->name + "." + p_doc->name + "(";
- for (int i = 0; i < p_doc->arguments.size(); i++) {
- const DocData::ArgumentDoc &arg = p_doc->arguments[i];
- tooltip += arg.type + " " + arg.name;
- if (arg.default_value != "") {
- tooltip += " = " + arg.default_value;
- }
- if (i < p_doc->arguments.size() - 1) {
- tooltip += ", ";
- }
- }
- tooltip += ")";
- return _create_member_item(p_parent, p_class_doc->name, "MemberSignal", p_doc->name, p_doc->name, TTRC("Signal"), "signal", tooltip, p_doc->description);
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_constant_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::ConstantDoc *p_doc) {
- String tooltip = p_class_doc->name + "." + p_doc->name;
- return _create_member_item(p_parent, p_class_doc->name, "MemberConstant", p_doc->name, p_doc->name, TTRC("Constant"), "constant", tooltip, p_doc->description);
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_property_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::PropertyDoc *p_doc) {
- String tooltip = p_doc->type + " " + p_class_doc->name + "." + p_doc->name;
- tooltip += "\n " + p_class_doc->name + "." + p_doc->setter + "(value) setter";
- tooltip += "\n " + p_class_doc->name + "." + p_doc->getter + "() getter";
- return _create_member_item(p_parent, p_class_doc->name, "MemberProperty", p_doc->name, p_doc->name, TTRC("Property"), "property", tooltip, p_doc->description);
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_theme_property_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::ThemeItemDoc *p_doc) {
- String tooltip = p_doc->type + " " + p_class_doc->name + "." + p_doc->name;
- return _create_member_item(p_parent, p_class_doc->name, "MemberTheme", p_doc->name, p_doc->name, TTRC("Theme Property"), "theme_item", tooltip, p_doc->description);
-}
-
-TreeItem *VisualScriptPropertySelector::SearchRunner::_create_member_item(TreeItem *p_parent, const String &p_class_name, const String &p_icon, const String &p_name, const String &p_text, const String &p_type, const String &p_metatype, const String &p_tooltip, const String &p_description) {
- Ref<Texture2D> icon;
- String text;
- if (search_flags & SEARCH_SHOW_HIERARCHY) {
- icon = ui_service->get_theme_icon(p_icon, SNAME("EditorIcons"));
- text = p_text;
- } else {
- icon = ui_service->get_theme_icon(p_icon, SNAME("EditorIcons"));
- text = p_class_name + "." + p_text;
- }
-
- TreeItem *item = results_tree->create_item(p_parent);
- item->set_icon(0, icon);
- item->set_text(0, text);
- item->set_text(1, TTRGET(p_type));
- item->set_tooltip(0, p_tooltip);
- item->set_tooltip(1, p_tooltip);
- item->set_metadata(0, p_class_name + ":" + p_name);
- item->set_metadata(1, "class_" + p_metatype);
- item->set_meta("description", p_description);
-
- _match_item(item, p_name);
-
- return item;
-}
-
-bool VisualScriptPropertySelector::SearchRunner::work(uint64_t slot) {
- // Return true when the search has been completed, otherwise false.
- const uint64_t until = OS::get_singleton()->get_ticks_usec() + slot;
- while (!_slice()) {
- if (OS::get_singleton()->get_ticks_usec() > until) {
- return false;
- }
- }
- return true;
-}
-
-VisualScriptPropertySelector::SearchRunner::SearchRunner(VisualScriptPropertySelector *p_selector_ui, Tree *p_results_tree) :
- selector_ui(p_selector_ui),
- ui_service(p_selector_ui->vbox),
- results_tree(p_results_tree),
- term(p_selector_ui->search_box->get_text()),
- empty_icon(ui_service->get_theme_icon(SNAME("ArrowRight"), SNAME("EditorIcons"))),
- disabled_color(ui_service->get_theme_color(SNAME("disabled_font_color"), SNAME("Editor"))) {
-}
diff --git a/modules/visual_script/editor/visual_script_property_selector.h b/modules/visual_script/editor/visual_script_property_selector.h
deleted file mode 100644
index 4de626467e..0000000000
--- a/modules/visual_script/editor/visual_script_property_selector.h
+++ /dev/null
@@ -1,229 +0,0 @@
-/*************************************************************************/
-/* visual_script_property_selector.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 VISUAL_SCRIPT_PROPERTY_SELECTOR_H
-#define VISUAL_SCRIPT_PROPERTY_SELECTOR_H
-
-#include "../visual_script.h"
-#include "editor/editor_help.h"
-#include "scene/gui/rich_text_label.h"
-#include "scene/gui/tree.h"
-
-class VisualScriptPropertySelector : public ConfirmationDialog {
- GDCLASS(VisualScriptPropertySelector, ConfirmationDialog);
-
- enum SearchFlags {
- SEARCH_CLASSES = 1 << 0,
- SEARCH_CONSTRUCTORS = 1 << 1,
- SEARCH_METHODS = 1 << 2,
- SEARCH_OPERATORS = 1 << 3,
- SEARCH_SIGNALS = 1 << 4,
- SEARCH_CONSTANTS = 1 << 5,
- SEARCH_PROPERTIES = 1 << 6,
- SEARCH_THEME_ITEMS = 1 << 7,
- SEARCH_VISUAL_SCRIPT_NODES = 1 << 8,
- SEARCH_ALL = SEARCH_CLASSES | SEARCH_CONSTRUCTORS | SEARCH_METHODS | SEARCH_OPERATORS | SEARCH_SIGNALS | SEARCH_CONSTANTS | SEARCH_PROPERTIES | SEARCH_THEME_ITEMS,
- SEARCH_CASE_SENSITIVE = 1 << 29,
- SEARCH_SHOW_HIERARCHY = 1 << 30,
- };
-
- enum ScopeFlags {
- SCOPE_BASE = 1 << 0,
- SCOPE_INHERITERS = 1 << 1,
- SCOPE_UNRELATED = 1 << 2,
- SCOPE_RELATED = SCOPE_BASE | SCOPE_INHERITERS,
- SCOPE_ALL = SCOPE_BASE | SCOPE_INHERITERS | SCOPE_UNRELATED
- };
-
- enum ScopeCombo {
- COMBO_RELATED,
- COMBO_SEPARATOR,
- COMBO_BASE,
- COMBO_INHERITERS,
- COMBO_UNRELATED,
- COMBO_ALL,
- };
-
- LineEdit *search_box = nullptr;
-
- Button *case_sensitive_button = nullptr;
- Button *hierarchy_button = nullptr;
-
- Button *search_visual_script_nodes = nullptr;
- Button *search_classes = nullptr;
- Button *search_operators = nullptr;
-
- Button *search_methods = nullptr;
- Button *search_signals = nullptr;
- Button *search_constants = nullptr;
- Button *search_properties = nullptr;
- Button *search_theme_items = nullptr;
-
- OptionButton *scope_combo = nullptr;
- Tree *results_tree = nullptr;
-
- class SearchRunner;
- Ref<SearchRunner> search_runner;
-
- void _update_icons();
-
- void _sbox_input(const Ref<InputEvent> &p_ie);
- void _update_results_i(int p_int);
- void _update_results_s(String p_string);
- void _update_results_search_all();
- void _update_results();
-
- void _confirmed();
- void _item_selected();
- void _hide_requested();
-
- EditorHelpBit *help_bit = nullptr;
-
- bool properties = false;
- bool visual_script_generic = false;
- bool connecting = false;
- String selected;
- Variant::Type type;
- String base_type;
- String base_script;
- ObjectID script;
- Object *instance = nullptr;
- bool virtuals_only = false;
- VBoxContainer *vbox = nullptr;
-
-protected:
- void _notification(int p_what);
- static void _bind_methods();
-
-public:
- void select_method_from_base_type(const String &p_base, const bool p_virtuals_only = false, const bool p_connecting = true, bool clear_text = true);
- void select_from_base_type(const String &p_base, const String &p_base_script = "", bool p_virtuals_only = false, const bool p_connecting = true, bool clear_text = true);
- void select_from_script(const Ref<Script> &p_script, const bool p_connecting = true, bool clear_text = true);
- void select_from_basic_type(Variant::Type p_type, const bool p_connecting = true, bool clear_text = true);
- void select_from_action(const String &p_type, const bool p_connecting = true, bool clear_text = true);
- void select_from_instance(Object *p_instance, const bool p_connecting = true, bool clear_text = true);
- void select_from_visual_script(const Ref<Script> &p_script, bool clear_text = true);
-
- void show_window(float p_screen_ratio);
-
- VisualScriptPropertySelector();
-};
-
-class VisualScriptPropertySelector::SearchRunner : public RefCounted {
- enum Phase {
- PHASE_INIT,
- PHASE_MATCH_CLASSES_INIT,
- PHASE_NODE_CLASSES_INIT,
- PHASE_NODE_CLASSES_BUILD,
- PHASE_MATCH_CLASSES,
- PHASE_CLASS_ITEMS_INIT,
- PHASE_CLASS_ITEMS,
- PHASE_MEMBER_ITEMS_INIT,
- PHASE_MEMBER_ITEMS,
- PHASE_SELECT_MATCH,
- PHASE_MAX
- };
- int phase = 0;
-
- struct ClassMatch {
- DocData::ClassDoc *doc;
- bool name = false;
- String category = "";
- Vector<DocData::MethodDoc *> constructors;
- Vector<DocData::MethodDoc *> methods;
- Vector<DocData::MethodDoc *> operators;
- Vector<DocData::MethodDoc *> signals;
- Vector<DocData::ConstantDoc *> constants;
- Vector<DocData::PropertyDoc *> properties;
- Vector<DocData::ThemeItemDoc *> theme_properties;
-
- bool required() {
- return name || methods.size() || signals.size() || constants.size() || properties.size() || theme_properties.size();
- }
- };
-
- VisualScriptPropertySelector *selector_ui = nullptr;
- Control *ui_service = nullptr;
- Tree *results_tree = nullptr;
- String term;
- int search_flags = 0;
- int scope_flags = 0;
-
- Ref<Texture2D> empty_icon;
- Color disabled_color;
-
- HashMap<String, DocData::ClassDoc>::Iterator iterator_doc;
- HashMap<String, ClassMatch> matches;
- HashMap<String, ClassMatch>::Iterator iterator_match;
- TreeItem *root_item = nullptr;
- HashMap<String, TreeItem *> class_items;
- TreeItem *matched_item = nullptr;
- float match_highest_score = 0;
-
- HashMap<String, DocData::ClassDoc> combined_docs;
- List<String> vs_nodes;
-
- bool _is_class_disabled_by_feature_profile(const StringName &p_class);
- bool _is_class_disabled_by_scope(const StringName &p_class);
-
- bool _slice();
- bool _phase_init();
- bool _phase_match_classes_init();
- bool _phase_node_classes_init();
- bool _phase_node_classes_build();
- bool _phase_match_classes();
- bool _phase_class_items_init();
- bool _phase_class_items();
- bool _phase_member_items_init();
- bool _phase_member_items();
- bool _phase_select_match();
-
- bool _match_string(const String &p_term, const String &p_string) const;
- bool _match_visual_script(DocData::ClassDoc &class_doc);
- bool _match_is_hidden(DocData::ClassDoc &class_doc);
- void _match_item(TreeItem *p_item, const String &p_text);
- void _add_class_doc(String class_name, String inherits, String category);
- DocData::MethodDoc _get_method_doc(MethodInfo method_info);
- TreeItem *_create_class_hierarchy(const ClassMatch &p_match);
- TreeItem *_create_class_item(TreeItem *p_parent, const DocData::ClassDoc *p_doc, bool p_gray);
- TreeItem *_create_method_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const String &p_text, const DocData::MethodDoc *p_doc);
- TreeItem *_create_signal_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::MethodDoc *p_doc);
- TreeItem *_create_constant_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::ConstantDoc *p_doc);
- TreeItem *_create_property_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::PropertyDoc *p_doc);
- TreeItem *_create_theme_property_item(TreeItem *p_parent, const DocData::ClassDoc *p_class_doc, const DocData::ThemeItemDoc *p_doc);
- TreeItem *_create_member_item(TreeItem *p_parent, const String &p_class_name, const String &p_icon, const String &p_name, const String &p_text, const String &p_type, const String &p_metatype, const String &p_tooltip, const String &p_description);
-
-public:
- bool work(uint64_t slot = 100000);
-
- SearchRunner(VisualScriptPropertySelector *p_selector_ui, Tree *p_results_tree);
-};
-
-#endif // VISUAL_SCRIPT_PROPERTY_SELECTOR_H
diff --git a/modules/visual_script/icons/VisualScript.svg b/modules/visual_script/icons/VisualScript.svg
deleted file mode 100644
index bc698247c9..0000000000
--- a/modules/visual_script/icons/VisualScript.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><g transform="translate(0 -1036.4)"><ellipse cx="3" cy="1039.4" fill="#e0e0e0"/><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.5625v2h5.2715a2 2 0 0 1 -.27148-1 2 2 0 0 1 2-2 2 2 0 0 1 2 2 2 2 0 0 1 -.26953 1h5.2695v-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-4 9v6h2a3 3 0 0 0 3-3v-3h-2v3a1 1 0 0 1 -1 1v-4zm8 0a2 2 0 0 0 -1.7324 1 2 2 0 0 0 0 2 2 2 0 0 0 1.7324 1h-2v2h2a2 2 0 0 0 1.7324-1 2 2 0 0 0 0-2 2 2 0 0 0 -1.7324-1h2v-2z" fill="#e0e0e0" transform="translate(0 1036.4)"/></g></svg>
diff --git a/modules/visual_script/icons/VisualScriptInternal.svg b/modules/visual_script/icons/VisualScriptInternal.svg
deleted file mode 100644
index 8ab39ad929..0000000000
--- a/modules/visual_script/icons/VisualScriptInternal.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><circle cx="3" cy="3.000024" fill="#e0e0e0" r="0"/><path d="m11 10a2 2 0 0 0 -1.7324 1 2 2 0 0 0 0 2 2 2 0 0 0 1.7324 1h-2v2h2a2 2 0 0 0 1.7324-1 2 2 0 0 0 0-2 2 2 0 0 0 -1.7324-1h2v-2z" fill="#e0e0e0"/><path d="m3 10v6h2a3 3 0 0 0 3-3v-3h-2v3a1 1 0 0 1 -1 1v-4z" fill="#e0e0e0"/><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.5625v2h5.2715a2 2 0 0 1 -.27148-1 2 2 0 0 1 2-2 2 2 0 0 1 2 2 2 2 0 0 1 -.26953 1h5.2695v-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-2z" fill="none" stroke="#e0e0e0"/></svg>
diff --git a/modules/visual_script/register_types.cpp b/modules/visual_script/register_types.cpp
deleted file mode 100644
index 04a7442d0a..0000000000
--- a/modules/visual_script/register_types.cpp
+++ /dev/null
@@ -1,150 +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/engine.h"
-#include "core/io/resource_loader.h"
-#include "visual_script.h"
-#include "visual_script_builtin_funcs.h"
-#include "visual_script_expression.h"
-#include "visual_script_flow_control.h"
-#include "visual_script_func_nodes.h"
-#include "visual_script_nodes.h"
-#include "visual_script_yield_nodes.h"
-
-VisualScriptLanguage *visual_script_language = nullptr;
-
-#ifdef TOOLS_ENABLED
-#include "editor/visual_script_editor.h"
-static VisualScriptCustomNodes *vs_custom_nodes_singleton = nullptr;
-#endif
-
-void initialize_visual_script_module(ModuleInitializationLevel p_level) {
- if (p_level == MODULE_INITIALIZATION_LEVEL_SERVERS) {
- visual_script_language = memnew(VisualScriptLanguage);
- //script_language_gd->init();
- ScriptServer::register_language(visual_script_language);
-
- GDREGISTER_CLASS(VisualScript);
- GDREGISTER_ABSTRACT_CLASS(VisualScriptNode);
- GDREGISTER_CLASS(VisualScriptFunctionState);
- GDREGISTER_CLASS(VisualScriptFunction);
- GDREGISTER_ABSTRACT_CLASS(VisualScriptLists);
- GDREGISTER_CLASS(VisualScriptComposeArray);
- GDREGISTER_CLASS(VisualScriptOperator);
- GDREGISTER_CLASS(VisualScriptVariableSet);
- GDREGISTER_CLASS(VisualScriptVariableGet);
- GDREGISTER_CLASS(VisualScriptConstant);
- GDREGISTER_CLASS(VisualScriptIndexGet);
- GDREGISTER_CLASS(VisualScriptIndexSet);
- GDREGISTER_CLASS(VisualScriptGlobalConstant);
- GDREGISTER_CLASS(VisualScriptClassConstant);
- GDREGISTER_CLASS(VisualScriptMathConstant);
- GDREGISTER_CLASS(VisualScriptBasicTypeConstant);
- GDREGISTER_CLASS(VisualScriptEngineSingleton);
- GDREGISTER_CLASS(VisualScriptSceneNode);
- GDREGISTER_CLASS(VisualScriptSceneTree);
- GDREGISTER_CLASS(VisualScriptResourcePath);
- GDREGISTER_CLASS(VisualScriptSelf);
- GDREGISTER_CLASS(VisualScriptCustomNode);
- GDREGISTER_CLASS(VisualScriptSubCall);
- GDREGISTER_CLASS(VisualScriptComment);
- GDREGISTER_CLASS(VisualScriptConstructor);
- GDREGISTER_CLASS(VisualScriptLocalVar);
- GDREGISTER_CLASS(VisualScriptLocalVarSet);
- GDREGISTER_CLASS(VisualScriptInputAction);
- GDREGISTER_CLASS(VisualScriptDeconstruct);
- GDREGISTER_CLASS(VisualScriptPreload);
- GDREGISTER_CLASS(VisualScriptTypeCast);
-
- GDREGISTER_CLASS(VisualScriptFunctionCall);
- GDREGISTER_CLASS(VisualScriptPropertySet);
- GDREGISTER_CLASS(VisualScriptPropertyGet);
- //ClassDB::register_type<VisualScriptScriptCall>();
- GDREGISTER_CLASS(VisualScriptEmitSignal);
-
- GDREGISTER_CLASS(VisualScriptReturn);
- GDREGISTER_CLASS(VisualScriptCondition);
- GDREGISTER_CLASS(VisualScriptWhile);
- GDREGISTER_CLASS(VisualScriptIterator);
- GDREGISTER_CLASS(VisualScriptSequence);
- //GDREGISTER_CLASS(VisualScriptInputFilter);
- GDREGISTER_CLASS(VisualScriptSwitch);
- GDREGISTER_CLASS(VisualScriptSelect);
-
- GDREGISTER_CLASS(VisualScriptYield);
- GDREGISTER_CLASS(VisualScriptYieldSignal);
-
- GDREGISTER_CLASS(VisualScriptBuiltinFunc);
-
- GDREGISTER_CLASS(VisualScriptExpression);
-
- register_visual_script_nodes();
- register_visual_script_func_nodes();
- register_visual_script_builtin_func_node();
- register_visual_script_flow_control_nodes();
- register_visual_script_yield_nodes();
- register_visual_script_expression_node();
- }
-
-#ifdef TOOLS_ENABLED
- if (p_level == MODULE_INITIALIZATION_LEVEL_EDITOR) {
- ClassDB::set_current_api(ClassDB::API_EDITOR);
- GDREGISTER_CLASS(VisualScriptCustomNodes);
- ClassDB::set_current_api(ClassDB::API_CORE);
- vs_custom_nodes_singleton = memnew(VisualScriptCustomNodes);
- Engine::get_singleton()->add_singleton(Engine::Singleton("VisualScriptCustomNodes", VisualScriptCustomNodes::get_singleton()));
-
- VisualScriptEditor::register_editor();
- }
-#endif
-}
-
-void uninitialize_visual_script_module(ModuleInitializationLevel p_level) {
- if (p_level == MODULE_INITIALIZATION_LEVEL_SERVERS) {
- unregister_visual_script_nodes();
-
- ScriptServer::unregister_language(visual_script_language);
-
- if (visual_script_language) {
- memdelete(visual_script_language);
- }
- }
-
-#ifdef TOOLS_ENABLED
- if (p_level == MODULE_INITIALIZATION_LEVEL_EDITOR) {
- VisualScriptEditor::free_clipboard();
- if (vs_custom_nodes_singleton) {
- memdelete(vs_custom_nodes_singleton);
- }
- }
-#endif
-}
diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp
deleted file mode 100644
index 73249371cd..0000000000
--- a/modules/visual_script/visual_script.cpp
+++ /dev/null
@@ -1,2506 +0,0 @@
-/*************************************************************************/
-/* visual_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. */
-/*************************************************************************/
-
-#include "visual_script.h"
-
-#include "core/config/project_settings.h"
-#include "core/core_string_names.h"
-#include "core/os/os.h"
-#include "scene/main/node.h"
-#include "visual_script_nodes.h"
-
-// Used by editor, this is not really saved.
-void VisualScriptNode::set_breakpoint(bool p_breakpoint) {
- breakpoint = p_breakpoint;
-}
-
-bool VisualScriptNode::is_breakpoint() const {
- return breakpoint;
-}
-
-void VisualScriptNode::ports_changed_notify() {
- emit_signal(SNAME("ports_changed"));
-}
-
-void VisualScriptNode::set_default_input_value(int p_port, const Variant &p_value) {
- ERR_FAIL_INDEX(p_port, default_input_values.size());
-
- default_input_values[p_port] = p_value;
-
-#ifdef TOOLS_ENABLED
- if (script_used.is_valid()) {
- script_used->set_edited(true);
- }
-#endif
-}
-
-Variant VisualScriptNode::get_default_input_value(int p_port) const {
- ERR_FAIL_INDEX_V(p_port, default_input_values.size(), Variant());
- return default_input_values[p_port];
-}
-
-void VisualScriptNode::_set_default_input_values(Array p_values) {
- default_input_values = p_values;
-}
-
-void VisualScriptNode::validate_input_default_values() {
- default_input_values.resize(MAX(default_input_values.size(), get_input_value_port_count())); //let it grow as big as possible, we don't want to lose values on resize
-
- // Actually validate on save.
- for (int i = 0; i < get_input_value_port_count(); i++) {
- Variant::Type expected = get_input_value_port_info(i).type;
-
- if (expected == Variant::NIL || expected == default_input_values[i].get_type()) {
- continue;
- } else {
- // Not the same, reconvert.
- Callable::CallError ce;
- Variant existing = default_input_values[i];
- const Variant *existingp = &existing;
- Variant::construct(expected, default_input_values[i], &existingp, 1, ce);
- if (ce.error != Callable::CallError::CALL_OK) {
- //could not convert? force..
- Variant::construct(expected, default_input_values[i], nullptr, 0, ce);
- }
- }
- }
-}
-
-Array VisualScriptNode::_get_default_input_values() const {
- // Validate on save, since on load there is little info about this.
- Array values = default_input_values;
- values.resize(get_input_value_port_count());
-
- return values;
-}
-
-String VisualScriptNode::get_text() const {
- return "";
-}
-
-void VisualScriptNode::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_visual_script"), &VisualScriptNode::get_visual_script);
- ClassDB::bind_method(D_METHOD("set_default_input_value", "port_idx", "value"), &VisualScriptNode::set_default_input_value);
- ClassDB::bind_method(D_METHOD("get_default_input_value", "port_idx"), &VisualScriptNode::get_default_input_value);
- ClassDB::bind_method(D_METHOD("ports_changed_notify"), &VisualScriptNode::ports_changed_notify);
- ClassDB::bind_method(D_METHOD("_set_default_input_values", "values"), &VisualScriptNode::_set_default_input_values);
- ClassDB::bind_method(D_METHOD("_get_default_input_values"), &VisualScriptNode::_get_default_input_values);
-
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "_default_input_values", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_default_input_values", "_get_default_input_values");
- ADD_SIGNAL(MethodInfo("ports_changed"));
-}
-
-VisualScriptNode::TypeGuess VisualScriptNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- ERR_FAIL_COND_V(get_output_value_port_count() <= p_output, TypeGuess());
-
- PropertyInfo pinfo = get_output_value_port_info(p_output);
-
- TypeGuess tg;
-
- tg.type = pinfo.type;
- if (pinfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
- tg.gdclass = pinfo.hint_string;
- }
-
- return tg;
-}
-
-Ref<VisualScript> VisualScriptNode::get_visual_script() const {
- return script_used;
-}
-
-VisualScriptNode::VisualScriptNode() {
-}
-
-////////////////
-
-/////////////////////
-
-VisualScriptNodeInstance::VisualScriptNodeInstance() {
-}
-
-VisualScriptNodeInstance::~VisualScriptNodeInstance() {
- if (sequence_outputs) {
- memdelete_arr(sequence_outputs);
- }
-
- if (input_ports) {
- memdelete_arr(input_ports);
- }
-
- if (output_ports) {
- memdelete_arr(output_ports);
- }
-}
-
-void VisualScript::add_function(const StringName &p_name, int p_func_node_id) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!String(p_name).is_valid_identifier());
- ERR_FAIL_COND(functions.has(p_name));
- ERR_FAIL_COND(variables.has(p_name));
- ERR_FAIL_COND(custom_signals.has(p_name));
-
- functions[p_name] = Function();
- functions[p_name].func_id = p_func_node_id;
-}
-
-bool VisualScript::has_function(const StringName &p_name) const {
- return functions.has(p_name);
-}
-
-void VisualScript::remove_function(const StringName &p_name) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!functions.has(p_name));
-
- // Let the editor handle the node removal.
- functions.erase(p_name);
-}
-
-void VisualScript::rename_function(const StringName &p_name, const StringName &p_new_name) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!functions.has(p_name));
- if (p_new_name == p_name) {
- return;
- }
-
- ERR_FAIL_COND(!String(p_new_name).is_valid_identifier());
-
- ERR_FAIL_COND(functions.has(p_new_name));
- ERR_FAIL_COND(variables.has(p_new_name));
- ERR_FAIL_COND(custom_signals.has(p_new_name));
-
- functions[p_new_name] = functions[p_name];
- functions.erase(p_name);
-}
-
-void VisualScript::set_scroll(const Vector2 &p_scroll) {
- scroll = p_scroll;
-}
-
-Vector2 VisualScript::get_scroll() const {
- return scroll;
-}
-
-void VisualScript::get_function_list(List<StringName> *r_functions) const {
- for (const KeyValue<StringName, Function> &E : functions) {
- r_functions->push_back(E.key);
- }
-}
-
-int VisualScript::get_function_node_id(const StringName &p_name) const {
- ERR_FAIL_COND_V(!functions.has(p_name), -1);
-
- return functions[p_name].func_id;
-}
-
-void VisualScript::_node_ports_changed(int p_id) {
- Ref<VisualScriptNode> vsn = nodes[p_id].node;
-
- vsn->validate_input_default_values();
-
- // Must revalidate all the functions.
-
- {
- List<SequenceConnection> to_remove;
-
- for (const SequenceConnection &E : sequence_connections) {
- if (E.from_node == p_id && E.from_output >= vsn->get_output_sequence_port_count()) {
- to_remove.push_back(E);
- }
- if (E.to_node == p_id && !vsn->has_input_sequence_port()) {
- to_remove.push_back(E);
- }
- }
-
- while (to_remove.size()) {
- sequence_connections.erase(to_remove.front()->get());
- to_remove.pop_front();
- }
- }
-
- {
- List<DataConnection> to_remove;
-
- for (const DataConnection &E : data_connections) {
- if (E.from_node == p_id && E.from_port >= vsn->get_output_value_port_count()) {
- to_remove.push_back(E);
- }
- if (E.to_node == p_id && E.to_port >= vsn->get_input_value_port_count()) {
- to_remove.push_back(E);
- }
- }
-
- while (to_remove.size()) {
- data_connections.erase(to_remove.front()->get());
- to_remove.pop_front();
- }
- }
-
-#ifdef TOOLS_ENABLED
- set_edited(true); // Something changed, let's set as edited.
- emit_signal(SNAME("node_ports_changed"), p_id);
-#endif
-}
-
-void VisualScript::add_node(int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(nodes.has(p_id)); // ID can exist only one in script.
- ERR_FAIL_COND(p_node.is_null());
-
- NodeData nd;
- nd.node = p_node;
- nd.pos = p_pos;
-
- Ref<VisualScriptNode> vsn = p_node;
- vsn->connect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed).bind(p_id));
- vsn->script_used = Ref<VisualScript>(this);
- vsn->validate_input_default_values(); // Validate when fully loaded.
-
- nodes[p_id] = nd;
-}
-
-void VisualScript::remove_node(int p_id) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!nodes.has(p_id));
- {
- List<SequenceConnection> to_remove;
-
- for (const SequenceConnection &E : sequence_connections) {
- if (E.from_node == p_id || E.to_node == p_id) {
- to_remove.push_back(E);
- }
- }
-
- while (to_remove.size()) {
- sequence_connections.erase(to_remove.front()->get());
- to_remove.pop_front();
- }
- }
-
- {
- List<DataConnection> to_remove;
-
- for (const DataConnection &E : data_connections) {
- if (E.from_node == p_id || E.to_node == p_id) {
- to_remove.push_back(E);
- }
- }
-
- while (to_remove.size()) {
- data_connections.erase(to_remove.front()->get());
- to_remove.pop_front();
- }
- }
-
- nodes[p_id].node->disconnect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed));
- nodes[p_id].node->script_used.unref();
-
- nodes.erase(p_id);
-}
-
-bool VisualScript::has_node(int p_id) const {
- return nodes.has(p_id);
-}
-
-Ref<VisualScriptNode> VisualScript::get_node(int p_id) const {
- ERR_FAIL_COND_V(!nodes.has(p_id), Ref<VisualScriptNode>());
-
- return nodes[p_id].node;
-}
-
-void VisualScript::set_node_position(int p_id, const Point2 &p_pos) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!nodes.has(p_id));
- nodes[p_id].pos = p_pos;
-}
-
-Point2 VisualScript::get_node_position(int p_id) const {
- ERR_FAIL_COND_V(!nodes.has(p_id), Point2());
- return nodes[p_id].pos;
-}
-
-void VisualScript::get_node_list(List<int> *r_nodes) const {
- for (const KeyValue<int, NodeData> &E : nodes) {
- r_nodes->push_back(E.key);
- }
-}
-
-void VisualScript::sequence_connect(int p_from_node, int p_from_output, int p_to_node) {
- ERR_FAIL_COND(instances.size());
-
- SequenceConnection sc;
- sc.from_node = p_from_node;
- sc.from_output = p_from_output;
- sc.to_node = p_to_node;
- ERR_FAIL_COND(sequence_connections.has(sc));
-
- sequence_connections.insert(sc);
-}
-
-void VisualScript::sequence_disconnect(int p_from_node, int p_from_output, int p_to_node) {
- SequenceConnection sc;
- sc.from_node = p_from_node;
- sc.from_output = p_from_output;
- sc.to_node = p_to_node;
- ERR_FAIL_COND(!sequence_connections.has(sc));
-
- sequence_connections.erase(sc);
-}
-
-bool VisualScript::has_sequence_connection(int p_from_node, int p_from_output, int p_to_node) const {
- SequenceConnection sc;
- sc.from_node = p_from_node;
- sc.from_output = p_from_output;
- sc.to_node = p_to_node;
-
- return sequence_connections.has(sc);
-}
-
-void VisualScript::get_sequence_connection_list(List<SequenceConnection> *r_connection) const {
- for (const SequenceConnection &E : sequence_connections) {
- r_connection->push_back(E);
- }
-}
-
-void VisualScript::data_connect(int p_from_node, int p_from_port, int p_to_node, int p_to_port) {
- ERR_FAIL_COND(instances.size());
-
- DataConnection dc;
- dc.from_node = p_from_node;
- dc.from_port = p_from_port;
- dc.to_node = p_to_node;
- dc.to_port = p_to_port;
-
- ERR_FAIL_COND(data_connections.has(dc));
-
- data_connections.insert(dc);
-}
-
-void VisualScript::data_disconnect(int p_from_node, int p_from_port, int p_to_node, int p_to_port) {
- DataConnection dc;
- dc.from_node = p_from_node;
- dc.from_port = p_from_port;
- dc.to_node = p_to_node;
- dc.to_port = p_to_port;
-
- ERR_FAIL_COND(!data_connections.has(dc));
-
- data_connections.erase(dc);
-}
-
-bool VisualScript::has_data_connection(int p_from_node, int p_from_port, int p_to_node, int p_to_port) const {
- DataConnection dc;
- dc.from_node = p_from_node;
- dc.from_port = p_from_port;
- dc.to_node = p_to_node;
- dc.to_port = p_to_port;
-
- return data_connections.has(dc);
-}
-
-bool VisualScript::is_input_value_port_connected(int p_node, int p_port) const {
- for (const DataConnection &E : data_connections) {
- if (E.to_node == p_node && E.to_port == p_port) {
- return true;
- }
- }
- return false;
-}
-
-bool VisualScript::get_input_value_port_connection_source(int p_node, int p_port, int *r_node, int *r_port) const {
- for (const DataConnection &E : data_connections) {
- if (E.to_node == p_node && E.to_port == p_port) {
- *r_node = E.from_node;
- *r_port = E.from_port;
- return true;
- }
- }
- return false;
-}
-
-void VisualScript::get_data_connection_list(List<DataConnection> *r_connection) const {
- for (const DataConnection &E : data_connections) {
- r_connection->push_back(E);
- }
-}
-
-void VisualScript::set_tool_enabled(bool p_enabled) {
- is_tool_script = p_enabled;
-}
-
-void VisualScript::add_variable(const StringName &p_name, const Variant &p_default_value, bool p_export) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!String(p_name).is_valid_identifier());
- ERR_FAIL_COND(variables.has(p_name));
-
- Variable v;
- v.default_value = p_default_value;
- v.info.type = p_default_value.get_type();
- v.info.name = p_name;
- v.info.hint = PROPERTY_HINT_NONE;
- v._export = p_export;
-
- variables[p_name] = v;
-
-#ifdef TOOLS_ENABLED
- _update_placeholders();
-#endif
-}
-
-bool VisualScript::has_variable(const StringName &p_name) const {
- return variables.has(p_name);
-}
-
-void VisualScript::remove_variable(const StringName &p_name) {
- ERR_FAIL_COND(!variables.has(p_name));
- variables.erase(p_name);
-
-#ifdef TOOLS_ENABLED
- _update_placeholders();
-#endif
-}
-
-void VisualScript::set_variable_default_value(const StringName &p_name, const Variant &p_value) {
- ERR_FAIL_COND(!variables.has(p_name));
-
- variables[p_name].default_value = p_value;
-
-#ifdef TOOLS_ENABLED
- _update_placeholders();
-#endif
-}
-
-Variant VisualScript::get_variable_default_value(const StringName &p_name) const {
- ERR_FAIL_COND_V(!variables.has(p_name), Variant());
- return variables[p_name].default_value;
-}
-
-void VisualScript::set_variable_info(const StringName &p_name, const PropertyInfo &p_info) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!variables.has(p_name));
- variables[p_name].info = p_info;
- variables[p_name].info.name = p_name;
-
-#ifdef TOOLS_ENABLED
- _update_placeholders();
-#endif
-}
-
-PropertyInfo VisualScript::get_variable_info(const StringName &p_name) const {
- ERR_FAIL_COND_V(!variables.has(p_name), PropertyInfo());
- return variables[p_name].info;
-}
-
-void VisualScript::set_variable_export(const StringName &p_name, bool p_export) {
- ERR_FAIL_COND(!variables.has(p_name));
-
- variables[p_name]._export = p_export;
-#ifdef TOOLS_ENABLED
- _update_placeholders();
-#endif
-}
-
-bool VisualScript::get_variable_export(const StringName &p_name) const {
- ERR_FAIL_COND_V(!variables.has(p_name), false);
- return variables[p_name]._export;
-}
-
-void VisualScript::_set_variable_info(const StringName &p_name, const Dictionary &p_info) {
- PropertyInfo pinfo;
- if (p_info.has("type")) {
- pinfo.type = Variant::Type(int(p_info["type"]));
- }
- if (p_info.has("name")) {
- pinfo.name = p_info["name"];
- }
- if (p_info.has("hint")) {
- pinfo.hint = PropertyHint(int(p_info["hint"]));
- }
- if (p_info.has("hint_string")) {
- pinfo.hint_string = p_info["hint_string"];
- }
- if (p_info.has("usage")) {
- pinfo.usage = p_info["usage"];
- }
-
- set_variable_info(p_name, pinfo);
-}
-
-Dictionary VisualScript::_get_variable_info(const StringName &p_name) const {
- PropertyInfo pinfo = get_variable_info(p_name);
- Dictionary d;
- d["type"] = pinfo.type;
- d["name"] = pinfo.name;
- d["hint"] = pinfo.hint;
- d["hint_string"] = pinfo.hint_string;
- d["usage"] = pinfo.usage;
-
- return d;
-}
-
-void VisualScript::get_variable_list(List<StringName> *r_variables) const {
- for (const KeyValue<StringName, Variable> &E : variables) {
- r_variables->push_back(E.key);
- }
-}
-
-void VisualScript::set_instance_base_type(const StringName &p_type) {
- ERR_FAIL_COND(instances.size());
- base_type = p_type;
-}
-
-void VisualScript::rename_variable(const StringName &p_name, const StringName &p_new_name) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!variables.has(p_name));
- if (p_new_name == p_name) {
- return;
- }
-
- ERR_FAIL_COND(!String(p_new_name).is_valid_identifier());
-
- ERR_FAIL_COND(functions.has(p_new_name));
- ERR_FAIL_COND(variables.has(p_new_name));
- ERR_FAIL_COND(custom_signals.has(p_new_name));
-
- variables[p_new_name] = variables[p_name];
- variables.erase(p_name);
- List<int> ids;
- get_node_list(&ids);
- for (int &E : ids) {
- Ref<VisualScriptVariableGet> nodeget = get_node(E);
- if (nodeget.is_valid()) {
- if (nodeget->get_variable() == p_name) {
- nodeget->set_variable(p_new_name);
- }
- } else {
- Ref<VisualScriptVariableSet> nodeset = get_node(E);
- if (nodeset.is_valid()) {
- if (nodeset->get_variable() == p_name) {
- nodeset->set_variable(p_new_name);
- }
- }
- }
- }
-}
-
-void VisualScript::add_custom_signal(const StringName &p_name) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!String(p_name).is_valid_identifier());
- ERR_FAIL_COND(custom_signals.has(p_name));
-
- custom_signals[p_name] = Vector<Argument>();
-}
-
-bool VisualScript::has_custom_signal(const StringName &p_name) const {
- return custom_signals.has(p_name);
-}
-
-void VisualScript::custom_signal_add_argument(const StringName &p_func, Variant::Type p_type, const String &p_name, int p_index) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!custom_signals.has(p_func));
- Argument arg;
- arg.type = p_type;
- arg.name = p_name;
- if (p_index < 0) {
- custom_signals[p_func].push_back(arg);
- } else {
- custom_signals[p_func].insert(0, arg);
- }
-}
-
-void VisualScript::custom_signal_set_argument_type(const StringName &p_func, int p_argidx, Variant::Type p_type) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!custom_signals.has(p_func));
- ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
- custom_signals[p_func].write[p_argidx].type = p_type;
-}
-
-Variant::Type VisualScript::custom_signal_get_argument_type(const StringName &p_func, int p_argidx) const {
- ERR_FAIL_COND_V(!custom_signals.has(p_func), Variant::NIL);
- ERR_FAIL_INDEX_V(p_argidx, custom_signals[p_func].size(), Variant::NIL);
- return custom_signals[p_func][p_argidx].type;
-}
-
-void VisualScript::custom_signal_set_argument_name(const StringName &p_func, int p_argidx, const String &p_name) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!custom_signals.has(p_func));
- ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
- custom_signals[p_func].write[p_argidx].name = p_name;
-}
-
-String VisualScript::custom_signal_get_argument_name(const StringName &p_func, int p_argidx) const {
- ERR_FAIL_COND_V(!custom_signals.has(p_func), String());
- ERR_FAIL_INDEX_V(p_argidx, custom_signals[p_func].size(), String());
- return custom_signals[p_func][p_argidx].name;
-}
-
-void VisualScript::custom_signal_remove_argument(const StringName &p_func, int p_argidx) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!custom_signals.has(p_func));
- ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
- custom_signals[p_func].remove_at(p_argidx);
-}
-
-int VisualScript::custom_signal_get_argument_count(const StringName &p_func) const {
- ERR_FAIL_COND_V(!custom_signals.has(p_func), 0);
- return custom_signals[p_func].size();
-}
-
-void VisualScript::custom_signal_swap_argument(const StringName &p_func, int p_argidx, int p_with_argidx) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!custom_signals.has(p_func));
- ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
- ERR_FAIL_INDEX(p_with_argidx, custom_signals[p_func].size());
-
- SWAP(custom_signals[p_func].write[p_argidx], custom_signals[p_func].write[p_with_argidx]);
-}
-
-void VisualScript::remove_custom_signal(const StringName &p_name) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!custom_signals.has(p_name));
- custom_signals.erase(p_name);
-}
-
-void VisualScript::rename_custom_signal(const StringName &p_name, const StringName &p_new_name) {
- ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!custom_signals.has(p_name));
- if (p_new_name == p_name) {
- return;
- }
-
- ERR_FAIL_COND(!String(p_new_name).is_valid_identifier());
-
- ERR_FAIL_COND(functions.has(p_new_name));
- ERR_FAIL_COND(variables.has(p_new_name));
- ERR_FAIL_COND(custom_signals.has(p_new_name));
-
- custom_signals[p_new_name] = custom_signals[p_name];
- custom_signals.erase(p_name);
-}
-
-void VisualScript::get_custom_signal_list(List<StringName> *r_custom_signals) const {
- for (const KeyValue<StringName, Vector<Argument>> &E : custom_signals) {
- r_custom_signals->push_back(E.key);
- }
-
- r_custom_signals->sort_custom<StringName::AlphCompare>();
-}
-
-int VisualScript::get_available_id() const {
- // This is infinitely increasing,
- // so one might want to implement a better solution,
- // if the there is a case for huge number of nodes to be added to visual script.
-
- int max = -1;
- for (const KeyValue<int, NodeData> &E : nodes) {
- if (E.key > max) {
- max = E.key;
- }
- }
- return (max + 1);
-}
-
-/////////////////////////////////
-
-bool VisualScript::can_instantiate() const {
- return true; // ScriptServer::is_scripting_enabled();
-}
-
-StringName VisualScript::get_instance_base_type() const {
- return base_type;
-}
-
-Ref<Script> VisualScript::get_base_script() const {
- return Ref<Script>(); // No inheritance in visual script.
-}
-
-#ifdef TOOLS_ENABLED
-void VisualScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
- placeholders.erase(p_placeholder);
-}
-
-void VisualScript::_update_placeholders() {
- if (placeholders.size() == 0) {
- return; // No bother if no placeholders.
- }
- List<PropertyInfo> pinfo;
- HashMap<StringName, Variant> values;
-
- for (const KeyValue<StringName, Variable> &E : variables) {
- if (!variables[E.key]._export) {
- continue;
- }
-
- PropertyInfo p = variables[E.key].info;
- p.name = String(E.key);
- pinfo.push_back(p);
- values[p.name] = variables[E.key].default_value;
- }
-
- for (PlaceHolderScriptInstance *E : placeholders) {
- E->update(pinfo, values);
- }
-}
-
-#endif
-
-ScriptInstance *VisualScript::instance_create(Object *p_this) {
-#ifdef TOOLS_ENABLED
-
- if (!ScriptServer::is_scripting_enabled() && !is_tool_script) {
- PlaceHolderScriptInstance *sins = memnew(PlaceHolderScriptInstance(VisualScriptLanguage::singleton, Ref<Script>((Script *)this), p_this));
- placeholders.insert(sins);
-
- List<PropertyInfo> pinfo;
- HashMap<StringName, Variant> values;
-
- for (const KeyValue<StringName, Variable> &E : variables) {
- if (!variables[E.key]._export) {
- continue;
- }
-
- PropertyInfo p = variables[E.key].info;
- p.name = String(E.key);
- pinfo.push_back(p);
- values[p.name] = variables[E.key].default_value;
- }
- sins->update(pinfo, values);
-
- return sins;
- }
-#endif
-
- VisualScriptInstance *instance = memnew(VisualScriptInstance);
- instance->create(Ref<VisualScript>(this), p_this);
-
- {
- MutexLock lock(VisualScriptLanguage::singleton->lock);
-
- instances[p_this] = instance;
- }
-
- return instance;
-}
-
-bool VisualScript::instance_has(const Object *p_this) const {
- return instances.has((Object *)p_this);
-}
-
-bool VisualScript::has_source_code() const {
- return false;
-}
-
-String VisualScript::get_source_code() const {
- return String();
-}
-
-void VisualScript::set_source_code(const String &p_code) {
-}
-
-Error VisualScript::reload(bool p_keep_state) {
- return OK;
-}
-
-bool VisualScript::is_tool() const {
- return is_tool_script;
-}
-
-bool VisualScript::is_valid() const {
- return true; // Always valid.
-}
-
-ScriptLanguage *VisualScript::get_language() const {
- return VisualScriptLanguage::singleton;
-}
-
-bool VisualScript::has_script_signal(const StringName &p_signal) const {
- return custom_signals.has(p_signal);
-}
-
-void VisualScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
- for (const KeyValue<StringName, Vector<Argument>> &E : custom_signals) {
- MethodInfo mi;
- mi.name = E.key;
- for (int i = 0; i < E.value.size(); i++) {
- PropertyInfo arg;
- arg.type = E.value[i].type;
- arg.name = E.value[i].name;
- mi.arguments.push_back(arg);
- }
-
- r_signals->push_back(mi);
- }
-}
-
-bool VisualScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
- if (!variables.has(p_property)) {
- return false;
- }
-
- r_value = variables[p_property].default_value;
- return true;
-}
-
-void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const {
- for (const KeyValue<StringName, Function> &E : functions) {
- MethodInfo mi;
- mi.name = E.key;
- if (functions[E.key].func_id >= 0) {
- Ref<VisualScriptFunction> func = nodes[functions[E.key].func_id].node;
- if (func.is_valid()) {
- for (int i = 0; i < func->get_argument_count(); i++) {
- PropertyInfo arg;
- arg.name = func->get_argument_name(i);
- arg.type = func->get_argument_type(i);
- mi.arguments.push_back(arg);
- }
-
- p_list->push_back(mi);
- }
- }
- }
-}
-
-bool VisualScript::has_method(const StringName &p_method) const {
- return functions.has(p_method);
-}
-
-MethodInfo VisualScript::get_method_info(const StringName &p_method) const {
- const Function funct = functions[p_method];
- if (funct.func_id == -1) {
- return MethodInfo();
- }
-
- MethodInfo mi;
- mi.name = p_method;
- if (funct.func_id >= 0) {
- Ref<VisualScriptFunction> func = nodes[funct.func_id].node;
- if (func.is_valid()) {
- for (int i = 0; i < func->get_argument_count(); i++) {
- PropertyInfo arg;
- arg.name = func->get_argument_name(i);
- arg.type = func->get_argument_type(i);
- mi.arguments.push_back(arg);
- }
-
- if (!func->is_sequenced()) {
- mi.flags |= METHOD_FLAG_CONST;
- }
- }
- }
-
- return mi;
-}
-
-void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const {
- List<StringName> vars;
- 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);
- }
-}
-
-int VisualScript::get_member_line(const StringName &p_member) const {
- return functions[p_member].func_id; // will be -1 if not found
-}
-
-#ifdef TOOLS_ENABLED
-bool VisualScript::are_subnodes_edited() const {
- for (const KeyValue<int, NodeData> &F : nodes) {
- if (F.value.node->is_edited()) {
- return true;
- }
- }
- return false;
-}
-#endif
-
-const Variant VisualScript::get_rpc_config() const {
- return rpc_functions;
-}
-
-void VisualScript::_set_data(const Dictionary &p_data) {
- Dictionary d = p_data;
- if (d.has("base_type")) {
- base_type = d["base_type"];
- }
-
- variables.clear();
- Array vars = d["variables"];
- for (int i = 0; i < vars.size(); i++) {
- Dictionary v = vars[i];
- StringName name = v["name"];
- add_variable(name);
- _set_variable_info(name, v);
- set_variable_default_value(name, v["default_value"]);
- set_variable_export(name, v.has("export") && bool(v["export"]));
- }
-
- custom_signals.clear();
- Array sigs = d["signals"];
- for (int i = 0; i < sigs.size(); i++) {
- Dictionary cs = sigs[i];
- add_custom_signal(cs["name"]);
-
- Array args = cs["arguments"];
- for (int j = 0; j < args.size(); j += 2) {
- custom_signal_add_argument(cs["name"], Variant::Type(int(args[j + 1])), args[j]);
- }
- }
-
- Array funcs = d["functions"];
- functions.clear();
-
- for (int i = 0; i < funcs.size(); i++) {
- Dictionary func = funcs[i];
- add_function(func["name"], func["function_id"]);
- }
- {
- Array nodes = d["nodes"];
- for (int i = 0; i < nodes.size(); i += 3) {
- add_node(nodes[i], nodes[i + 2], nodes[i + 1]);
- }
-
- Array sequence_connections = d["sequence_connections"];
- for (int j = 0; j < sequence_connections.size(); j += 3) {
- sequence_connect(sequence_connections[j + 0], sequence_connections[j + 1], sequence_connections[j + 2]);
- }
-
- Array data_connections = d["data_connections"];
- for (int j = 0; j < data_connections.size(); j += 4) {
- data_connect(data_connections[j + 0], data_connections[j + 1], data_connections[j + 2], data_connections[j + 3]);
- }
- }
- is_tool_script = d["is_tool_script"];
- scroll = d["scroll"];
-
- // Takes all the rpc methods.
- rpc_functions.clear();
- for (const KeyValue<StringName, Function> &E : functions) {
- if (E.value.func_id >= 0 && nodes.has(E.value.func_id)) {
- Ref<VisualScriptFunction> vsf = nodes[E.value.func_id].node;
- if (!vsf.is_valid() || vsf->get_rpc_mode() == MultiplayerAPI::RPC_MODE_DISABLED) {
- continue;
- }
- Dictionary nd;
- nd["rpc_mode"] = vsf->get_rpc_mode();
- nd["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE; // TODO
- nd["call_local"] = false; // TODO
- rpc_functions[E.key] = nd;
- }
- }
-}
-
-Dictionary VisualScript::_get_data() const {
- Dictionary d;
- d["base_type"] = base_type;
-
- Array vars;
- for (const KeyValue<StringName, Variable> &E : variables) {
- Dictionary var = _get_variable_info(E.key);
- var["name"] = E.key; // Make sure it's the right one.
- var["default_value"] = E.value.default_value;
- var["export"] = E.value._export;
- vars.push_back(var);
- }
- d["variables"] = vars;
-
- Array sigs;
- for (const KeyValue<StringName, Vector<Argument>> &E : custom_signals) {
- Dictionary cs;
- cs["name"] = E.key;
- Array args;
- for (int i = 0; i < E.value.size(); i++) {
- args.push_back(E.value[i].name);
- args.push_back(E.value[i].type);
- }
- cs["arguments"] = args;
-
- sigs.push_back(cs);
- }
-
- d["signals"] = sigs;
-
- Array funcs;
- for (const KeyValue<StringName, Function> &E : functions) {
- Dictionary func;
- func["name"] = E.key;
- func["function_id"] = E.value.func_id;
- funcs.push_back(func);
- }
- d["functions"] = funcs;
-
- Array nds;
- for (const KeyValue<int, NodeData> &F : nodes) {
- nds.push_back(F.key);
- nds.push_back(F.value.pos);
- nds.push_back(F.value.node);
- }
- d["nodes"] = nds;
-
- Array seqconns;
- for (const SequenceConnection &F : sequence_connections) {
- seqconns.push_back(F.from_node);
- seqconns.push_back(F.from_output);
- seqconns.push_back(F.to_node);
- }
- d["sequence_connections"] = seqconns;
-
- Array dataconns;
- for (const DataConnection &F : data_connections) {
- dataconns.push_back(F.from_node);
- dataconns.push_back(F.from_port);
- dataconns.push_back(F.to_node);
- dataconns.push_back(F.to_port);
- }
- d["data_connections"] = dataconns;
-
- d["is_tool_script"] = is_tool_script;
- d["scroll"] = scroll;
-
- return d;
-}
-
-void VisualScript::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_function", "name", "func_node_id"), &VisualScript::add_function);
- ClassDB::bind_method(D_METHOD("has_function", "name"), &VisualScript::has_function);
- ClassDB::bind_method(D_METHOD("remove_function", "name"), &VisualScript::remove_function);
- ClassDB::bind_method(D_METHOD("rename_function", "name", "new_name"), &VisualScript::rename_function);
- ClassDB::bind_method(D_METHOD("set_scroll", "offset"), &VisualScript::set_scroll);
- ClassDB::bind_method(D_METHOD("get_scroll"), &VisualScript::get_scroll);
-
- ClassDB::bind_method(D_METHOD("add_node", "id", "node", "position"), &VisualScript::add_node, DEFVAL(Point2()));
- ClassDB::bind_method(D_METHOD("remove_node", "id"), &VisualScript::remove_node);
- ClassDB::bind_method(D_METHOD("get_function_node_id", "name"), &VisualScript::get_function_node_id);
-
- ClassDB::bind_method(D_METHOD("get_node", "id"), &VisualScript::get_node);
- ClassDB::bind_method(D_METHOD("has_node", "id"), &VisualScript::has_node);
- ClassDB::bind_method(D_METHOD("set_node_position", "id", "position"), &VisualScript::set_node_position);
- ClassDB::bind_method(D_METHOD("get_node_position", "id"), &VisualScript::get_node_position);
-
- ClassDB::bind_method(D_METHOD("sequence_connect", "from_node", "from_output", "to_node"), &VisualScript::sequence_connect);
- ClassDB::bind_method(D_METHOD("sequence_disconnect", "from_node", "from_output", "to_node"), &VisualScript::sequence_disconnect);
- ClassDB::bind_method(D_METHOD("has_sequence_connection", "from_node", "from_output", "to_node"), &VisualScript::has_sequence_connection);
-
- ClassDB::bind_method(D_METHOD("data_connect", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_connect);
- ClassDB::bind_method(D_METHOD("data_disconnect", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_disconnect);
- ClassDB::bind_method(D_METHOD("has_data_connection", "from_node", "from_port", "to_node", "to_port"), &VisualScript::has_data_connection);
-
- ClassDB::bind_method(D_METHOD("add_variable", "name", "default_value", "export"), &VisualScript::add_variable, DEFVAL(Variant()), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("has_variable", "name"), &VisualScript::has_variable);
- ClassDB::bind_method(D_METHOD("remove_variable", "name"), &VisualScript::remove_variable);
- ClassDB::bind_method(D_METHOD("set_variable_default_value", "name", "value"), &VisualScript::set_variable_default_value);
- ClassDB::bind_method(D_METHOD("get_variable_default_value", "name"), &VisualScript::get_variable_default_value);
- ClassDB::bind_method(D_METHOD("set_variable_info", "name", "value"), &VisualScript::_set_variable_info);
- ClassDB::bind_method(D_METHOD("get_variable_info", "name"), &VisualScript::_get_variable_info);
- ClassDB::bind_method(D_METHOD("set_variable_export", "name", "enable"), &VisualScript::set_variable_export);
- ClassDB::bind_method(D_METHOD("get_variable_export", "name"), &VisualScript::get_variable_export);
- ClassDB::bind_method(D_METHOD("rename_variable", "name", "new_name"), &VisualScript::rename_variable);
-
- ClassDB::bind_method(D_METHOD("add_custom_signal", "name"), &VisualScript::add_custom_signal);
- ClassDB::bind_method(D_METHOD("has_custom_signal", "name"), &VisualScript::has_custom_signal);
- ClassDB::bind_method(D_METHOD("custom_signal_add_argument", "name", "type", "argname", "index"), &VisualScript::custom_signal_add_argument, DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("custom_signal_set_argument_type", "name", "argidx", "type"), &VisualScript::custom_signal_set_argument_type);
- ClassDB::bind_method(D_METHOD("custom_signal_get_argument_type", "name", "argidx"), &VisualScript::custom_signal_get_argument_type);
- ClassDB::bind_method(D_METHOD("custom_signal_set_argument_name", "name", "argidx", "argname"), &VisualScript::custom_signal_set_argument_name);
- ClassDB::bind_method(D_METHOD("custom_signal_get_argument_name", "name", "argidx"), &VisualScript::custom_signal_get_argument_name);
- ClassDB::bind_method(D_METHOD("custom_signal_remove_argument", "name", "argidx"), &VisualScript::custom_signal_remove_argument);
- ClassDB::bind_method(D_METHOD("custom_signal_get_argument_count", "name"), &VisualScript::custom_signal_get_argument_count);
- ClassDB::bind_method(D_METHOD("custom_signal_swap_argument", "name", "argidx", "withidx"), &VisualScript::custom_signal_swap_argument);
- ClassDB::bind_method(D_METHOD("remove_custom_signal", "name"), &VisualScript::remove_custom_signal);
- ClassDB::bind_method(D_METHOD("rename_custom_signal", "name", "new_name"), &VisualScript::rename_custom_signal);
-
- ClassDB::bind_method(D_METHOD("set_instance_base_type", "type"), &VisualScript::set_instance_base_type);
-
- ClassDB::bind_method(D_METHOD("_set_data", "data"), &VisualScript::_set_data);
- ClassDB::bind_method(D_METHOD("_get_data"), &VisualScript::_get_data);
-
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
-
- ADD_SIGNAL(MethodInfo("node_ports_changed", PropertyInfo(Variant::INT, "id")));
-}
-
-VisualScript::VisualScript() {
- base_type = "Object";
- is_tool_script = false;
-}
-
-bool VisualScript::inherits_script(const Ref<Script> &p_script) const {
- return this == p_script.ptr(); // There is no inheritance in visual scripts, so this is enough.
-}
-
-RBSet<int> VisualScript::get_output_sequence_ports_connected(int from_node) {
- List<VisualScript::SequenceConnection> *sc = memnew(List<VisualScript::SequenceConnection>);
- get_sequence_connection_list(sc);
- RBSet<int> connected;
- for (List<VisualScript::SequenceConnection>::Element *E = sc->front(); E; E = E->next()) {
- if (E->get().from_node == from_node) {
- connected.insert(E->get().from_output);
- }
- }
- memdelete(sc);
- return connected;
-}
-
-VisualScript::~VisualScript() {
- // Remove all nodes and stuff that hold data refs.
- for (const KeyValue<int, NodeData> &E : nodes) {
- remove_node(E.key);
- }
-}
-
-////////////////////////////////////////////
-
-bool VisualScriptInstance::set(const StringName &p_name, const Variant &p_value) {
- HashMap<StringName, Variant>::Iterator E = variables.find(p_name);
- if (!E) {
- return false;
- }
-
- E->value = p_value;
-
- return true;
-}
-
-bool VisualScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
- HashMap<StringName, Variant>::ConstIterator E = variables.find(p_name);
- if (!E) {
- return false;
- }
-
- r_ret = E->value;
- return true;
-}
-
-void VisualScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
-#ifdef TOOLS_ENABLED
- p_properties->push_back(script->get_class_category());
-#endif // TOOLS_ENABLED
-
- for (const KeyValue<StringName, VisualScript::Variable> &E : script->variables) {
- if (!E.value._export) {
- continue;
- }
- PropertyInfo p = E.value.info;
- p.name = String(E.key);
- p.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
- p_properties->push_back(p);
- }
-}
-
-Variant::Type VisualScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
- if (!script->variables.has(p_name)) {
- if (r_is_valid) {
- *r_is_valid = false;
- }
- ERR_FAIL_V(Variant::NIL);
- }
-
- if (r_is_valid) {
- *r_is_valid = true;
- }
-
- return script->variables[p_name].info.type;
-}
-
-void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
- for (const KeyValue<StringName, VisualScript::Function> &E : script->functions) {
- MethodInfo mi;
- mi.name = E.key;
- if (E.value.func_id >= 0 && script->nodes.has(E.value.func_id)) {
- Ref<VisualScriptFunction> vsf = script->nodes[E.value.func_id].node;
- if (vsf.is_valid()) {
- for (int i = 0; i < vsf->get_argument_count(); i++) {
- PropertyInfo arg;
- arg.name = vsf->get_argument_name(i);
- arg.type = vsf->get_argument_type(i);
-
- mi.arguments.push_back(arg);
- }
-
- if (!vsf->is_sequenced()) { // Assumed constant if not sequenced.
- mi.flags |= METHOD_FLAG_CONST;
- }
- }
- }
- p_list->push_back(mi);
- }
-}
-
-bool VisualScriptInstance::has_method(const StringName &p_method) const {
- return script->functions.has(p_method);
-}
-
-//#define VSDEBUG(m_text) print_line(m_text)
-#define VSDEBUG(m_text)
-
-void VisualScriptInstance::_dependency_step(VisualScriptNodeInstance *node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Callable::CallError &r_error, String &error_str, VisualScriptNodeInstance **r_error_node) {
- ERR_FAIL_COND(node->pass_idx == -1);
-
- if (pass_stack[node->pass_idx] == p_pass) {
- return;
- }
-
- pass_stack[node->pass_idx] = p_pass;
-
- if (!node->dependencies.is_empty()) {
- int dc = node->dependencies.size();
- VisualScriptNodeInstance **deps = node->dependencies.ptrw();
-
- for (int i = 0; i < dc; i++) {
- _dependency_step(deps[i], p_pass, pass_stack, input_args, output_args, variant_stack, r_error, error_str, r_error_node);
- if (r_error.error != Callable::CallError::CALL_OK) {
- return;
- }
- }
- }
-
- for (int i = 0; i < node->input_port_count; i++) {
- int index = node->input_ports[i] & VisualScriptNodeInstance::INPUT_MASK;
-
- if (node->input_ports[i] & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) {
- // Is a default value (unassigned input port).
- input_args[i] = &default_values[index];
- } else {
- // Regular temporary in stack.
- input_args[i] = &variant_stack[index];
- }
- }
- for (int i = 0; i < node->output_port_count; i++) {
- output_args[i] = &variant_stack[node->output_ports[i]];
- }
-
- Variant *working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)nullptr;
-
- node->step(input_args, output_args, VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE, working_mem, r_error, error_str);
- // Ignore return.
- if (r_error.error != Callable::CallError::CALL_OK) {
- *r_error_node = node;
- }
-}
-
-Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p_stack, int p_stack_size, VisualScriptNodeInstance *p_node, int p_flow_stack_pos, int p_pass, bool p_resuming_yield, Callable::CallError &r_error) {
- HashMap<StringName, Function>::Iterator F = functions.find(p_method);
- ERR_FAIL_COND_V(!F, Variant());
- Function *f = &F->value;
-
- // This call goes separate, so it can be yielded and suspended.
- Variant *variant_stack = (Variant *)p_stack;
- bool *sequence_bits = (bool *)(variant_stack + f->max_stack);
- const Variant **input_args = (const Variant **)(sequence_bits + f->node_count);
- Variant **output_args = (Variant **)(input_args + max_input_args);
- int flow_max = f->flow_stack_size;
- int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)nullptr;
- int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)nullptr;
-
- String error_str;
-
- VisualScriptNodeInstance *node = p_node;
- bool error = false;
- int current_node_id = f->node;
- Variant return_value;
- Variant *working_mem = nullptr;
-
- int flow_stack_pos = p_flow_stack_pos;
-
-#ifdef DEBUG_ENABLED
- if (EngineDebugger::is_active()) {
- VisualScriptLanguage::singleton->enter_function(this, &p_method, variant_stack, &working_mem, &current_node_id);
- }
-#endif
-
- while (true) {
- p_pass++; // Increment pass.
- current_node_id = node->get_id();
-
- VSDEBUG("==========AT NODE: " + itos(current_node_id) + " base: " + node->get_base_node()->get_class_name());
- VSDEBUG("AT STACK POS: " + itos(flow_stack_pos));
-
- // Setup working mem.
- working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)nullptr;
-
- VSDEBUG("WORKING MEM: " + itos(node->working_mem_idx));
-
- if (current_node_id == f->node) {
- // If function node, set up function arguments from beginning of stack.
-
- for (int i = 0; i < f->argument_count; i++) {
- input_args[i] = &variant_stack[i];
- }
- } else {
- // Run dependencies first.
-
- if (!node->dependencies.is_empty()) {
- int dc = node->dependencies.size();
- VisualScriptNodeInstance **deps = node->dependencies.ptrw();
-
- for (int i = 0; i < dc; i++) {
- _dependency_step(deps[i], p_pass, pass_stack, input_args, output_args, variant_stack, r_error, error_str, &node);
- if (r_error.error != Callable::CallError::CALL_OK) {
- error = true;
- current_node_id = node->id;
- break;
- }
- }
- }
-
- if (!error) {
- // Setup input pointers normally.
- VSDEBUG("INPUT PORTS: " + itos(node->input_port_count));
-
- for (int i = 0; i < node->input_port_count; i++) {
- int index = node->input_ports[i] & VisualScriptNodeInstance::INPUT_MASK;
-
- if (node->input_ports[i] & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) {
- // Is a default value (unassigned input port).
- input_args[i] = &default_values[index];
- VSDEBUG("\tPORT " + itos(i) + " DEFAULT VAL");
- } else {
- // Regular temporary in stack.
- input_args[i] = &variant_stack[index];
- VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(index));
- }
- }
- }
- }
-
- if (error) {
- break;
- }
-
- // Setup output pointers.
-
- VSDEBUG("OUTPUT PORTS: " + itos(node->output_port_count));
- for (int i = 0; i < node->output_port_count; i++) {
- output_args[i] = &variant_stack[node->output_ports[i]];
- VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(node->output_ports[i]));
- }
-
- // Do step.
-
- VisualScriptNodeInstance::StartMode start_mode;
- {
- if (p_resuming_yield) {
- start_mode = VisualScriptNodeInstance::START_MODE_RESUME_YIELD;
- p_resuming_yield = false; // Should resume only the first time.
- } else if (flow_stack && (flow_stack[flow_stack_pos] & VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT)) {
- // If there is a push bit, it means we are continuing a sequence.
- start_mode = VisualScriptNodeInstance::START_MODE_CONTINUE_SEQUENCE;
- } else {
- start_mode = VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE;
- }
- }
-
- VSDEBUG("STEP - STARTSEQ: " + itos(start_mode));
-
- int ret = node->step(input_args, output_args, start_mode, working_mem, r_error, error_str);
-
- if (r_error.error != Callable::CallError::CALL_OK) {
- // Use error from step.
- error = true;
- break;
- }
-
- if (ret & VisualScriptNodeInstance::STEP_YIELD_BIT) {
- // Yielded!
- if (node->get_working_memory_size() == 0) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- error_str = RTR("A node yielded without working memory, please read the docs on how to yield properly!");
- error = true;
- break;
-
- } else {
- Ref<VisualScriptFunctionState> state = *working_mem;
- if (!state.is_valid()) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- error_str = RTR("Node yielded, but did not return a function state in the first working memory.");
- error = true;
- break;
- }
-
- // Step 1, capture all state.
- state->instance_id = get_owner_ptr()->get_instance_id();
- state->script_id = get_script()->get_instance_id();
- state->instance = this;
- state->function = p_method;
- state->working_mem_index = node->working_mem_idx;
- state->variant_stack_size = f->max_stack;
- state->node = node;
- state->flow_stack_pos = flow_stack_pos;
- state->stack.resize(p_stack_size);
- state->pass = p_pass;
- memcpy(state->stack.ptrw(), p_stack, p_stack_size);
- // Step 2, run away, return directly.
- r_error.error = Callable::CallError::CALL_OK;
-
-#ifdef DEBUG_ENABLED
- // Will re-enter later, so exiting.
- if (EngineDebugger::is_active()) {
- VisualScriptLanguage::singleton->exit_function();
- }
-#endif
-
- return state;
- }
- }
-
-#ifdef DEBUG_ENABLED
- if (EngineDebugger::is_active()) {
- // line
- bool do_break = false;
-
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0) {
- if (EngineDebugger::get_script_debugger()->get_depth() <= 0) {
- EngineDebugger::get_script_debugger()->set_lines_left(EngineDebugger::get_script_debugger()->get_lines_left() - 1);
- }
- if (EngineDebugger::get_script_debugger()->get_lines_left() <= 0) {
- do_break = true;
- }
- }
-
- if (EngineDebugger::get_script_debugger()->is_breakpoint(current_node_id, source)) {
- do_break = true;
- }
-
- if (do_break) {
- VisualScriptLanguage::singleton->debug_break("Breakpoint", true);
- }
-
- EngineDebugger::get_singleton()->line_poll();
- }
-#endif
- int output = ret & VisualScriptNodeInstance::STEP_MASK;
-
- VSDEBUG("STEP RETURN: " + itos(ret));
-
- if (ret & VisualScriptNodeInstance::STEP_EXIT_FUNCTION_BIT) {
- if (node->get_working_memory_size() == 0) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- error_str = RTR("Return value must be assigned to first element of node working memory! Fix your node please.");
- error = true;
- } else {
- // Assign from working memory, first element.
- return_value = *working_mem;
- }
-
- VSDEBUG("EXITING FUNCTION - VALUE " + String(return_value));
- break; // Exit function requested, bye
- }
-
- VisualScriptNodeInstance *next = nullptr; // Next node.
-
- if ((ret == output || ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) && node->sequence_output_count) {
- // If no exit bit was set, and has sequence outputs, guess next node.
- if (output >= node->sequence_output_count) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- error_str = RTR("Node returned an invalid sequence output:") + " " + itos(output);
- error = true;
- break;
- }
-
- next = node->sequence_outputs[output];
- VSDEBUG("GOT NEXT NODE - " + (next ? itos(next->get_id()) : "Null"));
- }
-
- if (flow_stack) {
- // Update flow stack pos (may have changed).
- flow_stack[flow_stack_pos] = current_node_id;
-
- // Add stack push bit if requested.
- if (ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) {
- flow_stack[flow_stack_pos] |= VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT;
- sequence_bits[node->sequence_index] = true; // Remember sequence bit.
- VSDEBUG("NEXT SEQ - FLAG BIT");
- } else {
- sequence_bits[node->sequence_index] = false; // Forget sequence bit.
- VSDEBUG("NEXT SEQ - NORMAL");
- }
-
- if (ret & VisualScriptNodeInstance::STEP_FLAG_GO_BACK_BIT) {
- // Go back request.
-
- if (flow_stack_pos > 0) {
- flow_stack_pos--;
- node = instances[flow_stack[flow_stack_pos] & VisualScriptNodeInstance::FLOW_STACK_MASK];
- VSDEBUG("NEXT IS GO BACK");
- } else {
- VSDEBUG("NEXT IS GO BACK, BUT NO NEXT SO EXIT");
- break; // Simply exit without value or error.
- }
- } else if (next) {
- if (sequence_bits[next->sequence_index]) {
- // What happened here is that we are entering a node that is in the middle of doing a sequence (pushed stack) from the front
- // because each node has a working memory, we can't really do a sub-sequence
- // as a result, the sequence will be restarted and the stack will roll back to find where this node
- // started the sequence.
-
- bool found = false;
-
- for (int i = flow_stack_pos; i >= 0; i--) {
- if ((flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_MASK) == next->get_id()) {
- flow_stack_pos = i; // Roll back and remove bit.
- flow_stack[i] = next->get_id();
- sequence_bits[next->sequence_index] = false;
- found = true;
- }
- }
-
- if (!found) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- error_str = RTR("Found sequence bit but not the node in the stack (please report).");
- error = true;
- break;
- }
-
- node = next;
- VSDEBUG("RE-ENTERED A LOOP, RETURNED STACK POS TO - " + itos(flow_stack_pos));
-
- } else {
- // Check for stack overflow.
- if (flow_stack_pos + 1 >= flow_max) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- error_str = vformat(RTR("Stack overflow (stack size: %s). Check for infinite recursion in your script."), output);
- error = true;
- break;
- }
-
- node = next;
-
- flow_stack_pos++;
- flow_stack[flow_stack_pos] = node->get_id();
-
- VSDEBUG("INCREASE FLOW STACK");
- }
-
- } else {
- // No next node, try to go back in stack to pushed bit.
-
- bool found = false;
-
- for (int i = flow_stack_pos; i >= 0; i--) {
- VSDEBUG("FS " + itos(i) + " - " + itos(flow_stack[i]));
- if (flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT) {
- node = instances[flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_MASK];
- flow_stack_pos = i;
- found = true;
- break;
- }
- }
-
- if (!found) {
- VSDEBUG("NO NEXT NODE, NO GO BACK, EXITING");
- break; // Done, couldn't find a push stack bit.
- }
-
- VSDEBUG("NO NEXT NODE, GO BACK TO: " + itos(flow_stack_pos));
- }
- } else {
- node = next; // Stackless mode, simply assign next node.
- }
- }
-
- if (error) {
- // Error
- // Function, file, line, error, explanation.
- String err_file = script->get_path();
- String err_func = p_method;
- int err_line = current_node_id; // Not a line but it works as one.
-
- if (node && (r_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD || error_str.is_empty())) {
- if (!error_str.is_empty()) {
- error_str += " ";
- }
-
- if (r_error.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) {
- int errorarg = r_error.argument;
- error_str += "Cannot convert argument " + itos(errorarg + 1) + " to " + Variant::get_type_name(Variant::Type(r_error.expected)) + ".";
- } else if (r_error.error == Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
- error_str += "Expected " + itos(r_error.argument) + " arguments.";
- } else if (r_error.error == Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
- error_str += "Expected " + itos(r_error.argument) + " arguments.";
- } else if (r_error.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) {
- error_str += "Invalid Call.";
- } else if (r_error.error == Callable::CallError::CALL_ERROR_METHOD_NOT_CONST) {
- error_str += "Method not const in a const instance.";
- } else if (r_error.error == Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
- error_str += "Base Instance is null";
- }
- }
-
- //if (!GDScriptLanguage::get_singleton()->debug_break(err_text,false)) {
- // debugger break did not happen
-
- if (!VisualScriptLanguage::singleton->debug_break(error_str, false)) {
- _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, error_str.utf8().get_data(), false, ERR_HANDLER_SCRIPT);
- }
-
- //}
- } else {
- //return_value=
- }
-
-#ifdef DEBUG_ENABLED
- if (EngineDebugger::is_active()) {
- VisualScriptLanguage::singleton->exit_function();
- }
-#endif
-
- // Clean up variant stack.
- for (int i = 0; i < f->max_stack; i++) {
- variant_stack[i].~Variant();
- }
-
- return return_value;
-}
-
-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
-
- HashMap<StringName, Function>::Iterator F = functions.find(p_method);
- if (!F) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return Variant();
- }
-
- VSDEBUG("CALLING: " + String(p_method));
-
- Function *f = &F->value;
-
- int total_stack_size = 0;
-
- total_stack_size += f->max_stack * sizeof(Variant); //variants
- total_stack_size += f->node_count * sizeof(bool);
- total_stack_size += (max_input_args + max_output_args) * sizeof(Variant *); //arguments
- total_stack_size += f->flow_stack_size * sizeof(int); //flow
- total_stack_size += f->pass_stack_size * sizeof(int);
-
- VSDEBUG("STACK SIZE: " + itos(total_stack_size));
- VSDEBUG("STACK VARIANTS: : " + itos(f->max_stack));
- VSDEBUG("SEQBITS: : " + itos(f->node_count));
- VSDEBUG("MAX INPUT: " + itos(max_input_args));
- VSDEBUG("MAX OUTPUT: " + itos(max_output_args));
- VSDEBUG("FLOW STACK SIZE: " + itos(f->flow_stack_size));
- VSDEBUG("PASS STACK SIZE: " + itos(f->pass_stack_size));
-
- void *stack = alloca(total_stack_size);
-
- Variant *variant_stack = (Variant *)stack;
- bool *sequence_bits = (bool *)(variant_stack + f->max_stack);
- const Variant **input_args = (const Variant **)(sequence_bits + f->node_count);
- Variant **output_args = (Variant **)(input_args + max_input_args);
- int flow_max = f->flow_stack_size;
- int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)nullptr;
- int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)nullptr;
-
- for (int i = 0; i < f->node_count; i++) {
- sequence_bits[i] = false; // All starts as false.
- }
-
- memset(pass_stack, 0, f->pass_stack_size * sizeof(int));
-
- HashMap<int, VisualScriptNodeInstance *>::Iterator E = instances.find(f->node);
- if (!E) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
-
- ERR_FAIL_V_MSG(Variant(), "No VisualScriptFunction node in function.");
- }
-
- VisualScriptNodeInstance *node = E->value;
-
- if (flow_stack) {
- flow_stack[0] = node->get_id();
- }
-
- VSDEBUG("ARGUMENTS: " + itos(f->argument_count) = " RECEIVED: " + itos(p_argcount));
-
- if (p_argcount < f->argument_count) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = node->get_input_port_count();
-
- return Variant();
- }
-
- if (p_argcount > f->argument_count) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument = node->get_input_port_count();
-
- return Variant();
- }
-
- // Allocate variant stack.
- for (int i = 0; i < f->max_stack; i++) {
- memnew_placement(&variant_stack[i], Variant);
- }
-
- // Allocate function arguments (must be copied for yield to work properly).
- for (int i = 0; i < p_argcount; i++) {
- variant_stack[i] = *p_args[i];
- }
-
- return _call_internal(p_method, stack, total_stack_size, node, 0, 0, false, r_error);
-}
-
-void VisualScriptInstance::notification(int p_notification) {
- // Do nothing as this is called using virtual.
-
- Variant what = p_notification;
- const Variant *whatp = &what;
- Callable::CallError ce;
- 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 = 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) {
- *r_valid = false;
- }
- ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String.");
- }
- if (r_valid) {
- *r_valid = true;
- }
- return ret.operator String();
- }
- }
- if (r_valid) {
- *r_valid = false;
- }
- return String();
-}
-
-Ref<Script> VisualScriptInstance::get_script() const {
- return script;
-}
-
-const Variant VisualScriptInstance::get_rpc_config() const {
- return script->get_rpc_config();
-}
-
-void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_owner) {
- script = p_script;
- owner = p_owner;
- source = p_script->get_path();
-
- max_input_args = 0;
- max_output_args = 0;
-
- // Setup variables.
- {
- for (const KeyValue<StringName, VisualScript::Variable> &E : script->variables) {
- variables[E.key] = E.value.default_value;
- }
- }
-
- // Setup functions from sequence trees.
- {
- for (const KeyValue<StringName, VisualScript::Function> &E : script->functions) {
- const VisualScript::Function &vsfn = E.value;
- Function function;
- function.node = vsfn.func_id;
- function.max_stack = 0;
- function.flow_stack_size = 0;
- function.pass_stack_size = 0;
- function.node_count = 0;
-
- HashMap<StringName, int> local_var_indices;
-
- if (function.node < 0) {
- VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No start node in function: " + String(E.key));
- ERR_CONTINUE(function.node < 0);
- }
-
- {
- Ref<VisualScriptFunction> func_node = script->get_node(vsfn.func_id);
-
- if (func_node.is_null()) {
- VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E.key));
- }
-
- ERR_CONTINUE(!func_node.is_valid());
-
- function.argument_count = func_node->get_argument_count();
- function.max_stack += function.argument_count;
- function.flow_stack_size = func_node->is_stack_less() ? 0 : func_node->get_stack_size();
- max_input_args = MAX(max_input_args, function.argument_count);
- }
- // Function nodes graphs.
- RBSet<VisualScript::SequenceConnection> seqconns;
- RBSet<VisualScript::DataConnection> dataconns;
- RBSet<int> node_ids;
- node_ids.insert(function.node);
- {
- List<int> nd_queue;
- nd_queue.push_back(function.node);
- while (!nd_queue.is_empty()) {
- for (const VisualScript::SequenceConnection &F : script->sequence_connections) {
- if (nd_queue.front()->get() == F.from_node && !node_ids.has(F.to_node)) {
- nd_queue.push_back(F.to_node);
- node_ids.insert(F.to_node);
- }
- if (nd_queue.front()->get() == F.from_node && !seqconns.has(F)) {
- seqconns.insert(F);
- }
- }
- nd_queue.pop_front();
- }
- HashMap<int, HashMap<int, Pair<int, int>>> dc_lut; // :: to -> to_port -> (from, from_port)
- for (const VisualScript::DataConnection &F : script->data_connections) {
- dc_lut[F.to_node][F.to_port] = Pair<int, int>(F.from_node, F.from_port);
- }
- for (const int &F : node_ids) {
- nd_queue.push_back(F);
- }
- List<int> dc_keys;
- while (!nd_queue.is_empty()) {
- int ky = nd_queue.front()->get();
- for (const KeyValue<int, Pair<int, int>> &F : dc_lut[ky]) {
- VisualScript::DataConnection dc;
- dc.from_node = F.value.first;
- dc.from_port = F.value.second;
- dc.to_node = ky;
- dc.to_port = F.key;
- dataconns.insert(dc);
- nd_queue.push_back(dc.from_node);
- node_ids.insert(dc.from_node);
- }
- dc_keys.clear(); // Necessary as get_key_list does a push_back not a set.
- nd_queue.pop_front();
- }
- }
-
- //Multiple passes are required to set up this complex thing..
- //First create the nodes.
- for (const int &F : node_ids) {
- Ref<VisualScriptNode> node = script->nodes[F].node;
-
- VisualScriptNodeInstance *instance = node->instantiate(this); // Create instance.
- ERR_FAIL_COND(!instance);
-
- instance->base = node.ptr();
-
- instance->id = F;
- instance->input_port_count = node->get_input_value_port_count();
- instance->input_ports = nullptr;
- instance->output_port_count = node->get_output_value_port_count();
- instance->output_ports = nullptr;
- instance->sequence_output_count = node->get_output_sequence_port_count();
- instance->sequence_index = function.node_count++;
- instance->sequence_outputs = nullptr;
- instance->pass_idx = -1;
-
- if (instance->input_port_count) {
- instance->input_ports = memnew_arr(int, instance->input_port_count);
- for (int i = 0; i < instance->input_port_count; i++) {
- instance->input_ports[i] = -1; // If not assigned, will become default value.
- }
- }
-
- if (instance->output_port_count) {
- instance->output_ports = memnew_arr(int, instance->output_port_count);
- for (int i = 0; i < instance->output_port_count; i++) {
- instance->output_ports[i] = -1; // If not assigned, will output to trash.
- }
- }
-
- if (instance->sequence_output_count) {
- instance->sequence_outputs = memnew_arr(VisualScriptNodeInstance *, instance->sequence_output_count);
- for (int i = 0; i < instance->sequence_output_count; i++) {
- instance->sequence_outputs[i] = nullptr; // If it remains null, flow ends here.
- }
- }
-
- if (Object::cast_to<VisualScriptLocalVar>(node.ptr()) || Object::cast_to<VisualScriptLocalVarSet>(*node)) {
- // Working memory is shared only for this node, for the same variables.
- Ref<VisualScriptLocalVar> vslv = node;
-
- StringName var_name;
-
- if (Object::cast_to<VisualScriptLocalVar>(*node)) {
- var_name = String(Object::cast_to<VisualScriptLocalVar>(*node)->get_var_name()).strip_edges();
- } else {
- var_name = String(Object::cast_to<VisualScriptLocalVarSet>(*node)->get_var_name()).strip_edges();
- }
-
- if (!local_var_indices.has(var_name)) {
- local_var_indices[var_name] = function.max_stack;
- function.max_stack++;
- }
-
- instance->working_mem_idx = local_var_indices[var_name];
-
- } else if (instance->get_working_memory_size()) {
- instance->working_mem_idx = function.max_stack;
- function.max_stack += instance->get_working_memory_size();
- } else {
- instance->working_mem_idx = -1; //no working mem
- }
-
- max_input_args = MAX(max_input_args, instance->input_port_count);
- max_output_args = MAX(max_output_args, instance->output_port_count);
-
- instances[F] = instance;
- }
-
- function.trash_pos = function.max_stack++; // create pos for trash
-
- // Second pass, do data connections.
- for (const VisualScript::DataConnection &F : dataconns) {
- VisualScript::DataConnection dc = F;
- ERR_CONTINUE(!instances.has(dc.from_node));
- VisualScriptNodeInstance *from = instances[dc.from_node];
- ERR_CONTINUE(!instances.has(dc.to_node));
- VisualScriptNodeInstance *to = instances[dc.to_node];
- ERR_CONTINUE(dc.from_port >= from->output_port_count);
- ERR_CONTINUE(dc.to_port >= to->input_port_count);
-
- if (from->output_ports[dc.from_port] == -1) {
- int stack_pos = function.max_stack++;
- from->output_ports[dc.from_port] = stack_pos;
- }
-
- if (from->get_sequence_output_count() == 0 && to->dependencies.find(from) == -1) {
- // If the node we are reading from has no output sequence, we must call step() before reading from it.
- if (from->pass_idx == -1) {
- from->pass_idx = function.pass_stack_size;
- function.pass_stack_size++;
- }
- to->dependencies.push_back(from);
- }
-
- to->input_ports[dc.to_port] = from->output_ports[dc.from_port]; // Read from wherever the stack is.
- }
-
- // Third pass, do sequence connections.
- for (const VisualScript::SequenceConnection &F : seqconns) {
- VisualScript::SequenceConnection sc = F;
- ERR_CONTINUE(!instances.has(sc.from_node));
- VisualScriptNodeInstance *from = instances[sc.from_node];
- ERR_CONTINUE(!instances.has(sc.to_node));
- VisualScriptNodeInstance *to = instances[sc.to_node];
- ERR_CONTINUE(sc.from_output >= from->sequence_output_count);
-
- from->sequence_outputs[sc.from_output] = to;
- }
-
- //fourth pass:
- // 1) unassigned input ports to default values
- // 2) connect unassigned output ports to trash
- for (const int &F : node_ids) {
- ERR_CONTINUE(!instances.has(F));
-
- Ref<VisualScriptNode> node = script->nodes[F].node;
- VisualScriptNodeInstance *instance = instances[F];
-
- // Connect to default values.
- for (int i = 0; i < instance->input_port_count; i++) {
- if (instance->input_ports[i] == -1) {
- // Unassigned, connect to default val.
- instance->input_ports[i] = default_values.size() | VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT;
- default_values.push_back(node->get_default_input_value(i));
- }
- }
-
- // Connect to trash.
- for (int i = 0; i < instance->output_port_count; i++) {
- if (instance->output_ports[i] == -1) {
- instance->output_ports[i] = function.trash_pos; //trash is same for all
- }
- }
- }
-
- functions[E.key] = function;
- }
- }
-}
-
-ScriptLanguage *VisualScriptInstance::get_language() {
- return VisualScriptLanguage::singleton;
-}
-
-VisualScriptInstance::VisualScriptInstance() {
-}
-
-VisualScriptInstance::~VisualScriptInstance() {
- {
- MutexLock lock(VisualScriptLanguage::singleton->lock);
-
- script->instances.erase(owner);
- }
-
- for (const KeyValue<int, VisualScriptNodeInstance *> &E : instances) {
- memdelete(E.value);
- }
-}
-
-/////////////////////////////////////////////
-
-/////////////////////
-
-Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
- ERR_FAIL_COND_V(function == StringName(), Variant());
-
-#ifdef DEBUG_ENABLED
-
- ERR_FAIL_COND_V_MSG(instance_id.is_valid() && !ObjectDB::get_instance(instance_id), Variant(), "Resumed after yield, but class instance is gone.");
- ERR_FAIL_COND_V_MSG(script_id.is_valid() && !ObjectDB::get_instance(script_id), Variant(), "Resumed after yield, but script is gone.");
-
-#endif
-
- r_error.error = Callable::CallError::CALL_OK;
-
- Array args;
-
- if (p_argcount == 0) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = 1;
- return Variant();
- } else if (p_argcount == 1) {
- //noooneee, reserved for me, me and only me.
- } else {
- for (int i = 0; i < p_argcount - 1; i++) {
- args.push_back(*p_args[i]);
- }
- }
-
- Ref<VisualScriptFunctionState> self = *p_args[p_argcount - 1]; //hi, I'm myself, needed this to remain alive.
-
- if (self.is_null()) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = p_argcount - 1;
- r_error.expected = Variant::OBJECT;
- return Variant();
- }
-
- r_error.error = Callable::CallError::CALL_OK;
-
- Variant *working_mem = ((Variant *)stack.ptr()) + working_mem_index;
-
- *working_mem = args; // Arguments go to working mem.
-
- Variant ret = instance->_call_internal(function, stack.ptrw(), stack.size(), node, flow_stack_pos, pass, true, r_error);
- function = StringName(); //invalidate
- return ret;
-}
-
-void VisualScriptFunctionState::connect_to_signal(Object *p_obj, const String &p_signal, Array p_binds) {
- ERR_FAIL_NULL(p_obj);
- Vector<Variant> binds;
- for (int i = 0; i < p_binds.size(); i++) {
- binds.push_back(p_binds[i]);
- }
- binds.push_back(Ref<VisualScriptFunctionState>(this)); //add myself on the back to avoid dying from unreferencing
-
- Vector<const Variant *> bind_ptrs;
- bind_ptrs.resize(p_binds.size());
- for (int i = 0; i < bind_ptrs.size(); i++) {
- bind_ptrs.write[i] = &binds.write[i];
- }
-
- p_obj->connect(p_signal, Callable(this, "_signal_callback").bindp((const Variant **)bind_ptrs.ptr(), bind_ptrs.size()), CONNECT_ONESHOT);
-}
-
-bool VisualScriptFunctionState::is_valid() const {
- return function != StringName();
-}
-
-Variant VisualScriptFunctionState::resume(Array p_args) {
- ERR_FAIL_COND_V(function == StringName(), Variant());
-#ifdef DEBUG_ENABLED
-
- ERR_FAIL_COND_V_MSG(instance_id.is_valid() && !ObjectDB::get_instance(instance_id), Variant(), "Resumed after yield, but class instance is gone.");
- ERR_FAIL_COND_V_MSG(script_id.is_valid() && !ObjectDB::get_instance(script_id), Variant(), "Resumed after yield, but script is gone.");
-
-#endif
-
- Callable::CallError r_error;
- r_error.error = Callable::CallError::CALL_OK;
-
- Variant *working_mem = ((Variant *)stack.ptr()) + working_mem_index;
-
- *working_mem = p_args; // Arguments go to working mem.
-
- Variant ret = instance->_call_internal(function, stack.ptrw(), stack.size(), node, flow_stack_pos, pass, true, r_error);
- function = StringName(); //invalidate
- return ret;
-}
-
-void VisualScriptFunctionState::_bind_methods() {
- ClassDB::bind_method(D_METHOD("connect_to_signal", "obj", "signals", "args"), &VisualScriptFunctionState::connect_to_signal);
- ClassDB::bind_method(D_METHOD("resume", "args"), &VisualScriptFunctionState::resume, DEFVAL(Array()));
- ClassDB::bind_method(D_METHOD("is_valid"), &VisualScriptFunctionState::is_valid);
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &VisualScriptFunctionState::_signal_callback, MethodInfo("_signal_callback"));
-}
-
-VisualScriptFunctionState::VisualScriptFunctionState() {
-}
-
-VisualScriptFunctionState::~VisualScriptFunctionState() {
- if (function != StringName()) {
- Variant *s = ((Variant *)stack.ptr());
- for (int i = 0; i < variant_stack_size; i++) {
- s[i].~Variant();
- }
- }
-}
-
-///////////////////////////////////////////////
-
-String VisualScriptLanguage::get_name() const {
- return "VisualScript";
-}
-
-/* LANGUAGE FUNCTIONS */
-void VisualScriptLanguage::init() {
-}
-
-String VisualScriptLanguage::get_type() const {
- return "VisualScript";
-}
-
-String VisualScriptLanguage::get_extension() const {
- return "vs";
-}
-
-Error VisualScriptLanguage::execute_file(const String &p_path) {
- return OK;
-}
-
-void VisualScriptLanguage::finish() {
-}
-
-/* EDITOR FUNCTIONS */
-void VisualScriptLanguage::get_reserved_words(List<String> *p_words) const {
-}
-
-bool VisualScriptLanguage::is_control_flow_keyword(String p_keyword) const {
- return false;
-}
-
-void VisualScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
-}
-
-void VisualScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const {
-}
-
-bool VisualScriptLanguage::is_using_templates() {
- return false;
-}
-
-Ref<Script> VisualScriptLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const {
- Ref<VisualScript> script;
- script.instantiate();
- script->set_instance_base_type(p_base_class_name);
- return script;
-}
-
-bool VisualScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, HashSet<int> *r_safe_lines) const {
- return false;
-}
-
-Script *VisualScriptLanguage::create_script() const {
- return memnew(VisualScript);
-}
-
-bool VisualScriptLanguage::has_named_classes() const {
- return false;
-}
-
-bool VisualScriptLanguage::supports_builtin_mode() const {
- return true;
-}
-
-int VisualScriptLanguage::find_function(const String &p_function, const String &p_code) const {
- return -1;
-}
-
-String VisualScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const {
- return String();
-}
-
-void VisualScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {
-}
-
-void VisualScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
-}
-
-/* DEBUGGER FUNCTIONS */
-
-bool VisualScriptLanguage::debug_break_parse(const String &p_file, int p_node, const String &p_error) {
- // Break because of parse error.
-
- if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
- _debug_parse_err_node = p_node;
- _debug_parse_err_file = p_file;
- _debug_error = p_error;
- EngineDebugger::get_script_debugger()->debug(this, false, true);
- return true;
- } else {
- return false;
- }
-}
-
-bool VisualScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) {
- if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
- _debug_parse_err_node = -1;
- _debug_parse_err_file = "";
- _debug_error = p_error;
- EngineDebugger::get_script_debugger()->debug(this, p_allow_continue, true);
- return true;
- } else {
- return false;
- }
-}
-
-String VisualScriptLanguage::debug_get_error() const {
- return _debug_error;
-}
-
-int VisualScriptLanguage::debug_get_stack_level_count() const {
- if (_debug_parse_err_node >= 0) {
- return 1;
- }
-
- return _debug_call_stack_pos;
-}
-
-int VisualScriptLanguage::debug_get_stack_level_line(int p_level) const {
- if (_debug_parse_err_node >= 0) {
- return _debug_parse_err_node;
- }
-
- ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1);
-
- int l = _debug_call_stack_pos - p_level - 1;
-
- return *(_call_stack[l].current_id);
-}
-
-String VisualScriptLanguage::debug_get_stack_level_function(int p_level) const {
- if (_debug_parse_err_node >= 0) {
- return "";
- }
-
- ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
- int l = _debug_call_stack_pos - p_level - 1;
- return *_call_stack[l].function;
-}
-
-String VisualScriptLanguage::debug_get_stack_level_source(int p_level) const {
- if (_debug_parse_err_node >= 0) {
- return _debug_parse_err_file;
- }
-
- ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
- int l = _debug_call_stack_pos - p_level - 1;
- return _call_stack[l].instance->get_script_ptr()->get_path();
-}
-
-void VisualScriptLanguage::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 (_debug_parse_err_node >= 0) {
- return;
- }
-
- ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
-
- int l = _debug_call_stack_pos - p_level - 1;
- const StringName *f = _call_stack[l].function;
-
- ERR_FAIL_COND(!_call_stack[l].instance->functions.has(*f));
-
- VisualScriptNodeInstance *node = _call_stack[l].instance->instances[*_call_stack[l].current_id];
- ERR_FAIL_COND(!node);
-
- p_locals->push_back("node_name");
- p_values->push_back(node->get_base_node()->get_text());
-
- for (int i = 0; i < node->input_port_count; i++) {
- String name = node->get_base_node()->get_input_value_port_info(i).name;
- if (name.is_empty()) {
- name = "in_" + itos(i);
- }
-
- p_locals->push_back("input/" + name);
-
- //value is trickier
-
- int in_from = node->input_ports[i];
- int in_value = in_from & VisualScriptNodeInstance::INPUT_MASK;
-
- if (in_from & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) {
- p_values->push_back(_call_stack[l].instance->default_values[in_value]);
- } else {
- p_values->push_back(_call_stack[l].stack[in_value]);
- }
- }
-
- for (int i = 0; i < node->output_port_count; i++) {
- String name = node->get_base_node()->get_output_value_port_info(i).name;
- if (name.is_empty()) {
- name = "out_" + itos(i);
- }
-
- p_locals->push_back("output/" + name);
-
- //value is trickier
-
- int in_from = node->output_ports[i];
- p_values->push_back(_call_stack[l].stack[in_from]);
- }
-
- for (int i = 0; i < node->get_working_memory_size(); i++) {
- p_locals->push_back("working_mem/mem_" + itos(i));
- p_values->push_back((*_call_stack[l].work_mem)[i]);
- }
-}
-
-void VisualScriptLanguage::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 (_debug_parse_err_node >= 0) {
- return;
- }
-
- ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
- int l = _debug_call_stack_pos - p_level - 1;
-
- Ref<VisualScript> vs = _call_stack[l].instance->get_script();
- if (vs.is_null()) {
- return;
- }
-
- List<StringName> vars;
- vs->get_variable_list(&vars);
- for (const StringName &E : vars) {
- Variant v;
- if (_call_stack[l].instance->get_variable(E, &v)) {
- p_members->push_back("variables/" + E);
- p_values->push_back(v);
- }
- }
-}
-
-void VisualScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
- // No globals are really reachable in gdscript.
-}
-
-String VisualScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
- return "";
-}
-
-void VisualScriptLanguage::reload_all_scripts() {
-}
-
-void VisualScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
-}
-
-/* LOADER FUNCTIONS */
-
-void VisualScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const {
- p_extensions->push_back("vs");
-}
-
-void VisualScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const {
-}
-
-void VisualScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_constants) const {
-}
-
-void VisualScriptLanguage::get_public_annotations(List<MethodInfo> *p_annotations) const {
-}
-
-void VisualScriptLanguage::profiling_start() {
-}
-
-void VisualScriptLanguage::profiling_stop() {
-}
-
-int VisualScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
- return 0;
-}
-
-int VisualScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
- return 0;
-}
-
-VisualScriptLanguage *VisualScriptLanguage::singleton = nullptr;
-
-void VisualScriptLanguage::add_register_func(const String &p_name, VisualScriptNodeRegisterFunc p_func) {
- ERR_FAIL_COND(register_funcs.has(p_name));
- register_funcs[p_name] = p_func;
-}
-
-void VisualScriptLanguage::remove_register_func(const String &p_name) {
- ERR_FAIL_COND(!register_funcs.has(p_name));
- register_funcs.erase(p_name);
-}
-
-Ref<VisualScriptNode> VisualScriptLanguage::create_node_from_name(const String &p_name) {
- ERR_FAIL_COND_V(!register_funcs.has(p_name), Ref<VisualScriptNode>());
-
- return register_funcs[p_name](p_name);
-}
-
-void VisualScriptLanguage::get_registered_node_names(List<String> *r_names) {
- for (const KeyValue<String, VisualScriptNodeRegisterFunc> &E : register_funcs) {
- r_names->push_back(E.key);
- }
-}
-
-VisualScriptLanguage::VisualScriptLanguage() {
- singleton = this;
-
- int dmcs = GLOBAL_DEF("debug/settings/visual_script/max_call_stack", 1024);
- ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/visual_script/max_call_stack", PropertyInfo(Variant::INT, "debug/settings/visual_script/max_call_stack", PROPERTY_HINT_RANGE, "1024,4096,1,or_greater")); //minimum is 1024
-
- if (EngineDebugger::is_active()) {
- // Debugging enabled!
- _debug_max_call_stack = dmcs;
- _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
-
- } else {
- _debug_max_call_stack = 0;
- _call_stack = nullptr;
- }
-}
-
-VisualScriptLanguage::~VisualScriptLanguage() {
- if (_call_stack) {
- memdelete_arr(_call_stack);
- }
- singleton = nullptr;
-}
diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h
deleted file mode 100644
index 14cb14e8d9..0000000000
--- a/modules/visual_script/visual_script.h
+++ /dev/null
@@ -1,627 +0,0 @@
-/*************************************************************************/
-/* visual_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 VISUAL_SCRIPT_H
-#define VISUAL_SCRIPT_H
-
-#include "core/debugger/engine_debugger.h"
-#include "core/debugger/script_debugger.h"
-#include "core/doc_data.h"
-#include "core/object/script_language.h"
-#include "core/os/thread.h"
-#include "core/templates/rb_set.h"
-
-class VisualScriptInstance;
-class VisualScriptNodeInstance;
-class VisualScript;
-
-class VisualScriptNode : public Resource {
- GDCLASS(VisualScriptNode, Resource);
-
- friend class VisualScript;
-
- Ref<VisualScript> script_used;
-
- Array default_input_values;
- bool breakpoint = false;
-
- void _set_default_input_values(Array p_values);
- Array _get_default_input_values() const;
-
- void validate_input_default_values();
-
-protected:
- void ports_changed_notify();
- static void _bind_methods();
-
-public:
- Ref<VisualScript> get_visual_script() const;
-
- virtual int get_output_sequence_port_count() const = 0;
- virtual bool has_input_sequence_port() const = 0;
-
- virtual String get_output_sequence_port_text(int p_port) const = 0;
-
- virtual bool has_mixed_input_and_sequence_ports() const { return false; }
-
- virtual int get_input_value_port_count() const = 0;
- virtual int get_output_value_port_count() const = 0;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const = 0;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const = 0;
-
- void set_default_input_value(int p_port, const Variant &p_value);
- Variant get_default_input_value(int p_port) const;
-
- virtual String get_caption() const = 0;
- virtual String get_text() const;
- virtual String get_category() const = 0;
-
- // Used by editor, this is not really saved.
- void set_breakpoint(bool p_breakpoint);
- bool is_breakpoint() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) = 0;
-
- struct TypeGuess {
- Variant::Type type = Variant::NIL;
- StringName gdclass;
- Ref<Script> script;
- };
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
-
- VisualScriptNode();
-};
-
-class VisualScriptNodeInstance {
- friend class VisualScriptInstance;
- friend class VisualScriptLanguage; // For debugger.
-
- enum { // Input argument addressing.
- INPUT_SHIFT = 1 << 24,
- INPUT_MASK = INPUT_SHIFT - 1,
- INPUT_DEFAULT_VALUE_BIT = INPUT_SHIFT, // from unassigned input port, using default value (edited by user)
- };
-
- int id = 0;
- int sequence_index = 0;
- VisualScriptNodeInstance **sequence_outputs = nullptr;
- int sequence_output_count = 0;
- Vector<VisualScriptNodeInstance *> dependencies;
- int *input_ports = nullptr;
- int input_port_count = 0;
- int *output_ports = nullptr;
- int output_port_count = 0;
- int working_mem_idx = 0;
- int pass_idx = 0;
-
- VisualScriptNode *base = nullptr;
-
-public:
- enum StartMode {
- START_MODE_BEGIN_SEQUENCE,
- START_MODE_CONTINUE_SEQUENCE,
- START_MODE_RESUME_YIELD
- };
-
- enum {
- STEP_SHIFT = 1 << 24,
- STEP_MASK = STEP_SHIFT - 1,
- STEP_FLAG_PUSH_STACK_BIT = STEP_SHIFT, // push bit to stack
- STEP_FLAG_GO_BACK_BIT = STEP_SHIFT << 1, // go back to previous node
- STEP_NO_ADVANCE_BIT = STEP_SHIFT << 2, // do not advance past this node
- STEP_EXIT_FUNCTION_BIT = STEP_SHIFT << 3, // return from function
- STEP_YIELD_BIT = STEP_SHIFT << 4, // yield (will find VisualScriptFunctionState state in first working memory)
-
- FLOW_STACK_PUSHED_BIT = 1 << 30, // in flow stack, means bit was pushed (must go back here if end of sequence)
- FLOW_STACK_MASK = FLOW_STACK_PUSHED_BIT - 1
-
- };
-
- _FORCE_INLINE_ int get_input_port_count() const { return input_port_count; }
- _FORCE_INLINE_ int get_output_port_count() const { return output_port_count; }
- _FORCE_INLINE_ int get_sequence_output_count() const { return sequence_output_count; }
-
- _FORCE_INLINE_ int get_id() const { return id; }
-
- virtual int get_working_memory_size() const { return 0; }
-
- virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) = 0; // Do a step, return which sequence port to go out.
-
- Ref<VisualScriptNode> get_base_node() { return Ref<VisualScriptNode>(base); }
-
- VisualScriptNodeInstance();
- virtual ~VisualScriptNodeInstance();
-};
-
-class VisualScript : public Script {
- GDCLASS(VisualScript, Script);
-
- RES_BASE_EXTENSION("vs");
-
-public:
- struct SequenceConnection {
- union {
- struct {
- uint64_t from_node : 24;
- uint64_t from_output : 16;
- uint64_t to_node : 24;
- };
- uint64_t id = 0;
- };
-
- bool operator<(const SequenceConnection &p_connection) const {
- return id < p_connection.id;
- }
- };
-
- struct DataConnection {
- union {
- struct {
- uint64_t from_node : 24;
- uint64_t from_port : 8;
- uint64_t to_node : 24;
- uint64_t to_port : 8;
- };
- uint64_t id = 0;
- };
-
- bool operator<(const DataConnection &p_connection) const {
- return id < p_connection.id;
- }
- };
-
-private:
- friend class VisualScriptInstance;
-
- StringName base_type;
- struct Argument {
- String name;
- Variant::Type type = Variant::Type::NIL;
- };
-
- struct NodeData {
- Point2 pos;
- Ref<VisualScriptNode> node;
- };
-
- HashMap<int, NodeData> nodes; // Can be a sparse map.
-
- RBSet<SequenceConnection> sequence_connections;
- RBSet<DataConnection> data_connections;
-
- Vector2 scroll;
-
- struct Function {
- int func_id;
- Function() { func_id = -1; }
- };
-
- struct Variable {
- PropertyInfo info;
- Variant default_value;
- bool _export = false;
- // Add getter & setter options here.
- };
-
- HashMap<StringName, Function> functions;
- HashMap<StringName, Variable> variables;
- HashMap<StringName, Vector<Argument>> custom_signals;
- Dictionary rpc_functions;
-
- HashMap<Object *, VisualScriptInstance *> instances;
-
- bool is_tool_script;
-
-#ifdef TOOLS_ENABLED
- RBSet<PlaceHolderScriptInstance *> placeholders;
- // void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
- virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
- void _update_placeholders();
-#endif
-
- void _set_variable_info(const StringName &p_name, const Dictionary &p_info);
- Dictionary _get_variable_info(const StringName &p_name) const;
-
- void _set_data(const Dictionary &p_data);
- Dictionary _get_data() const;
-
-protected:
- void _node_ports_changed(int p_id);
- static void _bind_methods();
-
-public:
- bool inherits_script(const Ref<Script> &p_script) const override;
-
- void set_scroll(const Vector2 &p_scroll);
- Vector2 get_scroll() const;
-
- void add_function(const StringName &p_name, int p_func_node_id);
- bool has_function(const StringName &p_name) const;
- void remove_function(const StringName &p_name);
- void rename_function(const StringName &p_name, const StringName &p_new_name);
- void get_function_list(List<StringName> *r_functions) const;
- int get_function_node_id(const StringName &p_name) const;
- void set_tool_enabled(bool p_enabled);
-
- void add_node(int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos = Point2());
- void remove_node(int p_id);
- bool has_node(int p_id) const;
- Ref<VisualScriptNode> get_node(int p_id) const;
- void set_node_position(int p_id, const Point2 &p_pos);
- Point2 get_node_position(int p_id) const;
- void get_node_list(List<int> *r_nodes) const;
-
- void sequence_connect(int p_from_node, int p_from_output, int p_to_node);
- void sequence_disconnect(int p_from_node, int p_from_output, int p_to_node);
- bool has_sequence_connection(int p_from_node, int p_from_output, int p_to_node) const;
- void get_sequence_connection_list(List<SequenceConnection> *r_connection) const;
- RBSet<int> get_output_sequence_ports_connected(int from_node);
-
- void data_connect(int p_from_node, int p_from_port, int p_to_node, int p_to_port);
- void data_disconnect(int p_from_node, int p_from_port, int p_to_node, int p_to_port);
- bool has_data_connection(int p_from_node, int p_from_port, int p_to_node, int p_to_port) const;
- void get_data_connection_list(List<DataConnection> *r_connection) const;
-
- bool is_input_value_port_connected(int p_node, int p_port) const;
- bool get_input_value_port_connection_source(int p_node, int p_port, int *r_node, int *r_port) const;
-
- void add_variable(const StringName &p_name, const Variant &p_default_value = Variant(), bool p_export = false);
- bool has_variable(const StringName &p_name) const;
- void remove_variable(const StringName &p_name);
- void set_variable_default_value(const StringName &p_name, const Variant &p_value);
- Variant get_variable_default_value(const StringName &p_name) const;
- void set_variable_info(const StringName &p_name, const PropertyInfo &p_info);
- PropertyInfo get_variable_info(const StringName &p_name) const;
- void set_variable_export(const StringName &p_name, bool p_export);
- bool get_variable_export(const StringName &p_name) const;
- void get_variable_list(List<StringName> *r_variables) const;
- void rename_variable(const StringName &p_name, const StringName &p_new_name);
-
- void add_custom_signal(const StringName &p_name);
- bool has_custom_signal(const StringName &p_name) const;
- void custom_signal_add_argument(const StringName &p_func, Variant::Type p_type, const String &p_name, int p_index = -1);
- void custom_signal_set_argument_type(const StringName &p_func, int p_argidx, Variant::Type p_type);
- Variant::Type custom_signal_get_argument_type(const StringName &p_func, int p_argidx) const;
- void custom_signal_set_argument_name(const StringName &p_func, int p_argidx, const String &p_name);
- String custom_signal_get_argument_name(const StringName &p_func, int p_argidx) const;
- void custom_signal_remove_argument(const StringName &p_func, int p_argidx);
- int custom_signal_get_argument_count(const StringName &p_func) const;
- void custom_signal_swap_argument(const StringName &p_func, int p_argidx, int p_with_argidx);
- void remove_custom_signal(const StringName &p_name);
- void rename_custom_signal(const StringName &p_name, const StringName &p_new_name);
- RBSet<int> get_output_sequence_ports_connected(const String &edited_func, int from_node);
-
- void get_custom_signal_list(List<StringName> *r_custom_signals) const;
-
- int get_available_id() const;
-
- void set_instance_base_type(const StringName &p_type);
-
- virtual bool can_instantiate() const override;
-
- virtual Ref<Script> get_base_script() const override;
- virtual StringName get_instance_base_type() const override;
- 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;
-
-#ifdef TOOLS_ENABLED
- virtual Vector<DocData::ClassDoc> get_documentation() const override {
- Vector<DocData::ClassDoc> docs;
- return docs;
- }
-#endif // TOOLS_ENABLED
-
- 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 get_script_method_list(List<MethodInfo> *p_list) const override;
-
- virtual bool has_method(const StringName &p_method) const override;
- virtual MethodInfo get_method_info(const StringName &p_method) const override;
-
- virtual void get_script_property_list(List<PropertyInfo> *p_list) const override;
-
- virtual int get_member_line(const StringName &p_member) const override;
-
- virtual const Variant get_rpc_config() const override;
-
-#ifdef TOOLS_ENABLED
- virtual bool are_subnodes_edited() const;
-#endif
-
- VisualScript();
- ~VisualScript();
-};
-
-class VisualScriptInstance : public ScriptInstance {
- Object *owner = nullptr;
- Ref<VisualScript> script;
-
- HashMap<StringName, Variant> variables; // Using variable path, not script.
- HashMap<int, VisualScriptNodeInstance *> instances;
-
- struct Function {
- int node = 0;
- int max_stack = 0;
- int trash_pos = 0;
- int flow_stack_size = 0;
- int pass_stack_size = 0;
- int node_count = 0;
- int argument_count = 0;
- };
-
- HashMap<StringName, Function> functions;
-
- Vector<Variant> default_values;
- int max_input_args = 0;
- int max_output_args = 0;
-
- StringName source;
-
- void _dependency_step(VisualScriptNodeInstance *node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Callable::CallError &r_error, String &error_str, VisualScriptNodeInstance **r_error_node);
- Variant _call_internal(const StringName &p_method, void *p_stack, int p_stack_size, VisualScriptNodeInstance *p_node, int p_flow_stack_pos, int p_pass, bool p_resuming_yield, Callable::CallError &r_error);
-
- friend class VisualScriptFunctionState; // For yield.
- friend class VisualScriptLanguage; // For debugger.
-public:
- 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 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);
-
- bool set_variable(const StringName &p_variable, const Variant &p_value) {
- HashMap<StringName, Variant>::Iterator E = variables.find(p_variable);
- if (!E) {
- return false;
- }
-
- E->value = p_value;
- return true;
- }
-
- bool get_variable(const StringName &p_variable, Variant *r_variable) const {
- HashMap<StringName, Variant>::ConstIterator E = variables.find(p_variable);
- if (!E) {
- return false;
- }
-
- *r_variable = E->value;
- return true;
- }
-
- virtual Ref<Script> get_script() const;
-
- _FORCE_INLINE_ VisualScript *get_script_ptr() { return script.ptr(); }
- _FORCE_INLINE_ Object *get_owner_ptr() { return owner; }
-
- void create(const Ref<VisualScript> &p_script, Object *p_owner);
-
- virtual ScriptLanguage *get_language();
-
- virtual const Variant get_rpc_config() const;
-
- VisualScriptInstance();
- ~VisualScriptInstance();
-};
-
-class VisualScriptFunctionState : public RefCounted {
- GDCLASS(VisualScriptFunctionState, RefCounted);
- friend class VisualScriptInstance;
-
- ObjectID instance_id;
- ObjectID script_id;
- VisualScriptInstance *instance = nullptr;
- StringName function;
- Vector<uint8_t> stack;
- int working_mem_index = 0;
- int variant_stack_size = 0;
- VisualScriptNodeInstance *node = nullptr;
- int flow_stack_pos = 0;
- int pass = 0;
-
- Variant _signal_callback(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
-
-protected:
- static void _bind_methods();
-
-public:
- void connect_to_signal(Object *p_obj, const String &p_signal, Array p_binds);
- bool is_valid() const;
- Variant resume(Array p_args);
- VisualScriptFunctionState();
- ~VisualScriptFunctionState();
-};
-
-typedef Ref<VisualScriptNode> (*VisualScriptNodeRegisterFunc)(const String &p_type);
-
-class VisualScriptLanguage : public ScriptLanguage {
- HashMap<String, VisualScriptNodeRegisterFunc> register_funcs;
-
- struct CallLevel {
- Variant *stack = nullptr;
- Variant **work_mem = nullptr;
- const StringName *function = nullptr;
- VisualScriptInstance *instance = nullptr;
- int *current_id = nullptr;
- };
-
- int _debug_parse_err_node = -1;
- String _debug_parse_err_file = "";
- String _debug_error;
- int _debug_call_stack_pos = 0;
- int _debug_max_call_stack;
- CallLevel *_call_stack = nullptr;
-
-public:
- StringName notification = "_notification";
- StringName _get_output_port_unsequenced;
- StringName _step = "_step";
- StringName _subcall = "_subcall";
-
- static VisualScriptLanguage *singleton;
-
- Mutex lock;
-
- bool debug_break(const String &p_error, bool p_allow_continue = true);
- bool debug_break_parse(const String &p_file, int p_node, const String &p_error);
-
- _FORCE_INLINE_ void enter_function(VisualScriptInstance *p_instance, const StringName *p_function, Variant *p_stack, Variant **p_work_mem, int *current_id) {
- if (Thread::get_main_id() != Thread::get_caller_id()) {
- return; // No support for other threads than main for now.
- }
-
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) {
- EngineDebugger::get_script_debugger()->set_depth(EngineDebugger::get_script_debugger()->get_depth() + 1);
- }
-
- if (_debug_call_stack_pos >= _debug_max_call_stack) {
- // Stack overflow.
- _debug_error = vformat("Stack overflow (stack size: %s). Check for infinite recursion in your script.", _debug_max_call_stack);
- EngineDebugger::get_script_debugger()->debug(this);
- return;
- }
-
- _call_stack[_debug_call_stack_pos].stack = p_stack;
- _call_stack[_debug_call_stack_pos].instance = p_instance;
- _call_stack[_debug_call_stack_pos].function = p_function;
- _call_stack[_debug_call_stack_pos].work_mem = p_work_mem;
- _call_stack[_debug_call_stack_pos].current_id = current_id;
- _debug_call_stack_pos++;
- }
-
- _FORCE_INLINE_ void exit_function() {
- if (Thread::get_main_id() != Thread::get_caller_id()) {
- return; // No support for other threads than main for now.
- }
-
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) {
- EngineDebugger::get_script_debugger()->set_depth(EngineDebugger::get_script_debugger()->get_depth() - 1);
- }
-
- if (_debug_call_stack_pos == 0) {
- _debug_error = "Stack underflow (engine bug), please report.";
- EngineDebugger::get_script_debugger()->debug(this);
- return;
- }
-
- _debug_call_stack_pos--;
- }
-
- //////////////////////////////////////
-
- virtual String get_name() const override;
-
- /* LANGUAGE FUNCTIONS */
- virtual void init() override;
- virtual String get_type() const override;
- virtual String get_extension() const override;
- virtual Error execute_file(const String &p_path) override;
- virtual void finish() override;
-
- /* EDITOR FUNCTIONS */
- virtual void get_reserved_words(List<String> *p_words) const override;
- virtual bool is_control_flow_keyword(String p_keyword) const override;
- virtual void get_comment_delimiters(List<String> *p_delimiters) const override;
- virtual void get_string_delimiters(List<String> *p_delimiters) const override;
- virtual bool is_using_templates() override;
- virtual Ref<Script> make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const override;
- 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, HashSet<int> *r_safe_lines = nullptr) const override;
- virtual Script *create_script() const override;
- virtual bool has_named_classes() const override;
- virtual bool supports_builtin_mode() const override;
- virtual int find_function(const String &p_function, const String &p_code) const override;
- virtual String make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const override;
- virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const override;
- virtual void add_global_constant(const StringName &p_variable, const Variant &p_value) override;
-
- /* DEBUGGER FUNCTIONS */
-
- virtual String debug_get_error() const override;
- virtual int debug_get_stack_level_count() const override;
- virtual int debug_get_stack_level_line(int p_level) const override;
- virtual String debug_get_stack_level_function(int p_level) const override;
- virtual String debug_get_stack_level_source(int p_level) const override;
- 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) override;
- 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) override;
- virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1) override;
- virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1) override;
-
- virtual void reload_all_scripts() override;
- virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) override;
- /* LOADER FUNCTIONS */
-
- virtual void get_recognized_extensions(List<String> *p_extensions) const override;
- virtual void get_public_functions(List<MethodInfo> *p_functions) const override;
- virtual void get_public_constants(List<Pair<String, Variant>> *p_constants) const override;
- virtual void get_public_annotations(List<MethodInfo> *p_annotations) const override;
-
- virtual void profiling_start() override;
- virtual void profiling_stop() override;
-
- virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) override;
- virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) override;
-
- void add_register_func(const String &p_name, VisualScriptNodeRegisterFunc p_func);
- void remove_register_func(const String &p_name);
- Ref<VisualScriptNode> create_node_from_name(const String &p_name);
- void get_registered_node_names(List<String> *r_names);
-
- VisualScriptLanguage();
- ~VisualScriptLanguage();
-};
-
-// Aid for registering.
-template <class T>
-static Ref<VisualScriptNode> create_node_generic(const String &p_name) {
- Ref<T> node;
- node.instantiate();
- return node;
-}
-
-#endif // VISUAL_SCRIPT_H
diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp
deleted file mode 100644
index 44e792869d..0000000000
--- a/modules/visual_script/visual_script_builtin_funcs.cpp
+++ /dev/null
@@ -1,1380 +0,0 @@
-/*************************************************************************/
-/* visual_script_builtin_funcs.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 "visual_script_builtin_funcs.h"
-
-#include "core/io/marshalls.h"
-#include "core/math/math_funcs.h"
-#include "core/object/class_db.h"
-#include "core/object/ref_counted.h"
-#include "core/os/os.h"
-#include "core/variant/variant_parser.h"
-
-const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX] = {
- "sin",
- "cos",
- "tan",
- "sinh",
- "cosh",
- "tanh",
- "asin",
- "acos",
- "atan",
- "atan2",
- "sqrt",
- "fmod",
- "fposmod",
- "floor",
- "ceil",
- "round",
- "abs",
- "sign",
- "pow",
- "log",
- "exp",
- "is_nan",
- "is_inf",
- "ease",
- "step_decimals",
- "snapped",
- "lerp",
- "cubic_interpolate",
- "inverse_lerp",
- "range_lerp",
- "move_toward",
- "randomize",
- "randi",
- "randf",
- "randi_range",
- "randf_range",
- "randfn",
- "seed",
- "rand_seed",
- "deg2rad",
- "rad2deg",
- "linear2db",
- "db2linear",
- "wrapi",
- "wrapf",
- "pingpong",
- "max",
- "min",
- "clamp",
- "nearest_po2",
- "weakref",
- "convert",
- "typeof",
- "type_exists",
- "char",
- "str",
- "print",
- "printerr",
- "printraw",
- "print_verbose",
- "var2str",
- "str2var",
- "var2bytes",
- "bytes2var",
- "smoothstep",
- "posmod",
- "lerp_angle",
- "ord",
-};
-
-VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::find_function(const String &p_string) {
- for (int i = 0; i < FUNC_MAX; i++) {
- if (p_string == func_name[i]) {
- return BuiltinFunc(i);
- }
- }
-
- return FUNC_MAX;
-}
-
-String VisualScriptBuiltinFunc::get_func_name(BuiltinFunc p_func) {
- ERR_FAIL_INDEX_V(p_func, FUNC_MAX, String());
- return func_name[p_func];
-}
-
-int VisualScriptBuiltinFunc::get_output_sequence_port_count() const {
- return has_input_sequence_port() ? 1 : 0;
-}
-
-bool VisualScriptBuiltinFunc::has_input_sequence_port() const {
- switch (func) {
- case MATH_RANDOMIZE:
- case TEXT_PRINT:
- case TEXT_PRINTERR:
- case TEXT_PRINTRAW:
- case TEXT_PRINT_VERBOSE:
- case MATH_SEED:
- return true;
- default:
- return false;
- }
-}
-
-int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
- switch (p_func) {
- case MATH_RANDOMIZE:
- case MATH_RANDI:
- case MATH_RANDF:
- return 0;
- case MATH_SIN:
- case MATH_COS:
- case MATH_TAN:
- case MATH_SINH:
- case MATH_COSH:
- case MATH_TANH:
- case MATH_ASIN:
- case MATH_ACOS:
- case MATH_ATAN:
- case MATH_SQRT:
- case MATH_FLOOR:
- case MATH_CEIL:
- case MATH_ROUND:
- case MATH_ABS:
- case MATH_SIGN:
- case MATH_LOG:
- case MATH_EXP:
- case MATH_ISNAN:
- case MATH_ISINF:
- case MATH_STEP_DECIMALS:
- case MATH_SEED:
- case MATH_RANDSEED:
- case MATH_DEG2RAD:
- case MATH_RAD2DEG:
- case MATH_LINEAR2DB:
- case MATH_DB2LINEAR:
- case LOGIC_NEAREST_PO2:
- case OBJ_WEAKREF:
- case TYPE_OF:
- case TEXT_CHAR:
- case TEXT_ORD:
- case TEXT_STR:
- case TEXT_PRINT:
- case TEXT_PRINTERR:
- case TEXT_PRINTRAW:
- case TEXT_PRINT_VERBOSE:
- case VAR_TO_STR:
- case STR_TO_VAR:
- case TYPE_EXISTS:
- return 1;
- case VAR_TO_BYTES:
- case BYTES_TO_VAR:
- case MATH_ATAN2:
- case MATH_FMOD:
- case MATH_FPOSMOD:
- case MATH_POSMOD:
- case MATH_PINGPONG:
- case MATH_POW:
- case MATH_EASE:
- case MATH_SNAPPED:
- case MATH_RANDI_RANGE:
- case MATH_RANDF_RANGE:
- case MATH_RANDFN:
- case LOGIC_MAX:
- case LOGIC_MIN:
- case TYPE_CONVERT:
- return 2;
- case MATH_LERP:
- case MATH_LERP_ANGLE:
- case MATH_INVERSE_LERP:
- case MATH_SMOOTHSTEP:
- case MATH_MOVE_TOWARD:
- case MATH_WRAP:
- case MATH_WRAPF:
- case LOGIC_CLAMP:
- return 3;
- case MATH_CUBIC_INTERPOLATE:
- case MATH_RANGE_LERP:
- return 5;
- case FUNC_MAX: {
- }
- }
- return 0;
-}
-
-int VisualScriptBuiltinFunc::get_input_value_port_count() const {
- return get_func_argument_count(func);
-}
-
-int VisualScriptBuiltinFunc::get_output_value_port_count() const {
- switch (func) {
- case MATH_RANDOMIZE:
- case TEXT_PRINT:
- case TEXT_PRINTERR:
- case TEXT_PRINTRAW:
- case TEXT_PRINT_VERBOSE:
- case MATH_SEED:
- return 0;
- case MATH_RANDSEED:
- return 2;
- default:
- return 1;
- }
-
- return 1;
-}
-
-String VisualScriptBuiltinFunc::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const {
- switch (func) {
- case MATH_SIN:
- case MATH_COS:
- case MATH_TAN:
- case MATH_SINH:
- case MATH_COSH:
- case MATH_TANH:
- case MATH_ASIN:
- case MATH_ACOS:
- case MATH_ATAN:
- case MATH_SQRT:
- case MATH_FLOOR:
- case MATH_CEIL:
- case MATH_ROUND:
- case MATH_ABS:
- case MATH_SIGN:
- case MATH_LOG:
- case MATH_EXP:
- case MATH_ISNAN:
- case MATH_ISINF: {
- return PropertyInfo(Variant::FLOAT, "s");
- } break;
- case MATH_ATAN2: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "y");
- } else {
- return PropertyInfo(Variant::FLOAT, "x");
- }
- } break;
- case MATH_FMOD:
- case MATH_FPOSMOD:
- case LOGIC_MAX:
- case LOGIC_MIN: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "a");
- } else {
- return PropertyInfo(Variant::FLOAT, "b");
- }
- } break;
- case MATH_POSMOD: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::INT, "a");
- } else {
- return PropertyInfo(Variant::INT, "b");
- }
- } break;
- case MATH_POW: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "base");
- } else {
- return PropertyInfo(Variant::FLOAT, "exp");
- }
- } break;
- case MATH_EASE: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "s");
- } else {
- return PropertyInfo(Variant::FLOAT, "curve");
- }
- } break;
- case MATH_STEP_DECIMALS: {
- return PropertyInfo(Variant::FLOAT, "step");
- } break;
- case MATH_SNAPPED: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "s");
- } else {
- return PropertyInfo(Variant::FLOAT, "steps");
- }
- } break;
- case MATH_LERP:
- case MATH_LERP_ANGLE:
- case MATH_INVERSE_LERP:
- case MATH_SMOOTHSTEP: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "from");
- } else if (p_idx == 1) {
- return PropertyInfo(Variant::FLOAT, "to");
- } else {
- 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");
- } else if (p_idx == 1) {
- return PropertyInfo(Variant::FLOAT, "istart");
- } else if (p_idx == 2) {
- return PropertyInfo(Variant::FLOAT, "istop");
- } else if (p_idx == 3) {
- return PropertyInfo(Variant::FLOAT, "ostart");
- } else {
- return PropertyInfo(Variant::FLOAT, "ostop");
- }
- } break;
- case MATH_MOVE_TOWARD: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "from");
- } else if (p_idx == 1) {
- return PropertyInfo(Variant::FLOAT, "to");
- } else {
- return PropertyInfo(Variant::FLOAT, "delta");
- }
- } break;
- case MATH_RANDOMIZE:
- case MATH_RANDI:
- case MATH_RANDF: {
- } break;
- case MATH_RANDI_RANGE: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::INT, "from");
- } else {
- return PropertyInfo(Variant::INT, "to");
- }
- } break;
- case MATH_RANDF_RANGE: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "from");
- } else {
- return PropertyInfo(Variant::FLOAT, "to");
- }
- } break;
- case MATH_RANDFN: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "mean");
- } else {
- return PropertyInfo(Variant::FLOAT, "deviation");
- }
- } break;
- case MATH_SEED:
- case MATH_RANDSEED: {
- return PropertyInfo(Variant::INT, "seed");
- } break;
- case MATH_DEG2RAD: {
- return PropertyInfo(Variant::FLOAT, "deg");
- } break;
- case MATH_RAD2DEG: {
- return PropertyInfo(Variant::FLOAT, "rad");
- } break;
- case MATH_LINEAR2DB: {
- return PropertyInfo(Variant::FLOAT, "nrg");
- } break;
- case MATH_DB2LINEAR: {
- return PropertyInfo(Variant::FLOAT, "db");
- } break;
- case MATH_PINGPONG: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "value");
- } else {
- return PropertyInfo(Variant::FLOAT, "length");
- }
- } break;
- case MATH_WRAP: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::INT, "value");
- } else if (p_idx == 1) {
- return PropertyInfo(Variant::INT, "min");
- } else {
- return PropertyInfo(Variant::INT, "max");
- }
- } break;
- case MATH_WRAPF:
- case LOGIC_CLAMP: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::FLOAT, "value");
- } else if (p_idx == 1) {
- return PropertyInfo(Variant::FLOAT, "min");
- } else {
- return PropertyInfo(Variant::FLOAT, "max");
- }
- } break;
- case LOGIC_NEAREST_PO2: {
- return PropertyInfo(Variant::INT, "value");
- } break;
- case OBJ_WEAKREF: {
- return PropertyInfo(Variant::OBJECT, "source");
- } break;
- case TYPE_CONVERT: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::NIL, "what");
- } else {
- return PropertyInfo(Variant::STRING, "type");
- }
- } break;
- case TYPE_OF: {
- return PropertyInfo(Variant::NIL, "what");
- } break;
- case TYPE_EXISTS: {
- return PropertyInfo(Variant::STRING, "type");
- } break;
- case TEXT_ORD: {
- return PropertyInfo(Variant::STRING, "character");
- } break;
- case TEXT_CHAR: {
- return PropertyInfo(Variant::INT, "ascii");
- } break;
- case TEXT_STR:
- case TEXT_PRINT:
- case TEXT_PRINTERR:
- case TEXT_PRINTRAW:
- case TEXT_PRINT_VERBOSE: {
- return PropertyInfo(Variant::NIL, "value");
- } break;
- case STR_TO_VAR: {
- return PropertyInfo(Variant::STRING, "string");
- } break;
- case VAR_TO_STR:
- case VAR_TO_BYTES: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::NIL, "var");
- } else {
- return PropertyInfo(Variant::BOOL, "full_objects");
- }
-
- } break;
- case BYTES_TO_VAR: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::PACKED_BYTE_ARRAY, "bytes");
- } else {
- return PropertyInfo(Variant::BOOL, "allow_objects");
- }
- } break;
- case FUNC_MAX: {
- }
- }
-
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) const {
- Variant::Type t = Variant::NIL;
- switch (func) {
- case MATH_SIN:
- case MATH_COS:
- case MATH_TAN:
- case MATH_SINH:
- case MATH_COSH:
- case MATH_TANH:
- case MATH_ASIN:
- case MATH_ACOS:
- case MATH_ATAN:
- case MATH_ATAN2:
- case MATH_SQRT:
- case MATH_FMOD:
- case MATH_FPOSMOD:
- case MATH_FLOOR:
- case MATH_CEIL: {
- t = Variant::FLOAT;
- } break;
- case MATH_POSMOD: {
- t = Variant::INT;
- } break;
- case MATH_ROUND: {
- t = Variant::FLOAT;
- } break;
- case MATH_ABS: {
- t = Variant::NIL;
- } break;
- case MATH_SIGN: {
- t = Variant::NIL;
- } break;
- case MATH_POW:
- case MATH_LOG:
- case MATH_EXP: {
- t = Variant::FLOAT;
- } break;
- case MATH_ISNAN:
- case MATH_ISINF: {
- t = Variant::BOOL;
- } break;
- case MATH_EASE: {
- t = Variant::FLOAT;
- } break;
- case MATH_STEP_DECIMALS: {
- t = Variant::INT;
- } break;
- case MATH_SNAPPED:
- case MATH_LERP:
- case MATH_CUBIC_INTERPOLATE:
- case MATH_LERP_ANGLE:
- case MATH_INVERSE_LERP:
- case MATH_RANGE_LERP:
- case MATH_SMOOTHSTEP:
- case MATH_MOVE_TOWARD:
- case MATH_RANDOMIZE: {
- } break;
- case MATH_RANDI: {
- t = Variant::INT;
- } break;
- case MATH_RANDF:
- case MATH_RANDFN:
- case MATH_RANDF_RANGE: {
- t = Variant::FLOAT;
- } break;
- case MATH_RANDI_RANGE: {
- t = Variant::INT;
- } break;
- case MATH_SEED: {
- } break;
- case MATH_RANDSEED: {
- if (p_idx == 0) {
- return PropertyInfo(Variant::INT, "rnd");
- } else {
- return PropertyInfo(Variant::INT, "seed");
- }
- } break;
- case MATH_DEG2RAD:
- case MATH_RAD2DEG:
- case MATH_LINEAR2DB:
- case MATH_WRAPF:
- case MATH_PINGPONG:
- case MATH_DB2LINEAR: {
- t = Variant::FLOAT;
- } break;
- case MATH_WRAP: {
- t = Variant::INT;
- } break;
- case LOGIC_MAX:
- case LOGIC_MIN:
- case LOGIC_CLAMP: {
- } break;
-
- case LOGIC_NEAREST_PO2: {
- t = Variant::NIL;
- } break;
- case OBJ_WEAKREF: {
- t = Variant::OBJECT;
-
- } break;
- case TYPE_CONVERT: {
- } break;
- case TEXT_ORD:
- case TYPE_OF: {
- t = Variant::INT;
-
- } break;
- case TYPE_EXISTS: {
- t = Variant::BOOL;
-
- } break;
- case TEXT_CHAR:
- case TEXT_STR: {
- t = Variant::STRING;
-
- } break;
- case TEXT_PRINT: {
- } break;
- case TEXT_PRINTERR: {
- } break;
- case TEXT_PRINTRAW: {
- } break;
- case TEXT_PRINT_VERBOSE: {
- } break;
- case VAR_TO_STR: {
- t = Variant::STRING;
- } break;
- case STR_TO_VAR: {
- } break;
- case VAR_TO_BYTES: {
- if (p_idx == 0) {
- t = Variant::PACKED_BYTE_ARRAY;
- } else {
- t = Variant::BOOL;
- }
-
- } break;
- case BYTES_TO_VAR: {
- if (p_idx == 1) {
- t = Variant::BOOL;
- }
- } break;
- case FUNC_MAX: {
- }
- }
-
- return PropertyInfo(t, "");
-}
-
-/*
-String VisualScriptBuiltinFunc::get_caption() const {
- return "BuiltinFunc";
-}
-
-*/
-
-String VisualScriptBuiltinFunc::get_caption() const {
- return func_name[func];
-}
-
-void VisualScriptBuiltinFunc::set_func(BuiltinFunc p_which) {
- ERR_FAIL_INDEX(p_which, FUNC_MAX);
- func = p_which;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::get_func() {
- return func;
-}
-
-#define VALIDATE_ARG_NUM(m_arg) \
- if (!p_inputs[m_arg]->is_num()) { \
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; \
- r_error.argument = m_arg; \
- r_error.expected = Variant::FLOAT; \
- return; \
- }
-
-void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_inputs, Variant *r_return, Callable::CallError &r_error, String &r_error_str) {
- switch (p_func) {
- case VisualScriptBuiltinFunc::MATH_SIN: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::sin((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_COS: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::cos((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_TAN: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::tan((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_SINH: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::sinh((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_COSH: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::cosh((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_TANH: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::tanh((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ASIN: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::asin((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ACOS: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::acos((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ATAN: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::atan((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ATAN2: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::atan2((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_SQRT: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::sqrt((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_FMOD: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::fmod((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_FPOSMOD: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::fposmod((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_POSMOD: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::posmod((int64_t)*p_inputs[0], (int64_t)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_FLOOR: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::floor((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_CEIL: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::ceil((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ROUND: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::round((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ABS: {
- if (p_inputs[0]->get_type() == Variant::INT) {
- int64_t i = *p_inputs[0];
- *r_return = ABS(i);
- } else if (p_inputs[0]->get_type() == Variant::FLOAT) {
- real_t r = *p_inputs[0];
- *r_return = Math::abs(r);
- } else {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::FLOAT;
- }
- } break;
- case VisualScriptBuiltinFunc::MATH_SIGN: {
- if (p_inputs[0]->get_type() == Variant::INT) {
- int64_t i = *p_inputs[0];
- *r_return = i < 0 ? -1 : (i > 0 ? +1 : 0);
- } else if (p_inputs[0]->get_type() == Variant::FLOAT) {
- real_t r = *p_inputs[0];
- *r_return = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0);
- } else {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::FLOAT;
- }
- } break;
- case VisualScriptBuiltinFunc::MATH_POW: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::pow((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_LOG: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::log((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_EXP: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::exp((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ISNAN: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::is_nan((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_ISINF: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::is_inf((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_EASE: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::ease((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_STEP_DECIMALS: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::step_decimals((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_SNAPPED: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::snapped((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_LERP: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- 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);
- VALIDATE_ARG_NUM(2);
- *r_return = Math::lerp_angle((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
- } break;
- case VisualScriptBuiltinFunc::MATH_INVERSE_LERP: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- *r_return = Math::inverse_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
- } break;
- case VisualScriptBuiltinFunc::MATH_RANGE_LERP: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- VALIDATE_ARG_NUM(3);
- VALIDATE_ARG_NUM(4);
- *r_return = Math::range_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2], (double)*p_inputs[3], (double)*p_inputs[4]);
- } break;
- case VisualScriptBuiltinFunc::MATH_SMOOTHSTEP: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- *r_return = Math::smoothstep((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
- } break;
- case VisualScriptBuiltinFunc::MATH_MOVE_TOWARD: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- *r_return = Math::move_toward((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
- } break;
- case VisualScriptBuiltinFunc::MATH_RANDOMIZE: {
- Math::randomize();
-
- } break;
- case VisualScriptBuiltinFunc::MATH_RANDI: {
- *r_return = Math::rand();
- } break;
- case VisualScriptBuiltinFunc::MATH_RANDF: {
- *r_return = Math::randf();
- } break;
- case VisualScriptBuiltinFunc::MATH_RANDI_RANGE: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::random((int)*p_inputs[0], (int)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_RANDF_RANGE: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::random((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_RANDFN: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::randfn((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_SEED: {
- VALIDATE_ARG_NUM(0);
- uint64_t seed = *p_inputs[0];
- Math::seed(seed);
-
- } break;
- case VisualScriptBuiltinFunc::MATH_RANDSEED: {
- VALIDATE_ARG_NUM(0);
- uint64_t seed = *p_inputs[0];
- int ret = Math::rand_from_seed(&seed);
- Array reta;
- reta.push_back(ret);
- reta.push_back(seed);
- *r_return = reta;
-
- } break;
- case VisualScriptBuiltinFunc::MATH_DEG2RAD: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::deg2rad((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_RAD2DEG: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::rad2deg((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_LINEAR2DB: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::linear2db((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_DB2LINEAR: {
- VALIDATE_ARG_NUM(0);
- *r_return = Math::db2linear((double)*p_inputs[0]);
- } break;
- case VisualScriptBuiltinFunc::MATH_PINGPONG: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- *r_return = Math::pingpong((double)*p_inputs[0], (double)*p_inputs[1]);
- } break;
- case VisualScriptBuiltinFunc::MATH_WRAP: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- *r_return = Math::wrapi((int64_t)*p_inputs[0], (int64_t)*p_inputs[1], (int64_t)*p_inputs[2]);
- } break;
- case VisualScriptBuiltinFunc::MATH_WRAPF: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- *r_return = Math::wrapf((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
- } break;
- case VisualScriptBuiltinFunc::LOGIC_MAX: {
- if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT) {
- int64_t a = *p_inputs[0];
- int64_t b = *p_inputs[1];
- *r_return = MAX(a, b);
- } else {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
-
- real_t a = *p_inputs[0];
- real_t b = *p_inputs[1];
-
- *r_return = MAX(a, b);
- }
-
- } break;
- case VisualScriptBuiltinFunc::LOGIC_MIN: {
- if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT) {
- int64_t a = *p_inputs[0];
- int64_t b = *p_inputs[1];
- *r_return = MIN(a, b);
- } else {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
-
- real_t a = *p_inputs[0];
- real_t b = *p_inputs[1];
-
- *r_return = MIN(a, b);
- }
- } break;
- case VisualScriptBuiltinFunc::LOGIC_CLAMP: {
- if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT && p_inputs[2]->get_type() == Variant::INT) {
- int64_t a = *p_inputs[0];
- int64_t b = *p_inputs[1];
- int64_t c = *p_inputs[2];
- *r_return = CLAMP(a, b, c);
- } else {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
-
- real_t a = *p_inputs[0];
- real_t b = *p_inputs[1];
- real_t c = *p_inputs[2];
-
- *r_return = CLAMP(a, b, c);
- }
- } break;
- case VisualScriptBuiltinFunc::LOGIC_NEAREST_PO2: {
- VALIDATE_ARG_NUM(0);
- int64_t num = *p_inputs[0];
- *r_return = next_power_of_2(num);
- } break;
- case VisualScriptBuiltinFunc::OBJ_WEAKREF: {
- if (p_inputs[0]->get_type() != Variant::OBJECT) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
-
- return;
- }
-
- if (p_inputs[0]->is_ref_counted()) {
- Ref<RefCounted> r = *p_inputs[0];
- if (!r.is_valid()) {
- return;
- }
-
- Ref<WeakRef> wref = memnew(WeakRef);
- wref->set_ref(r);
- *r_return = wref;
- } else {
- Object *obj = *p_inputs[0];
- if (!obj) {
- return;
- }
- Ref<WeakRef> wref = memnew(WeakRef);
- wref->set_obj(obj);
- *r_return = wref;
- }
-
- } break;
- case VisualScriptBuiltinFunc::TYPE_CONVERT: {
- VALIDATE_ARG_NUM(1);
- int type = *p_inputs[1];
- if (type < 0 || type >= Variant::VARIANT_MAX) {
- r_error_str = RTR("Invalid type argument to convert(), use TYPE_* constants.");
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::INT;
- return;
-
- } else {
- Variant::construct(Variant::Type(type), *r_return, p_inputs, 1, r_error);
- }
- } break;
- case VisualScriptBuiltinFunc::TYPE_OF: {
- *r_return = p_inputs[0]->get_type();
-
- } break;
- case VisualScriptBuiltinFunc::TYPE_EXISTS: {
- *r_return = ClassDB::class_exists(*p_inputs[0]);
-
- } break;
- case VisualScriptBuiltinFunc::TEXT_CHAR: {
- char32_t result[2] = { *p_inputs[0], 0 };
-
- *r_return = String(result);
-
- } break;
- case VisualScriptBuiltinFunc::TEXT_ORD: {
- if (p_inputs[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
-
- return;
- }
-
- String str = p_inputs[0]->operator String();
-
- if (str.length() != 1) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- *r_return = "Expected a string of length 1 (a character).";
-
- return;
- }
-
- *r_return = str.get(0);
-
- } break;
- case VisualScriptBuiltinFunc::TEXT_STR: {
- String str = *p_inputs[0];
-
- *r_return = str;
-
- } break;
- case VisualScriptBuiltinFunc::TEXT_PRINT: {
- String str = *p_inputs[0];
- print_line(str);
-
- } break;
-
- case VisualScriptBuiltinFunc::TEXT_PRINTERR: {
- String str = *p_inputs[0];
- print_error(str);
-
- } break;
- case VisualScriptBuiltinFunc::TEXT_PRINTRAW: {
- String str = *p_inputs[0];
- OS::get_singleton()->print("%s", str.utf8().get_data());
-
- } break;
- case VisualScriptBuiltinFunc::TEXT_PRINT_VERBOSE: {
- String str = *p_inputs[0];
- print_verbose(str);
- } break;
- case VisualScriptBuiltinFunc::VAR_TO_STR: {
- String vars;
- VariantWriter::write_to_string(*p_inputs[0], vars);
- *r_return = vars;
- } break;
- case VisualScriptBuiltinFunc::STR_TO_VAR: {
- if (p_inputs[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
-
- return;
- }
-
- VariantParser::StreamString ss;
- ss.s = *p_inputs[0];
-
- String errs;
- int line;
- Error err = VariantParser::parse(&ss, *r_return, errs, line);
-
- if (err != OK) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- *r_return = "Parse error at line " + itos(line) + ": " + errs;
- return;
- }
-
- } break;
- case VisualScriptBuiltinFunc::VAR_TO_BYTES: {
- if (p_inputs[1]->get_type() != Variant::BOOL) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 1;
- r_error.expected = Variant::BOOL;
- return;
- }
- PackedByteArray barr;
- int len;
- bool full_objects = *p_inputs[1];
- Error err = encode_variant(*p_inputs[0], nullptr, len, full_objects);
- if (err) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::NIL;
- r_error_str = "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).";
- return;
- }
-
- barr.resize(len);
- {
- uint8_t *w = barr.ptrw();
- encode_variant(*p_inputs[0], w, len, full_objects);
- }
- *r_return = barr;
- } break;
- case VisualScriptBuiltinFunc::BYTES_TO_VAR: {
- if (p_inputs[0]->get_type() != Variant::PACKED_BYTE_ARRAY) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::PACKED_BYTE_ARRAY;
- return;
- }
- if (p_inputs[1]->get_type() != Variant::BOOL) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 1;
- r_error.expected = Variant::BOOL;
- return;
- }
-
- PackedByteArray varr = *p_inputs[0];
- bool allow_objects = *p_inputs[1];
- Variant ret;
- {
- const uint8_t *r = varr.ptr();
- Error err = decode_variant(ret, r, varr.size(), nullptr, allow_objects);
- if (err != OK) {
- r_error_str = RTR("Not enough bytes for decoding bytes, or invalid format.");
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::PACKED_BYTE_ARRAY;
- return;
- }
- }
-
- *r_return = ret;
-
- } break;
- default: {
- }
- }
-}
-
-class VisualScriptNodeInstanceBuiltinFunc : public VisualScriptNodeInstance {
-public:
- VisualScriptBuiltinFunc *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- VisualScriptBuiltinFunc::BuiltinFunc func;
-
- //virtual int get_working_memory_size() const override { return 0; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- VisualScriptBuiltinFunc::exec_func(func, p_inputs, p_outputs[0], r_error, r_error_str);
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptBuiltinFunc::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceBuiltinFunc *instance = memnew(VisualScriptNodeInstanceBuiltinFunc);
- instance->node = this;
- instance->instance = p_instance;
- instance->func = func;
- return instance;
-}
-
-void VisualScriptBuiltinFunc::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_func", "which"), &VisualScriptBuiltinFunc::set_func);
- ClassDB::bind_method(D_METHOD("get_func"), &VisualScriptBuiltinFunc::get_func);
-
- String cc;
-
- for (int i = 0; i < FUNC_MAX; i++) {
- if (i > 0) {
- cc += ",";
- }
- cc += func_name[i];
- }
- ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, cc), "set_func", "get_func");
-
- BIND_ENUM_CONSTANT(MATH_SIN);
- BIND_ENUM_CONSTANT(MATH_COS);
- BIND_ENUM_CONSTANT(MATH_TAN);
- BIND_ENUM_CONSTANT(MATH_SINH);
- BIND_ENUM_CONSTANT(MATH_COSH);
- BIND_ENUM_CONSTANT(MATH_TANH);
- BIND_ENUM_CONSTANT(MATH_ASIN);
- BIND_ENUM_CONSTANT(MATH_ACOS);
- BIND_ENUM_CONSTANT(MATH_ATAN);
- BIND_ENUM_CONSTANT(MATH_ATAN2);
- BIND_ENUM_CONSTANT(MATH_SQRT);
- BIND_ENUM_CONSTANT(MATH_FMOD);
- BIND_ENUM_CONSTANT(MATH_FPOSMOD);
- BIND_ENUM_CONSTANT(MATH_FLOOR);
- BIND_ENUM_CONSTANT(MATH_CEIL);
- BIND_ENUM_CONSTANT(MATH_ROUND);
- BIND_ENUM_CONSTANT(MATH_ABS);
- BIND_ENUM_CONSTANT(MATH_SIGN);
- BIND_ENUM_CONSTANT(MATH_POW);
- BIND_ENUM_CONSTANT(MATH_LOG);
- BIND_ENUM_CONSTANT(MATH_EXP);
- BIND_ENUM_CONSTANT(MATH_ISNAN);
- BIND_ENUM_CONSTANT(MATH_ISINF);
- BIND_ENUM_CONSTANT(MATH_EASE);
- 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);
- BIND_ENUM_CONSTANT(MATH_RANDOMIZE);
- BIND_ENUM_CONSTANT(MATH_RANDI);
- BIND_ENUM_CONSTANT(MATH_RANDF);
- BIND_ENUM_CONSTANT(MATH_RANDI_RANGE);
- BIND_ENUM_CONSTANT(MATH_RANDF_RANGE);
- BIND_ENUM_CONSTANT(MATH_RANDFN);
- BIND_ENUM_CONSTANT(MATH_SEED);
- BIND_ENUM_CONSTANT(MATH_RANDSEED);
- BIND_ENUM_CONSTANT(MATH_DEG2RAD);
- BIND_ENUM_CONSTANT(MATH_RAD2DEG);
- BIND_ENUM_CONSTANT(MATH_LINEAR2DB);
- BIND_ENUM_CONSTANT(MATH_DB2LINEAR);
- BIND_ENUM_CONSTANT(MATH_WRAP);
- BIND_ENUM_CONSTANT(MATH_WRAPF);
- BIND_ENUM_CONSTANT(MATH_PINGPONG);
- BIND_ENUM_CONSTANT(LOGIC_MAX);
- BIND_ENUM_CONSTANT(LOGIC_MIN);
- BIND_ENUM_CONSTANT(LOGIC_CLAMP);
- BIND_ENUM_CONSTANT(LOGIC_NEAREST_PO2);
- BIND_ENUM_CONSTANT(OBJ_WEAKREF);
- BIND_ENUM_CONSTANT(TYPE_CONVERT);
- BIND_ENUM_CONSTANT(TYPE_OF);
- BIND_ENUM_CONSTANT(TYPE_EXISTS);
- BIND_ENUM_CONSTANT(TEXT_CHAR);
- BIND_ENUM_CONSTANT(TEXT_STR);
- BIND_ENUM_CONSTANT(TEXT_PRINT);
- BIND_ENUM_CONSTANT(TEXT_PRINTERR);
- BIND_ENUM_CONSTANT(TEXT_PRINTRAW);
- BIND_ENUM_CONSTANT(TEXT_PRINT_VERBOSE);
- BIND_ENUM_CONSTANT(VAR_TO_STR);
- BIND_ENUM_CONSTANT(STR_TO_VAR);
- BIND_ENUM_CONSTANT(VAR_TO_BYTES);
- BIND_ENUM_CONSTANT(BYTES_TO_VAR);
- BIND_ENUM_CONSTANT(MATH_SMOOTHSTEP);
- BIND_ENUM_CONSTANT(MATH_POSMOD);
- BIND_ENUM_CONSTANT(MATH_LERP_ANGLE);
- BIND_ENUM_CONSTANT(TEXT_ORD);
- BIND_ENUM_CONSTANT(FUNC_MAX);
-}
-
-VisualScriptBuiltinFunc::VisualScriptBuiltinFunc(VisualScriptBuiltinFunc::BuiltinFunc func) {
- this->func = func;
-}
-
-VisualScriptBuiltinFunc::VisualScriptBuiltinFunc() {
- func = MATH_SIN;
-}
-
-template <VisualScriptBuiltinFunc::BuiltinFunc func>
-static Ref<VisualScriptNode> create_builtin_func_node(const String &p_name) {
- Ref<VisualScriptBuiltinFunc> node = memnew(VisualScriptBuiltinFunc(func));
- return node;
-}
-
-void register_visual_script_builtin_func_node() {
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/sin", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SIN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/cos", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_COS>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/tan", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_TAN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/sinh", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SINH>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/cosh", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_COSH>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/tanh", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_TANH>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/asin", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ASIN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/acos", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ACOS>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/atan", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ATAN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/atan2", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ATAN2>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/sqrt", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SQRT>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/fmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FMOD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/fposmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FPOSMOD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/posmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_POSMOD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/floor", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FLOOR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/ceil", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_CEIL>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/round", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ROUND>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/abs", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ABS>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/sign", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SIGN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/pow", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_POW>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/log", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LOG>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/exp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_EXP>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/isnan", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ISNAN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/isinf", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ISINF>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/ease", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_EASE>);
- 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>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/smoothstep", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SMOOTHSTEP>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/move_toward", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_MOVE_TOWARD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randomize", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDOMIZE>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randi", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDI>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randf", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDF>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randi_range", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDI_RANGE>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randf_range", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDF_RANGE>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randfn", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDFN>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/seed", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SEED>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randseed", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDSEED>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/deg2rad", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DEG2RAD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/rad2deg", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RAD2DEG>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/linear2db", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LINEAR2DB>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/db2linear", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DB2LINEAR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/wrapi", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_WRAP>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/wrapf", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_WRAPF>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/pingpong", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_PINGPONG>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/max", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_MAX>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/min", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_MIN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/clamp", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_CLAMP>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/nearest_po2", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_NEAREST_PO2>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/weakref", create_builtin_func_node<VisualScriptBuiltinFunc::OBJ_WEAKREF>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/convert", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_CONVERT>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/typeof", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_OF>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/type_exists", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_EXISTS>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/char", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_CHAR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/ord", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_ORD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/str", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_STR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/print", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINT>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/printerr", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINTERR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/printraw", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINTRAW>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/print_verbose", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINT_VERBOSE>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/var2str", create_builtin_func_node<VisualScriptBuiltinFunc::VAR_TO_STR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/str2var", create_builtin_func_node<VisualScriptBuiltinFunc::STR_TO_VAR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/var2bytes", create_builtin_func_node<VisualScriptBuiltinFunc::VAR_TO_BYTES>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/bytes2var", create_builtin_func_node<VisualScriptBuiltinFunc::BYTES_TO_VAR>);
-}
diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h
deleted file mode 100644
index 18935b9995..0000000000
--- a/modules/visual_script/visual_script_builtin_funcs.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/*************************************************************************/
-/* visual_script_builtin_funcs.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 VISUAL_SCRIPT_BUILTIN_FUNCS_H
-#define VISUAL_SCRIPT_BUILTIN_FUNCS_H
-
-#include "visual_script.h"
-
-class VisualScriptBuiltinFunc : public VisualScriptNode {
- GDCLASS(VisualScriptBuiltinFunc, VisualScriptNode);
-
-public:
- enum BuiltinFunc {
- MATH_SIN,
- MATH_COS,
- MATH_TAN,
- MATH_SINH,
- MATH_COSH,
- MATH_TANH,
- MATH_ASIN,
- MATH_ACOS,
- MATH_ATAN,
- MATH_ATAN2,
- MATH_SQRT,
- MATH_FMOD,
- MATH_FPOSMOD,
- MATH_FLOOR,
- MATH_CEIL,
- MATH_ROUND,
- MATH_ABS,
- MATH_SIGN,
- MATH_POW,
- MATH_LOG,
- MATH_EXP,
- MATH_ISNAN,
- MATH_ISINF,
- MATH_EASE,
- MATH_STEP_DECIMALS,
- MATH_SNAPPED,
- MATH_LERP,
- MATH_CUBIC_INTERPOLATE,
- MATH_INVERSE_LERP,
- MATH_RANGE_LERP,
- MATH_MOVE_TOWARD,
- MATH_RANDOMIZE,
- MATH_RANDI,
- MATH_RANDF,
- MATH_RANDI_RANGE,
- MATH_RANDF_RANGE,
- MATH_RANDFN,
- MATH_SEED,
- MATH_RANDSEED,
- MATH_DEG2RAD,
- MATH_RAD2DEG,
- MATH_LINEAR2DB,
- MATH_DB2LINEAR,
- MATH_WRAP,
- MATH_WRAPF,
- MATH_PINGPONG,
- LOGIC_MAX,
- LOGIC_MIN,
- LOGIC_CLAMP,
- LOGIC_NEAREST_PO2,
- OBJ_WEAKREF,
- TYPE_CONVERT,
- TYPE_OF,
- TYPE_EXISTS,
- TEXT_CHAR,
- TEXT_STR,
- TEXT_PRINT,
- TEXT_PRINTERR,
- TEXT_PRINTRAW,
- TEXT_PRINT_VERBOSE,
- VAR_TO_STR,
- STR_TO_VAR,
- VAR_TO_BYTES,
- BYTES_TO_VAR,
- MATH_SMOOTHSTEP,
- MATH_POSMOD,
- MATH_LERP_ANGLE,
- TEXT_ORD,
- FUNC_MAX
- };
-
- static int get_func_argument_count(BuiltinFunc p_func);
- static String get_func_name(BuiltinFunc p_func);
- static void exec_func(BuiltinFunc p_func, const Variant **p_inputs, Variant *r_return, Callable::CallError &r_error, String &r_error_str);
- static BuiltinFunc find_function(const String &p_string);
-
-private:
- static const char *func_name[FUNC_MAX];
- BuiltinFunc func;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- //virtual String get_text() const;
- virtual String get_category() const override { return "functions"; }
-
- void set_func(BuiltinFunc p_which);
- BuiltinFunc get_func();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptBuiltinFunc(VisualScriptBuiltinFunc::BuiltinFunc func);
- VisualScriptBuiltinFunc();
-};
-
-VARIANT_ENUM_CAST(VisualScriptBuiltinFunc::BuiltinFunc)
-
-void register_visual_script_builtin_func_node();
-
-#endif // VISUAL_SCRIPT_BUILTIN_FUNCS_H
diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp
deleted file mode 100644
index e0f6436094..0000000000
--- a/modules/visual_script/visual_script_expression.cpp
+++ /dev/null
@@ -1,1570 +0,0 @@
-/*************************************************************************/
-/* visual_script_expression.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 "visual_script_expression.h"
-
-bool VisualScriptExpression::_set(const StringName &p_name, const Variant &p_value) {
- if (String(p_name) == "expression") {
- expression = p_value;
- expression_dirty = true;
- ports_changed_notify();
- return true;
- }
-
- if (String(p_name) == "out_type") {
- output_type = Variant::Type(int(p_value));
- expression_dirty = true;
- ports_changed_notify();
- return true;
- }
- if (String(p_name) == "sequenced") {
- sequenced = p_value;
- ports_changed_notify();
- return true;
- }
-
- if (String(p_name) == "input_count") {
- int from = inputs.size();
- inputs.resize(int(p_value));
- for (int i = from; i < inputs.size(); i++) {
- inputs.write[i].name = String::chr('a' + i);
- if (from == 0) {
- inputs.write[i].type = output_type;
- } else {
- inputs.write[i].type = inputs[from - 1].type;
- }
- }
- expression_dirty = true;
- ports_changed_notify();
- notify_property_list_changed();
- return true;
- }
-
- if (String(p_name).begins_with("input_")) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int();
- ERR_FAIL_INDEX_V(idx, inputs.size(), false);
-
- String what = String(p_name).get_slice("/", 1);
-
- if (what == "type") {
- inputs.write[idx].type = Variant::Type(int(p_value));
- } else if (what == "name") {
- inputs.write[idx].name = p_value;
- } else {
- return false;
- }
-
- expression_dirty = true;
- ports_changed_notify();
- return true;
- }
-
- return false;
-}
-
-bool VisualScriptExpression::_get(const StringName &p_name, Variant &r_ret) const {
- if (String(p_name) == "expression") {
- r_ret = expression;
- return true;
- }
-
- if (String(p_name) == "out_type") {
- r_ret = output_type;
- return true;
- }
-
- if (String(p_name) == "sequenced") {
- r_ret = sequenced;
- return true;
- }
-
- if (String(p_name) == "input_count") {
- r_ret = inputs.size();
- return true;
- }
-
- if (String(p_name).begins_with("input_")) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int();
- ERR_FAIL_INDEX_V(idx, inputs.size(), false);
-
- String what = String(p_name).get_slice("/", 1);
-
- if (what == "type") {
- r_ret = inputs[idx].type;
- } else if (what == "name") {
- r_ret = inputs[idx].name;
- } else {
- return false;
- }
-
- return true;
- }
-
- return false;
-}
-
-void VisualScriptExpression::_get_property_list(List<PropertyInfo> *p_list) const {
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- p_list->push_back(PropertyInfo(Variant::STRING, "expression", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
- p_list->push_back(PropertyInfo(Variant::INT, "out_type", PROPERTY_HINT_ENUM, argt));
- p_list->push_back(PropertyInfo(Variant::INT, "input_count", PROPERTY_HINT_RANGE, "0,64,1"));
- p_list->push_back(PropertyInfo(Variant::BOOL, "sequenced"));
-
- for (int i = 0; i < inputs.size(); i++) {
- p_list->push_back(PropertyInfo(Variant::INT, "input_" + itos(i) + "/type", PROPERTY_HINT_ENUM, argt));
- p_list->push_back(PropertyInfo(Variant::STRING, "input_" + itos(i) + "/name"));
- }
-}
-
-int VisualScriptExpression::get_output_sequence_port_count() const {
- return sequenced ? 1 : 0;
-}
-
-bool VisualScriptExpression::has_input_sequence_port() const {
- return sequenced;
-}
-
-String VisualScriptExpression::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-int VisualScriptExpression::get_input_value_port_count() const {
- return inputs.size();
-}
-
-int VisualScriptExpression::get_output_value_port_count() const {
- return 1;
-}
-
-PropertyInfo VisualScriptExpression::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(inputs[p_idx].type, inputs[p_idx].name);
-}
-
-PropertyInfo VisualScriptExpression::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(output_type, "result");
-}
-
-String VisualScriptExpression::get_caption() const {
- return RTR("Expression");
-}
-
-String VisualScriptExpression::get_text() const {
- return expression;
-}
-
-Error VisualScriptExpression::_get_token(Token &r_token) {
- while (true) {
-#define GET_CHAR() (str_ofs >= expression.length() ? 0 : expression[str_ofs++])
-
- char32_t cchar = GET_CHAR();
- if (cchar == 0) {
- r_token.type = TK_EOF;
- return OK;
- }
-
- switch (cchar) {
- case 0: {
- r_token.type = TK_EOF;
- return OK;
- } break;
- case '{': {
- r_token.type = TK_CURLY_BRACKET_OPEN;
- return OK;
- };
- case '}': {
- r_token.type = TK_CURLY_BRACKET_CLOSE;
- return OK;
- };
- case '[': {
- r_token.type = TK_BRACKET_OPEN;
- return OK;
- };
- case ']': {
- r_token.type = TK_BRACKET_CLOSE;
- return OK;
- };
- case '(': {
- r_token.type = TK_PARENTHESIS_OPEN;
- return OK;
- };
- case ')': {
- r_token.type = TK_PARENTHESIS_CLOSE;
- return OK;
- };
- case ',': {
- r_token.type = TK_COMMA;
- return OK;
- };
- case ':': {
- r_token.type = TK_COLON;
- return OK;
- };
- case '.': {
- r_token.type = TK_PERIOD;
- return OK;
- };
- case '=': {
- cchar = GET_CHAR();
- if (cchar == '=') {
- r_token.type = TK_OP_EQUAL;
- } else {
- _set_error("Expected '='");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- return OK;
- };
- case '!': {
- if (expression[str_ofs] == '=') {
- r_token.type = TK_OP_NOT_EQUAL;
- str_ofs++;
- } else {
- r_token.type = TK_OP_NOT;
- }
- return OK;
- };
- case '>': {
- if (expression[str_ofs] == '=') {
- r_token.type = TK_OP_GREATER_EQUAL;
- str_ofs++;
- } else if (expression[str_ofs] == '>') {
- r_token.type = TK_OP_SHIFT_RIGHT;
- str_ofs++;
- } else {
- r_token.type = TK_OP_GREATER;
- }
- return OK;
- };
- case '<': {
- if (expression[str_ofs] == '=') {
- r_token.type = TK_OP_LESS_EQUAL;
- str_ofs++;
- } else if (expression[str_ofs] == '<') {
- r_token.type = TK_OP_SHIFT_LEFT;
- str_ofs++;
- } else {
- r_token.type = TK_OP_LESS;
- }
- return OK;
- };
- case '+': {
- r_token.type = TK_OP_ADD;
- return OK;
- };
- case '-': {
- r_token.type = TK_OP_SUB;
- return OK;
- };
- case '/': {
- r_token.type = TK_OP_DIV;
- return OK;
- };
- case '*': {
- r_token.type = TK_OP_MUL;
- return OK;
- };
- case '%': {
- r_token.type = TK_OP_MOD;
- return OK;
- };
- case '&': {
- if (expression[str_ofs] == '&') {
- r_token.type = TK_OP_AND;
- str_ofs++;
- } else {
- r_token.type = TK_OP_BIT_AND;
- }
- return OK;
- };
- case '|': {
- if (expression[str_ofs] == '|') {
- r_token.type = TK_OP_OR;
- str_ofs++;
- } else {
- r_token.type = TK_OP_BIT_OR;
- }
- return OK;
- };
- case '^': {
- r_token.type = TK_OP_BIT_XOR;
-
- return OK;
- };
- case '~': {
- r_token.type = TK_OP_BIT_INVERT;
-
- return OK;
- };
- case '"': {
- String str;
- char32_t prev = 0;
- while (true) {
- char32_t ch = GET_CHAR();
-
- if (ch == 0) {
- _set_error("Unterminated String");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- } else if (ch == '"') {
- break;
- } else if (ch == '\\') {
- //escaped characters...
-
- char32_t next = GET_CHAR();
- if (next == 0) {
- _set_error("Unterminated String");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- char32_t res = 0;
-
- switch (next) {
- case 'b':
- res = 8;
- break;
- case 't':
- res = 9;
- break;
- case 'n':
- res = 10;
- break;
- case 'f':
- res = 12;
- break;
- case 'r':
- res = 13;
- break;
- case 'U':
- case 'u': {
- // Hexadecimal sequence.
- int hex_len = (next == 'U') ? 6 : 4;
- for (int j = 0; j < hex_len; j++) {
- char32_t c = GET_CHAR();
-
- if (c == 0) {
- _set_error("Unterminated String");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- if (!is_hex_digit(c)) {
- _set_error("Malformed hex constant in string");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- char32_t v;
- if (is_digit(c)) {
- v = c - '0';
- } else if (c >= 'a' && c <= 'f') {
- v = c - 'a';
- v += 10;
- } else if (c >= 'A' && c <= 'F') {
- v = c - 'A';
- v += 10;
- } else {
- ERR_PRINT("Bug parsing hex constant.");
- v = 0;
- }
-
- res <<= 4;
- res |= v;
- }
-
- } break;
- default: {
- res = next;
- } break;
- }
-
- // Parse UTF-16 pair.
- if ((res & 0xfffffc00) == 0xd800) {
- if (prev == 0) {
- prev = res;
- continue;
- } else {
- _set_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- } else if ((res & 0xfffffc00) == 0xdc00) {
- if (prev == 0) {
- _set_error("Invalid UTF-16 sequence in string, unpaired trail surrogate");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- } else {
- res = (prev << 10UL) + res - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
- prev = 0;
- }
- }
- if (prev != 0) {
- _set_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- str += res;
- } else {
- if (prev != 0) {
- _set_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- str += ch;
- }
- }
- if (prev != 0) {
- _set_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
-
- r_token.type = TK_CONSTANT;
- r_token.value = str;
- return OK;
-
- } break;
- default: {
- if (cchar <= 32) {
- break;
- }
-
- if (is_digit(cchar)) {
- //a number
-
- String num;
-#define READING_SIGN 0
-#define READING_INT 1
-#define READING_DEC 2
-#define READING_EXP 3
-#define READING_DONE 4
- int reading = READING_INT;
-
- char32_t c = cchar;
- bool exp_sign = false;
- bool exp_beg = false;
- bool is_float = false;
-
- while (true) {
- switch (reading) {
- case READING_INT: {
- if (is_digit(c)) {
- //pass
- } else if (c == '.') {
- reading = READING_DEC;
- is_float = true;
- } else if (c == 'e') {
- reading = READING_EXP;
- } else {
- reading = READING_DONE;
- }
-
- } break;
- case READING_DEC: {
- if (is_digit(c)) {
- } else if (c == 'e') {
- reading = READING_EXP;
-
- } else {
- reading = READING_DONE;
- }
-
- } break;
- case READING_EXP: {
- if (is_digit(c)) {
- exp_beg = true;
-
- } else if ((c == '-' || c == '+') && !exp_sign && !exp_beg) {
- if (c == '-') {
- is_float = true;
- }
- exp_sign = true;
-
- } else {
- reading = READING_DONE;
- }
- } break;
- }
-
- if (reading == READING_DONE) {
- break;
- }
- num += String::chr(c);
- c = GET_CHAR();
- }
-
- str_ofs--;
-
- r_token.type = TK_CONSTANT;
-
- if (is_float) {
- r_token.value = num.to_float();
- } else {
- r_token.value = num.to_int();
- }
- return OK;
-
- } else if (is_ascii_char(cchar) || cchar == '_') {
- String id;
- bool first = true;
-
- while (is_ascii_char(cchar) || cchar == '_' || (!first && is_digit(cchar))) {
- id += String::chr(cchar);
- cchar = GET_CHAR();
- first = false;
- }
-
- str_ofs--; //go back one
-
- if (id == "in") {
- r_token.type = TK_OP_IN;
- } else if (id == "null") {
- r_token.type = TK_CONSTANT;
- r_token.value = Variant();
- } else if (id == "true") {
- r_token.type = TK_CONSTANT;
- r_token.value = true;
- } else if (id == "false") {
- r_token.type = TK_CONSTANT;
- r_token.value = false;
- } else if (id == "PI") {
- r_token.type = TK_CONSTANT;
- r_token.value = Math_PI;
- } else if (id == "TAU") {
- r_token.type = TK_CONSTANT;
- r_token.value = Math_TAU;
- } else if (id == "INF") {
- r_token.type = TK_CONSTANT;
- r_token.value = INFINITY;
- } else if (id == "NAN") {
- r_token.type = TK_CONSTANT;
- r_token.value = NAN;
- } else if (id == "not") {
- r_token.type = TK_OP_NOT;
- } else if (id == "or") {
- r_token.type = TK_OP_OR;
- } else if (id == "and") {
- r_token.type = TK_OP_AND;
- } else if (id == "self") {
- r_token.type = TK_SELF;
- } else {
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (id == Variant::get_type_name(Variant::Type(i))) {
- r_token.type = TK_BASIC_TYPE;
- r_token.value = i;
- return OK;
- }
- }
-
- VisualScriptBuiltinFunc::BuiltinFunc bifunc = VisualScriptBuiltinFunc::find_function(id);
- if (bifunc != VisualScriptBuiltinFunc::FUNC_MAX) {
- r_token.type = TK_BUILTIN_FUNC;
- r_token.value = bifunc;
- return OK;
- }
-
- r_token.type = TK_IDENTIFIER;
- r_token.value = id;
- }
-
- return OK;
- } else {
- _set_error("Unexpected character.");
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
- }
- }
- }
- }
-
- r_token.type = TK_ERROR;
- return ERR_PARSE_ERROR;
-}
-
-const char *VisualScriptExpression::token_name[TK_MAX] = {
- "CURLY BRACKET OPEN",
- "CURLY BRACKET CLOSE",
- "BRACKET OPEN",
- "BRACKET CLOSE",
- "PARENTHESIS OPEN",
- "PARENTHESIS CLOSE",
- "IDENTIFIER",
- "BUILTIN FUNC",
- "SELF",
- "CONSTANT",
- "BASIC TYPE",
- "COLON",
- "COMMA",
- "PERIOD",
- "OP IN",
- "OP EQUAL",
- "OP NOT EQUAL",
- "OP LESS",
- "OP LESS EQUAL",
- "OP GREATER",
- "OP GREATER EQUAL",
- "OP AND",
- "OP OR",
- "OP NOT",
- "OP ADD",
- "OP SUB",
- "OP MUL",
- "OP DIV",
- "OP MOD",
- "OP SHIFT LEFT",
- "OP SHIFT RIGHT",
- "OP BIT AND",
- "OP BIT OR",
- "OP BIT XOR",
- "OP BIT INVERT",
- "EOF",
- "ERROR"
-};
-
-VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
- Vector<Expression> expression;
-
- while (true) {
- //keep appending stuff to expression
- ENode *expr = nullptr;
-
- Token tk;
- _get_token(tk);
- if (error_set) {
- return nullptr;
- }
-
- switch (tk.type) {
- case TK_CURLY_BRACKET_OPEN: {
- //a dictionary
- DictionaryNode *dn = alloc_node<DictionaryNode>();
-
- while (true) {
- int cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_CURLY_BRACKET_CLOSE) {
- break;
- }
- str_ofs = cofs; //revert
- //parse an expression
- ENode *expr2 = _parse_expression();
- if (!expr2) {
- return nullptr;
- }
- dn->dict.push_back(expr2);
-
- _get_token(tk);
- if (tk.type != TK_COLON) {
- _set_error("Expected ':'");
- return nullptr;
- }
-
- expr2 = _parse_expression();
- if (!expr2) {
- return nullptr;
- }
-
- dn->dict.push_back(expr2);
-
- cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_COMMA) {
- //all good
- } else if (tk.type == TK_CURLY_BRACKET_CLOSE) {
- str_ofs = cofs;
- } else {
- _set_error("Expected ',' or '}'");
- }
- }
-
- expr = dn;
- } break;
- case TK_BRACKET_OPEN: {
- //an array
-
- ArrayNode *an = alloc_node<ArrayNode>();
-
- while (true) {
- int cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_BRACKET_CLOSE) {
- break;
- }
- str_ofs = cofs; //revert
- //parse an expression
- ENode *expr2 = _parse_expression();
- if (!expr2) {
- return nullptr;
- }
- an->array.push_back(expr2);
-
- cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_COMMA) {
- //all good
- } else if (tk.type == TK_BRACKET_CLOSE) {
- str_ofs = cofs;
- } else {
- _set_error("Expected ',' or ']'");
- }
- }
-
- expr = an;
- } break;
- case TK_PARENTHESIS_OPEN: {
- //a suexpression
- ENode *e = _parse_expression();
- if (error_set) {
- return nullptr;
- }
- _get_token(tk);
- if (tk.type != TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')'");
- return nullptr;
- }
-
- expr = e;
-
- } break;
- case TK_IDENTIFIER: {
- String what = tk.value;
- int index = -1;
- for (int i = 0; i < inputs.size(); i++) {
- if (what == inputs[i].name) {
- index = i;
- break;
- }
- }
-
- if (index != -1) {
- InputNode *input = alloc_node<InputNode>();
- input->index = index;
- expr = input;
- } else {
- _set_error("Invalid input identifier '" + what + "'. For script variables, use self (locals are for inputs)." + what);
- return nullptr;
- }
- } break;
- case TK_SELF: {
- SelfNode *self = alloc_node<SelfNode>();
- expr = self;
- } break;
- case TK_CONSTANT: {
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = tk.value;
- expr = constant;
- } break;
- case TK_BASIC_TYPE: {
- //constructor..
-
- Variant::Type bt = Variant::Type(int(tk.value));
- _get_token(tk);
- if (tk.type != TK_PARENTHESIS_OPEN) {
- _set_error("Expected '('");
- return nullptr;
- }
-
- ConstructorNode *constructor = alloc_node<ConstructorNode>();
- constructor->data_type = bt;
-
- while (true) {
- int cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_PARENTHESIS_CLOSE) {
- break;
- }
- str_ofs = cofs; //revert
- //parse an expression
- ENode *expr2 = _parse_expression();
- if (!expr2) {
- return nullptr;
- }
-
- constructor->arguments.push_back(expr2);
-
- cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_COMMA) {
- //all good
- } else if (tk.type == TK_PARENTHESIS_CLOSE) {
- str_ofs = cofs;
- } else {
- _set_error("Expected ',' or ')'");
- }
- }
-
- expr = constructor;
-
- } break;
- case TK_BUILTIN_FUNC: {
- //builtin function
-
- _get_token(tk);
- if (tk.type != TK_PARENTHESIS_OPEN) {
- _set_error("Expected '('");
- return nullptr;
- }
-
- BuiltinFuncNode *bifunc = alloc_node<BuiltinFuncNode>();
- bifunc->func = VisualScriptBuiltinFunc::BuiltinFunc(int(tk.value));
-
- while (true) {
- int cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_PARENTHESIS_CLOSE) {
- break;
- }
- str_ofs = cofs; //revert
- //parse an expression
- ENode *expr2 = _parse_expression();
- if (!expr2) {
- return nullptr;
- }
-
- bifunc->arguments.push_back(expr2);
-
- cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_COMMA) {
- //all good
- } else if (tk.type == TK_PARENTHESIS_CLOSE) {
- str_ofs = cofs;
- } else {
- _set_error("Expected ',' or ')'");
- }
- }
-
- int expected_args = VisualScriptBuiltinFunc::get_func_argument_count(bifunc->func);
- if (bifunc->arguments.size() != expected_args) {
- _set_error("Builtin func '" + VisualScriptBuiltinFunc::get_func_name(bifunc->func) + "' expects " + itos(expected_args) + " arguments.");
- }
-
- expr = bifunc;
-
- } break;
- case TK_OP_SUB: {
- Expression e;
- e.is_op = true;
- e.op = Variant::OP_NEGATE;
- expression.push_back(e);
- continue;
- } break;
- case TK_OP_NOT: {
- Expression e;
- e.is_op = true;
- e.op = Variant::OP_NOT;
- expression.push_back(e);
- continue;
- } break;
-
- default: {
- _set_error("Expected expression.");
- return nullptr;
- } break;
- }
-
- //before going to operators, must check indexing!
-
- while (true) {
- int cofs2 = str_ofs;
- _get_token(tk);
- if (error_set) {
- return nullptr;
- }
-
- bool done = false;
-
- switch (tk.type) {
- case TK_BRACKET_OPEN: {
- //value indexing
-
- IndexNode *index = alloc_node<IndexNode>();
- index->base = expr;
-
- ENode *what = _parse_expression();
- if (!what) {
- return nullptr;
- }
-
- index->index = what;
-
- _get_token(tk);
- if (tk.type != TK_BRACKET_CLOSE) {
- _set_error("Expected ']' at end of index.");
- return nullptr;
- }
- expr = index;
-
- } break;
- case TK_PERIOD: {
- //named indexing or function call
- _get_token(tk);
- if (tk.type != TK_IDENTIFIER) {
- _set_error("Expected identifier after '.'");
- return nullptr;
- }
-
- StringName identifier = tk.value;
-
- int cofs = str_ofs;
- _get_token(tk);
- if (tk.type == TK_PARENTHESIS_OPEN) {
- //function call
- CallNode *func_call = alloc_node<CallNode>();
- func_call->method = identifier;
- func_call->base = expr;
-
- while (true) {
- int cofs3 = str_ofs;
- _get_token(tk);
- if (tk.type == TK_PARENTHESIS_CLOSE) {
- break;
- }
- str_ofs = cofs3; //revert
- //parse an expression
- ENode *expr2 = _parse_expression();
- if (!expr2) {
- return nullptr;
- }
-
- func_call->arguments.push_back(expr2);
-
- cofs3 = str_ofs;
- _get_token(tk);
- if (tk.type == TK_COMMA) {
- //all good
- } else if (tk.type == TK_PARENTHESIS_CLOSE) {
- str_ofs = cofs3;
- } else {
- _set_error("Expected ',' or ')'");
- }
- }
-
- expr = func_call;
- } else {
- //named indexing
- str_ofs = cofs;
-
- NamedIndexNode *index = alloc_node<NamedIndexNode>();
- index->base = expr;
- index->name = identifier;
- expr = index;
- }
-
- } break;
- default: {
- str_ofs = cofs2;
- done = true;
- } break;
- }
-
- if (done) {
- break;
- }
- }
-
- //push expression
- {
- Expression e;
- e.is_op = false;
- e.node = expr;
- expression.push_back(e);
- }
-
- //ok finally look for an operator
-
- int cofs = str_ofs;
- _get_token(tk);
- if (error_set) {
- return nullptr;
- }
-
- Variant::Operator op = Variant::OP_MAX;
-
- switch (tk.type) {
- case TK_OP_IN:
- op = Variant::OP_IN;
- break;
- case TK_OP_EQUAL:
- op = Variant::OP_EQUAL;
- break;
- case TK_OP_NOT_EQUAL:
- op = Variant::OP_NOT_EQUAL;
- break;
- case TK_OP_LESS:
- op = Variant::OP_LESS;
- break;
- case TK_OP_LESS_EQUAL:
- op = Variant::OP_LESS_EQUAL;
- break;
- case TK_OP_GREATER:
- op = Variant::OP_GREATER;
- break;
- case TK_OP_GREATER_EQUAL:
- op = Variant::OP_GREATER_EQUAL;
- break;
- case TK_OP_AND:
- op = Variant::OP_AND;
- break;
- case TK_OP_OR:
- op = Variant::OP_OR;
- break;
- case TK_OP_NOT:
- op = Variant::OP_NOT;
- break;
- case TK_OP_ADD:
- op = Variant::OP_ADD;
- break;
- case TK_OP_SUB:
- op = Variant::OP_SUBTRACT;
- break;
- case TK_OP_MUL:
- op = Variant::OP_MULTIPLY;
- break;
- case TK_OP_DIV:
- op = Variant::OP_DIVIDE;
- break;
- case TK_OP_MOD:
- op = Variant::OP_MODULE;
- break;
- case TK_OP_SHIFT_LEFT:
- op = Variant::OP_SHIFT_LEFT;
- break;
- case TK_OP_SHIFT_RIGHT:
- op = Variant::OP_SHIFT_RIGHT;
- break;
- case TK_OP_BIT_AND:
- op = Variant::OP_BIT_AND;
- break;
- case TK_OP_BIT_OR:
- op = Variant::OP_BIT_OR;
- break;
- case TK_OP_BIT_XOR:
- op = Variant::OP_BIT_XOR;
- break;
- case TK_OP_BIT_INVERT:
- op = Variant::OP_BIT_NEGATE;
- break;
- default: {
- };
- }
-
- if (op == Variant::OP_MAX) { //stop appending stuff
- str_ofs = cofs;
- break;
- }
-
- //push operator and go on
- {
- Expression e;
- e.is_op = true;
- e.op = op;
- expression.push_back(e);
- }
- }
-
- /* Reduce the set of expressions and place them in an operator tree, respecting precedence */
-
- while (expression.size() > 1) {
- int next_op = -1;
- int min_priority = 0xFFFFF;
- bool is_unary = false;
-
- for (int i = 0; i < expression.size(); i++) {
- if (!expression[i].is_op) {
- continue;
- }
-
- int priority;
-
- bool unary = false;
-
- switch (expression[i].op) {
- case Variant::OP_BIT_NEGATE:
- priority = 0;
- unary = true;
- break;
- case Variant::OP_NEGATE:
- priority = 1;
- unary = true;
- break;
-
- case Variant::OP_MULTIPLY:
- priority = 2;
- break;
- case Variant::OP_DIVIDE:
- priority = 2;
- break;
- case Variant::OP_MODULE:
- priority = 2;
- break;
-
- case Variant::OP_ADD:
- priority = 3;
- break;
- case Variant::OP_SUBTRACT:
- priority = 3;
- break;
-
- case Variant::OP_SHIFT_LEFT:
- priority = 4;
- break;
- case Variant::OP_SHIFT_RIGHT:
- priority = 4;
- break;
-
- case Variant::OP_BIT_AND:
- priority = 5;
- break;
- case Variant::OP_BIT_XOR:
- priority = 6;
- break;
- case Variant::OP_BIT_OR:
- priority = 7;
- break;
-
- case Variant::OP_LESS:
- priority = 8;
- break;
- case Variant::OP_LESS_EQUAL:
- priority = 8;
- break;
- case Variant::OP_GREATER:
- priority = 8;
- break;
- case Variant::OP_GREATER_EQUAL:
- priority = 8;
- break;
-
- case Variant::OP_EQUAL:
- priority = 8;
- break;
- case Variant::OP_NOT_EQUAL:
- priority = 8;
- break;
-
- case Variant::OP_IN:
- priority = 10;
- break;
-
- case Variant::OP_NOT:
- priority = 11;
- unary = true;
- break;
- case Variant::OP_AND:
- priority = 12;
- break;
- case Variant::OP_OR:
- priority = 13;
- break;
-
- default: {
- _set_error("Parser bug, invalid operator in expression: " + itos(expression[i].op));
- return nullptr;
- }
- }
-
- if (priority < min_priority) {
- // < is used for left to right (default)
- // <= is used for right to left
-
- next_op = i;
- min_priority = priority;
- is_unary = unary;
- }
- }
-
- if (next_op == -1) {
- _set_error("Yet another parser bug....");
- ERR_FAIL_V(nullptr);
- }
-
- // OK! create operator..
- if (is_unary) {
- int expr_pos = next_op;
- while (expression[expr_pos].is_op) {
- expr_pos++;
- if (expr_pos == expression.size()) {
- //can happen..
- _set_error("Unexpected end of expression...");
- return nullptr;
- }
- }
-
- //consecutively do unary operators
- for (int i = expr_pos - 1; i >= next_op; i--) {
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = expression[i].op;
- op->nodes[0] = expression[i + 1].node;
- op->nodes[1] = nullptr;
- expression.write[i].is_op = false;
- expression.write[i].node = op;
- expression.remove_at(i + 1);
- }
-
- } else {
- if (next_op < 1 || next_op >= (expression.size() - 1)) {
- _set_error("Parser bug...");
- ERR_FAIL_V(nullptr);
- }
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = expression[next_op].op;
-
- if (expression[next_op - 1].is_op) {
- _set_error("Parser bug...");
- ERR_FAIL_V(nullptr);
- }
-
- if (expression[next_op + 1].is_op) {
- // this is not invalid and can really appear
- // but it becomes invalid anyway because no binary op
- // can be followed by a unary op in a valid combination,
- // due to how precedence works, unaries will always disappear first
-
- _set_error("Unexpected two consecutive operators.");
- return nullptr;
- }
-
- op->nodes[0] = expression[next_op - 1].node; //expression goes as left
- op->nodes[1] = expression[next_op + 1].node; //next expression goes as right
-
- //replace all 3 nodes by this operator and make it an expression
- expression.write[next_op - 1].node = op;
- expression.remove_at(next_op);
- expression.remove_at(next_op);
- }
- }
-
- return expression[0].node;
-}
-
-bool VisualScriptExpression::_compile_expression() {
- if (!expression_dirty) {
- return error_set;
- }
-
- if (nodes) {
- memdelete(nodes);
- nodes = nullptr;
- root = nullptr;
- }
-
- error_str = String();
- error_set = false;
- str_ofs = 0;
-
- root = _parse_expression();
-
- if (error_set) {
- root = nullptr;
- if (nodes) {
- memdelete(nodes);
- }
- nodes = nullptr;
- return true;
- }
-
- expression_dirty = false;
- return false;
-}
-
-class VisualScriptNodeInstanceExpression : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- VisualScriptExpression *expression = nullptr;
-
- //virtual int get_working_memory_size() const override { return 0; }
- //execute by parsing the tree directly
- virtual bool _execute(const Variant **p_inputs, VisualScriptExpression::ENode *p_node, Variant &r_ret, String &r_error_str, Callable::CallError &ce) {
- switch (p_node->type) {
- case VisualScriptExpression::ENode::TYPE_INPUT: {
- const VisualScriptExpression::InputNode *in = static_cast<const VisualScriptExpression::InputNode *>(p_node);
- r_ret = *p_inputs[in->index];
- } break;
- case VisualScriptExpression::ENode::TYPE_CONSTANT: {
- const VisualScriptExpression::ConstantNode *c = static_cast<const VisualScriptExpression::ConstantNode *>(p_node);
- r_ret = c->value;
-
- } break;
- case VisualScriptExpression::ENode::TYPE_SELF: {
- r_ret = instance->get_owner_ptr();
- } break;
- case VisualScriptExpression::ENode::TYPE_OPERATOR: {
- const VisualScriptExpression::OperatorNode *op = static_cast<const VisualScriptExpression::OperatorNode *>(p_node);
-
- Variant a;
- bool ret = _execute(p_inputs, op->nodes[0], a, r_error_str, ce);
- if (ret) {
- return true;
- }
-
- Variant b;
-
- if (op->nodes[1]) {
- ret = _execute(p_inputs, op->nodes[1], b, r_error_str, ce);
- if (ret) {
- return true;
- }
- }
-
- bool valid = true;
- Variant::evaluate(op->op, a, b, r_ret, valid);
- if (!valid) {
- r_error_str = "Invalid operands to operator " + Variant::get_operator_name(op->op) + ": " + Variant::get_type_name(a.get_type()) + " and " + Variant::get_type_name(b.get_type()) + ".";
- return true;
- }
-
- } break;
- case VisualScriptExpression::ENode::TYPE_INDEX: {
- const VisualScriptExpression::IndexNode *index = static_cast<const VisualScriptExpression::IndexNode *>(p_node);
-
- Variant base;
- bool ret = _execute(p_inputs, index->base, base, r_error_str, ce);
- if (ret) {
- return true;
- }
-
- Variant idx;
-
- ret = _execute(p_inputs, index->index, idx, r_error_str, ce);
- if (ret) {
- return true;
- }
-
- bool valid;
- r_ret = base.get(idx, &valid);
- if (!valid) {
- r_error_str = "Invalid index of type " + Variant::get_type_name(idx.get_type()) + " for base of type " + Variant::get_type_name(base.get_type()) + ".";
- return true;
- }
-
- } break;
- case VisualScriptExpression::ENode::TYPE_NAMED_INDEX: {
- const VisualScriptExpression::NamedIndexNode *index = static_cast<const VisualScriptExpression::NamedIndexNode *>(p_node);
-
- Variant base;
- bool ret = _execute(p_inputs, index->base, base, r_error_str, ce);
- if (ret) {
- return true;
- }
-
- bool valid;
- r_ret = base.get_named(index->name, valid);
- if (!valid) {
- r_error_str = "Invalid index '" + String(index->name) + "' for base of type " + Variant::get_type_name(base.get_type()) + ".";
- return true;
- }
-
- } break;
- case VisualScriptExpression::ENode::TYPE_ARRAY: {
- const VisualScriptExpression::ArrayNode *array = static_cast<const VisualScriptExpression::ArrayNode *>(p_node);
-
- Array arr;
- arr.resize(array->array.size());
- for (int i = 0; i < array->array.size(); i++) {
- Variant value;
- bool ret = _execute(p_inputs, array->array[i], value, r_error_str, ce);
- if (ret) {
- return true;
- }
- arr[i] = value;
- }
-
- r_ret = arr;
-
- } break;
- case VisualScriptExpression::ENode::TYPE_DICTIONARY: {
- const VisualScriptExpression::DictionaryNode *dictionary = static_cast<const VisualScriptExpression::DictionaryNode *>(p_node);
-
- Dictionary d;
- for (int i = 0; i < dictionary->dict.size(); i += 2) {
- Variant key;
- bool ret = _execute(p_inputs, dictionary->dict[i + 0], key, r_error_str, ce);
- if (ret) {
- return true;
- }
-
- Variant value;
- ret = _execute(p_inputs, dictionary->dict[i + 1], value, r_error_str, ce);
- if (ret) {
- return true;
- }
-
- d[key] = value;
- }
-
- r_ret = d;
- } break;
- case VisualScriptExpression::ENode::TYPE_CONSTRUCTOR: {
- const VisualScriptExpression::ConstructorNode *constructor = static_cast<const VisualScriptExpression::ConstructorNode *>(p_node);
-
- Vector<Variant> arr;
- Vector<const Variant *> argp;
- arr.resize(constructor->arguments.size());
- argp.resize(constructor->arguments.size());
-
- for (int i = 0; i < constructor->arguments.size(); i++) {
- Variant value;
- bool ret = _execute(p_inputs, constructor->arguments[i], value, r_error_str, ce);
- if (ret) {
- return true;
- }
- arr.write[i] = value;
- argp.write[i] = &arr[i];
- }
-
- Variant::construct(constructor->data_type, r_ret, (const Variant **)argp.ptr(), argp.size(), ce);
-
- if (ce.error != Callable::CallError::CALL_OK) {
- r_error_str = "Invalid arguments to construct '" + Variant::get_type_name(constructor->data_type) + "'.";
- return true;
- }
-
- } break;
- case VisualScriptExpression::ENode::TYPE_BUILTIN_FUNC: {
- const VisualScriptExpression::BuiltinFuncNode *bifunc = static_cast<const VisualScriptExpression::BuiltinFuncNode *>(p_node);
-
- Vector<Variant> arr;
- Vector<const Variant *> argp;
- arr.resize(bifunc->arguments.size());
- argp.resize(bifunc->arguments.size());
-
- for (int i = 0; i < bifunc->arguments.size(); i++) {
- Variant value;
- bool ret = _execute(p_inputs, bifunc->arguments[i], value, r_error_str, ce);
- if (ret) {
- return true;
- }
- arr.write[i] = value;
- argp.write[i] = &arr[i];
- }
-
- VisualScriptBuiltinFunc::exec_func(bifunc->func, (const Variant **)argp.ptr(), &r_ret, ce, r_error_str);
-
- if (ce.error != Callable::CallError::CALL_OK) {
- r_error_str = "Builtin Call Failed. " + r_error_str;
- return true;
- }
-
- } break;
- case VisualScriptExpression::ENode::TYPE_CALL: {
- const VisualScriptExpression::CallNode *call = static_cast<const VisualScriptExpression::CallNode *>(p_node);
-
- Variant base;
- bool ret = _execute(p_inputs, call->base, base, r_error_str, ce);
- if (ret) {
- return true;
- }
-
- Vector<Variant> arr;
- Vector<const Variant *> argp;
- arr.resize(call->arguments.size());
- argp.resize(call->arguments.size());
-
- for (int i = 0; i < call->arguments.size(); i++) {
- Variant value;
- bool ret2 = _execute(p_inputs, call->arguments[i], value, r_error_str, ce);
- if (ret2) {
- return true;
- }
- arr.write[i] = value;
- argp.write[i] = &arr[i];
- }
-
- 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) + "':";
- return true;
- }
-
- } break;
- }
- return false;
- }
-
- 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) override {
- if (!expression->root || expression->error_set) {
- r_error_str = expression->error_str;
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return 0;
- }
-
- bool error = _execute(p_inputs, expression->root, *p_outputs[0], r_error_str, r_error);
- if (error && r_error.error == Callable::CallError::CALL_OK) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- }
-
-#ifdef DEBUG_ENABLED
- if (!error && expression->output_type != Variant::NIL && !Variant::can_convert_strict(p_outputs[0]->get_type(), expression->output_type)) {
- r_error_str += "Can't convert expression result from " + Variant::get_type_name(p_outputs[0]->get_type()) + " to " + Variant::get_type_name(expression->output_type) + ".";
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- }
-#endif
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptExpression::instantiate(VisualScriptInstance *p_instance) {
- _compile_expression();
- VisualScriptNodeInstanceExpression *instance = memnew(VisualScriptNodeInstanceExpression);
- instance->instance = p_instance;
- instance->expression = this;
- return instance;
-}
-
-void VisualScriptExpression::reset_state() {
- if (nodes) {
- memdelete(nodes);
- nodes = nullptr;
- root = nullptr;
- }
-
- error_str = String();
- error_set = false;
- str_ofs = 0;
- inputs.clear();
-}
-
-VisualScriptExpression::VisualScriptExpression() {
-}
-
-VisualScriptExpression::~VisualScriptExpression() {
- if (nodes) {
- memdelete(nodes);
- }
-}
-
-void register_visual_script_expression_node() {
- VisualScriptLanguage::singleton->add_register_func("operators/expression", create_node_generic<VisualScriptExpression>);
-}
diff --git a/modules/visual_script/visual_script_expression.h b/modules/visual_script/visual_script_expression.h
deleted file mode 100644
index 7e10f98f36..0000000000
--- a/modules/visual_script/visual_script_expression.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/*************************************************************************/
-/* visual_script_expression.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 VISUAL_SCRIPT_EXPRESSION_H
-#define VISUAL_SCRIPT_EXPRESSION_H
-
-#include "visual_script.h"
-#include "visual_script_builtin_funcs.h"
-
-class VisualScriptExpression : public VisualScriptNode {
- GDCLASS(VisualScriptExpression, VisualScriptNode);
- friend class VisualScriptNodeInstanceExpression;
-
- struct Input {
- Variant::Type type = Variant::NIL;
- String name;
- };
-
- Vector<Input> inputs;
- Variant::Type output_type = Variant::NIL;
-
- String expression;
-
- bool sequenced = false;
- int str_ofs = 0;
- bool expression_dirty = true;
-
- bool _compile_expression();
-
- enum TokenType {
- TK_CURLY_BRACKET_OPEN,
- TK_CURLY_BRACKET_CLOSE,
- TK_BRACKET_OPEN,
- TK_BRACKET_CLOSE,
- TK_PARENTHESIS_OPEN,
- TK_PARENTHESIS_CLOSE,
- TK_IDENTIFIER,
- TK_BUILTIN_FUNC,
- TK_SELF,
- TK_CONSTANT,
- TK_BASIC_TYPE,
- TK_COLON,
- TK_COMMA,
- TK_PERIOD,
- TK_OP_IN,
- TK_OP_EQUAL,
- TK_OP_NOT_EQUAL,
- TK_OP_LESS,
- TK_OP_LESS_EQUAL,
- TK_OP_GREATER,
- TK_OP_GREATER_EQUAL,
- TK_OP_AND,
- TK_OP_OR,
- TK_OP_NOT,
- TK_OP_ADD,
- TK_OP_SUB,
- TK_OP_MUL,
- TK_OP_DIV,
- TK_OP_MOD,
- TK_OP_SHIFT_LEFT,
- TK_OP_SHIFT_RIGHT,
- TK_OP_BIT_AND,
- TK_OP_BIT_OR,
- TK_OP_BIT_XOR,
- TK_OP_BIT_INVERT,
- TK_EOF,
- TK_ERROR,
- TK_MAX
- };
-
- static const char *token_name[TK_MAX];
- struct Token {
- TokenType type;
- Variant value;
- };
-
- void _set_error(const String &p_err) {
- if (error_set) {
- return;
- }
- error_str = p_err;
- error_set = true;
- }
-
- Error _get_token(Token &r_token);
-
- String error_str;
- bool error_set = true;
-
- struct ENode {
- enum Type {
- TYPE_INPUT,
- TYPE_CONSTANT,
- TYPE_SELF,
- TYPE_OPERATOR,
- TYPE_INDEX,
- TYPE_NAMED_INDEX,
- TYPE_ARRAY,
- TYPE_DICTIONARY,
- TYPE_CONSTRUCTOR,
- TYPE_BUILTIN_FUNC,
- TYPE_CALL
- };
-
- ENode *next = nullptr;
-
- Type type = Type::TYPE_SELF;
-
- virtual ~ENode() {
- if (next) {
- memdelete(next);
- }
- }
- };
-
- struct Expression {
- bool is_op = false;
- union {
- Variant::Operator op;
- ENode *node = nullptr;
- };
- };
-
- ENode *_parse_expression();
-
- struct InputNode : public ENode {
- int index = 0;
- InputNode() {
- type = TYPE_INPUT;
- }
- };
-
- struct ConstantNode : public ENode {
- Variant value;
- ConstantNode() {
- type = TYPE_CONSTANT;
- }
- };
-
- struct OperatorNode : public ENode {
- Variant::Operator op = Variant::Operator::OP_ADD;
-
- ENode *nodes[2] = { nullptr, nullptr };
-
- OperatorNode() {
- type = TYPE_OPERATOR;
- }
- };
-
- struct SelfNode : public ENode {
- SelfNode() {
- type = TYPE_SELF;
- }
- };
-
- struct IndexNode : public ENode {
- ENode *base = nullptr;
- ENode *index = nullptr;
-
- IndexNode() {
- type = TYPE_INDEX;
- }
- };
-
- struct NamedIndexNode : public ENode {
- ENode *base = nullptr;
- StringName name;
-
- NamedIndexNode() {
- type = TYPE_NAMED_INDEX;
- }
- };
-
- struct ConstructorNode : public ENode {
- Variant::Type data_type = Variant::Type::NIL;
- Vector<ENode *> arguments;
-
- ConstructorNode() {
- type = TYPE_CONSTRUCTOR;
- }
- };
-
- struct CallNode : public ENode {
- ENode *base = nullptr;
- StringName method;
- Vector<ENode *> arguments;
-
- CallNode() {
- type = TYPE_CALL;
- }
- };
-
- struct ArrayNode : public ENode {
- Vector<ENode *> array;
- ArrayNode() {
- type = TYPE_ARRAY;
- }
- };
-
- struct DictionaryNode : public ENode {
- Vector<ENode *> dict;
- DictionaryNode() {
- type = TYPE_DICTIONARY;
- }
- };
-
- struct BuiltinFuncNode : public ENode {
- VisualScriptBuiltinFunc::BuiltinFunc func = VisualScriptBuiltinFunc::BuiltinFunc::BYTES_TO_VAR;
- Vector<ENode *> arguments;
- BuiltinFuncNode() {
- type = TYPE_BUILTIN_FUNC;
- }
- };
-
- template <class T>
- T *alloc_node() {
- T *node = memnew(T);
- node->next = nodes;
- nodes = node;
- return node;
- }
-
- ENode *root = nullptr;
- ENode *nodes = nullptr;
-
-protected:
- bool _set(const StringName &p_name, const Variant &p_value);
- bool _get(const StringName &p_name, Variant &r_ret) const;
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- virtual void reset_state() override;
-
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "operators"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptExpression();
- ~VisualScriptExpression();
-};
-
-void register_visual_script_expression_node();
-
-#endif // VISUAL_SCRIPT_EXPRESSION_H
diff --git a/modules/visual_script/visual_script_flow_control.cpp b/modules/visual_script/visual_script_flow_control.cpp
deleted file mode 100644
index 19bbd834cc..0000000000
--- a/modules/visual_script/visual_script_flow_control.cpp
+++ /dev/null
@@ -1,880 +0,0 @@
-/*************************************************************************/
-/* visual_script_flow_control.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 "visual_script_flow_control.h"
-
-#include "core/config/project_settings.h"
-#include "core/io/resource_loader.h"
-#include "core/os/keyboard.h"
-
-//////////////////////////////////////////
-////////////////RETURN////////////////////
-//////////////////////////////////////////
-
-int VisualScriptReturn::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptReturn::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptReturn::get_input_value_port_count() const {
- return with_value ? 1 : 0;
-}
-
-int VisualScriptReturn::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptReturn::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptReturn::get_input_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = "result";
- pinfo.type = type;
- return pinfo;
-}
-
-PropertyInfo VisualScriptReturn::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptReturn::get_caption() const {
- return RTR("Return");
-}
-
-String VisualScriptReturn::get_text() const {
- return get_name();
-}
-
-void VisualScriptReturn::set_return_type(Variant::Type p_type) {
- if (type == p_type) {
- return;
- }
- type = p_type;
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptReturn::get_return_type() const {
- return type;
-}
-
-void VisualScriptReturn::set_enable_return_value(bool p_enable) {
- if (with_value == p_enable) {
- return;
- }
-
- with_value = p_enable;
- ports_changed_notify();
-}
-
-bool VisualScriptReturn::is_return_value_enabled() const {
- return with_value;
-}
-
-void VisualScriptReturn::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_return_type", "type"), &VisualScriptReturn::set_return_type);
- ClassDB::bind_method(D_METHOD("get_return_type"), &VisualScriptReturn::get_return_type);
- ClassDB::bind_method(D_METHOD("set_enable_return_value", "enable"), &VisualScriptReturn::set_enable_return_value);
- ClassDB::bind_method(D_METHOD("is_return_value_enabled"), &VisualScriptReturn::is_return_value_enabled);
-
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "return_enabled"), "set_enable_return_value", "is_return_value_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "return_type", PROPERTY_HINT_ENUM, argt), "set_return_type", "get_return_type");
-}
-
-class VisualScriptNodeInstanceReturn : public VisualScriptNodeInstance {
-public:
- VisualScriptReturn *node = nullptr;
- VisualScriptInstance *instance = nullptr;
- bool with_value = false;
-
- virtual int get_working_memory_size() const override { return 1; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- if (with_value) {
- *p_working_mem = *p_inputs[0];
- return STEP_EXIT_FUNCTION_BIT;
- } else {
- *p_working_mem = Variant();
- return 0;
- }
- }
-};
-
-VisualScriptNodeInstance *VisualScriptReturn::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceReturn *instance = memnew(VisualScriptNodeInstanceReturn);
- instance->node = this;
- instance->instance = p_instance;
- instance->with_value = with_value;
- return instance;
-}
-
-VisualScriptReturn::VisualScriptReturn() {
- with_value = false;
- type = Variant::NIL;
-}
-
-template <bool with_value>
-static Ref<VisualScriptNode> create_return_node(const String &p_name) {
- Ref<VisualScriptReturn> node;
- node.instantiate();
- node->set_enable_return_value(with_value);
- return node;
-}
-
-//////////////////////////////////////////
-////////////////CONDITION/////////////////
-//////////////////////////////////////////
-
-int VisualScriptCondition::get_output_sequence_port_count() const {
- return 3;
-}
-
-bool VisualScriptCondition::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptCondition::get_input_value_port_count() const {
- return 1;
-}
-
-int VisualScriptCondition::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptCondition::get_output_sequence_port_text(int p_port) const {
- if (p_port == 0) {
- return "true";
- } else if (p_port == 1) {
- return "false";
- } else {
- return "done";
- }
-}
-
-PropertyInfo VisualScriptCondition::get_input_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = "cond";
- pinfo.type = Variant::BOOL;
- return pinfo;
-}
-
-PropertyInfo VisualScriptCondition::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptCondition::get_caption() const {
- return RTR("Condition");
-}
-
-String VisualScriptCondition::get_text() const {
- return RTR("if (cond) is:");
-}
-
-void VisualScriptCondition::_bind_methods() {
-}
-
-class VisualScriptNodeInstanceCondition : public VisualScriptNodeInstance {
-public:
- VisualScriptCondition *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- //virtual int get_working_memory_size() const override { return 1; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- if (p_start_mode == START_MODE_CONTINUE_SEQUENCE) {
- return 2;
- } else if (p_inputs[0]->operator bool()) {
- return 0 | STEP_FLAG_PUSH_STACK_BIT;
- } else {
- return 1 | STEP_FLAG_PUSH_STACK_BIT;
- }
- }
-};
-
-VisualScriptNodeInstance *VisualScriptCondition::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceCondition *instance = memnew(VisualScriptNodeInstanceCondition);
- instance->node = this;
- instance->instance = p_instance;
- return instance;
-}
-
-VisualScriptCondition::VisualScriptCondition() {
-}
-
-//////////////////////////////////////////
-////////////////WHILE/////////////////
-//////////////////////////////////////////
-
-int VisualScriptWhile::get_output_sequence_port_count() const {
- return 2;
-}
-
-bool VisualScriptWhile::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptWhile::get_input_value_port_count() const {
- return 1;
-}
-
-int VisualScriptWhile::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptWhile::get_output_sequence_port_text(int p_port) const {
- if (p_port == 0) {
- return "repeat";
- } else {
- return "exit";
- }
-}
-
-PropertyInfo VisualScriptWhile::get_input_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = "cond";
- pinfo.type = Variant::BOOL;
- return pinfo;
-}
-
-PropertyInfo VisualScriptWhile::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptWhile::get_caption() const {
- return RTR("While");
-}
-
-String VisualScriptWhile::get_text() const {
- return RTR("while (cond):");
-}
-
-void VisualScriptWhile::_bind_methods() {
-}
-
-class VisualScriptNodeInstanceWhile : public VisualScriptNodeInstance {
-public:
- VisualScriptWhile *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- //virtual int get_working_memory_size() const override { return 1; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- bool keep_going = p_inputs[0]->operator bool();
-
- if (keep_going) {
- return 0 | STEP_FLAG_PUSH_STACK_BIT;
- } else {
- return 1;
- }
- }
-};
-
-VisualScriptNodeInstance *VisualScriptWhile::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceWhile *instance = memnew(VisualScriptNodeInstanceWhile);
- instance->node = this;
- instance->instance = p_instance;
- return instance;
-}
-
-VisualScriptWhile::VisualScriptWhile() {
-}
-
-//////////////////////////////////////////
-////////////////ITERATOR/////////////////
-//////////////////////////////////////////
-
-int VisualScriptIterator::get_output_sequence_port_count() const {
- return 2;
-}
-
-bool VisualScriptIterator::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptIterator::get_input_value_port_count() const {
- return 1;
-}
-
-int VisualScriptIterator::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptIterator::get_output_sequence_port_text(int p_port) const {
- if (p_port == 0) {
- return "each";
- } else {
- return "exit";
- }
-}
-
-PropertyInfo VisualScriptIterator::get_input_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = "input";
- pinfo.type = Variant::NIL;
- return pinfo;
-}
-
-PropertyInfo VisualScriptIterator::get_output_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = "elem";
- pinfo.type = Variant::NIL;
- return pinfo;
-}
-
-String VisualScriptIterator::get_caption() const {
- return RTR("Iterator");
-}
-
-String VisualScriptIterator::get_text() const {
- return RTR("for (elem) in (input):");
-}
-
-void VisualScriptIterator::_bind_methods() {
-}
-
-class VisualScriptNodeInstanceIterator : public VisualScriptNodeInstance {
-public:
- VisualScriptIterator *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- virtual int get_working_memory_size() const override { return 2; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- if (p_start_mode == START_MODE_BEGIN_SEQUENCE) {
- p_working_mem[0] = *p_inputs[0];
- bool valid;
- bool can_iter = p_inputs[0]->iter_init(p_working_mem[1], valid);
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Input type not iterable:") + " " + Variant::get_type_name(p_inputs[0]->get_type());
- return 0;
- }
-
- if (!can_iter) {
- return 1; //nothing to iterate
- }
-
- *p_outputs[0] = p_working_mem[0].iter_get(p_working_mem[1], valid);
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Iterator became invalid");
- return 0;
- }
-
- } else { //continue sequence
-
- bool valid;
- bool can_iter = p_working_mem[0].iter_next(p_working_mem[1], valid);
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Iterator became invalid:") + " " + Variant::get_type_name(p_inputs[0]->get_type());
- return 0;
- }
-
- if (!can_iter) {
- return 1; //nothing to iterate
- }
-
- *p_outputs[0] = p_working_mem[0].iter_get(p_working_mem[1], valid);
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Iterator became invalid");
- return 0;
- }
- }
-
- return 0 | STEP_FLAG_PUSH_STACK_BIT; //go around
- }
-};
-
-VisualScriptNodeInstance *VisualScriptIterator::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceIterator *instance = memnew(VisualScriptNodeInstanceIterator);
- instance->node = this;
- instance->instance = p_instance;
- return instance;
-}
-
-VisualScriptIterator::VisualScriptIterator() {
-}
-
-//////////////////////////////////////////
-////////////////SEQUENCE/////////////////
-//////////////////////////////////////////
-
-int VisualScriptSequence::get_output_sequence_port_count() const {
- return steps;
-}
-
-bool VisualScriptSequence::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptSequence::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptSequence::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptSequence::get_output_sequence_port_text(int p_port) const {
- return itos(p_port + 1);
-}
-
-PropertyInfo VisualScriptSequence::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptSequence::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::INT, "current");
-}
-
-String VisualScriptSequence::get_caption() const {
- return RTR("Sequence");
-}
-
-String VisualScriptSequence::get_text() const {
- return RTR("in order:");
-}
-
-void VisualScriptSequence::set_steps(int p_steps) {
- ERR_FAIL_COND(p_steps < 1);
- if (steps == p_steps) {
- return;
- }
-
- steps = p_steps;
- ports_changed_notify();
-}
-
-int VisualScriptSequence::get_steps() const {
- return steps;
-}
-
-void VisualScriptSequence::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_steps", "steps"), &VisualScriptSequence::set_steps);
- ClassDB::bind_method(D_METHOD("get_steps"), &VisualScriptSequence::get_steps);
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "steps", PROPERTY_HINT_RANGE, "1,64,1"), "set_steps", "get_steps");
-}
-
-class VisualScriptNodeInstanceSequence : public VisualScriptNodeInstance {
-public:
- VisualScriptSequence *node = nullptr;
- VisualScriptInstance *instance = nullptr;
- int steps = 0;
-
- virtual int get_working_memory_size() const override { return 1; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- if (p_start_mode == START_MODE_BEGIN_SEQUENCE) {
- p_working_mem[0] = 0;
- }
-
- int step = p_working_mem[0];
-
- *p_outputs[0] = step;
-
- if (step + 1 == steps) {
- return step;
- } else {
- p_working_mem[0] = step + 1;
- return step | STEP_FLAG_PUSH_STACK_BIT;
- }
- }
-};
-
-VisualScriptNodeInstance *VisualScriptSequence::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSequence *instance = memnew(VisualScriptNodeInstanceSequence);
- instance->node = this;
- instance->instance = p_instance;
- instance->steps = steps;
- return instance;
-}
-
-VisualScriptSequence::VisualScriptSequence() {
- steps = 1;
-}
-
-//////////////////////////////////////////
-////////////////EVENT TYPE FILTER///////////
-//////////////////////////////////////////
-
-int VisualScriptSwitch::get_output_sequence_port_count() const {
- return case_values.size() + 1;
-}
-
-bool VisualScriptSwitch::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptSwitch::get_input_value_port_count() const {
- return case_values.size() + 1;
-}
-
-int VisualScriptSwitch::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptSwitch::get_output_sequence_port_text(int p_port) const {
- if (p_port == case_values.size()) {
- return "done";
- }
-
- return String();
-}
-
-PropertyInfo VisualScriptSwitch::get_input_value_port_info(int p_idx) const {
- if (p_idx < case_values.size()) {
- return PropertyInfo(case_values[p_idx].type, " =");
- } else {
- return PropertyInfo(Variant::NIL, "input");
- }
-}
-
-PropertyInfo VisualScriptSwitch::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptSwitch::get_caption() const {
- return RTR("Switch");
-}
-
-String VisualScriptSwitch::get_text() const {
- return RTR("'input' is:");
-}
-
-class VisualScriptNodeInstanceSwitch : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- int case_count = 0;
-
- //virtual int get_working_memory_size() const override { return 0; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; }
-
- 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) override {
- if (p_start_mode == START_MODE_CONTINUE_SEQUENCE) {
- return case_count; //exit
- }
-
- for (int i = 0; i < case_count; i++) {
- if (*p_inputs[i] == *p_inputs[case_count]) {
- return i | STEP_FLAG_PUSH_STACK_BIT;
- }
- }
-
- return case_count;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptSwitch::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSwitch *instance = memnew(VisualScriptNodeInstanceSwitch);
- instance->instance = p_instance;
- instance->case_count = case_values.size();
- return instance;
-}
-
-bool VisualScriptSwitch::_set(const StringName &p_name, const Variant &p_value) {
- if (String(p_name) == "case_count") {
- case_values.resize(p_value);
- notify_property_list_changed();
- ports_changed_notify();
- return true;
- }
-
- if (String(p_name).begins_with("case/")) {
- int idx = String(p_name).get_slice("/", 1).to_int();
- ERR_FAIL_INDEX_V(idx, case_values.size(), false);
-
- case_values.write[idx].type = Variant::Type(int(p_value));
- notify_property_list_changed();
- ports_changed_notify();
-
- return true;
- }
-
- return false;
-}
-
-bool VisualScriptSwitch::_get(const StringName &p_name, Variant &r_ret) const {
- if (String(p_name) == "case_count") {
- r_ret = case_values.size();
- return true;
- }
-
- if (String(p_name).begins_with("case/")) {
- int idx = String(p_name).get_slice("/", 1).to_int();
- ERR_FAIL_INDEX_V(idx, case_values.size(), false);
-
- r_ret = case_values[idx].type;
- return true;
- }
-
- return false;
-}
-
-void VisualScriptSwitch::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::INT, "case_count", PROPERTY_HINT_RANGE, "0,128"));
-
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- for (int i = 0; i < case_values.size(); i++) {
- p_list->push_back(PropertyInfo(Variant::INT, "case/" + itos(i), PROPERTY_HINT_ENUM, argt));
- }
-}
-
-void VisualScriptSwitch::reset_state() {
- case_values.clear();
-}
-
-void VisualScriptSwitch::_bind_methods() {
-}
-
-VisualScriptSwitch::VisualScriptSwitch() {
-}
-
-//////////////////////////////////////////
-////////////////TYPE CAST///////////
-//////////////////////////////////////////
-
-int VisualScriptTypeCast::get_output_sequence_port_count() const {
- return 2;
-}
-
-bool VisualScriptTypeCast::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptTypeCast::get_input_value_port_count() const {
- return 1;
-}
-
-int VisualScriptTypeCast::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptTypeCast::get_output_sequence_port_text(int p_port) const {
- return p_port == 0 ? "yes" : "no";
-}
-
-PropertyInfo VisualScriptTypeCast::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT, "instance");
-}
-
-PropertyInfo VisualScriptTypeCast::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_TYPE_STRING, get_base_type());
-}
-
-String VisualScriptTypeCast::get_caption() const {
- return RTR("Type Cast");
-}
-
-String VisualScriptTypeCast::get_text() const {
- if (!script.is_empty()) {
- return vformat(RTR("Is %s?"), script.get_file());
- } else {
- return vformat(RTR("Is %s?"), base_type);
- }
-}
-
-void VisualScriptTypeCast::set_base_type(const StringName &p_type) {
- if (base_type == p_type) {
- return;
- }
-
- base_type = p_type;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptTypeCast::get_base_type() const {
- return base_type;
-}
-
-void VisualScriptTypeCast::set_base_script(const String &p_path) {
- if (script == p_path) {
- return;
- }
-
- script = p_path;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-String VisualScriptTypeCast::get_base_script() const {
- return script;
-}
-
-VisualScriptTypeCast::TypeGuess VisualScriptTypeCast::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- TypeGuess tg;
- tg.type = Variant::OBJECT;
- if (!script.is_empty()) {
- tg.script = ResourceLoader::load(script);
- }
- //if (!tg.script.is_valid()) {
- // tg.gdclass = base_type;
- //}
-
- return tg;
-}
-
-class VisualScriptNodeInstanceTypeCast : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- StringName base_type;
- String script;
-
- //virtual int get_working_memory_size() const override { return 0; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; }
-
- 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) override {
- Object *obj = *p_inputs[0];
-
- *p_outputs[0] = Variant();
-
- if (!obj) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Instance is null";
- return 0;
- }
-
- if (!script.is_empty()) {
- Ref<Script> obj_script = obj->get_script();
- if (!obj_script.is_valid()) {
- return 1; //well, definitely not the script because object we got has no script.
- }
-
- if (!ResourceCache::has(script)) {
- //if the script is not in use by anyone, we can safely assume whatever we got is not casting to it.
- return 1;
- }
- Ref<Script> cast_script = ResourceCache::get_ref(script);
- if (!cast_script.is_valid()) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Script path is not a script: " + script;
- return 1;
- }
-
- while (obj_script.is_valid()) {
- if (cast_script == obj_script) {
- *p_outputs[0] = *p_inputs[0]; //copy
- return 0; // it is the script, yey
- }
-
- obj_script = obj_script->get_base_script();
- }
-
- return 1; //not found sorry
- }
-
- if (ClassDB::is_parent_class(obj->get_class_name(), base_type)) {
- *p_outputs[0] = *p_inputs[0]; //copy
- return 0;
- } else {
- return 1;
- }
- }
-};
-
-VisualScriptNodeInstance *VisualScriptTypeCast::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceTypeCast *instance = memnew(VisualScriptNodeInstanceTypeCast);
- instance->instance = p_instance;
- instance->base_type = base_type;
- instance->script = script;
- return instance;
-}
-
-void VisualScriptTypeCast::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_base_type", "type"), &VisualScriptTypeCast::set_base_type);
- ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptTypeCast::get_base_type);
-
- ClassDB::bind_method(D_METHOD("set_base_script", "path"), &VisualScriptTypeCast::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptTypeCast::get_base_script);
-
- List<String> script_extensions;
- for (int i = 0; i > ScriptServer::get_language_count(); i++) {
- ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
- }
-
- String script_ext_hint;
- for (const String &E : script_extensions) {
- if (!script_ext_hint.is_empty()) {
- script_ext_hint += ",";
- }
- script_ext_hint += "*." + E;
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
-}
-
-VisualScriptTypeCast::VisualScriptTypeCast() {
- base_type = "Object";
-}
-
-void register_visual_script_flow_control_nodes() {
- VisualScriptLanguage::singleton->add_register_func("flow_control/return", create_return_node<false>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/return_with_value", create_return_node<true>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/condition", create_node_generic<VisualScriptCondition>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/while", create_node_generic<VisualScriptWhile>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/iterator", create_node_generic<VisualScriptIterator>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/sequence", create_node_generic<VisualScriptSequence>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/switch", create_node_generic<VisualScriptSwitch>);
- //VisualScriptLanguage::singleton->add_register_func("flow_control/input", create_node_generic<VisualScriptInputFilter>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/type_cast", create_node_generic<VisualScriptTypeCast>);
-}
diff --git a/modules/visual_script/visual_script_flow_control.h b/modules/visual_script/visual_script_flow_control.h
deleted file mode 100644
index 7ffdf3df65..0000000000
--- a/modules/visual_script/visual_script_flow_control.h
+++ /dev/null
@@ -1,268 +0,0 @@
-/*************************************************************************/
-/* visual_script_flow_control.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 VISUAL_SCRIPT_FLOW_CONTROL_H
-#define VISUAL_SCRIPT_FLOW_CONTROL_H
-
-#include "visual_script.h"
-
-class VisualScriptReturn : public VisualScriptNode {
- GDCLASS(VisualScriptReturn, VisualScriptNode);
-
- Variant::Type type;
- bool with_value;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- void set_return_type(Variant::Type);
- Variant::Type get_return_type() const;
-
- void set_enable_return_value(bool p_enable);
- bool is_return_value_enabled() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptReturn();
-};
-
-class VisualScriptCondition : public VisualScriptNode {
- GDCLASS(VisualScriptCondition, VisualScriptNode);
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptCondition();
-};
-
-class VisualScriptWhile : public VisualScriptNode {
- GDCLASS(VisualScriptWhile, VisualScriptNode);
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptWhile();
-};
-
-class VisualScriptIterator : public VisualScriptNode {
- GDCLASS(VisualScriptIterator, VisualScriptNode);
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptIterator();
-};
-
-class VisualScriptSequence : public VisualScriptNode {
- GDCLASS(VisualScriptSequence, VisualScriptNode);
-
- int steps;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- void set_steps(int p_steps);
- int get_steps() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptSequence();
-};
-
-class VisualScriptSwitch : public VisualScriptNode {
- GDCLASS(VisualScriptSwitch, VisualScriptNode);
-
- struct Case {
- Variant::Type type;
- Case() { type = Variant::NIL; }
- };
-
- Vector<Case> case_values;
-
- friend class VisualScriptNodeInstanceSwitch;
-
-protected:
- bool _set(const StringName &p_name, const Variant &p_value);
- bool _get(const StringName &p_name, Variant &r_ret) const;
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
- static void _bind_methods();
-
-public:
- virtual void reset_state() override;
-
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
- virtual bool has_mixed_input_and_sequence_ports() const override { return true; }
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptSwitch();
-};
-
-class VisualScriptTypeCast : public VisualScriptNode {
- GDCLASS(VisualScriptTypeCast, VisualScriptNode);
-
- StringName base_type;
- String script;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- void set_base_type(const StringName &p_type);
- StringName get_base_type() const;
-
- void set_base_script(const String &p_path);
- String get_base_script() const;
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptTypeCast();
-};
-
-void register_visual_script_flow_control_nodes();
-
-#endif // VISUAL_SCRIPT_FLOW_CONTROL_H
diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp
deleted file mode 100644
index b16358ae38..0000000000
--- a/modules/visual_script/visual_script_func_nodes.cpp
+++ /dev/null
@@ -1,2444 +0,0 @@
-/*************************************************************************/
-/* visual_script_func_nodes.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 "visual_script_func_nodes.h"
-
-#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"
-
-//////////////////////////////////////////
-////////////////CALL//////////////////////
-//////////////////////////////////////////
-
-int VisualScriptFunctionCall::get_output_sequence_port_count() const {
- if ((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_builtin_method_const(basic_type, function))) {
- return 0;
- } else {
- return 1;
- }
-}
-
-bool VisualScriptFunctionCall::has_input_sequence_port() const {
- return !((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_builtin_method_const(basic_type, function)));
-}
-#ifdef TOOLS_ENABLED
-
-static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
- return nullptr;
- }
-
- Ref<Script> scr = p_current_node->get_script();
-
- if (scr.is_valid() && scr == script) {
- return p_current_node;
- }
-
- for (int i = 0; i < p_current_node->get_child_count(); i++) {
- Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n) {
- return n;
- }
- }
-
- return nullptr;
-}
-
-#endif
-Node *VisualScriptFunctionCall::_get_base_node() const {
-#ifdef TOOLS_ENABLED
- Ref<Script> script = get_visual_script();
- if (!script.is_valid()) {
- return nullptr;
- }
-
- MainLoop *main_loop = OS::get_singleton()->get_main_loop();
- SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
-
- if (!scene_tree) {
- return nullptr;
- }
-
- Node *edited_scene = scene_tree->get_edited_scene_root();
-
- if (!edited_scene) {
- return nullptr;
- }
-
- Node *script_node = _find_script_node(edited_scene, edited_scene, script);
-
- if (!script_node) {
- return nullptr;
- }
-
- if (!script_node->has_node(base_path)) {
- return nullptr;
- }
-
- Node *path_to = script_node->get_node(base_path);
-
- return path_to;
-#else
-
- return nullptr;
-#endif
-}
-
-StringName VisualScriptFunctionCall::_get_base_type() const {
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
- return get_visual_script()->get_instance_base_type();
- } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
- Node *path = _get_base_node();
- if (path) {
- return path->get_class();
- }
- }
-
- return base_type;
-}
-
-int VisualScriptFunctionCall::get_input_value_port_count() const {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- Vector<Variant::Type> types;
- int argc = Variant::get_builtin_method_argument_count(basic_type, function);
- for (int i = 0; i < argc; i++) {
- types.push_back(Variant::get_builtin_method_argument_type(basic_type, function, i));
- }
- return types.size() + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) + 1;
-
- } else {
- MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
- if (mb) {
- int defaulted_args = mb->get_argument_count() < use_default_args ? mb->get_argument_count() : use_default_args;
- return mb->get_argument_count() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - defaulted_args;
- }
-
- int defaulted_args = method_cache.arguments.size() < use_default_args ? method_cache.arguments.size() : use_default_args;
- return method_cache.arguments.size() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - defaulted_args;
- }
-}
-
-int VisualScriptFunctionCall::get_output_value_port_count() const {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- bool returns = Variant::has_builtin_method_return_value(basic_type, function);
- return returns ? 1 : 0;
-
- } else {
- int ret;
- MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
- if (mb) {
- ret = mb->has_return() ? 1 : 0;
- } else {
- ret = 1; //it is assumed that script always returns something
- }
-
- if (call_mode == CALL_MODE_INSTANCE) {
- ret++;
- }
-
- return ret;
- }
-}
-
-String VisualScriptFunctionCall::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptFunctionCall::get_input_value_port_info(int p_idx) const {
- if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) {
- if (p_idx == 0) {
- PropertyInfo pi;
- pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type);
- pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower());
- return pi;
- } else {
- p_idx--;
- }
- }
-
- if (rpc_call_mode >= RPC_RELIABLE_TO_ID) {
- if (p_idx == 0) {
- return PropertyInfo(Variant::INT, "peer_id");
- } else {
- p_idx--;
- }
- }
-
-#ifdef DEBUG_METHODS_ENABLED
-
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- return PropertyInfo(Variant::get_builtin_method_argument_type(basic_type, function, p_idx), Variant::get_builtin_method_argument_name(basic_type, function, p_idx));
- } else {
- MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
- if (mb) {
- return mb->get_argument_info(p_idx);
- }
-
- if (p_idx >= 0 && p_idx < method_cache.arguments.size()) {
- return method_cache.arguments[p_idx];
- }
-
- return PropertyInfo();
- }
-#else
- return PropertyInfo();
-#endif
-}
-
-PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) const {
-#ifdef DEBUG_METHODS_ENABLED
-
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- return PropertyInfo(Variant::get_builtin_method_return_type(basic_type, function), "");
- } else {
- if (call_mode == CALL_MODE_INSTANCE) {
- if (p_idx == 0) {
- return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type());
- } else {
- p_idx--;
- }
- }
-
- PropertyInfo ret;
-
- /*MethodBind *mb = ClassDB::get_method(_get_base_type(),function);
- if (mb) {
- ret = mb->get_argument_info(-1);
- } else {*/
-
- ret = method_cache.return_val;
-
- //}
-
- if (call_mode == CALL_MODE_INSTANCE) {
- ret.name = "return";
- } else {
- ret.name = "";
- }
- return ret;
- }
-#else
- return PropertyInfo();
-#endif
-}
-
-String VisualScriptFunctionCall::get_caption() const {
- return " " + String(function) + "()";
-}
-
-String VisualScriptFunctionCall::get_text() const {
- String text;
-
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- text = vformat(RTR("On %s"), Variant::get_type_name(basic_type));
- } else if (call_mode == CALL_MODE_INSTANCE) {
- 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 = RTR("On Self");
- } else if (call_mode == CALL_MODE_SINGLETON) {
- text = String(singleton) + ":" + String(function) + "()";
- }
-
- if (rpc_call_mode) {
- text += " RPC";
- if (rpc_call_mode == RPC_UNRELIABLE || rpc_call_mode == RPC_UNRELIABLE_TO_ID) {
- text += " UNREL";
- }
- }
-
- return text;
-}
-
-void VisualScriptFunctionCall::set_basic_type(Variant::Type p_type) {
- if (basic_type == p_type) {
- return;
- }
- basic_type = p_type;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptFunctionCall::get_basic_type() const {
- return basic_type;
-}
-
-void VisualScriptFunctionCall::set_base_type(const StringName &p_type) {
- if (base_type == p_type) {
- return;
- }
-
- base_type = p_type;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptFunctionCall::get_base_type() const {
- return base_type;
-}
-
-void VisualScriptFunctionCall::set_base_script(const String &p_path) {
- if (base_script == p_path) {
- return;
- }
-
- base_script = p_path;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-String VisualScriptFunctionCall::get_base_script() const {
- return base_script;
-}
-
-void VisualScriptFunctionCall::set_singleton(const StringName &p_type) {
- if (singleton == p_type) {
- return;
- }
-
- singleton = p_type;
- Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
- if (obj) {
- base_type = obj->get_class();
- }
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptFunctionCall::get_singleton() const {
- return singleton;
-}
-
-void VisualScriptFunctionCall::_update_method_cache() {
- StringName type;
- Ref<Script> script;
-
- if (call_mode == CALL_MODE_NODE_PATH) {
- Node *node = _get_base_node();
- if (node) {
- type = node->get_class();
- base_type = type; //cache, too
- script = node->get_script();
- }
- } else if (call_mode == CALL_MODE_SELF) {
- if (get_visual_script().is_valid()) {
- type = get_visual_script()->get_instance_base_type();
- base_type = type; //cache, too
- script = get_visual_script();
- }
-
- } else if (call_mode == CALL_MODE_SINGLETON) {
- Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
- if (obj) {
- type = obj->get_class();
- script = obj->get_script();
- }
-
- } else if (call_mode == CALL_MODE_INSTANCE) {
- type = base_type;
- if (!base_script.is_empty()) {
- if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
- ScriptServer::edit_request_func(base_script); //make sure it's loaded
- }
-
- if (ResourceCache::has(base_script)) {
- script = ResourceCache::get_ref(base_script);
- } else {
- return;
- }
- }
- }
-
- MethodBind *mb = ClassDB::get_method(type, function);
- if (mb) {
- use_default_args = mb->get_default_argument_count();
- method_cache = MethodInfo();
- for (int i = 0; i < mb->get_argument_count(); i++) {
-#ifdef DEBUG_METHODS_ENABLED
- method_cache.arguments.push_back(mb->get_argument_info(i));
-#else
- method_cache.arguments.push_back(PropertyInfo());
-#endif
- }
-
- if (mb->is_const()) {
- method_cache.flags |= METHOD_FLAG_CONST;
- }
-
-#ifdef DEBUG_METHODS_ENABLED
-
- method_cache.return_val = mb->get_return_info();
-#endif
-
- if (mb->is_vararg()) {
- //for vararg just give it 10 arguments (should be enough for most use cases)
- for (int i = 0; i < 10; i++) {
- method_cache.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
- use_default_args++;
- }
- }
- } else if (script.is_valid() && script->has_method(function)) {
- method_cache = script->get_method_info(function);
- use_default_args = method_cache.default_arguments.size();
- }
-}
-
-void VisualScriptFunctionCall::set_function(const StringName &p_type) {
- if (function == p_type) {
- return;
- }
-
- function = p_type;
-
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- use_default_args = Variant::get_builtin_method_default_arguments(basic_type, function).size();
- } else {
- //update all caches
-
- _update_method_cache();
- }
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptFunctionCall::get_function() const {
- return function;
-}
-
-void VisualScriptFunctionCall::set_base_path(const NodePath &p_type) {
- if (base_path == p_type) {
- return;
- }
-
- base_path = p_type;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-NodePath VisualScriptFunctionCall::get_base_path() const {
- return base_path;
-}
-
-void VisualScriptFunctionCall::set_call_mode(CallMode p_mode) {
- if (call_mode == p_mode) {
- return;
- }
-
- call_mode = p_mode;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-VisualScriptFunctionCall::CallMode VisualScriptFunctionCall::get_call_mode() const {
- return call_mode;
-}
-
-void VisualScriptFunctionCall::set_use_default_args(int p_amount) {
- if (use_default_args == p_amount) {
- return;
- }
-
- use_default_args = p_amount;
- ports_changed_notify();
-}
-
-void VisualScriptFunctionCall::set_rpc_call_mode(VisualScriptFunctionCall::RPCCallMode p_mode) {
- if (rpc_call_mode == p_mode) {
- return;
- }
- rpc_call_mode = p_mode;
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-VisualScriptFunctionCall::RPCCallMode VisualScriptFunctionCall::get_rpc_call_mode() const {
- return rpc_call_mode;
-}
-
-int VisualScriptFunctionCall::get_use_default_args() const {
- return use_default_args;
-}
-
-void VisualScriptFunctionCall::set_validate(bool p_amount) {
- validate = p_amount;
-}
-
-bool VisualScriptFunctionCall::get_validate() const {
- return validate;
-}
-
-void VisualScriptFunctionCall::_set_argument_cache(const Dictionary &p_cache) {
- //so everything works in case all else fails
- method_cache = MethodInfo::from_dict(p_cache);
-}
-
-Dictionary VisualScriptFunctionCall::_get_argument_cache() const {
- return method_cache;
-}
-
-void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const {
- if (property.name == "base_type") {
- if (call_mode != CALL_MODE_INSTANCE) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
- }
- }
-
- if (property.name == "base_script") {
- if (call_mode != CALL_MODE_INSTANCE) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-
- if (property.name == "basic_type") {
- if (call_mode != CALL_MODE_BASIC_TYPE) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-
- if (property.name == "singleton") {
- if (call_mode != CALL_MODE_SINGLETON) {
- property.usage = PROPERTY_USAGE_NONE;
- } else {
- List<Engine::Singleton> names;
- Engine::get_singleton()->get_singletons(&names);
- property.hint = PROPERTY_HINT_ENUM;
- String sl;
- for (const Engine::Singleton &E : names) {
- if (!sl.is_empty()) {
- sl += ",";
- }
- sl += E.name;
- }
- property.hint_string = sl;
- }
- }
-
- if (property.name == "node_path") {
- if (call_mode != CALL_MODE_NODE_PATH) {
- property.usage = PROPERTY_USAGE_NONE;
- } else {
- Node *bnode = _get_base_node();
- if (bnode) {
- property.hint_string = bnode->get_path(); //convert to long string
- }
- }
- }
-
- if (property.name == "function") {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- property.hint = PROPERTY_HINT_METHOD_OF_VARIANT_TYPE;
- property.hint_string = Variant::get_type_name(basic_type);
-
- } else if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
- property.hint = PROPERTY_HINT_METHOD_OF_SCRIPT;
- property.hint_string = itos(get_visual_script()->get_instance_id());
- } else if (call_mode == CALL_MODE_SINGLETON) {
- Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
- if (obj) {
- property.hint = PROPERTY_HINT_METHOD_OF_INSTANCE;
- property.hint_string = itos(obj->get_instance_id());
- } else {
- property.hint = PROPERTY_HINT_METHOD_OF_BASE_TYPE;
- property.hint_string = base_type; //should be cached
- }
- } else if (call_mode == CALL_MODE_INSTANCE) {
- property.hint = PROPERTY_HINT_METHOD_OF_BASE_TYPE;
- property.hint_string = base_type;
-
- if (!base_script.is_empty()) {
- if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
- ScriptServer::edit_request_func(base_script); //make sure it's loaded
- }
-
- if (ResourceCache::has(base_script)) {
- Ref<Script> script = ResourceCache::get_ref(base_script);
- if (script.is_valid()) {
- property.hint = PROPERTY_HINT_METHOD_OF_SCRIPT;
- property.hint_string = itos(script->get_instance_id());
- }
- }
- }
-
- } else if (call_mode == CALL_MODE_NODE_PATH) {
- Node *node = _get_base_node();
- if (node) {
- property.hint = PROPERTY_HINT_METHOD_OF_INSTANCE;
- property.hint_string = itos(node->get_instance_id());
- } else {
- property.hint = PROPERTY_HINT_METHOD_OF_BASE_TYPE;
- property.hint_string = get_base_type();
- }
- }
- }
-
- if (property.name == "use_default_args") {
- property.hint = PROPERTY_HINT_RANGE;
-
- int mc = 0;
-
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- mc = Variant::get_builtin_method_default_arguments(basic_type, function).size();
- } else {
- MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
- if (mb) {
- mc = mb->get_default_argument_count();
- }
- }
-
- if (mc == 0) {
- property.usage = PROPERTY_USAGE_NONE; //do not show
- } else {
- property.hint_string = "0," + itos(mc) + ",1";
- }
- }
-
- if (property.name == "rpc_call_mode") {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-}
-
-void VisualScriptFunctionCall::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptFunctionCall::set_base_type);
- ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptFunctionCall::get_base_type);
-
- ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptFunctionCall::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptFunctionCall::get_base_script);
-
- ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptFunctionCall::set_basic_type);
- ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptFunctionCall::get_basic_type);
-
- ClassDB::bind_method(D_METHOD("set_singleton", "singleton"), &VisualScriptFunctionCall::set_singleton);
- ClassDB::bind_method(D_METHOD("get_singleton"), &VisualScriptFunctionCall::get_singleton);
-
- ClassDB::bind_method(D_METHOD("set_function", "function"), &VisualScriptFunctionCall::set_function);
- ClassDB::bind_method(D_METHOD("get_function"), &VisualScriptFunctionCall::get_function);
-
- ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptFunctionCall::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptFunctionCall::get_call_mode);
-
- ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptFunctionCall::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptFunctionCall::get_base_path);
-
- ClassDB::bind_method(D_METHOD("set_use_default_args", "amount"), &VisualScriptFunctionCall::set_use_default_args);
- ClassDB::bind_method(D_METHOD("get_use_default_args"), &VisualScriptFunctionCall::get_use_default_args);
-
- ClassDB::bind_method(D_METHOD("_set_argument_cache", "argument_cache"), &VisualScriptFunctionCall::_set_argument_cache);
- ClassDB::bind_method(D_METHOD("_get_argument_cache"), &VisualScriptFunctionCall::_get_argument_cache);
-
- ClassDB::bind_method(D_METHOD("set_rpc_call_mode", "mode"), &VisualScriptFunctionCall::set_rpc_call_mode);
- ClassDB::bind_method(D_METHOD("get_rpc_call_mode"), &VisualScriptFunctionCall::get_rpc_call_mode);
-
- ClassDB::bind_method(D_METHOD("set_validate", "enable"), &VisualScriptFunctionCall::set_validate);
- ClassDB::bind_method(D_METHOD("get_validate"), &VisualScriptFunctionCall::get_validate);
-
- String bt;
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0) {
- bt += ",";
- }
-
- bt += Variant::get_type_name(Variant::Type(i));
- }
-
- List<String> script_extensions;
- for (int i = 0; i < ScriptServer::get_language_count(); i++) {
- ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
- }
-
- String script_ext_hint;
- for (const String &E : script_extensions) {
- if (!script_ext_hint.is_empty()) {
- script_ext_hint += ",";
- }
- script_ext_hint += "*." + E;
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "call_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type,Singleton"), "set_call_mode", "get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "singleton"), "set_singleton", "get_singleton");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "argument_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_argument_cache", "_get_argument_cache");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "function"), "set_function", "get_function"); //when set, if loaded properly, will override argument count.
- ADD_PROPERTY(PropertyInfo(Variant::INT, "use_default_args"), "set_use_default_args", "get_use_default_args");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "validate"), "set_validate", "get_validate");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "rpc_call_mode", PROPERTY_HINT_ENUM, "Disabled,Reliable,Unreliable,ReliableToID,UnreliableToID"), "set_rpc_call_mode", "get_rpc_call_mode"); //when set, if loaded properly, will override argument count.
-
- BIND_ENUM_CONSTANT(CALL_MODE_SELF);
- BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH);
- BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE);
- BIND_ENUM_CONSTANT(CALL_MODE_BASIC_TYPE);
- BIND_ENUM_CONSTANT(CALL_MODE_SINGLETON);
-
- BIND_ENUM_CONSTANT(RPC_DISABLED);
- BIND_ENUM_CONSTANT(RPC_RELIABLE);
- BIND_ENUM_CONSTANT(RPC_UNRELIABLE);
- BIND_ENUM_CONSTANT(RPC_RELIABLE_TO_ID);
- BIND_ENUM_CONSTANT(RPC_UNRELIABLE_TO_ID);
-}
-
-class VisualScriptNodeInstanceFunctionCall : public VisualScriptNodeInstance {
-public:
- VisualScriptFunctionCall::CallMode call_mode;
- NodePath node_path;
- int input_args = 0;
- bool validate = false;
- int returns = 0;
- VisualScriptFunctionCall::RPCCallMode rpc_mode;
- StringName function;
- StringName singleton;
-
- VisualScriptFunctionCall *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- //virtual int get_working_memory_size() const override { return 0; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- _FORCE_INLINE_ bool call_rpc(Object *p_base, const Variant **p_args, int p_argcount) {
- if (!p_base) {
- return false;
- }
-
- Node *node = Object::cast_to<Node>(p_base);
- if (!node) {
- return false;
- }
-
- int to_id = 0;
- //bool reliable = true;
-
- if (rpc_mode >= VisualScriptFunctionCall::RPC_RELIABLE_TO_ID) {
- to_id = *p_args[0];
- p_args += 1;
- p_argcount -= 1;
- //if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE_TO_ID) {
- //reliable = false;
- //}
- }
- //else if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE) {
- //reliable = false;
- //}
-
- // TODO reliable?
- node->rpcp(to_id, function, p_args, p_argcount);
-
- return true;
- }
-
- 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) override {
- switch (call_mode) {
- case VisualScriptFunctionCall::CALL_MODE_SELF: {
- Object *object = instance->get_owner_ptr();
-
- if (rpc_mode) {
- call_rpc(object, p_inputs, input_args);
- } else if (returns) {
- *p_outputs[0] = object->callp(function, p_inputs, input_args, r_error);
- } else {
- object->callp(function, p_inputs, input_args, r_error);
- }
- } break;
- case VisualScriptFunctionCall::CALL_MODE_NODE_PATH: {
- Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
- if (!node) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Base object is not a Node!";
- return 0;
- }
-
- Node *another = node->get_node(node_path);
- if (!another) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Path does not lead Node!";
- return 0;
- }
-
- if (rpc_mode) {
- call_rpc(node, p_inputs, input_args);
- } else if (returns) {
- *p_outputs[0] = another->callp(function, p_inputs, input_args, r_error);
- } else {
- another->callp(function, p_inputs, input_args, r_error);
- }
-
- } break;
- case VisualScriptFunctionCall::CALL_MODE_INSTANCE:
- case VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE: {
- Variant v = *p_inputs[0];
-
- if (rpc_mode) {
- Object *obj = v;
- if (obj) {
- call_rpc(obj, p_inputs + 1, input_args - 1);
- }
- } else if (returns) {
- if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
- if (returns >= 2) {
- v.callp(function, p_inputs + 1, input_args, *p_outputs[1], r_error);
- } else if (returns == 1) {
- Variant ret;
- 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.callp(function, p_inputs + 1, input_args, *p_outputs[0], r_error);
- }
- } else {
- Variant ret;
- v.callp(function, p_inputs + 1, input_args, ret, r_error);
- }
-
- if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
- *p_outputs[0] = *p_inputs[0];
- }
-
- } break;
- case VisualScriptFunctionCall::CALL_MODE_SINGLETON: {
- Object *object = Engine::get_singleton()->get_singleton_object(singleton);
- if (!object) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Invalid singleton name: '" + String(singleton) + "'";
- return 0;
- }
-
- if (rpc_mode) {
- call_rpc(object, p_inputs, input_args);
- } else if (returns) {
- *p_outputs[0] = object->callp(function, p_inputs, input_args, r_error);
- } else {
- object->callp(function, p_inputs, input_args, r_error);
- }
- } break;
- }
-
- if (!validate) {
- //ignore call errors if validation is disabled
- r_error.error = Callable::CallError::CALL_OK;
- r_error_str = String();
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptFunctionCall::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceFunctionCall *instance = memnew(VisualScriptNodeInstanceFunctionCall);
- instance->node = this;
- instance->instance = p_instance;
- instance->singleton = singleton;
- instance->function = function;
- instance->call_mode = call_mode;
- instance->returns = get_output_value_port_count();
- instance->node_path = base_path;
- instance->input_args = get_input_value_port_count() - ((call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0);
- instance->rpc_mode = rpc_call_mode;
- instance->validate = validate;
- return instance;
-}
-
-VisualScriptFunctionCall::TypeGuess VisualScriptFunctionCall::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) {
- return p_inputs[0];
- }
-
- return VisualScriptNode::guess_output_type(p_inputs, p_output);
-}
-
-VisualScriptFunctionCall::VisualScriptFunctionCall() {
- validate = true;
- call_mode = CALL_MODE_SELF;
- basic_type = Variant::NIL;
- use_default_args = 0;
- base_type = "Object";
- rpc_call_mode = RPC_DISABLED;
-}
-
-template <VisualScriptFunctionCall::CallMode cmode>
-static Ref<VisualScriptNode> create_function_call_node(const String &p_name) {
- Ref<VisualScriptFunctionCall> node;
- node.instantiate();
- node->set_call_mode(cmode);
- return node;
-}
-
-//////////////////////////////////////////
-////////////////SET//////////////////////
-//////////////////////////////////////////
-
-int VisualScriptPropertySet::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptPropertySet::has_input_sequence_port() const {
- return true;
-}
-
-Node *VisualScriptPropertySet::_get_base_node() const {
-#ifdef TOOLS_ENABLED
- Ref<Script> script = get_visual_script();
- if (!script.is_valid()) {
- return nullptr;
- }
-
- MainLoop *main_loop = OS::get_singleton()->get_main_loop();
-
- SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
-
- if (!scene_tree) {
- return nullptr;
- }
-
- Node *edited_scene = scene_tree->get_edited_scene_root();
-
- if (!edited_scene) {
- return nullptr;
- }
-
- Node *script_node = _find_script_node(edited_scene, edited_scene, script);
-
- if (!script_node) {
- return nullptr;
- }
-
- if (!script_node->has_node(base_path)) {
- return nullptr;
- }
-
- Node *path_to = script_node->get_node(base_path);
-
- return path_to;
-#else
-
- return nullptr;
-#endif
-}
-
-StringName VisualScriptPropertySet::_get_base_type() const {
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
- return get_visual_script()->get_instance_base_type();
- } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
- Node *path = _get_base_node();
- if (path) {
- return path->get_class();
- }
- }
-
- return base_type;
-}
-
-int VisualScriptPropertySet::get_input_value_port_count() const {
- int pc = (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 2 : 1;
-
- return pc;
-}
-
-int VisualScriptPropertySet::get_output_value_port_count() const {
- return (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0;
-}
-
-String VisualScriptPropertySet::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-void VisualScriptPropertySet::_adjust_input_index(PropertyInfo &pinfo) const {
- if (index != StringName()) {
- Variant v;
- Callable::CallError ce;
- Variant::construct(pinfo.type, v, nullptr, 0, ce);
- Variant i = v.get(index);
- pinfo.type = i.get_type();
- }
-}
-
-PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const {
- if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) {
- if (p_idx == 0) {
- PropertyInfo pi;
- pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type);
- pi.name = "instance";
- return pi;
- }
- }
-
- List<PropertyInfo> props;
- ClassDB::get_property_list(_get_base_type(), &props, false);
- for (const PropertyInfo &E : props) {
- if (E.name == property) {
- String detail_prop_name = property;
- if (index != StringName()) {
- detail_prop_name += "." + String(index);
- }
- PropertyInfo pinfo = PropertyInfo(E.type, detail_prop_name, E.hint, E.hint_string);
- _adjust_input_index(pinfo);
- return pinfo;
- }
- }
-
- PropertyInfo pinfo = type_cache;
- _adjust_input_index(pinfo);
- return pinfo;
-}
-
-PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) const {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- return PropertyInfo(basic_type, "pass");
- } else if (call_mode == CALL_MODE_INSTANCE) {
- return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type());
- } else {
- return PropertyInfo();
- }
-}
-
-String VisualScriptPropertySet::get_caption() const {
- 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;
- if (index != StringName()) {
- prop += "." + String(index);
- }
-
- return vformat(opname[assign_op], prop);
-}
-
-String VisualScriptPropertySet::get_text() const {
- if (!has_input_sequence_port()) {
- return "";
- }
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- return vformat(RTR("On %s"), Variant::get_type_name(basic_type));
- } else if (call_mode == CALL_MODE_INSTANCE) {
- return vformat(RTR("On %s"), base_type);
- } else if (call_mode == CALL_MODE_NODE_PATH) {
- return " [" + String(base_path.simplified()) + "]";
- } else {
- return RTR("On Self");
- }
-}
-
-void VisualScriptPropertySet::_update_base_type() {
- //cache it because this information may not be available on load
- if (call_mode == CALL_MODE_NODE_PATH) {
- Node *node = _get_base_node();
- if (node) {
- base_type = node->get_class();
- }
- } else if (call_mode == CALL_MODE_SELF) {
- if (get_visual_script().is_valid()) {
- base_type = get_visual_script()->get_instance_base_type();
- }
- }
-}
-
-void VisualScriptPropertySet::set_basic_type(Variant::Type p_type) {
- if (basic_type == p_type) {
- return;
- }
- basic_type = p_type;
-
- notify_property_list_changed();
- _update_base_type();
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptPropertySet::get_basic_type() const {
- return basic_type;
-}
-
-void VisualScriptPropertySet::set_base_type(const StringName &p_type) {
- if (base_type == p_type) {
- return;
- }
-
- base_type = p_type;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptPropertySet::get_base_type() const {
- return base_type;
-}
-
-void VisualScriptPropertySet::set_base_script(const String &p_path) {
- if (base_script == p_path) {
- return;
- }
-
- base_script = p_path;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-String VisualScriptPropertySet::get_base_script() const {
- return base_script;
-}
-
-void VisualScriptPropertySet::_update_cache() {
- if (!Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop())) {
- return;
- }
-
- if (!Engine::get_singleton()->is_editor_hint()) { //only update cache if editor exists, it's pointless otherwise
- return;
- }
-
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- //not super efficient..
-
- Variant v;
- Callable::CallError ce;
- Variant::construct(basic_type, v, nullptr, 0, ce);
-
- List<PropertyInfo> pinfo;
- v.get_property_list(&pinfo);
-
- for (const PropertyInfo &E : pinfo) {
- if (E.name == property) {
- type_cache = E;
- }
- }
-
- } else {
- StringName type;
- Ref<Script> script;
- Node *node = nullptr;
-
- if (call_mode == CALL_MODE_NODE_PATH) {
- node = _get_base_node();
- if (node) {
- type = node->get_class();
- base_type = type; //cache, too
- script = node->get_script();
- }
- } else if (call_mode == CALL_MODE_SELF) {
- if (get_visual_script().is_valid()) {
- type = get_visual_script()->get_instance_base_type();
- base_type = type; //cache, too
- script = get_visual_script();
- }
- } else if (call_mode == CALL_MODE_INSTANCE) {
- type = base_type;
- if (!base_script.is_empty()) {
- if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
- ScriptServer::edit_request_func(base_script); //make sure it's loaded
- }
-
- if (ResourceCache::has(base_script)) {
- script = ResourceCache::get_ref(base_script);
- } else {
- return;
- }
- }
- }
-
- List<PropertyInfo> pinfo;
-
- if (node) {
- node->get_property_list(&pinfo);
- } else {
- ClassDB::get_property_list(type, &pinfo);
- }
-
- if (script.is_valid()) {
- script->get_script_property_list(&pinfo);
- }
-
- for (const PropertyInfo &E : pinfo) {
- if (E.name == property) {
- type_cache = E;
- return;
- }
- }
- }
-}
-
-void VisualScriptPropertySet::set_property(const StringName &p_type) {
- if (property == p_type) {
- return;
- }
-
- property = p_type;
- index = StringName();
- _update_cache();
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptPropertySet::get_property() const {
- return property;
-}
-
-void VisualScriptPropertySet::set_base_path(const NodePath &p_type) {
- if (base_path == p_type) {
- return;
- }
-
- base_path = p_type;
- _update_base_type();
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-NodePath VisualScriptPropertySet::get_base_path() const {
- return base_path;
-}
-
-void VisualScriptPropertySet::set_call_mode(CallMode p_mode) {
- if (call_mode == p_mode) {
- return;
- }
-
- call_mode = p_mode;
- _update_base_type();
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-VisualScriptPropertySet::CallMode VisualScriptPropertySet::get_call_mode() const {
- return call_mode;
-}
-
-void VisualScriptPropertySet::_set_type_cache(const Dictionary &p_type) {
- type_cache = PropertyInfo::from_dict(p_type);
-}
-
-Dictionary VisualScriptPropertySet::_get_type_cache() const {
- return type_cache;
-}
-
-void VisualScriptPropertySet::set_index(const StringName &p_type) {
- if (index == p_type) {
- return;
- }
- index = p_type;
- _update_cache();
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptPropertySet::get_index() const {
- return index;
-}
-
-void VisualScriptPropertySet::set_assign_op(AssignOp p_op) {
- ERR_FAIL_INDEX(p_op, ASSIGN_OP_MAX);
- if (assign_op == p_op) {
- return;
- }
-
- assign_op = p_op;
- _update_cache();
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-VisualScriptPropertySet::AssignOp VisualScriptPropertySet::get_assign_op() const {
- return assign_op;
-}
-
-void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
- if (property.name == "base_type") {
- if (call_mode != CALL_MODE_INSTANCE) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
- }
- }
-
- if (property.name == "base_script") {
- if (call_mode != CALL_MODE_INSTANCE) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-
- if (property.name == "basic_type") {
- if (call_mode != CALL_MODE_BASIC_TYPE) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-
- if (property.name == "node_path") {
- if (call_mode != CALL_MODE_NODE_PATH) {
- property.usage = PROPERTY_USAGE_NONE;
- } else {
- Node *bnode = _get_base_node();
- if (bnode) {
- property.hint_string = bnode->get_path(); //convert to long string
- }
- }
- }
-
- if (property.name == "property") {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
- property.hint_string = Variant::get_type_name(basic_type);
-
- } else if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
- property.hint_string = itos(get_visual_script()->get_instance_id());
- } else if (call_mode == CALL_MODE_INSTANCE) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string = base_type;
-
- if (!base_script.is_empty()) {
- if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
- ScriptServer::edit_request_func(base_script); //make sure it's loaded
- }
-
- if (ResourceCache::has(base_script)) {
- Ref<Script> script = ResourceCache::get_ref(base_script);
- if (script.is_valid()) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
- property.hint_string = itos(script->get_instance_id());
- }
- }
- }
-
- } else if (call_mode == CALL_MODE_NODE_PATH) {
- Node *node = _get_base_node();
- if (node) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_INSTANCE;
- property.hint_string = itos(node->get_instance_id());
- } else {
- property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string = get_base_type();
- }
- }
- }
-
- if (property.name == "index") {
- Callable::CallError ce;
- Variant v;
- Variant::construct(type_cache.type, v, nullptr, 0, ce);
- List<PropertyInfo> plist;
- v.get_property_list(&plist);
- String options = "";
- for (const PropertyInfo &E : plist) {
- options += "," + E.name;
- }
-
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = options;
- property.type = Variant::STRING;
- if (options.is_empty()) {
- property.usage = PROPERTY_USAGE_NONE; //hide if type has no usable index
- }
- }
-}
-
-void VisualScriptPropertySet::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptPropertySet::set_base_type);
- ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptPropertySet::get_base_type);
-
- ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptPropertySet::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptPropertySet::get_base_script);
-
- ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptPropertySet::set_basic_type);
- ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptPropertySet::get_basic_type);
-
- ClassDB::bind_method(D_METHOD("_set_type_cache", "type_cache"), &VisualScriptPropertySet::_set_type_cache);
- ClassDB::bind_method(D_METHOD("_get_type_cache"), &VisualScriptPropertySet::_get_type_cache);
-
- ClassDB::bind_method(D_METHOD("set_property", "property"), &VisualScriptPropertySet::set_property);
- ClassDB::bind_method(D_METHOD("get_property"), &VisualScriptPropertySet::get_property);
-
- ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptPropertySet::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptPropertySet::get_call_mode);
-
- ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptPropertySet::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptPropertySet::get_base_path);
-
- ClassDB::bind_method(D_METHOD("set_index", "index"), &VisualScriptPropertySet::set_index);
- ClassDB::bind_method(D_METHOD("get_index"), &VisualScriptPropertySet::get_index);
-
- ClassDB::bind_method(D_METHOD("set_assign_op", "assign_op"), &VisualScriptPropertySet::set_assign_op);
- ClassDB::bind_method(D_METHOD("get_assign_op"), &VisualScriptPropertySet::get_assign_op);
-
- String bt;
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0) {
- bt += ",";
- }
-
- bt += Variant::get_type_name(Variant::Type(i));
- }
-
- List<String> script_extensions;
- for (int i = 0; i < ScriptServer::get_language_count(); i++) {
- ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
- }
-
- String script_ext_hint;
- for (const String &E : script_extensions) {
- if (!script_ext_hint.is_empty()) {
- script_ext_hint += ",";
- }
- script_ext_hint += "*." + E;
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_type_cache", "_get_type_cache");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "property"), "set_property", "get_property");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "index"), "set_index", "get_index");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "assign_op", PROPERTY_HINT_ENUM, "Assign,Add,Sub,Mul,Div,Mod,ShiftLeft,ShiftRight,BitAnd,BitOr,Bitxor"), "set_assign_op", "get_assign_op");
-
- BIND_ENUM_CONSTANT(CALL_MODE_SELF);
- BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH);
- BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE);
- BIND_ENUM_CONSTANT(CALL_MODE_BASIC_TYPE);
-
- BIND_ENUM_CONSTANT(ASSIGN_OP_NONE);
- BIND_ENUM_CONSTANT(ASSIGN_OP_ADD);
- BIND_ENUM_CONSTANT(ASSIGN_OP_SUB);
- BIND_ENUM_CONSTANT(ASSIGN_OP_MUL);
- BIND_ENUM_CONSTANT(ASSIGN_OP_DIV);
- BIND_ENUM_CONSTANT(ASSIGN_OP_MOD);
- BIND_ENUM_CONSTANT(ASSIGN_OP_SHIFT_LEFT);
- BIND_ENUM_CONSTANT(ASSIGN_OP_SHIFT_RIGHT);
- BIND_ENUM_CONSTANT(ASSIGN_OP_BIT_AND);
- BIND_ENUM_CONSTANT(ASSIGN_OP_BIT_OR);
- BIND_ENUM_CONSTANT(ASSIGN_OP_BIT_XOR);
-}
-
-class VisualScriptNodeInstancePropertySet : public VisualScriptNodeInstance {
-public:
- VisualScriptPropertySet::CallMode call_mode;
- NodePath node_path;
- StringName property;
-
- VisualScriptPropertySet *node = nullptr;
- VisualScriptInstance *instance = nullptr;
- VisualScriptPropertySet::AssignOp assign_op;
- StringName index;
- bool needs_get = false;
-
- //virtual int get_working_memory_size() const override { return 0; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- _FORCE_INLINE_ void _process_get(Variant &source, const Variant &p_argument, bool &valid) {
- if (index != StringName() && assign_op == VisualScriptPropertySet::ASSIGN_OP_NONE) {
- source.set_named(index, p_argument, valid);
- } else {
- Variant value;
- if (index != StringName()) {
- value = source.get_named(index, valid);
- } else {
- value = source;
- }
-
- switch (assign_op) {
- case VisualScriptPropertySet::ASSIGN_OP_NONE: {
- //should never get here
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_ADD: {
- value = Variant::evaluate(Variant::OP_ADD, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_SUB: {
- value = Variant::evaluate(Variant::OP_SUBTRACT, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_MUL: {
- value = Variant::evaluate(Variant::OP_MULTIPLY, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_DIV: {
- value = Variant::evaluate(Variant::OP_DIVIDE, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_MOD: {
- value = Variant::evaluate(Variant::OP_MODULE, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_SHIFT_LEFT: {
- value = Variant::evaluate(Variant::OP_SHIFT_LEFT, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_SHIFT_RIGHT: {
- value = Variant::evaluate(Variant::OP_SHIFT_RIGHT, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_BIT_AND: {
- value = Variant::evaluate(Variant::OP_BIT_AND, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_BIT_OR: {
- value = Variant::evaluate(Variant::OP_BIT_OR, value, p_argument);
- } break;
- case VisualScriptPropertySet::ASSIGN_OP_BIT_XOR: {
- value = Variant::evaluate(Variant::OP_BIT_XOR, value, p_argument);
- } break;
- default: {
- }
- }
-
- if (index != StringName()) {
- source.set_named(index, value, valid);
- } else {
- source = value;
- }
- }
- }
-
- 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) override {
- switch (call_mode) {
- case VisualScriptPropertySet::CALL_MODE_SELF: {
- Object *object = instance->get_owner_ptr();
-
- bool valid;
-
- if (needs_get) {
- Variant value = object->get(property, &valid);
- _process_get(value, *p_inputs[0], valid);
- object->set(property, value, &valid);
- } else {
- object->set(property, *p_inputs[0], &valid);
- }
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Invalid set value '" + String(*p_inputs[0]) + "' on property '" + String(property) + "' of type " + object->get_class();
- }
- } break;
- case VisualScriptPropertySet::CALL_MODE_NODE_PATH: {
- Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
- if (!node) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Base object is not a Node!";
- return 0;
- }
-
- Node *another = node->get_node(node_path);
- if (!another) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Path does not lead Node!";
- return 0;
- }
-
- bool valid;
-
- if (needs_get) {
- Variant value = another->get(property, &valid);
- _process_get(value, *p_inputs[0], valid);
- another->set(property, value, &valid);
- } else {
- another->set(property, *p_inputs[0], &valid);
- }
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Invalid set value '" + String(*p_inputs[0]) + "' on property '" + String(property) + "' of type " + another->get_class();
- }
-
- } break;
- case VisualScriptPropertySet::CALL_MODE_INSTANCE:
- case VisualScriptPropertySet::CALL_MODE_BASIC_TYPE: {
- Variant v = *p_inputs[0];
-
- bool valid;
-
- if (needs_get) {
- Variant value = v.get_named(property, valid);
- _process_get(value, *p_inputs[1], valid);
- v.set_named(property, value, valid);
-
- } else {
- v.set_named(property, *p_inputs[1], valid);
- }
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Invalid set value '" + String(*p_inputs[1]) + "' (" + Variant::get_type_name(p_inputs[1]->get_type()) + ") on property '" + String(property) + "' of type " + Variant::get_type_name(v.get_type());
- }
-
- *p_outputs[0] = v;
-
- } break;
- }
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptPropertySet::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstancePropertySet *instance = memnew(VisualScriptNodeInstancePropertySet);
- instance->node = this;
- instance->instance = p_instance;
- instance->property = property;
- instance->call_mode = call_mode;
- instance->node_path = base_path;
- instance->assign_op = assign_op;
- instance->index = index;
- instance->needs_get = index != StringName() || assign_op != ASSIGN_OP_NONE;
- return instance;
-}
-
-VisualScriptPropertySet::TypeGuess VisualScriptPropertySet::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) {
- return p_inputs[0];
- }
-
- return VisualScriptNode::guess_output_type(p_inputs, p_output);
-}
-
-VisualScriptPropertySet::VisualScriptPropertySet() {
- assign_op = ASSIGN_OP_NONE;
- call_mode = CALL_MODE_SELF;
- base_type = "Object";
- basic_type = Variant::NIL;
-}
-
-template <VisualScriptPropertySet::CallMode cmode>
-static Ref<VisualScriptNode> create_property_set_node(const String &p_name) {
- Ref<VisualScriptPropertySet> node;
- node.instantiate();
- node->set_call_mode(cmode);
- return node;
-}
-
-//////////////////////////////////////////
-////////////////GET//////////////////////
-//////////////////////////////////////////
-
-int VisualScriptPropertyGet::get_output_sequence_port_count() const {
- return 0; // (call_mode==CALL_MODE_SELF || call_mode==CALL_MODE_NODE_PATH)?0:1;
-}
-
-bool VisualScriptPropertyGet::has_input_sequence_port() const {
- return false; //(call_mode==CALL_MODE_SELF || call_mode==CALL_MODE_NODE_PATH)?false:true;
-}
-
-void VisualScriptPropertyGet::_update_base_type() {
- //cache it because this information may not be available on load
- if (call_mode == CALL_MODE_NODE_PATH) {
- Node *node = _get_base_node();
- if (node) {
- base_type = node->get_class();
- }
- } else if (call_mode == CALL_MODE_SELF) {
- if (get_visual_script().is_valid()) {
- base_type = get_visual_script()->get_instance_base_type();
- }
- }
-}
-
-Node *VisualScriptPropertyGet::_get_base_node() const {
-#ifdef TOOLS_ENABLED
- Ref<Script> script = get_visual_script();
- if (!script.is_valid()) {
- return nullptr;
- }
-
- MainLoop *main_loop = OS::get_singleton()->get_main_loop();
-
- SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
-
- if (!scene_tree) {
- return nullptr;
- }
-
- Node *edited_scene = scene_tree->get_edited_scene_root();
-
- if (!edited_scene) {
- return nullptr;
- }
-
- Node *script_node = _find_script_node(edited_scene, edited_scene, script);
-
- if (!script_node) {
- return nullptr;
- }
-
- if (!script_node->has_node(base_path)) {
- return nullptr;
- }
-
- Node *path_to = script_node->get_node(base_path);
-
- return path_to;
-#else
-
- return nullptr;
-#endif
-}
-
-StringName VisualScriptPropertyGet::_get_base_type() const {
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
- return get_visual_script()->get_instance_base_type();
- } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
- Node *path = _get_base_node();
- if (path) {
- return path->get_class();
- }
- }
-
- return base_type;
-}
-
-int VisualScriptPropertyGet::get_input_value_port_count() const {
- return (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0;
-}
-
-int VisualScriptPropertyGet::get_output_value_port_count() const {
- int pc = (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 2 : 1;
-
- return pc;
-}
-
-String VisualScriptPropertyGet::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptPropertyGet::get_input_value_port_info(int p_idx) const {
- if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) {
- if (p_idx == 0) {
- PropertyInfo pi;
- pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type);
- pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower());
- return pi;
- }
- }
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) const {
- if (call_mode == CALL_MODE_BASIC_TYPE && p_idx == 0) {
- return PropertyInfo(basic_type, "pass");
- } else if (call_mode == CALL_MODE_INSTANCE && p_idx == 0) {
- return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type());
- } else {
- List<PropertyInfo> props;
- ClassDB::get_property_list(_get_base_type(), &props, false);
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- if (E->get().name == property) {
- PropertyInfo pinfo = PropertyInfo(E->get().type, String(property) + "." + String(index), E->get().hint, E->get().hint_string);
- _adjust_input_index(pinfo);
- return pinfo;
- }
- }
- }
-
- PropertyInfo pinfo = PropertyInfo(type_cache, "value");
- _adjust_input_index(pinfo);
- return pinfo;
-}
-
-String VisualScriptPropertyGet::get_caption() const {
- String prop = property;
- if (index != StringName()) {
- prop += "." + String(index);
- }
-
- return vformat(RTR("Get %s"), prop);
-}
-
-String VisualScriptPropertyGet::get_text() const {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- return vformat(RTR("On %s"), Variant::get_type_name(basic_type));
- } else if (call_mode == CALL_MODE_INSTANCE) {
- return vformat(RTR("On %s"), base_type);
- } else if (call_mode == CALL_MODE_NODE_PATH) {
- return " [" + String(base_path.simplified()) + "]";
- } else {
- return RTR("On Self");
- }
-}
-
-void VisualScriptPropertyGet::set_base_type(const StringName &p_type) {
- if (base_type == p_type) {
- return;
- }
-
- base_type = p_type;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptPropertyGet::get_base_type() const {
- return base_type;
-}
-
-void VisualScriptPropertyGet::set_base_script(const String &p_path) {
- if (base_script == p_path) {
- return;
- }
-
- base_script = p_path;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-String VisualScriptPropertyGet::get_base_script() const {
- return base_script;
-}
-
-void VisualScriptPropertyGet::_update_cache() {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- //not super efficient..
-
- Variant v;
- Callable::CallError ce;
- Variant::construct(basic_type, v, nullptr, 0, ce);
-
- List<PropertyInfo> pinfo;
- v.get_property_list(&pinfo);
-
- for (const PropertyInfo &E : pinfo) {
- if (E.name == property) {
- type_cache = E.type;
- return;
- }
- }
-
- } else {
- StringName type;
- Ref<Script> script;
- Node *node = nullptr;
-
- if (call_mode == CALL_MODE_NODE_PATH) {
- node = _get_base_node();
- if (node) {
- type = node->get_class();
- base_type = type; //cache, too
- script = node->get_script();
- }
- } else if (call_mode == CALL_MODE_SELF) {
- if (get_visual_script().is_valid()) {
- type = get_visual_script()->get_instance_base_type();
- base_type = type; //cache, too
- script = get_visual_script();
- }
- } else if (call_mode == CALL_MODE_INSTANCE) {
- type = base_type;
- if (!base_script.is_empty()) {
- if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
- ScriptServer::edit_request_func(base_script); //make sure it's loaded
- }
-
- if (ResourceCache::has(base_script)) {
- script = ResourceCache::get_ref(base_script);
- } else {
- return;
- }
- }
- }
-
- bool valid = false;
-
- Variant::Type type_ret;
-
- type_ret = ClassDB::get_property_type(base_type, property, &valid);
-
- if (valid) {
- type_cache = type_ret;
- return; //all dandy
- }
-
- if (node) {
- Variant prop = node->get(property, &valid);
- if (valid) {
- type_cache = prop.get_type();
- return; //all dandy again
- }
- }
-
- if (script.is_valid()) {
- type_ret = script->get_static_property_type(property, &valid);
-
- if (valid) {
- type_cache = type_ret;
- return; //all dandy
- }
- }
- }
-}
-
-void VisualScriptPropertyGet::set_property(const StringName &p_type) {
- if (property == p_type) {
- return;
- }
-
- property = p_type;
-
- _update_cache();
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptPropertyGet::get_property() const {
- return property;
-}
-
-void VisualScriptPropertyGet::set_base_path(const NodePath &p_type) {
- if (base_path == p_type) {
- return;
- }
-
- base_path = p_type;
- notify_property_list_changed();
- _update_base_type();
- ports_changed_notify();
-}
-
-NodePath VisualScriptPropertyGet::get_base_path() const {
- return base_path;
-}
-
-void VisualScriptPropertyGet::set_call_mode(CallMode p_mode) {
- if (call_mode == p_mode) {
- return;
- }
-
- call_mode = p_mode;
- notify_property_list_changed();
- _update_base_type();
- ports_changed_notify();
-}
-
-VisualScriptPropertyGet::CallMode VisualScriptPropertyGet::get_call_mode() const {
- return call_mode;
-}
-
-void VisualScriptPropertyGet::set_basic_type(Variant::Type p_type) {
- if (basic_type == p_type) {
- return;
- }
- basic_type = p_type;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptPropertyGet::get_basic_type() const {
- return basic_type;
-}
-
-void VisualScriptPropertyGet::_set_type_cache(Variant::Type p_type) {
- type_cache = p_type;
-}
-
-Variant::Type VisualScriptPropertyGet::_get_type_cache() const {
- return type_cache;
-}
-
-void VisualScriptPropertyGet::_adjust_input_index(PropertyInfo &pinfo) const {
- if (index != StringName()) {
- Variant v;
- Callable::CallError ce;
- Variant::construct(pinfo.type, v, nullptr, 0, ce);
- Variant i = v.get(index);
- pinfo.type = i.get_type();
- pinfo.name = String(property) + "." + index;
- } else {
- pinfo.name = String(property);
- }
-}
-
-void VisualScriptPropertyGet::set_index(const StringName &p_type) {
- if (index == p_type) {
- return;
- }
- index = p_type;
- _update_cache();
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptPropertyGet::get_index() const {
- return index;
-}
-
-void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
- if (property.name == "base_type") {
- if (call_mode != CALL_MODE_INSTANCE) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
- }
- }
-
- if (property.name == "base_script") {
- if (call_mode != CALL_MODE_INSTANCE) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-
- if (property.name == "basic_type") {
- if (call_mode != CALL_MODE_BASIC_TYPE) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-
- if (property.name == "node_path") {
- if (call_mode != CALL_MODE_NODE_PATH) {
- property.usage = PROPERTY_USAGE_NONE;
- } else {
- Node *bnode = _get_base_node();
- if (bnode) {
- property.hint_string = bnode->get_path(); //convert to long string
- }
- }
- }
-
- if (property.name == "property") {
- if (call_mode == CALL_MODE_BASIC_TYPE) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
- property.hint_string = Variant::get_type_name(basic_type);
-
- } else if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
- property.hint_string = itos(get_visual_script()->get_instance_id());
- } else if (call_mode == CALL_MODE_INSTANCE) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string = base_type;
-
- if (!base_script.is_empty()) {
- if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
- ScriptServer::edit_request_func(base_script); //make sure it's loaded
- }
-
- if (ResourceCache::has(base_script)) {
- Ref<Script> script = ResourceCache::get_ref(base_script);
- if (script.is_valid()) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
- property.hint_string = itos(script->get_instance_id());
- }
- }
- }
- } else if (call_mode == CALL_MODE_NODE_PATH) {
- Node *node = _get_base_node();
- if (node) {
- property.hint = PROPERTY_HINT_PROPERTY_OF_INSTANCE;
- property.hint_string = itos(node->get_instance_id());
- } else {
- property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string = get_base_type();
- }
- }
- }
-
- if (property.name == "index") {
- Callable::CallError ce;
- Variant v;
- Variant::construct(type_cache, v, nullptr, 0, ce);
- List<PropertyInfo> plist;
- v.get_property_list(&plist);
- String options = "";
- for (const PropertyInfo &E : plist) {
- options += "," + E.name;
- }
-
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = options;
- property.type = Variant::STRING;
- if (options.is_empty()) {
- property.usage = PROPERTY_USAGE_NONE; //hide if type has no usable index
- }
- }
-}
-
-void VisualScriptPropertyGet::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptPropertyGet::set_base_type);
- ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptPropertyGet::get_base_type);
-
- ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptPropertyGet::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptPropertyGet::get_base_script);
-
- ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptPropertyGet::set_basic_type);
- ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptPropertyGet::get_basic_type);
-
- ClassDB::bind_method(D_METHOD("_set_type_cache", "type_cache"), &VisualScriptPropertyGet::_set_type_cache);
- ClassDB::bind_method(D_METHOD("_get_type_cache"), &VisualScriptPropertyGet::_get_type_cache);
-
- ClassDB::bind_method(D_METHOD("set_property", "property"), &VisualScriptPropertyGet::set_property);
- ClassDB::bind_method(D_METHOD("get_property"), &VisualScriptPropertyGet::get_property);
-
- ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptPropertyGet::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptPropertyGet::get_call_mode);
-
- ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptPropertyGet::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptPropertyGet::get_base_path);
-
- ClassDB::bind_method(D_METHOD("set_index", "index"), &VisualScriptPropertyGet::set_index);
- ClassDB::bind_method(D_METHOD("get_index"), &VisualScriptPropertyGet::get_index);
-
- String bt;
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0) {
- bt += ",";
- }
-
- bt += Variant::get_type_name(Variant::Type(i));
- }
-
- List<String> script_extensions;
- for (int i = 0; i < ScriptServer::get_language_count(); i++) {
- ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
- }
-
- String script_ext_hint;
- for (const String &E : script_extensions) {
- if (!script_ext_hint.is_empty()) {
- script_ext_hint += ",";
- }
- script_ext_hint += "." + E;
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_type_cache", "_get_type_cache");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "property"), "set_property", "get_property");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "index", PROPERTY_HINT_ENUM), "set_index", "get_index");
-
- BIND_ENUM_CONSTANT(CALL_MODE_SELF);
- BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH);
- BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE);
- BIND_ENUM_CONSTANT(CALL_MODE_BASIC_TYPE);
-}
-
-class VisualScriptNodeInstancePropertyGet : public VisualScriptNodeInstance {
-public:
- VisualScriptPropertyGet::CallMode call_mode;
- NodePath node_path;
- StringName property;
- StringName index;
-
- VisualScriptPropertyGet *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- 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) override {
- switch (call_mode) {
- case VisualScriptPropertyGet::CALL_MODE_SELF: {
- Object *object = instance->get_owner_ptr();
-
- bool valid;
-
- *p_outputs[0] = object->get(property, &valid);
-
- if (index != StringName()) {
- *p_outputs[0] = p_outputs[0]->get_named(index, valid);
- }
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Invalid index property name.");
- return 0;
- }
- } break;
- case VisualScriptPropertyGet::CALL_MODE_NODE_PATH: {
- Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
- if (!node) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Base object is not a Node!");
- return 0;
- }
-
- Node *another = node->get_node(node_path);
- if (!another) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Path does not lead Node!");
- return 0;
- }
-
- bool valid;
-
- *p_outputs[0] = another->get(property, &valid);
-
- if (index != StringName()) {
- *p_outputs[0] = p_outputs[0]->get_named(index, valid);
- }
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = vformat(RTR("Invalid index property name '%s' in node %s."), String(property), another->get_name());
- return 0;
- }
-
- } break;
- default: {
- bool valid;
- Variant v = *p_inputs[0];
-
- *p_outputs[1] = v.get(property, &valid);
- if (index != StringName()) {
- *p_outputs[1] = p_outputs[1]->get_named(index, valid);
- }
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("Invalid index property name.");
- }
-
- *p_outputs[0] = v;
- };
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptPropertyGet::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstancePropertyGet *instance = memnew(VisualScriptNodeInstancePropertyGet);
- instance->node = this;
- instance->instance = p_instance;
- instance->property = property;
- instance->call_mode = call_mode;
- instance->node_path = base_path;
- instance->index = index;
-
- return instance;
-}
-
-VisualScriptPropertyGet::VisualScriptPropertyGet() {
- call_mode = CALL_MODE_SELF;
- base_type = "Object";
- basic_type = Variant::NIL;
- type_cache = Variant::NIL;
-}
-
-template <VisualScriptPropertyGet::CallMode cmode>
-static Ref<VisualScriptNode> create_property_get_node(const String &p_name) {
- Ref<VisualScriptPropertyGet> node;
- node.instantiate();
- node->set_call_mode(cmode);
- return node;
-}
-
-//////////////////////////////////////////
-////////////////EMIT//////////////////////
-//////////////////////////////////////////
-
-int VisualScriptEmitSignal::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptEmitSignal::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptEmitSignal::get_input_value_port_count() const {
- Ref<VisualScript> vs = get_visual_script();
- if (vs.is_valid()) {
- if (!vs->has_custom_signal(name)) {
- return 0;
- }
-
- return vs->custom_signal_get_argument_count(name);
- }
-
- return 0;
-}
-
-int VisualScriptEmitSignal::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptEmitSignal::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptEmitSignal::get_input_value_port_info(int p_idx) const {
- Ref<VisualScript> vs = get_visual_script();
- if (vs.is_valid()) {
- if (!vs->has_custom_signal(name)) {
- return PropertyInfo();
- }
-
- return PropertyInfo(vs->custom_signal_get_argument_type(name, p_idx), vs->custom_signal_get_argument_name(name, p_idx));
- }
-
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptEmitSignal::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptEmitSignal::get_caption() const {
- return vformat(RTR("Emit %s"), name);
-}
-
-void VisualScriptEmitSignal::set_signal(const StringName &p_type) {
- if (name == p_type) {
- return;
- }
-
- name = p_type;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptEmitSignal::get_signal() const {
- return name;
-}
-
-void VisualScriptEmitSignal::_validate_property(PropertyInfo &property) const {
- if (property.name == "signal") {
- property.hint = PROPERTY_HINT_ENUM;
-
- List<StringName> sigs;
- List<MethodInfo> base_sigs;
-
- Ref<VisualScript> vs = get_visual_script();
- if (vs.is_valid()) {
- vs->get_custom_signal_list(&sigs);
- ClassDB::get_signal_list(vs->get_instance_base_type(), &base_sigs);
- }
-
- String ml;
- for (const StringName &E : sigs) {
- if (!ml.is_empty()) {
- ml += ",";
- }
- ml += E;
- }
- for (const MethodInfo &E : base_sigs) {
- if (!ml.is_empty()) {
- ml += ",";
- }
- ml += E.name;
- }
-
- property.hint_string = ml;
- }
-}
-
-void VisualScriptEmitSignal::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_signal", "name"), &VisualScriptEmitSignal::set_signal);
- ClassDB::bind_method(D_METHOD("get_signal"), &VisualScriptEmitSignal::get_signal);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "signal"), "set_signal", "get_signal");
-}
-
-class VisualScriptNodeInstanceEmitSignal : public VisualScriptNodeInstance {
-public:
- VisualScriptEmitSignal *node = nullptr;
- VisualScriptInstance *instance = nullptr;
- int argcount = 0;
- StringName name;
-
- //virtual int get_working_memory_size() const override { return 0; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- Object *obj = instance->get_owner_ptr();
-
- obj->emit_signalp(name, p_inputs, argcount);
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptEmitSignal::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceEmitSignal *instance = memnew(VisualScriptNodeInstanceEmitSignal);
- instance->node = this;
- instance->instance = p_instance;
- instance->name = name;
- instance->argcount = get_input_value_port_count();
- return instance;
-}
-
-VisualScriptEmitSignal::VisualScriptEmitSignal() {
-}
-
-static Ref<VisualScriptNode> create_basic_type_call_node(const String &p_name) {
- Vector<String> path = p_name.split("/");
- ERR_FAIL_COND_V(path.size() < 4, Ref<VisualScriptNode>());
- String base_type = path[2];
- String method = path[3];
-
- Ref<VisualScriptFunctionCall> node;
- node.instantiate();
-
- Variant::Type type = Variant::VARIANT_MAX;
-
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (Variant::get_type_name(Variant::Type(i)) == base_type) {
- type = Variant::Type(i);
- break;
- }
- }
-
- ERR_FAIL_COND_V(type == Variant::VARIANT_MAX, Ref<VisualScriptNode>());
-
- node->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE);
- node->set_basic_type(type);
- node->set_function(method);
-
- return node;
-}
-
-void register_visual_script_func_nodes() {
- VisualScriptLanguage::singleton->add_register_func("functions/call", create_node_generic<VisualScriptFunctionCall>);
- VisualScriptLanguage::singleton->add_register_func("functions/set", create_node_generic<VisualScriptPropertySet>);
- VisualScriptLanguage::singleton->add_register_func("functions/get", create_node_generic<VisualScriptPropertyGet>);
-
- //VisualScriptLanguage::singleton->add_register_func("functions/call_script/call_self",create_script_call_node<VisualScriptScriptCall::CALL_MODE_SELF>);
- //VisualScriptLanguage::singleton->add_register_func("functions/call_script/call_node",create_script_call_node<VisualScriptScriptCall::CALL_MODE_NODE_PATH>);
- VisualScriptLanguage::singleton->add_register_func("functions/emit_signal", create_node_generic<VisualScriptEmitSignal>);
-
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- Variant::Type t = Variant::Type(i);
- String type_name = Variant::get_type_name(t);
- Callable::CallError ce;
- Variant vt;
- Variant::construct(t, vt, nullptr, 0, ce);
- List<MethodInfo> ml;
- vt.get_method_list(&ml);
-
- for (const MethodInfo &E : ml) {
- VisualScriptLanguage::singleton->add_register_func("functions/by_type/" + type_name + "/" + E.name, create_basic_type_call_node);
- }
- }
-}
diff --git a/modules/visual_script/visual_script_func_nodes.h b/modules/visual_script/visual_script_func_nodes.h
deleted file mode 100644
index 886ed7bc81..0000000000
--- a/modules/visual_script/visual_script_func_nodes.h
+++ /dev/null
@@ -1,363 +0,0 @@
-/*************************************************************************/
-/* visual_script_func_nodes.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 VISUAL_SCRIPT_FUNC_NODES_H
-#define VISUAL_SCRIPT_FUNC_NODES_H
-
-#include "visual_script.h"
-
-class VisualScriptFunctionCall : public VisualScriptNode {
- GDCLASS(VisualScriptFunctionCall, VisualScriptNode);
-
-public:
- enum CallMode {
- CALL_MODE_SELF,
- CALL_MODE_NODE_PATH,
- CALL_MODE_INSTANCE,
- CALL_MODE_BASIC_TYPE,
- CALL_MODE_SINGLETON,
- };
-
- enum RPCCallMode {
- RPC_DISABLED,
- RPC_RELIABLE,
- RPC_UNRELIABLE,
- RPC_RELIABLE_TO_ID,
- RPC_UNRELIABLE_TO_ID
- };
-
-private:
- CallMode call_mode;
- StringName base_type;
- String base_script;
- Variant::Type basic_type;
- NodePath base_path;
- StringName function;
- int use_default_args;
- RPCCallMode rpc_call_mode;
- StringName singleton;
- bool validate;
-
- Node *_get_base_node() const;
- StringName _get_base_type() const;
-
- MethodInfo method_cache;
- void _update_method_cache();
-
- void _set_argument_cache(const Dictionary &p_cache);
- Dictionary _get_argument_cache() const;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "functions"; }
-
- void set_basic_type(Variant::Type p_type);
- Variant::Type get_basic_type() const;
-
- void set_base_type(const StringName &p_type);
- StringName get_base_type() const;
-
- void set_base_script(const String &p_path);
- String get_base_script() const;
-
- void set_singleton(const StringName &p_type);
- StringName get_singleton() const;
-
- void set_function(const StringName &p_type);
- StringName get_function() const;
-
- void set_base_path(const NodePath &p_type);
- NodePath get_base_path() const;
-
- void set_call_mode(CallMode p_mode);
- CallMode get_call_mode() const;
-
- void set_use_default_args(int p_amount);
- int get_use_default_args() const;
-
- void set_validate(bool p_amount);
- bool get_validate() const;
-
- void set_rpc_call_mode(RPCCallMode p_mode);
- RPCCallMode get_rpc_call_mode() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- VisualScriptFunctionCall();
-};
-
-VARIANT_ENUM_CAST(VisualScriptFunctionCall::CallMode);
-VARIANT_ENUM_CAST(VisualScriptFunctionCall::RPCCallMode);
-
-class VisualScriptPropertySet : public VisualScriptNode {
- GDCLASS(VisualScriptPropertySet, VisualScriptNode);
-
-public:
- enum CallMode {
- CALL_MODE_SELF,
- CALL_MODE_NODE_PATH,
- CALL_MODE_INSTANCE,
- CALL_MODE_BASIC_TYPE,
-
- };
-
- enum AssignOp {
- ASSIGN_OP_NONE,
- ASSIGN_OP_ADD,
- ASSIGN_OP_SUB,
- ASSIGN_OP_MUL,
- ASSIGN_OP_DIV,
- ASSIGN_OP_MOD,
- ASSIGN_OP_SHIFT_LEFT,
- ASSIGN_OP_SHIFT_RIGHT,
- ASSIGN_OP_BIT_AND,
- ASSIGN_OP_BIT_OR,
- ASSIGN_OP_BIT_XOR,
- ASSIGN_OP_MAX
- };
-
-private:
- PropertyInfo type_cache;
-
- CallMode call_mode;
- Variant::Type basic_type;
- StringName base_type;
- String base_script;
- NodePath base_path;
- StringName property;
- StringName index;
- AssignOp assign_op;
-
- Node *_get_base_node() const;
- StringName _get_base_type() const;
-
- void _update_base_type();
-
- void _update_cache();
-
- void _set_type_cache(const Dictionary &p_type);
- Dictionary _get_type_cache() const;
-
- void _adjust_input_index(PropertyInfo &pinfo) const;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "functions"; }
-
- void set_base_type(const StringName &p_type);
- StringName get_base_type() const;
-
- void set_base_script(const String &p_path);
- String get_base_script() const;
-
- void set_basic_type(Variant::Type p_type);
- Variant::Type get_basic_type() const;
-
- void set_property(const StringName &p_type);
- StringName get_property() const;
-
- void set_base_path(const NodePath &p_type);
- NodePath get_base_path() const;
-
- void set_call_mode(CallMode p_mode);
- CallMode get_call_mode() const;
-
- void set_index(const StringName &p_type);
- StringName get_index() const;
-
- void set_assign_op(AssignOp p_op);
- AssignOp get_assign_op() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- VisualScriptPropertySet();
-};
-
-VARIANT_ENUM_CAST(VisualScriptPropertySet::CallMode);
-VARIANT_ENUM_CAST(VisualScriptPropertySet::AssignOp);
-
-class VisualScriptPropertyGet : public VisualScriptNode {
- GDCLASS(VisualScriptPropertyGet, VisualScriptNode);
-
-public:
- enum CallMode {
- CALL_MODE_SELF,
- CALL_MODE_NODE_PATH,
- CALL_MODE_INSTANCE,
- CALL_MODE_BASIC_TYPE,
-
- };
-
-private:
- Variant::Type type_cache;
-
- CallMode call_mode;
- Variant::Type basic_type;
- StringName base_type;
- String base_script;
- NodePath base_path;
- StringName property;
- StringName index;
-
- void _update_base_type();
- Node *_get_base_node() const;
- StringName _get_base_type() const;
-
- void _update_cache();
-
- void _set_type_cache(Variant::Type p_type);
- Variant::Type _get_type_cache() const;
-
- void _adjust_input_index(PropertyInfo &pinfo) const;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "functions"; }
-
- void set_base_type(const StringName &p_type);
- StringName get_base_type() const;
-
- void set_base_script(const String &p_path);
- String get_base_script() const;
-
- void set_basic_type(Variant::Type p_type);
- Variant::Type get_basic_type() const;
-
- void set_property(const StringName &p_type);
- StringName get_property() const;
-
- void set_base_path(const NodePath &p_type);
- NodePath get_base_path() const;
-
- void set_call_mode(CallMode p_mode);
- CallMode get_call_mode() const;
-
- void set_index(const StringName &p_type);
- StringName get_index() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptPropertyGet();
-};
-
-VARIANT_ENUM_CAST(VisualScriptPropertyGet::CallMode);
-
-class VisualScriptEmitSignal : public VisualScriptNode {
- GDCLASS(VisualScriptEmitSignal, VisualScriptNode);
-
-private:
- StringName name;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- //virtual String get_text() const;
- virtual String get_category() const override { return "functions"; }
-
- void set_signal(const StringName &p_type);
- StringName get_signal() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptEmitSignal();
-};
-
-void register_visual_script_func_nodes();
-
-#endif // VISUAL_SCRIPT_FUNC_NODES_H
diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp
deleted file mode 100644
index 5907e6a489..0000000000
--- a/modules/visual_script/visual_script_nodes.cpp
+++ /dev/null
@@ -1,4072 +0,0 @@
-/*************************************************************************/
-/* visual_script_nodes.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 "visual_script_nodes.h"
-
-#include "core/config/engine.h"
-#include "core/config/project_settings.h"
-#include "core/core_constants.h"
-#include "core/input/input.h"
-#include "core/os/os.h"
-#include "scene/main/node.h"
-#include "scene/main/scene_tree.h"
-
-//////////////////////////////////////////
-////////////////FUNCTION//////////////////
-//////////////////////////////////////////
-
-bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value) {
- if (p_name == "argument_count") {
- int new_argc = p_value;
- int argc = arguments.size();
- if (argc == new_argc) {
- return true;
- }
-
- arguments.resize(new_argc);
-
- for (int i = argc; i < new_argc; i++) {
- arguments.write[i].name = "arg" + itos(i + 1);
- arguments.write[i].type = Variant::NIL;
- }
- ports_changed_notify();
- notify_property_list_changed();
- return true;
- }
- if (String(p_name).begins_with("argument_")) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, arguments.size(), false);
- String what = String(p_name).get_slice("/", 1);
- if (what == "type") {
- Variant::Type new_type = Variant::Type(int(p_value));
- arguments.write[idx].type = new_type;
- ports_changed_notify();
-
- return true;
- }
-
- if (what == "name") {
- arguments.write[idx].name = p_value;
- ports_changed_notify();
- return true;
- }
- }
-
- if (p_name == "stack/stackless") {
- set_stack_less(p_value);
- return true;
- }
-
- if (p_name == "stack/size") {
- stack_size = p_value;
- return true;
- }
-
- if (p_name == "rpc/mode") {
- rpc_mode = MultiplayerAPI::RPCMode(int(p_value));
- return true;
- }
-
- if (p_name == "sequenced/sequenced") {
- sequenced = p_value;
- ports_changed_notify();
- return true;
- }
-
- return false;
-}
-
-bool VisualScriptFunction::_get(const StringName &p_name, Variant &r_ret) const {
- if (p_name == "argument_count") {
- r_ret = arguments.size();
- return true;
- }
- if (String(p_name).begins_with("argument_")) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, arguments.size(), false);
- String what = String(p_name).get_slice("/", 1);
- if (what == "type") {
- r_ret = arguments[idx].type;
- return true;
- }
- if (what == "name") {
- r_ret = arguments[idx].name;
- return true;
- }
- }
-
- if (p_name == "stack/stackless") {
- r_ret = stack_less;
- return true;
- }
-
- if (p_name == "stack/size") {
- r_ret = stack_size;
- return true;
- }
-
- if (p_name == "rpc/mode") {
- r_ret = rpc_mode;
- return true;
- }
-
- if (p_name == "sequenced/sequenced") {
- r_ret = sequenced;
- return true;
- }
-
- return false;
-}
-
-void VisualScriptFunction::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::INT, "argument_count", PROPERTY_HINT_RANGE, "0,256"));
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- for (int i = 0; i < arguments.size(); i++) {
- p_list->push_back(PropertyInfo(Variant::INT, "argument_" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt));
- p_list->push_back(PropertyInfo(Variant::STRING, "argument_" + itos(i + 1) + "/name"));
- }
-
- p_list->push_back(PropertyInfo(Variant::BOOL, "sequenced/sequenced"));
-
- if (!stack_less) {
- p_list->push_back(PropertyInfo(Variant::INT, "stack/size", PROPERTY_HINT_RANGE, "1,100000"));
- }
- p_list->push_back(PropertyInfo(Variant::BOOL, "stack/stackless"));
- p_list->push_back(PropertyInfo(Variant::INT, "rpc/mode", PROPERTY_HINT_ENUM, "Disabled,Any,Authority"));
-}
-
-int VisualScriptFunction::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptFunction::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptFunction::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptFunction::get_output_value_port_count() const {
- return arguments.size();
-}
-
-String VisualScriptFunction::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const {
- ERR_FAIL_V(PropertyInfo());
-}
-
-PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const {
- // Need to check it without ERR_FAIL_COND, to prevent warnings from appearing on node creation via dragging.
- if (p_idx < 0 || p_idx >= arguments.size()) {
- return PropertyInfo();
- }
- PropertyInfo out;
- out.type = arguments[p_idx].type;
- out.name = arguments[p_idx].name;
- out.hint = arguments[p_idx].hint;
- out.hint_string = arguments[p_idx].hint_string;
- return out;
-}
-
-String VisualScriptFunction::get_caption() const {
- return RTR("Function");
-}
-
-String VisualScriptFunction::get_text() const {
- return get_name(); //use name as function name I guess
-}
-
-void VisualScriptFunction::add_argument(Variant::Type p_type, const String &p_name, int p_index, const PropertyHint p_hint, const String &p_hint_string) {
- Argument arg;
- arg.name = p_name;
- arg.type = p_type;
- arg.hint = p_hint;
- arg.hint_string = p_hint_string;
- if (p_index >= 0) {
- arguments.insert(p_index, arg);
- } else {
- arguments.push_back(arg);
- }
-
- ports_changed_notify();
-}
-
-void VisualScriptFunction::set_argument_type(int p_argidx, Variant::Type p_type) {
- ERR_FAIL_INDEX(p_argidx, arguments.size());
-
- arguments.write[p_argidx].type = p_type;
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptFunction::get_argument_type(int p_argidx) const {
- ERR_FAIL_INDEX_V(p_argidx, arguments.size(), Variant::NIL);
- return arguments[p_argidx].type;
-}
-
-void VisualScriptFunction::set_argument_name(int p_argidx, const String &p_name) {
- ERR_FAIL_INDEX(p_argidx, arguments.size());
-
- arguments.write[p_argidx].name = p_name;
- ports_changed_notify();
-}
-
-String VisualScriptFunction::get_argument_name(int p_argidx) const {
- ERR_FAIL_INDEX_V(p_argidx, arguments.size(), String());
- return arguments[p_argidx].name;
-}
-
-void VisualScriptFunction::remove_argument(int p_argidx) {
- ERR_FAIL_INDEX(p_argidx, arguments.size());
-
- arguments.remove_at(p_argidx);
- ports_changed_notify();
-}
-
-int VisualScriptFunction::get_argument_count() const {
- return arguments.size();
-}
-
-void VisualScriptFunction::set_rpc_mode(MultiplayerAPI::RPCMode p_mode) {
- rpc_mode = p_mode;
-}
-
-MultiplayerAPI::RPCMode VisualScriptFunction::get_rpc_mode() const {
- return rpc_mode;
-}
-
-class VisualScriptNodeInstanceFunction : public VisualScriptNodeInstance {
-public:
- VisualScriptFunction *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- int ac = node->get_argument_count();
-
- for (int i = 0; i < ac; i++) {
-#ifdef DEBUG_ENABLED
- Variant::Type expected = node->get_argument_type(i);
- if (expected != Variant::NIL) {
- if (!Variant::can_convert_strict(p_inputs[i]->get_type(), expected)) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.expected = expected;
- r_error.argument = i;
- return 0;
- }
- }
-#endif
-
- *p_outputs[i] = *p_inputs[i];
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptFunction::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceFunction *instance = memnew(VisualScriptNodeInstanceFunction);
- instance->node = this;
- instance->instance = p_instance;
- return instance;
-}
-
-void VisualScriptFunction::reset_state() {
- arguments.clear();
- stack_size = 256;
- stack_less = false;
- sequenced = true;
- rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
-}
-
-VisualScriptFunction::VisualScriptFunction() {
- stack_size = 256;
- stack_less = false;
- sequenced = true;
- rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
-}
-
-void VisualScriptFunction::set_stack_less(bool p_enable) {
- stack_less = p_enable;
- notify_property_list_changed();
-}
-
-bool VisualScriptFunction::is_stack_less() const {
- return stack_less;
-}
-
-void VisualScriptFunction::set_sequenced(bool p_enable) {
- sequenced = p_enable;
-}
-
-bool VisualScriptFunction::is_sequenced() const {
- return sequenced;
-}
-
-void VisualScriptFunction::set_stack_size(int p_size) {
- ERR_FAIL_COND(p_size < 1 || p_size > 100000);
- stack_size = p_size;
-}
-
-int VisualScriptFunction::get_stack_size() const {
- return stack_size;
-}
-
-//////////////////////////////////////////
-/////////////////LISTS////////////////////
-//////////////////////////////////////////
-
-int VisualScriptLists::get_output_sequence_port_count() const {
- if (sequenced) {
- return 1;
- }
- return 0;
-}
-
-bool VisualScriptLists::has_input_sequence_port() const {
- return sequenced;
-}
-
-String VisualScriptLists::get_output_sequence_port_text(int p_port) const {
- return "";
-}
-
-int VisualScriptLists::get_input_value_port_count() const {
- return inputports.size();
-}
-
-int VisualScriptLists::get_output_value_port_count() const {
- return outputports.size();
-}
-
-PropertyInfo VisualScriptLists::get_input_value_port_info(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo());
-
- PropertyInfo pi;
- pi.name = inputports[p_idx].name;
- pi.type = inputports[p_idx].type;
- return pi;
-}
-
-PropertyInfo VisualScriptLists::get_output_value_port_info(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx, outputports.size(), PropertyInfo());
-
- PropertyInfo pi;
- pi.name = outputports[p_idx].name;
- pi.type = outputports[p_idx].type;
- return pi;
-}
-
-bool VisualScriptLists::is_input_port_editable() const {
- return ((flags & INPUT_EDITABLE) == INPUT_EDITABLE);
-}
-
-bool VisualScriptLists::is_input_port_name_editable() const {
- return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE);
-}
-
-bool VisualScriptLists::is_input_port_type_editable() const {
- return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE);
-}
-
-bool VisualScriptLists::is_output_port_editable() const {
- return ((flags & OUTPUT_EDITABLE) == OUTPUT_EDITABLE);
-}
-
-bool VisualScriptLists::is_output_port_name_editable() const {
- return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE);
-}
-
-bool VisualScriptLists::is_output_port_type_editable() const {
- return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE);
-}
-
-// for the inspector
-bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
- if (p_name == "input_count" && is_input_port_editable()) {
- int new_argc = p_value;
- int argc = inputports.size();
- if (argc == new_argc) {
- return true;
- }
-
- inputports.resize(new_argc);
-
- for (int i = argc; i < new_argc; i++) {
- inputports.write[i].name = "arg" + itos(i + 1);
- inputports.write[i].type = Variant::NIL;
- }
- ports_changed_notify();
- notify_property_list_changed();
- return true;
- }
- if (String(p_name).begins_with("input_") && is_input_port_editable()) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, inputports.size(), false);
- String what = String(p_name).get_slice("/", 1);
- if (what == "type") {
- Variant::Type new_type = Variant::Type(int(p_value));
- inputports.write[idx].type = new_type;
- ports_changed_notify();
-
- return true;
- }
-
- if (what == "name") {
- inputports.write[idx].name = p_value;
- ports_changed_notify();
- return true;
- }
- }
-
- if (p_name == "output_count" && is_output_port_editable()) {
- int new_argc = p_value;
- int argc = outputports.size();
- if (argc == new_argc) {
- return true;
- }
-
- outputports.resize(new_argc);
-
- for (int i = argc; i < new_argc; i++) {
- outputports.write[i].name = "arg" + itos(i + 1);
- outputports.write[i].type = Variant::NIL;
- }
- ports_changed_notify();
- notify_property_list_changed();
- return true;
- }
- if (String(p_name).begins_with("output_") && is_output_port_editable()) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, outputports.size(), false);
- String what = String(p_name).get_slice("/", 1);
- if (what == "type") {
- Variant::Type new_type = Variant::Type(int(p_value));
- outputports.write[idx].type = new_type;
- ports_changed_notify();
-
- return true;
- }
-
- if (what == "name") {
- outputports.write[idx].name = p_value;
- ports_changed_notify();
- return true;
- }
- }
-
- if (p_name == "sequenced/sequenced") {
- sequenced = p_value;
- ports_changed_notify();
- return true;
- }
-
- return false;
-}
-
-bool VisualScriptLists::_get(const StringName &p_name, Variant &r_ret) const {
- if (p_name == "input_count" && is_input_port_editable()) {
- r_ret = inputports.size();
- return true;
- }
- if (String(p_name).begins_with("input_") && is_input_port_editable()) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, inputports.size(), false);
- String what = String(p_name).get_slice("/", 1);
- if (what == "type") {
- r_ret = inputports[idx].type;
- return true;
- }
- if (what == "name") {
- r_ret = inputports[idx].name;
- return true;
- }
- }
-
- if (p_name == "output_count" && is_output_port_editable()) {
- r_ret = outputports.size();
- return true;
- }
- if (String(p_name).begins_with("output_") && is_output_port_editable()) {
- int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1;
- ERR_FAIL_INDEX_V(idx, outputports.size(), false);
- String what = String(p_name).get_slice("/", 1);
- if (what == "type") {
- r_ret = outputports[idx].type;
- return true;
- }
- if (what == "name") {
- r_ret = outputports[idx].name;
- return true;
- }
- }
-
- if (p_name == "sequenced/sequenced") {
- r_ret = sequenced;
- return true;
- }
-
- return false;
-}
-
-void VisualScriptLists::_get_property_list(List<PropertyInfo> *p_list) const {
- if (is_input_port_editable()) {
- p_list->push_back(PropertyInfo(Variant::INT, "input_count", PROPERTY_HINT_RANGE, "0,256"));
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- for (int i = 0; i < inputports.size(); i++) {
- p_list->push_back(PropertyInfo(Variant::INT, "input_" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt));
- p_list->push_back(PropertyInfo(Variant::STRING, "input_" + itos(i + 1) + "/name"));
- }
- }
-
- if (is_output_port_editable()) {
- p_list->push_back(PropertyInfo(Variant::INT, "output_count", PROPERTY_HINT_RANGE, "0,256"));
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- for (int i = 0; i < outputports.size(); i++) {
- p_list->push_back(PropertyInfo(Variant::INT, "output_" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt));
- p_list->push_back(PropertyInfo(Variant::STRING, "output_" + itos(i + 1) + "/name"));
- }
- }
- p_list->push_back(PropertyInfo(Variant::BOOL, "sequenced/sequenced"));
-}
-
-// input data port interaction
-void VisualScriptLists::add_input_data_port(Variant::Type p_type, const String &p_name, int p_index) {
- if (!is_input_port_editable()) {
- return;
- }
-
- Port inp;
- inp.name = p_name;
- inp.type = p_type;
- if (p_index >= 0) {
- inputports.insert(p_index, inp);
- } else {
- inputports.push_back(inp);
- }
-
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-void VisualScriptLists::set_input_data_port_type(int p_idx, Variant::Type p_type) {
- if (!is_input_port_type_editable()) {
- return;
- }
-
- ERR_FAIL_INDEX(p_idx, inputports.size());
-
- inputports.write[p_idx].type = p_type;
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-void VisualScriptLists::set_input_data_port_name(int p_idx, const String &p_name) {
- if (!is_input_port_name_editable()) {
- return;
- }
-
- ERR_FAIL_INDEX(p_idx, inputports.size());
-
- inputports.write[p_idx].name = p_name;
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-void VisualScriptLists::remove_input_data_port(int p_argidx) {
- if (!is_input_port_editable()) {
- return;
- }
-
- ERR_FAIL_INDEX(p_argidx, inputports.size());
-
- inputports.remove_at(p_argidx);
-
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-// output data port interaction
-void VisualScriptLists::add_output_data_port(Variant::Type p_type, const String &p_name, int p_index) {
- if (!is_output_port_editable()) {
- return;
- }
-
- Port out;
- out.name = p_name;
- out.type = p_type;
- if (p_index >= 0) {
- outputports.insert(p_index, out);
- } else {
- outputports.push_back(out);
- }
-
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-void VisualScriptLists::set_output_data_port_type(int p_idx, Variant::Type p_type) {
- if (!is_output_port_type_editable()) {
- return;
- }
-
- ERR_FAIL_INDEX(p_idx, outputports.size());
-
- outputports.write[p_idx].type = p_type;
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-void VisualScriptLists::set_output_data_port_name(int p_idx, const String &p_name) {
- if (!is_output_port_name_editable()) {
- return;
- }
-
- ERR_FAIL_INDEX(p_idx, outputports.size());
-
- outputports.write[p_idx].name = p_name;
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-void VisualScriptLists::remove_output_data_port(int p_argidx) {
- if (!is_output_port_editable()) {
- return;
- }
-
- ERR_FAIL_INDEX(p_argidx, outputports.size());
-
- outputports.remove_at(p_argidx);
-
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-// sequences
-void VisualScriptLists::set_sequenced(bool p_enable) {
- if (sequenced == p_enable) {
- return;
- }
- sequenced = p_enable;
- ports_changed_notify();
-}
-
-bool VisualScriptLists::is_sequenced() const {
- return sequenced;
-}
-
-void VisualScriptLists::reset_state() {
- inputports.clear();
- outputports.clear();
- sequenced = false;
- flags = 0;
-}
-
-VisualScriptLists::VisualScriptLists() {
- // initialize
- sequenced = false;
- flags = 0;
-}
-
-void VisualScriptLists::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_input_data_port", "type", "name", "index"), &VisualScriptLists::add_input_data_port);
- ClassDB::bind_method(D_METHOD("set_input_data_port_name", "index", "name"), &VisualScriptLists::set_input_data_port_name);
- ClassDB::bind_method(D_METHOD("set_input_data_port_type", "index", "type"), &VisualScriptLists::set_input_data_port_type);
- ClassDB::bind_method(D_METHOD("remove_input_data_port", "index"), &VisualScriptLists::remove_input_data_port);
-
- ClassDB::bind_method(D_METHOD("add_output_data_port", "type", "name", "index"), &VisualScriptLists::add_output_data_port);
- ClassDB::bind_method(D_METHOD("set_output_data_port_name", "index", "name"), &VisualScriptLists::set_output_data_port_name);
- ClassDB::bind_method(D_METHOD("set_output_data_port_type", "index", "type"), &VisualScriptLists::set_output_data_port_type);
- ClassDB::bind_method(D_METHOD("remove_output_data_port", "index"), &VisualScriptLists::remove_output_data_port);
-}
-
-//////////////////////////////////////////
-//////////////COMPOSEARRAY////////////////
-//////////////////////////////////////////
-
-int VisualScriptComposeArray::get_output_sequence_port_count() const {
- if (sequenced) {
- return 1;
- }
- return 0;
-}
-
-bool VisualScriptComposeArray::has_input_sequence_port() const {
- return sequenced;
-}
-
-String VisualScriptComposeArray::get_output_sequence_port_text(int p_port) const {
- return "";
-}
-
-int VisualScriptComposeArray::get_input_value_port_count() const {
- return inputports.size();
-}
-
-int VisualScriptComposeArray::get_output_value_port_count() const {
- return 1;
-}
-
-PropertyInfo VisualScriptComposeArray::get_input_value_port_info(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo());
-
- PropertyInfo pi;
- pi.name = inputports[p_idx].name;
- pi.type = inputports[p_idx].type;
- return pi;
-}
-
-PropertyInfo VisualScriptComposeArray::get_output_value_port_info(int p_idx) const {
- PropertyInfo pi;
- pi.name = "out";
- pi.type = Variant::ARRAY;
- return pi;
-}
-
-String VisualScriptComposeArray::get_caption() const {
- return RTR("Compose Array");
-}
-
-String VisualScriptComposeArray::get_text() const {
- return "";
-}
-
-class VisualScriptComposeArrayNode : public VisualScriptNodeInstance {
-public:
- int input_count = 0;
- virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- if (input_count > 0) {
- Array arr;
- for (int i = 0; i < input_count; i++) {
- arr.push_back((*p_inputs[i]));
- }
- Variant va = Variant(arr);
-
- *p_outputs[0] = va;
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptComposeArray::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptComposeArrayNode *instance = memnew(VisualScriptComposeArrayNode);
- instance->input_count = inputports.size();
- return instance;
-}
-
-VisualScriptComposeArray::VisualScriptComposeArray() {
- // initialize stuff here
- sequenced = false;
- flags = INPUT_EDITABLE;
-}
-
-//////////////////////////////////////////
-////////////////OPERATOR//////////////////
-//////////////////////////////////////////
-
-int VisualScriptOperator::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptOperator::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptOperator::get_input_value_port_count() const {
- return (op == Variant::OP_BIT_NEGATE || op == Variant::OP_NOT || op == Variant::OP_NEGATE || op == Variant::OP_POSITIVE) ? 1 : 2;
-}
-
-int VisualScriptOperator::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptOperator::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const {
- static const Variant::Type port_types[Variant::OP_MAX][2] = {
- { Variant::NIL, Variant::NIL }, //OP_EQUAL,
- { Variant::NIL, Variant::NIL }, //OP_NOT_EQUAL,
- { Variant::NIL, Variant::NIL }, //OP_LESS,
- { Variant::NIL, Variant::NIL }, //OP_LESS_EQUAL,
- { Variant::NIL, Variant::NIL }, //OP_GREATER,
- { Variant::NIL, Variant::NIL }, //OP_GREATER_EQUAL,
- //mathematic
- { Variant::NIL, Variant::NIL }, //OP_ADD,
- { Variant::NIL, Variant::NIL }, //OP_SUBTRACT,
- { Variant::NIL, Variant::NIL }, //OP_MULTIPLY,
- { Variant::NIL, Variant::NIL }, //OP_DIVIDE,
- { Variant::NIL, Variant::NIL }, //OP_NEGATE,
- { Variant::NIL, Variant::NIL }, //OP_POSITIVE,
- { Variant::INT, Variant::INT }, //OP_MODULE,
- //bitwise
- { Variant::INT, Variant::INT }, //OP_SHIFT_LEFT,
- { Variant::INT, Variant::INT }, //OP_SHIFT_RIGHT,
- { Variant::INT, Variant::INT }, //OP_BIT_AND,
- { Variant::INT, Variant::INT }, //OP_BIT_OR,
- { Variant::INT, Variant::INT }, //OP_BIT_XOR,
- { Variant::INT, Variant::INT }, //OP_BIT_NEGATE,
- //logic
- { Variant::BOOL, Variant::BOOL }, //OP_AND,
- { Variant::BOOL, Variant::BOOL }, //OP_OR,
- { Variant::BOOL, Variant::BOOL }, //OP_XOR,
- { Variant::BOOL, Variant::BOOL }, //OP_NOT,
- //containment
- { Variant::NIL, Variant::NIL } //OP_IN,
- };
-
- ERR_FAIL_INDEX_V(p_idx, 2, PropertyInfo());
-
- PropertyInfo pinfo;
- pinfo.name = p_idx == 0 ? "A" : "B";
- pinfo.type = port_types[op][p_idx];
- if (pinfo.type == Variant::NIL) {
- pinfo.type = typed;
- }
- return pinfo;
-}
-
-PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const {
- static const Variant::Type port_types[Variant::OP_MAX] = {
- //comparison
- Variant::BOOL, //OP_EQUAL,
- Variant::BOOL, //OP_NOT_EQUAL,
- Variant::BOOL, //OP_LESS,
- Variant::BOOL, //OP_LESS_EQUAL,
- Variant::BOOL, //OP_GREATER,
- Variant::BOOL, //OP_GREATER_EQUAL,
- //mathematic
- Variant::NIL, //OP_ADD,
- Variant::NIL, //OP_SUBTRACT,
- Variant::NIL, //OP_MULTIPLY,
- Variant::NIL, //OP_DIVIDE,
- Variant::NIL, //OP_NEGATE,
- Variant::NIL, //OP_POSITIVE,
- Variant::INT, //OP_MODULE,
- //bitwise
- Variant::INT, //OP_SHIFT_LEFT,
- Variant::INT, //OP_SHIFT_RIGHT,
- Variant::INT, //OP_BIT_AND,
- Variant::INT, //OP_BIT_OR,
- Variant::INT, //OP_BIT_XOR,
- Variant::INT, //OP_BIT_NEGATE,
- //logic
- Variant::BOOL, //OP_AND,
- Variant::BOOL, //OP_OR,
- Variant::BOOL, //OP_XOR,
- Variant::BOOL, //OP_NOT,
- //containment
- Variant::BOOL //OP_IN,
- };
-
- PropertyInfo pinfo;
- pinfo.name = "";
- pinfo.type = port_types[op];
- if (pinfo.type == Variant::NIL) {
- pinfo.type = typed;
- }
- return pinfo;
-}
-
-String VisualScriptOperator::get_caption() const {
- switch (op) {
- // comparison
- case Variant::OP_EQUAL:
- return U"A = B";
- case Variant::OP_NOT_EQUAL:
- return U"A \u2260 B";
- case Variant::OP_LESS:
- return U"A < B";
- case Variant::OP_LESS_EQUAL:
- return U"A \u2264 B";
- case Variant::OP_GREATER:
- return U"A > B";
- case Variant::OP_GREATER_EQUAL:
- return U"A \u2265 B";
-
- // mathematic
- case Variant::OP_ADD:
- return U"A + B";
- case Variant::OP_SUBTRACT:
- return U"A - B";
- case Variant::OP_MULTIPLY:
- return U"A \u00D7 B";
- case Variant::OP_DIVIDE:
- return U"A \u00F7 B";
- case Variant::OP_NEGATE:
- return U"\u00AC A";
- case Variant::OP_POSITIVE:
- return U"+ A";
- case Variant::OP_MODULE:
- return U"A mod B";
-
- // bitwise
- case Variant::OP_SHIFT_LEFT:
- return U"A << B";
- case Variant::OP_SHIFT_RIGHT:
- return U"A >> B";
- case Variant::OP_BIT_AND:
- return U"A & B";
- case Variant::OP_BIT_OR:
- return U"A | B";
- case Variant::OP_BIT_XOR:
- return U"A ^ B";
- case Variant::OP_BIT_NEGATE:
- return U"~A";
-
- // logic
- case Variant::OP_AND:
- return U"A and B";
- case Variant::OP_OR:
- return U"A or B";
- case Variant::OP_XOR:
- return U"A xor B";
- case Variant::OP_NOT:
- return U"not A";
- case Variant::OP_IN:
- return U"A in B";
-
- default: {
- ERR_FAIL_V_MSG(
- U"Unknown node",
- U"Unknown node type encountered, caption not available.");
- }
- }
-}
-
-String VisualScriptOperator::get_operator_name(Variant::Operator p_op) {
- switch (p_op) {
- // comparison
- case Variant::OP_EQUAL:
- return "Are Equal";
- case Variant::OP_NOT_EQUAL:
- return "Are Not Equal";
- case Variant::OP_LESS:
- return "Less Than";
- case Variant::OP_LESS_EQUAL:
- return "Less Than or Equal";
- case Variant::OP_GREATER:
- return "Greater Than";
- case Variant::OP_GREATER_EQUAL:
- return "Greater Than or Equal";
-
- // mathematic
- case Variant::OP_ADD:
- return "Add";
- case Variant::OP_SUBTRACT:
- return "Subtract";
- case Variant::OP_MULTIPLY:
- return "Multiply";
- case Variant::OP_DIVIDE:
- return "Divide";
- case Variant::OP_NEGATE:
- return "Negate";
- case Variant::OP_POSITIVE:
- return "Positive";
- case Variant::OP_MODULE:
- return "Remainder";
-
- // bitwise
- case Variant::OP_SHIFT_LEFT:
- return "Bit Shift Left";
- case Variant::OP_SHIFT_RIGHT:
- return "Bit Shift Right";
- case Variant::OP_BIT_AND:
- return "Bit And";
- case Variant::OP_BIT_OR:
- return "Bit Or";
- case Variant::OP_BIT_XOR:
- return "Bit Xor";
- case Variant::OP_BIT_NEGATE:
- return "Bit Negate";
-
- // logic
- case Variant::OP_AND:
- return "And";
- case Variant::OP_OR:
- return "Or";
- case Variant::OP_XOR:
- return "Xor";
- case Variant::OP_NOT:
- return "Not";
- case Variant::OP_IN:
- return "In";
-
- default: {
- ERR_FAIL_INDEX_V(p_op, Variant::OP_MAX, "");
- return "Unknown Operator";
- }
- }
-}
-
-void VisualScriptOperator::set_operator(Variant::Operator p_op) {
- if (op == p_op) {
- return;
- }
- op = p_op;
- ports_changed_notify();
-}
-
-Variant::Operator VisualScriptOperator::get_operator() const {
- return op;
-}
-
-void VisualScriptOperator::set_typed(Variant::Type p_op) {
- if (typed == p_op) {
- return;
- }
-
- typed = p_op;
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptOperator::get_typed() const {
- return typed;
-}
-
-void VisualScriptOperator::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualScriptOperator::set_operator);
- ClassDB::bind_method(D_METHOD("get_operator"), &VisualScriptOperator::get_operator);
-
- ClassDB::bind_method(D_METHOD("set_typed", "type"), &VisualScriptOperator::set_typed);
- ClassDB::bind_method(D_METHOD("get_typed"), &VisualScriptOperator::get_typed);
-
- String types;
- for (int i = 0; i < Variant::OP_MAX; i++) {
- if (i > 0) {
- types += ",";
- }
- types += get_operator_name(static_cast<Variant::Operator>(i));
- }
-
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, types), "set_operator", "get_operator");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt), "set_typed", "get_typed");
-}
-
-class VisualScriptNodeInstanceOperator : public VisualScriptNodeInstance {
-public:
- bool unary = false;
- Variant::Operator op;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- bool valid;
- if (unary) {
- Variant::evaluate(op, *p_inputs[0], Variant(), *p_outputs[0], valid);
- } else {
- Variant::evaluate(op, *p_inputs[0], *p_inputs[1], *p_outputs[0], valid);
- }
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- if (p_outputs[0]->get_type() == Variant::STRING) {
- r_error_str = *p_outputs[0];
- } else {
- if (unary) {
- r_error_str = String(Variant::get_operator_name(op)) + ": " + RTR("Invalid argument of type:") + " " + Variant::get_type_name(p_inputs[0]->get_type());
- } else {
- r_error_str = String(Variant::get_operator_name(op)) + ": " + RTR("Invalid arguments:") + " A: " + Variant::get_type_name(p_inputs[0]->get_type()) + ", B: " + Variant::get_type_name(p_inputs[1]->get_type());
- }
- }
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptOperator::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceOperator *instance = memnew(VisualScriptNodeInstanceOperator);
- instance->unary = get_input_value_port_count() == 1;
- instance->op = op;
- return instance;
-}
-
-VisualScriptOperator::VisualScriptOperator() {
- op = Variant::OP_ADD;
- typed = Variant::NIL;
-}
-
-template <Variant::Operator OP>
-static Ref<VisualScriptNode> create_op_node(const String &p_name) {
- Ref<VisualScriptOperator> node;
- node.instantiate();
- node->set_operator(OP);
- return node;
-}
-
-//////////////////////////////////////////
-////////////////OPERATOR//////////////////
-//////////////////////////////////////////
-
-int VisualScriptSelect::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptSelect::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptSelect::get_input_value_port_count() const {
- return 3;
-}
-
-int VisualScriptSelect::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptSelect::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptSelect::get_input_value_port_info(int p_idx) const {
- if (p_idx == 0) {
- return PropertyInfo(Variant::BOOL, "cond");
- } else if (p_idx == 1) {
- return PropertyInfo(typed, "a");
- } else {
- return PropertyInfo(typed, "b");
- }
-}
-
-PropertyInfo VisualScriptSelect::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(typed, "out");
-}
-
-String VisualScriptSelect::get_caption() const {
- return RTR("Select");
-}
-
-String VisualScriptSelect::get_text() const {
- return RTR("a if cond, else b");
-}
-
-void VisualScriptSelect::set_typed(Variant::Type p_op) {
- if (typed == p_op) {
- return;
- }
-
- typed = p_op;
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptSelect::get_typed() const {
- return typed;
-}
-
-void VisualScriptSelect::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_typed", "type"), &VisualScriptSelect::set_typed);
- ClassDB::bind_method(D_METHOD("get_typed"), &VisualScriptSelect::get_typed);
-
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt), "set_typed", "get_typed");
-}
-
-class VisualScriptNodeInstanceSelect : public VisualScriptNodeInstance {
-public:
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- bool cond = *p_inputs[0];
- if (cond) {
- *p_outputs[0] = *p_inputs[1];
- } else {
- *p_outputs[0] = *p_inputs[2];
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptSelect::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSelect *instance = memnew(VisualScriptNodeInstanceSelect);
- return instance;
-}
-
-VisualScriptSelect::VisualScriptSelect() {
- typed = Variant::NIL;
-}
-
-//////////////////////////////////////////
-////////////////VARIABLE GET//////////////////
-//////////////////////////////////////////
-
-int VisualScriptVariableGet::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptVariableGet::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptVariableGet::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptVariableGet::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptVariableGet::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptVariableGet::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptVariableGet::get_output_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = "value";
- if (get_visual_script().is_valid() && get_visual_script()->has_variable(variable)) {
- PropertyInfo vinfo = get_visual_script()->get_variable_info(variable);
- pinfo.type = vinfo.type;
- pinfo.hint = vinfo.hint;
- pinfo.hint_string = vinfo.hint_string;
- }
- return pinfo;
-}
-
-String VisualScriptVariableGet::get_caption() const {
- return vformat(RTR("Get %s"), variable);
-}
-
-void VisualScriptVariableGet::set_variable(StringName p_variable) {
- if (variable == p_variable) {
- return;
- }
- variable = p_variable;
- ports_changed_notify();
-}
-
-StringName VisualScriptVariableGet::get_variable() const {
- return variable;
-}
-
-void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const {
- if (property.name == "var_name" && get_visual_script().is_valid()) {
- Ref<VisualScript> vs = get_visual_script();
- List<StringName> vars;
- vs->get_variable_list(&vars);
-
- String vhint;
- for (const StringName &E : vars) {
- if (!vhint.is_empty()) {
- vhint += ",";
- }
-
- vhint += E.operator String();
- }
-
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = vhint;
- }
-}
-
-void VisualScriptVariableGet::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_variable", "name"), &VisualScriptVariableGet::set_variable);
- ClassDB::bind_method(D_METHOD("get_variable"), &VisualScriptVariableGet::get_variable);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "var_name"), "set_variable", "get_variable");
-}
-
-class VisualScriptNodeInstanceVariableGet : public VisualScriptNodeInstance {
-public:
- VisualScriptVariableGet *node = nullptr;
- VisualScriptInstance *instance = nullptr;
- StringName variable;
-
- 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) override {
- if (!instance->get_variable(variable, p_outputs[0])) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("VariableGet not found in script:") + " '" + String(variable) + "'";
- return 0;
- }
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptVariableGet::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceVariableGet *instance = memnew(VisualScriptNodeInstanceVariableGet);
- instance->node = this;
- instance->instance = p_instance;
- instance->variable = variable;
- return instance;
-}
-
-VisualScriptVariableGet::VisualScriptVariableGet() {
-}
-
-//////////////////////////////////////////
-////////////////VARIABLE SET//////////////////
-//////////////////////////////////////////
-
-int VisualScriptVariableSet::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptVariableSet::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptVariableSet::get_input_value_port_count() const {
- return 1;
-}
-
-int VisualScriptVariableSet::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptVariableSet::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptVariableSet::get_input_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = "set";
- if (get_visual_script().is_valid() && get_visual_script()->has_variable(variable)) {
- PropertyInfo vinfo = get_visual_script()->get_variable_info(variable);
- pinfo.type = vinfo.type;
- pinfo.hint = vinfo.hint;
- pinfo.hint_string = vinfo.hint_string;
- }
- return pinfo;
-}
-
-PropertyInfo VisualScriptVariableSet::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptVariableSet::get_caption() const {
- return vformat(RTR("Set %s"), variable);
-}
-
-void VisualScriptVariableSet::set_variable(StringName p_variable) {
- if (variable == p_variable) {
- return;
- }
- variable = p_variable;
- ports_changed_notify();
-}
-
-StringName VisualScriptVariableSet::get_variable() const {
- return variable;
-}
-
-void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const {
- if (property.name == "var_name" && get_visual_script().is_valid()) {
- Ref<VisualScript> vs = get_visual_script();
- List<StringName> vars;
- vs->get_variable_list(&vars);
-
- String vhint;
- for (const StringName &E : vars) {
- if (!vhint.is_empty()) {
- vhint += ",";
- }
-
- vhint += E.operator String();
- }
-
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = vhint;
- }
-}
-
-void VisualScriptVariableSet::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_variable", "name"), &VisualScriptVariableSet::set_variable);
- ClassDB::bind_method(D_METHOD("get_variable"), &VisualScriptVariableSet::get_variable);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "var_name"), "set_variable", "get_variable");
-}
-
-class VisualScriptNodeInstanceVariableSet : public VisualScriptNodeInstance {
-public:
- VisualScriptVariableSet *node = nullptr;
- VisualScriptInstance *instance = nullptr;
- StringName variable;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- if (!instance->set_variable(variable, *p_inputs[0])) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = RTR("VariableSet not found in script:") + " '" + String(variable) + "'";
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptVariableSet::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceVariableSet *instance = memnew(VisualScriptNodeInstanceVariableSet);
- instance->node = this;
- instance->instance = p_instance;
- instance->variable = variable;
- return instance;
-}
-
-VisualScriptVariableSet::VisualScriptVariableSet() {
-}
-
-//////////////////////////////////////////
-////////////////CONSTANT//////////////////
-//////////////////////////////////////////
-
-int VisualScriptConstant::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptConstant::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptConstant::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptConstant::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptConstant::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptConstant::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptConstant::get_output_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.name = String(value);
- pinfo.type = type;
- return pinfo;
-}
-
-String VisualScriptConstant::get_caption() const {
- return RTR("Constant");
-}
-
-void VisualScriptConstant::set_constant_type(Variant::Type p_type) {
- if (type == p_type) {
- return;
- }
-
- type = p_type;
- Callable::CallError ce;
- Variant::construct(type, value, nullptr, 0, ce);
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-Variant::Type VisualScriptConstant::get_constant_type() const {
- return type;
-}
-
-void VisualScriptConstant::set_constant_value(Variant p_value) {
- if (value == p_value) {
- return;
- }
-
- value = p_value;
- ports_changed_notify();
-}
-
-Variant VisualScriptConstant::get_constant_value() const {
- return value;
-}
-
-void VisualScriptConstant::_validate_property(PropertyInfo &property) const {
- if (property.name == "value") {
- property.type = type;
- if (type == Variant::NIL) {
- property.usage = PROPERTY_USAGE_NONE; //do not save if nil
- }
- }
-}
-
-void VisualScriptConstant::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_constant_type", "type"), &VisualScriptConstant::set_constant_type);
- ClassDB::bind_method(D_METHOD("get_constant_type"), &VisualScriptConstant::get_constant_type);
-
- ClassDB::bind_method(D_METHOD("set_constant_value", "value"), &VisualScriptConstant::set_constant_value);
- ClassDB::bind_method(D_METHOD("get_constant_value"), &VisualScriptConstant::get_constant_value);
-
- String argt = "Null";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt), "set_constant_type", "get_constant_type");
- ADD_PROPERTY(PropertyInfo(Variant::NIL, "value", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NIL_IS_VARIANT | PROPERTY_USAGE_DEFAULT), "set_constant_value", "get_constant_value");
-}
-
-class VisualScriptNodeInstanceConstant : public VisualScriptNodeInstance {
-public:
- Variant constant;
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- *p_outputs[0] = constant;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptConstant::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceConstant *instance = memnew(VisualScriptNodeInstanceConstant);
- instance->constant = value;
- return instance;
-}
-
-VisualScriptConstant::VisualScriptConstant() {
- type = Variant::NIL;
-}
-
-//////////////////////////////////////////
-////////////////PRELOAD//////////////////
-//////////////////////////////////////////
-
-int VisualScriptPreload::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptPreload::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptPreload::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptPreload::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptPreload::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptPreload::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptPreload::get_output_value_port_info(int p_idx) const {
- PropertyInfo pinfo;
- pinfo.type = Variant::OBJECT;
- if (preload.is_valid()) {
- pinfo.hint = PROPERTY_HINT_RESOURCE_TYPE;
- pinfo.hint_string = preload->get_class();
- if (preload->get_path().is_resource_file()) {
- pinfo.name = preload->get_path();
- } else if (!preload->get_name().is_empty()) {
- pinfo.name = preload->get_name();
- } else {
- pinfo.name = preload->get_class();
- }
- } else {
- pinfo.name = "<empty>";
- }
-
- return pinfo;
-}
-
-String VisualScriptPreload::get_caption() const {
- return RTR("Preload");
-}
-
-void VisualScriptPreload::set_preload(const Ref<Resource> &p_preload) {
- if (preload == p_preload) {
- return;
- }
-
- preload = p_preload;
- ports_changed_notify();
-}
-
-Ref<Resource> VisualScriptPreload::get_preload() const {
- return preload;
-}
-
-void VisualScriptPreload::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_preload", "resource"), &VisualScriptPreload::set_preload);
- ClassDB::bind_method(D_METHOD("get_preload"), &VisualScriptPreload::get_preload);
-
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "resource", PROPERTY_HINT_RESOURCE_TYPE, "Resource"), "set_preload", "get_preload");
-}
-
-class VisualScriptNodeInstancePreload : public VisualScriptNodeInstance {
-public:
- Ref<Resource> preload;
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- *p_outputs[0] = preload;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptPreload::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstancePreload *instance = memnew(VisualScriptNodeInstancePreload);
- instance->preload = preload;
- return instance;
-}
-
-VisualScriptPreload::VisualScriptPreload() {
-}
-
-//////////////////////////////////////////
-////////////////INDEX////////////////////
-//////////////////////////////////////////
-
-int VisualScriptIndexGet::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptIndexGet::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptIndexGet::get_input_value_port_count() const {
- return 2;
-}
-
-int VisualScriptIndexGet::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptIndexGet::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptIndexGet::get_input_value_port_info(int p_idx) const {
- if (p_idx == 0) {
- return PropertyInfo(Variant::NIL, "base");
- } else {
- return PropertyInfo(Variant::NIL, "index");
- }
-}
-
-PropertyInfo VisualScriptIndexGet::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptIndexGet::get_caption() const {
- return RTR("Get Index");
-}
-
-class VisualScriptNodeInstanceIndexGet : public VisualScriptNodeInstance {
-public:
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- bool valid;
- *p_outputs[0] = p_inputs[0]->get(*p_inputs[1], &valid);
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Invalid get: " + p_inputs[0]->get_construct_string();
- }
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptIndexGet::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceIndexGet *instance = memnew(VisualScriptNodeInstanceIndexGet);
- return instance;
-}
-
-VisualScriptIndexGet::VisualScriptIndexGet() {
-}
-
-//////////////////////////////////////////
-////////////////INDEXSET//////////////////
-//////////////////////////////////////////
-
-int VisualScriptIndexSet::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptIndexSet::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptIndexSet::get_input_value_port_count() const {
- return 3;
-}
-
-int VisualScriptIndexSet::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptIndexSet::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptIndexSet::get_input_value_port_info(int p_idx) const {
- if (p_idx == 0) {
- return PropertyInfo(Variant::NIL, "base");
- } else if (p_idx == 1) {
- return PropertyInfo(Variant::NIL, "index");
-
- } else {
- return PropertyInfo(Variant::NIL, "value");
- }
-}
-
-PropertyInfo VisualScriptIndexSet::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptIndexSet::get_caption() const {
- return RTR("Set Index");
-}
-
-class VisualScriptNodeInstanceIndexSet : public VisualScriptNodeInstance {
-public:
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- bool valid;
- ((Variant *)p_inputs[0])->set(*p_inputs[1], *p_inputs[2], &valid);
-
- if (!valid) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Invalid set: " + p_inputs[1]->get_construct_string();
- }
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptIndexSet::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceIndexSet *instance = memnew(VisualScriptNodeInstanceIndexSet);
- return instance;
-}
-
-VisualScriptIndexSet::VisualScriptIndexSet() {
-}
-
-//////////////////////////////////////////
-////////////////GLOBALCONSTANT///////////
-//////////////////////////////////////////
-
-int VisualScriptGlobalConstant::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptGlobalConstant::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptGlobalConstant::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptGlobalConstant::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptGlobalConstant::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptGlobalConstant::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptGlobalConstant::get_output_value_port_info(int p_idx) const {
- String name = CoreConstants::get_global_constant_name(index);
- return PropertyInfo(Variant::INT, name);
-}
-
-String VisualScriptGlobalConstant::get_caption() const {
- return RTR("Global Constant");
-}
-
-void VisualScriptGlobalConstant::set_global_constant(int p_which) {
- index = p_which;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-int VisualScriptGlobalConstant::get_global_constant() {
- return index;
-}
-
-class VisualScriptNodeInstanceGlobalConstant : public VisualScriptNodeInstance {
-public:
- int index = 0;
-
- 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) override {
- *p_outputs[0] = CoreConstants::get_global_constant_value(index);
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptGlobalConstant::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceGlobalConstant *instance = memnew(VisualScriptNodeInstanceGlobalConstant);
- instance->index = index;
- return instance;
-}
-
-void VisualScriptGlobalConstant::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_global_constant", "index"), &VisualScriptGlobalConstant::set_global_constant);
- ClassDB::bind_method(D_METHOD("get_global_constant"), &VisualScriptGlobalConstant::get_global_constant);
-
- String cc;
-
- for (int i = 0; i < CoreConstants::get_global_constant_count(); i++) {
- if (i > 0) {
- cc += ",";
- }
- cc += CoreConstants::get_global_constant_name(i);
- }
- ADD_PROPERTY(PropertyInfo(Variant::INT, "constant", PROPERTY_HINT_ENUM, cc), "set_global_constant", "get_global_constant");
-}
-
-VisualScriptGlobalConstant::VisualScriptGlobalConstant() {
- index = 0;
-}
-
-//////////////////////////////////////////
-////////////////CLASSCONSTANT///////////
-//////////////////////////////////////////
-
-int VisualScriptClassConstant::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptClassConstant::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptClassConstant::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptClassConstant::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptClassConstant::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptClassConstant::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptClassConstant::get_output_value_port_info(int p_idx) const {
- if (name == "") {
- return PropertyInfo(Variant::INT, String(base_type));
- } else {
- return PropertyInfo(Variant::INT, String(base_type) + "." + String(name));
- }
-}
-
-String VisualScriptClassConstant::get_caption() const {
- return RTR("Class Constant");
-}
-
-void VisualScriptClassConstant::set_class_constant(const StringName &p_which) {
- name = p_which;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptClassConstant::get_class_constant() {
- return name;
-}
-
-void VisualScriptClassConstant::set_base_type(const StringName &p_which) {
- base_type = p_which;
- List<String> constants;
- ClassDB::get_integer_constant_list(base_type, &constants, true);
- if (constants.size() > 0) {
- bool found_name = false;
- for (const String &E : constants) {
- if (E == name) {
- found_name = true;
- break;
- }
- }
- if (!found_name) {
- name = constants[0];
- }
- } else {
- name = "";
- }
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptClassConstant::get_base_type() {
- return base_type;
-}
-
-class VisualScriptNodeInstanceClassConstant : public VisualScriptNodeInstance {
-public:
- int value = 0;
- bool valid = false;
-
- 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) override {
- if (!valid) {
- r_error_str = "Invalid constant name, pick a valid class constant.";
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- }
-
- *p_outputs[0] = value;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptClassConstant::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceClassConstant *instance = memnew(VisualScriptNodeInstanceClassConstant);
- instance->value = ClassDB::get_integer_constant(base_type, name, &instance->valid);
- return instance;
-}
-
-void VisualScriptClassConstant::_validate_property(PropertyInfo &property) const {
- if (property.name == "constant") {
- List<String> constants;
- ClassDB::get_integer_constant_list(base_type, &constants, true);
-
- property.hint_string = "";
- for (const String &E : constants) {
- if (!property.hint_string.is_empty()) {
- property.hint_string += ",";
- }
- property.hint_string += E;
- }
- }
-}
-
-void VisualScriptClassConstant::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_class_constant", "name"), &VisualScriptClassConstant::set_class_constant);
- ClassDB::bind_method(D_METHOD("get_class_constant"), &VisualScriptClassConstant::get_class_constant);
-
- ClassDB::bind_method(D_METHOD("set_base_type", "name"), &VisualScriptClassConstant::set_base_type);
- ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptClassConstant::get_base_type);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "constant", PROPERTY_HINT_ENUM, ""), "set_class_constant", "get_class_constant");
-}
-
-VisualScriptClassConstant::VisualScriptClassConstant() {
- base_type = "Object";
-}
-
-//////////////////////////////////////////
-////////////////BASICTYPECONSTANT///////////
-//////////////////////////////////////////
-
-int VisualScriptBasicTypeConstant::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptBasicTypeConstant::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptBasicTypeConstant::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptBasicTypeConstant::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptBasicTypeConstant::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptBasicTypeConstant::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptBasicTypeConstant::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(type, "value");
-}
-
-String VisualScriptBasicTypeConstant::get_caption() const {
- return RTR("Basic Constant");
-}
-
-String VisualScriptBasicTypeConstant::get_text() const {
- if (name == "") {
- return Variant::get_type_name(type);
- } else {
- return Variant::get_type_name(type) + "." + String(name);
- }
-}
-
-void VisualScriptBasicTypeConstant::set_basic_type_constant(const StringName &p_which) {
- name = p_which;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptBasicTypeConstant::get_basic_type_constant() const {
- return name;
-}
-
-void VisualScriptBasicTypeConstant::set_basic_type(Variant::Type p_which) {
- type = p_which;
-
- List<StringName> constants;
- Variant::get_constants_for_type(type, &constants);
- if (constants.size() > 0) {
- bool found_name = false;
- for (const StringName &E : constants) {
- if (E == name) {
- found_name = true;
- break;
- }
- }
- if (!found_name) {
- name = constants[0];
- }
- } else {
- name = "";
- }
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptBasicTypeConstant::get_basic_type() const {
- return type;
-}
-
-class VisualScriptNodeInstanceBasicTypeConstant : public VisualScriptNodeInstance {
-public:
- Variant value;
- bool valid = false;
-
- 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) override {
- if (!valid) {
- r_error_str = "Invalid constant name, pick a valid basic type constant.";
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- }
-
- *p_outputs[0] = value;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptBasicTypeConstant::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceBasicTypeConstant *instance = memnew(VisualScriptNodeInstanceBasicTypeConstant);
- instance->value = Variant::get_constant_value(type, name, &instance->valid);
- return instance;
-}
-
-void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo &property) const {
- if (property.name == "constant") {
- List<StringName> constants;
- Variant::get_constants_for_type(type, &constants);
-
- if (constants.size() == 0) {
- property.usage = PROPERTY_USAGE_NONE;
- return;
- }
- property.hint_string = "";
- for (const StringName &E : constants) {
- if (!property.hint_string.is_empty()) {
- property.hint_string += ",";
- }
- property.hint_string += String(E);
- }
- }
-}
-
-void VisualScriptBasicTypeConstant::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_basic_type", "name"), &VisualScriptBasicTypeConstant::set_basic_type);
- ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptBasicTypeConstant::get_basic_type);
-
- ClassDB::bind_method(D_METHOD("set_basic_type_constant", "name"), &VisualScriptBasicTypeConstant::set_basic_type_constant);
- ClassDB::bind_method(D_METHOD("get_basic_type_constant"), &VisualScriptBasicTypeConstant::get_basic_type_constant);
-
- String argt = "Null";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, argt), "set_basic_type", "get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "constant", PROPERTY_HINT_ENUM, ""), "set_basic_type_constant", "get_basic_type_constant");
-}
-
-VisualScriptBasicTypeConstant::VisualScriptBasicTypeConstant() {
- type = Variant::NIL;
-}
-
-//////////////////////////////////////////
-////////////////MATHCONSTANT///////////
-//////////////////////////////////////////
-
-const char *VisualScriptMathConstant::const_name[MATH_CONSTANT_MAX] = {
- "One",
- "PI",
- "PI/2",
- "TAU",
- "E",
- "Sqrt2",
- "INF",
- "NAN"
-};
-
-double VisualScriptMathConstant::const_value[MATH_CONSTANT_MAX] = {
- 1.0,
- Math_PI,
- Math_PI * 0.5,
- Math_TAU,
- 2.71828182845904523536,
- Math::sqrt(2.0),
- INFINITY,
- NAN
-};
-
-int VisualScriptMathConstant::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptMathConstant::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptMathConstant::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptMathConstant::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptMathConstant::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptMathConstant::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptMathConstant::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::FLOAT, const_name[constant]);
-}
-
-String VisualScriptMathConstant::get_caption() const {
- return RTR("Math Constant");
-}
-
-void VisualScriptMathConstant::set_math_constant(MathConstant p_which) {
- constant = p_which;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-VisualScriptMathConstant::MathConstant VisualScriptMathConstant::get_math_constant() {
- return constant;
-}
-
-class VisualScriptNodeInstanceMathConstant : public VisualScriptNodeInstance {
-public:
- float value = 0.0f;
-
- 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) override {
- *p_outputs[0] = value;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptMathConstant::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceMathConstant *instance = memnew(VisualScriptNodeInstanceMathConstant);
- instance->value = const_value[constant];
- return instance;
-}
-
-void VisualScriptMathConstant::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_math_constant", "which"), &VisualScriptMathConstant::set_math_constant);
- ClassDB::bind_method(D_METHOD("get_math_constant"), &VisualScriptMathConstant::get_math_constant);
-
- String cc;
-
- for (int i = 0; i < MATH_CONSTANT_MAX; i++) {
- if (i > 0) {
- cc += ",";
- }
- cc += const_name[i];
- }
- ADD_PROPERTY(PropertyInfo(Variant::INT, "constant", PROPERTY_HINT_ENUM, cc), "set_math_constant", "get_math_constant");
-
- BIND_ENUM_CONSTANT(MATH_CONSTANT_ONE);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_PI);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_HALF_PI);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_TAU);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_E);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_SQRT2);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_INF);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_NAN);
- BIND_ENUM_CONSTANT(MATH_CONSTANT_MAX);
-}
-
-VisualScriptMathConstant::VisualScriptMathConstant() {
- constant = MATH_CONSTANT_ONE;
-}
-
-//////////////////////////////////////////
-////////////////ENGINESINGLETON///////////
-//////////////////////////////////////////
-
-int VisualScriptEngineSingleton::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptEngineSingleton::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptEngineSingleton::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptEngineSingleton::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptEngineSingleton::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptEngineSingleton::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptEngineSingleton::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT, singleton);
-}
-
-String VisualScriptEngineSingleton::get_caption() const {
- return RTR("Get Engine Singleton");
-}
-
-void VisualScriptEngineSingleton::set_singleton(const String &p_string) {
- singleton = p_string;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-String VisualScriptEngineSingleton::get_singleton() {
- return singleton;
-}
-
-class VisualScriptNodeInstanceEngineSingleton : public VisualScriptNodeInstance {
-public:
- Object *singleton = nullptr;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- *p_outputs[0] = singleton;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptEngineSingleton::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceEngineSingleton *instance = memnew(VisualScriptNodeInstanceEngineSingleton);
- instance->singleton = Engine::get_singleton()->get_singleton_object(singleton);
- return instance;
-}
-
-VisualScriptEngineSingleton::TypeGuess VisualScriptEngineSingleton::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
- TypeGuess tg;
- tg.type = Variant::OBJECT;
- if (obj) {
- tg.gdclass = obj->get_class();
- tg.script = obj->get_script();
- }
-
- return tg;
-}
-
-void VisualScriptEngineSingleton::_validate_property(PropertyInfo &property) const {
- String cc;
-
- List<Engine::Singleton> singletons;
-
- Engine::get_singleton()->get_singletons(&singletons);
-
- for (const Engine::Singleton &E : singletons) {
- if (E.name == "VS" || E.name == "PS" || E.name == "PS2D" || E.name == "AS" || E.name == "TS" || E.name == "SS" || E.name == "SS2D") {
- continue; //skip these, too simple named
- }
-
- if (!cc.is_empty()) {
- cc += ",";
- }
- cc += E.name;
- }
-
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = cc;
-}
-
-void VisualScriptEngineSingleton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_singleton", "name"), &VisualScriptEngineSingleton::set_singleton);
- ClassDB::bind_method(D_METHOD("get_singleton"), &VisualScriptEngineSingleton::get_singleton);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "constant"), "set_singleton", "get_singleton");
-}
-
-VisualScriptEngineSingleton::VisualScriptEngineSingleton() {
- singleton = String();
-}
-
-//////////////////////////////////////////
-////////////////GETNODE///////////
-//////////////////////////////////////////
-
-int VisualScriptSceneNode::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptSceneNode::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptSceneNode::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptSceneNode::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptSceneNode::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptSceneNode::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptSceneNode::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT, path.simplified());
-}
-
-String VisualScriptSceneNode::get_caption() const {
- return RTR("Get Scene Node");
-}
-
-void VisualScriptSceneNode::set_node_path(const NodePath &p_path) {
- path = p_path;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-NodePath VisualScriptSceneNode::get_node_path() {
- return path;
-}
-
-class VisualScriptNodeInstanceSceneNode : public VisualScriptNodeInstance {
-public:
- VisualScriptSceneNode *node = nullptr;
- VisualScriptInstance *instance = nullptr;
- NodePath path;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
- if (!node) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Base object is not a Node!";
- return 0;
- }
-
- Node *another = node->get_node(path);
- if (!another) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Path does not lead Node!";
- return 0;
- }
-
- *p_outputs[0] = another;
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptSceneNode::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSceneNode *instance = memnew(VisualScriptNodeInstanceSceneNode);
- instance->node = this;
- instance->instance = p_instance;
- instance->path = path;
- return instance;
-}
-
-#ifdef TOOLS_ENABLED
-
-static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
- return nullptr;
- }
-
- Ref<Script> scr = p_current_node->get_script();
-
- if (scr.is_valid() && scr == script) {
- return p_current_node;
- }
-
- for (int i = 0; i < p_current_node->get_child_count(); i++) {
- Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n) {
- return n;
- }
- }
-
- return nullptr;
-}
-
-#endif
-
-VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- VisualScriptSceneNode::TypeGuess tg;
- tg.type = Variant::OBJECT;
- tg.gdclass = SNAME("Node");
-
-#ifdef TOOLS_ENABLED
- Ref<Script> script = get_visual_script();
- if (!script.is_valid()) {
- return tg;
- }
-
- MainLoop *main_loop = OS::get_singleton()->get_main_loop();
- SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
-
- if (!scene_tree) {
- return tg;
- }
-
- Node *edited_scene = scene_tree->get_edited_scene_root();
-
- if (!edited_scene) {
- return tg;
- }
-
- Node *script_node = _find_script_node(edited_scene, edited_scene, script);
-
- if (!script_node) {
- return tg;
- }
-
- Node *another = script_node->get_node(path);
-
- if (another) {
- tg.gdclass = another->get_class();
- tg.script = another->get_script();
- }
-#endif
- return tg;
-}
-
-void VisualScriptSceneNode::_validate_property(PropertyInfo &property) const {
-#ifdef TOOLS_ENABLED
- if (property.name == "node_path") {
- Ref<Script> script = get_visual_script();
- if (!script.is_valid()) {
- return;
- }
-
- MainLoop *main_loop = OS::get_singleton()->get_main_loop();
- SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
-
- if (!scene_tree) {
- return;
- }
-
- Node *edited_scene = scene_tree->get_edited_scene_root();
-
- if (!edited_scene) {
- return;
- }
-
- Node *script_node = _find_script_node(edited_scene, edited_scene, script);
-
- if (!script_node) {
- return;
- }
-
- property.hint_string = script_node->get_path();
- }
-#endif
-}
-
-void VisualScriptSceneNode::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_node_path", "path"), &VisualScriptSceneNode::set_node_path);
- ClassDB::bind_method(D_METHOD("get_node_path"), &VisualScriptSceneNode::get_node_path);
-
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_node_path", "get_node_path");
-}
-
-VisualScriptSceneNode::VisualScriptSceneNode() {
- path = String(".");
-}
-
-//////////////////////////////////////////
-////////////////SceneTree///////////
-//////////////////////////////////////////
-
-int VisualScriptSceneTree::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptSceneTree::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptSceneTree::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptSceneTree::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptSceneTree::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptSceneTree::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptSceneTree::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT, "Scene Tree", PROPERTY_HINT_TYPE_STRING, "SceneTree");
-}
-
-String VisualScriptSceneTree::get_caption() const {
- return RTR("Get Scene Tree");
-}
-
-class VisualScriptNodeInstanceSceneTree : public VisualScriptNodeInstance {
-public:
- VisualScriptSceneTree *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
- if (!node) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Base object is not a Node!";
- return 0;
- }
-
- SceneTree *tree = node->get_tree();
- if (!tree) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Attempt to get SceneTree while node is not in the active tree.";
- return 0;
- }
-
- *p_outputs[0] = tree;
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptSceneTree::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSceneTree *instance = memnew(VisualScriptNodeInstanceSceneTree);
- instance->node = this;
- instance->instance = p_instance;
- return instance;
-}
-
-VisualScriptSceneTree::TypeGuess VisualScriptSceneTree::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- TypeGuess tg;
- tg.type = Variant::OBJECT;
- tg.gdclass = SNAME("SceneTree");
- return tg;
-}
-
-void VisualScriptSceneTree::_validate_property(PropertyInfo &property) const {
-}
-
-void VisualScriptSceneTree::_bind_methods() {
-}
-
-VisualScriptSceneTree::VisualScriptSceneTree() {
-}
-
-//////////////////////////////////////////
-////////////////RESPATH///////////
-//////////////////////////////////////////
-
-int VisualScriptResourcePath::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptResourcePath::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptResourcePath::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptResourcePath::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptResourcePath::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptResourcePath::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptResourcePath::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::STRING, path);
-}
-
-String VisualScriptResourcePath::get_caption() const {
- return RTR("Resource Path");
-}
-
-void VisualScriptResourcePath::set_resource_path(const String &p_path) {
- path = p_path;
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-String VisualScriptResourcePath::get_resource_path() {
- return path;
-}
-
-class VisualScriptNodeInstanceResourcePath : public VisualScriptNodeInstance {
-public:
- String path;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- *p_outputs[0] = path;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptResourcePath::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceResourcePath *instance = memnew(VisualScriptNodeInstanceResourcePath);
- instance->path = path;
- return instance;
-}
-
-void VisualScriptResourcePath::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_resource_path", "path"), &VisualScriptResourcePath::set_resource_path);
- ClassDB::bind_method(D_METHOD("get_resource_path"), &VisualScriptResourcePath::get_resource_path);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "path", PROPERTY_HINT_FILE), "set_resource_path", "get_resource_path");
-}
-
-VisualScriptResourcePath::VisualScriptResourcePath() {
- path = "";
-}
-
-//////////////////////////////////////////
-////////////////SELF///////////
-//////////////////////////////////////////
-
-int VisualScriptSelf::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptSelf::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptSelf::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptSelf::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptSelf::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptSelf::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const {
- StringName type_name;
- if (get_visual_script().is_valid()) {
- type_name = get_visual_script()->get_instance_base_type();
- } else {
- type_name = SNAME("instance");
- }
-
- return PropertyInfo(Variant::OBJECT, type_name);
-}
-
-String VisualScriptSelf::get_caption() const {
- return RTR("Get Self");
-}
-
-class VisualScriptNodeInstanceSelf : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- *p_outputs[0] = instance->get_owner_ptr();
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptSelf::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSelf *instance = memnew(VisualScriptNodeInstanceSelf);
- instance->instance = p_instance;
- return instance;
-}
-
-VisualScriptSelf::TypeGuess VisualScriptSelf::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- VisualScriptSceneNode::TypeGuess tg;
- tg.type = Variant::OBJECT;
- tg.gdclass = SNAME("Object");
-
- Ref<Script> script = get_visual_script();
- if (!script.is_valid()) {
- return tg;
- }
-
- tg.gdclass = script->get_instance_base_type();
- tg.script = script;
-
- return tg;
-}
-
-void VisualScriptSelf::_bind_methods() {
-}
-
-VisualScriptSelf::VisualScriptSelf() {
-}
-
-//////////////////////////////////////////
-////////////////CUSTOM (SCRIPTED)///////////
-//////////////////////////////////////////
-
-int VisualScriptCustomNode::get_output_sequence_port_count() const {
- int ret;
- if (GDVIRTUAL_CALL(_get_output_sequence_port_count, ret)) {
- return ret;
- }
- return 0;
-}
-
-bool VisualScriptCustomNode::has_input_sequence_port() const {
- bool ret;
- if (GDVIRTUAL_CALL(_has_input_sequence_port, ret)) {
- return ret;
- }
- return false;
-}
-
-int VisualScriptCustomNode::get_input_value_port_count() const {
- int ret;
- if (GDVIRTUAL_CALL(_get_input_value_port_count, ret)) {
- return ret;
- }
- return 0;
-}
-
-int VisualScriptCustomNode::get_output_value_port_count() const {
- int ret;
- if (GDVIRTUAL_CALL(_get_output_value_port_count, ret)) {
- return ret;
- }
- return 0;
-}
-
-String VisualScriptCustomNode::get_output_sequence_port_text(int p_port) const {
- String ret;
- if (GDVIRTUAL_CALL(_get_output_sequence_port_text, p_port, ret)) {
- return ret;
- }
-
- return String();
-}
-
-PropertyInfo VisualScriptCustomNode::get_input_value_port_info(int p_idx) const {
- PropertyInfo info;
- {
- int type;
- if (GDVIRTUAL_CALL(_get_input_value_port_type, p_idx, type)) {
- info.type = Variant::Type(type);
- }
- }
- {
- String name;
- if (GDVIRTUAL_CALL(_get_input_value_port_name, p_idx, name)) {
- info.name = name;
- }
- }
- {
- int hint;
- if (GDVIRTUAL_CALL(_get_input_value_port_hint, p_idx, hint)) {
- info.hint = PropertyHint(hint);
- }
- }
-
- {
- String hint_string;
- if (GDVIRTUAL_CALL(_get_input_value_port_hint_string, p_idx, hint_string)) {
- info.hint_string = hint_string;
- }
- }
-
- return info;
-}
-
-PropertyInfo VisualScriptCustomNode::get_output_value_port_info(int p_idx) const {
- PropertyInfo info;
- {
- int type;
- if (GDVIRTUAL_CALL(_get_output_value_port_type, p_idx, type)) {
- info.type = Variant::Type(type);
- }
- }
- {
- String name;
- if (GDVIRTUAL_CALL(_get_output_value_port_name, p_idx, name)) {
- info.name = name;
- }
- }
- {
- int hint;
- if (GDVIRTUAL_CALL(_get_output_value_port_hint, p_idx, hint)) {
- info.hint = PropertyHint(hint);
- }
- }
-
- {
- String hint_string;
- if (GDVIRTUAL_CALL(_get_output_value_port_hint_string, p_idx, hint_string)) {
- info.hint_string = hint_string;
- }
- }
- return info;
-}
-
-VisualScriptCustomNode::TypeGuess VisualScriptCustomNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- TypeGuess tg;
- PropertyInfo pi = VisualScriptCustomNode::get_output_value_port_info(p_output);
- tg.type = pi.type;
- if (pi.type == Variant::OBJECT) {
- if (pi.hint == PROPERTY_HINT_RESOURCE_TYPE) {
- if (pi.hint_string.is_resource_file()) {
- tg.script = ResourceLoader::load(pi.hint_string);
- } else if (ClassDB::class_exists(pi.hint_string)) {
- tg.gdclass = pi.hint_string;
- }
- }
- }
- return tg;
-}
-
-String VisualScriptCustomNode::get_caption() const {
- String ret;
- if (GDVIRTUAL_CALL(_get_caption, ret)) {
- return ret;
- }
- return RTR("CustomNode");
-}
-
-String VisualScriptCustomNode::get_text() const {
- String ret;
- if (GDVIRTUAL_CALL(_get_text, ret)) {
- return ret;
- }
- return "";
-}
-
-String VisualScriptCustomNode::get_category() const {
- String ret;
- if (GDVIRTUAL_CALL(_get_category, ret)) {
- return ret;
- }
- return "Custom";
-}
-
-class VisualScriptNodeInstanceCustomNode : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- VisualScriptCustomNode *node = nullptr;
- int in_count = 0;
- int out_count = 0;
- int work_mem_size = 0;
-
- virtual int get_working_memory_size() const override { return work_mem_size; }
- 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) override {
- if (GDVIRTUAL_IS_OVERRIDDEN_PTR(node, _step)) {
- Array in_values;
- Array out_values;
- Array work_mem;
-
- in_values.resize(in_count);
-
- for (int i = 0; i < in_count; i++) {
- in_values[i] = *p_inputs[i];
- }
-
- out_values.resize(out_count);
-
- work_mem.resize(work_mem_size);
-
- for (int i = 0; i < work_mem_size; i++) {
- work_mem[i] = p_working_mem[i];
- }
-
- int ret_out;
-
- Variant ret;
- GDVIRTUAL_CALL_PTR(node, _step, in_values, out_values, p_start_mode, work_mem, ret);
- if (ret.get_type() == Variant::STRING) {
- r_error_str = ret;
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return 0;
- } else if (ret.is_num()) {
- ret_out = ret;
- } else {
- r_error_str = RTR("Invalid return value from _step(), must be integer (seq out), or string (error).");
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return 0;
- }
-
- for (int i = 0; i < out_count; i++) {
- if (i < out_values.size()) {
- *p_outputs[i] = out_values[i];
- }
- }
-
- for (int i = 0; i < work_mem_size; i++) {
- if (i < work_mem.size()) {
- p_working_mem[i] = work_mem[i];
- }
- }
-
- return ret_out;
- } else {
- r_error_str = RTR("Custom node has no _step() method, can't process graph.");
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptCustomNode::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceCustomNode *instance = memnew(VisualScriptNodeInstanceCustomNode);
- instance->instance = p_instance;
- instance->node = this;
- instance->in_count = get_input_value_port_count();
- instance->out_count = get_output_value_port_count();
-
- instance->work_mem_size = 0;
- GDVIRTUAL_CALL(_get_working_memory_size, instance->work_mem_size);
-
- return instance;
-}
-
-void VisualScriptCustomNode::_script_changed() {
- call_deferred(SNAME("ports_changed_notify"));
-}
-
-void VisualScriptCustomNode::_bind_methods() {
- GDVIRTUAL_BIND(_get_output_sequence_port_count);
- GDVIRTUAL_BIND(_has_input_sequence_port);
- GDVIRTUAL_BIND(_get_output_sequence_port_text, "seq_idx");
-
- GDVIRTUAL_BIND(_get_input_value_port_count);
- GDVIRTUAL_BIND(_get_input_value_port_type, "input_idx");
- GDVIRTUAL_BIND(_get_input_value_port_name, "input_idx");
- GDVIRTUAL_BIND(_get_input_value_port_hint, "input_idx");
- GDVIRTUAL_BIND(_get_input_value_port_hint_string, "input_idx");
-
- GDVIRTUAL_BIND(_get_output_value_port_count);
- GDVIRTUAL_BIND(_get_output_value_port_type, "output_idx");
- GDVIRTUAL_BIND(_get_output_value_port_name, "output_idx");
- GDVIRTUAL_BIND(_get_output_value_port_hint, "output_idx");
- GDVIRTUAL_BIND(_get_output_value_port_hint_string, "output_idx");
-
- GDVIRTUAL_BIND(_get_caption);
- GDVIRTUAL_BIND(_get_text);
- GDVIRTUAL_BIND(_get_category);
-
- GDVIRTUAL_BIND(_get_working_memory_size);
-
- GDVIRTUAL_BIND(_step, "inputs", "outputs", "start_mode", "working_mem");
-
- BIND_ENUM_CONSTANT(START_MODE_BEGIN_SEQUENCE);
- BIND_ENUM_CONSTANT(START_MODE_CONTINUE_SEQUENCE);
- BIND_ENUM_CONSTANT(START_MODE_RESUME_YIELD);
-
- BIND_CONSTANT(STEP_PUSH_STACK_BIT);
- BIND_CONSTANT(STEP_GO_BACK_BIT);
- BIND_CONSTANT(STEP_NO_ADVANCE_BIT);
- BIND_CONSTANT(STEP_EXIT_FUNCTION_BIT);
- BIND_CONSTANT(STEP_YIELD_BIT);
-}
-
-VisualScriptCustomNode::VisualScriptCustomNode() {
- connect("script_changed", callable_mp(this, &VisualScriptCustomNode::_script_changed));
-}
-
-//////////////////////////////////////////
-////////////////SUBCALL///////////
-//////////////////////////////////////////
-
-int VisualScriptSubCall::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptSubCall::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptSubCall::get_input_value_port_count() const {
- Ref<Script> script = get_script();
-
- if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
- MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
- return mi.arguments.size();
- }
-
- return 0;
-}
-
-int VisualScriptSubCall::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptSubCall::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptSubCall::get_input_value_port_info(int p_idx) const {
- Ref<Script> script = get_script();
- if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
- MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
- return mi.arguments[p_idx];
- }
-
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptSubCall::get_output_value_port_info(int p_idx) const {
- Ref<Script> script = get_script();
- if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
- MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
- return mi.return_val;
- }
- return PropertyInfo();
-}
-
-String VisualScriptSubCall::get_caption() const {
- return RTR("SubCall");
-}
-
-String VisualScriptSubCall::get_text() const {
- Ref<Script> script = get_script();
- if (script.is_valid()) {
- if (!script->get_name().is_empty()) {
- return script->get_name();
- }
- if (script->get_path().is_resource_file()) {
- return script->get_path().get_file();
- }
- return script->get_class();
- }
- return "";
-}
-
-String VisualScriptSubCall::get_category() const {
- return "custom";
-}
-
-class VisualScriptNodeInstanceSubCall : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- VisualScriptSubCall *subcall = nullptr;
- int input_args = 0;
- bool valid = false;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- if (!valid) {
- r_error_str = "Node requires a script with a _subcall(<args>) method to work.";
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return 0;
- }
- *p_outputs[0] = subcall->callp(VisualScriptLanguage::singleton->_subcall, p_inputs, input_args, r_error);
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptSubCall::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSubCall *instance = memnew(VisualScriptNodeInstanceSubCall);
- instance->instance = p_instance;
- Ref<Script> script = get_script();
- if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
- instance->valid = true;
- instance->input_args = get_input_value_port_count();
- } else {
- instance->valid = false;
- }
- return instance;
-}
-
-void VisualScriptSubCall::_bind_methods() {
- // Since this is script only, registering virtual function is no longer valid. Will have to go in docs.
-}
-
-VisualScriptSubCall::VisualScriptSubCall() {
-}
-
-//////////////////////////////////////////
-////////////////Comment///////////
-//////////////////////////////////////////
-
-int VisualScriptComment::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptComment::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptComment::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptComment::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptComment::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptComment::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptComment::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptComment::get_caption() const {
- return title;
-}
-
-String VisualScriptComment::get_text() const {
- return description;
-}
-
-void VisualScriptComment::set_title(const String &p_title) {
- if (title == p_title) {
- return;
- }
- title = p_title;
- ports_changed_notify();
-}
-
-String VisualScriptComment::get_title() const {
- return title;
-}
-
-void VisualScriptComment::set_description(const String &p_description) {
- if (description == p_description) {
- return;
- }
- description = p_description;
- ports_changed_notify();
-}
-
-String VisualScriptComment::get_description() const {
- return description;
-}
-
-void VisualScriptComment::set_size(const Size2 &p_size) {
- if (size == p_size) {
- return;
- }
- size = p_size;
- ports_changed_notify();
-}
-
-Size2 VisualScriptComment::get_size() const {
- return size;
-}
-
-String VisualScriptComment::get_category() const {
- return "data";
-}
-
-class VisualScriptNodeInstanceComment : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptComment::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceComment *instance = memnew(VisualScriptNodeInstanceComment);
- instance->instance = p_instance;
- return instance;
-}
-
-void VisualScriptComment::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_title", "title"), &VisualScriptComment::set_title);
- ClassDB::bind_method(D_METHOD("get_title"), &VisualScriptComment::get_title);
-
- ClassDB::bind_method(D_METHOD("set_description", "description"), &VisualScriptComment::set_description);
- ClassDB::bind_method(D_METHOD("get_description"), &VisualScriptComment::get_description);
-
- ClassDB::bind_method(D_METHOD("set_size", "size"), &VisualScriptComment::set_size);
- ClassDB::bind_method(D_METHOD("get_size"), &VisualScriptComment::get_size);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "title"), "set_title", "get_title");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "description", PROPERTY_HINT_MULTILINE_TEXT), "set_description", "get_description");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size"), "set_size", "get_size");
-}
-
-VisualScriptComment::VisualScriptComment() {
- title = "Comment";
- size = Size2(150, 150);
-}
-
-//////////////////////////////////////////
-////////////////Constructor///////////
-//////////////////////////////////////////
-
-int VisualScriptConstructor::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptConstructor::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptConstructor::get_input_value_port_count() const {
- return constructor.arguments.size();
-}
-
-int VisualScriptConstructor::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptConstructor::get_output_sequence_port_text(int p_port) const {
- return "";
-}
-
-PropertyInfo VisualScriptConstructor::get_input_value_port_info(int p_idx) const {
- return constructor.arguments[p_idx];
-}
-
-PropertyInfo VisualScriptConstructor::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(type, "value");
-}
-
-String VisualScriptConstructor::get_caption() const {
- return vformat(RTR("Construct %s"), Variant::get_type_name(type));
-}
-
-String VisualScriptConstructor::get_category() const {
- return "functions";
-}
-
-void VisualScriptConstructor::set_constructor_type(Variant::Type p_type) {
- if (type == p_type) {
- return;
- }
-
- type = p_type;
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptConstructor::get_constructor_type() const {
- return type;
-}
-
-void VisualScriptConstructor::set_constructor(const Dictionary &p_info) {
- constructor = MethodInfo::from_dict(p_info);
- ports_changed_notify();
-}
-
-Dictionary VisualScriptConstructor::get_constructor() const {
- return constructor;
-}
-
-class VisualScriptNodeInstanceConstructor : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- Variant::Type type;
- int argcount = 0;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- Callable::CallError ce;
- Variant::construct(type, *p_outputs[0], p_inputs, argcount, ce);
- if (ce.error != Callable::CallError::CALL_OK) {
- r_error_str = "Invalid arguments for constructor";
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptConstructor::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceConstructor *instance = memnew(VisualScriptNodeInstanceConstructor);
- instance->instance = p_instance;
- instance->type = type;
- instance->argcount = constructor.arguments.size();
- return instance;
-}
-
-void VisualScriptConstructor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_constructor_type", "type"), &VisualScriptConstructor::set_constructor_type);
- ClassDB::bind_method(D_METHOD("get_constructor_type"), &VisualScriptConstructor::get_constructor_type);
-
- ClassDB::bind_method(D_METHOD("set_constructor", "constructor"), &VisualScriptConstructor::set_constructor);
- ClassDB::bind_method(D_METHOD("get_constructor"), &VisualScriptConstructor::get_constructor);
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_constructor_type", "get_constructor_type");
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "constructor", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_constructor", "get_constructor");
-}
-
-VisualScriptConstructor::VisualScriptConstructor() {
- type = Variant::NIL;
-}
-
-static HashMap<String, Pair<Variant::Type, MethodInfo>> constructor_map;
-
-static Ref<VisualScriptNode> create_constructor_node(const String &p_name) {
- ERR_FAIL_COND_V(!constructor_map.has(p_name), Ref<VisualScriptNode>());
-
- Ref<VisualScriptConstructor> vsc;
- vsc.instantiate();
- vsc->set_constructor_type(constructor_map[p_name].first);
- vsc->set_constructor(constructor_map[p_name].second);
-
- return vsc;
-}
-
-//////////////////////////////////////////
-////////////////LocalVar///////////
-//////////////////////////////////////////
-
-int VisualScriptLocalVar::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptLocalVar::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptLocalVar::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptLocalVar::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptLocalVar::get_output_sequence_port_text(int p_port) const {
- return "";
-}
-
-PropertyInfo VisualScriptLocalVar::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptLocalVar::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(type, name);
-}
-
-String VisualScriptLocalVar::get_caption() const {
- return RTR("Get Local Var");
-}
-
-String VisualScriptLocalVar::get_category() const {
- return "data";
-}
-
-void VisualScriptLocalVar::set_var_name(const StringName &p_name) {
- if (name == p_name) {
- return;
- }
-
- name = p_name;
- ports_changed_notify();
-}
-
-StringName VisualScriptLocalVar::get_var_name() const {
- return name;
-}
-
-void VisualScriptLocalVar::set_var_type(Variant::Type p_type) {
- type = p_type;
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptLocalVar::get_var_type() const {
- return type;
-}
-
-class VisualScriptNodeInstanceLocalVar : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- StringName name;
-
- virtual int get_working_memory_size() const override { return 1; }
- 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) override {
- *p_outputs[0] = *p_working_mem;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptLocalVar::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceLocalVar *instance = memnew(VisualScriptNodeInstanceLocalVar);
- instance->instance = p_instance;
- instance->name = name;
-
- return instance;
-}
-
-void VisualScriptLocalVar::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_var_name", "name"), &VisualScriptLocalVar::set_var_name);
- ClassDB::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVar::get_var_name);
-
- ClassDB::bind_method(D_METHOD("set_var_type", "type"), &VisualScriptLocalVar::set_var_type);
- ClassDB::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVar::get_var_type);
-
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "var_name"), "set_var_name", "get_var_name");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt), "set_var_type", "get_var_type");
-}
-
-VisualScriptLocalVar::VisualScriptLocalVar() {
- name = "new_local";
- type = Variant::NIL;
-}
-
-//////////////////////////////////////////
-////////////////LocalVar///////////
-//////////////////////////////////////////
-
-int VisualScriptLocalVarSet::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptLocalVarSet::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptLocalVarSet::get_input_value_port_count() const {
- return 1;
-}
-
-int VisualScriptLocalVarSet::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptLocalVarSet::get_output_sequence_port_text(int p_port) const {
- return "";
-}
-
-PropertyInfo VisualScriptLocalVarSet::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(type, "set");
-}
-
-PropertyInfo VisualScriptLocalVarSet::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(type, "get");
-}
-
-String VisualScriptLocalVarSet::get_caption() const {
- return RTR("Set Local Var");
-}
-
-String VisualScriptLocalVarSet::get_text() const {
- return name;
-}
-
-String VisualScriptLocalVarSet::get_category() const {
- return "data";
-}
-
-void VisualScriptLocalVarSet::set_var_name(const StringName &p_name) {
- if (name == p_name) {
- return;
- }
-
- name = p_name;
- ports_changed_notify();
-}
-
-StringName VisualScriptLocalVarSet::get_var_name() const {
- return name;
-}
-
-void VisualScriptLocalVarSet::set_var_type(Variant::Type p_type) {
- type = p_type;
- ports_changed_notify();
-}
-
-Variant::Type VisualScriptLocalVarSet::get_var_type() const {
- return type;
-}
-
-class VisualScriptNodeInstanceLocalVarSet : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- StringName name;
-
- virtual int get_working_memory_size() const override { return 1; }
- 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) override {
- *p_working_mem = *p_inputs[0];
- *p_outputs[0] = *p_working_mem;
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptLocalVarSet::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceLocalVarSet *instance = memnew(VisualScriptNodeInstanceLocalVarSet);
- instance->instance = p_instance;
- instance->name = name;
-
- return instance;
-}
-
-void VisualScriptLocalVarSet::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_var_name", "name"), &VisualScriptLocalVarSet::set_var_name);
- ClassDB::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVarSet::get_var_name);
-
- ClassDB::bind_method(D_METHOD("set_var_type", "type"), &VisualScriptLocalVarSet::set_var_type);
- ClassDB::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVarSet::get_var_type);
-
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "var_name"), "set_var_name", "get_var_name");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt), "set_var_type", "get_var_type");
-}
-
-VisualScriptLocalVarSet::VisualScriptLocalVarSet() {
- name = "new_local";
- type = Variant::NIL;
-}
-
-//////////////////////////////////////////
-////////////////LocalVar///////////
-//////////////////////////////////////////
-
-int VisualScriptInputAction::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptInputAction::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptInputAction::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptInputAction::get_output_value_port_count() const {
- return 1;
-}
-
-String VisualScriptInputAction::get_output_sequence_port_text(int p_port) const {
- return "";
-}
-
-PropertyInfo VisualScriptInputAction::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptInputAction::get_output_value_port_info(int p_idx) const {
- String mstr;
- switch (mode) {
- case MODE_PRESSED: {
- mstr = "pressed";
- } break;
- case MODE_RELEASED: {
- mstr = "not pressed";
- } break;
- case MODE_JUST_PRESSED: {
- mstr = "just pressed";
- } break;
- case MODE_JUST_RELEASED: {
- mstr = "just released";
- } break;
- }
-
- return PropertyInfo(Variant::BOOL, mstr);
-}
-
-String VisualScriptInputAction::get_caption() const {
- return vformat(RTR("Action %s"), name);
-}
-
-String VisualScriptInputAction::get_category() const {
- return "data";
-}
-
-void VisualScriptInputAction::set_action_name(const StringName &p_name) {
- if (name == p_name) {
- return;
- }
-
- name = p_name;
- ports_changed_notify();
-}
-
-StringName VisualScriptInputAction::get_action_name() const {
- return name;
-}
-
-void VisualScriptInputAction::set_action_mode(Mode p_mode) {
- if (mode == p_mode) {
- return;
- }
-
- mode = p_mode;
- ports_changed_notify();
-}
-
-VisualScriptInputAction::Mode VisualScriptInputAction::get_action_mode() const {
- return mode;
-}
-
-class VisualScriptNodeInstanceInputAction : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- StringName action;
- VisualScriptInputAction::Mode mode;
-
- 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) override {
- switch (mode) {
- case VisualScriptInputAction::MODE_PRESSED: {
- *p_outputs[0] = Input::get_singleton()->is_action_pressed(action);
- } break;
- case VisualScriptInputAction::MODE_RELEASED: {
- *p_outputs[0] = !Input::get_singleton()->is_action_pressed(action);
- } break;
- case VisualScriptInputAction::MODE_JUST_PRESSED: {
- *p_outputs[0] = Input::get_singleton()->is_action_just_pressed(action);
- } break;
- case VisualScriptInputAction::MODE_JUST_RELEASED: {
- *p_outputs[0] = Input::get_singleton()->is_action_just_released(action);
- } break;
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptInputAction::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceInputAction *instance = memnew(VisualScriptNodeInstanceInputAction);
- instance->instance = p_instance;
- instance->action = name;
- instance->mode = mode;
-
- return instance;
-}
-
-void VisualScriptInputAction::_validate_property(PropertyInfo &property) const {
- if (property.name == "action") {
- property.hint = PROPERTY_HINT_ENUM;
- String actions;
-
- List<PropertyInfo> pinfo;
- ProjectSettings::get_singleton()->get_property_list(&pinfo);
- Vector<String> al;
-
- for (const PropertyInfo &pi : pinfo) {
- if (!pi.name.begins_with("input/")) {
- continue;
- }
-
- String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
-
- al.push_back(name);
- }
-
- al.sort();
-
- for (int i = 0; i < al.size(); i++) {
- if (!actions.is_empty()) {
- actions += ",";
- }
- actions += al[i];
- }
-
- property.hint_string = actions;
- }
-}
-
-void VisualScriptInputAction::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_action_name", "name"), &VisualScriptInputAction::set_action_name);
- ClassDB::bind_method(D_METHOD("get_action_name"), &VisualScriptInputAction::get_action_name);
-
- ClassDB::bind_method(D_METHOD("set_action_mode", "mode"), &VisualScriptInputAction::set_action_mode);
- ClassDB::bind_method(D_METHOD("get_action_mode"), &VisualScriptInputAction::get_action_mode);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "action"), "set_action_name", "get_action_name");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Pressed,Released,JustPressed,JustReleased"), "set_action_mode", "get_action_mode");
-
- BIND_ENUM_CONSTANT(MODE_PRESSED);
- BIND_ENUM_CONSTANT(MODE_RELEASED);
- BIND_ENUM_CONSTANT(MODE_JUST_PRESSED);
- BIND_ENUM_CONSTANT(MODE_JUST_RELEASED);
-}
-
-VisualScriptInputAction::VisualScriptInputAction() {
- name = "";
- mode = MODE_PRESSED;
-}
-
-//////////////////////////////////////////
-////////////////Constructor///////////
-//////////////////////////////////////////
-
-int VisualScriptDeconstruct::get_output_sequence_port_count() const {
- return 0;
-}
-
-bool VisualScriptDeconstruct::has_input_sequence_port() const {
- return false;
-}
-
-int VisualScriptDeconstruct::get_input_value_port_count() const {
- return 1;
-}
-
-int VisualScriptDeconstruct::get_output_value_port_count() const {
- return elements.size();
-}
-
-String VisualScriptDeconstruct::get_output_sequence_port_text(int p_port) const {
- return "";
-}
-
-PropertyInfo VisualScriptDeconstruct::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(type, "value");
-}
-
-PropertyInfo VisualScriptDeconstruct::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(elements[p_idx].type, elements[p_idx].name);
-}
-
-String VisualScriptDeconstruct::get_caption() const {
- return vformat(RTR("Deconstruct %s"), Variant::get_type_name(type));
-}
-
-String VisualScriptDeconstruct::get_category() const {
- return "functions";
-}
-
-void VisualScriptDeconstruct::_update_elements() {
- elements.clear();
- Variant v;
- Callable::CallError ce;
- Variant::construct(type, v, nullptr, 0, ce);
-
- List<PropertyInfo> pinfo;
- v.get_property_list(&pinfo);
-
- for (const PropertyInfo &E : pinfo) {
- Element e;
- e.name = E.name;
- e.type = E.type;
- elements.push_back(e);
- }
-}
-
-void VisualScriptDeconstruct::set_deconstruct_type(Variant::Type p_type) {
- if (type == p_type) {
- return;
- }
-
- type = p_type;
- _update_elements();
- ports_changed_notify();
- notify_property_list_changed(); //to make input appear/disappear
-}
-
-Variant::Type VisualScriptDeconstruct::get_deconstruct_type() const {
- return type;
-}
-
-void VisualScriptDeconstruct::_set_elem_cache(const Array &p_elements) {
- ERR_FAIL_COND(p_elements.size() % 2 == 1);
- elements.resize(p_elements.size() / 2);
- for (int i = 0; i < elements.size(); i++) {
- elements.write[i].name = p_elements[i * 2 + 0];
- elements.write[i].type = Variant::Type(int(p_elements[i * 2 + 1]));
- }
-}
-
-Array VisualScriptDeconstruct::_get_elem_cache() const {
- Array ret;
- for (int i = 0; i < elements.size(); i++) {
- ret.push_back(elements[i].name);
- ret.push_back(elements[i].type);
- }
- return ret;
-}
-
-class VisualScriptNodeInstanceDeconstruct : public VisualScriptNodeInstance {
-public:
- VisualScriptInstance *instance = nullptr;
- Vector<StringName> outputs;
-
- //virtual int get_working_memory_size() const override { return 0; }
-
- 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) override {
- Variant in = *p_inputs[0];
-
- for (int i = 0; i < outputs.size(); i++) {
- bool valid;
- *p_outputs[i] = in.get(outputs[i], &valid);
- if (!valid) {
- r_error_str = "Can't obtain element '" + String(outputs[i]) + "' from " + Variant::get_type_name(in.get_type());
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return 0;
- }
- }
-
- return 0;
- }
-};
-
-VisualScriptNodeInstance *VisualScriptDeconstruct::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceDeconstruct *instance = memnew(VisualScriptNodeInstanceDeconstruct);
- instance->instance = p_instance;
- instance->outputs.resize(elements.size());
- for (int i = 0; i < elements.size(); i++) {
- instance->outputs.write[i] = elements[i].name;
- }
-
- return instance;
-}
-
-void VisualScriptDeconstruct::_validate_property(PropertyInfo &property) const {
-}
-
-void VisualScriptDeconstruct::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_deconstruct_type", "type"), &VisualScriptDeconstruct::set_deconstruct_type);
- ClassDB::bind_method(D_METHOD("get_deconstruct_type"), &VisualScriptDeconstruct::get_deconstruct_type);
-
- ClassDB::bind_method(D_METHOD("_set_elem_cache", "_cache"), &VisualScriptDeconstruct::_set_elem_cache);
- ClassDB::bind_method(D_METHOD("_get_elem_cache"), &VisualScriptDeconstruct::_get_elem_cache);
-
- String argt = "Any";
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- argt += "," + Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt), "set_deconstruct_type", "get_deconstruct_type");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "elem_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_elem_cache", "_get_elem_cache");
-}
-
-VisualScriptDeconstruct::VisualScriptDeconstruct() {
- type = Variant::NIL;
-}
-
-template <Variant::Type T>
-static Ref<VisualScriptNode> create_node_deconst_typed(const String &p_name) {
- Ref<VisualScriptDeconstruct> node;
- node.instantiate();
- node->set_deconstruct_type(T);
- return node;
-}
-
-void register_visual_script_nodes() {
- VisualScriptLanguage::singleton->add_register_func("data/set_variable", create_node_generic<VisualScriptVariableSet>);
- VisualScriptLanguage::singleton->add_register_func("data/get_variable", create_node_generic<VisualScriptVariableGet>);
- VisualScriptLanguage::singleton->add_register_func("data/engine_singleton", create_node_generic<VisualScriptEngineSingleton>);
- VisualScriptLanguage::singleton->add_register_func("data/scene_node", create_node_generic<VisualScriptSceneNode>);
- VisualScriptLanguage::singleton->add_register_func("data/scene_tree", create_node_generic<VisualScriptSceneTree>);
- VisualScriptLanguage::singleton->add_register_func("data/resource_path", create_node_generic<VisualScriptResourcePath>);
- VisualScriptLanguage::singleton->add_register_func("data/self", create_node_generic<VisualScriptSelf>);
- VisualScriptLanguage::singleton->add_register_func("data/comment", create_node_generic<VisualScriptComment>);
- VisualScriptLanguage::singleton->add_register_func("data/get_local_variable", create_node_generic<VisualScriptLocalVar>);
- VisualScriptLanguage::singleton->add_register_func("data/set_local_variable", create_node_generic<VisualScriptLocalVarSet>);
- VisualScriptLanguage::singleton->add_register_func("data/preload", create_node_generic<VisualScriptPreload>);
- VisualScriptLanguage::singleton->add_register_func("data/action", create_node_generic<VisualScriptInputAction>);
-
- VisualScriptLanguage::singleton->add_register_func("constants/constant", create_node_generic<VisualScriptConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/math_constant", create_node_generic<VisualScriptMathConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/class_constant", create_node_generic<VisualScriptClassConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/global_constant", create_node_generic<VisualScriptGlobalConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/basic_type_constant", create_node_generic<VisualScriptBasicTypeConstant>);
-
- VisualScriptLanguage::singleton->add_register_func("custom/custom_node", create_node_generic<VisualScriptCustomNode>);
- VisualScriptLanguage::singleton->add_register_func("custom/sub_call", create_node_generic<VisualScriptSubCall>);
-
- VisualScriptLanguage::singleton->add_register_func("index/get_index", create_node_generic<VisualScriptIndexGet>);
- VisualScriptLanguage::singleton->add_register_func("index/set_index", create_node_generic<VisualScriptIndexSet>);
-
- VisualScriptLanguage::singleton->add_register_func("operators/compare/equal", create_op_node<Variant::OP_EQUAL>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/not_equal", create_op_node<Variant::OP_NOT_EQUAL>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/less", create_op_node<Variant::OP_LESS>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/less_equal", create_op_node<Variant::OP_LESS_EQUAL>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/greater", create_op_node<Variant::OP_GREATER>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/greater_equal", create_op_node<Variant::OP_GREATER_EQUAL>);
- //mathematic
- VisualScriptLanguage::singleton->add_register_func("operators/math/add", create_op_node<Variant::OP_ADD>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/subtract", create_op_node<Variant::OP_SUBTRACT>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/multiply", create_op_node<Variant::OP_MULTIPLY>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/divide", create_op_node<Variant::OP_DIVIDE>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/negate", create_op_node<Variant::OP_NEGATE>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/positive", create_op_node<Variant::OP_POSITIVE>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/remainder", create_op_node<Variant::OP_MODULE>);
- //bitwise
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_left", create_op_node<Variant::OP_SHIFT_LEFT>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_right", create_op_node<Variant::OP_SHIFT_RIGHT>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_and", create_op_node<Variant::OP_BIT_AND>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_or", create_op_node<Variant::OP_BIT_OR>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_xor", create_op_node<Variant::OP_BIT_XOR>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_negate", create_op_node<Variant::OP_BIT_NEGATE>);
- //logic
- VisualScriptLanguage::singleton->add_register_func("operators/logic/and", create_op_node<Variant::OP_AND>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/or", create_op_node<Variant::OP_OR>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/xor", create_op_node<Variant::OP_XOR>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/not", create_op_node<Variant::OP_NOT>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/in", create_op_node<Variant::OP_IN>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/select", create_node_generic<VisualScriptSelect>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR2), create_node_deconst_typed<Variant::Type::VECTOR2>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR2I), create_node_deconst_typed<Variant::Type::VECTOR2I>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR3), create_node_deconst_typed<Variant::Type::VECTOR3>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR3I), create_node_deconst_typed<Variant::Type::VECTOR3I>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR4), create_node_deconst_typed<Variant::Type::VECTOR4>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR4I), create_node_deconst_typed<Variant::Type::VECTOR4I>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::COLOR), create_node_deconst_typed<Variant::Type::COLOR>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::RECT2), create_node_deconst_typed<Variant::Type::RECT2>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::RECT2I), create_node_deconst_typed<Variant::Type::RECT2I>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::TRANSFORM2D), create_node_deconst_typed<Variant::Type::TRANSFORM2D>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::PLANE), create_node_deconst_typed<Variant::Type::PLANE>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::QUATERNION), create_node_deconst_typed<Variant::Type::QUATERNION>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::AABB), create_node_deconst_typed<Variant::Type::AABB>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::BASIS), create_node_deconst_typed<Variant::Type::BASIS>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::TRANSFORM3D), create_node_deconst_typed<Variant::Type::TRANSFORM3D>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::PROJECTION), create_node_deconst_typed<Variant::Type::PROJECTION>);
- VisualScriptLanguage::singleton->add_register_func("functions/compose_array", create_node_generic<VisualScriptComposeArray>);
-
- for (int i = 1; i < Variant::VARIANT_MAX; i++) {
- List<MethodInfo> constructors;
- Variant::get_constructor_list(Variant::Type(i), &constructors);
-
- for (const MethodInfo &E : constructors) {
- if (E.arguments.size() > 0) {
- String name = "functions/constructors/" + Variant::get_type_name(Variant::Type(i)) + "(";
- for (int j = 0; j < E.arguments.size(); j++) {
- if (j > 0) {
- name += ", ";
- }
- if (E.arguments.size() == 1) {
- name += Variant::get_type_name(E.arguments[j].type);
- } else {
- name += E.arguments[j].name;
- }
- }
- name += ")";
- VisualScriptLanguage::singleton->add_register_func(name, create_constructor_node);
- Pair<Variant::Type, MethodInfo> pair;
- pair.first = Variant::Type(i);
- pair.second = E;
- constructor_map[name] = pair;
- }
- }
- }
-}
-
-void unregister_visual_script_nodes() {
- constructor_map.clear();
-}
diff --git a/modules/visual_script/visual_script_nodes.h b/modules/visual_script/visual_script_nodes.h
deleted file mode 100644
index 35e3c490cd..0000000000
--- a/modules/visual_script/visual_script_nodes.h
+++ /dev/null
@@ -1,1092 +0,0 @@
-/*************************************************************************/
-/* visual_script_nodes.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 VISUAL_SCRIPT_NODES_H
-#define VISUAL_SCRIPT_NODES_H
-
-#include "core/object/gdvirtual.gen.inc"
-#include "core/object/script_language.h"
-#include "scene/main/multiplayer_api.h"
-#include "visual_script.h"
-
-class VisualScriptFunction : public VisualScriptNode {
- GDCLASS(VisualScriptFunction, VisualScriptNode);
-
- struct Argument {
- String name;
- Variant::Type type;
- PropertyHint hint;
- String hint_string;
- };
-
- Vector<Argument> arguments;
-
- bool stack_less;
- int stack_size;
- MultiplayerAPI::RPCMode rpc_mode;
- bool sequenced;
-
-protected:
- bool _set(const StringName &p_name, const Variant &p_value);
- bool _get(const StringName &p_name, Variant &r_ret) const;
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "flow_control"; }
-
- void add_argument(Variant::Type p_type, const String &p_name, int p_index = -1, const PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_string = String(""));
- void set_argument_type(int p_argidx, Variant::Type p_type);
- Variant::Type get_argument_type(int p_argidx) const;
- void set_argument_name(int p_argidx, const String &p_name);
- String get_argument_name(int p_argidx) const;
- void remove_argument(int p_argidx);
- int get_argument_count() const;
-
- void set_stack_less(bool p_enable);
- bool is_stack_less() const;
-
- void set_sequenced(bool p_enable);
- bool is_sequenced() const;
-
- void set_stack_size(int p_size);
- int get_stack_size() const;
-
- void set_rpc_mode(MultiplayerAPI::RPCMode p_mode);
- MultiplayerAPI::RPCMode get_rpc_mode() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- virtual void reset_state() override;
-
- VisualScriptFunction();
-};
-
-class VisualScriptLists : public VisualScriptNode {
- GDCLASS(VisualScriptLists, VisualScriptNode)
-
- struct Port {
- String name;
- Variant::Type type;
- };
-
-protected:
- Vector<Port> inputports;
- Vector<Port> outputports;
-
- enum {
- OUTPUT_EDITABLE = 0x0001,
- OUTPUT_NAME_EDITABLE = 0x0002,
- OUTPUT_TYPE_EDITABLE = 0x0004,
- INPUT_EDITABLE = 0x0008,
- INPUT_NAME_EDITABLE = 0x000F,
- INPUT_TYPE_EDITABLE = 0x0010,
- };
-
- int flags;
-
- bool sequenced;
-
- bool _set(const StringName &p_name, const Variant &p_value);
- bool _get(const StringName &p_name, Variant &r_ret) const;
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
- static void _bind_methods();
-
-public:
- virtual void reset_state() override;
-
- virtual bool is_output_port_editable() const;
- virtual bool is_output_port_name_editable() const;
- virtual bool is_output_port_type_editable() const;
-
- virtual bool is_input_port_editable() const;
- virtual bool is_input_port_name_editable() const;
- virtual bool is_input_port_type_editable() const;
-
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- void add_input_data_port(Variant::Type p_type, const String &p_name, int p_index = -1);
- void set_input_data_port_type(int p_idx, Variant::Type p_type);
- void set_input_data_port_name(int p_idx, const String &p_name);
- void remove_input_data_port(int p_argidx);
-
- void add_output_data_port(Variant::Type p_type, const String &p_name, int p_index = -1);
- void set_output_data_port_type(int p_idx, Variant::Type p_type);
- void set_output_data_port_name(int p_idx, const String &p_name);
- void remove_output_data_port(int p_argidx);
-
- void set_sequenced(bool p_enable);
- bool is_sequenced() const;
-
- VisualScriptLists();
-};
-
-class VisualScriptComposeArray : public VisualScriptLists {
- GDCLASS(VisualScriptComposeArray, VisualScriptLists)
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "functions"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptComposeArray();
-};
-
-class VisualScriptOperator : public VisualScriptNode {
- GDCLASS(VisualScriptOperator, VisualScriptNode);
-
- Variant::Type typed;
- Variant::Operator op;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "operators"; }
-
- void set_operator(Variant::Operator p_op);
- Variant::Operator get_operator() const;
-
- void set_typed(Variant::Type p_op);
- Variant::Type get_typed() const;
-
- static String get_operator_name(Variant::Operator p_op);
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptOperator();
-};
-
-class VisualScriptSelect : public VisualScriptNode {
- GDCLASS(VisualScriptSelect, VisualScriptNode);
-
- Variant::Type typed;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "operators"; }
-
- void set_typed(Variant::Type p_op);
- Variant::Type get_typed() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptSelect();
-};
-
-class VisualScriptVariableGet : public VisualScriptNode {
- GDCLASS(VisualScriptVariableGet, VisualScriptNode);
-
- StringName variable;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- void set_variable(StringName p_variable);
- StringName get_variable() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptVariableGet();
-};
-
-class VisualScriptVariableSet : public VisualScriptNode {
- GDCLASS(VisualScriptVariableSet, VisualScriptNode);
-
- StringName variable;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- void set_variable(StringName p_variable);
- StringName get_variable() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptVariableSet();
-};
-
-class VisualScriptConstant : public VisualScriptNode {
- GDCLASS(VisualScriptConstant, VisualScriptNode);
-
- Variant::Type type;
- Variant value;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "constants"; }
-
- void set_constant_type(Variant::Type p_type);
- Variant::Type get_constant_type() const;
-
- void set_constant_value(Variant p_value);
- Variant get_constant_value() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptConstant();
-};
-
-class VisualScriptPreload : public VisualScriptNode {
- GDCLASS(VisualScriptPreload, VisualScriptNode);
-
- Ref<Resource> preload;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- void set_preload(const Ref<Resource> &p_preload);
- Ref<Resource> get_preload() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptPreload();
-};
-
-class VisualScriptIndexGet : public VisualScriptNode {
- GDCLASS(VisualScriptIndexGet, VisualScriptNode);
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "operators"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptIndexGet();
-};
-
-class VisualScriptIndexSet : public VisualScriptNode {
- GDCLASS(VisualScriptIndexSet, VisualScriptNode);
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "operators"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptIndexSet();
-};
-
-class VisualScriptGlobalConstant : public VisualScriptNode {
- GDCLASS(VisualScriptGlobalConstant, VisualScriptNode);
-
- int index;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "constants"; }
-
- void set_global_constant(int p_which);
- int get_global_constant();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptGlobalConstant();
-};
-
-class VisualScriptClassConstant : public VisualScriptNode {
- GDCLASS(VisualScriptClassConstant, VisualScriptNode);
-
- StringName base_type;
- StringName name;
-
-protected:
- static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "constants"; }
-
- void set_class_constant(const StringName &p_which);
- StringName get_class_constant();
-
- void set_base_type(const StringName &p_which);
- StringName get_base_type();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptClassConstant();
-};
-
-class VisualScriptBasicTypeConstant : public VisualScriptNode {
- GDCLASS(VisualScriptBasicTypeConstant, VisualScriptNode);
-
- Variant::Type type;
- StringName name;
-
-protected:
- static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "constants"; }
-
- void set_basic_type_constant(const StringName &p_which);
- StringName get_basic_type_constant() const;
-
- void set_basic_type(Variant::Type p_which);
- Variant::Type get_basic_type() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptBasicTypeConstant();
-};
-
-class VisualScriptMathConstant : public VisualScriptNode {
- GDCLASS(VisualScriptMathConstant, VisualScriptNode);
-
-public:
- enum MathConstant {
- MATH_CONSTANT_ONE,
- MATH_CONSTANT_PI,
- MATH_CONSTANT_HALF_PI,
- MATH_CONSTANT_TAU,
- MATH_CONSTANT_E,
- MATH_CONSTANT_SQRT2,
- MATH_CONSTANT_INF,
- MATH_CONSTANT_NAN,
- MATH_CONSTANT_MAX
- };
-
-private:
- static const char *const_name[MATH_CONSTANT_MAX];
- static double const_value[MATH_CONSTANT_MAX];
- MathConstant constant;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "constants"; }
-
- void set_math_constant(MathConstant p_which);
- MathConstant get_math_constant();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptMathConstant();
-};
-
-VARIANT_ENUM_CAST(VisualScriptMathConstant::MathConstant)
-
-class VisualScriptEngineSingleton : public VisualScriptNode {
- GDCLASS(VisualScriptEngineSingleton, VisualScriptNode);
-
- String singleton;
-
-protected:
- void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- void set_singleton(const String &p_string);
- String get_singleton();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- VisualScriptEngineSingleton();
-};
-
-class VisualScriptSceneNode : public VisualScriptNode {
- GDCLASS(VisualScriptSceneNode, VisualScriptNode);
-
- NodePath path;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- void set_node_path(const NodePath &p_path);
- NodePath get_node_path();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- VisualScriptSceneNode();
-};
-
-class VisualScriptSceneTree : public VisualScriptNode {
- GDCLASS(VisualScriptSceneTree, VisualScriptNode);
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- VisualScriptSceneTree();
-};
-
-class VisualScriptResourcePath : public VisualScriptNode {
- GDCLASS(VisualScriptResourcePath, VisualScriptNode);
-
- String path;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- void set_resource_path(const String &p_path);
- String get_resource_path();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptResourcePath();
-};
-
-class VisualScriptSelf : public VisualScriptNode {
- GDCLASS(VisualScriptSelf, VisualScriptNode);
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override { return "data"; }
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- VisualScriptSelf();
-};
-
-class VisualScriptCustomNode : public VisualScriptNode {
- GDCLASS(VisualScriptCustomNode, VisualScriptNode);
-
-protected:
- static void _bind_methods();
- friend class VisualScriptNodeInstanceCustomNode;
- GDVIRTUAL0RC(int, _get_output_sequence_port_count)
- GDVIRTUAL0RC(bool, _has_input_sequence_port)
- GDVIRTUAL1RC(String, _get_output_sequence_port_text, int)
-
- GDVIRTUAL0RC(int, _get_input_value_port_count)
- GDVIRTUAL1RC(int, _get_input_value_port_type, int)
- GDVIRTUAL1RC(String, _get_input_value_port_name, int)
- GDVIRTUAL1RC(int, _get_input_value_port_hint, int)
- GDVIRTUAL1RC(String, _get_input_value_port_hint_string, int)
-
- GDVIRTUAL0RC(int, _get_output_value_port_count)
- GDVIRTUAL1RC(int, _get_output_value_port_type, int)
- GDVIRTUAL1RC(String, _get_output_value_port_name, int)
- GDVIRTUAL1RC(int, _get_output_value_port_hint, int)
- GDVIRTUAL1RC(String, _get_output_value_port_hint_string, int)
-
- GDVIRTUAL0RC(String, _get_caption)
- GDVIRTUAL0RC(String, _get_text)
- GDVIRTUAL0RC(String, _get_category)
-
- GDVIRTUAL0RC(int, _get_working_memory_size)
-
- GDVIRTUAL4RC(Variant, _step, Array, Array, int, Array)
-
-public:
- enum StartMode { //replicated for step
- START_MODE_BEGIN_SEQUENCE,
- START_MODE_CONTINUE_SEQUENCE,
- START_MODE_RESUME_YIELD
- };
-
- enum { //replicated for step
- STEP_SHIFT = 1 << 24,
- STEP_MASK = STEP_SHIFT - 1,
- STEP_PUSH_STACK_BIT = STEP_SHIFT, //push bit to stack
- STEP_GO_BACK_BIT = STEP_SHIFT << 1, //go back to previous node
- STEP_NO_ADVANCE_BIT = STEP_SHIFT << 2, //do not advance past this node
- STEP_EXIT_FUNCTION_BIT = STEP_SHIFT << 3, //return from function
- STEP_YIELD_BIT = STEP_SHIFT << 4, //yield (will find VisualScriptFunctionState state in first working memory)
- };
-
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
-
- void _script_changed();
-
- VisualScriptCustomNode();
-};
-
-VARIANT_ENUM_CAST(VisualScriptCustomNode::StartMode);
-
-class VisualScriptSubCall : public VisualScriptNode {
- GDCLASS(VisualScriptSubCall, VisualScriptNode);
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptSubCall();
-};
-
-class VisualScriptComment : public VisualScriptNode {
- GDCLASS(VisualScriptComment, VisualScriptNode);
-
- String title;
- String description;
- Size2 size;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override;
-
- void set_title(const String &p_title);
- String get_title() const;
-
- void set_description(const String &p_description);
- String get_description() const;
-
- void set_size(const Size2 &p_size);
- Size2 get_size() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptComment();
-};
-
-class VisualScriptConstructor : public VisualScriptNode {
- GDCLASS(VisualScriptConstructor, VisualScriptNode);
-
- Variant::Type type;
- MethodInfo constructor;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override;
-
- void set_constructor_type(Variant::Type p_type);
- Variant::Type get_constructor_type() const;
-
- void set_constructor(const Dictionary &p_info);
- Dictionary get_constructor() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptConstructor();
-};
-
-class VisualScriptLocalVar : public VisualScriptNode {
- GDCLASS(VisualScriptLocalVar, VisualScriptNode);
-
- StringName name;
- Variant::Type type;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override;
-
- void set_var_name(const StringName &p_name);
- StringName get_var_name() const;
-
- void set_var_type(Variant::Type p_type);
- Variant::Type get_var_type() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptLocalVar();
-};
-
-class VisualScriptLocalVarSet : public VisualScriptNode {
- GDCLASS(VisualScriptLocalVarSet, VisualScriptNode);
-
- StringName name;
- Variant::Type type;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override;
-
- void set_var_name(const StringName &p_name);
- StringName get_var_name() const;
-
- void set_var_type(Variant::Type p_type);
- Variant::Type get_var_type() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptLocalVarSet();
-};
-
-class VisualScriptInputAction : public VisualScriptNode {
- GDCLASS(VisualScriptInputAction, VisualScriptNode);
-
-public:
- enum Mode {
- MODE_PRESSED,
- MODE_RELEASED,
- MODE_JUST_PRESSED,
- MODE_JUST_RELEASED,
- };
-
- StringName name;
- Mode mode;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override;
-
- void set_action_name(const StringName &p_name);
- StringName get_action_name() const;
-
- void set_action_mode(Mode p_mode);
- Mode get_action_mode() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptInputAction();
-};
-
-VARIANT_ENUM_CAST(VisualScriptInputAction::Mode)
-
-class VisualScriptDeconstruct : public VisualScriptNode {
- GDCLASS(VisualScriptDeconstruct, VisualScriptNode);
-
- struct Element {
- StringName name;
- Variant::Type type;
- };
-
- Vector<Element> elements;
-
- void _update_elements();
- Variant::Type type;
-
- void _set_elem_cache(const Array &p_elements);
- Array _get_elem_cache() const;
-
- virtual void _validate_property(PropertyInfo &property) const override;
-
-protected:
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_category() const override;
-
- void set_deconstruct_type(Variant::Type p_type);
- Variant::Type get_deconstruct_type() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptDeconstruct();
-};
-
-void register_visual_script_nodes();
-void unregister_visual_script_nodes();
-
-#endif // VISUAL_SCRIPT_NODES_H
diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp
deleted file mode 100644
index 96e91a0baf..0000000000
--- a/modules/visual_script/visual_script_yield_nodes.cpp
+++ /dev/null
@@ -1,598 +0,0 @@
-/*************************************************************************/
-/* visual_script_yield_nodes.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 "visual_script_yield_nodes.h"
-
-#include "core/os/os.h"
-#include "scene/main/node.h"
-#include "scene/main/scene_tree.h"
-#include "visual_script_nodes.h"
-
-//////////////////////////////////////////
-////////////////YIELD///////////
-//////////////////////////////////////////
-
-int VisualScriptYield::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptYield::has_input_sequence_port() const {
- return true;
-}
-
-int VisualScriptYield::get_input_value_port_count() const {
- return 0;
-}
-
-int VisualScriptYield::get_output_value_port_count() const {
- return 0;
-}
-
-String VisualScriptYield::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptYield::get_input_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-PropertyInfo VisualScriptYield::get_output_value_port_info(int p_idx) const {
- return PropertyInfo();
-}
-
-String VisualScriptYield::get_caption() const {
- return yield_mode == YIELD_RETURN ? RTR("Yield") : RTR("Wait");
-}
-
-String VisualScriptYield::get_text() const {
- switch (yield_mode) {
- case YIELD_RETURN:
- return "";
- break;
- case YIELD_FRAME:
- return RTR("Next Frame");
- break;
- case YIELD_PHYSICS_FRAME:
- return RTR("Next Physics Frame");
- break;
- case YIELD_WAIT:
- return vformat(RTR("%s sec(s)"), rtos(wait_time));
- break;
- }
-
- return String();
-}
-
-class VisualScriptNodeInstanceYield : public VisualScriptNodeInstance {
-public:
- VisualScriptYield::YieldMode mode;
- double wait_time = 0.0;
-
- virtual int get_working_memory_size() const override { return 1; } //yield needs at least 1
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; }
-
- 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) override {
- if (p_start_mode == START_MODE_RESUME_YIELD) {
- return 0; //resuming yield
- } else {
- //yield
-
- SceneTree *tree = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());
- if (!tree) {
- r_error_str = "Main Loop is not SceneTree";
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return 0;
- }
-
- Ref<VisualScriptFunctionState> state;
- state.instantiate();
-
- int ret = STEP_YIELD_BIT;
- switch (mode) {
- case VisualScriptYield::YIELD_RETURN:
- ret = STEP_EXIT_FUNCTION_BIT;
- break; //return the yield
- case VisualScriptYield::YIELD_FRAME:
- state->connect_to_signal(tree, "process_frame", Array());
- break;
- case VisualScriptYield::YIELD_PHYSICS_FRAME:
- state->connect_to_signal(tree, "physics_frame", Array());
- break;
- case VisualScriptYield::YIELD_WAIT:
- state->connect_to_signal(tree->create_timer(wait_time).ptr(), "timeout", Array());
- break;
- }
-
- *p_working_mem = state;
-
- return ret;
- }
- }
-};
-
-VisualScriptNodeInstance *VisualScriptYield::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceYield *instance = memnew(VisualScriptNodeInstanceYield);
- //instance->instance=p_instance;
- instance->mode = yield_mode;
- instance->wait_time = wait_time;
- return instance;
-}
-
-void VisualScriptYield::set_yield_mode(YieldMode p_mode) {
- if (yield_mode == p_mode) {
- return;
- }
- yield_mode = p_mode;
- ports_changed_notify();
- notify_property_list_changed();
-}
-
-VisualScriptYield::YieldMode VisualScriptYield::get_yield_mode() {
- return yield_mode;
-}
-
-void VisualScriptYield::set_wait_time(double p_time) {
- if (wait_time == p_time) {
- return;
- }
- wait_time = p_time;
- ports_changed_notify();
-}
-
-double VisualScriptYield::get_wait_time() {
- return wait_time;
-}
-
-void VisualScriptYield::_validate_property(PropertyInfo &property) const {
- if (property.name == "wait_time") {
- if (yield_mode != YIELD_WAIT) {
- property.usage = PROPERTY_USAGE_NONE;
- }
- }
-}
-
-void VisualScriptYield::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_yield_mode", "mode"), &VisualScriptYield::set_yield_mode);
- ClassDB::bind_method(D_METHOD("get_yield_mode"), &VisualScriptYield::get_yield_mode);
-
- ClassDB::bind_method(D_METHOD("set_wait_time", "sec"), &VisualScriptYield::set_wait_time);
- ClassDB::bind_method(D_METHOD("get_wait_time"), &VisualScriptYield::get_wait_time);
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Frame,Physics Frame,Time", PROPERTY_USAGE_NO_EDITOR), "set_yield_mode", "get_yield_mode");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wait_time"), "set_wait_time", "get_wait_time");
-
- BIND_ENUM_CONSTANT(YIELD_FRAME);
- BIND_ENUM_CONSTANT(YIELD_PHYSICS_FRAME);
- BIND_ENUM_CONSTANT(YIELD_WAIT);
-}
-
-VisualScriptYield::VisualScriptYield() {
- yield_mode = YIELD_FRAME;
- wait_time = 1;
-}
-
-template <VisualScriptYield::YieldMode MODE>
-static Ref<VisualScriptNode> create_yield_node(const String &p_name) {
- Ref<VisualScriptYield> node;
- node.instantiate();
- node->set_yield_mode(MODE);
- return node;
-}
-
-///////////////////////////////////////////////////
-////////////////YIELD SIGNAL//////////////////////
-//////////////////////////////////////////////////
-
-int VisualScriptYieldSignal::get_output_sequence_port_count() const {
- return 1;
-}
-
-bool VisualScriptYieldSignal::has_input_sequence_port() const {
- return true;
-}
-#ifdef TOOLS_ENABLED
-
-static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
- return nullptr;
- }
-
- Ref<Script> scr = p_current_node->get_script();
-
- if (scr.is_valid() && scr == script) {
- return p_current_node;
- }
-
- for (int i = 0; i < p_current_node->get_child_count(); i++) {
- Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n) {
- return n;
- }
- }
-
- return nullptr;
-}
-
-#endif
-Node *VisualScriptYieldSignal::_get_base_node() const {
-#ifdef TOOLS_ENABLED
- Ref<Script> script = get_visual_script();
- if (!script.is_valid()) {
- return nullptr;
- }
-
- MainLoop *main_loop = OS::get_singleton()->get_main_loop();
- SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
-
- if (!scene_tree) {
- return nullptr;
- }
-
- Node *edited_scene = scene_tree->get_edited_scene_root();
-
- if (!edited_scene) {
- return nullptr;
- }
-
- Node *script_node = _find_script_node(edited_scene, edited_scene, script);
-
- if (!script_node) {
- return nullptr;
- }
-
- if (!script_node->has_node(base_path)) {
- return nullptr;
- }
-
- Node *path_to = script_node->get_node(base_path);
-
- return path_to;
-#else
-
- return nullptr;
-#endif
-}
-
-StringName VisualScriptYieldSignal::_get_base_type() const {
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
- return get_visual_script()->get_instance_base_type();
- } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
- Node *path = _get_base_node();
- if (path) {
- return path->get_class();
- }
- }
-
- return base_type;
-}
-
-int VisualScriptYieldSignal::get_input_value_port_count() const {
- if (call_mode == CALL_MODE_INSTANCE) {
- return 1;
- } else {
- return 0;
- }
-}
-
-int VisualScriptYieldSignal::get_output_value_port_count() const {
- MethodInfo sr;
-
- if (!ClassDB::get_signal(_get_base_type(), signal, &sr)) {
- return 0;
- }
-
- return sr.arguments.size();
-}
-
-String VisualScriptYieldSignal::get_output_sequence_port_text(int p_port) const {
- return String();
-}
-
-PropertyInfo VisualScriptYieldSignal::get_input_value_port_info(int p_idx) const {
- if (call_mode == CALL_MODE_INSTANCE) {
- return PropertyInfo(Variant::OBJECT, "instance");
- } else {
- return PropertyInfo();
- }
-}
-
-PropertyInfo VisualScriptYieldSignal::get_output_value_port_info(int p_idx) const {
- MethodInfo sr;
-
- if (!ClassDB::get_signal(_get_base_type(), signal, &sr)) {
- return PropertyInfo(); //no signal
- }
- ERR_FAIL_INDEX_V(p_idx, sr.arguments.size(), PropertyInfo());
- return sr.arguments[p_idx];
-}
-
-String VisualScriptYieldSignal::get_caption() const {
- 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 {
- if (call_mode == CALL_MODE_SELF) {
- return " " + String(signal) + "()";
- } else {
- return " " + _get_base_type() + "." + String(signal) + "()";
- }
-}
-
-void VisualScriptYieldSignal::set_base_type(const StringName &p_type) {
- if (base_type == p_type) {
- return;
- }
-
- base_type = p_type;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptYieldSignal::get_base_type() const {
- return base_type;
-}
-
-void VisualScriptYieldSignal::set_signal(const StringName &p_type) {
- if (signal == p_type) {
- return;
- }
-
- signal = p_type;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-StringName VisualScriptYieldSignal::get_signal() const {
- return signal;
-}
-
-void VisualScriptYieldSignal::set_base_path(const NodePath &p_type) {
- if (base_path == p_type) {
- return;
- }
-
- base_path = p_type;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-NodePath VisualScriptYieldSignal::get_base_path() const {
- return base_path;
-}
-
-void VisualScriptYieldSignal::set_call_mode(CallMode p_mode) {
- if (call_mode == p_mode) {
- return;
- }
-
- call_mode = p_mode;
-
- notify_property_list_changed();
- ports_changed_notify();
-}
-
-VisualScriptYieldSignal::CallMode VisualScriptYieldSignal::get_call_mode() const {
- return call_mode;
-}
-
-void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
- if (property.name == "base_type") {
- if (call_mode != CALL_MODE_INSTANCE) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
- }
- }
-
- if (property.name == "node_path") {
- if (call_mode != CALL_MODE_NODE_PATH) {
- property.usage = PROPERTY_USAGE_NONE;
- } else {
- Node *bnode = _get_base_node();
- if (bnode) {
- property.hint_string = bnode->get_path(); //convert to long string
- }
- }
- }
-
- if (property.name == "signal") {
- property.hint = PROPERTY_HINT_ENUM;
-
- List<MethodInfo> methods;
-
- ClassDB::get_signal_list(_get_base_type(), &methods);
-
- List<String> mstring;
- for (const MethodInfo &E : methods) {
- if (E.name.begins_with("_")) {
- continue;
- }
- mstring.push_back(E.name.get_slice(":", 0));
- }
-
- mstring.sort();
-
- String ml;
- for (const String &E : mstring) {
- if (!ml.is_empty()) {
- ml += ",";
- }
- ml += E;
- }
-
- property.hint_string = ml;
- }
-}
-
-void VisualScriptYieldSignal::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptYieldSignal::set_base_type);
- ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptYieldSignal::get_base_type);
-
- ClassDB::bind_method(D_METHOD("set_signal", "signal"), &VisualScriptYieldSignal::set_signal);
- ClassDB::bind_method(D_METHOD("get_signal"), &VisualScriptYieldSignal::get_signal);
-
- ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptYieldSignal::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptYieldSignal::get_call_mode);
-
- ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptYieldSignal::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptYieldSignal::get_base_path);
-
- String bt;
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0) {
- bt += ",";
- }
-
- bt += Variant::get_type_name(Variant::Type(i));
- }
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "call_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance"), "set_call_mode", "get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "signal"), "set_signal", "get_signal");
-
- BIND_ENUM_CONSTANT(CALL_MODE_SELF);
- BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH);
- BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE);
-}
-
-class VisualScriptNodeInstanceYieldSignal : public VisualScriptNodeInstance {
-public:
- VisualScriptYieldSignal::CallMode call_mode;
- NodePath node_path;
- int output_args = 0;
- StringName signal;
-
- VisualScriptYieldSignal *node = nullptr;
- VisualScriptInstance *instance = nullptr;
-
- virtual int get_working_memory_size() const override { return 1; }
- //virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
- //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
-
- 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) override {
- if (p_start_mode == START_MODE_RESUME_YIELD) {
- return 0; //resuming yield
- } else {
- //yield
-
- Object *object = nullptr;
-
- switch (call_mode) {
- case VisualScriptYieldSignal::CALL_MODE_SELF: {
- object = instance->get_owner_ptr();
-
- } break;
- case VisualScriptYieldSignal::CALL_MODE_NODE_PATH: {
- Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
- if (!node) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Base object is not a Node!";
- return 0;
- }
-
- Node *another = node->get_node(node_path);
- if (!another) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Path does not lead Node!";
- return 0;
- }
-
- object = another;
-
- } break;
- case VisualScriptYieldSignal::CALL_MODE_INSTANCE: {
- object = *p_inputs[0];
- if (!object) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str = "Supplied instance input is null.";
- return 0;
- }
-
- } break;
- }
-
- Ref<VisualScriptFunctionState> state;
- state.instantiate();
-
- state->connect_to_signal(object, signal, Array());
-
- *p_working_mem = state;
-
- return STEP_YIELD_BIT;
- }
- }
-};
-
-VisualScriptNodeInstance *VisualScriptYieldSignal::instantiate(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceYieldSignal *instance = memnew(VisualScriptNodeInstanceYieldSignal);
- instance->node = this;
- instance->instance = p_instance;
- instance->signal = signal;
- instance->call_mode = call_mode;
- instance->node_path = base_path;
- instance->output_args = get_output_value_port_count();
- return instance;
-}
-
-VisualScriptYieldSignal::VisualScriptYieldSignal() {
- call_mode = CALL_MODE_SELF;
- base_type = "Object";
-}
-
-template <VisualScriptYieldSignal::CallMode cmode>
-static Ref<VisualScriptNode> create_yield_signal_node(const String &p_name) {
- Ref<VisualScriptYieldSignal> node;
- node.instantiate();
- node->set_call_mode(cmode);
- return node;
-}
-
-void register_visual_script_yield_nodes() {
- VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_frame", create_yield_node<VisualScriptYield::YIELD_FRAME>);
- VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_physics_frame", create_yield_node<VisualScriptYield::YIELD_PHYSICS_FRAME>);
- VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_time", create_yield_node<VisualScriptYield::YIELD_WAIT>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/yield", create_yield_node<VisualScriptYield::YIELD_RETURN>);
- VisualScriptLanguage::singleton->add_register_func("functions/yield_signal", create_node_generic<VisualScriptYieldSignal>);
-}
diff --git a/modules/visual_script/visual_script_yield_nodes.h b/modules/visual_script/visual_script_yield_nodes.h
deleted file mode 100644
index a7bf4e8a78..0000000000
--- a/modules/visual_script/visual_script_yield_nodes.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*************************************************************************/
-/* visual_script_yield_nodes.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 VISUAL_SCRIPT_YIELD_NODES_H
-#define VISUAL_SCRIPT_YIELD_NODES_H
-
-#include "visual_script.h"
-
-class VisualScriptYield : public VisualScriptNode {
- GDCLASS(VisualScriptYield, VisualScriptNode);
-
-public:
- enum YieldMode {
- YIELD_RETURN,
- YIELD_FRAME,
- YIELD_PHYSICS_FRAME,
- YIELD_WAIT
-
- };
-
-private:
- YieldMode yield_mode;
- double wait_time;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "functions"; }
-
- void set_yield_mode(YieldMode p_mode);
- YieldMode get_yield_mode();
-
- void set_wait_time(double p_time);
- double get_wait_time();
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptYield();
-};
-VARIANT_ENUM_CAST(VisualScriptYield::YieldMode)
-
-class VisualScriptYieldSignal : public VisualScriptNode {
- GDCLASS(VisualScriptYieldSignal, VisualScriptNode);
-
-public:
- enum CallMode {
- CALL_MODE_SELF,
- CALL_MODE_NODE_PATH,
- CALL_MODE_INSTANCE,
-
- };
-
-private:
- CallMode call_mode;
- StringName base_type;
- NodePath base_path;
- StringName signal;
-
- Node *_get_base_node() const;
- StringName _get_base_type() const;
-
-protected:
- virtual void _validate_property(PropertyInfo &property) const override;
-
- static void _bind_methods();
-
-public:
- virtual int get_output_sequence_port_count() const override;
- virtual bool has_input_sequence_port() const override;
-
- virtual String get_output_sequence_port_text(int p_port) const override;
-
- virtual int get_input_value_port_count() const override;
- virtual int get_output_value_port_count() const override;
-
- virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
-
- virtual String get_caption() const override;
- virtual String get_text() const override;
- virtual String get_category() const override { return "functions"; }
-
- void set_base_type(const StringName &p_type);
- StringName get_base_type() const;
-
- void set_signal(const StringName &p_type);
- StringName get_signal() const;
-
- void set_base_path(const NodePath &p_type);
- NodePath get_base_path() const;
-
- void set_call_mode(CallMode p_mode);
- CallMode get_call_mode() const;
-
- virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override;
-
- VisualScriptYieldSignal();
-};
-
-VARIANT_ENUM_CAST(VisualScriptYieldSignal::CallMode);
-
-void register_visual_script_yield_nodes();
-
-#endif // VISUAL_SCRIPT_YIELD_NODES_H
diff --git a/modules/webp/SCsub b/modules/webp/SCsub
index 80d62400c8..72ad1ea5e4 100644
--- a/modules/webp/SCsub
+++ b/modules/webp/SCsub
@@ -12,123 +12,129 @@ thirdparty_obj = []
if env["builtin_libwebp"]:
thirdparty_dir = "#thirdparty/libwebp/"
thirdparty_sources = [
- "dec/alpha_dec.c",
- "dec/buffer_dec.c",
- "dec/frame_dec.c",
- "dec/idec_dec.c",
- "dec/io_dec.c",
- "dec/quant_dec.c",
- "dec/tree_dec.c",
- "dec/vp8_dec.c",
- "dec/vp8l_dec.c",
- "dec/webp_dec.c",
- "demux/anim_decode.c",
- "demux/demux.c",
- "dsp/alpha_processing.c",
- "dsp/alpha_processing_mips_dsp_r2.c",
- "dsp/alpha_processing_neon.c",
- "dsp/alpha_processing_sse2.c",
- "dsp/alpha_processing_sse41.c",
- "dsp/cost.c",
- "dsp/cost_mips32.c",
- "dsp/cost_mips_dsp_r2.c",
- "dsp/cost_neon.c",
- "dsp/cost_sse2.c",
- "dsp/cpu.c",
- "dsp/dec.c",
- "dsp/dec_clip_tables.c",
- "dsp/dec_mips32.c",
- "dsp/dec_mips_dsp_r2.c",
- "dsp/dec_msa.c",
- "dsp/dec_neon.c",
- "dsp/dec_sse2.c",
- "dsp/dec_sse41.c",
- "dsp/enc.c",
- "dsp/enc_mips32.c",
- "dsp/enc_mips_dsp_r2.c",
- "dsp/enc_msa.c",
- "dsp/enc_neon.c",
- "dsp/enc_sse2.c",
- "dsp/enc_sse41.c",
- "dsp/filters.c",
- "dsp/filters_mips_dsp_r2.c",
- "dsp/filters_msa.c",
- "dsp/filters_neon.c",
- "dsp/filters_sse2.c",
- "dsp/lossless.c",
- "dsp/lossless_enc.c",
- "dsp/lossless_enc_mips32.c",
- "dsp/lossless_enc_mips_dsp_r2.c",
- "dsp/lossless_enc_msa.c",
- "dsp/lossless_enc_neon.c",
- "dsp/lossless_enc_sse2.c",
- "dsp/lossless_enc_sse41.c",
- "dsp/lossless_mips_dsp_r2.c",
- "dsp/lossless_msa.c",
- "dsp/lossless_neon.c",
- "dsp/lossless_sse2.c",
- "dsp/lossless_sse41.c",
- "dsp/rescaler.c",
- "dsp/rescaler_mips32.c",
- "dsp/rescaler_mips_dsp_r2.c",
- "dsp/rescaler_msa.c",
- "dsp/rescaler_neon.c",
- "dsp/rescaler_sse2.c",
- "dsp/ssim.c",
- "dsp/ssim_sse2.c",
- "dsp/upsampling.c",
- "dsp/upsampling_mips_dsp_r2.c",
- "dsp/upsampling_msa.c",
- "dsp/upsampling_neon.c",
- "dsp/upsampling_sse2.c",
- "dsp/upsampling_sse41.c",
- "dsp/yuv.c",
- "dsp/yuv_mips32.c",
- "dsp/yuv_mips_dsp_r2.c",
- "dsp/yuv_neon.c",
- "dsp/yuv_sse2.c",
- "dsp/yuv_sse41.c",
- "enc/alpha_enc.c",
- "enc/analysis_enc.c",
- "enc/backward_references_cost_enc.c",
- "enc/backward_references_enc.c",
- "enc/config_enc.c",
- "enc/cost_enc.c",
- "enc/filter_enc.c",
- "enc/frame_enc.c",
- "enc/histogram_enc.c",
- "enc/iterator_enc.c",
- "enc/near_lossless_enc.c",
- "enc/picture_csp_enc.c",
- "enc/picture_enc.c",
- "enc/picture_psnr_enc.c",
- "enc/picture_rescale_enc.c",
- "enc/picture_tools_enc.c",
- "enc/predictor_enc.c",
- "enc/quant_enc.c",
- "enc/syntax_enc.c",
- "enc/token_enc.c",
- "enc/tree_enc.c",
- "enc/vp8l_enc.c",
- "enc/webp_enc.c",
- "mux/anim_encode.c",
- "mux/muxedit.c",
- "mux/muxinternal.c",
- "mux/muxread.c",
- "utils/bit_reader_utils.c",
- "utils/bit_writer_utils.c",
- "utils/color_cache_utils.c",
- "utils/filters_utils.c",
- "utils/huffman_encode_utils.c",
- "utils/huffman_utils.c",
- "utils/quant_levels_dec_utils.c",
- "utils/quant_levels_utils.c",
- "utils/random_utils.c",
- "utils/rescaler_utils.c",
- "utils/thread_utils.c",
- "utils/utils.c",
+ "sharpyuv/sharpyuv.c",
+ "sharpyuv/sharpyuv_csp.c",
+ "sharpyuv/sharpyuv_dsp.c",
+ "sharpyuv/sharpyuv_gamma.c",
+ "sharpyuv/sharpyuv_neon.c",
+ "sharpyuv/sharpyuv_sse2.c",
+ "src/dec/alpha_dec.c",
+ "src/dec/buffer_dec.c",
+ "src/dec/frame_dec.c",
+ "src/dec/idec_dec.c",
+ "src/dec/io_dec.c",
+ "src/dec/quant_dec.c",
+ "src/dec/tree_dec.c",
+ "src/dec/vp8_dec.c",
+ "src/dec/vp8l_dec.c",
+ "src/dec/webp_dec.c",
+ "src/demux/anim_decode.c",
+ "src/demux/demux.c",
+ "src/dsp/alpha_processing.c",
+ "src/dsp/alpha_processing_mips_dsp_r2.c",
+ "src/dsp/alpha_processing_neon.c",
+ "src/dsp/alpha_processing_sse2.c",
+ "src/dsp/alpha_processing_sse41.c",
+ "src/dsp/cost.c",
+ "src/dsp/cost_mips32.c",
+ "src/dsp/cost_mips_dsp_r2.c",
+ "src/dsp/cost_neon.c",
+ "src/dsp/cost_sse2.c",
+ "src/dsp/cpu.c",
+ "src/dsp/dec.c",
+ "src/dsp/dec_clip_tables.c",
+ "src/dsp/dec_mips32.c",
+ "src/dsp/dec_mips_dsp_r2.c",
+ "src/dsp/dec_msa.c",
+ "src/dsp/dec_neon.c",
+ "src/dsp/dec_sse2.c",
+ "src/dsp/dec_sse41.c",
+ "src/dsp/enc.c",
+ "src/dsp/enc_mips32.c",
+ "src/dsp/enc_mips_dsp_r2.c",
+ "src/dsp/enc_msa.c",
+ "src/dsp/enc_neon.c",
+ "src/dsp/enc_sse2.c",
+ "src/dsp/enc_sse41.c",
+ "src/dsp/filters.c",
+ "src/dsp/filters_mips_dsp_r2.c",
+ "src/dsp/filters_msa.c",
+ "src/dsp/filters_neon.c",
+ "src/dsp/filters_sse2.c",
+ "src/dsp/lossless.c",
+ "src/dsp/lossless_enc.c",
+ "src/dsp/lossless_enc_mips32.c",
+ "src/dsp/lossless_enc_mips_dsp_r2.c",
+ "src/dsp/lossless_enc_msa.c",
+ "src/dsp/lossless_enc_neon.c",
+ "src/dsp/lossless_enc_sse2.c",
+ "src/dsp/lossless_enc_sse41.c",
+ "src/dsp/lossless_mips_dsp_r2.c",
+ "src/dsp/lossless_msa.c",
+ "src/dsp/lossless_neon.c",
+ "src/dsp/lossless_sse2.c",
+ "src/dsp/lossless_sse41.c",
+ "src/dsp/rescaler.c",
+ "src/dsp/rescaler_mips32.c",
+ "src/dsp/rescaler_mips_dsp_r2.c",
+ "src/dsp/rescaler_msa.c",
+ "src/dsp/rescaler_neon.c",
+ "src/dsp/rescaler_sse2.c",
+ "src/dsp/ssim.c",
+ "src/dsp/ssim_sse2.c",
+ "src/dsp/upsampling.c",
+ "src/dsp/upsampling_mips_dsp_r2.c",
+ "src/dsp/upsampling_msa.c",
+ "src/dsp/upsampling_neon.c",
+ "src/dsp/upsampling_sse2.c",
+ "src/dsp/upsampling_sse41.c",
+ "src/dsp/yuv.c",
+ "src/dsp/yuv_mips32.c",
+ "src/dsp/yuv_mips_dsp_r2.c",
+ "src/dsp/yuv_neon.c",
+ "src/dsp/yuv_sse2.c",
+ "src/dsp/yuv_sse41.c",
+ "src/enc/alpha_enc.c",
+ "src/enc/analysis_enc.c",
+ "src/enc/backward_references_cost_enc.c",
+ "src/enc/backward_references_enc.c",
+ "src/enc/config_enc.c",
+ "src/enc/cost_enc.c",
+ "src/enc/filter_enc.c",
+ "src/enc/frame_enc.c",
+ "src/enc/histogram_enc.c",
+ "src/enc/iterator_enc.c",
+ "src/enc/near_lossless_enc.c",
+ "src/enc/picture_csp_enc.c",
+ "src/enc/picture_enc.c",
+ "src/enc/picture_psnr_enc.c",
+ "src/enc/picture_rescale_enc.c",
+ "src/enc/picture_tools_enc.c",
+ "src/enc/predictor_enc.c",
+ "src/enc/quant_enc.c",
+ "src/enc/syntax_enc.c",
+ "src/enc/token_enc.c",
+ "src/enc/tree_enc.c",
+ "src/enc/vp8l_enc.c",
+ "src/enc/webp_enc.c",
+ "src/mux/anim_encode.c",
+ "src/mux/muxedit.c",
+ "src/mux/muxinternal.c",
+ "src/mux/muxread.c",
+ "src/utils/bit_reader_utils.c",
+ "src/utils/bit_writer_utils.c",
+ "src/utils/color_cache_utils.c",
+ "src/utils/filters_utils.c",
+ "src/utils/huffman_encode_utils.c",
+ "src/utils/huffman_utils.c",
+ "src/utils/quant_levels_dec_utils.c",
+ "src/utils/quant_levels_utils.c",
+ "src/utils/random_utils.c",
+ "src/utils/rescaler_utils.c",
+ "src/utils/thread_utils.c",
+ "src/utils/utils.c",
]
- thirdparty_sources = [thirdparty_dir + "src/" + file for file in thirdparty_sources]
+ thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
env_webp.Prepend(CPPPATH=[thirdparty_dir, thirdparty_dir + "src/"])
diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp
index 778d562278..705ab508ab 100644
--- a/modules/webp/image_loader_webp.cpp
+++ b/modules/webp/image_loader_webp.cpp
@@ -48,7 +48,7 @@ static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) {
return img;
}
-Error ImageLoaderWebP::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) {
+Error ImageLoaderWebP::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) {
Vector<uint8_t> src_image;
uint64_t src_image_len = f->get_length();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h
index 9a5dc6cd7c..d868ae3f7f 100644
--- a/modules/webp/image_loader_webp.h
+++ b/modules/webp/image_loader_webp.h
@@ -35,7 +35,7 @@
class ImageLoaderWebP : public ImageFormatLoader {
public:
- virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale);
+ virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderWebP();
};
diff --git a/platform/android/README.md b/platform/android/README.md
index 343e588553..f6aabab708 100644
--- a/platform/android/README.md
+++ b/platform/android/README.md
@@ -3,6 +3,13 @@
This folder contains the Java and C++ (JNI) code for the Android platform port,
using [Gradle](https://gradle.org/) as a build system.
+## Documentation
+
+- [Compiling for Android](https://docs.godotengine.org/en/latest/development/compiling/compiling_for_android.html)
+ - Instructions on building this platform port from source.
+- [Exporting for Android](https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_android.html)
+ - Instructions on using the compiled export templates to export a project.
+
## Artwork license
[`logo.png`](logo.png) and [`run_icon.png`](run_icon.png) are licensed under
diff --git a/platform/android/SCsub b/platform/android/SCsub
index d370a4d18d..344ca036de 100644
--- a/platform/android/SCsub
+++ b/platform/android/SCsub
@@ -41,13 +41,13 @@ lib = env_android.add_shared_library("#bin/libgodot", [android_objects], SHLIBSU
env.Depends(lib, thirdparty_obj)
lib_arch_dir = ""
-if env["android_arch"] == "armv7":
+if env["arch"] == "arm32":
lib_arch_dir = "armeabi-v7a"
-elif env["android_arch"] == "arm64v8":
+elif env["arch"] == "arm64":
lib_arch_dir = "arm64-v8a"
-elif env["android_arch"] == "x86":
+elif env["arch"] == "x86_32":
lib_arch_dir = "x86"
-elif env["android_arch"] == "x86_64":
+elif env["arch"] == "x86_64":
lib_arch_dir = "x86_64"
else:
print("WARN: Architecture not suitable for embedding into APK; keeping .so at \\bin")
diff --git a/platform/android/detect.py b/platform/android/detect.py
index 2ff5bf59ea..ad63821162 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -22,7 +22,6 @@ def get_opts():
return [
("ANDROID_SDK_ROOT", "Path to the Android SDK", get_env_android_sdk_root()),
("ndk_platform", 'Target platform (android-<api>, e.g. "android-24")', "android-24"),
- EnumVariable("android_arch", "Target architecture", "arm64v8", ("armv7", "arm64v8", "x86", "x86_64")),
]
@@ -46,6 +45,7 @@ def get_ndk_version():
def get_flags():
return [
+ ("arch", "arm64"), # Default for convenience.
("tools", False),
]
@@ -75,35 +75,37 @@ def install_ndk_if_needed(env):
def configure(env):
+ # Validate arch.
+ supported_arches = ["x86_32", "x86_64", "arm32", "arm64"]
+ if env["arch"] not in supported_arches:
+ print(
+ 'Unsupported CPU architecture "%s" for Android. Supported architectures are: %s.'
+ % (env["arch"], ", ".join(supported_arches))
+ )
+ sys.exit()
+
install_ndk_if_needed(env)
ndk_root = env["ANDROID_NDK_ROOT"]
# Architecture
- if env["android_arch"] not in ["armv7", "arm64v8", "x86", "x86_64"]:
- env["android_arch"] = "arm64v8"
-
- print("Building for Android, platform " + env["ndk_platform"] + " (" + env["android_arch"] + ")")
-
- if get_min_sdk_version(env["ndk_platform"]) < 21:
- if env["android_arch"] == "x86_64" or env["android_arch"] == "arm64v8":
- print(
- "WARNING: android_arch="
- + env["android_arch"]
- + " is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21"
- )
- env["ndk_platform"] = "android-21"
+ if get_min_sdk_version(env["ndk_platform"]) < 21 and env["arch"] in ["x86_64", "arm64"]:
+ print(
+ 'WARNING: arch="%s" is not supported with "ndk_platform" lower than "android-21". Forcing platform 21.'
+ % env["arch"]
+ )
+ env["ndk_platform"] = "android-21"
- if env["android_arch"] == "armv7":
+ if env["arch"] == "arm32":
target_triple = "armv7a-linux-androideabi"
env.extra_suffix = ".armv7" + env.extra_suffix
- elif env["android_arch"] == "arm64v8":
+ elif env["arch"] == "arm64":
target_triple = "aarch64-linux-android"
env.extra_suffix = ".armv8" + env.extra_suffix
- elif env["android_arch"] == "x86":
+ elif env["arch"] == "x86_32":
target_triple = "i686-linux-android"
env.extra_suffix = ".x86" + env.extra_suffix
- elif env["android_arch"] == "x86_64":
+ elif env["arch"] == "x86_64":
target_triple = "x86_64-linux-android"
env.extra_suffix = ".x86_64" + env.extra_suffix
@@ -176,14 +178,14 @@ def configure(env):
if get_min_sdk_version(env["ndk_platform"]) >= 24:
env.Append(CPPDEFINES=[("_FILE_OFFSET_BITS", 64)])
- if env["android_arch"] == "x86":
+ if env["arch"] == "x86_32":
# The NDK adds this if targeting API < 24, so we can drop it when Godot targets it at least
env.Append(CCFLAGS=["-mstackrealign"])
- elif env["android_arch"] == "armv7":
+ elif env["arch"] == "arm32":
env.Append(CCFLAGS="-march=armv7-a -mfloat-abi=softfp".split())
env.Append(CPPDEFINES=["__ARM_ARCH_7__", "__ARM_ARCH_7A__"])
env.Append(CPPDEFINES=["__ARM_NEON__"])
- elif env["android_arch"] == "arm64v8":
+ elif env["arch"] == "arm64":
env.Append(CCFLAGS=["-mfix-cortex-a53-835769"])
env.Append(CPPDEFINES=["__ARM_ARCH_8A__"])
diff --git a/platform/android/dir_access_jandroid.cpp b/platform/android/dir_access_jandroid.cpp
index eb344d3b43..428135de56 100644
--- a/platform/android/dir_access_jandroid.cpp
+++ b/platform/android/dir_access_jandroid.cpp
@@ -135,6 +135,20 @@ String DirAccessJAndroid::get_drive(int p_drive) {
}
}
+String DirAccessJAndroid::get_current_dir(bool p_include_drive) const {
+ String base = _get_root_path();
+ String bd = current_dir;
+ if (!base.is_empty()) {
+ bd = current_dir.replace_first(base, "");
+ }
+
+ if (bd.begins_with("/")) {
+ return _get_root_string() + bd.substr(1, bd.length());
+ } else {
+ return _get_root_string() + bd;
+ }
+}
+
Error DirAccessJAndroid::change_dir(String p_dir) {
String new_dir = get_absolute_path(p_dir);
if (new_dir == current_dir) {
diff --git a/platform/android/dir_access_jandroid.h b/platform/android/dir_access_jandroid.h
index d469c9d317..5b7b4a9c4d 100644
--- a/platform/android/dir_access_jandroid.h
+++ b/platform/android/dir_access_jandroid.h
@@ -67,6 +67,7 @@ public:
virtual int get_drive_count() override;
virtual String get_drive(int p_drive) override;
+ virtual String get_current_dir(bool p_include_drive = true) const override; ///< return current dir location
virtual Error change_dir(String p_dir) override; ///< can be relative or absolute, return false on success
diff --git a/platform/android/display_server_android.cpp b/platform/android/display_server_android.cpp
index b51dd18af6..d3bce12de1 100644
--- a/platform/android/display_server_android.cpp
+++ b/platform/android/display_server_android.cpp
@@ -83,7 +83,7 @@ bool DisplayServerAndroid::tts_is_paused() const {
return TTS_Android::is_paused();
}
-Array DisplayServerAndroid::tts_get_voices() const {
+TypedArray<Dictionary> DisplayServerAndroid::tts_get_voices() const {
return TTS_Android::get_voices();
}
@@ -136,7 +136,7 @@ bool DisplayServerAndroid::clipboard_has() const {
}
}
-Array DisplayServerAndroid::get_display_cutouts() const {
+TypedArray<Rect2> DisplayServerAndroid::get_display_cutouts() const {
GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java();
ERR_FAIL_NULL_V(godot_io_java, Array());
return godot_io_java->get_display_cutouts();
diff --git a/platform/android/display_server_android.h b/platform/android/display_server_android.h
index 2f30642319..6e14ba3e23 100644
--- a/platform/android/display_server_android.h
+++ b/platform/android/display_server_android.h
@@ -93,7 +93,7 @@ public:
virtual bool tts_is_speaking() const override;
virtual bool tts_is_paused() const override;
- virtual Array tts_get_voices() const override;
+ virtual TypedArray<Dictionary> tts_get_voices() const override;
virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
virtual void tts_pause() override;
@@ -104,7 +104,7 @@ public:
virtual String clipboard_get() const override;
virtual bool clipboard_has() const override;
- virtual Array get_display_cutouts() const override;
+ virtual TypedArray<Rect2> get_display_cutouts() const override;
virtual Rect2i get_display_safe_area() const override;
virtual void screen_set_keep_on(bool p_enable) override;
diff --git a/platform/android/export/export_plugin.cpp b/platform/android/export/export_plugin.cpp
index 685b1f01af..016af40b52 100644
--- a/platform/android/export/export_plugin.cpp
+++ b/platform/android/export/export_plugin.cpp
@@ -588,9 +588,9 @@ zip_fileinfo EditorExportPlatformAndroid::get_zip_fileinfo() {
Vector<String> EditorExportPlatformAndroid::get_abis() {
Vector<String> abis;
- abis.push_back("armeabi-v7a");
- abis.push_back("arm64-v8a");
- abis.push_back("x86");
+ abis.push_back("arm32");
+ abis.push_back("arm64");
+ abis.push_back("x86_32");
abis.push_back("x86_64");
return abis;
}
@@ -1710,7 +1710,7 @@ void EditorExportPlatformAndroid::get_export_options(List<ExportOption> *r_optio
const String abi = abis[i];
// All Android devices supporting Vulkan run 64-bit Android,
// so there is usually no point in exporting for 32-bit Android.
- const bool is_default = abi == "arm64-v8a";
+ const bool is_default = abi == "arm64";
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, vformat("%s/%s", PNAME("architectures"), abi)), is_default));
}
diff --git a/platform/android/java/build.gradle b/platform/android/java/build.gradle
index da30bd3a95..81c7130c03 100644
--- a/platform/android/java/build.gradle
+++ b/platform/android/java/build.gradle
@@ -28,7 +28,7 @@ allprojects {
}
ext {
- supportedAbis = ["armv7", "arm64v8", "x86", "x86_64"]
+ supportedAbis = ["arm32", "arm64", "x86_32", "x86_64"]
supportedTargetsMap = [release: "release", dev: "debug", debug: "release_debug"]
supportedFlavors = ["editor", "template"]
@@ -37,7 +37,7 @@ ext {
// If building manually on the command line, it's recommended to use the
// `./gradlew generateGodotTemplates` build command instead after running the `scons` command(s).
// The {selectedAbis} values must be from the {supportedAbis} values.
- selectedAbis = ["arm64v8"]
+ selectedAbis = ["arm64"]
}
def rootDir = "../../.."
diff --git a/platform/android/java/lib/build.gradle b/platform/android/java/lib/build.gradle
index 6b82326a27..318ae1143f 100644
--- a/platform/android/java/lib/build.gradle
+++ b/platform/android/java/lib/build.gradle
@@ -159,7 +159,7 @@ android {
def taskName = getSconsTaskName(flavorName, buildType, selectedAbi)
tasks.create(name: taskName, type: Exec) {
executable sconsExecutableFile.absolutePath
- args "--directory=${pathToRootDir}", "platform=android", "tools=${toolsFlag}", "target=${sconsTarget}", "android_arch=${selectedAbi}", "-j" + Runtime.runtime.availableProcessors()
+ args "--directory=${pathToRootDir}", "platform=android", "tools=${toolsFlag}", "target=${sconsTarget}", "arch=${selectedAbi}", "-j" + Runtime.runtime.availableProcessors()
}
// Schedule the tasks so the generated libs are present before the aar file is packaged.
diff --git a/platform/android/java_godot_io_wrapper.cpp b/platform/android/java_godot_io_wrapper.cpp
index 5877c15114..cea64a7f22 100644
--- a/platform/android/java_godot_io_wrapper.cpp
+++ b/platform/android/java_godot_io_wrapper.cpp
@@ -165,8 +165,8 @@ float GodotIOJavaWrapper::get_screen_refresh_rate(float fallback) {
return fallback;
}
-Array GodotIOJavaWrapper::get_display_cutouts() {
- Array result;
+TypedArray<Rect2> GodotIOJavaWrapper::get_display_cutouts() {
+ TypedArray<Rect2> result;
ERR_FAIL_NULL_V(_get_display_cutouts, result);
JNIEnv *env = get_jni_env();
ERR_FAIL_NULL_V(env, result);
diff --git a/platform/android/java_godot_io_wrapper.h b/platform/android/java_godot_io_wrapper.h
index dc68f4d90d..9a1a877b6f 100644
--- a/platform/android/java_godot_io_wrapper.h
+++ b/platform/android/java_godot_io_wrapper.h
@@ -38,7 +38,7 @@
#include <jni.h>
#include "core/math/rect2i.h"
-#include "core/variant/array.h"
+#include "core/variant/typed_array.h"
#include "string_android.h"
// Class that makes functions in java/src/org/godotengine/godot/GodotIO.java callable from C++
@@ -78,7 +78,7 @@ public:
int get_screen_dpi();
float get_scaled_density();
float get_screen_refresh_rate(float fallback);
- Array get_display_cutouts();
+ TypedArray<Rect2> get_display_cutouts();
Rect2i get_display_safe_area();
String get_unique_id();
bool has_vk();
diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp
index 0f551e7f4f..f94614c741 100644
--- a/platform/android/os_android.cpp
+++ b/platform/android/os_android.cpp
@@ -370,15 +370,15 @@ bool OS_Android::_check_internal_feature_support(const String &p_feature) {
return true;
}
#if defined(__aarch64__)
- if (p_feature == "arm64-v8a") {
+ if (p_feature == "arm64-v8a" || p_feature == "arm64") {
return true;
}
#elif defined(__ARM_ARCH_7A__)
- if (p_feature == "armeabi-v7a" || p_feature == "armeabi") {
+ if (p_feature == "armeabi-v7a" || p_feature == "armeabi" || p_feature == "arm32") {
return true;
}
#elif defined(__arm__)
- if (p_feature == "armeabi") {
+ if (p_feature == "armeabi" || p_feature == "arm") {
return true;
}
#endif
diff --git a/platform/ios/README.md b/platform/ios/README.md
new file mode 100644
index 0000000000..82c275ad31
--- /dev/null
+++ b/platform/ios/README.md
@@ -0,0 +1,14 @@
+# iOS platform port
+
+This folder contains the C++, Objective-C and Objective-C++ code for the iOS
+platform port.
+
+See also [`misc/dist/ios_xcode`](/misc/dist/ios_xcode) folder for the Xcode
+project template used for packaging the iOS export templates.
+
+## Documentation
+
+- [Compiling for iOS](https://docs.godotengine.org/en/latest/development/compiling/compiling_for_ios.html)
+ - Instructions on building this platform port from source.
+- [Exporting for iOS](https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_ios.html)
+ - Instructions on using the compiled export templates to export a project.
diff --git a/platform/ios/detect.py b/platform/ios/detect.py
index 67c90b10a0..1a8d24d12d 100644
--- a/platform/ios/detect.py
+++ b/platform/ios/detect.py
@@ -36,12 +36,22 @@ def get_opts():
def get_flags():
return [
+ ("arch", "arm64"), # Default for convenience.
("tools", False),
("use_volk", False),
]
def configure(env):
+ # Validate arch.
+ supported_arches = ["x86_64", "arm64"]
+ if env["arch"] not in supported_arches:
+ print(
+ 'Unsupported CPU architecture "%s" for iOS. Supported architectures are: %s.'
+ % (env["arch"], ", ".join(supported_arches))
+ )
+ sys.exit()
+
## Build type
if env["target"].startswith("release"):
@@ -64,11 +74,6 @@ def configure(env):
env.Append(CCFLAGS=["-flto"])
env.Append(LINKFLAGS=["-flto"])
- ## Architecture
- env["bits"] = "64"
- if env["arch"] != "x86_64":
- env["arch"] = "arm64"
-
## Compiler configuration
# Save this in environment for use by other modules
diff --git a/platform/ios/display_server_ios.h b/platform/ios/display_server_ios.h
index bbb2dd3ab3..f3624f24ab 100644
--- a/platform/ios/display_server_ios.h
+++ b/platform/ios/display_server_ios.h
@@ -127,7 +127,7 @@ public:
virtual bool tts_is_speaking() const override;
virtual bool tts_is_paused() const override;
- virtual Array tts_get_voices() const override;
+ virtual TypedArray<Dictionary> tts_get_voices() const override;
virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
virtual void tts_pause() override;
diff --git a/platform/ios/display_server_ios.mm b/platform/ios/display_server_ios.mm
index 6ce7e676a2..74d6bc2e97 100644
--- a/platform/ios/display_server_ios.mm
+++ b/platform/ios/display_server_ios.mm
@@ -336,8 +336,8 @@ bool DisplayServerIOS::tts_is_paused() const {
return [tts isPaused];
}
-Array DisplayServerIOS::tts_get_voices() const {
- ERR_FAIL_COND_V(!tts, Array());
+TypedArray<Dictionary> DisplayServerIOS::tts_get_voices() const {
+ ERR_FAIL_COND_V(!tts, TypedArray<Dictionary>());
return [tts getVoices];
}
diff --git a/platform/ios/export/export_plugin.cpp b/platform/ios/export/export_plugin.cpp
index 425a977569..db55c7944f 100644
--- a/platform/ios/export/export_plugin.cpp
+++ b/platform/ios/export/export_plugin.cpp
@@ -140,27 +140,27 @@ void EditorExportPlatformIOS::get_export_options(List<ExportOption> *r_options)
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "privacy/photolibrary_usage_description", PROPERTY_HINT_PLACEHOLDER_TEXT, "Provide a message if you need access to the photo library"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::DICTIONARY, "privacy/photolibrary_usage_description_localized", PROPERTY_HINT_LOCALIZABLE_STRING), Dictionary()));
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/iphone_120x120", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPhone/iPod Touch with Retina display
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/iphone_180x180", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPhone with Retina HD display
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/iphone_120x120", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // Home screen on iPhone/iPod Touch with Retina display
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/iphone_180x180", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // Home screen on iPhone with Retina HD display
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/ipad_76x76", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/ipad_152x152", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad with Retina display
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/ipad_167x167", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad Pro
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/ipad_76x76", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // Home screen on iPad
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/ipad_152x152", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // Home screen on iPad with Retina display
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/ipad_167x167", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // Home screen on iPad Pro
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/app_store_1024x1024", PROPERTY_HINT_FILE, "*.png"), "")); // App Store
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/app_store_1024x1024", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // App Store
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/spotlight_40x40", PROPERTY_HINT_FILE, "*.png"), "")); // Spotlight
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/spotlight_80x80", PROPERTY_HINT_FILE, "*.png"), "")); // Spotlight on devices with Retina display
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/spotlight_40x40", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // Spotlight
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/spotlight_80x80", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), "")); // Spotlight on devices with Retina display
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "storyboard/use_launch_screen_storyboard"), false));
r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "storyboard/image_scale_mode", PROPERTY_HINT_ENUM, "Same as Logo,Center,Scale to Fit,Scale to Fill,Scale"), 0));
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "storyboard/custom_image@2x", PROPERTY_HINT_FILE, "*.png"), ""));
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "storyboard/custom_image@3x", PROPERTY_HINT_FILE, "*.png"), ""));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "storyboard/custom_image@2x", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), ""));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "storyboard/custom_image@3x", PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "storyboard/use_custom_bg_color"), false));
r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "storyboard/custom_bg_color"), Color()));
for (uint64_t i = 0; i < sizeof(loading_screen_infos) / sizeof(loading_screen_infos[0]); ++i) {
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, loading_screen_infos[i].preset_key, PROPERTY_HINT_FILE, "*.png"), ""));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, loading_screen_infos[i].preset_key, PROPERTY_HINT_FILE, "*.png,*.jpg,*.jpeg"), ""));
}
}
@@ -531,26 +531,27 @@ struct IconInfo {
const char *actual_size_side;
const char *scale;
const char *unscaled_size;
+ const bool force_opaque;
};
static const IconInfo icon_infos[] = {
// Home screen on iPhone
- { "icons/iphone_120x120", "iphone", "Icon-120.png", "120", "2x", "60x60" },
- { "icons/iphone_120x120", "iphone", "Icon-120.png", "120", "3x", "40x40" },
- { "icons/iphone_180x180", "iphone", "Icon-180.png", "180", "3x", "60x60" },
+ { "icons/iphone_120x120", "iphone", "Icon-120.png", "120", "2x", "60x60", false },
+ { "icons/iphone_120x120", "iphone", "Icon-120.png", "120", "3x", "40x40", false },
+ { "icons/iphone_180x180", "iphone", "Icon-180.png", "180", "3x", "60x60", false },
// Home screen on iPad
- { "icons/ipad_76x76", "ipad", "Icon-76.png", "76", "1x", "76x76" },
- { "icons/ipad_152x152", "ipad", "Icon-152.png", "152", "2x", "76x76" },
- { "icons/ipad_167x167", "ipad", "Icon-167.png", "167", "2x", "83.5x83.5" },
+ { "icons/ipad_76x76", "ipad", "Icon-76.png", "76", "1x", "76x76", false },
+ { "icons/ipad_152x152", "ipad", "Icon-152.png", "152", "2x", "76x76", false },
+ { "icons/ipad_167x167", "ipad", "Icon-167.png", "167", "2x", "83.5x83.5", false },
// App Store
- { "icons/app_store_1024x1024", "ios-marketing", "Icon-1024.png", "1024", "1x", "1024x1024" },
+ { "icons/app_store_1024x1024", "ios-marketing", "Icon-1024.png", "1024", "1x", "1024x1024", true },
// Spotlight
- { "icons/spotlight_40x40", "ipad", "Icon-40.png", "40", "1x", "40x40" },
- { "icons/spotlight_80x80", "iphone", "Icon-80.png", "80", "2x", "40x40" },
- { "icons/spotlight_80x80", "ipad", "Icon-80.png", "80", "2x", "40x40" }
+ { "icons/spotlight_40x40", "ipad", "Icon-40.png", "40", "1x", "40x40", false },
+ { "icons/spotlight_80x80", "iphone", "Icon-80.png", "80", "2x", "40x40", false },
+ { "icons/spotlight_80x80", "ipad", "Icon-80.png", "80", "2x", "40x40", false }
};
Error EditorExportPlatformIOS::_export_icons(const Ref<EditorExportPreset> &p_preset, const String &p_iconset_dir) {
@@ -570,14 +571,17 @@ Error EditorExportPlatformIOS::_export_icons(const Ref<EditorExportPreset> &p_pr
Ref<Image> img = memnew(Image);
Error err = ImageLoader::load_image(icon_path, img);
if (err != OK) {
- ERR_PRINT("Invalid icon (" + String(info.preset_key) + "): '" + icon_path + "'.");
+ add_message(EXPORT_MESSAGE_ERROR, TTR("Export Icons"), vformat("Invalid icon (%s): '%s'.", info.preset_key, icon_path));
+ return ERR_UNCONFIGURED;
+ }
+ if (info.force_opaque && img->detect_alpha() != Image::ALPHA_NONE) {
+ add_message(EXPORT_MESSAGE_ERROR, TTR("Export Icons"), vformat("Icon (%s) must be opaque.", info.preset_key));
return ERR_UNCONFIGURED;
}
img->resize(side_size, side_size);
err = img->save_png(p_iconset_dir + info.export_name);
if (err) {
- String err_str = String("Failed to export icon(" + String(info.preset_key) + "): '" + icon_path + "'.");
- ERR_PRINT(err_str.utf8().get_data());
+ add_message(EXPORT_MESSAGE_ERROR, TTR("Export Icons"), vformat("Failed to export icon (%s): '%s'.", info.preset_key, icon_path));
return err;
}
} else {
@@ -585,11 +589,15 @@ Error EditorExportPlatformIOS::_export_icons(const Ref<EditorExportPreset> &p_pr
Ref<Image> img = memnew(Image);
Error err = ImageLoader::load_image(icon_path, img);
if (err != OK) {
- ERR_PRINT("Invalid icon (" + String(info.preset_key) + "): '" + icon_path + "'.");
+ add_message(EXPORT_MESSAGE_ERROR, TTR("Export Icons"), vformat("Invalid icon (%s): '%s'.", info.preset_key, icon_path));
+ return ERR_UNCONFIGURED;
+ }
+ if (info.force_opaque && img->detect_alpha() != Image::ALPHA_NONE) {
+ add_message(EXPORT_MESSAGE_ERROR, TTR("Export Icons"), vformat("Icon (%s) must be opaque.", info.preset_key));
return ERR_UNCONFIGURED;
}
if (img->get_width() != side_size || img->get_height() != side_size) {
- WARN_PRINT("Icon (" + String(info.preset_key) + "): '" + icon_path + "' has incorrect size (" + String::num_int64(img->get_width()) + "x" + String::num_int64(img->get_height()) + ") and was automatically resized to " + String::num_int64(side_size) + "x" + String::num_int64(side_size) + ".");
+ add_message(EXPORT_MESSAGE_WARNING, TTR("Export Icons"), vformat("Icon (%s): '%s' has incorrect size %s and was automatically resized to %s.", info.preset_key, icon_path, img->get_size(), Vector2i(side_size, side_size)));
img->resize(side_size, side_size);
err = img->save_png(p_iconset_dir + info.export_name);
} else {
@@ -597,8 +605,7 @@ Error EditorExportPlatformIOS::_export_icons(const Ref<EditorExportPreset> &p_pr
}
if (err) {
- String err_str = String("Failed to export icon(" + String(info.preset_key) + "): '" + icon_path + "'.");
- ERR_PRINT(err_str.utf8().get_data());
+ add_message(EXPORT_MESSAGE_ERROR, TTR("Export Icons"), vformat("Failed to export icon (%s): '%s'.", info.preset_key, icon_path));
return err;
}
}
diff --git a/platform/javascript/README.md b/platform/javascript/README.md
index f181bea9e0..812ab6778b 100644
--- a/platform/javascript/README.md
+++ b/platform/javascript/README.md
@@ -5,8 +5,15 @@ compiled using [Emscripten](https://emscripten.org/).
It also contains a ESLint linting setup (see [`package.json`](package.json)).
-See also [`misc/dist/html`](/misc/dist/html) folder for files used by this platform
-such as the HTML5 shell.
+See also [`misc/dist/html`](/misc/dist/html) folder for additional files used by
+this platform such as the HTML5 shell.
+
+## Documentation
+
+- [Compiling for the Web](https://docs.godotengine.org/en/latest/development/compiling/compiling_for_web.html)
+ - Instructions on building this platform port from source.
+- [Exporting for the Web](https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_web.html)
+ - Instructions on using the compiled export templates to export a project.
## Artwork license
diff --git a/platform/javascript/detect.py b/platform/javascript/detect.py
index a769260f01..048c9c2eb4 100644
--- a/platform/javascript/detect.py
+++ b/platform/javascript/detect.py
@@ -46,6 +46,7 @@ def get_opts():
def get_flags():
return [
+ ("arch", "wasm32"),
("tools", False),
("builtin_pcre2_with_jit", False),
("vulkan", False),
@@ -53,6 +54,15 @@ def get_flags():
def configure(env):
+ # Validate arch.
+ supported_arches = ["wasm32"]
+ if env["arch"] not in supported_arches:
+ print(
+ 'Unsupported CPU architecture "%s" for iOS. Supported architectures are: %s.'
+ % (env["arch"], ", ".join(supported_arches))
+ )
+ sys.exit()
+
try:
env["initial_memory"] = int(env["initial_memory"])
except Exception:
diff --git a/platform/javascript/display_server_javascript.cpp b/platform/javascript/display_server_javascript.cpp
index 48f637fcfe..30240ad2db 100644
--- a/platform/javascript/display_server_javascript.cpp
+++ b/platform/javascript/display_server_javascript.cpp
@@ -296,7 +296,7 @@ void DisplayServerJavaScript::update_voices_callback(int p_size, const char **p_
}
}
-Array DisplayServerJavaScript::tts_get_voices() const {
+TypedArray<Dictionary> DisplayServerJavaScript::tts_get_voices() const {
godot_js_tts_get_voices(update_voices_callback);
return voices;
}
diff --git a/platform/javascript/display_server_javascript.h b/platform/javascript/display_server_javascript.h
index fb7f5d02a8..cbb91477b7 100644
--- a/platform/javascript/display_server_javascript.h
+++ b/platform/javascript/display_server_javascript.h
@@ -124,7 +124,7 @@ public:
// tts
virtual bool tts_is_speaking() const override;
virtual bool tts_is_paused() const override;
- virtual Array tts_get_voices() const override;
+ virtual TypedArray<Dictionary> tts_get_voices() const override;
virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
virtual void tts_pause() override;
diff --git a/platform/javascript/js/libs/library_godot_display.js b/platform/javascript/js/libs/library_godot_display.js
index c7729a8c5b..768eaf9e1d 100644
--- a/platform/javascript/js/libs/library_godot_display.js
+++ b/platform/javascript/js/libs/library_godot_display.js
@@ -336,26 +336,12 @@ const GodotDisplay = {
$GodotDisplay__deps: ['$GodotConfig', '$GodotRuntime', '$GodotDisplayCursor', '$GodotEventListeners', '$GodotDisplayScreen', '$GodotDisplayVK'],
$GodotDisplay: {
window_icon: '',
- findDPI: function () {
- function testDPI(dpi) {
- return window.matchMedia(`(max-resolution: ${dpi}dpi)`).matches;
- }
- function bisect(low, high, func) {
- const mid = parseInt(((high - low) / 2) + low, 10);
- if (high - low <= 1) {
- return func(high) ? high : low;
- }
- if (func(mid)) {
- return bisect(low, mid, func);
- }
- return bisect(mid, high, func);
- }
- try {
- const dpi = bisect(0, 800, testDPI);
- return dpi >= 96 ? dpi : 96;
- } catch (e) {
- return 96;
- }
+ getDPI: function () {
+ // devicePixelRatio is given in dppx
+ // https://drafts.csswg.org/css-values/#resolution
+ // > due to the 1:96 fixed ratio of CSS *in* to CSS *px*, 1dppx is equivalent to 96dpi.
+ const dpi = Math.round(window.devicePixelRatio * 96);
+ return dpi >= 96 ? dpi : 96;
},
},
@@ -461,7 +447,7 @@ const GodotDisplay = {
godot_js_display_screen_dpi_get__sig: 'i',
godot_js_display_screen_dpi_get: function () {
- return GodotDisplay.findDPI();
+ return GodotDisplay.getDPI();
},
godot_js_display_pixel_ratio_get__sig: 'f',
diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h
index 35e13c94fc..d932745177 100644
--- a/platform/javascript/os_javascript.h
+++ b/platform/javascript/os_javascript.h
@@ -98,7 +98,6 @@ public:
String get_user_data_dir() const override;
bool is_userfs_persistent() const override;
- bool is_single_window() const override { return true; }
void alert(const String &p_alert, const String &p_title = "ALERT!") override;
diff --git a/platform/linuxbsd/README.md b/platform/linuxbsd/README.md
index 0d3fb37be5..efa8682062 100644
--- a/platform/linuxbsd/README.md
+++ b/platform/linuxbsd/README.md
@@ -2,10 +2,20 @@
This folder contains the C++ code for the Linux/*BSD platform port.
+See also [`misc/dist/linux`](/misc/dist/linux) folder for additional files
+used by this platform.
+
+## Documentation
+
+- [Compiling for Linux/*BSD](https://docs.godotengine.org/en/latest/development/compiling/compiling_for_linuxbsd.html)
+ - Instructions on building this platform port from source.
+- [Exporting for Linux/*BSD](https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_linux.html)
+ - Instructions on using the compiled export templates to export a project.
+
## Artwork license
[`logo.png`](logo.png) is derived from the [Linux logo](https://isc.tamu.edu/~lewing/linux/):
> Permission to use and/or modify this image is granted provided you acknowledge me
- <lewing@isc.tamu.edu> and [The GIMP](https://isc.tamu.edu/~lewing/gimp/)
- if someone asks.
+> <lewing@isc.tamu.edu> and [The GIMP](https://isc.tamu.edu/~lewing/gimp/)
+> if someone asks.
diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py
index 00e2b9e6eb..8563cc3cb2 100644
--- a/platform/linuxbsd/detect.py
+++ b/platform/linuxbsd/detect.py
@@ -2,6 +2,7 @@ import os
import platform
import sys
from methods import get_compiler_version, using_gcc
+from platform_methods import detect_arch
def is_active():
@@ -52,10 +53,21 @@ def get_opts():
def get_flags():
- return []
+ return [
+ ("arch", detect_arch()),
+ ]
def configure(env):
+ # Validate arch.
+ supported_arches = ["x86_32", "x86_64", "arm32", "arm64", "rv64", "ppc32", "ppc64"]
+ if env["arch"] not in supported_arches:
+ print(
+ 'Unsupported CPU architecture "%s" for Linux / *BSD. Supported architectures are: %s.'
+ % (env["arch"], ", ".join(supported_arches))
+ )
+ sys.exit()
+
## Build type
if env["target"] == "release":
@@ -80,23 +92,7 @@ def configure(env):
env.Prepend(CCFLAGS=["-g3"])
env.Append(LINKFLAGS=["-rdynamic"])
- ## Architecture
-
- is64 = sys.maxsize > 2**32
- if env["bits"] == "default":
- env["bits"] = "64" if is64 else "32"
-
- machines = {
- "riscv64": "rv64",
- "ppc64le": "ppc64",
- "ppc64": "ppc64",
- "ppcle": "ppc",
- "ppc": "ppc",
- }
-
- if env["arch"] == "" and platform.machine() in machines:
- env["arch"] = machines[platform.machine()]
-
+ # CPU architecture flags.
if env["arch"] == "rv64":
# G = General-purpose extensions, C = Compression extension (very common).
env.Append(CCFLAGS=["-march=rv64gc"])
@@ -262,8 +258,7 @@ def configure(env):
env["builtin_libvorbis"] = False # Needed to link against system libtheora
env.ParseConfig("pkg-config theora theoradec --cflags --libs")
else:
- list_of_x86 = ["x86_64", "x86", "i386", "i586"]
- if any(platform.machine() in s for s in list_of_x86):
+ if env["arch"] in ["x86_64", "x86_32"]:
env["x86_libtheora_opt_gcc"] = True
if not env["builtin_libvorbis"]:
@@ -405,11 +400,12 @@ def configure(env):
env.Append(LINKFLAGS=["-T", "platform/linuxbsd/pck_embed.legacy.ld"])
## Cross-compilation
-
- if is64 and env["bits"] == "32":
+ # TODO: Support cross-compilation on architectures other than x86.
+ host_is_64_bit = sys.maxsize > 2**32
+ if host_is_64_bit and env["arch"] == "x86_32":
env.Append(CCFLAGS=["-m32"])
env.Append(LINKFLAGS=["-m32", "-L/usr/lib/i386-linux-gnu"])
- elif not is64 and env["bits"] == "64":
+ elif not host_is_64_bit and env["arch"] == "x86_64":
env.Append(CCFLAGS=["-m64"])
env.Append(LINKFLAGS=["-m64", "-L/usr/lib/i686-linux-gnu"])
diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp
index 8efbd2e3c5..63998e2fde 100644
--- a/platform/linuxbsd/display_server_x11.cpp
+++ b/platform/linuxbsd/display_server_x11.cpp
@@ -322,8 +322,8 @@ bool DisplayServerX11::tts_is_paused() const {
return tts->is_paused();
}
-Array DisplayServerX11::tts_get_voices() const {
- ERR_FAIL_COND_V(!tts, Array());
+TypedArray<Dictionary> DisplayServerX11::tts_get_voices() const {
+ ERR_FAIL_COND_V(!tts, TypedArray<Dictionary>());
return tts->get_voices();
}
diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h
index 9ce6a557db..0174cfb881 100644
--- a/platform/linuxbsd/display_server_x11.h
+++ b/platform/linuxbsd/display_server_x11.h
@@ -308,7 +308,7 @@ public:
#ifdef SPEECHD_ENABLED
virtual bool tts_is_speaking() const override;
virtual bool tts_is_paused() const override;
- virtual Array tts_get_voices() const override;
+ virtual TypedArray<Dictionary> tts_get_voices() const override;
virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
virtual void tts_pause() override;
diff --git a/platform/macos/README.md b/platform/macos/README.md
new file mode 100644
index 0000000000..feead80736
--- /dev/null
+++ b/platform/macos/README.md
@@ -0,0 +1,19 @@
+# macOS platform port
+
+This folder contains the C++, Objective-C and Objective-C++ code for the macOS
+platform port.
+
+See also [`misc/dist/macos`](/misc/dist/macos) folder for additional files used
+by this platform. [`misc/dist/macos_tools.app`](/misc/dist/macos_tools.app) is
+an `.app` bundle template used for packaging the macOS editor, while
+[`misc/dist/macos_template.app`](/misc/dist/macos_template.app) is used for
+packaging macOS export templates.
+
+## Documentation
+
+- [Compiling for macOS](https://docs.godotengine.org/en/latest/development/compiling/compiling_for_macos.html)
+ - Instructions on building this platform port from source.
+- [Exporting for macOS](https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_macos.html)
+ - Instructions on using the compiled export templates to export a project.
+- [Running Godot apps on macOS](https://docs.godotengine.org/en/latest/tutorials/export/running_on_macos.html)
+ - Instructions on running Godot projects on macOS.
diff --git a/platform/macos/detect.py b/platform/macos/detect.py
index 20e7afa772..e5bcb46b02 100644
--- a/platform/macos/detect.py
+++ b/platform/macos/detect.py
@@ -1,6 +1,7 @@
import os
import sys
from methods import detect_darwin_sdk_path
+from platform_methods import detect_arch
def is_active():
@@ -37,6 +38,7 @@ def get_opts():
def get_flags():
return [
+ ("arch", detect_arch()),
("use_volk", False),
]
@@ -71,6 +73,15 @@ def get_mvk_sdk_path():
def configure(env):
+ # Validate arch.
+ supported_arches = ["x86_64", "arm64"]
+ if env["arch"] not in supported_arches:
+ print(
+ 'Unsupported CPU architecture "%s" for macOS. Supported architectures are: %s.'
+ % (env["arch"], ", ".join(supported_arches))
+ )
+ sys.exit()
+
## Build type
if env["target"] == "release":
@@ -96,25 +107,20 @@ def configure(env):
env.Prepend(CCFLAGS=["-g3"])
env.Prepend(LINKFLAGS=["-Xlinker", "-no_deduplicate"])
- ## Architecture
-
- # macOS no longer runs on 32-bit since 10.7 which is unsupported since 2014
- # As such, we only support 64-bit
- env["bits"] = "64"
-
## Compiler configuration
# Save this in environment for use by other modules
if "OSXCROSS_ROOT" in os.environ:
env["osxcross"] = True
+ # CPU architecture.
if env["arch"] == "arm64":
- print("Building for macOS 11.0+, platform arm64.")
+ print("Building for macOS 11.0+.")
env.Append(ASFLAGS=["-arch", "arm64", "-mmacosx-version-min=11.0"])
env.Append(CCFLAGS=["-arch", "arm64", "-mmacosx-version-min=11.0"])
env.Append(LINKFLAGS=["-arch", "arm64", "-mmacosx-version-min=11.0"])
- else:
- print("Building for macOS 10.12+, platform x86_64.")
+ elif env["arch"] == "x86_64":
+ print("Building for macOS 10.12+.")
env.Append(ASFLAGS=["-arch", "x86_64", "-mmacosx-version-min=10.12"])
env.Append(CCFLAGS=["-arch", "x86_64", "-mmacosx-version-min=10.12"])
env.Append(LINKFLAGS=["-arch", "x86_64", "-mmacosx-version-min=10.12"])
@@ -185,9 +191,8 @@ def configure(env):
## Dependencies
- if env["builtin_libtheora"]:
- if env["arch"] != "arm64":
- env["x86_libtheora_opt_gcc"] = True
+ if env["builtin_libtheora"] and env["arch"] == "x86_64":
+ env["x86_libtheora_opt_gcc"] = True
## Flags
diff --git a/platform/macos/display_server_macos.h b/platform/macos/display_server_macos.h
index 54c479fc81..e305ff3593 100644
--- a/platform/macos/display_server_macos.h
+++ b/platform/macos/display_server_macos.h
@@ -196,6 +196,9 @@ private:
static NSCursor *_cursor_from_selector(SEL p_selector, SEL p_fallback = nil);
+ bool _has_help_menu() const;
+ NSMenuItem *_menu_add_item(const String &p_menu_root, const String &p_label, Key p_accel, int p_index, int *r_out);
+
public:
NSMenu *get_dock_menu() const;
void menu_callback(id p_sender);
@@ -224,15 +227,15 @@ public:
virtual bool has_feature(Feature p_feature) const override;
virtual String get_name() const override;
- virtual void global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
- virtual void global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
- virtual void global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
- virtual void global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
- virtual void global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
- virtual void global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
- virtual void global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
- virtual void global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index = -1) override;
- virtual void global_menu_add_separator(const String &p_menu_root, int p_index = -1) override;
+ virtual int global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
+ virtual int global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
+ virtual int global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
+ virtual int global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
+ virtual int global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
+ virtual int global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
+ virtual int global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1) override;
+ virtual int global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index = -1) override;
+ virtual int global_menu_add_separator(const String &p_menu_root, int p_index = -1) override;
virtual int global_menu_get_item_index_from_text(const String &p_menu_root, const String &p_text) const override;
virtual int global_menu_get_item_index_from_tag(const String &p_menu_root, const Variant &p_tag) const override;
@@ -250,6 +253,7 @@ public:
virtual int global_menu_get_item_state(const String &p_menu_root, int p_idx) const override;
virtual int global_menu_get_item_max_states(const String &p_menu_root, int p_idx) const override;
virtual Ref<Texture2D> global_menu_get_item_icon(const String &p_menu_root, int p_idx) const override;
+ virtual int global_menu_get_item_indentation_level(const String &p_menu_root, int p_idx) const override;
virtual void global_menu_set_item_checked(const String &p_menu_root, int p_idx, bool p_checked) override;
virtual void global_menu_set_item_checkable(const String &p_menu_root, int p_idx, bool p_checkable) override;
@@ -264,6 +268,7 @@ public:
virtual void global_menu_set_item_state(const String &p_menu_root, int p_idx, int p_state) override;
virtual void global_menu_set_item_max_states(const String &p_menu_root, int p_idx, int p_max_states) override;
virtual void global_menu_set_item_icon(const String &p_menu_root, int p_idx, const Ref<Texture2D> &p_icon) override;
+ virtual void global_menu_set_item_indentation_level(const String &p_menu_root, int p_idx, int p_level) override;
virtual int global_menu_get_item_count(const String &p_menu_root) const override;
@@ -272,7 +277,7 @@ public:
virtual bool tts_is_speaking() const override;
virtual bool tts_is_paused() const override;
- virtual Array tts_get_voices() const override;
+ virtual TypedArray<Dictionary> tts_get_voices() const override;
virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
virtual void tts_pause() override;
diff --git a/platform/macos/display_server_macos.mm b/platform/macos/display_server_macos.mm
index a49485154b..fa6bcda902 100644
--- a/platform/macos/display_server_macos.mm
+++ b/platform/macos/display_server_macos.mm
@@ -63,7 +63,7 @@
const NSMenu *DisplayServerMacOS::_get_menu_root(const String &p_menu_root) const {
const NSMenu *menu = nullptr;
- if (p_menu_root == "") {
+ if (p_menu_root == "" || p_menu_root.to_lower() == "_main") {
// Main menu.
menu = [NSApp mainMenu];
} else if (p_menu_root.to_lower() == "_dock") {
@@ -84,7 +84,7 @@ const NSMenu *DisplayServerMacOS::_get_menu_root(const String &p_menu_root) cons
NSMenu *DisplayServerMacOS::_get_menu_root(const String &p_menu_root) {
NSMenu *menu = nullptr;
- if (p_menu_root == "") {
+ if (p_menu_root == "" || p_menu_root.to_lower() == "_main") {
// Main menu.
menu = [NSApp mainMenu];
} else if (p_menu_root.to_lower() == "_dock") {
@@ -714,18 +714,51 @@ String DisplayServerMacOS::get_name() const {
return "macOS";
}
-void DisplayServerMacOS::global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
- _THREAD_SAFE_METHOD_
+bool DisplayServerMacOS::_has_help_menu() const {
+ if ([NSApp helpMenu]) {
+ return true;
+ } else {
+ NSMenu *menu = [NSApp mainMenu];
+ const NSMenuItem *menu_item = [menu itemAtIndex:[menu numberOfItems] - 1];
+ if (menu_item) {
+ String menu_name = String::utf8([[menu_item title] UTF8String]);
+ if (menu_name == "Help" || menu_name == RTR("Help")) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
+NSMenuItem *DisplayServerMacOS::_menu_add_item(const String &p_menu_root, const String &p_label, Key p_accel, int p_index, int *r_out) {
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
String keycode = KeyMappingMacOS::keycode_get_native_string(p_accel & KeyModifierMask::CODE_MASK);
NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
+ int item_count = ((menu == [NSApp mainMenu]) && _has_help_menu()) ? [menu numberOfItems] - 1 : [menu numberOfItems];
+ if ((menu == [NSApp mainMenu]) && (p_label == "Help" || p_label == RTR("Help"))) {
+ p_index = [menu numberOfItems];
+ } else if (p_index < 0) {
+ p_index = item_count;
} else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]];
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_index++;
+ }
+ p_index = CLAMP(p_index, 0, item_count);
}
+ menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
+ *r_out = (menu == [NSApp mainMenu]) ? p_index - 1 : p_index;
+ return menu_item;
+ }
+ return nullptr;
+}
+
+int DisplayServerMacOS::global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+ _THREAD_SAFE_METHOD_
+
+ int out = -1;
+ NSMenuItem *menu_item = _menu_add_item(p_menu_root, p_label, p_accel, p_index, &out);
+ if (menu_item) {
GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
@@ -735,20 +768,15 @@ void DisplayServerMacOS::global_menu_add_item(const String &p_menu_root, const S
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_accel)];
[menu_item setRepresentedObject:obj];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServerMacOS::global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
_THREAD_SAFE_METHOD_
- NSMenu *menu = _get_menu_root(p_menu_root);
- if (menu) {
- String keycode = KeyMappingMacOS::keycode_get_native_string(p_accel & KeyModifierMask::CODE_MASK);
- NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
- } else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]];
- }
+ int out = -1;
+ NSMenuItem *menu_item = _menu_add_item(p_menu_root, p_label, p_accel, p_index, &out);
+ if (menu_item) {
GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
@@ -758,20 +786,15 @@ void DisplayServerMacOS::global_menu_add_check_item(const String &p_menu_root, c
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_accel)];
[menu_item setRepresentedObject:obj];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServerMacOS::global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
_THREAD_SAFE_METHOD_
- NSMenu *menu = _get_menu_root(p_menu_root);
- if (menu) {
- String keycode = KeyMappingMacOS::keycode_get_native_string(p_accel & KeyModifierMask::CODE_MASK);
- NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
- } else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]];
- }
+ int out = -1;
+ NSMenuItem *menu_item = _menu_add_item(p_menu_root, p_label, p_accel, p_index, &out);
+ if (menu_item) {
GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
@@ -790,20 +813,15 @@ void DisplayServerMacOS::global_menu_add_icon_item(const String &p_menu_root, co
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_accel)];
[menu_item setRepresentedObject:obj];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServerMacOS::global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
_THREAD_SAFE_METHOD_
- NSMenu *menu = _get_menu_root(p_menu_root);
- if (menu) {
- String keycode = KeyMappingMacOS::keycode_get_native_string(p_accel & KeyModifierMask::CODE_MASK);
- NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
- } else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]];
- }
+ int out = -1;
+ NSMenuItem *menu_item = _menu_add_item(p_menu_root, p_label, p_accel, p_index, &out);
+ if (menu_item) {
GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
@@ -822,20 +840,15 @@ void DisplayServerMacOS::global_menu_add_icon_check_item(const String &p_menu_ro
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_accel)];
[menu_item setRepresentedObject:obj];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServerMacOS::global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
_THREAD_SAFE_METHOD_
- NSMenu *menu = _get_menu_root(p_menu_root);
- if (menu) {
- String keycode = KeyMappingMacOS::keycode_get_native_string(p_accel & KeyModifierMask::CODE_MASK);
- NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
- } else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]];
- }
+ int out = -1;
+ NSMenuItem *menu_item = _menu_add_item(p_menu_root, p_label, p_accel, p_index, &out);
+ if (menu_item) {
GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
@@ -845,20 +858,15 @@ void DisplayServerMacOS::global_menu_add_radio_check_item(const String &p_menu_r
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_accel)];
[menu_item setRepresentedObject:obj];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServerMacOS::global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
_THREAD_SAFE_METHOD_
- NSMenu *menu = _get_menu_root(p_menu_root);
- if (menu) {
- String keycode = KeyMappingMacOS::keycode_get_native_string(p_accel & KeyModifierMask::CODE_MASK);
- NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
- } else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]];
- }
+ int out = -1;
+ NSMenuItem *menu_item = _menu_add_item(p_menu_root, p_label, p_accel, p_index, &out);
+ if (menu_item) {
GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
@@ -877,20 +885,31 @@ void DisplayServerMacOS::global_menu_add_icon_radio_check_item(const String &p_m
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_accel)];
[menu_item setRepresentedObject:obj];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServerMacOS::global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
_THREAD_SAFE_METHOD_
NSMenu *menu = _get_menu_root(p_menu_root);
+ int out = -1;
if (menu) {
String keycode = KeyMappingMacOS::keycode_get_native_string(p_accel & KeyModifierMask::CODE_MASK);
NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
+ int item_count = ((menu == [NSApp mainMenu]) && _has_help_menu()) ? [menu numberOfItems] - 1 : [menu numberOfItems];
+ if ((menu == [NSApp mainMenu]) && (p_label == "Help" || p_label == RTR("Help"))) {
+ p_index = [menu numberOfItems];
+ } else if (p_index < 0) {
+ p_index = item_count;
} else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]];
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_index++;
+ }
+ p_index = CLAMP(p_index, 0, item_count);
}
+ menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()] atIndex:p_index];
+ out = (menu == [NSApp mainMenu]) ? p_index - 1 : p_index;
+
GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
@@ -900,44 +919,69 @@ void DisplayServerMacOS::global_menu_add_multistate_item(const String &p_menu_ro
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_accel)];
[menu_item setRepresentedObject:obj];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index) {
+int DisplayServerMacOS::global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index) {
_THREAD_SAFE_METHOD_
NSMenu *menu = _get_menu_root(p_menu_root);
NSMenu *sub_menu = _get_menu_root(p_submenu);
+ int out = -1;
if (menu && sub_menu) {
if (sub_menu == menu) {
ERR_PRINT("Can't set submenu to self!");
- return;
+ return -1;
}
if ([sub_menu supermenu]) {
ERR_PRINT("Can't set submenu to menu that is already a submenu of some other menu!");
- return;
+ return -1;
}
NSMenuItem *menu_item;
- if (p_index != -1) {
- menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:nil keyEquivalent:@"" atIndex:p_index];
+ int item_count = ((menu == [NSApp mainMenu]) && _has_help_menu()) ? [menu numberOfItems] - 1 : [menu numberOfItems];
+ if ((menu == [NSApp mainMenu]) && (p_label == "Help" || p_label == RTR("Help"))) {
+ p_index = [menu numberOfItems];
+ } else if (p_index < 0) {
+ p_index = item_count;
} else {
- menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:nil keyEquivalent:@""];
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_index++;
+ }
+ p_index = CLAMP(p_index, 0, item_count);
}
+ menu_item = [menu insertItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:nil keyEquivalent:@"" atIndex:p_index];
+ out = (menu == [NSApp mainMenu]) ? p_index - 1 : p_index;
+
+ GodotMenuItem *obj = [[GodotMenuItem alloc] init];
+ obj->callback = Callable();
+ obj->checkable_type = CHECKABLE_TYPE_NONE;
+ obj->max_states = 0;
+ obj->state = 0;
+ [menu_item setRepresentedObject:obj];
+
[sub_menu setTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()]];
[menu setSubmenu:sub_menu forItem:menu_item];
}
+ return out;
}
-void DisplayServerMacOS::global_menu_add_separator(const String &p_menu_root, int p_index) {
+int DisplayServerMacOS::global_menu_add_separator(const String &p_menu_root, int p_index) {
_THREAD_SAFE_METHOD_
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if (p_index != -1) {
- [menu insertItem:[NSMenuItem separatorItem] atIndex:p_index];
+ if (menu == [NSApp mainMenu]) { // Do not add separators into main menu.
+ return -1;
+ }
+ if (p_index < 0) {
+ p_index = [menu numberOfItems];
} else {
- [menu addItem:[NSMenuItem separatorItem]];
+ p_index = CLAMP(p_index, 0, [menu numberOfItems]);
}
+ [menu insertItem:[NSMenuItem separatorItem] atIndex:p_index];
+ return p_index;
}
+ return -1;
}
int DisplayServerMacOS::global_menu_get_item_index_from_text(const String &p_menu_root, const String &p_text) const {
@@ -945,7 +989,11 @@ int DisplayServerMacOS::global_menu_get_item_index_from_text(const String &p_men
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- return [menu indexOfItemWithTitle:[NSString stringWithUTF8String:p_text.utf8().get_data()]];
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ return [menu indexOfItemWithTitle:[NSString stringWithUTF8String:p_text.utf8().get_data()]] - 1;
+ } else {
+ return [menu indexOfItemWithTitle:[NSString stringWithUTF8String:p_text.utf8().get_data()]];
+ }
}
return -1;
@@ -956,12 +1004,16 @@ int DisplayServerMacOS::global_menu_get_item_index_from_tag(const String &p_menu
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- for (NSInteger i = 0; i < [menu numberOfItems]; i++) {
+ for (NSInteger i = (menu == [NSApp mainMenu]) ? 1 : 0; i < [menu numberOfItems]; i++) {
const NSMenuItem *menu_item = [menu itemAtIndex:i];
if (menu_item) {
const GodotMenuItem *obj = [menu_item representedObject];
if (obj && obj->meta == p_tag) {
- return i;
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ return i - 1;
+ } else {
+ return i;
+ }
}
}
}
@@ -975,6 +1027,11 @@ bool DisplayServerMacOS::global_menu_is_item_checked(const String &p_menu_root,
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, false);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], false);
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
return ([menu_item state] == NSControlStateValueOn);
@@ -988,6 +1045,11 @@ bool DisplayServerMacOS::global_menu_is_item_checkable(const String &p_menu_root
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, false);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], false);
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
@@ -1004,6 +1066,11 @@ bool DisplayServerMacOS::global_menu_is_item_radio_checkable(const String &p_men
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, false);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], false);
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
@@ -1020,6 +1087,11 @@ Callable DisplayServerMacOS::global_menu_get_item_callback(const String &p_menu_
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, Callable());
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], Callable());
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
@@ -1036,6 +1108,11 @@ Variant DisplayServerMacOS::global_menu_get_item_tag(const String &p_menu_root,
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, Variant());
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], Variant());
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
@@ -1052,6 +1129,11 @@ String DisplayServerMacOS::global_menu_get_item_text(const String &p_menu_root,
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, String());
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], String());
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
return String::utf8([[menu_item title] UTF8String]);
@@ -1065,6 +1147,11 @@ String DisplayServerMacOS::global_menu_get_item_submenu(const String &p_menu_roo
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, String());
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], String());
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
const NSMenu *sub_menu = [menu_item submenu];
@@ -1085,6 +1172,11 @@ Key DisplayServerMacOS::global_menu_get_item_accelerator(const String &p_menu_ro
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, Key::NONE);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], Key::NONE);
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
String ret = String::utf8([[menu_item keyEquivalent] UTF8String]);
@@ -1116,6 +1208,11 @@ bool DisplayServerMacOS::global_menu_is_item_disabled(const String &p_menu_root,
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, false);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], false);
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
return ![menu_item isEnabled];
@@ -1129,6 +1226,11 @@ String DisplayServerMacOS::global_menu_get_item_tooltip(const String &p_menu_roo
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, String());
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], String());
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
return String::utf8([[menu_item toolTip] UTF8String]);
@@ -1142,6 +1244,11 @@ int DisplayServerMacOS::global_menu_get_item_state(const String &p_menu_root, in
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], 0);
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
@@ -1158,6 +1265,11 @@ int DisplayServerMacOS::global_menu_get_item_max_states(const String &p_menu_roo
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], 0);
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
@@ -1174,6 +1286,11 @@ Ref<Texture2D> DisplayServerMacOS::global_menu_get_item_icon(const String &p_men
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, Ref<Texture2D>());
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], Ref<Texture2D>());
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
@@ -1187,14 +1304,34 @@ Ref<Texture2D> DisplayServerMacOS::global_menu_get_item_icon(const String &p_men
return Ref<Texture2D>();
}
+int DisplayServerMacOS::global_menu_get_item_indentation_level(const String &p_menu_root, int p_idx) const {
+ _THREAD_SAFE_METHOD_
+
+ const NSMenu *menu = _get_menu_root(p_menu_root);
+ if (menu) {
+ ERR_FAIL_COND_V(p_idx < 0, 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], 0);
+ const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
+ if (menu_item) {
+ return [menu_item indentationLevel];
+ }
+ }
+ return 0;
+}
+
void DisplayServerMacOS::global_menu_set_item_checked(const String &p_menu_root, int p_idx, bool p_checked) {
_THREAD_SAFE_METHOD_
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
if (p_checked) {
@@ -1211,12 +1348,15 @@ void DisplayServerMacOS::global_menu_set_item_checkable(const String &p_menu_roo
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
+ ERR_FAIL_COND(!obj);
obj->checkable_type = (p_checkable) ? CHECKABLE_TYPE_CHECK_BOX : CHECKABLE_TYPE_NONE;
}
}
@@ -1227,12 +1367,15 @@ void DisplayServerMacOS::global_menu_set_item_radio_checkable(const String &p_me
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
+ ERR_FAIL_COND(!obj);
obj->checkable_type = (p_checkable) ? CHECKABLE_TYPE_RADIO_BUTTON : CHECKABLE_TYPE_NONE;
}
}
@@ -1243,12 +1386,15 @@ void DisplayServerMacOS::global_menu_set_item_callback(const String &p_menu_root
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
+ ERR_FAIL_COND(!obj);
obj->callback = p_callback;
}
}
@@ -1259,12 +1405,15 @@ void DisplayServerMacOS::global_menu_set_item_tag(const String &p_menu_root, int
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
+ ERR_FAIL_COND(!obj);
obj->meta = p_tag;
}
}
@@ -1275,9 +1424,11 @@ void DisplayServerMacOS::global_menu_set_item_text(const String &p_menu_root, in
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
[menu_item setTitle:[NSString stringWithUTF8String:p_text.utf8().get_data()]];
@@ -1299,9 +1450,11 @@ void DisplayServerMacOS::global_menu_set_item_submenu(const String &p_menu_root,
ERR_PRINT("Can't set submenu to menu that is already a submenu of some other menu!");
return;
}
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
[menu setSubmenu:sub_menu forItem:menu_item];
@@ -1314,9 +1467,11 @@ void DisplayServerMacOS::global_menu_set_item_accelerator(const String &p_menu_r
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
[menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_keycode)];
@@ -1331,9 +1486,11 @@ void DisplayServerMacOS::global_menu_set_item_disabled(const String &p_menu_root
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
[menu_item setEnabled:(!p_disabled)];
@@ -1346,9 +1503,11 @@ void DisplayServerMacOS::global_menu_set_item_tooltip(const String &p_menu_root,
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
[menu_item setToolTip:[NSString stringWithUTF8String:p_tooltip.utf8().get_data()]];
@@ -1361,15 +1520,16 @@ void DisplayServerMacOS::global_menu_set_item_state(const String &p_menu_root, i
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
- if (obj) {
- obj->state = p_state;
- }
+ ERR_FAIL_COND(!obj);
+ obj->state = p_state;
}
}
}
@@ -1379,15 +1539,16 @@ void DisplayServerMacOS::global_menu_set_item_max_states(const String &p_menu_ro
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
- if (obj) {
- obj->max_states = p_max_states;
- }
+ ERR_FAIL_COND(!obj);
+ obj->max_states = p_max_states;
}
}
}
@@ -1397,12 +1558,15 @@ void DisplayServerMacOS::global_menu_set_item_icon(const String &p_menu_root, in
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
GodotMenuItem *obj = [menu_item representedObject];
+ ERR_FAIL_COND(!obj);
if (p_icon.is_valid()) {
obj->img = p_icon->get_image();
obj->img = obj->img->duplicate();
@@ -1419,12 +1583,33 @@ void DisplayServerMacOS::global_menu_set_item_icon(const String &p_menu_root, in
}
}
+void DisplayServerMacOS::global_menu_set_item_indentation_level(const String &p_menu_root, int p_idx, int p_level) {
+ _THREAD_SAFE_METHOD_
+
+ NSMenu *menu = _get_menu_root(p_menu_root);
+ if (menu) {
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
+ }
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
+ NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
+ if (menu_item) {
+ [menu_item setIndentationLevel:p_level];
+ }
+ }
+}
+
int DisplayServerMacOS::global_menu_get_item_count(const String &p_menu_root) const {
_THREAD_SAFE_METHOD_
const NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- return [menu numberOfItems];
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ return [menu numberOfItems] - 1;
+ } else {
+ return [menu numberOfItems];
+ }
} else {
return 0;
}
@@ -1435,9 +1620,11 @@ void DisplayServerMacOS::global_menu_remove_item(const String &p_menu_root, int
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
- if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not delete Apple menu.
- return;
+ ERR_FAIL_COND(p_idx < 0);
+ if (menu == [NSApp mainMenu]) { // Skip Apple menu.
+ p_idx++;
}
+ ERR_FAIL_COND(p_idx >= [menu numberOfItems]);
[menu removeItemAtIndex:p_idx];
}
}
@@ -1453,6 +1640,9 @@ void DisplayServerMacOS::global_menu_clear(const String &p_menu_root) {
NSMenuItem *menu_item = [menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
[menu setSubmenu:apple_menu forItem:menu_item];
}
+ if (submenu.has(p_menu_root)) {
+ submenu.erase(p_menu_root);
+ }
}
}
@@ -1466,7 +1656,7 @@ bool DisplayServerMacOS::tts_is_paused() const {
return [tts isPaused];
}
-Array DisplayServerMacOS::tts_get_voices() const {
+TypedArray<Dictionary> DisplayServerMacOS::tts_get_voices() const {
ERR_FAIL_COND_V(!tts, Array());
return [tts getVoices];
}
@@ -3222,7 +3412,7 @@ DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowM
[apple_menu addItem:[NSMenuItem separatorItem]];
- title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
+ title = [NSString stringWithFormat:NSLocalizedString(@"\t\tQuit %@", nil), nsappname];
[apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
// Add items to the menu bar.
diff --git a/platform/macos/godot_menu_item.h b/platform/macos/godot_menu_item.h
index 2c12897f10..e0b9f41632 100644
--- a/platform/macos/godot_menu_item.h
+++ b/platform/macos/godot_menu_item.h
@@ -46,7 +46,6 @@ enum GlobalMenuCheckType {
@public
Callable callback;
Variant meta;
- int id;
GlobalMenuCheckType checkable_type;
int max_states;
int state;
diff --git a/platform/uwp/README.md b/platform/uwp/README.md
new file mode 100644
index 0000000000..575f90e3c7
--- /dev/null
+++ b/platform/uwp/README.md
@@ -0,0 +1,20 @@
+# UWP platform port
+
+> **Warning**
+>
+> The UWP platform port is not currently in a working state for the `master`
+> branch, and may be dropped in the future.
+
+This folder contains the C++ code for the Universal Windows Platform (UWP)
+platform port. **This is not to be confused with the "standard" Win32 port**,
+which is available in [`platform/windows`](/platform/windows).
+
+See also [`misc/dist/uwp_template`](/misc/dist/uwp_template) folder for the UWP
+project template used for packaging the UWP export templates.
+
+## Documentation
+
+- [Compiling for Universal Windows Platform](https://docs.godotengine.org/en/latest/development/compiling/compiling_for_uwp.html)
+ - Instructions on building this platform port from source.
+- [Exporting for Universal Windows Platform](https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_uwp.html)
+ - Instructions on using the compiled export templates to export a project.
diff --git a/platform/uwp/detect.py b/platform/uwp/detect.py
index 9c91378b22..2c5746cb06 100644
--- a/platform/uwp/detect.py
+++ b/platform/uwp/detect.py
@@ -1,6 +1,7 @@
import methods
import os
import sys
+from platform_methods import detect_arch
def is_active():
@@ -31,6 +32,7 @@ def get_opts():
def get_flags():
return [
+ ("arch", detect_arch()),
("tools", False),
("xaudio2", True),
("builtin_pcre2_with_jit", False),
@@ -38,19 +40,17 @@ def get_flags():
def configure(env):
- env.msvc = True
-
- if env["bits"] != "default":
- print("Error: bits argument is disabled for MSVC")
+ # Validate arch.
+ supported_arches = ["x86_32", "x86_64", "arm32"]
+ if env["arch"] not in supported_arches:
print(
- """
- Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console
- (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits
- argument (example: scons p=uwp) and SCons will attempt to detect what MSVC compiler will be executed and inform you.
- """
+ 'Unsupported CPU architecture "%s" for UWP. Supported architectures are: %s.'
+ % (env["arch"], ", ".join(supported_arches))
)
sys.exit()
+ env.msvc = True
+
## Build type
if env["target"] == "release":
@@ -101,11 +101,10 @@ def configure(env):
arch = ""
if str(os.getenv("Platform")).lower() == "arm":
-
- print("Compiled program architecture will be an ARM executable. (forcing bits=32).")
+ print("Compiled program architecture will be an ARM executable (forcing arch=arm32).")
arch = "arm"
- env["bits"] = "32"
+ env["arch"] = "arm32"
env.Append(LINKFLAGS=["/MACHINE:ARM"])
env.Append(LIBPATH=[vc_base_path + "lib/store/arm"])
@@ -117,20 +116,20 @@ def configure(env):
compiler_version_str = methods.detect_visual_c_compiler_version(env["ENV"])
if compiler_version_str == "amd64" or compiler_version_str == "x86_amd64":
- env["bits"] = "64"
- print("Compiled program architecture will be a x64 executable (forcing bits=64).")
+ env["arch"] = "x86_64"
+ print("Compiled program architecture will be a x64 executable (forcing arch=x86_64).")
elif compiler_version_str == "x86" or compiler_version_str == "amd64_x86":
- env["bits"] = "32"
- print("Compiled program architecture will be a x86 executable. (forcing bits=32).")
+ env["arch"] = "x86_32"
+ print("Compiled program architecture will be a x86 executable (forcing arch=x86_32).")
else:
print(
- "Failed to detect MSVC compiler architecture version... Defaulting to 32-bit executable settings"
- " (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture"
+ "Failed to detect MSVC compiler architecture version... Defaulting to x86 32-bit executable settings"
+ " (forcing arch=x86_32). Compilation attempt will continue, but SCons can not detect for what architecture"
" this build is compiled for. You should check your settings/compilation setup."
)
- env["bits"] = "32"
+ env["arch"] = "x86_32"
- if env["bits"] == "32":
+ if env["arch"] == "x86_32":
arch = "x86"
angle_build_cmd += "Win32"
diff --git a/platform/windows/README.md b/platform/windows/README.md
new file mode 100644
index 0000000000..17ce6f216b
--- /dev/null
+++ b/platform/windows/README.md
@@ -0,0 +1,15 @@
+# Windows platform port
+
+This folder contains the C++ and JavaScript code for the Windows platform port.
+
+See also [`misc/dist/windows`](/misc/dist/windows) folder for additional files
+used by this platform.
+
+## Documentation
+
+- [Compiling for Windows](https://docs.godotengine.org/en/latest/development/compiling/compiling_for_windows.html)
+ - Instructions on building this platform port from source.
+- [Exporting for Windows](https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_windows.html)
+ - Instructions on using the compiled export templates to export a project.
+- [Changing application icon for Windows](https://docs.godotengine.org/en/stable/tutorials/export/changing_application_icon_for_windows.html)
+ - Instructions on using a custom icon for the exported project executable.
diff --git a/platform/windows/detect.py b/platform/windows/detect.py
index dd2df1f004..6dd6892757 100644
--- a/platform/windows/detect.py
+++ b/platform/windows/detect.py
@@ -1,5 +1,6 @@
import methods
import os
+from platform_methods import detect_arch
# To match other platforms
STACK_SIZE = 8388608
@@ -46,6 +47,7 @@ def can_build():
def get_opts():
from SCons.Variables import BoolVariable, EnumVariable
+ # TODO: These shouldn't be hard-coded for x86.
mingw32 = ""
mingw64 = ""
if os.name == "posix":
@@ -77,11 +79,14 @@ def get_opts():
def get_flags():
- return []
+ return [
+ ("arch", detect_arch()),
+ ]
def build_res_file(target, source, env):
- if env["bits"] == "32":
+ # TODO: This shouldn't be hard-coded for x86.
+ if env["arch"] == "x86_32":
cmdbase = env["mingw_prefix_32"]
else:
cmdbase = env["mingw_prefix_64"]
@@ -100,21 +105,27 @@ def build_res_file(target, source, env):
def setup_msvc_manual(env):
+ # FIXME: This is super hacky, and probably obsolete.
+ # Won't work with detect_arch() used for `arch` by default.
+
"""Set up env to use MSVC manually, using VCINSTALLDIR"""
- if env["bits"] != "default":
+ if env["arch"] != "auto":
print(
"""
- Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console
- (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits
- argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you.
+ Arch argument is not supported for MSVC manual configuration (VCINSTALLDIR configured).
+ Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console (or Visual Studio settings) that is being used to run SCons.
+ As a consequence, the arch argument is disabled. Run scons again without arch argument (example: scons p=windows)
+ and SCons will attempt to detect what MSVC compiler will be executed and inform you.
"""
)
- raise SCons.Errors.UserError("Bits argument should not be used when using VCINSTALLDIR")
+ raise SCons.Errors.UserError("Arch argument should not be used when using VCINSTALLDIR")
- # Force bits arg
+ # Force ARCH arg
# (Actually msys2 mingw can support 64-bit, we could detect that)
- env["bits"] = "32"
- env["x86_libtheora_opt_vc"] = True
+ # TODO: This is wrong, but not sure what to do about it.
+ # We want to determine the arch and bitness in the SConstruct only.
+ # We can check if it's correct in here, but if it's not, it should
+ # just fail with an error message instead of trying to force it.
# find compiler manually
compiler_version_str = methods.detect_visual_c_compiler_version(env["ENV"])
@@ -122,17 +133,19 @@ def setup_msvc_manual(env):
# If building for 64bit architecture, disable assembly optimisations for 32 bit builds (theora as of writing)... vc compiler for 64bit can not compile _asm
if compiler_version_str == "amd64" or compiler_version_str == "x86_amd64":
- env["bits"] = "64"
+ env["arch"] = "x86_64"
env["x86_libtheora_opt_vc"] = False
- print("Compiled program architecture will be a 64 bit executable (forcing bits=64).")
+ print("Compiled program architecture will be a 64 bit executable (forcing arch=x86_64).")
elif compiler_version_str == "x86" or compiler_version_str == "amd64_x86":
- print("Compiled program architecture will be a 32 bit executable. (forcing bits=32).")
+ env["arch"] = "x86_32"
+ env["x86_libtheora_opt_vc"] = True
+ print("Compiled program architecture will be a 32 bit executable (forcing arch=x86_32).")
else:
print(
- "Failed to manually detect MSVC compiler architecture version... Defaulting to 32bit executable settings"
- " (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this"
- " build is compiled for. You should check your settings/compilation setup, or avoid setting VCINSTALLDIR."
+ "Failed to manually detect MSVC compiler architecture version.\n"
+ "You should check your settings/compilation setup, or avoid setting VCINSTALLDIR."
)
+ sys.exit()
def setup_msvc_auto(env):
@@ -141,6 +154,18 @@ def setup_msvc_auto(env):
# If MSVC_VERSION is set by SCons, we know MSVC is installed.
# But we may want a different version or target arch.
+ # Valid architectures for MSVC's TARGET_ARCH:
+ # ['amd64', 'emt64', 'i386', 'i486', 'i586', 'i686', 'ia64', 'itanium', 'x86', 'x86_64', 'arm', 'arm64', 'aarch64']
+ # Our x86_64 and arm64 are the same, and we need to map the 32-bit
+ # architectures to other names since MSVC isn't as explicit.
+ # The rest we don't need to worry about because they are
+ # aliases or aren't supported by Godot (itanium & ia64).
+ msvc_arch_aliases = {"x86_32": "x86", "arm32": "arm"}
+ if env["arch"] in msvc_arch_aliases.keys():
+ env["TARGET_ARCH"] = msvc_arch_aliases[env["arch"]]
+ else:
+ env["TARGET_ARCH"] = env["arch"]
+
# The env may have already been set up with default MSVC tools, so
# reset a few things so we can set it up with the tools we want.
# (Ideally we'd decide on the tool config before configuring any
@@ -149,21 +174,14 @@ def setup_msvc_auto(env):
env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool
env["MSVS_VERSION"] = None
env["MSVC_VERSION"] = None
- env["TARGET_ARCH"] = None
- if env["bits"] != "default":
- env["TARGET_ARCH"] = {"32": "x86", "64": "x86_64"}[env["bits"]]
+
if "msvc_version" in env:
env["MSVC_VERSION"] = env["msvc_version"]
env.Tool("msvc")
env.Tool("mssdk") # we want the MS SDK
# Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
- # Get actual target arch into bits (it may be "default" at this point):
- if env["TARGET_ARCH"] in ("amd64", "x86_64"):
- env["bits"] = "64"
- else:
- env["bits"] = "32"
- print("Found MSVC version %s, arch %s, bits=%s" % (env["MSVC_VERSION"], env["TARGET_ARCH"], env["bits"]))
- if env["TARGET_ARCH"] in ("amd64", "x86_64"):
+ print("Found MSVC version %s, arch %s" % (env["MSVC_VERSION"], env["TARGET_ARCH"]))
+ if env["arch"] == "x86_32":
env["x86_libtheora_opt_vc"] = False
@@ -244,7 +262,7 @@ def configure_msvc(env, manual_msvc_config):
]
)
env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros
- if env["bits"] == "64":
+ if env["arch"] == "x86_64":
env.AppendUnique(CPPDEFINES=["_WIN64"])
## Libs
@@ -328,10 +346,10 @@ def configure_mingw(env):
env.Append(CCFLAGS=["-msse2"])
if env["optimize"] == "speed": # optimize for speed (default)
- if env["bits"] == "64":
- env.Append(CCFLAGS=["-O3"])
- else:
+ if env["arch"] == "x86_32":
env.Append(CCFLAGS=["-O2"])
+ else:
+ env.Append(CCFLAGS=["-O3"])
else: # optimize for size
env.Prepend(CCFLAGS=["-Os"])
@@ -365,15 +383,12 @@ def configure_mingw(env):
if os.name != "nt":
env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation
- if env["bits"] == "default":
- if os.name == "nt":
- env["bits"] = "64" if "PROGRAMFILES(X86)" in os.environ else "32"
- else: # default to 64-bit on Linux
- env["bits"] = "64"
-
mingw_prefix = ""
- if env["bits"] == "32":
+ # TODO: This doesn't seem to be working, or maybe I just have
+ # MinGW set up incorrectly. It always gives me x86_64 builds,
+ # even though arch == "x86_32" and the file name has x86_32 in it.
+ if env["arch"] == "x86_32":
if env["use_static_cpp"]:
env.Append(LINKFLAGS=["-static"])
env.Append(LINKFLAGS=["-static-libgcc"])
@@ -460,11 +475,18 @@ def configure_mingw(env):
def configure(env):
+ # Validate arch.
+ supported_arches = ["x86_32", "x86_64", "arm32", "arm64"]
+ if env["arch"] not in supported_arches:
+ print(
+ 'Unsupported CPU architecture "%s" for Windows. Supported architectures are: %s.'
+ % (env["arch"], ", ".join(supported_arches))
+ )
+ sys.exit()
+
# At this point the env has been set up with basic tools/compilers.
env.Prepend(CPPPATH=["#platform/windows"])
- print("Configuring for Windows: target=%s, bits=%s" % (env["target"], env["bits"]))
-
if os.name == "nt":
env["ENV"] = os.environ # this makes build less repeatable, but simplifies some things
env["ENV"]["TMP"] = os.environ["TMP"]
diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp
index 8c8dbef8a4..7eb61b3038 100644
--- a/platform/windows/display_server_windows.cpp
+++ b/platform/windows/display_server_windows.cpp
@@ -144,8 +144,8 @@ bool DisplayServerWindows::tts_is_paused() const {
return tts->is_paused();
}
-Array DisplayServerWindows::tts_get_voices() const {
- ERR_FAIL_COND_V(!tts, Array());
+TypedArray<Dictionary> DisplayServerWindows::tts_get_voices() const {
+ ERR_FAIL_COND_V(!tts, TypedArray<Dictionary>());
return tts->get_voices();
}
diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h
index db9b589304..556ce9ff5d 100644
--- a/platform/windows/display_server_windows.h
+++ b/platform/windows/display_server_windows.h
@@ -478,7 +478,7 @@ public:
virtual bool tts_is_speaking() const override;
virtual bool tts_is_paused() const override;
- virtual Array tts_get_voices() const override;
+ virtual TypedArray<Dictionary> tts_get_voices() const override;
virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
virtual void tts_pause() override;
diff --git a/platform/windows/platform_windows_builders.py b/platform/windows/platform_windows_builders.py
index 22e33b51b4..33ca2e8ffa 100644
--- a/platform/windows/platform_windows_builders.py
+++ b/platform/windows/platform_windows_builders.py
@@ -9,7 +9,7 @@ from platform_methods import subprocess_main
def make_debug_mingw(target, source, env):
mingw_prefix = ""
- if env["bits"] == "32":
+ if env["arch"] == "x86_32":
mingw_prefix = env["mingw_prefix_32"]
else:
mingw_prefix = env["mingw_prefix_64"]
diff --git a/platform_methods.py b/platform_methods.py
index be4957475d..1a2520794c 100644
--- a/platform_methods.py
+++ b/platform_methods.py
@@ -1,6 +1,7 @@
import os
import sys
import json
+import platform
import uuid
import functools
import subprocess
@@ -71,9 +72,42 @@ def run_in_subprocess(builder_function):
def subprocess_main(namespace):
-
with open(sys.argv[1]) as json_file:
data = json.load(json_file)
fn = namespace[data["fn"]]
fn(*data["args"])
+
+
+# CPU architecture options.
+architectures = ["x86_32", "x86_64", "arm32", "arm64", "rv64", "ppc32", "ppc64", "wasm32"]
+architecture_aliases = {
+ "x86": "x86_32",
+ "x64": "x86_64",
+ "amd64": "x86_64",
+ "armv7": "arm32",
+ "armv8": "arm64",
+ "arm64v8": "arm64",
+ "aarch64": "arm64",
+ "rv": "rv64",
+ "riscv": "rv64",
+ "riscv64": "rv64",
+ "ppcle": "ppc32",
+ "ppc": "ppc32",
+ "ppc64le": "ppc64",
+}
+
+
+def detect_arch():
+ host_machine = platform.machine().lower()
+ if host_machine in architectures:
+ return host_machine
+ elif host_machine in architecture_aliases.keys():
+ return architecture_aliases[host_machine]
+ elif "86" in host_machine:
+ # Catches x86, i386, i486, i586, i686, etc.
+ return "x86_32"
+ else:
+ print("Unsupported CPU architecture: " + host_machine)
+ print("Falling back to x86_64.")
+ return "x86_64"
diff --git a/scene/2d/animated_sprite_2d.cpp b/scene/2d/animated_sprite_2d.cpp
index d56c7b8811..177f587f4f 100644
--- a/scene/2d/animated_sprite_2d.cpp
+++ b/scene/2d/animated_sprite_2d.cpp
@@ -104,12 +104,12 @@ Rect2 AnimatedSprite2D::_get_rect() const {
return Rect2(ofs, s);
}
-void AnimatedSprite2D::_validate_property(PropertyInfo &property) const {
+void AnimatedSprite2D::_validate_property(PropertyInfo &p_property) const {
if (!frames.is_valid()) {
return;
}
- if (property.name == "animation") {
- property.hint = PROPERTY_HINT_ENUM;
+ if (p_property.name == "animation") {
+ p_property.hint = PROPERTY_HINT_ENUM;
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
@@ -118,33 +118,33 @@ void AnimatedSprite2D::_validate_property(PropertyInfo &property) const {
for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
if (E->prev()) {
- property.hint_string += ",";
+ p_property.hint_string += ",";
}
- property.hint_string += String(E->get());
+ p_property.hint_string += String(E->get());
if (animation == E->get()) {
current_found = true;
}
}
if (!current_found) {
- if (property.hint_string.is_empty()) {
- property.hint_string = String(animation);
+ if (p_property.hint_string.is_empty()) {
+ p_property.hint_string = String(animation);
} else {
- property.hint_string = String(animation) + "," + property.hint_string;
+ p_property.hint_string = String(animation) + "," + p_property.hint_string;
}
}
}
- if (property.name == "frame") {
- property.hint = PROPERTY_HINT_RANGE;
+ if (p_property.name == "frame") {
+ p_property.hint = PROPERTY_HINT_RANGE;
if (frames->has_animation(animation) && frames->get_frame_count(animation) > 0) {
- property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
+ p_property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
- property.hint_string = "0,0,1";
+ p_property.hint_string = "0,0,1";
}
- property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
+ p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
}
diff --git a/scene/2d/animated_sprite_2d.h b/scene/2d/animated_sprite_2d.h
index ec38795a1a..0a19e250d8 100644
--- a/scene/2d/animated_sprite_2d.h
+++ b/scene/2d/animated_sprite_2d.h
@@ -62,7 +62,7 @@ class AnimatedSprite2D : public Node2D {
protected:
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
#ifdef TOOLS_ENABLED
diff --git a/scene/2d/area_2d.cpp b/scene/2d/area_2d.cpp
index 7890348314..75f1497edc 100644
--- a/scene/2d/area_2d.cpp
+++ b/scene/2d/area_2d.cpp
@@ -498,8 +498,8 @@ StringName Area2D::get_audio_bus_name() const {
return "Master";
}
-void Area2D::_validate_property(PropertyInfo &property) const {
- if (property.name == "audio_bus_name") {
+void Area2D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "audio_bus_name") {
String options;
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (i > 0) {
@@ -509,28 +509,28 @@ void Area2D::_validate_property(PropertyInfo &property) const {
options += name;
}
- property.hint_string = options;
- } else if (property.name.begins_with("gravity") && property.name != "gravity_space_override") {
+ p_property.hint_string = options;
+ } else if (p_property.name.begins_with("gravity") && p_property.name != "gravity_space_override") {
if (gravity_space_override == SPACE_OVERRIDE_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
} else {
if (gravity_is_point) {
- if (property.name == "gravity_direction") {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "gravity_direction") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
} else {
- if (property.name.begins_with("gravity_point_")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name.begins_with("gravity_point_")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
- } else if (property.name.begins_with("linear_damp") && property.name != "linear_damp_space_override") {
+ } else if (p_property.name.begins_with("linear_damp") && p_property.name != "linear_damp_space_override") {
if (linear_damp_space_override == SPACE_OVERRIDE_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- } else if (property.name.begins_with("angular_damp") && property.name != "angular_damp_space_override") {
+ } else if (p_property.name.begins_with("angular_damp") && p_property.name != "angular_damp_space_override") {
if (angular_damp_space_override == SPACE_OVERRIDE_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
diff --git a/scene/2d/area_2d.h b/scene/2d/area_2d.h
index a584420ced..3d8d77eabb 100644
--- a/scene/2d/area_2d.h
+++ b/scene/2d/area_2d.h
@@ -135,7 +135,7 @@ private:
protected:
void _notification(int p_what);
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_gravity_space_override_mode(SpaceOverride p_mode);
diff --git a/scene/2d/audio_stream_player_2d.cpp b/scene/2d/audio_stream_player_2d.cpp
index 94d22111ea..fa49552085 100644
--- a/scene/2d/audio_stream_player_2d.cpp
+++ b/scene/2d/audio_stream_player_2d.cpp
@@ -323,8 +323,8 @@ bool AudioStreamPlayer2D::_is_active() const {
return active.is_set();
}
-void AudioStreamPlayer2D::_validate_property(PropertyInfo &property) const {
- if (property.name == "bus") {
+void AudioStreamPlayer2D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "bus") {
String options;
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (i > 0) {
@@ -334,7 +334,7 @@ void AudioStreamPlayer2D::_validate_property(PropertyInfo &property) const {
options += name;
}
- property.hint_string = options;
+ p_property.hint_string = options;
}
}
diff --git a/scene/2d/audio_stream_player_2d.h b/scene/2d/audio_stream_player_2d.h
index d1c4dc4fdf..616d7fdb60 100644
--- a/scene/2d/audio_stream_player_2d.h
+++ b/scene/2d/audio_stream_player_2d.h
@@ -85,7 +85,7 @@ private:
float cached_global_panning_strength = 1.0f;
protected:
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
static void _bind_methods();
diff --git a/scene/2d/camera_2d.cpp b/scene/2d/camera_2d.cpp
index c43a796170..88f9c2a4a6 100644
--- a/scene/2d/camera_2d.cpp
+++ b/scene/2d/camera_2d.cpp
@@ -655,9 +655,9 @@ bool Camera2D::is_margin_drawing_enabled() const {
return margin_drawing_enabled;
}
-void Camera2D::_validate_property(PropertyInfo &property) const {
- if (!smoothing_enabled && property.name == "smoothing_speed") {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void Camera2D::_validate_property(PropertyInfo &p_property) const {
+ if (!smoothing_enabled && p_property.name == "smoothing_speed") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
diff --git a/scene/2d/camera_2d.h b/scene/2d/camera_2d.h
index 294a6fcb80..78654ee606 100644
--- a/scene/2d/camera_2d.h
+++ b/scene/2d/camera_2d.h
@@ -100,7 +100,7 @@ protected:
void _notification(int p_what);
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_offset(const Vector2 &p_offset);
diff --git a/scene/2d/collision_object_2d.cpp b/scene/2d/collision_object_2d.cpp
index a8c12f4893..85de1fedee 100644
--- a/scene/2d/collision_object_2d.cpp
+++ b/scene/2d/collision_object_2d.cpp
@@ -186,6 +186,17 @@ bool CollisionObject2D::get_collision_mask_value(int p_layer_number) const {
return get_collision_mask() & (1 << (p_layer_number - 1));
}
+void CollisionObject2D::set_collision_priority(real_t p_priority) {
+ collision_priority = p_priority;
+ if (!area) {
+ PhysicsServer2D::get_singleton()->body_set_collision_priority(get_rid(), p_priority);
+ }
+}
+
+real_t CollisionObject2D::get_collision_priority() const {
+ return collision_priority;
+}
+
void CollisionObject2D::set_disable_mode(DisableMode p_mode) {
if (disable_mode == p_mode) {
return;
@@ -350,8 +361,8 @@ void CollisionObject2D::get_shape_owners(List<uint32_t> *r_owners) {
}
}
-Array CollisionObject2D::_get_shape_owners() {
- Array ret;
+PackedInt32Array CollisionObject2D::_get_shape_owners() {
+ PackedInt32Array ret;
for (const KeyValue<uint32_t, ShapeData> &E : shapes) {
ret.push_back(E.key);
}
@@ -574,6 +585,8 @@ void CollisionObject2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_collision_layer_value", "layer_number"), &CollisionObject2D::get_collision_layer_value);
ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &CollisionObject2D::set_collision_mask_value);
ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &CollisionObject2D::get_collision_mask_value);
+ ClassDB::bind_method(D_METHOD("set_collision_priority", "priority"), &CollisionObject2D::set_collision_priority);
+ ClassDB::bind_method(D_METHOD("get_collision_priority"), &CollisionObject2D::get_collision_priority);
ClassDB::bind_method(D_METHOD("set_disable_mode", "mode"), &CollisionObject2D::set_disable_mode);
ClassDB::bind_method(D_METHOD("get_disable_mode"), &CollisionObject2D::get_disable_mode);
ClassDB::bind_method(D_METHOD("set_pickable", "enabled"), &CollisionObject2D::set_pickable);
@@ -611,6 +624,7 @@ void CollisionObject2D::_bind_methods() {
ADD_GROUP("Collision", "collision_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_layer", "get_collision_layer");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_priority"), "set_collision_priority", "get_collision_priority");
ADD_GROUP("Input", "input_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_pickable"), "set_pickable", "is_pickable");
diff --git a/scene/2d/collision_object_2d.h b/scene/2d/collision_object_2d.h
index 997afee6c4..af216edc98 100644
--- a/scene/2d/collision_object_2d.h
+++ b/scene/2d/collision_object_2d.h
@@ -49,6 +49,7 @@ public:
private:
uint32_t collision_layer = 1;
uint32_t collision_mask = 1;
+ real_t collision_priority = 1.0;
bool area = false;
RID rid;
@@ -115,13 +116,16 @@ public:
void set_collision_mask_value(int p_layer_number, bool p_value);
bool get_collision_mask_value(int p_layer_number) const;
+ void set_collision_priority(real_t p_priority);
+ real_t get_collision_priority() const;
+
void set_disable_mode(DisableMode p_mode);
DisableMode get_disable_mode() const;
uint32_t create_shape_owner(Object *p_owner);
void remove_shape_owner(uint32_t owner);
void get_shape_owners(List<uint32_t> *r_owners);
- Array _get_shape_owners();
+ PackedInt32Array _get_shape_owners();
void shape_owner_set_transform(uint32_t p_owner, const Transform2D &p_transform);
Transform2D shape_owner_get_transform(uint32_t p_owner) const;
diff --git a/scene/2d/cpu_particles_2d.cpp b/scene/2d/cpu_particles_2d.cpp
index 26204a3b1a..40f74d3f50 100644
--- a/scene/2d/cpu_particles_2d.cpp
+++ b/scene/2d/cpu_particles_2d.cpp
@@ -503,32 +503,32 @@ bool CPUParticles2D::get_split_scale() {
return split_scale;
}
-void CPUParticles2D::_validate_property(PropertyInfo &property) const {
- if (property.name == "emission_sphere_radius" && (emission_shape != EMISSION_SHAPE_SPHERE && emission_shape != EMISSION_SHAPE_SPHERE_SURFACE)) {
- property.usage = PROPERTY_USAGE_NONE;
+void CPUParticles2D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "emission_sphere_radius" && (emission_shape != EMISSION_SHAPE_SPHERE && emission_shape != EMISSION_SHAPE_SPHERE_SURFACE)) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_rect_extents" && emission_shape != EMISSION_SHAPE_RECTANGLE) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_rect_extents" && emission_shape != EMISSION_SHAPE_RECTANGLE) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if ((property.name == "emission_point_texture" || property.name == "emission_color_texture") && (emission_shape < EMISSION_SHAPE_POINTS)) {
- property.usage = PROPERTY_USAGE_NONE;
+ if ((p_property.name == "emission_point_texture" || p_property.name == "emission_color_texture") && (emission_shape < EMISSION_SHAPE_POINTS)) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_normals" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_normals" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_points" && emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_points" && emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_colors" && emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_colors" && emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("scale_curve_") && !split_scale) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("scale_curve_") && !split_scale) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
diff --git a/scene/2d/cpu_particles_2d.h b/scene/2d/cpu_particles_2d.h
index 51d58723b4..8f1671d280 100644
--- a/scene/2d/cpu_particles_2d.h
+++ b/scene/2d/cpu_particles_2d.h
@@ -193,7 +193,7 @@ private:
protected:
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_emitting(bool p_emitting);
diff --git a/scene/2d/gpu_particles_2d.cpp b/scene/2d/gpu_particles_2d.cpp
index 075421a26d..e4354a69e2 100644
--- a/scene/2d/gpu_particles_2d.cpp
+++ b/scene/2d/gpu_particles_2d.cpp
@@ -340,7 +340,7 @@ Ref<Texture2D> GPUParticles2D::get_texture() const {
return texture;
}
-void GPUParticles2D::_validate_property(PropertyInfo &property) const {
+void GPUParticles2D::_validate_property(PropertyInfo &p_property) const {
}
void GPUParticles2D::emit_particle(const Transform2D &p_transform2d, const Vector2 &p_velocity2d, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags) {
diff --git a/scene/2d/gpu_particles_2d.h b/scene/2d/gpu_particles_2d.h
index a4231cc45d..7eece32898 100644
--- a/scene/2d/gpu_particles_2d.h
+++ b/scene/2d/gpu_particles_2d.h
@@ -84,7 +84,7 @@ private:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
void _update_collision_size();
diff --git a/scene/2d/light_2d.cpp b/scene/2d/light_2d.cpp
index 0481a58431..7eb6b43af7 100644
--- a/scene/2d/light_2d.cpp
+++ b/scene/2d/light_2d.cpp
@@ -227,9 +227,9 @@ real_t Light2D::get_shadow_smooth() const {
return shadow_smooth;
}
-void Light2D::_validate_property(PropertyInfo &property) const {
- if (!shadow && (property.name == "shadow_color" || property.name == "shadow_filter" || property.name == "shadow_filter_smooth" || property.name == "shadow_item_cull_mask")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void Light2D::_validate_property(PropertyInfo &p_property) const {
+ if (!shadow && (p_property.name == "shadow_color" || p_property.name == "shadow_filter" || p_property.name == "shadow_filter_smooth" || p_property.name == "shadow_item_cull_mask")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
diff --git a/scene/2d/light_2d.h b/scene/2d/light_2d.h
index a84b6516c0..373cfe59fd 100644
--- a/scene/2d/light_2d.h
+++ b/scene/2d/light_2d.h
@@ -79,7 +79,7 @@ protected:
_FORCE_INLINE_ RID _get_light() const { return canvas_light; }
void _notification(int p_what);
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_enabled(bool p_enabled);
diff --git a/scene/2d/position_2d.cpp b/scene/2d/marker_2d.cpp
index cfa4d0401e..ba1d2ffbfd 100644
--- a/scene/2d/position_2d.cpp
+++ b/scene/2d/marker_2d.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* position_2d.cpp */
+/* marker_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,9 +28,9 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "position_2d.h"
+#include "marker_2d.h"
-void Position2D::_draw_cross() {
+void Marker2D::_draw_cross() {
const real_t extents = get_gizmo_extents();
// Add more points to create a "hard stop" in the color gradient.
@@ -50,7 +50,7 @@ void Position2D::_draw_cross() {
// Use the axis color which is brighter for the positive axis.
// Use a darkened axis color for the negative axis.
- // This makes it possible to see in which direction the Position3D node is rotated
+ // This makes it possible to see in which direction the Marker3D node is rotated
// (which can be important depending on how it's used).
// Axis colors are taken from `axis_x_color` and `axis_y_color` (defined in `editor/editor_themes.cpp`).
const Color color_x = Color(0.96, 0.20, 0.32);
@@ -73,17 +73,17 @@ void Position2D::_draw_cross() {
}
#ifdef TOOLS_ENABLED
-Rect2 Position2D::_edit_get_rect() const {
+Rect2 Marker2D::_edit_get_rect() const {
real_t extents = get_gizmo_extents();
return Rect2(Point2(-extents, -extents), Size2(extents * 2, extents * 2));
}
-bool Position2D::_edit_use_rect() const {
+bool Marker2D::_edit_use_rect() const {
return false;
}
#endif
-void Position2D::_notification(int p_what) {
+void Marker2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
update();
@@ -100,21 +100,21 @@ void Position2D::_notification(int p_what) {
}
}
-void Position2D::set_gizmo_extents(real_t p_extents) {
+void Marker2D::set_gizmo_extents(real_t p_extents) {
gizmo_extents = p_extents;
update();
}
-real_t Position2D::get_gizmo_extents() const {
+real_t Marker2D::get_gizmo_extents() const {
return gizmo_extents;
}
-void Position2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_gizmo_extents", "extents"), &Position2D::set_gizmo_extents);
- ClassDB::bind_method(D_METHOD("get_gizmo_extents"), &Position2D::get_gizmo_extents);
+void Marker2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_gizmo_extents", "extents"), &Marker2D::set_gizmo_extents);
+ ClassDB::bind_method(D_METHOD("get_gizmo_extents"), &Marker2D::get_gizmo_extents);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gizmo_extents", PROPERTY_HINT_RANGE, "0,1000,0.1,or_greater,suffix:px"), "set_gizmo_extents", "get_gizmo_extents");
}
-Position2D::Position2D() {
+Marker2D::Marker2D() {
}
diff --git a/scene/2d/position_2d.h b/scene/2d/marker_2d.h
index 99b0266130..e287018dfc 100644
--- a/scene/2d/position_2d.h
+++ b/scene/2d/marker_2d.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* position_2d.h */
+/* marker_2d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,13 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef POSITION_2D_H
-#define POSITION_2D_H
+#ifndef MARKER_2D_H
+#define MARKER_2D_H
#include "scene/2d/node_2d.h"
-class Position2D : public Node2D {
- GDCLASS(Position2D, Node2D);
+class Marker2D : public Node2D {
+ GDCLASS(Marker2D, Node2D);
real_t gizmo_extents = 10.0;
@@ -53,7 +53,7 @@ public:
void set_gizmo_extents(real_t p_extents);
real_t get_gizmo_extents() const;
- Position2D();
+ Marker2D();
};
-#endif // POSITION_2D_H
+#endif // MARKER_2D_H
diff --git a/scene/2d/navigation_agent_2d.cpp b/scene/2d/navigation_agent_2d.cpp
index a5f7faffef..d7f75c63a4 100644
--- a/scene/2d/navigation_agent_2d.cpp
+++ b/scene/2d/navigation_agent_2d.cpp
@@ -49,8 +49,8 @@ void NavigationAgent2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_radius", "radius"), &NavigationAgent2D::set_radius);
ClassDB::bind_method(D_METHOD("get_radius"), &NavigationAgent2D::get_radius);
- ClassDB::bind_method(D_METHOD("set_neighbor_dist", "neighbor_dist"), &NavigationAgent2D::set_neighbor_dist);
- ClassDB::bind_method(D_METHOD("get_neighbor_dist"), &NavigationAgent2D::get_neighbor_dist);
+ ClassDB::bind_method(D_METHOD("set_neighbor_distance", "neighbor_distance"), &NavigationAgent2D::set_neighbor_distance);
+ ClassDB::bind_method(D_METHOD("get_neighbor_distance"), &NavigationAgent2D::get_neighbor_distance);
ClassDB::bind_method(D_METHOD("set_max_neighbors", "max_neighbors"), &NavigationAgent2D::set_max_neighbors);
ClassDB::bind_method(D_METHOD("get_max_neighbors"), &NavigationAgent2D::get_max_neighbors);
@@ -96,7 +96,7 @@ void NavigationAgent2D::_bind_methods() {
ADD_GROUP("Avoidance", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "avoidance_enabled"), "set_avoidance_enabled", "get_avoidance_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.1,500,0.01,suffix:px"), "set_radius", "get_radius");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "neighbor_dist", PROPERTY_HINT_RANGE, "0.1,100000,0.01,suffix:px"), "set_neighbor_dist", "get_neighbor_dist");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "neighbor_distance", PROPERTY_HINT_RANGE, "0.1,100000,0.01,suffix:px"), "set_neighbor_distance", "get_neighbor_distance");
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_neighbors", PROPERTY_HINT_RANGE, "1,10000,1"), "set_max_neighbors", "get_max_neighbors");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_horizon", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:s"), "set_time_horizon", "get_time_horizon");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_speed", PROPERTY_HINT_RANGE, "0.1,100000,0.01,suffix:px/s"), "set_max_speed", "get_max_speed");
@@ -173,7 +173,7 @@ void NavigationAgent2D::_notification(int p_what) {
NavigationAgent2D::NavigationAgent2D() {
agent = NavigationServer2D::get_singleton()->agent_create();
- set_neighbor_dist(500.0);
+ set_neighbor_distance(500.0);
set_max_neighbors(10);
set_time_horizon(20.0);
set_radius(10.0);
@@ -275,9 +275,9 @@ void NavigationAgent2D::set_radius(real_t p_radius) {
NavigationServer2D::get_singleton()->agent_set_radius(agent, radius);
}
-void NavigationAgent2D::set_neighbor_dist(real_t p_dist) {
- neighbor_dist = p_dist;
- NavigationServer2D::get_singleton()->agent_set_neighbor_dist(agent, neighbor_dist);
+void NavigationAgent2D::set_neighbor_distance(real_t p_distance) {
+ neighbor_distance = p_distance;
+ NavigationServer2D::get_singleton()->agent_set_neighbor_distance(agent, neighbor_distance);
}
void NavigationAgent2D::set_max_neighbors(int p_count) {
diff --git a/scene/2d/navigation_agent_2d.h b/scene/2d/navigation_agent_2d.h
index 76eba20058..11b845665d 100644
--- a/scene/2d/navigation_agent_2d.h
+++ b/scene/2d/navigation_agent_2d.h
@@ -50,7 +50,7 @@ class NavigationAgent2D : public Node {
real_t path_desired_distance = 1.0;
real_t target_desired_distance = 1.0;
real_t radius = 0.0;
- real_t neighbor_dist = 0.0;
+ real_t neighbor_distance = 0.0;
int max_neighbors = 0;
real_t time_horizon = 0.0;
real_t max_speed = 0.0;
@@ -110,9 +110,9 @@ public:
return radius;
}
- void set_neighbor_dist(real_t p_dist);
- real_t get_neighbor_dist() const {
- return neighbor_dist;
+ void set_neighbor_distance(real_t p_distance);
+ real_t get_neighbor_distance() const {
+ return neighbor_distance;
}
void set_max_neighbors(int p_count);
diff --git a/scene/2d/navigation_obstacle_2d.cpp b/scene/2d/navigation_obstacle_2d.cpp
index 0320c6c917..c5966bedd2 100644
--- a/scene/2d/navigation_obstacle_2d.cpp
+++ b/scene/2d/navigation_obstacle_2d.cpp
@@ -135,7 +135,7 @@ TypedArray<String> NavigationObstacle2D::get_configuration_warnings() const {
}
void NavigationObstacle2D::initialize_agent() {
- NavigationServer2D::get_singleton()->agent_set_neighbor_dist(agent, 0.0);
+ NavigationServer2D::get_singleton()->agent_set_neighbor_distance(agent, 0.0);
NavigationServer2D::get_singleton()->agent_set_max_neighbors(agent, 0);
NavigationServer2D::get_singleton()->agent_set_time_horizon(agent, 0.0);
NavigationServer2D::get_singleton()->agent_set_max_speed(agent, 0.0);
diff --git a/scene/2d/navigation_obstacle_2d.h b/scene/2d/navigation_obstacle_2d.h
index afda05956a..5795c6c94f 100644
--- a/scene/2d/navigation_obstacle_2d.h
+++ b/scene/2d/navigation_obstacle_2d.h
@@ -46,7 +46,7 @@ class NavigationObstacle2D : public Node {
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &p_property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
public:
diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp
index 9862c4bfb1..bbc326a4b4 100644
--- a/scene/2d/path_2d.cpp
+++ b/scene/2d/path_2d.cpp
@@ -175,10 +175,10 @@ void PathFollow2D::_update_transform() {
if (path_length == 0) {
return;
}
- Vector2 pos = c->interpolate_baked(offset, cubic);
+ Vector2 pos = c->interpolate_baked(progress, cubic);
if (rotates) {
- real_t ahead = offset + lookahead;
+ real_t ahead = progress + lookahead;
if (loop && ahead >= path_length) {
// If our lookahead will loop, we need to check if the path is closed.
@@ -202,7 +202,7 @@ void PathFollow2D::_update_transform() {
// This will happen at the end of non-looping or non-closed paths.
// We'll try a look behind instead, in order to get a meaningful angle.
tangent_to_curve =
- (pos - c->interpolate_baked(offset - lookahead, cubic)).normalized();
+ (pos - c->interpolate_baked(progress - lookahead, cubic)).normalized();
} else {
tangent_to_curve = (ahead_pos - pos).normalized();
}
@@ -245,14 +245,14 @@ bool PathFollow2D::get_cubic_interpolation() const {
return cubic;
}
-void PathFollow2D::_validate_property(PropertyInfo &property) const {
- if (property.name == "offset") {
+void PathFollow2D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "offset") {
real_t max = 10000.0;
if (path && path->get_curve().is_valid()) {
max = path->get_curve()->get_baked_length();
}
- property.hint_string = "0," + rtos(max) + ",0.01,or_lesser,or_greater";
+ p_property.hint_string = "0," + rtos(max) + ",0.01,or_lesser,or_greater";
}
}
@@ -269,8 +269,8 @@ TypedArray<String> PathFollow2D::get_configuration_warnings() const {
}
void PathFollow2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_offset", "offset"), &PathFollow2D::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"), &PathFollow2D::get_offset);
+ ClassDB::bind_method(D_METHOD("set_progress", "progress"), &PathFollow2D::set_progress);
+ ClassDB::bind_method(D_METHOD("get_progress"), &PathFollow2D::get_progress);
ClassDB::bind_method(D_METHOD("set_h_offset", "h_offset"), &PathFollow2D::set_h_offset);
ClassDB::bind_method(D_METHOD("get_h_offset"), &PathFollow2D::get_h_offset);
@@ -278,8 +278,8 @@ void PathFollow2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_v_offset", "v_offset"), &PathFollow2D::set_v_offset);
ClassDB::bind_method(D_METHOD("get_v_offset"), &PathFollow2D::get_v_offset);
- ClassDB::bind_method(D_METHOD("set_unit_offset", "unit_offset"), &PathFollow2D::set_unit_offset);
- ClassDB::bind_method(D_METHOD("get_unit_offset"), &PathFollow2D::get_unit_offset);
+ ClassDB::bind_method(D_METHOD("set_progress_ratio", "ratio"), &PathFollow2D::set_progress_ratio);
+ ClassDB::bind_method(D_METHOD("get_progress_ratio"), &PathFollow2D::get_progress_ratio);
ClassDB::bind_method(D_METHOD("set_rotates", "enable"), &PathFollow2D::set_rotates);
ClassDB::bind_method(D_METHOD("is_rotating"), &PathFollow2D::is_rotating);
@@ -293,8 +293,8 @@ void PathFollow2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_lookahead", "lookahead"), &PathFollow2D::set_lookahead);
ClassDB::bind_method(D_METHOD("get_lookahead"), &PathFollow2D::get_lookahead);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "offset", PROPERTY_HINT_RANGE, "0,10000,0.01,or_lesser,or_greater,suffix:px"), "set_offset", "get_offset");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "unit_offset", PROPERTY_HINT_RANGE, "0,1,0.0001,or_lesser,or_greater", PROPERTY_USAGE_EDITOR), "set_unit_offset", "get_unit_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "progress", PROPERTY_HINT_RANGE, "0,10000,0.01,or_lesser,or_greater,suffix:px"), "set_progress", "get_progress");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "progress_ratio", PROPERTY_HINT_RANGE, "0,1,0.0001,or_lesser,or_greater", PROPERTY_USAGE_EDITOR), "set_progress_ratio", "get_progress_ratio");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "h_offset"), "set_h_offset", "get_h_offset");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "v_offset"), "set_v_offset", "get_v_offset");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "rotates"), "set_rotates", "is_rotating");
@@ -303,20 +303,20 @@ void PathFollow2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lookahead", PROPERTY_HINT_RANGE, "0.001,1024.0,0.001"), "set_lookahead", "get_lookahead");
}
-void PathFollow2D::set_offset(real_t p_offset) {
- ERR_FAIL_COND(!isfinite(p_offset));
- offset = p_offset;
+void PathFollow2D::set_progress(real_t p_progress) {
+ ERR_FAIL_COND(!isfinite(p_progress));
+ progress = p_progress;
if (path) {
if (path->get_curve().is_valid()) {
real_t path_length = path->get_curve()->get_baked_length();
if (loop && path_length) {
- offset = Math::fposmod(offset, path_length);
- if (!Math::is_zero_approx(p_offset) && Math::is_zero_approx(offset)) {
- offset = path_length;
+ progress = Math::fposmod(progress, path_length);
+ if (!Math::is_zero_approx(p_progress) && Math::is_zero_approx(progress)) {
+ progress = path_length;
}
} else {
- offset = CLAMP(offset, 0, path_length);
+ progress = CLAMP(progress, 0, path_length);
}
}
@@ -346,19 +346,19 @@ real_t PathFollow2D::get_v_offset() const {
return v_offset;
}
-real_t PathFollow2D::get_offset() const {
- return offset;
+real_t PathFollow2D::get_progress() const {
+ return progress;
}
-void PathFollow2D::set_unit_offset(real_t p_unit_offset) {
+void PathFollow2D::set_progress_ratio(real_t p_ratio) {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) {
- set_offset(p_unit_offset * path->get_curve()->get_baked_length());
+ set_progress(p_ratio * path->get_curve()->get_baked_length());
}
}
-real_t PathFollow2D::get_unit_offset() const {
+real_t PathFollow2D::get_progress_ratio() const {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) {
- return get_offset() / path->get_curve()->get_baked_length();
+ return get_progress() / path->get_curve()->get_baked_length();
} else {
return 0;
}
diff --git a/scene/2d/path_2d.h b/scene/2d/path_2d.h
index bc55f84831..3d66ca1fab 100644
--- a/scene/2d/path_2d.h
+++ b/scene/2d/path_2d.h
@@ -65,7 +65,7 @@ class PathFollow2D : public Node2D {
public:
private:
Path2D *path = nullptr;
- real_t offset = 0.0;
+ real_t progress = 0.0;
real_t h_offset = 0.0;
real_t v_offset = 0.0;
real_t lookahead = 4.0;
@@ -76,14 +76,14 @@ private:
void _update_transform();
protected:
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
static void _bind_methods();
public:
- void set_offset(real_t p_offset);
- real_t get_offset() const;
+ void set_progress(real_t p_progress);
+ real_t get_progress() const;
void set_h_offset(real_t p_h_offset);
real_t get_h_offset() const;
@@ -91,8 +91,8 @@ public:
void set_v_offset(real_t p_v_offset);
real_t get_v_offset() const;
- void set_unit_offset(real_t p_unit_offset);
- real_t get_unit_offset() const;
+ void set_progress_ratio(real_t p_ratio);
+ real_t get_progress_ratio() const;
void set_lookahead(real_t p_lookahead);
real_t get_lookahead() const;
diff --git a/scene/2d/physical_bone_2d.cpp b/scene/2d/physical_bone_2d.cpp
index 2999736d64..62f4d855ef 100644
--- a/scene/2d/physical_bone_2d.cpp
+++ b/scene/2d/physical_bone_2d.cpp
@@ -158,6 +158,7 @@ void PhysicalBone2D::_start_physics_simulation() {
// Apply the layers and masks.
PhysicsServer2D::get_singleton()->body_set_collision_layer(get_rid(), get_collision_layer());
PhysicsServer2D::get_singleton()->body_set_collision_mask(get_rid(), get_collision_mask());
+ PhysicsServer2D::get_singleton()->body_set_collision_priority(get_rid(), get_collision_priority());
// Apply the correct mode.
_apply_body_mode();
@@ -176,6 +177,7 @@ void PhysicalBone2D::_stop_physics_simulation() {
set_physics_process_internal(false);
PhysicsServer2D::get_singleton()->body_set_collision_layer(get_rid(), 0);
PhysicsServer2D::get_singleton()->body_set_collision_mask(get_rid(), 0);
+ PhysicsServer2D::get_singleton()->body_set_collision_priority(get_rid(), 1.0);
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_STATIC);
}
}
diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp
index 2ead48c889..a317285a1b 100644
--- a/scene/2d/physics_body_2d.cpp
+++ b/scene/2d/physics_body_2d.cpp
@@ -787,6 +787,12 @@ int RigidDynamicBody2D::get_max_contacts_reported() const {
return max_contacts_reported;
}
+int RigidDynamicBody2D::get_contact_count() const {
+ PhysicsDirectBodyState2D *bs = PhysicsServer2D::get_singleton()->body_get_direct_state(get_rid());
+ ERR_FAIL_NULL_V(bs, 0);
+ return bs->get_contact_count();
+}
+
void RigidDynamicBody2D::apply_central_impulse(const Vector2 &p_impulse) {
PhysicsServer2D::get_singleton()->body_apply_central_impulse(get_rid(), p_impulse);
}
@@ -849,7 +855,7 @@ RigidDynamicBody2D::CCDMode RigidDynamicBody2D::get_continuous_collision_detecti
}
TypedArray<Node2D> RigidDynamicBody2D::get_colliding_bodies() const {
- ERR_FAIL_COND_V(!contact_monitor, Array());
+ ERR_FAIL_COND_V(!contact_monitor, TypedArray<Node2D>());
TypedArray<Node2D> ret;
ret.resize(contact_monitor->body_map.size());
@@ -966,6 +972,7 @@ void RigidDynamicBody2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidDynamicBody2D::set_max_contacts_reported);
ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidDynamicBody2D::get_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("get_contact_count"), &RigidDynamicBody2D::get_contact_count);
ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidDynamicBody2D::set_use_custom_integrator);
ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidDynamicBody2D::is_using_custom_integrator);
@@ -1023,7 +1030,7 @@ void RigidDynamicBody2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator");
ADD_PROPERTY(PropertyInfo(Variant::INT, "continuous_cd", PROPERTY_HINT_ENUM, "Disabled,Cast Ray,Cast Shape"), "set_continuous_collision_detection_mode", "get_continuous_collision_detection_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "contacts_reported", PROPERTY_HINT_RANGE, "0,64,1,or_greater"), "set_max_contacts_reported", "get_max_contacts_reported");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_contacts_reported", PROPERTY_HINT_RANGE, "0,64,1,or_greater"), "set_max_contacts_reported", "get_max_contacts_reported");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep");
@@ -1062,10 +1069,10 @@ void RigidDynamicBody2D::_bind_methods() {
BIND_ENUM_CONSTANT(CCD_MODE_CAST_SHAPE);
}
-void RigidDynamicBody2D::_validate_property(PropertyInfo &property) const {
+void RigidDynamicBody2D::_validate_property(PropertyInfo &p_property) const {
if (center_of_mass_mode != CENTER_OF_MASS_MODE_CUSTOM) {
- if (property.name == "center_of_mass") {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "center_of_mass") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
@@ -1107,9 +1114,9 @@ bool CharacterBody2D::move_and_slide() {
if ((on_floor || on_wall) && platform_rid.is_valid()) {
bool excluded = false;
if (on_floor) {
- excluded = (moving_platform_floor_layers & platform_layer) == 0;
+ excluded = (platform_floor_layers & platform_layer) == 0;
} else if (on_wall) {
- excluded = (moving_platform_wall_layers & platform_layer) == 0;
+ excluded = (platform_wall_layers & platform_layer) == 0;
}
if (!excluded) {
//this approach makes sure there is less delay between the actual body velocity and the one we saved
@@ -1159,10 +1166,10 @@ bool CharacterBody2D::move_and_slide() {
// Compute real velocity.
real_velocity = get_position_delta() / delta;
- if (moving_platform_apply_velocity_on_leave != PLATFORM_VEL_ON_LEAVE_NEVER) {
+ if (platform_on_leave != PLATFORM_ON_LEAVE_DO_NOTHING) {
// Add last platform velocity when just left a moving platform.
if (!on_floor && !on_wall) {
- if (moving_platform_apply_velocity_on_leave == PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY && current_platform_velocity.dot(up_direction) < 0) {
+ if (platform_on_leave == PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY && current_platform_velocity.dot(up_direction) < 0) {
current_platform_velocity = current_platform_velocity.slide(up_direction);
}
velocity += current_platform_velocity;
@@ -1606,20 +1613,20 @@ void CharacterBody2D::set_slide_on_ceiling_enabled(bool p_enabled) {
slide_on_ceiling = p_enabled;
}
-uint32_t CharacterBody2D::get_moving_platform_floor_layers() const {
- return moving_platform_floor_layers;
+uint32_t CharacterBody2D::get_platform_floor_layers() const {
+ return platform_floor_layers;
}
-void CharacterBody2D::set_moving_platform_floor_layers(uint32_t p_exclude_layers) {
- moving_platform_floor_layers = p_exclude_layers;
+void CharacterBody2D::set_platform_floor_layers(uint32_t p_exclude_layers) {
+ platform_floor_layers = p_exclude_layers;
}
-uint32_t CharacterBody2D::get_moving_platform_wall_layers() const {
- return moving_platform_wall_layers;
+uint32_t CharacterBody2D::get_platform_wall_layers() const {
+ return platform_wall_layers;
}
-void CharacterBody2D::set_moving_platform_wall_layers(uint32_t p_exclude_layers) {
- moving_platform_wall_layers = p_exclude_layers;
+void CharacterBody2D::set_platform_wall_layers(uint32_t p_exclude_layers) {
+ platform_wall_layers = p_exclude_layers;
}
void CharacterBody2D::set_motion_mode(MotionMode p_mode) {
@@ -1630,12 +1637,12 @@ CharacterBody2D::MotionMode CharacterBody2D::get_motion_mode() const {
return motion_mode;
}
-void CharacterBody2D::set_moving_platform_apply_velocity_on_leave(MovingPlatformApplyVelocityOnLeave p_on_leave_apply_velocity) {
- moving_platform_apply_velocity_on_leave = p_on_leave_apply_velocity;
+void CharacterBody2D::set_platform_on_leave(PlatformOnLeave p_on_leave_apply_velocity) {
+ platform_on_leave = p_on_leave_apply_velocity;
}
-CharacterBody2D::MovingPlatformApplyVelocityOnLeave CharacterBody2D::get_moving_platform_apply_velocity_on_leave() const {
- return moving_platform_apply_velocity_on_leave;
+CharacterBody2D::PlatformOnLeave CharacterBody2D::get_platform_on_leave() const {
+ return platform_on_leave;
}
int CharacterBody2D::get_max_slides() const {
@@ -1702,7 +1709,7 @@ void CharacterBody2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &CharacterBody2D::set_velocity);
ClassDB::bind_method(D_METHOD("get_velocity"), &CharacterBody2D::get_velocity);
- ClassDB::bind_method(D_METHOD("set_safe_margin", "pixels"), &CharacterBody2D::set_safe_margin);
+ ClassDB::bind_method(D_METHOD("set_safe_margin", "margin"), &CharacterBody2D::set_safe_margin);
ClassDB::bind_method(D_METHOD("get_safe_margin"), &CharacterBody2D::get_safe_margin);
ClassDB::bind_method(D_METHOD("is_floor_stop_on_slope_enabled"), &CharacterBody2D::is_floor_stop_on_slope_enabled);
ClassDB::bind_method(D_METHOD("set_floor_stop_on_slope_enabled", "enabled"), &CharacterBody2D::set_floor_stop_on_slope_enabled);
@@ -1713,10 +1720,10 @@ void CharacterBody2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_slide_on_ceiling_enabled", "enabled"), &CharacterBody2D::set_slide_on_ceiling_enabled);
ClassDB::bind_method(D_METHOD("is_slide_on_ceiling_enabled"), &CharacterBody2D::is_slide_on_ceiling_enabled);
- ClassDB::bind_method(D_METHOD("set_moving_platform_floor_layers", "exclude_layer"), &CharacterBody2D::set_moving_platform_floor_layers);
- ClassDB::bind_method(D_METHOD("get_moving_platform_floor_layers"), &CharacterBody2D::get_moving_platform_floor_layers);
- ClassDB::bind_method(D_METHOD("set_moving_platform_wall_layers", "exclude_layer"), &CharacterBody2D::set_moving_platform_wall_layers);
- ClassDB::bind_method(D_METHOD("get_moving_platform_wall_layers"), &CharacterBody2D::get_moving_platform_wall_layers);
+ ClassDB::bind_method(D_METHOD("set_platform_floor_layers", "exclude_layer"), &CharacterBody2D::set_platform_floor_layers);
+ ClassDB::bind_method(D_METHOD("get_platform_floor_layers"), &CharacterBody2D::get_platform_floor_layers);
+ ClassDB::bind_method(D_METHOD("set_platform_wall_layers", "exclude_layer"), &CharacterBody2D::set_platform_wall_layers);
+ ClassDB::bind_method(D_METHOD("get_platform_wall_layers"), &CharacterBody2D::get_platform_wall_layers);
ClassDB::bind_method(D_METHOD("get_max_slides"), &CharacterBody2D::get_max_slides);
ClassDB::bind_method(D_METHOD("set_max_slides", "max_slides"), &CharacterBody2D::set_max_slides);
@@ -1730,8 +1737,8 @@ void CharacterBody2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_up_direction", "up_direction"), &CharacterBody2D::set_up_direction);
ClassDB::bind_method(D_METHOD("set_motion_mode", "mode"), &CharacterBody2D::set_motion_mode);
ClassDB::bind_method(D_METHOD("get_motion_mode"), &CharacterBody2D::get_motion_mode);
- ClassDB::bind_method(D_METHOD("set_moving_platform_apply_velocity_on_leave", "on_leave_apply_velocity"), &CharacterBody2D::set_moving_platform_apply_velocity_on_leave);
- ClassDB::bind_method(D_METHOD("get_moving_platform_apply_velocity_on_leave"), &CharacterBody2D::get_moving_platform_apply_velocity_on_leave);
+ ClassDB::bind_method(D_METHOD("set_platform_on_leave", "on_leave_apply_velocity"), &CharacterBody2D::set_platform_on_leave);
+ ClassDB::bind_method(D_METHOD("get_platform_on_leave"), &CharacterBody2D::get_platform_on_leave);
ClassDB::bind_method(D_METHOD("is_on_floor"), &CharacterBody2D::is_on_floor);
ClassDB::bind_method(D_METHOD("is_on_floor_only"), &CharacterBody2D::is_on_floor_only);
@@ -1756,34 +1763,38 @@ void CharacterBody2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "slide_on_ceiling"), "set_slide_on_ceiling_enabled", "is_slide_on_ceiling_enabled");
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_slides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_max_slides", "get_max_slides");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wall_min_slide_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians", PROPERTY_USAGE_DEFAULT), "set_wall_min_slide_angle", "get_wall_min_slide_angle");
+
ADD_GROUP("Floor", "floor_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_stop_on_slope"), "set_floor_stop_on_slope_enabled", "is_floor_stop_on_slope_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_constant_speed"), "set_floor_constant_speed_enabled", "is_floor_constant_speed_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_block_on_wall"), "set_floor_block_on_wall_enabled", "is_floor_block_on_wall_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_max_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians"), "set_floor_max_angle", "get_floor_max_angle");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_snap_length", PROPERTY_HINT_RANGE, "0,32,0.1,or_greater,suffix:px"), "set_floor_snap_length", "get_floor_snap_length");
- ADD_GROUP("Moving Platform", "moving_platform");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_apply_velocity_on_leave", PROPERTY_HINT_ENUM, "Always,Upward Only,Never", PROPERTY_USAGE_DEFAULT), "set_moving_platform_apply_velocity_on_leave", "get_moving_platform_apply_velocity_on_leave");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_floor_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_moving_platform_floor_layers", "get_moving_platform_floor_layers");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_wall_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_moving_platform_wall_layers", "get_moving_platform_wall_layers");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision/safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001,suffix:px"), "set_safe_margin", "get_safe_margin");
+
+ ADD_GROUP("Moving Platform", "platform");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_on_leave", PROPERTY_HINT_ENUM, "Add Velocity,Add Upward Velocity,Do Nothing", PROPERTY_USAGE_DEFAULT), "set_platform_on_leave", "get_platform_on_leave");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_floor_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_platform_floor_layers", "get_platform_floor_layers");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_wall_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_platform_wall_layers", "get_platform_wall_layers");
+
+ ADD_GROUP("Collision", "");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001,suffix:px"), "set_safe_margin", "get_safe_margin");
BIND_ENUM_CONSTANT(MOTION_MODE_GROUNDED);
BIND_ENUM_CONSTANT(MOTION_MODE_FLOATING);
- BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_ALWAYS);
- BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY);
- BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_NEVER);
+ BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_VELOCITY);
+ BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY);
+ BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_DO_NOTHING);
}
-void CharacterBody2D::_validate_property(PropertyInfo &property) const {
+void CharacterBody2D::_validate_property(PropertyInfo &p_property) const {
if (motion_mode == MOTION_MODE_FLOATING) {
- if (property.name.begins_with("floor_") || property.name == "up_direction" || property.name == "slide_on_ceiling") {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name.begins_with("floor_") || p_property.name == "up_direction" || p_property.name == "slide_on_ceiling") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
} else {
- if (property.name == "wall_min_slide_angle") {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "wall_min_slide_angle") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
diff --git a/scene/2d/physics_body_2d.h b/scene/2d/physics_body_2d.h
index c762a832c4..fe64c087c6 100644
--- a/scene/2d/physics_body_2d.h
+++ b/scene/2d/physics_body_2d.h
@@ -216,7 +216,7 @@ protected:
void _notification(int p_what);
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
GDVIRTUAL1(_integrate_forces, PhysicsDirectBodyState2D *)
@@ -284,6 +284,7 @@ public:
void set_max_contacts_reported(int p_amount);
int get_max_contacts_reported() const;
+ int get_contact_count() const;
void set_continuous_collision_detection_mode(CCDMode p_mode);
CCDMode get_continuous_collision_detection_mode() const;
@@ -330,10 +331,10 @@ public:
MOTION_MODE_GROUNDED,
MOTION_MODE_FLOATING,
};
- enum MovingPlatformApplyVelocityOnLeave {
- PLATFORM_VEL_ON_LEAVE_ALWAYS,
- PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY,
- PLATFORM_VEL_ON_LEAVE_NEVER,
+ enum PlatformOnLeave {
+ PLATFORM_ON_LEAVE_ADD_VELOCITY,
+ PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY,
+ PLATFORM_ON_LEAVE_DO_NOTHING,
};
bool move_and_slide();
@@ -364,7 +365,7 @@ public:
private:
real_t margin = 0.08;
MotionMode motion_mode = MOTION_MODE_GROUNDED;
- MovingPlatformApplyVelocityOnLeave moving_platform_apply_velocity_on_leave = PLATFORM_VEL_ON_LEAVE_ALWAYS;
+ PlatformOnLeave platform_on_leave = PLATFORM_ON_LEAVE_ADD_VELOCITY;
bool floor_constant_speed = false;
bool floor_stop_on_slope = true;
@@ -376,8 +377,8 @@ private:
real_t floor_snap_length = 1;
real_t wall_min_slide_angle = Math::deg2rad((real_t)15.0);
Vector2 up_direction = Vector2(0.0, -1.0);
- uint32_t moving_platform_floor_layers = UINT32_MAX;
- uint32_t moving_platform_wall_layers = 0;
+ uint32_t platform_floor_layers = UINT32_MAX;
+ uint32_t platform_wall_layers = 0;
Vector2 velocity;
Vector2 floor_normal;
@@ -423,17 +424,17 @@ private:
real_t get_wall_min_slide_angle() const;
void set_wall_min_slide_angle(real_t p_radians);
- uint32_t get_moving_platform_floor_layers() const;
- void set_moving_platform_floor_layers(const uint32_t p_exclude_layer);
+ uint32_t get_platform_floor_layers() const;
+ void set_platform_floor_layers(const uint32_t p_exclude_layer);
- uint32_t get_moving_platform_wall_layers() const;
- void set_moving_platform_wall_layers(const uint32_t p_exclude_layer);
+ uint32_t get_platform_wall_layers() const;
+ void set_platform_wall_layers(const uint32_t p_exclude_layer);
void set_motion_mode(MotionMode p_mode);
MotionMode get_motion_mode() const;
- void set_moving_platform_apply_velocity_on_leave(MovingPlatformApplyVelocityOnLeave p_on_leave_velocity);
- MovingPlatformApplyVelocityOnLeave get_moving_platform_apply_velocity_on_leave() const;
+ void set_platform_on_leave(PlatformOnLeave p_on_leave_velocity);
+ PlatformOnLeave get_platform_on_leave() const;
void _move_and_slide_floating(double p_delta);
void _move_and_slide_grounded(double p_delta, bool p_was_on_floor);
@@ -450,11 +451,11 @@ private:
protected:
void _notification(int p_what);
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
};
VARIANT_ENUM_CAST(CharacterBody2D::MotionMode);
-VARIANT_ENUM_CAST(CharacterBody2D::MovingPlatformApplyVelocityOnLeave);
+VARIANT_ENUM_CAST(CharacterBody2D::PlatformOnLeave);
class KinematicCollision2D : public RefCounted {
GDCLASS(KinematicCollision2D, RefCounted);
diff --git a/scene/2d/polygon_2d.cpp b/scene/2d/polygon_2d.cpp
index ba62941d3a..8161fb5bd9 100644
--- a/scene/2d/polygon_2d.cpp
+++ b/scene/2d/polygon_2d.cpp
@@ -90,9 +90,9 @@ bool Polygon2D::_edit_is_selected_on_click(const Point2 &p_point, double p_toler
}
#endif
-void Polygon2D::_validate_property(PropertyInfo &property) const {
- if (!invert && property.name == "invert_border") {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void Polygon2D::_validate_property(PropertyInfo &p_property) const {
+ if (!invert && p_property.name == "invert_border") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
@@ -602,8 +602,8 @@ void Polygon2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture_scale", "texture_scale"), &Polygon2D::set_texture_scale);
ClassDB::bind_method(D_METHOD("get_texture_scale"), &Polygon2D::get_texture_scale);
- ClassDB::bind_method(D_METHOD("set_invert", "invert"), &Polygon2D::set_invert);
- ClassDB::bind_method(D_METHOD("get_invert"), &Polygon2D::get_invert);
+ ClassDB::bind_method(D_METHOD("set_invert_enabled", "invert"), &Polygon2D::set_invert);
+ ClassDB::bind_method(D_METHOD("get_invert_enabled"), &Polygon2D::get_invert);
ClassDB::bind_method(D_METHOD("set_antialiased", "antialiased"), &Polygon2D::set_antialiased);
ClassDB::bind_method(D_METHOD("get_antialiased"), &Polygon2D::get_antialiased);
@@ -646,7 +646,7 @@ void Polygon2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "skeleton", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Skeleton2D"), "set_skeleton", "get_skeleton");
ADD_GROUP("Invert", "invert_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "invert_enable"), "set_invert", "get_invert");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "invert_enabled"), "set_invert_enabled", "get_invert_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "invert_border", PROPERTY_HINT_RANGE, "0.1,16384,0.1,suffix:px"), "set_invert_border", "get_invert_border");
ADD_GROUP("Data", "");
diff --git a/scene/2d/polygon_2d.h b/scene/2d/polygon_2d.h
index d6a1be0f6d..d333152f62 100644
--- a/scene/2d/polygon_2d.h
+++ b/scene/2d/polygon_2d.h
@@ -77,7 +77,7 @@ class Polygon2D : public Node2D {
protected:
void _notification(int p_what);
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
#ifdef TOOLS_ENABLED
diff --git a/scene/2d/ray_cast_2d.cpp b/scene/2d/ray_cast_2d.cpp
index 68e5ffdcf9..c4036faa79 100644
--- a/scene/2d/ray_cast_2d.cpp
+++ b/scene/2d/ray_cast_2d.cpp
@@ -82,6 +82,10 @@ Object *RayCast2D::get_collider() const {
return ObjectDB::get_instance(against);
}
+RID RayCast2D::get_collider_rid() const {
+ return against_rid;
+}
+
int RayCast2D::get_collider_shape() const {
return against_shape;
}
@@ -203,12 +207,14 @@ void RayCast2D::_update_raycast_state() {
if (dss->intersect_ray(ray_params, rr)) {
collided = true;
against = rr.collider_id;
+ against_rid = rr.rid;
collision_point = rr.position;
collision_normal = rr.normal;
against_shape = rr.shape;
} else {
collided = false;
against = ObjectID();
+ against_rid = RID();
against_shape = 0;
}
@@ -321,6 +327,7 @@ void RayCast2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("force_raycast_update"), &RayCast2D::force_raycast_update);
ClassDB::bind_method(D_METHOD("get_collider"), &RayCast2D::get_collider);
+ ClassDB::bind_method(D_METHOD("get_collider_rid"), &RayCast2D::get_collider_rid);
ClassDB::bind_method(D_METHOD("get_collider_shape"), &RayCast2D::get_collider_shape);
ClassDB::bind_method(D_METHOD("get_collision_point"), &RayCast2D::get_collision_point);
ClassDB::bind_method(D_METHOD("get_collision_normal"), &RayCast2D::get_collision_normal);
diff --git a/scene/2d/ray_cast_2d.h b/scene/2d/ray_cast_2d.h
index 1fb97d89fe..57f993fe8d 100644
--- a/scene/2d/ray_cast_2d.h
+++ b/scene/2d/ray_cast_2d.h
@@ -41,6 +41,7 @@ class RayCast2D : public Node2D {
bool enabled = true;
bool collided = false;
ObjectID against;
+ RID against_rid;
int against_shape = 0;
Vector2 collision_point;
Vector2 collision_normal;
@@ -91,6 +92,7 @@ public:
bool is_colliding() const;
Object *get_collider() const;
+ RID get_collider_rid() const;
int get_collider_shape() const;
Vector2 get_collision_point() const;
Vector2 get_collision_normal() const;
diff --git a/scene/2d/sprite_2d.cpp b/scene/2d/sprite_2d.cpp
index b3062ca02a..e1983f9cb9 100644
--- a/scene/2d/sprite_2d.cpp
+++ b/scene/2d/sprite_2d.cpp
@@ -368,19 +368,19 @@ Rect2 Sprite2D::get_rect() const {
return Rect2(ofs, s);
}
-void Sprite2D::_validate_property(PropertyInfo &property) const {
- if (property.name == "frame") {
- property.hint = PROPERTY_HINT_RANGE;
- property.hint_string = "0," + itos(vframes * hframes - 1) + ",1";
- property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
+void Sprite2D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "frame") {
+ p_property.hint = PROPERTY_HINT_RANGE;
+ p_property.hint_string = "0," + itos(vframes * hframes - 1) + ",1";
+ p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
- if (property.name == "frame_coords") {
- property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
+ if (p_property.name == "frame_coords") {
+ p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
- if (!region_enabled && (property.name == "region_rect" || property.name == "region_filter_clip")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (!region_enabled && (p_property.name == "region_rect" || p_property.name == "region_filter_clip")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
diff --git a/scene/2d/sprite_2d.h b/scene/2d/sprite_2d.h
index 5b33bb6802..60f5940cfe 100644
--- a/scene/2d/sprite_2d.h
+++ b/scene/2d/sprite_2d.h
@@ -64,7 +64,7 @@ protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
#ifdef TOOLS_ENABLED
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index 5ba8c95a06..13bdd2bd5f 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -2063,6 +2063,18 @@ int TileMap::get_cell_alternative_tile(int p_layer, const Vector2i &p_coords, bo
return E->value.alternative_tile;
}
+TileData *TileMap::get_cell_tile_data(int p_layer, const Vector2i &p_coords, bool p_use_proxies) const {
+ int source_id = get_cell_source_id(p_layer, p_coords, p_use_proxies);
+ ERR_FAIL_COND_V_MSG(source_id == TileSet::INVALID_SOURCE, nullptr, vformat("Invalid TileSetSource at cell %s. Make sure a tile exists at this cell.", p_coords));
+
+ Ref<TileSetAtlasSource> source = tile_set->get_source(source_id);
+ if (source.is_valid()) {
+ return source->get_tile_data(get_cell_atlas_coords(p_layer, p_coords, p_use_proxies), get_cell_alternative_tile(p_layer, p_coords, p_use_proxies));
+ }
+
+ return nullptr;
+}
+
Ref<TileMapPattern> TileMap::get_pattern(int p_layer, TypedArray<Vector2i> p_coords_array) {
ERR_FAIL_INDEX_V(p_layer, (int)layers.size(), nullptr);
ERR_FAIL_COND_V(!tile_set.is_valid(), nullptr);
@@ -3846,9 +3858,10 @@ void TileMap::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_cell", "layer", "coords", "source_id", "atlas_coords", "alternative_tile"), &TileMap::set_cell, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(0));
ClassDB::bind_method(D_METHOD("erase_cell", "layer", "coords"), &TileMap::erase_cell);
- ClassDB::bind_method(D_METHOD("get_cell_source_id", "layer", "coords", "use_proxies"), &TileMap::get_cell_source_id);
- ClassDB::bind_method(D_METHOD("get_cell_atlas_coords", "layer", "coords", "use_proxies"), &TileMap::get_cell_atlas_coords);
- ClassDB::bind_method(D_METHOD("get_cell_alternative_tile", "layer", "coords", "use_proxies"), &TileMap::get_cell_alternative_tile);
+ ClassDB::bind_method(D_METHOD("get_cell_source_id", "layer", "coords", "use_proxies"), &TileMap::get_cell_source_id, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_cell_atlas_coords", "layer", "coords", "use_proxies"), &TileMap::get_cell_atlas_coords, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_cell_alternative_tile", "layer", "coords", "use_proxies"), &TileMap::get_cell_alternative_tile, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_cell_tile_data", "layer", "coords", "use_proxies"), &TileMap::get_cell_tile_data, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_coords_for_body_rid", "body"), &TileMap::get_coords_for_body_rid);
diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h
index 012bf01df9..ecc6ee1d59 100644
--- a/scene/2d/tile_map.h
+++ b/scene/2d/tile_map.h
@@ -343,6 +343,8 @@ public:
int get_cell_source_id(int p_layer, const Vector2i &p_coords, bool p_use_proxies = false) const;
Vector2i get_cell_atlas_coords(int p_layer, const Vector2i &p_coords, bool p_use_proxies = false) const;
int get_cell_alternative_tile(int p_layer, const Vector2i &p_coords, bool p_use_proxies = false) const;
+ // Helper method to make accessing the data easier.
+ TileData *get_cell_tile_data(int p_layer, const Vector2i &p_coords, bool p_use_proxies = false) const;
// Patterns.
Ref<TileMapPattern> get_pattern(int p_layer, TypedArray<Vector2i> p_coords_array);
diff --git a/scene/3d/area_3d.cpp b/scene/3d/area_3d.cpp
index e9e19488e9..db7c3233f6 100644
--- a/scene/3d/area_3d.cpp
+++ b/scene/3d/area_3d.cpp
@@ -598,8 +598,8 @@ float Area3D::get_reverb_uniformity() const {
return reverb_uniformity;
}
-void Area3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "audio_bus_name" || property.name == "reverb_bus_name") {
+void Area3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "audio_bus_name" || p_property.name == "reverb_bus_name") {
String options;
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (i > 0) {
@@ -609,32 +609,30 @@ void Area3D::_validate_property(PropertyInfo &property) const {
options += name;
}
- property.hint_string = options;
- } else if (property.name.begins_with("gravity") && property.name != "gravity_space_override") {
+ p_property.hint_string = options;
+ } else if (p_property.name.begins_with("gravity") && p_property.name != "gravity_space_override") {
if (gravity_space_override == SPACE_OVERRIDE_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
} else {
if (gravity_is_point) {
- if (property.name == "gravity_direction") {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "gravity_direction") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
} else {
- if (property.name.begins_with("gravity_point_")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name.begins_with("gravity_point_")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
- } else if (property.name.begins_with("linear_damp") && property.name != "linear_damp_space_override") {
+ } else if (p_property.name.begins_with("linear_damp") && p_property.name != "linear_damp_space_override") {
if (linear_damp_space_override == SPACE_OVERRIDE_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- } else if (property.name.begins_with("angular_damp") && property.name != "angular_damp_space_override") {
+ } else if (p_property.name.begins_with("angular_damp") && p_property.name != "angular_damp_space_override") {
if (angular_damp_space_override == SPACE_OVERRIDE_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
-
- CollisionObject3D::_validate_property(property);
}
void Area3D::_bind_methods() {
diff --git a/scene/3d/area_3d.h b/scene/3d/area_3d.h
index 3b892baf57..48364739b7 100644
--- a/scene/3d/area_3d.h
+++ b/scene/3d/area_3d.h
@@ -141,7 +141,7 @@ private:
float reverb_amount = 0.0;
float reverb_uniformity = 0.0;
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _initialize_wind();
diff --git a/scene/3d/audio_stream_player_3d.cpp b/scene/3d/audio_stream_player_3d.cpp
index 65b00742ee..93e91f9b5b 100644
--- a/scene/3d/audio_stream_player_3d.cpp
+++ b/scene/3d/audio_stream_player_3d.cpp
@@ -648,8 +648,8 @@ bool AudioStreamPlayer3D::_is_active() const {
return active.is_set();
}
-void AudioStreamPlayer3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "bus") {
+void AudioStreamPlayer3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "bus") {
String options;
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (i > 0) {
@@ -659,10 +659,8 @@ void AudioStreamPlayer3D::_validate_property(PropertyInfo &property) const {
options += name;
}
- property.hint_string = options;
+ p_property.hint_string = options;
}
-
- Node3D::_validate_property(property);
}
void AudioStreamPlayer3D::_bus_layout_changed() {
diff --git a/scene/3d/audio_stream_player_3d.h b/scene/3d/audio_stream_player_3d.h
index 647b18a4a7..ef48269544 100644
--- a/scene/3d/audio_stream_player_3d.h
+++ b/scene/3d/audio_stream_player_3d.h
@@ -120,7 +120,7 @@ private:
float cached_global_panning_strength = 1.0f;
protected:
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
static void _bind_methods();
diff --git a/scene/3d/bone_attachment_3d.cpp b/scene/3d/bone_attachment_3d.cpp
index fbd5b5b65b..b3ff6497a7 100644
--- a/scene/3d/bone_attachment_3d.cpp
+++ b/scene/3d/bone_attachment_3d.cpp
@@ -30,8 +30,8 @@
#include "bone_attachment_3d.h"
-void BoneAttachment3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "bone_name") {
+void BoneAttachment3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "bone_name") {
// Because it is a constant function, we cannot use the _get_skeleton_3d function.
const Skeleton3D *parent = nullptr;
if (use_external_skeleton) {
@@ -51,15 +51,13 @@ void BoneAttachment3D::_validate_property(PropertyInfo &property) const {
names += parent->get_bone_name(i);
}
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = names;
+ p_property.hint = PROPERTY_HINT_ENUM;
+ p_property.hint_string = names;
} else {
- property.hint = PROPERTY_HINT_NONE;
- property.hint_string = "";
+ p_property.hint = PROPERTY_HINT_NONE;
+ p_property.hint_string = "";
}
}
-
- Node3D::_validate_property(property);
}
bool BoneAttachment3D::_set(const StringName &p_path, const Variant &p_value) {
diff --git a/scene/3d/bone_attachment_3d.h b/scene/3d/bone_attachment_3d.h
index 3224361a25..f85053e614 100644
--- a/scene/3d/bone_attachment_3d.h
+++ b/scene/3d/bone_attachment_3d.h
@@ -64,7 +64,7 @@ class BoneAttachment3D : public Node3D {
Skeleton3D *_get_skeleton3d();
protected:
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
bool _get(const StringName &p_path, Variant &r_ret) const;
bool _set(const StringName &p_path, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_list) const;
diff --git a/scene/3d/camera_3d.cpp b/scene/3d/camera_3d.cpp
index f654373ee5..b8b6296c45 100644
--- a/scene/3d/camera_3d.cpp
+++ b/scene/3d/camera_3d.cpp
@@ -71,8 +71,6 @@ void Camera3D::_validate_property(PropertyInfo &p_property) const {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
-
- Node3D::_validate_property(p_property);
}
void Camera3D::_update_camera() {
@@ -487,7 +485,7 @@ void Camera3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_keep_aspect_mode"), &Camera3D::get_keep_aspect_mode);
ClassDB::bind_method(D_METHOD("set_doppler_tracking", "mode"), &Camera3D::set_doppler_tracking);
ClassDB::bind_method(D_METHOD("get_doppler_tracking"), &Camera3D::get_doppler_tracking);
- ClassDB::bind_method(D_METHOD("get_frustum"), &Camera3D::get_frustum);
+ ClassDB::bind_method(D_METHOD("get_frustum"), &Camera3D::_get_frustum);
ClassDB::bind_method(D_METHOD("is_position_in_frustum", "world_point"), &Camera3D::is_position_in_frustum);
ClassDB::bind_method(D_METHOD("get_camera_rid"), &Camera3D::get_camera);
ClassDB::bind_method(D_METHOD("get_pyramid_shape_rid"), &Camera3D::get_pyramid_shape_rid);
@@ -617,6 +615,11 @@ Vector<Plane> Camera3D::get_frustum() const {
return cm.get_projection_planes(get_camera_transform());
}
+TypedArray<Plane> Camera3D::_get_frustum() const {
+ Variant ret = get_frustum();
+ return ret;
+}
+
bool Camera3D::is_position_in_frustum(const Vector3 &p_position) const {
Vector<Plane> frustum = get_frustum();
for (int i = 0; i < frustum.size(); i++) {
diff --git a/scene/3d/camera_3d.h b/scene/3d/camera_3d.h
index cedd976890..bba9b7d1e4 100644
--- a/scene/3d/camera_3d.h
+++ b/scene/3d/camera_3d.h
@@ -86,6 +86,7 @@ private:
// void _camera_make_current(Node *p_camera);
friend class Viewport;
void _update_audio_listener_state();
+ TypedArray<Plane> _get_frustum() const;
DopplerTracking doppler_tracking = DOPPLER_TRACKING_DISABLED;
Ref<VelocityTracker3D> velocity_tracker;
@@ -99,7 +100,7 @@ protected:
void _update_camera_mode();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &p_property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
diff --git a/scene/3d/collision_object_3d.cpp b/scene/3d/collision_object_3d.cpp
index 9a5d4f5480..48eb2a66b1 100644
--- a/scene/3d/collision_object_3d.cpp
+++ b/scene/3d/collision_object_3d.cpp
@@ -183,6 +183,17 @@ bool CollisionObject3D::get_collision_mask_value(int p_layer_number) const {
return get_collision_mask() & (1 << (p_layer_number - 1));
}
+void CollisionObject3D::set_collision_priority(real_t p_priority) {
+ collision_priority = p_priority;
+ if (!area) {
+ PhysicsServer3D::get_singleton()->body_set_collision_priority(get_rid(), p_priority);
+ }
+}
+
+real_t CollisionObject3D::get_collision_priority() const {
+ return collision_priority;
+}
+
void CollisionObject3D::set_disable_mode(DisableMode p_mode) {
if (disable_mode == p_mode) {
return;
@@ -432,6 +443,8 @@ void CollisionObject3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_collision_layer_value", "layer_number"), &CollisionObject3D::get_collision_layer_value);
ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &CollisionObject3D::set_collision_mask_value);
ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &CollisionObject3D::get_collision_mask_value);
+ ClassDB::bind_method(D_METHOD("set_collision_priority", "priority"), &CollisionObject3D::set_collision_priority);
+ ClassDB::bind_method(D_METHOD("get_collision_priority"), &CollisionObject3D::get_collision_priority);
ClassDB::bind_method(D_METHOD("set_disable_mode", "mode"), &CollisionObject3D::set_disable_mode);
ClassDB::bind_method(D_METHOD("get_disable_mode"), &CollisionObject3D::get_disable_mode);
ClassDB::bind_method(D_METHOD("set_ray_pickable", "ray_pickable"), &CollisionObject3D::set_ray_pickable);
@@ -466,6 +479,7 @@ void CollisionObject3D::_bind_methods() {
ADD_GROUP("Collision", "collision_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_priority"), "set_collision_priority", "get_collision_priority");
ADD_GROUP("Input", "input_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_ray_pickable"), "set_ray_pickable", "is_ray_pickable");
@@ -532,8 +546,8 @@ void CollisionObject3D::get_shape_owners(List<uint32_t> *r_owners) {
}
}
-Array CollisionObject3D::_get_shape_owners() {
- Array ret;
+PackedInt32Array CollisionObject3D::_get_shape_owners() {
+ PackedInt32Array ret;
for (const KeyValue<uint32_t, ShapeData> &E : shapes) {
ret.push_back(E.key);
}
diff --git a/scene/3d/collision_object_3d.h b/scene/3d/collision_object_3d.h
index 3ec3aa0fc1..51c31da79f 100644
--- a/scene/3d/collision_object_3d.h
+++ b/scene/3d/collision_object_3d.h
@@ -47,6 +47,7 @@ public:
private:
uint32_t collision_layer = 1;
uint32_t collision_mask = 1;
+ real_t collision_priority = 1.0;
bool area = false;
@@ -125,13 +126,16 @@ public:
void set_collision_mask_value(int p_layer_number, bool p_value);
bool get_collision_mask_value(int p_layer_number) const;
+ void set_collision_priority(real_t p_priority);
+ real_t get_collision_priority() const;
+
void set_disable_mode(DisableMode p_mode);
DisableMode get_disable_mode() const;
uint32_t create_shape_owner(Object *p_owner);
void remove_shape_owner(uint32_t owner);
void get_shape_owners(List<uint32_t> *r_owners);
- Array _get_shape_owners();
+ PackedInt32Array _get_shape_owners();
void shape_owner_set_transform(uint32_t p_owner, const Transform3D &p_transform);
Transform3D shape_owner_get_transform(uint32_t p_owner) const;
diff --git a/scene/3d/cpu_particles_3d.cpp b/scene/3d/cpu_particles_3d.cpp
index 4df0c37ad6..a79fd15b1a 100644
--- a/scene/3d/cpu_particles_3d.cpp
+++ b/scene/3d/cpu_particles_3d.cpp
@@ -516,36 +516,34 @@ bool CPUParticles3D::get_split_scale() {
return split_scale;
}
-void CPUParticles3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "emission_sphere_radius" && (emission_shape != EMISSION_SHAPE_SPHERE && emission_shape != EMISSION_SHAPE_SPHERE_SURFACE)) {
- property.usage = PROPERTY_USAGE_NONE;
+void CPUParticles3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "emission_sphere_radius" && (emission_shape != EMISSION_SHAPE_SPHERE && emission_shape != EMISSION_SHAPE_SPHERE_SURFACE)) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_box_extents" && emission_shape != EMISSION_SHAPE_BOX) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_box_extents" && emission_shape != EMISSION_SHAPE_BOX) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if ((property.name == "emission_point_texture" || property.name == "emission_color_texture" || property.name == "emission_points") && (emission_shape != EMISSION_SHAPE_POINTS && (emission_shape != EMISSION_SHAPE_DIRECTED_POINTS))) {
- property.usage = PROPERTY_USAGE_NONE;
+ if ((p_property.name == "emission_point_texture" || p_property.name == "emission_color_texture" || p_property.name == "emission_points") && (emission_shape != EMISSION_SHAPE_POINTS && (emission_shape != EMISSION_SHAPE_DIRECTED_POINTS))) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_normals" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_normals" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("emission_ring_") && emission_shape != EMISSION_SHAPE_RING) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("emission_ring_") && emission_shape != EMISSION_SHAPE_RING) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("orbit_") && !particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("orbit_") && !particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("scale_curve_") && !split_scale) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("scale_curve_") && !split_scale) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
-
- Node3D::_validate_property(property);
}
static uint32_t idhash(uint32_t x) {
diff --git a/scene/3d/cpu_particles_3d.h b/scene/3d/cpu_particles_3d.h
index e26c301038..d84b0aedd2 100644
--- a/scene/3d/cpu_particles_3d.h
+++ b/scene/3d/cpu_particles_3d.h
@@ -198,7 +198,7 @@ private:
protected:
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
AABB get_aabb() const override;
diff --git a/scene/3d/decal.cpp b/scene/3d/decal.cpp
index 0112f24e0c..460402ad1d 100644
--- a/scene/3d/decal.cpp
+++ b/scene/3d/decal.cpp
@@ -152,11 +152,10 @@ AABB Decal::get_aabb() const {
return aabb;
}
-void Decal::_validate_property(PropertyInfo &property) const {
- if (!distance_fade_enabled && (property.name == "distance_fade_begin" || property.name == "distance_fade_length")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void Decal::_validate_property(PropertyInfo &p_property) const {
+ if (!distance_fade_enabled && (p_property.name == "distance_fade_begin" || p_property.name == "distance_fade_length")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- VisualInstance3D::_validate_property(property);
}
TypedArray<String> Decal::get_configuration_warnings() const {
diff --git a/scene/3d/decal.h b/scene/3d/decal.h
index 38da4c14e3..1a7d55b108 100644
--- a/scene/3d/decal.h
+++ b/scene/3d/decal.h
@@ -62,7 +62,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
virtual TypedArray<String> get_configuration_warnings() const override;
diff --git a/scene/3d/fog_volume.cpp b/scene/3d/fog_volume.cpp
index 1b329143b6..319129603e 100644
--- a/scene/3d/fog_volume.cpp
+++ b/scene/3d/fog_volume.cpp
@@ -45,12 +45,11 @@ void FogVolume::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "FogMaterial,ShaderMaterial"), "set_material", "get_material");
}
-void FogVolume::_validate_property(PropertyInfo &property) const {
- if (property.name == "extents" && shape == RS::FOG_VOLUME_SHAPE_WORLD) {
- property.usage = PROPERTY_USAGE_NONE;
+void FogVolume::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "extents" && shape == RS::FOG_VOLUME_SHAPE_WORLD) {
+ p_property.usage = PROPERTY_USAGE_NONE;
return;
}
- VisualInstance3D::_validate_property(property);
}
void FogVolume::set_extents(const Vector3 &p_extents) {
diff --git a/scene/3d/fog_volume.h b/scene/3d/fog_volume.h
index 556a92ad3f..fcdc1e2807 100644
--- a/scene/3d/fog_volume.h
+++ b/scene/3d/fog_volume.h
@@ -49,7 +49,7 @@ class FogVolume : public VisualInstance3D {
protected:
_FORCE_INLINE_ RID _get_volume() { return volume; }
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_extents(const Vector3 &p_extents);
diff --git a/scene/3d/gpu_particles_3d.cpp b/scene/3d/gpu_particles_3d.cpp
index 2ee126e161..b46e6a8b71 100644
--- a/scene/3d/gpu_particles_3d.cpp
+++ b/scene/3d/gpu_particles_3d.cpp
@@ -376,16 +376,14 @@ AABB GPUParticles3D::capture_aabb() const {
return RS::get_singleton()->particles_get_current_aabb(particles);
}
-void GPUParticles3D::_validate_property(PropertyInfo &property) const {
- if (property.name.begins_with("draw_pass_")) {
- int index = property.name.get_slicec('_', 2).to_int() - 1;
+void GPUParticles3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name.begins_with("draw_pass_")) {
+ int index = p_property.name.get_slicec('_', 2).to_int() - 1;
if (index >= draw_passes.size()) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
return;
}
}
-
- GeometryInstance3D::_validate_property(property);
}
void GPUParticles3D::emit_particle(const Transform3D &p_transform, const Vector3 &p_velocity, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags) {
diff --git a/scene/3d/gpu_particles_3d.h b/scene/3d/gpu_particles_3d.h
index 0c745dd734..2ad9672474 100644
--- a/scene/3d/gpu_particles_3d.h
+++ b/scene/3d/gpu_particles_3d.h
@@ -94,7 +94,7 @@ private:
protected:
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
AABB get_aabb() const override;
diff --git a/scene/3d/joint_3d.cpp b/scene/3d/joint_3d.cpp
index b0509475a7..d5cab6728a 100644
--- a/scene/3d/joint_3d.cpp
+++ b/scene/3d/joint_3d.cpp
@@ -221,11 +221,11 @@ void Joint3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_exclude_nodes_from_collision", "enable"), &Joint3D::set_exclude_nodes_from_collision);
ClassDB::bind_method(D_METHOD("get_exclude_nodes_from_collision"), &Joint3D::get_exclude_nodes_from_collision);
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_a", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "PhysicsBody3D"), "set_node_a", "get_node_a");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_b", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "PhysicsBody3D"), "set_node_b", "get_node_b");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "solver/priority", PROPERTY_HINT_RANGE, "1,8,1"), "set_solver_priority", "get_solver_priority");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_a", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "PhysicsBody3D"), "set_node_a", "get_node_a");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_b", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "PhysicsBody3D"), "set_node_b", "get_node_b");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "solver_priority", PROPERTY_HINT_RANGE, "1,8,1"), "set_solver_priority", "get_solver_priority");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision/exclude_nodes"), "set_exclude_nodes_from_collision", "get_exclude_nodes_from_collision");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exclude_nodes_from_collision"), "set_exclude_nodes_from_collision", "get_exclude_nodes_from_collision");
}
Joint3D::Joint3D() {
@@ -292,22 +292,6 @@ PinJoint3D::PinJoint3D() {
///////////////////////////////////
-void HingeJoint3D::_set_upper_limit(real_t p_limit) {
- set_param(PARAM_LIMIT_UPPER, Math::deg2rad(p_limit));
-}
-
-real_t HingeJoint3D::_get_upper_limit() const {
- return Math::rad2deg(get_param(PARAM_LIMIT_UPPER));
-}
-
-void HingeJoint3D::_set_lower_limit(real_t p_limit) {
- set_param(PARAM_LIMIT_LOWER, Math::deg2rad(p_limit));
-}
-
-real_t HingeJoint3D::_get_lower_limit() const {
- return Math::rad2deg(get_param(PARAM_LIMIT_LOWER));
-}
-
void HingeJoint3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &HingeJoint3D::set_param);
ClassDB::bind_method(D_METHOD("get_param", "param"), &HingeJoint3D::get_param);
@@ -315,17 +299,11 @@ void HingeJoint3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_flag", "flag", "enabled"), &HingeJoint3D::set_flag);
ClassDB::bind_method(D_METHOD("get_flag", "flag"), &HingeJoint3D::get_flag);
- ClassDB::bind_method(D_METHOD("_set_upper_limit", "upper_limit"), &HingeJoint3D::_set_upper_limit);
- ClassDB::bind_method(D_METHOD("_get_upper_limit"), &HingeJoint3D::_get_upper_limit);
-
- ClassDB::bind_method(D_METHOD("_set_lower_limit", "lower_limit"), &HingeJoint3D::_set_lower_limit);
- ClassDB::bind_method(D_METHOD("_get_lower_limit"), &HingeJoint3D::_get_lower_limit);
-
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "params/bias", PROPERTY_HINT_RANGE, "0.00,0.99,0.01"), "set_param", "get_param", PARAM_BIAS);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit/enable"), "set_flag", "get_flag", FLAG_USE_LIMIT);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit/upper", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit", "_get_upper_limit");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit/lower", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit", "_get_lower_limit");
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/upper", PROPERTY_HINT_RANGE, "-180,180,0.1,radians"), "set_param", "get_param", PARAM_LIMIT_UPPER);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/lower", PROPERTY_HINT_RANGE, "-180,180,0.1,radians"), "set_param", "get_param", PARAM_LIMIT_LOWER);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_LIMIT_BIAS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/relaxation", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_RELAXATION);
@@ -420,34 +398,10 @@ HingeJoint3D::HingeJoint3D() {
/////////////////////////////////////////////////
-//////////////////////////////////
-
-void SliderJoint3D::_set_upper_limit_angular(real_t p_limit_angular) {
- set_param(PARAM_ANGULAR_LIMIT_UPPER, Math::deg2rad(p_limit_angular));
-}
-
-real_t SliderJoint3D::_get_upper_limit_angular() const {
- return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_UPPER));
-}
-
-void SliderJoint3D::_set_lower_limit_angular(real_t p_limit_angular) {
- set_param(PARAM_ANGULAR_LIMIT_LOWER, Math::deg2rad(p_limit_angular));
-}
-
-real_t SliderJoint3D::_get_lower_limit_angular() const {
- return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_LOWER));
-}
-
void SliderJoint3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &SliderJoint3D::set_param);
ClassDB::bind_method(D_METHOD("get_param", "param"), &SliderJoint3D::get_param);
- ClassDB::bind_method(D_METHOD("_set_upper_limit_angular", "upper_limit_angular"), &SliderJoint3D::_set_upper_limit_angular);
- ClassDB::bind_method(D_METHOD("_get_upper_limit_angular"), &SliderJoint3D::_get_upper_limit_angular);
-
- ClassDB::bind_method(D_METHOD("_set_lower_limit_angular", "lower_limit_angular"), &SliderJoint3D::_set_lower_limit_angular);
- ClassDB::bind_method(D_METHOD("_get_lower_limit_angular"), &SliderJoint3D::_get_lower_limit_angular);
-
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/upper_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01,suffix:m"), "set_param", "get_param", PARAM_LINEAR_LIMIT_UPPER);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/lower_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01,suffix:m"), "set_param", "get_param", PARAM_LINEAR_LIMIT_LOWER);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_SOFTNESS);
@@ -460,8 +414,8 @@ void SliderJoint3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_ortho/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_ortho/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_DAMPING);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit_angular", "_get_upper_limit_angular");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit_angular", "_get_lower_limit_angular");
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.1,radians"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_UPPER);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.1,radians"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_LOWER);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_DAMPING);
@@ -562,34 +516,12 @@ SliderJoint3D::SliderJoint3D() {
//////////////////////////////////
-void ConeTwistJoint3D::_set_swing_span(real_t p_limit_angular) {
- set_param(PARAM_SWING_SPAN, Math::deg2rad(p_limit_angular));
-}
-
-real_t ConeTwistJoint3D::_get_swing_span() const {
- return Math::rad2deg(get_param(PARAM_SWING_SPAN));
-}
-
-void ConeTwistJoint3D::_set_twist_span(real_t p_limit_angular) {
- set_param(PARAM_TWIST_SPAN, Math::deg2rad(p_limit_angular));
-}
-
-real_t ConeTwistJoint3D::_get_twist_span() const {
- return Math::rad2deg(get_param(PARAM_TWIST_SPAN));
-}
-
void ConeTwistJoint3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &ConeTwistJoint3D::set_param);
ClassDB::bind_method(D_METHOD("get_param", "param"), &ConeTwistJoint3D::get_param);
- ClassDB::bind_method(D_METHOD("_set_swing_span", "swing_span"), &ConeTwistJoint3D::_set_swing_span);
- ClassDB::bind_method(D_METHOD("_get_swing_span"), &ConeTwistJoint3D::_get_swing_span);
-
- ClassDB::bind_method(D_METHOD("_set_twist_span", "twist_span"), &ConeTwistJoint3D::_set_twist_span);
- ClassDB::bind_method(D_METHOD("_get_twist_span"), &ConeTwistJoint3D::_get_twist_span);
-
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "swing_span", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_swing_span", "_get_swing_span");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "twist_span", PROPERTY_HINT_RANGE, "-40000,40000,0.1"), "_set_twist_span", "_get_twist_span");
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "swing_span", PROPERTY_HINT_RANGE, "-180,180,0.1,radians"), "set_param", "get_param", PARAM_SWING_SPAN);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "twist_span", PROPERTY_HINT_RANGE, "-40000,40000,0.1,radians"), "set_param", "get_param", PARAM_TWIST_SPAN);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "bias", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_BIAS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_SOFTNESS);
@@ -620,8 +552,6 @@ real_t ConeTwistJoint3D::get_param(Param p_param) const {
void ConeTwistJoint3D::_configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) {
Transform3D gt = get_global_transform();
- //Vector3 cone_twistpos = gt.origin;
- //Vector3 cone_twistdir = gt.basis.get_axis(2);
Transform3D ainv = body_a->get_global_transform().affine_inverse();
@@ -652,73 +582,7 @@ ConeTwistJoint3D::ConeTwistJoint3D() {
/////////////////////////////////////////////////////////////////////
-void Generic6DOFJoint3D::_set_angular_hi_limit_x(real_t p_limit_angular) {
- set_param_x(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
-}
-
-real_t Generic6DOFJoint3D::_get_angular_hi_limit_x() const {
- return Math::rad2deg(get_param_x(PARAM_ANGULAR_UPPER_LIMIT));
-}
-
-void Generic6DOFJoint3D::_set_angular_lo_limit_x(real_t p_limit_angular) {
- set_param_x(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
-}
-
-real_t Generic6DOFJoint3D::_get_angular_lo_limit_x() const {
- return Math::rad2deg(get_param_x(PARAM_ANGULAR_LOWER_LIMIT));
-}
-
-void Generic6DOFJoint3D::_set_angular_hi_limit_y(real_t p_limit_angular) {
- set_param_y(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
-}
-
-real_t Generic6DOFJoint3D::_get_angular_hi_limit_y() const {
- return Math::rad2deg(get_param_y(PARAM_ANGULAR_UPPER_LIMIT));
-}
-
-void Generic6DOFJoint3D::_set_angular_lo_limit_y(real_t p_limit_angular) {
- set_param_y(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
-}
-
-real_t Generic6DOFJoint3D::_get_angular_lo_limit_y() const {
- return Math::rad2deg(get_param_y(PARAM_ANGULAR_LOWER_LIMIT));
-}
-
-void Generic6DOFJoint3D::_set_angular_hi_limit_z(real_t p_limit_angular) {
- set_param_z(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
-}
-
-real_t Generic6DOFJoint3D::_get_angular_hi_limit_z() const {
- return Math::rad2deg(get_param_z(PARAM_ANGULAR_UPPER_LIMIT));
-}
-
-void Generic6DOFJoint3D::_set_angular_lo_limit_z(real_t p_limit_angular) {
- set_param_z(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
-}
-
-real_t Generic6DOFJoint3D::_get_angular_lo_limit_z() const {
- return Math::rad2deg(get_param_z(PARAM_ANGULAR_LOWER_LIMIT));
-}
-
void Generic6DOFJoint3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_x", "angle"), &Generic6DOFJoint3D::_set_angular_hi_limit_x);
- ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_x"), &Generic6DOFJoint3D::_get_angular_hi_limit_x);
-
- ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_x", "angle"), &Generic6DOFJoint3D::_set_angular_lo_limit_x);
- ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_x"), &Generic6DOFJoint3D::_get_angular_lo_limit_x);
-
- ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_y", "angle"), &Generic6DOFJoint3D::_set_angular_hi_limit_y);
- ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_y"), &Generic6DOFJoint3D::_get_angular_hi_limit_y);
-
- ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_y", "angle"), &Generic6DOFJoint3D::_set_angular_lo_limit_y);
- ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_y"), &Generic6DOFJoint3D::_get_angular_lo_limit_y);
-
- ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_z", "angle"), &Generic6DOFJoint3D::_set_angular_hi_limit_z);
- ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_z"), &Generic6DOFJoint3D::_get_angular_hi_limit_z);
-
- ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_z", "angle"), &Generic6DOFJoint3D::_set_angular_lo_limit_z);
- ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_z"), &Generic6DOFJoint3D::_get_angular_lo_limit_z);
-
ClassDB::bind_method(D_METHOD("set_param_x", "param", "value"), &Generic6DOFJoint3D::set_param_x);
ClassDB::bind_method(D_METHOD("get_param_x", "param"), &Generic6DOFJoint3D::get_param_x);
@@ -794,8 +658,8 @@ void Generic6DOFJoint3D::_bind_methods() {
ADD_GROUP("Angular Limit", "angular_limit_");
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_ANGULAR_LIMIT);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit_x/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_x", "_get_angular_hi_limit_x");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit_x/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_x", "_get_angular_lo_limit_x");
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_x/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01,radians"), "set_param_x", "get_param_x", PARAM_ANGULAR_UPPER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_x/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01,radians"), "set_param_x", "get_param_x", PARAM_ANGULAR_LOWER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_x/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_x/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_x/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_DAMPING);
@@ -803,8 +667,8 @@ void Generic6DOFJoint3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_x/erp"), "set_param_x", "get_param_x", PARAM_ANGULAR_ERP);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_ANGULAR_LIMIT);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit_y/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_y", "_get_angular_hi_limit_y");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit_y/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_y", "_get_angular_lo_limit_y");
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_y/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01,radians"), "set_param_y", "get_param_y", PARAM_ANGULAR_UPPER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_y/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01,radians"), "set_param_y", "get_param_y", PARAM_ANGULAR_LOWER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_y/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_y/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_y/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_DAMPING);
@@ -812,8 +676,8 @@ void Generic6DOFJoint3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_y/erp"), "set_param_y", "get_param_y", PARAM_ANGULAR_ERP);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_ANGULAR_LIMIT);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit_z/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_z", "_get_angular_hi_limit_z");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_limit_z/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_z", "_get_angular_lo_limit_z");
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_z/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01,radians"), "set_param_z", "get_param_z", PARAM_ANGULAR_UPPER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_z/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01,radians"), "set_param_z", "get_param_z", PARAM_ANGULAR_LOWER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_z/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_z/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit_z/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_DAMPING);
diff --git a/scene/3d/joint_3d.h b/scene/3d/joint_3d.h
index ea356ef3b7..cb967023e8 100644
--- a/scene/3d/joint_3d.h
+++ b/scene/3d/joint_3d.h
@@ -136,12 +136,6 @@ protected:
virtual void _configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) override;
static void _bind_methods();
- void _set_upper_limit(real_t p_limit);
- real_t _get_upper_limit() const;
-
- void _set_lower_limit(real_t p_limit);
- real_t _get_lower_limit() const;
-
public:
void set_param(Param p_param, real_t p_value);
real_t get_param(Param p_param) const;
@@ -188,12 +182,6 @@ public:
};
protected:
- void _set_upper_limit_angular(real_t p_limit_angular);
- real_t _get_upper_limit_angular() const;
-
- void _set_lower_limit_angular(real_t p_limit_angular);
- real_t _get_lower_limit_angular() const;
-
real_t params[PARAM_MAX];
virtual void _configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) override;
static void _bind_methods();
@@ -221,12 +209,6 @@ public:
};
protected:
- void _set_swing_span(real_t p_limit_angular);
- real_t _get_swing_span() const;
-
- void _set_twist_span(real_t p_limit_angular);
- real_t _get_twist_span() const;
-
real_t params[PARAM_MAX];
virtual void _configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) override;
static void _bind_methods();
@@ -281,24 +263,6 @@ public:
};
protected:
- void _set_angular_hi_limit_x(real_t p_limit_angular);
- real_t _get_angular_hi_limit_x() const;
-
- void _set_angular_hi_limit_y(real_t p_limit_angular);
- real_t _get_angular_hi_limit_y() const;
-
- void _set_angular_hi_limit_z(real_t p_limit_angular);
- real_t _get_angular_hi_limit_z() const;
-
- void _set_angular_lo_limit_x(real_t p_limit_angular);
- real_t _get_angular_lo_limit_x() const;
-
- void _set_angular_lo_limit_y(real_t p_limit_angular);
- real_t _get_angular_lo_limit_y() const;
-
- void _set_angular_lo_limit_z(real_t p_limit_angular);
- real_t _get_angular_lo_limit_z() const;
-
real_t params_x[PARAM_MAX];
bool flags_x[FLAG_MAX];
real_t params_y[PARAM_MAX];
diff --git a/scene/3d/label_3d.cpp b/scene/3d/label_3d.cpp
index 712a37e745..35036b70d8 100644
--- a/scene/3d/label_3d.cpp
+++ b/scene/3d/label_3d.cpp
@@ -162,9 +162,19 @@ void Label3D::_bind_methods() {
BIND_ENUM_CONSTANT(ALPHA_CUT_OPAQUE_PREPASS);
}
-void Label3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "material_override" || property.name == "material_overlay") {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void Label3D::_validate_property(PropertyInfo &p_property) const {
+ if (
+ p_property.name == "material_override" ||
+ p_property.name == "material_overlay" ||
+ p_property.name == "lod_bias" ||
+ p_property.name == "gi_mode" ||
+ p_property.name == "gi_lightmap_scale") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+
+ if (p_property.name == "cast_shadow" && alpha_cut == ALPHA_CUT_DISABLED) {
+ // Alpha-blended materials can't cast shadows.
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
@@ -422,7 +432,7 @@ void Label3D::_shape() {
TS->shaped_text_set_spacing(text_rid, TextServer::SpacingType(i), font->get_spacing(TextServer::SpacingType(i)));
}
- Array stt;
+ TypedArray<Vector2i> stt;
if (st_parser == TextServer::STRUCTURED_TEXT_CUSTOM) {
GDVIRTUAL_CALL(_structured_text_parser, st_args, text, stt);
} else {
@@ -889,6 +899,7 @@ void Label3D::set_alpha_cut_mode(AlphaCutMode p_mode) {
if (alpha_cut != p_mode) {
alpha_cut = p_mode;
_queue_update();
+ notify_property_list_changed();
}
}
@@ -927,7 +938,12 @@ Label3D::Label3D() {
mesh = RenderingServer::get_singleton()->mesh_create();
+ // Disable shadow casting by default to improve performance and avoid unintended visual artifacts.
set_cast_shadows_setting(SHADOW_CASTING_SETTING_OFF);
+
+ // Label3D can't contribute to GI in any way, so disable it to improve performance.
+ set_gi_mode(GI_MODE_DISABLED);
+
set_base(mesh);
}
diff --git a/scene/3d/label_3d.h b/scene/3d/label_3d.h
index d4bfe743a6..3c9a758e6e 100644
--- a/scene/3d/label_3d.h
+++ b/scene/3d/label_3d.h
@@ -149,7 +149,7 @@ protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _im_update();
void _font_changed();
diff --git a/scene/3d/light_3d.cpp b/scene/3d/light_3d.cpp
index 53c072c318..0581544e07 100644
--- a/scene/3d/light_3d.cpp
+++ b/scene/3d/light_3d.cpp
@@ -223,21 +223,19 @@ bool Light3D::is_editor_only() const {
return editor_only;
}
-void Light3D::_validate_property(PropertyInfo &property) const {
- if (!shadow && (property.name == "shadow_bias" || property.name == "shadow_normal_bias" || property.name == "shadow_reverse_cull_face" || property.name == "shadow_transmittance_bias" || property.name == "shadow_fog_fade" || property.name == "shadow_opacity" || property.name == "shadow_blur" || property.name == "distance_fade_shadow")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void Light3D::_validate_property(PropertyInfo &p_property) const {
+ if (!shadow && (p_property.name == "shadow_bias" || p_property.name == "shadow_normal_bias" || p_property.name == "shadow_reverse_cull_face" || p_property.name == "shadow_transmittance_bias" || p_property.name == "shadow_fog_fade" || p_property.name == "shadow_opacity" || p_property.name == "shadow_blur" || p_property.name == "distance_fade_shadow")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (get_light_type() != RS::LIGHT_DIRECTIONAL && property.name == "light_angular_distance") {
+ if (get_light_type() != RS::LIGHT_DIRECTIONAL && p_property.name == "light_angular_distance") {
// Angular distance is only used in DirectionalLight3D.
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (!distance_fade_enabled && (property.name == "distance_fade_begin" || property.name == "distance_fade_shadow" || property.name == "distance_fade_length")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (!distance_fade_enabled && (p_property.name == "distance_fade_begin" || p_property.name == "distance_fade_shadow" || p_property.name == "distance_fade_length")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
-
- VisualInstance3D::_validate_property(property);
}
void Light3D::_bind_methods() {
@@ -429,29 +427,27 @@ DirectionalLight3D::SkyMode DirectionalLight3D::get_sky_mode() const {
return sky_mode;
}
-void DirectionalLight3D::_validate_property(PropertyInfo &property) const {
- if (shadow_mode == SHADOW_ORTHOGONAL && (property.name == "directional_shadow_split_1" || property.name == "directional_shadow_blend_splits")) {
+void DirectionalLight3D::_validate_property(PropertyInfo &p_property) const {
+ if (shadow_mode == SHADOW_ORTHOGONAL && (p_property.name == "directional_shadow_split_1" || p_property.name == "directional_shadow_blend_splits")) {
// Split 2 and split blending are only used with the PSSM 2 Splits and PSSM 4 Splits shadow modes.
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if ((shadow_mode == SHADOW_ORTHOGONAL || shadow_mode == SHADOW_PARALLEL_2_SPLITS) && (property.name == "directional_shadow_split_2" || property.name == "directional_shadow_split_3")) {
+ if ((shadow_mode == SHADOW_ORTHOGONAL || shadow_mode == SHADOW_PARALLEL_2_SPLITS) && (p_property.name == "directional_shadow_split_2" || p_property.name == "directional_shadow_split_3")) {
// Splits 3 and 4 are only used with the PSSM 4 Splits shadow mode.
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "light_size" || property.name == "light_projector" || property.name == "light_specular") {
+ if (p_property.name == "light_size" || p_property.name == "light_projector" || p_property.name == "light_specular") {
// Not implemented in DirectionalLight3D (`light_size` is replaced by `light_angular_distance`).
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "distance_fade_enabled" || property.name == "distance_fade_begin" || property.name == "distance_fade_shadow" || property.name == "distance_fade_length") {
+ if (p_property.name == "distance_fade_enabled" || p_property.name == "distance_fade_begin" || p_property.name == "distance_fade_shadow" || p_property.name == "distance_fade_length") {
// Not relevant for DirectionalLight3D, as the light LOD system only pertains to point lights.
// For DirectionalLight3D, `directional_shadow_max_distance` can be used instead.
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
-
- Light3D::_validate_property(property);
}
void DirectionalLight3D::_bind_methods() {
diff --git a/scene/3d/light_3d.h b/scene/3d/light_3d.h
index ef003e133d..035ba50e42 100644
--- a/scene/3d/light_3d.h
+++ b/scene/3d/light_3d.h
@@ -93,7 +93,7 @@ protected:
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
Light3D(RenderingServer::LightType p_type);
@@ -171,7 +171,7 @@ private:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_shadow_mode(ShadowMode p_mode);
diff --git a/scene/3d/lightmap_gi.cpp b/scene/3d/lightmap_gi.cpp
index 6b6a2eff9e..7efda6db32 100644
--- a/scene/3d/lightmap_gi.cpp
+++ b/scene/3d/lightmap_gi.cpp
@@ -1410,17 +1410,16 @@ LightmapGI::GenerateProbes LightmapGI::get_generate_probes() const {
return gen_probes;
}
-void LightmapGI::_validate_property(PropertyInfo &property) const {
- if (property.name == "environment_custom_sky" && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
- property.usage = PROPERTY_USAGE_NONE;
+void LightmapGI::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "environment_custom_sky" && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "environment_custom_color" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "environment_custom_color" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "environment_custom_energy" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "environment_custom_energy" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- VisualInstance3D::_validate_property(property);
}
void LightmapGI::_bind_methods() {
diff --git a/scene/3d/lightmap_gi.h b/scene/3d/lightmap_gi.h
index 85150b833f..87add9facc 100644
--- a/scene/3d/lightmap_gi.h
+++ b/scene/3d/lightmap_gi.h
@@ -216,7 +216,7 @@ private:
void _gen_new_positions_from_octree(const GenProbesOctree *p_cell, float p_cell_size, const Vector<Vector3> &probe_positions, LocalVector<Vector3> &new_probe_positions, HashMap<Vector3i, bool> &positions_used, const AABB &p_bounds);
protected:
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
void _notification(int p_what);
diff --git a/scene/3d/position_3d.cpp b/scene/3d/marker_3d.cpp
index 7dc1b1ace0..3987172561 100644
--- a/scene/3d/position_3d.cpp
+++ b/scene/3d/marker_3d.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* position_3d.cpp */
+/* marker_3d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,7 +28,7 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "position_3d.h"
+#include "marker_3d.h"
-Position3D::Position3D() {
+Marker3D::Marker3D() {
}
diff --git a/scene/3d/position_3d.h b/scene/3d/marker_3d.h
index 5514399e6e..95caa101c5 100644
--- a/scene/3d/position_3d.h
+++ b/scene/3d/marker_3d.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* position_3d.h */
+/* marker_3d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,16 +28,16 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef POSITION_3D_H
-#define POSITION_3D_H
+#ifndef MARKER_3D_H
+#define MARKER_3D_H
#include "scene/3d/node_3d.h"
-class Position3D : public Node3D {
- GDCLASS(Position3D, Node3D);
+class Marker3D : public Node3D {
+ GDCLASS(Marker3D, Node3D);
public:
- Position3D();
+ Marker3D();
};
-#endif // POSITION_3D_H
+#endif // MARKER_3D_H
diff --git a/scene/3d/navigation_agent_3d.cpp b/scene/3d/navigation_agent_3d.cpp
index 3752713d6a..34e84861a2 100644
--- a/scene/3d/navigation_agent_3d.cpp
+++ b/scene/3d/navigation_agent_3d.cpp
@@ -53,8 +53,8 @@ void NavigationAgent3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_ignore_y", "ignore"), &NavigationAgent3D::set_ignore_y);
ClassDB::bind_method(D_METHOD("get_ignore_y"), &NavigationAgent3D::get_ignore_y);
- ClassDB::bind_method(D_METHOD("set_neighbor_dist", "neighbor_dist"), &NavigationAgent3D::set_neighbor_dist);
- ClassDB::bind_method(D_METHOD("get_neighbor_dist"), &NavigationAgent3D::get_neighbor_dist);
+ ClassDB::bind_method(D_METHOD("set_neighbor_distance", "neighbor_distance"), &NavigationAgent3D::set_neighbor_distance);
+ ClassDB::bind_method(D_METHOD("get_neighbor_distance"), &NavigationAgent3D::get_neighbor_distance);
ClassDB::bind_method(D_METHOD("set_max_neighbors", "max_neighbors"), &NavigationAgent3D::set_max_neighbors);
ClassDB::bind_method(D_METHOD("get_max_neighbors"), &NavigationAgent3D::get_max_neighbors);
@@ -101,7 +101,7 @@ void NavigationAgent3D::_bind_methods() {
ADD_GROUP("Avoidance", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "avoidance_enabled"), "set_avoidance_enabled", "get_avoidance_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.1,100,0.01,suffix:m"), "set_radius", "get_radius");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "neighbor_dist", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:m"), "set_neighbor_dist", "get_neighbor_dist");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "neighbor_distance", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:m"), "set_neighbor_distance", "get_neighbor_distance");
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_neighbors", PROPERTY_HINT_RANGE, "1,10000,1"), "set_max_neighbors", "get_max_neighbors");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_horizon", PROPERTY_HINT_RANGE, "0.01,100,0.01,suffix:s"), "set_time_horizon", "get_time_horizon");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_speed", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:m/s"), "set_max_speed", "get_max_speed");
@@ -179,7 +179,7 @@ void NavigationAgent3D::_notification(int p_what) {
NavigationAgent3D::NavigationAgent3D() {
agent = NavigationServer3D::get_singleton()->agent_create();
- set_neighbor_dist(50.0);
+ set_neighbor_distance(50.0);
set_max_neighbors(10);
set_time_horizon(5.0);
set_radius(1.0);
@@ -291,9 +291,9 @@ void NavigationAgent3D::set_ignore_y(bool p_ignore_y) {
NavigationServer3D::get_singleton()->agent_set_ignore_y(agent, ignore_y);
}
-void NavigationAgent3D::set_neighbor_dist(real_t p_dist) {
- neighbor_dist = p_dist;
- NavigationServer3D::get_singleton()->agent_set_neighbor_dist(agent, neighbor_dist);
+void NavigationAgent3D::set_neighbor_distance(real_t p_distance) {
+ neighbor_distance = p_distance;
+ NavigationServer3D::get_singleton()->agent_set_neighbor_distance(agent, neighbor_distance);
}
void NavigationAgent3D::set_max_neighbors(int p_count) {
diff --git a/scene/3d/navigation_agent_3d.h b/scene/3d/navigation_agent_3d.h
index e05f0287f7..35c1b1175a 100644
--- a/scene/3d/navigation_agent_3d.h
+++ b/scene/3d/navigation_agent_3d.h
@@ -52,7 +52,7 @@ class NavigationAgent3D : public Node {
real_t radius = 0.0;
real_t navigation_height_offset = 0.0;
bool ignore_y = false;
- real_t neighbor_dist = 0.0;
+ real_t neighbor_distance = 0.0;
int max_neighbors = 0;
real_t time_horizon = 0.0;
real_t max_speed = 0.0;
@@ -122,9 +122,9 @@ public:
return ignore_y;
}
- void set_neighbor_dist(real_t p_dist);
- real_t get_neighbor_dist() const {
- return neighbor_dist;
+ void set_neighbor_distance(real_t p_distance);
+ real_t get_neighbor_distance() const {
+ return neighbor_distance;
}
void set_max_neighbors(int p_count);
diff --git a/scene/3d/navigation_obstacle_3d.cpp b/scene/3d/navigation_obstacle_3d.cpp
index c6eda1f9cd..ef9e191f69 100644
--- a/scene/3d/navigation_obstacle_3d.cpp
+++ b/scene/3d/navigation_obstacle_3d.cpp
@@ -141,7 +141,7 @@ TypedArray<String> NavigationObstacle3D::get_configuration_warnings() const {
}
void NavigationObstacle3D::initialize_agent() {
- NavigationServer3D::get_singleton()->agent_set_neighbor_dist(agent, 0.0);
+ NavigationServer3D::get_singleton()->agent_set_neighbor_distance(agent, 0.0);
NavigationServer3D::get_singleton()->agent_set_max_neighbors(agent, 0);
NavigationServer3D::get_singleton()->agent_set_time_horizon(agent, 0.0);
NavigationServer3D::get_singleton()->agent_set_max_speed(agent, 0.0);
diff --git a/scene/3d/navigation_obstacle_3d.h b/scene/3d/navigation_obstacle_3d.h
index 0316fc37a8..7f6af668b6 100644
--- a/scene/3d/navigation_obstacle_3d.h
+++ b/scene/3d/navigation_obstacle_3d.h
@@ -45,7 +45,7 @@ class NavigationObstacle3D : public Node {
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &p_property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
public:
diff --git a/scene/3d/node_3d.cpp b/scene/3d/node_3d.cpp
index 1de85d57a3..426a8c1684 100644
--- a/scene/3d/node_3d.cpp
+++ b/scene/3d/node_3d.cpp
@@ -561,8 +561,8 @@ void Node3D::clear_gizmos() {
#endif
}
-Array Node3D::get_gizmos_bind() const {
- Array ret;
+TypedArray<Node3DGizmo> Node3D::get_gizmos_bind() const {
+ TypedArray<Node3DGizmo> ret;
#ifdef TOOLS_ENABLED
for (int i = 0; i < data.gizmos.size(); i++) {
@@ -879,25 +879,25 @@ NodePath Node3D::get_visibility_parent() const {
return visibility_parent_path;
}
-void Node3D::_validate_property(PropertyInfo &property) const {
- if (data.rotation_edit_mode != ROTATION_EDIT_MODE_BASIS && property.name == "basis") {
- property.usage = 0;
+void Node3D::_validate_property(PropertyInfo &p_property) const {
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_BASIS && p_property.name == "basis") {
+ p_property.usage = 0;
}
- if (data.rotation_edit_mode == ROTATION_EDIT_MODE_BASIS && property.name == "scale") {
- property.usage = 0;
+ if (data.rotation_edit_mode == ROTATION_EDIT_MODE_BASIS && p_property.name == "scale") {
+ p_property.usage = 0;
}
- if (data.rotation_edit_mode != ROTATION_EDIT_MODE_QUATERNION && property.name == "quaternion") {
- property.usage = 0;
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_QUATERNION && p_property.name == "quaternion") {
+ p_property.usage = 0;
}
- if (data.rotation_edit_mode != ROTATION_EDIT_MODE_EULER && property.name == "rotation") {
- property.usage = 0;
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_EULER && p_property.name == "rotation") {
+ p_property.usage = 0;
}
- if (data.rotation_edit_mode != ROTATION_EDIT_MODE_EULER && property.name == "rotation_order") {
- property.usage = 0;
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_EULER && p_property.name == "rotation_order") {
+ p_property.usage = 0;
}
}
-bool Node3D::property_can_revert(const String &p_name) {
+bool Node3D::_property_can_revert(const StringName &p_name) const {
if (p_name == "basis") {
return true;
} else if (p_name == "scale") {
@@ -912,47 +912,48 @@ bool Node3D::property_can_revert(const String &p_name) {
return false;
}
-Variant Node3D::property_get_revert(const String &p_name) {
- Variant r_ret;
+bool Node3D::_property_get_revert(const StringName &p_name, Variant &r_property) const {
bool valid = false;
if (p_name == "basis") {
Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
- r_ret = Transform3D(variant).get_basis();
+ r_property = Transform3D(variant).get_basis();
} else {
- r_ret = Basis();
+ r_property = Basis();
}
} else if (p_name == "scale") {
Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
- r_ret = Transform3D(variant).get_basis().get_scale();
+ r_property = Transform3D(variant).get_basis().get_scale();
} else {
- return Vector3(1.0, 1.0, 1.0);
+ r_property = Vector3(1.0, 1.0, 1.0);
}
} else if (p_name == "quaternion") {
Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
- r_ret = Quaternion(Transform3D(variant).get_basis().get_rotation_quaternion());
+ r_property = Quaternion(Transform3D(variant).get_basis().get_rotation_quaternion());
} else {
- return Quaternion();
+ r_property = Quaternion();
}
} else if (p_name == "rotation") {
Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
- r_ret = Transform3D(variant).get_basis().get_euler_normalized(data.euler_rotation_order);
+ r_property = Transform3D(variant).get_basis().get_euler_normalized(data.euler_rotation_order);
} else {
- return Vector3();
+ r_property = Vector3();
}
} else if (p_name == "position") {
Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
if (valid) {
- r_ret = Transform3D(variant).get_origin();
+ r_property = Transform3D(variant).get_origin();
} else {
- return Vector3();
+ r_property = Vector3();
}
+ } else {
+ return false;
}
- return r_ret;
+ return true;
}
void Node3D::_bind_methods() {
@@ -1032,9 +1033,6 @@ void Node3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("to_local", "global_point"), &Node3D::to_local);
ClassDB::bind_method(D_METHOD("to_global", "local_point"), &Node3D::to_global);
- ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &Node3D::property_can_revert);
- ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &Node3D::property_get_revert);
-
BIND_CONSTANT(NOTIFICATION_TRANSFORM_CHANGED);
BIND_CONSTANT(NOTIFICATION_ENTER_WORLD);
BIND_CONSTANT(NOTIFICATION_EXIT_WORLD);
@@ -1056,7 +1054,7 @@ void Node3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "global_transform", PROPERTY_HINT_NONE, "suffix:m", PROPERTY_USAGE_NONE), "set_global_transform", "get_global_transform");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "position", PROPERTY_HINT_RANGE, "-99999,99999,0.001,or_greater,or_lesser,no_slider,suffix:m", PROPERTY_USAGE_EDITOR), "set_position", "get_position");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation", PROPERTY_HINT_RANGE, "-360,360,0.1,or_lesser,or_greater,radians", PROPERTY_USAGE_EDITOR), "set_rotation", "get_rotation");
- ADD_PROPERTY(PropertyInfo(Variant::QUATERNION, "quaternion", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_quaternion", "get_quaternion");
+ ADD_PROPERTY(PropertyInfo(Variant::QUATERNION, "quaternion", PROPERTY_HINT_HIDE_QUATERNION_EDIT, "", PROPERTY_USAGE_EDITOR), "set_quaternion", "get_quaternion");
ADD_PROPERTY(PropertyInfo(Variant::BASIS, "basis", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_basis", "get_basis");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale", PROPERTY_HINT_LINK, "", PROPERTY_USAGE_EDITOR), "set_scale", "get_scale");
ADD_PROPERTY(PropertyInfo(Variant::INT, "rotation_edit_mode", PROPERTY_HINT_ENUM, "Euler,Quaternion,Basis"), "set_rotation_edit_mode", "get_rotation_edit_mode");
diff --git a/scene/3d/node_3d.h b/scene/3d/node_3d.h
index b1e129798d..90c7bc89ef 100644
--- a/scene/3d/node_3d.h
+++ b/scene/3d/node_3d.h
@@ -155,10 +155,10 @@ protected:
void _notification(int p_what);
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
- bool property_can_revert(const String &p_name);
- Variant property_get_revert(const String &p_name);
+ bool _property_can_revert(const StringName &p_name) const;
+ bool _property_get_revert(const StringName &p_name, Variant &r_property) const;
public:
enum {
@@ -216,7 +216,7 @@ public:
void set_subgizmo_selection(Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform = Transform3D());
void clear_subgizmo_selection();
Vector<Ref<Node3DGizmo>> get_gizmos() const;
- Array get_gizmos_bind() const;
+ TypedArray<Node3DGizmo> get_gizmos_bind() const;
void add_gizmo(Ref<Node3DGizmo> p_gizmo);
void remove_gizmo(Ref<Node3DGizmo> p_gizmo);
void clear_gizmos();
diff --git a/scene/3d/path_3d.cpp b/scene/3d/path_3d.cpp
index 25226ad384..7d79d9b4fd 100644
--- a/scene/3d/path_3d.cpp
+++ b/scene/3d/path_3d.cpp
@@ -183,8 +183,8 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
return;
}
real_t bi = c->get_bake_interval();
- real_t o_next = offset + bi;
- real_t o_prev = offset - bi;
+ real_t o_next = progress + bi;
+ real_t o_prev = progress - bi;
if (loop) {
o_next = Math::fposmod(o_next, bl);
@@ -198,7 +198,7 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
}
}
- Vector3 pos = c->interpolate_baked(offset, cubic);
+ Vector3 pos = c->interpolate_baked(progress, cubic);
Transform3D t = get_transform();
// Vector3 pos_offset = Vector3(h_offset, v_offset, 0); not used in all cases
// will be replaced by "Vector3(h_offset, v_offset, 0)" where it was formerly used
@@ -217,9 +217,9 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
forward.normalize();
}
- Vector3 up = c->interpolate_baked_up_vector(offset, true);
+ Vector3 up = c->interpolate_baked_up_vector(progress, true);
- if (o_next < offset) {
+ if (o_next < progress) {
Vector3 up1 = c->interpolate_baked_up_vector(o_next, true);
Vector3 axis = up.cross(up1);
@@ -247,12 +247,12 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
// for a discussion about why not Frenet frame.
t.origin = pos;
- if (p_update_xyz_rot && prev_offset != offset) { // Only update rotation if some parameter has changed - i.e. not on addition to scene tree.
+ if (p_update_xyz_rot && prev_offset != progress) { // Only update rotation if some parameter has changed - i.e. not on addition to scene tree.
real_t sample_distance = bi * 0.01;
Vector3 t_prev_pos_a = c->interpolate_baked(prev_offset - sample_distance, cubic);
Vector3 t_prev_pos_b = c->interpolate_baked(prev_offset + sample_distance, cubic);
- Vector3 t_cur_pos_a = c->interpolate_baked(offset - sample_distance, cubic);
- Vector3 t_cur_pos_b = c->interpolate_baked(offset + sample_distance, cubic);
+ Vector3 t_cur_pos_a = c->interpolate_baked(progress - sample_distance, cubic);
+ Vector3 t_cur_pos_b = c->interpolate_baked(progress + sample_distance, cubic);
Vector3 t_prev = (t_prev_pos_a - t_prev_pos_b).normalized();
Vector3 t_cur = (t_cur_pos_a - t_cur_pos_b).normalized();
@@ -277,7 +277,7 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
}
// do the additional tilting
- real_t tilt_angle = c->interpolate_baked_tilt(offset);
+ real_t tilt_angle = c->interpolate_baked_tilt(progress);
Vector3 tilt_axis = t_cur; // not sure what tilt is supposed to do, is this correct??
if (likely(!Math::is_zero_approx(Math::abs(tilt_angle)))) {
@@ -330,16 +330,15 @@ bool PathFollow3D::get_cubic_interpolation() const {
return cubic;
}
-void PathFollow3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "offset") {
+void PathFollow3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "offset") {
real_t max = 10000;
if (path && path->get_curve().is_valid()) {
max = path->get_curve()->get_baked_length();
}
- property.hint_string = "0," + rtos(max) + ",0.01,or_lesser,or_greater";
+ p_property.hint_string = "0," + rtos(max) + ",0.01,or_lesser,or_greater";
}
- Node3D::_validate_property(property);
}
TypedArray<String> PathFollow3D::get_configuration_warnings() const {
@@ -360,8 +359,8 @@ TypedArray<String> PathFollow3D::get_configuration_warnings() const {
}
void PathFollow3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_offset", "offset"), &PathFollow3D::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"), &PathFollow3D::get_offset);
+ ClassDB::bind_method(D_METHOD("set_progress", "progress"), &PathFollow3D::set_progress);
+ ClassDB::bind_method(D_METHOD("get_progress"), &PathFollow3D::get_progress);
ClassDB::bind_method(D_METHOD("set_h_offset", "h_offset"), &PathFollow3D::set_h_offset);
ClassDB::bind_method(D_METHOD("get_h_offset"), &PathFollow3D::get_h_offset);
@@ -369,8 +368,8 @@ void PathFollow3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_v_offset", "v_offset"), &PathFollow3D::set_v_offset);
ClassDB::bind_method(D_METHOD("get_v_offset"), &PathFollow3D::get_v_offset);
- ClassDB::bind_method(D_METHOD("set_unit_offset", "unit_offset"), &PathFollow3D::set_unit_offset);
- ClassDB::bind_method(D_METHOD("get_unit_offset"), &PathFollow3D::get_unit_offset);
+ ClassDB::bind_method(D_METHOD("set_progress_ratio", "ratio"), &PathFollow3D::set_progress_ratio);
+ ClassDB::bind_method(D_METHOD("get_progress_ratio"), &PathFollow3D::get_progress_ratio);
ClassDB::bind_method(D_METHOD("set_rotation_mode", "rotation_mode"), &PathFollow3D::set_rotation_mode);
ClassDB::bind_method(D_METHOD("get_rotation_mode"), &PathFollow3D::get_rotation_mode);
@@ -381,8 +380,8 @@ void PathFollow3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_loop", "loop"), &PathFollow3D::set_loop);
ClassDB::bind_method(D_METHOD("has_loop"), &PathFollow3D::has_loop);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "offset", PROPERTY_HINT_RANGE, "0,10000,0.01,or_lesser,or_greater,suffix:m"), "set_offset", "get_offset");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "unit_offset", PROPERTY_HINT_RANGE, "0,1,0.0001,or_lesser,or_greater", PROPERTY_USAGE_EDITOR), "set_unit_offset", "get_unit_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "progress", PROPERTY_HINT_RANGE, "0,10000,0.01,or_lesser,or_greater,suffix:m"), "set_progress", "get_progress");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "progress_ratio", PROPERTY_HINT_RANGE, "0,1,0.0001,or_lesser,or_greater", PROPERTY_USAGE_EDITOR), "set_progress_ratio", "get_progress_ratio");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "h_offset", PROPERTY_HINT_NONE, "suffix:m"), "set_h_offset", "get_h_offset");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "v_offset", PROPERTY_HINT_NONE, "suffix:m"), "set_v_offset", "get_v_offset");
ADD_PROPERTY(PropertyInfo(Variant::INT, "rotation_mode", PROPERTY_HINT_ENUM, "None,Y,XY,XYZ,Oriented"), "set_rotation_mode", "get_rotation_mode");
@@ -396,22 +395,22 @@ void PathFollow3D::_bind_methods() {
BIND_ENUM_CONSTANT(ROTATION_ORIENTED);
}
-void PathFollow3D::set_offset(real_t p_offset) {
- ERR_FAIL_COND(!isfinite(p_offset));
- prev_offset = offset;
- offset = p_offset;
+void PathFollow3D::set_progress(real_t p_progress) {
+ ERR_FAIL_COND(!isfinite(p_progress));
+ prev_offset = progress;
+ progress = p_progress;
if (path) {
if (path->get_curve().is_valid()) {
real_t path_length = path->get_curve()->get_baked_length();
if (loop && path_length) {
- offset = Math::fposmod(offset, path_length);
- if (!Math::is_zero_approx(p_offset) && Math::is_zero_approx(offset)) {
- offset = path_length;
+ progress = Math::fposmod(progress, path_length);
+ if (!Math::is_zero_approx(p_progress) && Math::is_zero_approx(progress)) {
+ progress = path_length;
}
} else {
- offset = CLAMP(offset, 0, path_length);
+ progress = CLAMP(progress, 0, path_length);
}
}
@@ -441,19 +440,19 @@ real_t PathFollow3D::get_v_offset() const {
return v_offset;
}
-real_t PathFollow3D::get_offset() const {
- return offset;
+real_t PathFollow3D::get_progress() const {
+ return progress;
}
-void PathFollow3D::set_unit_offset(real_t p_unit_offset) {
+void PathFollow3D::set_progress_ratio(real_t p_ratio) {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) {
- set_offset(p_unit_offset * path->get_curve()->get_baked_length());
+ set_progress(p_ratio * path->get_curve()->get_baked_length());
}
}
-real_t PathFollow3D::get_unit_offset() const {
+real_t PathFollow3D::get_progress_ratio() const {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) {
- return get_offset() / path->get_curve()->get_baked_length();
+ return get_progress() / path->get_curve()->get_baked_length();
} else {
return 0;
}
diff --git a/scene/3d/path_3d.h b/scene/3d/path_3d.h
index b4cc6db7e3..45fa2c8917 100644
--- a/scene/3d/path_3d.h
+++ b/scene/3d/path_3d.h
@@ -75,7 +75,7 @@ public:
private:
Path3D *path = nullptr;
real_t prev_offset = 0.0; // Offset during the last _update_transform.
- real_t offset = 0.0;
+ real_t progress = 0.0;
real_t h_offset = 0.0;
real_t v_offset = 0.0;
bool cubic = true;
@@ -85,14 +85,14 @@ private:
void _update_transform(bool p_update_xyz_rot = true);
protected:
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
static void _bind_methods();
public:
- void set_offset(real_t p_offset);
- real_t get_offset() const;
+ void set_progress(real_t p_progress);
+ real_t get_progress() const;
void set_h_offset(real_t p_h_offset);
real_t get_h_offset() const;
@@ -100,8 +100,8 @@ public:
void set_v_offset(real_t p_v_offset);
real_t get_v_offset() const;
- void set_unit_offset(real_t p_unit_offset);
- real_t get_unit_offset() const;
+ void set_progress_ratio(real_t p_ratio);
+ real_t get_progress_ratio() const;
void set_loop(bool p_loop);
bool has_loop() const;
diff --git a/scene/3d/physics_body_3d.cpp b/scene/3d/physics_body_3d.cpp
index cbdef02826..c690b5d6ff 100644
--- a/scene/3d/physics_body_3d.cpp
+++ b/scene/3d/physics_body_3d.cpp
@@ -525,7 +525,7 @@ void RigidDynamicBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state)
}
_RigidDynamicBodyInOut *toadd = (_RigidDynamicBodyInOut *)alloca(p_state->get_contact_count() * sizeof(_RigidDynamicBodyInOut));
- int toadd_count = 0; //state->get_contact_count();
+ int toadd_count = 0;
RigidDynamicBody3D_RemoveAction *toremove = (RigidDynamicBody3D_RemoveAction *)alloca(rc * sizeof(RigidDynamicBody3D_RemoveAction));
int toremove_count = 0;
@@ -537,8 +537,6 @@ void RigidDynamicBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state)
int local_shape = p_state->get_contact_local_shape(i);
int shape = p_state->get_contact_collider_shape(i);
- //bool found=false;
-
HashMap<ObjectID, BodyState>::Iterator E = contact_monitor->body_map.find(obj);
if (!E) {
toadd[toadd_count].rid = rid;
@@ -865,6 +863,12 @@ int RigidDynamicBody3D::get_max_contacts_reported() const {
return max_contacts_reported;
}
+int RigidDynamicBody3D::get_contact_count() const {
+ PhysicsDirectBodyState3D *bs = PhysicsServer3D::get_singleton()->body_get_direct_state(get_rid());
+ ERR_FAIL_NULL_V(bs, 0);
+ return bs->get_contact_count();
+}
+
void RigidDynamicBody3D::apply_central_impulse(const Vector3 &p_impulse) {
PhysicsServer3D::get_singleton()->body_apply_central_impulse(get_rid(), p_impulse);
}
@@ -960,10 +964,10 @@ bool RigidDynamicBody3D::is_contact_monitor_enabled() const {
return contact_monitor != nullptr;
}
-Array RigidDynamicBody3D::get_colliding_bodies() const {
- ERR_FAIL_COND_V(!contact_monitor, Array());
+TypedArray<Node3D> RigidDynamicBody3D::get_colliding_bodies() const {
+ ERR_FAIL_COND_V(!contact_monitor, TypedArray<Node3D>());
- Array ret;
+ TypedArray<Node3D> ret;
ret.resize(contact_monitor->body_map.size());
int idx = 0;
for (const KeyValue<ObjectID, BodyState> &E : contact_monitor->body_map) {
@@ -1031,6 +1035,7 @@ void RigidDynamicBody3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidDynamicBody3D::set_max_contacts_reported);
ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidDynamicBody3D::get_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("get_contact_count"), &RigidDynamicBody3D::get_contact_count);
ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidDynamicBody3D::set_use_custom_integrator);
ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidDynamicBody3D::is_using_custom_integrator);
@@ -1089,7 +1094,7 @@ void RigidDynamicBody3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "continuous_cd"), "set_use_continuous_collision_detection", "is_using_continuous_collision_detection");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "contacts_reported", PROPERTY_HINT_RANGE, "0,64,1,or_greater"), "set_max_contacts_reported", "get_max_contacts_reported");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_contacts_reported", PROPERTY_HINT_RANGE, "0,64,1,or_greater"), "set_max_contacts_reported", "get_max_contacts_reported");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep");
@@ -1124,13 +1129,12 @@ void RigidDynamicBody3D::_bind_methods() {
BIND_ENUM_CONSTANT(DAMP_MODE_REPLACE);
}
-void RigidDynamicBody3D::_validate_property(PropertyInfo &property) const {
+void RigidDynamicBody3D::_validate_property(PropertyInfo &p_property) const {
if (center_of_mass_mode != CENTER_OF_MASS_MODE_CUSTOM) {
- if (property.name == "center_of_mass") {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "center_of_mass") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- PhysicsBody3D::_validate_property(property);
}
RigidDynamicBody3D::RigidDynamicBody3D() :
@@ -1177,9 +1181,9 @@ bool CharacterBody3D::move_and_slide() {
if ((collision_state.floor || collision_state.wall) && platform_rid.is_valid()) {
bool excluded = false;
if (collision_state.floor) {
- excluded = (moving_platform_floor_layers & platform_layer) == 0;
+ excluded = (platform_floor_layers & platform_layer) == 0;
} else if (collision_state.wall) {
- excluded = (moving_platform_wall_layers & platform_layer) == 0;
+ excluded = (platform_wall_layers & platform_layer) == 0;
}
if (!excluded) {
//this approach makes sure there is less delay between the actual body velocity and the one we saved
@@ -1231,10 +1235,10 @@ bool CharacterBody3D::move_and_slide() {
// Compute real velocity.
real_velocity = get_position_delta() / delta;
- if (moving_platform_apply_velocity_on_leave != PLATFORM_VEL_ON_LEAVE_NEVER) {
+ if (platform_on_leave != PLATFORM_ON_LEAVE_DO_NOTHING) {
// Add last platform velocity when just left a moving platform.
if (!collision_state.floor && !collision_state.wall) {
- if (moving_platform_apply_velocity_on_leave == PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY && current_platform_velocity.dot(up_direction) < 0) {
+ if (platform_on_leave == PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY && current_platform_velocity.dot(up_direction) < 0) {
current_platform_velocity = current_platform_velocity.slide(up_direction);
}
velocity += current_platform_velocity;
@@ -1854,20 +1858,20 @@ void CharacterBody3D::set_slide_on_ceiling_enabled(bool p_enabled) {
slide_on_ceiling = p_enabled;
}
-uint32_t CharacterBody3D::get_moving_platform_floor_layers() const {
- return moving_platform_floor_layers;
+uint32_t CharacterBody3D::get_platform_floor_layers() const {
+ return platform_floor_layers;
}
-void CharacterBody3D::set_moving_platform_floor_layers(uint32_t p_exclude_layers) {
- moving_platform_floor_layers = p_exclude_layers;
+void CharacterBody3D::set_platform_floor_layers(uint32_t p_exclude_layers) {
+ platform_floor_layers = p_exclude_layers;
}
-uint32_t CharacterBody3D::get_moving_platform_wall_layers() const {
- return moving_platform_wall_layers;
+uint32_t CharacterBody3D::get_platform_wall_layers() const {
+ return platform_wall_layers;
}
-void CharacterBody3D::set_moving_platform_wall_layers(uint32_t p_exclude_layers) {
- moving_platform_wall_layers = p_exclude_layers;
+void CharacterBody3D::set_platform_wall_layers(uint32_t p_exclude_layers) {
+ platform_wall_layers = p_exclude_layers;
}
void CharacterBody3D::set_motion_mode(MotionMode p_mode) {
@@ -1878,12 +1882,12 @@ CharacterBody3D::MotionMode CharacterBody3D::get_motion_mode() const {
return motion_mode;
}
-void CharacterBody3D::set_moving_platform_apply_velocity_on_leave(MovingPlatformApplyVelocityOnLeave p_on_leave_apply_velocity) {
- moving_platform_apply_velocity_on_leave = p_on_leave_apply_velocity;
+void CharacterBody3D::set_platform_on_leave(PlatformOnLeave p_on_leave_apply_velocity) {
+ platform_on_leave = p_on_leave_apply_velocity;
}
-CharacterBody3D::MovingPlatformApplyVelocityOnLeave CharacterBody3D::get_moving_platform_apply_velocity_on_leave() const {
- return moving_platform_apply_velocity_on_leave;
+CharacterBody3D::PlatformOnLeave CharacterBody3D::get_platform_on_leave() const {
+ return platform_on_leave;
}
int CharacterBody3D::get_max_slides() const {
@@ -1948,7 +1952,7 @@ void CharacterBody3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &CharacterBody3D::set_velocity);
ClassDB::bind_method(D_METHOD("get_velocity"), &CharacterBody3D::get_velocity);
- ClassDB::bind_method(D_METHOD("set_safe_margin", "pixels"), &CharacterBody3D::set_safe_margin);
+ ClassDB::bind_method(D_METHOD("set_safe_margin", "margin"), &CharacterBody3D::set_safe_margin);
ClassDB::bind_method(D_METHOD("get_safe_margin"), &CharacterBody3D::get_safe_margin);
ClassDB::bind_method(D_METHOD("is_floor_stop_on_slope_enabled"), &CharacterBody3D::is_floor_stop_on_slope_enabled);
ClassDB::bind_method(D_METHOD("set_floor_stop_on_slope_enabled", "enabled"), &CharacterBody3D::set_floor_stop_on_slope_enabled);
@@ -1959,10 +1963,10 @@ void CharacterBody3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_slide_on_ceiling_enabled", "enabled"), &CharacterBody3D::set_slide_on_ceiling_enabled);
ClassDB::bind_method(D_METHOD("is_slide_on_ceiling_enabled"), &CharacterBody3D::is_slide_on_ceiling_enabled);
- ClassDB::bind_method(D_METHOD("set_moving_platform_floor_layers", "exclude_layer"), &CharacterBody3D::set_moving_platform_floor_layers);
- ClassDB::bind_method(D_METHOD("get_moving_platform_floor_layers"), &CharacterBody3D::get_moving_platform_floor_layers);
- ClassDB::bind_method(D_METHOD("set_moving_platform_wall_layers", "exclude_layer"), &CharacterBody3D::set_moving_platform_wall_layers);
- ClassDB::bind_method(D_METHOD("get_moving_platform_wall_layers"), &CharacterBody3D::get_moving_platform_wall_layers);
+ ClassDB::bind_method(D_METHOD("set_platform_floor_layers", "exclude_layer"), &CharacterBody3D::set_platform_floor_layers);
+ ClassDB::bind_method(D_METHOD("get_platform_floor_layers"), &CharacterBody3D::get_platform_floor_layers);
+ ClassDB::bind_method(D_METHOD("set_platform_wall_layers", "exclude_layer"), &CharacterBody3D::set_platform_wall_layers);
+ ClassDB::bind_method(D_METHOD("get_platform_wall_layers"), &CharacterBody3D::get_platform_wall_layers);
ClassDB::bind_method(D_METHOD("get_max_slides"), &CharacterBody3D::get_max_slides);
ClassDB::bind_method(D_METHOD("set_max_slides", "max_slides"), &CharacterBody3D::set_max_slides);
@@ -1976,8 +1980,8 @@ void CharacterBody3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_up_direction", "up_direction"), &CharacterBody3D::set_up_direction);
ClassDB::bind_method(D_METHOD("set_motion_mode", "mode"), &CharacterBody3D::set_motion_mode);
ClassDB::bind_method(D_METHOD("get_motion_mode"), &CharacterBody3D::get_motion_mode);
- ClassDB::bind_method(D_METHOD("set_moving_platform_apply_velocity_on_leave", "on_leave_apply_velocity"), &CharacterBody3D::set_moving_platform_apply_velocity_on_leave);
- ClassDB::bind_method(D_METHOD("get_moving_platform_apply_velocity_on_leave"), &CharacterBody3D::get_moving_platform_apply_velocity_on_leave);
+ ClassDB::bind_method(D_METHOD("set_platform_on_leave", "on_leave_apply_velocity"), &CharacterBody3D::set_platform_on_leave);
+ ClassDB::bind_method(D_METHOD("get_platform_on_leave"), &CharacterBody3D::get_platform_on_leave);
ClassDB::bind_method(D_METHOD("is_on_floor"), &CharacterBody3D::is_on_floor);
ClassDB::bind_method(D_METHOD("is_on_floor_only"), &CharacterBody3D::is_on_floor_only);
@@ -2002,33 +2006,36 @@ void CharacterBody3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "velocity", PROPERTY_HINT_NONE, "suffix:m/s", PROPERTY_USAGE_NO_EDITOR), "set_velocity", "get_velocity");
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_slides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_max_slides", "get_max_slides");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wall_min_slide_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians", PROPERTY_USAGE_DEFAULT), "set_wall_min_slide_angle", "get_wall_min_slide_angle");
+
ADD_GROUP("Floor", "floor_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_stop_on_slope"), "set_floor_stop_on_slope_enabled", "is_floor_stop_on_slope_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_constant_speed"), "set_floor_constant_speed_enabled", "is_floor_constant_speed_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_block_on_wall"), "set_floor_block_on_wall_enabled", "is_floor_block_on_wall_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_max_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians"), "set_floor_max_angle", "get_floor_max_angle");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_snap_length", PROPERTY_HINT_RANGE, "0,1,0.01,or_greater,suffix:m"), "set_floor_snap_length", "get_floor_snap_length");
- ADD_GROUP("Moving Platform", "moving_platform");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_apply_velocity_on_leave", PROPERTY_HINT_ENUM, "Always,Upward Only,Never", PROPERTY_USAGE_DEFAULT), "set_moving_platform_apply_velocity_on_leave", "get_moving_platform_apply_velocity_on_leave");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_floor_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_moving_platform_floor_layers", "get_moving_platform_floor_layers");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_wall_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_moving_platform_wall_layers", "get_moving_platform_wall_layers");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision/safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001,suffix:m"), "set_safe_margin", "get_safe_margin");
+
+ ADD_GROUP("Moving Platform", "platform_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_on_leave", PROPERTY_HINT_ENUM, "Add Velocity,Add Upward Velocity,Do Nothing", PROPERTY_USAGE_DEFAULT), "set_platform_on_leave", "get_platform_on_leave");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_floor_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_platform_floor_layers", "get_platform_floor_layers");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_wall_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_platform_wall_layers", "get_platform_wall_layers");
+
+ ADD_GROUP("Collision", "");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001,suffix:m"), "set_safe_margin", "get_safe_margin");
BIND_ENUM_CONSTANT(MOTION_MODE_GROUNDED);
BIND_ENUM_CONSTANT(MOTION_MODE_FLOATING);
- BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_ALWAYS);
- BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY);
- BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_NEVER);
+ BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_VELOCITY);
+ BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY);
+ BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_DO_NOTHING);
}
-void CharacterBody3D::_validate_property(PropertyInfo &property) const {
+void CharacterBody3D::_validate_property(PropertyInfo &p_property) const {
if (motion_mode == MOTION_MODE_FLOATING) {
- if (property.name.begins_with("floor_") || property.name == "up_direction" || property.name == "slide_on_ceiling") {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name.begins_with("floor_") || p_property.name == "up_direction" || p_property.name == "slide_on_ceiling") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- PhysicsBody3D::_validate_property(property);
}
CharacterBody3D::CharacterBody3D() :
@@ -3417,6 +3424,7 @@ void PhysicalBone3D::_start_physics_simulation() {
set_body_mode(PhysicsServer3D::BODY_MODE_DYNAMIC);
PhysicsServer3D::get_singleton()->body_set_collision_layer(get_rid(), get_collision_layer());
PhysicsServer3D::get_singleton()->body_set_collision_mask(get_rid(), get_collision_mask());
+ PhysicsServer3D::get_singleton()->body_set_collision_priority(get_rid(), get_collision_priority());
PhysicsServer3D::get_singleton()->body_set_state_sync_callback(get_rid(), this, _body_state_changed_callback);
set_as_top_level(true);
_internal_simulate_physics = true;
@@ -3430,10 +3438,12 @@ void PhysicalBone3D::_stop_physics_simulation() {
set_body_mode(PhysicsServer3D::BODY_MODE_KINEMATIC);
PhysicsServer3D::get_singleton()->body_set_collision_layer(get_rid(), get_collision_layer());
PhysicsServer3D::get_singleton()->body_set_collision_mask(get_rid(), get_collision_mask());
+ PhysicsServer3D::get_singleton()->body_set_collision_priority(get_rid(), get_collision_priority());
} else {
set_body_mode(PhysicsServer3D::BODY_MODE_STATIC);
PhysicsServer3D::get_singleton()->body_set_collision_layer(get_rid(), 0);
PhysicsServer3D::get_singleton()->body_set_collision_mask(get_rid(), 0);
+ PhysicsServer3D::get_singleton()->body_set_collision_priority(get_rid(), 1.0);
}
if (_internal_simulate_physics) {
PhysicsServer3D::get_singleton()->body_set_state_sync_callback(get_rid(), nullptr, nullptr);
diff --git a/scene/3d/physics_body_3d.h b/scene/3d/physics_body_3d.h
index b9baba4d96..14a1cf7228 100644
--- a/scene/3d/physics_body_3d.h
+++ b/scene/3d/physics_body_3d.h
@@ -226,7 +226,7 @@ protected:
void _notification(int p_what);
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
GDVIRTUAL1(_integrate_forces, PhysicsDirectBodyState3D *)
@@ -300,11 +300,12 @@ public:
void set_max_contacts_reported(int p_amount);
int get_max_contacts_reported() const;
+ int get_contact_count() const;
void set_use_continuous_collision_detection(bool p_enable);
bool is_using_continuous_collision_detection() const;
- Array get_colliding_bodies() const;
+ TypedArray<Node3D> get_colliding_bodies() const;
void apply_central_impulse(const Vector3 &p_impulse);
void apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position = Vector3());
@@ -347,10 +348,10 @@ public:
MOTION_MODE_GROUNDED,
MOTION_MODE_FLOATING,
};
- enum MovingPlatformApplyVelocityOnLeave {
- PLATFORM_VEL_ON_LEAVE_ALWAYS,
- PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY,
- PLATFORM_VEL_ON_LEAVE_NEVER,
+ enum PlatformOnLeave {
+ PLATFORM_ON_LEAVE_ADD_VELOCITY,
+ PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY,
+ PLATFORM_ON_LEAVE_DO_NOTHING,
};
bool move_and_slide();
@@ -382,7 +383,7 @@ public:
private:
real_t margin = 0.001;
MotionMode motion_mode = MOTION_MODE_GROUNDED;
- MovingPlatformApplyVelocityOnLeave moving_platform_apply_velocity_on_leave = PLATFORM_VEL_ON_LEAVE_ALWAYS;
+ PlatformOnLeave platform_on_leave = PLATFORM_ON_LEAVE_ADD_VELOCITY;
union CollisionState {
uint32_t state = 0;
struct {
@@ -410,8 +411,8 @@ private:
int platform_layer = 0;
RID platform_rid;
ObjectID platform_object_id;
- uint32_t moving_platform_floor_layers = UINT32_MAX;
- uint32_t moving_platform_wall_layers = 0;
+ uint32_t platform_floor_layers = UINT32_MAX;
+ uint32_t platform_wall_layers = 0;
real_t floor_snap_length = 0.1;
real_t floor_max_angle = Math::deg2rad((real_t)45.0);
real_t wall_min_slide_angle = Math::deg2rad((real_t)15.0);
@@ -456,17 +457,17 @@ private:
real_t get_wall_min_slide_angle() const;
void set_wall_min_slide_angle(real_t p_radians);
- uint32_t get_moving_platform_floor_layers() const;
- void set_moving_platform_floor_layers(const uint32_t p_exclude_layer);
+ uint32_t get_platform_floor_layers() const;
+ void set_platform_floor_layers(const uint32_t p_exclude_layer);
- uint32_t get_moving_platform_wall_layers() const;
- void set_moving_platform_wall_layers(const uint32_t p_exclude_layer);
+ uint32_t get_platform_wall_layers() const;
+ void set_platform_wall_layers(const uint32_t p_exclude_layer);
void set_motion_mode(MotionMode p_mode);
MotionMode get_motion_mode() const;
- void set_moving_platform_apply_velocity_on_leave(MovingPlatformApplyVelocityOnLeave p_on_leave_velocity);
- MovingPlatformApplyVelocityOnLeave get_moving_platform_apply_velocity_on_leave() const;
+ void set_platform_on_leave(PlatformOnLeave p_on_leave_velocity);
+ PlatformOnLeave get_platform_on_leave() const;
void _move_and_slide_floating(double p_delta);
void _move_and_slide_grounded(double p_delta, bool p_was_on_floor);
@@ -483,11 +484,11 @@ private:
protected:
void _notification(int p_what);
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
};
VARIANT_ENUM_CAST(CharacterBody3D::MotionMode);
-VARIANT_ENUM_CAST(CharacterBody3D::MovingPlatformApplyVelocityOnLeave);
+VARIANT_ENUM_CAST(CharacterBody3D::PlatformOnLeave);
class KinematicCollision3D : public RefCounted {
GDCLASS(KinematicCollision3D, RefCounted);
diff --git a/scene/3d/ray_cast_3d.cpp b/scene/3d/ray_cast_3d.cpp
index 2db5ab2d4e..a45ef52452 100644
--- a/scene/3d/ray_cast_3d.cpp
+++ b/scene/3d/ray_cast_3d.cpp
@@ -88,6 +88,10 @@ Object *RayCast3D::get_collider() const {
return ObjectDB::get_instance(against);
}
+RID RayCast3D::get_collider_rid() const {
+ return against_rid;
+}
+
int RayCast3D::get_collider_shape() const {
return against_shape;
}
@@ -224,12 +228,14 @@ void RayCast3D::_update_raycast_state() {
if (dss->intersect_ray(ray_params, rr)) {
collided = true;
against = rr.collider_id;
+ against_rid = rr.rid;
collision_point = rr.position;
collision_normal = rr.normal;
against_shape = rr.shape;
} else {
collided = false;
against = ObjectID();
+ against_rid = RID();
against_shape = 0;
}
}
@@ -302,6 +308,7 @@ void RayCast3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("force_raycast_update"), &RayCast3D::force_raycast_update);
ClassDB::bind_method(D_METHOD("get_collider"), &RayCast3D::get_collider);
+ ClassDB::bind_method(D_METHOD("get_collider_rid"), &RayCast3D::get_collider_rid);
ClassDB::bind_method(D_METHOD("get_collider_shape"), &RayCast3D::get_collider_shape);
ClassDB::bind_method(D_METHOD("get_collision_point"), &RayCast3D::get_collision_point);
ClassDB::bind_method(D_METHOD("get_collision_normal"), &RayCast3D::get_collision_normal);
diff --git a/scene/3d/ray_cast_3d.h b/scene/3d/ray_cast_3d.h
index aa62f6927e..eb5c3ee90a 100644
--- a/scene/3d/ray_cast_3d.h
+++ b/scene/3d/ray_cast_3d.h
@@ -41,6 +41,7 @@ class RayCast3D : public Node3D {
bool enabled = true;
bool collided = false;
ObjectID against;
+ RID against_rid;
int against_shape = 0;
Vector3 collision_point;
Vector3 collision_normal;
@@ -113,6 +114,7 @@ public:
void force_raycast_update();
bool is_colliding() const;
Object *get_collider() const;
+ RID get_collider_rid() const;
int get_collider_shape() const;
Vector3 get_collision_point() const;
Vector3 get_collision_normal() const;
diff --git a/scene/3d/reflection_probe.cpp b/scene/3d/reflection_probe.cpp
index 0a9d6cbbeb..bc3cc31963 100644
--- a/scene/3d/reflection_probe.cpp
+++ b/scene/3d/reflection_probe.cpp
@@ -178,13 +178,12 @@ AABB ReflectionProbe::get_aabb() const {
return aabb;
}
-void ReflectionProbe::_validate_property(PropertyInfo &property) const {
- if (property.name == "interior/ambient_color" || property.name == "interior/ambient_color_energy") {
+void ReflectionProbe::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "ambient_color" || p_property.name == "ambient_color_energy") {
if (ambient_mode != AMBIENT_COLOR) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- VisualInstance3D::_validate_property(property);
}
void ReflectionProbe::_bind_methods() {
diff --git a/scene/3d/reflection_probe.h b/scene/3d/reflection_probe.h
index a161717ece..5a5a3fe0bb 100644
--- a/scene/3d/reflection_probe.h
+++ b/scene/3d/reflection_probe.h
@@ -67,7 +67,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_intensity(float p_intensity);
diff --git a/scene/3d/skeleton_3d.cpp b/scene/3d/skeleton_3d.cpp
index 4c38fccc8b..1bc138704e 100644
--- a/scene/3d/skeleton_3d.cpp
+++ b/scene/3d/skeleton_3d.cpp
@@ -176,39 +176,37 @@ void Skeleton3D::_get_property_list(List<PropertyInfo> *p_list) const {
}
}
-void Skeleton3D::_validate_property(PropertyInfo &property) const {
- PackedStringArray split = property.name.split("/");
+void Skeleton3D::_validate_property(PropertyInfo &p_property) const {
+ PackedStringArray split = p_property.name.split("/");
if (split.size() == 3 && split[0] == "bones") {
if (split[2] == "rest") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
if (is_show_rest_only()) {
if (split[2] == "enabled") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
if (split[2] == "position") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
if (split[2] == "rotation") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
if (split[2] == "scale") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
} else if (!is_bone_enabled(split[1].to_int())) {
if (split[2] == "position") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
if (split[2] == "rotation") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
if (split[2] == "scale") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
}
}
-
- Node3D::_validate_property(property);
}
void Skeleton3D::_update_process_order() {
@@ -615,42 +613,6 @@ Vector<int> Skeleton3D::get_bone_children(int p_bone) {
return bones[p_bone].child_bones;
}
-void Skeleton3D::set_bone_children(int p_bone, Vector<int> p_children) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX(p_bone, bone_size);
- bones.write[p_bone].child_bones = p_children;
-
- process_order_dirty = true;
- rest_dirty = true;
- _make_dirty();
-}
-
-void Skeleton3D::add_bone_child(int p_bone, int p_child) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX(p_bone, bone_size);
- bones.write[p_bone].child_bones.push_back(p_child);
-
- process_order_dirty = true;
- rest_dirty = true;
- _make_dirty();
-}
-
-void Skeleton3D::remove_bone_child(int p_bone, int p_child) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX(p_bone, bone_size);
-
- int child_idx = bones[p_bone].child_bones.find(p_child);
- if (child_idx >= 0) {
- bones.write[p_bone].child_bones.remove_at(child_idx);
- } else {
- WARN_PRINT("Cannot remove child bone: Child bone not found.");
- }
-
- process_order_dirty = true;
- rest_dirty = true;
- _make_dirty();
-}
-
Vector<int> Skeleton3D::get_parentless_bones() {
_update_process_order();
return parentless_bones;
@@ -762,6 +724,20 @@ Vector3 Skeleton3D::get_bone_pose_scale(int p_bone) const {
return bones[p_bone].pose_scale;
}
+void Skeleton3D::reset_bone_pose(int p_bone) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
+ set_bone_pose_position(p_bone, bones[p_bone].rest.origin);
+ set_bone_pose_rotation(p_bone, bones[p_bone].rest.basis.get_rotation_quaternion());
+ set_bone_pose_scale(p_bone, bones[p_bone].rest.basis.get_scale());
+}
+
+void Skeleton3D::reset_bone_poses() {
+ for (int i = 0; i < bones.size(); i++) {
+ reset_bone_pose(i);
+ }
+}
+
Transform3D Skeleton3D::get_bone_pose(int p_bone) const {
const int bone_size = bones.size();
ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
@@ -1226,9 +1202,6 @@ void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("unparent_bone_and_rest", "bone_idx"), &Skeleton3D::unparent_bone_and_rest);
ClassDB::bind_method(D_METHOD("get_bone_children", "bone_idx"), &Skeleton3D::get_bone_children);
- ClassDB::bind_method(D_METHOD("set_bone_children", "bone_idx", "bone_children"), &Skeleton3D::set_bone_children);
- ClassDB::bind_method(D_METHOD("add_bone_child", "bone_idx", "child_bone_idx"), &Skeleton3D::add_bone_child);
- ClassDB::bind_method(D_METHOD("remove_bone_child", "bone_idx", "child_bone_idx"), &Skeleton3D::remove_bone_child);
ClassDB::bind_method(D_METHOD("get_parentless_bones"), &Skeleton3D::get_parentless_bones);
@@ -1252,6 +1225,9 @@ void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_bone_pose_rotation", "bone_idx"), &Skeleton3D::get_bone_pose_rotation);
ClassDB::bind_method(D_METHOD("get_bone_pose_scale", "bone_idx"), &Skeleton3D::get_bone_pose_scale);
+ ClassDB::bind_method(D_METHOD("reset_bone_pose", "bone_idx"), &Skeleton3D::reset_bone_pose);
+ ClassDB::bind_method(D_METHOD("reset_bone_poses"), &Skeleton3D::reset_bone_poses);
+
ClassDB::bind_method(D_METHOD("is_bone_enabled", "bone_idx"), &Skeleton3D::is_bone_enabled);
ClassDB::bind_method(D_METHOD("set_bone_enabled", "bone_idx", "enabled"), &Skeleton3D::set_bone_enabled, DEFVAL(true));
diff --git a/scene/3d/skeleton_3d.h b/scene/3d/skeleton_3d.h
index 8b69410a39..79feadf44f 100644
--- a/scene/3d/skeleton_3d.h
+++ b/scene/3d/skeleton_3d.h
@@ -156,7 +156,7 @@ protected:
bool _get(const StringName &p_path, Variant &r_ret) const;
bool _set(const StringName &p_path, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_list) const;
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
static void _bind_methods();
@@ -227,6 +227,9 @@ public:
Quaternion get_bone_pose_rotation(int p_bone) const;
Vector3 get_bone_pose_scale(int p_bone) const;
+ void reset_bone_pose(int p_bone);
+ void reset_bone_poses();
+
void clear_bones_global_pose_override();
Transform3D get_bone_global_pose_override(int p_bone) const;
void set_bone_global_pose_override(int p_bone, const Transform3D &p_pose, real_t p_amount, bool p_persistent = false);
diff --git a/scene/3d/skeleton_ik_3d.cpp b/scene/3d/skeleton_ik_3d.cpp
index 2182c5ba11..f0534c8099 100644
--- a/scene/3d/skeleton_ik_3d.cpp
+++ b/scene/3d/skeleton_ik_3d.cpp
@@ -329,8 +329,8 @@ void FabrikInverseKinematic::_update_chain(const Skeleton3D *p_sk, ChainItem *p_
}
}
-void SkeletonIK3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "root_bone" || property.name == "tip_bone") {
+void SkeletonIK3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "root_bone" || p_property.name == "tip_bone") {
if (skeleton) {
String names("--,");
for (int i = 0; i < skeleton->get_bone_count(); i++) {
@@ -340,15 +340,13 @@ void SkeletonIK3D::_validate_property(PropertyInfo &property) const {
names += skeleton->get_bone_name(i);
}
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = names;
+ p_property.hint = PROPERTY_HINT_ENUM;
+ p_property.hint_string = names;
} else {
- property.hint = PROPERTY_HINT_NONE;
- property.hint_string = "";
+ p_property.hint = PROPERTY_HINT_NONE;
+ p_property.hint_string = "";
}
}
-
- Node::_validate_property(property);
}
void SkeletonIK3D::_bind_methods() {
diff --git a/scene/3d/skeleton_ik_3d.h b/scene/3d/skeleton_ik_3d.h
index 6ae86a2bf6..097df2c400 100644
--- a/scene/3d/skeleton_ik_3d.h
+++ b/scene/3d/skeleton_ik_3d.h
@@ -137,7 +137,7 @@ class SkeletonIK3D : public Node {
FabrikInverseKinematic::Task *task = nullptr;
protected:
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
virtual void _notification(int p_what);
diff --git a/scene/3d/soft_dynamic_body_3d.cpp b/scene/3d/soft_dynamic_body_3d.cpp
index 15f050defb..2650d62fa4 100644
--- a/scene/3d/soft_dynamic_body_3d.cpp
+++ b/scene/3d/soft_dynamic_body_3d.cpp
@@ -88,10 +88,10 @@ void SoftDynamicBodyRenderingServerHandler::set_normal(int p_vertex_id, const vo
memcpy(&n, p_vector3, sizeof(Vector3));
n *= Vector3(0.5, 0.5, 0.5);
n += Vector3(0.5, 0.5, 0.5);
+ Vector2 res = n.octahedron_encode();
uint32_t value = 0;
- value |= CLAMP(int(n.x * 1023.0), 0, 1023);
- value |= CLAMP(int(n.y * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int(n.z * 1023.0), 0, 1023) << 20;
+ value |= (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ value |= (uint16_t)CLAMP(res.y * 65535, 0, 65535) << 16;
memcpy(&write_buffer[p_vertex_id * stride + offset_normal], &value, sizeof(uint32_t));
}
@@ -591,10 +591,10 @@ Vector<SoftDynamicBody3D::PinnedPoint> SoftDynamicBody3D::get_pinned_points_indi
return pinned_points;
}
-Array SoftDynamicBody3D::get_collision_exceptions() {
+TypedArray<PhysicsBody3D> SoftDynamicBody3D::get_collision_exceptions() {
List<RID> exceptions;
PhysicsServer3D::get_singleton()->soft_body_get_collision_exceptions(physics_rid, &exceptions);
- Array ret;
+ TypedArray<PhysicsBody3D> ret;
for (const RID &body : exceptions) {
ObjectID instance_id = PhysicsServer3D::get_singleton()->body_get_object_instance_id(body);
Object *obj = ObjectDB::get_instance(instance_id);
diff --git a/scene/3d/soft_dynamic_body_3d.h b/scene/3d/soft_dynamic_body_3d.h
index 04f3365f72..2b86fe2cae 100644
--- a/scene/3d/soft_dynamic_body_3d.h
+++ b/scene/3d/soft_dynamic_body_3d.h
@@ -34,6 +34,7 @@
#include "scene/3d/mesh_instance_3d.h"
#include "servers/physics_server_3d.h"
+class PhysicsBody3D;
class SoftDynamicBody3D;
class SoftDynamicBodyRenderingServerHandler : public PhysicsServer3DRenderingServerHandler {
@@ -168,7 +169,7 @@ public:
void set_drag_coefficient(real_t p_drag_coefficient);
real_t get_drag_coefficient();
- Array get_collision_exceptions();
+ TypedArray<PhysicsBody3D> get_collision_exceptions();
void add_collision_exception_with(Node *p_node);
void remove_collision_exception_with(Node *p_node);
diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp
index ef2b9e1ce5..212d220ace 100644
--- a/scene/3d/sprite_3d.cpp
+++ b/scene/3d/sprite_3d.cpp
@@ -562,23 +562,21 @@ void Sprite3D::_draw() {
{
Vector3 n = normal * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
+ Vector2 res = n.octahedron_encode();
uint32_t value = 0;
- value |= CLAMP(int(n.x * 1023.0), 0, 1023);
- value |= CLAMP(int(n.y * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int(n.z * 1023.0), 0, 1023) << 20;
+ value |= (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ value |= (uint16_t)CLAMP(res.y * 65535, 0, 65535) << 16;
v_normal = value;
}
uint32_t v_tangent;
{
Plane t = tangent;
+ Vector2 res = t.normal.octahedron_tangent_encode(t.d);
uint32_t value = 0;
- value |= CLAMP(int((t.normal.x * 0.5 + 0.5) * 1023.0), 0, 1023);
- value |= CLAMP(int((t.normal.y * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int((t.normal.z * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
- if (t.d > 0) {
- value |= 3UL << 30;
- }
+ value |= (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ value |= (uint16_t)CLAMP(res.y * 65535, 0, 65535) << 16;
+
v_tangent = value;
}
@@ -751,18 +749,16 @@ Rect2 Sprite3D::get_item_rect() const {
return Rect2(ofs, s);
}
-void Sprite3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "frame") {
- property.hint = PROPERTY_HINT_RANGE;
- property.hint_string = "0," + itos(vframes * hframes - 1) + ",1";
- property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
+void Sprite3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "frame") {
+ p_property.hint = PROPERTY_HINT_RANGE;
+ p_property.hint_string = "0," + itos(vframes * hframes - 1) + ",1";
+ p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
- if (property.name == "frame_coords") {
- property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
+ if (p_property.name == "frame_coords") {
+ p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
-
- SpriteBase3D::_validate_property(property);
}
void Sprite3D::_bind_methods() {
@@ -929,23 +925,20 @@ void AnimatedSprite3D::_draw() {
{
Vector3 n = normal * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
+ Vector2 res = n.octahedron_encode();
uint32_t value = 0;
- value |= CLAMP(int(n.x * 1023.0), 0, 1023);
- value |= CLAMP(int(n.y * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int(n.z * 1023.0), 0, 1023) << 20;
+ value |= (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ value |= (uint16_t)CLAMP(res.y * 65535, 0, 65535) << 16;
v_normal = value;
}
uint32_t v_tangent;
{
Plane t = tangent;
+ Vector2 res = t.normal.octahedron_tangent_encode(t.d);
uint32_t value = 0;
- value |= CLAMP(int((t.normal.x * 0.5 + 0.5) * 1023.0), 0, 1023);
- value |= CLAMP(int((t.normal.y * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int((t.normal.z * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
- if (t.d > 0) {
- value |= 3UL << 30;
- }
+ value |= (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ value |= (uint16_t)CLAMP(res.y * 65535, 0, 65535) << 16;
v_tangent = value;
}
@@ -1000,12 +993,12 @@ void AnimatedSprite3D::_draw() {
}
}
-void AnimatedSprite3D::_validate_property(PropertyInfo &property) const {
+void AnimatedSprite3D::_validate_property(PropertyInfo &p_property) const {
if (!frames.is_valid()) {
return;
}
- if (property.name == "animation") {
- property.hint = PROPERTY_HINT_ENUM;
+ if (p_property.name == "animation") {
+ p_property.hint = PROPERTY_HINT_ENUM;
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
@@ -1014,36 +1007,34 @@ void AnimatedSprite3D::_validate_property(PropertyInfo &property) const {
for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
if (E->prev()) {
- property.hint_string += ",";
+ p_property.hint_string += ",";
}
- property.hint_string += String(E->get());
+ p_property.hint_string += String(E->get());
if (animation == E->get()) {
current_found = true;
}
}
if (!current_found) {
- if (property.hint_string.is_empty()) {
- property.hint_string = String(animation);
+ if (p_property.hint_string.is_empty()) {
+ p_property.hint_string = String(animation);
} else {
- property.hint_string = String(animation) + "," + property.hint_string;
+ p_property.hint_string = String(animation) + "," + p_property.hint_string;
}
}
}
- if (property.name == "frame") {
- property.hint = PROPERTY_HINT_RANGE;
+ if (p_property.name == "frame") {
+ p_property.hint = PROPERTY_HINT_RANGE;
if (frames->has_animation(animation) && frames->get_frame_count(animation) > 0) {
- property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
+ p_property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
- property.hint_string = "0,0,1";
+ p_property.hint_string = "0,0,1";
}
- property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
+ p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
-
- SpriteBase3D::_validate_property(property);
}
void AnimatedSprite3D::_notification(int p_what) {
diff --git a/scene/3d/sprite_3d.h b/scene/3d/sprite_3d.h
index 6ac85a7bbc..03688cf787 100644
--- a/scene/3d/sprite_3d.h
+++ b/scene/3d/sprite_3d.h
@@ -174,7 +174,7 @@ protected:
virtual void _draw() override;
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_texture(const Ref<Texture2D> &p_texture);
@@ -229,7 +229,7 @@ protected:
virtual void _draw() override;
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_sprite_frames(const Ref<SpriteFrames> &p_frames);
diff --git a/scene/3d/velocity_tracker_3d.h b/scene/3d/velocity_tracker_3d.h
index 6b27cdffc2..d3b92ab766 100644
--- a/scene/3d/velocity_tracker_3d.h
+++ b/scene/3d/velocity_tracker_3d.h
@@ -34,8 +34,6 @@
#include "scene/3d/node_3d.h"
class VelocityTracker3D : public RefCounted {
- GDCLASS(VelocityTracker3D, RefCounted);
-
struct PositionHistory {
uint64_t frame = 0;
Vector3 position;
diff --git a/scene/3d/xr_nodes.cpp b/scene/3d/xr_nodes.cpp
index 40a43043c6..de765d7ccb 100644
--- a/scene/3d/xr_nodes.cpp
+++ b/scene/3d/xr_nodes.cpp
@@ -244,27 +244,25 @@ void XRNode3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("trigger_haptic_pulse", "action_name", "frequency", "amplitude", "duration_sec", "delay_sec"), &XRNode3D::trigger_haptic_pulse);
};
-void XRNode3D::_validate_property(PropertyInfo &property) const {
+void XRNode3D::_validate_property(PropertyInfo &p_property) const {
XRServer *xr_server = XRServer::get_singleton();
ERR_FAIL_NULL(xr_server);
- if (property.name == "tracker") {
+ if (p_property.name == "tracker") {
PackedStringArray names = xr_server->get_suggested_tracker_names();
String hint_string;
for (const String &name : names) {
hint_string += name + ",";
}
- property.hint_string = hint_string;
- } else if (property.name == "pose") {
+ p_property.hint_string = hint_string;
+ } else if (p_property.name == "pose") {
PackedStringArray names = xr_server->get_suggested_pose_names(tracker_name);
String hint_string;
for (const String &name : names) {
hint_string += name + ",";
}
- property.hint_string = hint_string;
+ p_property.hint_string = hint_string;
}
-
- Node3D::_validate_property(property);
}
void XRNode3D::set_tracker(const StringName p_tracker_name) {
diff --git a/scene/3d/xr_nodes.h b/scene/3d/xr_nodes.h
index 3079e20dc7..312bef7856 100644
--- a/scene/3d/xr_nodes.h
+++ b/scene/3d/xr_nodes.h
@@ -93,7 +93,7 @@ protected:
void _pose_changed(const Ref<XRPose> &p_pose);
public:
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void set_tracker(const StringName p_tracker_name);
StringName get_tracker() const;
diff --git a/scene/animation/animation_blend_space_1d.cpp b/scene/animation/animation_blend_space_1d.cpp
index b42e426f51..f30aea3bdd 100644
--- a/scene/animation/animation_blend_space_1d.cpp
+++ b/scene/animation/animation_blend_space_1d.cpp
@@ -42,15 +42,14 @@ Ref<AnimationNode> AnimationNodeBlendSpace1D::get_child_by_name(const StringName
return get_blend_point_node(p_name.operator String().to_int());
}
-void AnimationNodeBlendSpace1D::_validate_property(PropertyInfo &property) const {
- if (property.name.begins_with("blend_point_")) {
- String left = property.name.get_slicec('/', 0);
+void AnimationNodeBlendSpace1D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name.begins_with("blend_point_")) {
+ String left = p_property.name.get_slicec('/', 0);
int idx = left.get_slicec('_', 2).to_int();
if (idx >= blend_points_used) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
- AnimationRootNode::_validate_property(property);
}
void AnimationNodeBlendSpace1D::_tree_changed() {
diff --git a/scene/animation/animation_blend_space_1d.h b/scene/animation/animation_blend_space_1d.h
index 346e8a3a2f..1876ccebc7 100644
--- a/scene/animation/animation_blend_space_1d.h
+++ b/scene/animation/animation_blend_space_1d.h
@@ -65,7 +65,7 @@ class AnimationNodeBlendSpace1D : public AnimationRootNode {
protected:
bool sync = false;
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
public:
diff --git a/scene/animation/animation_blend_space_2d.cpp b/scene/animation/animation_blend_space_2d.cpp
index 6b5851a977..2dc61efb94 100644
--- a/scene/animation/animation_blend_space_2d.cpp
+++ b/scene/animation/animation_blend_space_2d.cpp
@@ -566,18 +566,17 @@ String AnimationNodeBlendSpace2D::get_caption() const {
return "BlendSpace2D";
}
-void AnimationNodeBlendSpace2D::_validate_property(PropertyInfo &property) const {
- if (auto_triangles && property.name == "triangles") {
- property.usage = PROPERTY_USAGE_NONE;
+void AnimationNodeBlendSpace2D::_validate_property(PropertyInfo &p_property) const {
+ if (auto_triangles && p_property.name == "triangles") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("blend_point_")) {
- String left = property.name.get_slicec('/', 0);
+ if (p_property.name.begins_with("blend_point_")) {
+ String left = p_property.name.get_slicec('/', 0);
int idx = left.get_slicec('_', 2).to_int();
if (idx >= blend_points_used) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
- AnimationRootNode::_validate_property(property);
}
void AnimationNodeBlendSpace2D::set_auto_triangles(bool p_enable) {
diff --git a/scene/animation/animation_blend_space_2d.h b/scene/animation/animation_blend_space_2d.h
index 689b96e356..250189f202 100644
--- a/scene/animation/animation_blend_space_2d.h
+++ b/scene/animation/animation_blend_space_2d.h
@@ -90,7 +90,7 @@ protected:
protected:
bool sync = false;
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
public:
diff --git a/scene/animation/animation_blend_tree.cpp b/scene/animation/animation_blend_tree.cpp
index fe2fb1b7a1..61f068408c 100644
--- a/scene/animation/animation_blend_tree.cpp
+++ b/scene/animation/animation_blend_tree.cpp
@@ -47,8 +47,8 @@ void AnimationNodeAnimation::get_parameter_list(List<PropertyInfo> *r_list) cons
r_list->push_back(PropertyInfo(Variant::FLOAT, time, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
}
-void AnimationNodeAnimation::_validate_property(PropertyInfo &property) const {
- if (property.name == "animation" && get_editable_animation_list) {
+void AnimationNodeAnimation::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "animation" && get_editable_animation_list) {
Vector<String> names = get_editable_animation_list();
String anims;
for (int i = 0; i < names.size(); i++) {
@@ -58,8 +58,8 @@ void AnimationNodeAnimation::_validate_property(PropertyInfo &property) const {
anims += String(names[i]);
}
if (!anims.is_empty()) {
- property.hint = PROPERTY_HINT_ENUM;
- property.hint_string = anims;
+ p_property.hint = PROPERTY_HINT_ENUM;
+ p_property.hint_string = anims;
}
}
}
@@ -676,12 +676,20 @@ String AnimationNodeTransition::get_input_caption(int p_input) const {
return inputs[p_input].name;
}
-void AnimationNodeTransition::set_cross_fade_time(float p_fade) {
- xfade = p_fade;
+void AnimationNodeTransition::set_xfade_time(float p_fade) {
+ xfade_time = p_fade;
}
-float AnimationNodeTransition::get_cross_fade_time() const {
- return xfade;
+float AnimationNodeTransition::get_xfade_time() const {
+ return xfade_time;
+}
+
+void AnimationNodeTransition::set_xfade_curve(const Ref<Curve> &p_curve) {
+ xfade_curve = p_curve;
+}
+
+Ref<Curve> AnimationNodeTransition::get_xfade_curve() const {
+ return xfade_curve;
}
void AnimationNodeTransition::set_from_start(bool p_from_start) {
@@ -707,7 +715,7 @@ double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_seek_
set_parameter(this->prev, prev_current);
prev = prev_current;
- prev_xfading = xfade;
+ prev_xfading = xfade_time;
time = 0;
switched = true;
}
@@ -734,13 +742,16 @@ double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_seek_
time += p_time;
}
- if (inputs[current].auto_advance && rem <= xfade) {
+ if (inputs[current].auto_advance && rem <= xfade_time) {
set_parameter(this->current, (current + 1) % enabled_inputs);
}
} else { // cross-fading from prev to current
- float blend = xfade == 0 ? 0 : (prev_xfading / xfade);
+ float blend = xfade_time == 0 ? 0 : (prev_xfading / xfade_time);
+ if (xfade_curve.is_valid()) {
+ blend = xfade_curve->interpolate(blend);
+ }
if (from_start && !p_seek && switched) { //just switched, seek to start of current
@@ -768,18 +779,16 @@ double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_seek_
return rem;
}
-void AnimationNodeTransition::_validate_property(PropertyInfo &property) const {
- if (property.name.begins_with("input_")) {
- String n = property.name.get_slicec('/', 0).get_slicec('_', 1);
+void AnimationNodeTransition::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name.begins_with("input_")) {
+ String n = p_property.name.get_slicec('/', 0).get_slicec('_', 1);
if (n != "count") {
int idx = n.to_int();
if (idx >= enabled_inputs) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
}
-
- AnimationNode::_validate_property(property);
}
void AnimationNodeTransition::_bind_methods() {
@@ -792,14 +801,18 @@ void AnimationNodeTransition::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_input_caption", "input", "caption"), &AnimationNodeTransition::set_input_caption);
ClassDB::bind_method(D_METHOD("get_input_caption", "input"), &AnimationNodeTransition::get_input_caption);
- ClassDB::bind_method(D_METHOD("set_cross_fade_time", "time"), &AnimationNodeTransition::set_cross_fade_time);
- ClassDB::bind_method(D_METHOD("get_cross_fade_time"), &AnimationNodeTransition::get_cross_fade_time);
+ ClassDB::bind_method(D_METHOD("set_xfade_time", "time"), &AnimationNodeTransition::set_xfade_time);
+ ClassDB::bind_method(D_METHOD("get_xfade_time"), &AnimationNodeTransition::get_xfade_time);
+
+ ClassDB::bind_method(D_METHOD("set_xfade_curve", "curve"), &AnimationNodeTransition::set_xfade_curve);
+ ClassDB::bind_method(D_METHOD("get_xfade_curve"), &AnimationNodeTransition::get_xfade_curve);
ClassDB::bind_method(D_METHOD("set_from_start", "from_start"), &AnimationNodeTransition::set_from_start);
ClassDB::bind_method(D_METHOD("is_from_start"), &AnimationNodeTransition::is_from_start);
ADD_PROPERTY(PropertyInfo(Variant::INT, "input_count", PROPERTY_HINT_RANGE, "0,64,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_enabled_inputs", "get_enabled_inputs");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "xfade_time", PROPERTY_HINT_RANGE, "0,120,0.01,suffix:s"), "set_cross_fade_time", "get_cross_fade_time");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "xfade_time", PROPERTY_HINT_RANGE, "0,120,0.01,suffix:s"), "set_xfade_time", "get_xfade_time");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "xfade_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_xfade_curve", "get_xfade_curve");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "from_start"), "set_from_start", "is_from_start");
for (int i = 0; i < MAX_INPUTS; i++) {
diff --git a/scene/animation/animation_blend_tree.h b/scene/animation/animation_blend_tree.h
index d35ff04f30..59c074cc80 100644
--- a/scene/animation/animation_blend_tree.h
+++ b/scene/animation/animation_blend_tree.h
@@ -67,7 +67,7 @@ public:
AnimationNodeAnimation();
protected:
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
private:
@@ -297,14 +297,15 @@ class AnimationNodeTransition : public AnimationNodeSync {
StringName current = PNAME("current");
StringName prev_current = "prev_current";
- float xfade = 0.0;
+ float xfade_time = 0.0;
+ Ref<Curve> xfade_curve;
bool from_start = true;
void _update_inputs();
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
virtual void get_parameter_list(List<PropertyInfo> *r_list) const override;
@@ -321,8 +322,11 @@ public:
void set_input_caption(int p_input, const String &p_name);
String get_input_caption(int p_input) const;
- void set_cross_fade_time(float p_fade);
- float get_cross_fade_time() const;
+ void set_xfade_time(float p_fade);
+ float get_xfade_time() const;
+
+ void set_xfade_curve(const Ref<Curve> &p_curve);
+ Ref<Curve> get_xfade_curve() const;
void set_from_start(bool p_from_start);
bool is_from_start() const;
diff --git a/scene/animation/animation_node_state_machine.cpp b/scene/animation/animation_node_state_machine.cpp
index 793967d9ad..4b3d7fd0a6 100644
--- a/scene/animation/animation_node_state_machine.cpp
+++ b/scene/animation/animation_node_state_machine.cpp
@@ -98,12 +98,20 @@ NodePath AnimationNodeStateMachineTransition::get_advance_expression_base_node()
void AnimationNodeStateMachineTransition::set_xfade_time(float p_xfade) {
ERR_FAIL_COND(p_xfade < 0);
- xfade = p_xfade;
+ xfade_time = p_xfade;
emit_changed();
}
float AnimationNodeStateMachineTransition::get_xfade_time() const {
- return xfade;
+ return xfade_time;
+}
+
+void AnimationNodeStateMachineTransition::set_xfade_curve(const Ref<Curve> &p_curve) {
+ xfade_curve = p_curve;
+}
+
+Ref<Curve> AnimationNodeStateMachineTransition::get_xfade_curve() const {
+ return xfade_curve;
}
void AnimationNodeStateMachineTransition::set_disabled(bool p_disabled) {
@@ -137,6 +145,9 @@ void AnimationNodeStateMachineTransition::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_xfade_time", "secs"), &AnimationNodeStateMachineTransition::set_xfade_time);
ClassDB::bind_method(D_METHOD("get_xfade_time"), &AnimationNodeStateMachineTransition::get_xfade_time);
+ ClassDB::bind_method(D_METHOD("set_xfade_curve", "curve"), &AnimationNodeStateMachineTransition::set_xfade_curve);
+ ClassDB::bind_method(D_METHOD("get_xfade_curve"), &AnimationNodeStateMachineTransition::get_xfade_curve);
+
ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &AnimationNodeStateMachineTransition::set_disabled);
ClassDB::bind_method(D_METHOD("is_disabled"), &AnimationNodeStateMachineTransition::is_disabled);
@@ -150,6 +161,7 @@ void AnimationNodeStateMachineTransition::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_advance_expression_base_node"), &AnimationNodeStateMachineTransition::get_advance_expression_base_node);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "xfade_time", PROPERTY_HINT_RANGE, "0,240,0.01,suffix:s"), "set_xfade_time", "get_xfade_time");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "xfade_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_xfade_curve", "get_xfade_curve");
ADD_PROPERTY(PropertyInfo(Variant::INT, "priority", PROPERTY_HINT_RANGE, "0,32,1"), "set_priority", "get_priority");
ADD_GROUP("Switch", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "switch_mode", PROPERTY_HINT_ENUM, "Immediate,Sync,At End"), "set_switch_mode", "get_switch_mode");
@@ -420,6 +432,9 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
}
}
+ if (current_curve.is_valid()) {
+ fade_blend = current_curve->interpolate(fade_blend);
+ }
float rem = p_state_machine->blend_node(current, p_state_machine->states[current].node, p_time, p_seek, p_seek_root, fade_blend, AnimationNode::FILTER_IGNORE, true);
if (fading_from != StringName()) {
@@ -450,6 +465,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
if (p_state_machine->transitions[i].local_from == current && p_state_machine->transitions[i].local_to == path[0]) {
next_xfade = p_state_machine->transitions[i].transition->get_xfade_time();
+ current_curve = p_state_machine->transitions[i].transition->get_xfade_curve();
switch_mode = p_state_machine->transitions[i].transition->get_switch_mode();
next = path[0];
}
@@ -504,6 +520,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
tr.to = String(p_state_machine->transitions[auto_advance_to].to).replace_first("../", "");
tr.next = p_state_machine->transitions[auto_advance_to].to;
current_transition = tr;
+ current_curve = p_state_machine->transitions[auto_advance_to].transition->get_xfade_curve();
next_xfade = p_state_machine->transitions[auto_advance_to].transition->get_xfade_time();
switch_mode = p_state_machine->transitions[auto_advance_to].transition->get_switch_mode();
}
diff --git a/scene/animation/animation_node_state_machine.h b/scene/animation/animation_node_state_machine.h
index ead914db7a..ab78b1afe8 100644
--- a/scene/animation/animation_node_state_machine.h
+++ b/scene/animation/animation_node_state_machine.h
@@ -49,7 +49,8 @@ private:
bool auto_advance = false;
StringName advance_condition;
StringName advance_condition_name;
- float xfade = 0.0;
+ float xfade_time = 0.0;
+ Ref<Curve> xfade_curve;
bool disabled = false;
int priority = 1;
String advance_expression;
@@ -82,6 +83,9 @@ public:
void set_xfade_time(float p_xfade);
float get_xfade_time() const;
+ void set_xfade_curve(const Ref<Curve> &p_curve);
+ Ref<Curve> get_xfade_curve() const;
+
void set_disabled(bool p_disabled);
bool is_disabled() const;
@@ -117,6 +121,7 @@ class AnimationNodeStateMachinePlayback : public Resource {
StringName current;
Transition current_transition;
+ Ref<Curve> current_curve;
bool force_auto_advance = false;
StringName fading_from;
diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp
index 09ec086564..48626ccc1b 100644
--- a/scene/animation/animation_player.cpp
+++ b/scene/animation/animation_player.cpp
@@ -37,6 +37,7 @@
#ifdef TOOLS_ENABLED
#include "editor/editor_node.h"
+#include "editor/editor_undo_redo_manager.h"
#include "scene/2d/skeleton_2d.h"
void AnimatedValuesBackup::update_skeletons() {
@@ -174,8 +175,8 @@ bool AnimationPlayer::_get(const StringName &p_name, Variant &r_ret) const {
return true;
}
-void AnimationPlayer::_validate_property(PropertyInfo &property) const {
- if (property.name == "current_animation") {
+void AnimationPlayer::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "current_animation") {
List<String> names;
for (const KeyValue<StringName, AnimationData> &E : animation_set) {
@@ -191,10 +192,8 @@ void AnimationPlayer::_validate_property(PropertyInfo &property) const {
hint += E->get();
}
- property.hint_string = hint;
+ p_property.hint_string = hint;
}
-
- Node::_validate_property(property);
}
void AnimationPlayer::_get_property_list(List<PropertyInfo> *p_list) const {
@@ -323,10 +322,8 @@ void AnimationPlayer::_ensure_node_caches(AnimationData *p_anim, Node *p_root_ov
#endif // _3D_DISABLED
- {
- if (!child->is_connected("tree_exiting", callable_mp(this, &AnimationPlayer::_node_removed))) {
- child->connect("tree_exiting", callable_mp(this, &AnimationPlayer::_node_removed).bind(child), CONNECT_ONESHOT);
- }
+ if (!child->is_connected("tree_exiting", callable_mp(this, &AnimationPlayer::_node_removed))) {
+ child->connect("tree_exiting", callable_mp(this, &AnimationPlayer::_node_removed).bind(child), CONNECT_ONESHOT);
}
TrackNodeCacheKey key;
@@ -375,7 +372,7 @@ void AnimationPlayer::_ensure_node_caches(AnimationData *p_anim, Node *p_root_ov
node_cache->init_rot = rest.basis.get_rotation_quaternion();
node_cache->init_scale = rest.basis.get_scale();
} else {
- // no property, just use spatialnode
+ // Not a skeleton, the node can be accessed with the node_3d member.
node_cache->skeleton = nullptr;
}
}
@@ -2048,7 +2045,7 @@ Ref<AnimatedValuesBackup> AnimationPlayer::apply_reset(bool p_user_initiated) {
Ref<AnimatedValuesBackup> new_values = aux_player->backup_animated_values();
old_values->restore();
- UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+ Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
ur->create_action(TTR("Anim Apply Reset"));
ur->add_do_method(new_values.ptr(), "restore");
ur->add_undo_method(old_values.ptr(), "restore");
diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h
index b6d8dab1ed..caf1387ff0 100644
--- a/scene/animation/animation_player.h
+++ b/scene/animation/animation_player.h
@@ -311,7 +311,7 @@ private:
protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp
index 14cf64afad..7dbe892299 100644
--- a/scene/animation/animation_tree.cpp
+++ b/scene/animation/animation_tree.cpp
@@ -399,9 +399,9 @@ void AnimationNode::_set_filters(const Array &p_filters) {
}
}
-void AnimationNode::_validate_property(PropertyInfo &property) const {
- if (!has_filter() && (property.name == "filter_enabled" || property.name == "filters")) {
- property.usage = PROPERTY_USAGE_NONE;
+void AnimationNode::_validate_property(PropertyInfo &p_property) const {
+ if (!has_filter() && (p_property.name == "filter_enabled" || p_property.name == "filters")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
diff --git a/scene/animation/animation_tree.h b/scene/animation/animation_tree.h
index 99851d140e..ee51a54557 100644
--- a/scene/animation/animation_tree.h
+++ b/scene/animation/animation_tree.h
@@ -111,7 +111,7 @@ protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
GDVIRTUAL0RC(Dictionary, _get_child_nodes)
GDVIRTUAL0RC(Array, _get_parameter_list)
diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp
index dbc71cd9e7..7d9f83b7a2 100644
--- a/scene/animation/tween.cpp
+++ b/scene/animation/tween.cpp
@@ -479,12 +479,8 @@ Variant Tween::interpolate_variant(Variant p_initial_val, Variant p_delta_val, f
case Variant::QUATERNION: {
Quaternion i = p_initial_val;
Quaternion d = p_delta_val;
- Quaternion r;
-
- APPLY_EQUATION(x);
- APPLY_EQUATION(y);
- APPLY_EQUATION(z);
- APPLY_EQUATION(w);
+ Quaternion r = i * d;
+ r = i.slerp(r, run_equation(p_trans, p_ease, p_time, 0.0, 1.0, p_duration));
return r;
}
diff --git a/scene/audio/audio_stream_player.cpp b/scene/audio/audio_stream_player.cpp
index 04debcab05..7c85b650bf 100644
--- a/scene/audio/audio_stream_player.cpp
+++ b/scene/audio/audio_stream_player.cpp
@@ -283,8 +283,8 @@ Vector<AudioFrame> AudioStreamPlayer::_get_volume_vector() {
return volume_vector;
}
-void AudioStreamPlayer::_validate_property(PropertyInfo &property) const {
- if (property.name == "bus") {
+void AudioStreamPlayer::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "bus") {
String options;
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (i > 0) {
@@ -294,10 +294,8 @@ void AudioStreamPlayer::_validate_property(PropertyInfo &property) const {
options += name;
}
- property.hint_string = options;
+ p_property.hint_string = options;
}
-
- Node::_validate_property(property);
}
void AudioStreamPlayer::_bus_layout_changed() {
diff --git a/scene/audio/audio_stream_player.h b/scene/audio/audio_stream_player.h
index 67e616312a..45a6d7663e 100644
--- a/scene/audio/audio_stream_player.h
+++ b/scene/audio/audio_stream_player.h
@@ -72,7 +72,7 @@ private:
Vector<AudioFrame> _get_volume_vector();
protected:
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _notification(int p_what);
static void _bind_methods();
diff --git a/scene/gui/aspect_ratio_container.cpp b/scene/gui/aspect_ratio_container.cpp
index 75f19ac452..e4a79c7aa3 100644
--- a/scene/gui/aspect_ratio_container.cpp
+++ b/scene/gui/aspect_ratio_container.cpp
@@ -51,21 +51,33 @@ Size2 AspectRatioContainer::get_minimum_size() const {
}
void AspectRatioContainer::set_ratio(float p_ratio) {
+ if (ratio == p_ratio) {
+ return;
+ }
ratio = p_ratio;
queue_sort();
}
void AspectRatioContainer::set_stretch_mode(StretchMode p_mode) {
+ if (stretch_mode == p_mode) {
+ return;
+ }
stretch_mode = p_mode;
queue_sort();
}
void AspectRatioContainer::set_alignment_horizontal(AlignmentMode p_alignment_horizontal) {
+ if (alignment_horizontal == p_alignment_horizontal) {
+ return;
+ }
alignment_horizontal = p_alignment_horizontal;
queue_sort();
}
void AspectRatioContainer::set_alignment_vertical(AlignmentMode p_alignment_vertical) {
+ if (alignment_vertical == p_alignment_vertical) {
+ return;
+ }
alignment_vertical = p_alignment_vertical;
queue_sort();
}
diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp
index 776623f7ce..87a7355bb2 100644
--- a/scene/gui/base_button.cpp
+++ b/scene/gui/base_button.cpp
@@ -64,6 +64,8 @@ void BaseButton::gui_input(const Ref<InputEvent> &p_event) {
bool button_masked = mouse_button.is_valid() && (mouse_button_to_mask(mouse_button->get_button_index()) & button_mask) != MouseButton::NONE;
if (button_masked || ui_accept) {
+ was_mouse_pressed = button_masked;
+
on_action_event(p_event);
return;
}
@@ -417,6 +419,10 @@ bool BaseButton::_is_focus_owner_in_shortcut_context() const {
return ctx_node && vp_focus && (ctx_node == vp_focus || ctx_node->is_ancestor_of(vp_focus));
}
+bool BaseButton::_was_pressed_by_mouse() const {
+ return was_mouse_pressed;
+}
+
void BaseButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_pressed", "pressed"), &BaseButton::set_pressed);
ClassDB::bind_method(D_METHOD("is_pressed"), &BaseButton::is_pressed);
@@ -490,8 +496,8 @@ void ButtonGroup::get_buttons(List<BaseButton *> *r_buttons) {
}
}
-Array ButtonGroup::_get_buttons() {
- Array btns;
+TypedArray<BaseButton> ButtonGroup::_get_buttons() {
+ TypedArray<BaseButton> btns;
for (const BaseButton *E : buttons) {
btns.push_back(E);
}
diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h
index 7cf8de6432..c83b08aadf 100644
--- a/scene/gui/base_button.h
+++ b/scene/gui/base_button.h
@@ -49,6 +49,7 @@ private:
MouseButton button_mask = MouseButton::MASK_LEFT;
bool toggle_mode = false;
bool shortcut_in_tooltip = true;
+ bool was_mouse_pressed = false;
bool keep_pressed_outside = false;
Ref<Shortcut> shortcut;
ObjectID shortcut_context;
@@ -81,6 +82,7 @@ protected:
void _notification(int p_what);
bool _is_focus_owner_in_shortcut_context() const;
+ bool _was_pressed_by_mouse() const;
GDVIRTUAL0(_pressed)
GDVIRTUAL1(_toggled, bool)
@@ -151,7 +153,7 @@ protected:
public:
BaseButton *get_pressed_button();
void get_buttons(List<BaseButton *> *r_buttons);
- Array _get_buttons();
+ TypedArray<BaseButton> _get_buttons();
ButtonGroup();
};
diff --git a/scene/gui/box_container.cpp b/scene/gui/box_container.cpp
index df695feba8..a56a51a547 100644
--- a/scene/gui/box_container.cpp
+++ b/scene/gui/box_container.cpp
@@ -308,6 +308,9 @@ void BoxContainer::_notification(int p_what) {
}
void BoxContainer::set_alignment(AlignmentMode p_alignment) {
+ if (alignment == p_alignment) {
+ return;
+ }
alignment = p_alignment;
_resort();
}
diff --git a/scene/gui/button.cpp b/scene/gui/button.cpp
index 0a163b65ff..e163f4355c 100644
--- a/scene/gui/button.cpp
+++ b/scene/gui/button.cpp
@@ -34,11 +34,9 @@
#include "servers/rendering_server.h"
Size2 Button::get_minimum_size() const {
- Ref<Texture2D> _icon;
- if (icon.is_null() && has_theme_icon(SNAME("icon"))) {
+ Ref<Texture2D> _icon = icon;
+ if (_icon.is_null() && has_theme_icon(SNAME("icon"))) {
_icon = Control::get_theme_icon(SNAME("icon"));
- } else {
- _icon = icon;
}
return get_minimum_size_for_text_and_icon("", _icon);
@@ -342,13 +340,13 @@ Size2 Button::get_minimum_size_for_text_and_icon(const String &p_text, Ref<Textu
minsize.width = 0;
}
- if (!expand_icon && !p_icon.is_null()) {
+ if (!expand_icon && p_icon.is_valid()) {
minsize.height = MAX(minsize.height, p_icon->get_height());
if (icon_alignment != HORIZONTAL_ALIGNMENT_CENTER) {
minsize.width += p_icon->get_width();
if (!xl_text.is_empty() || !p_text.is_empty()) {
- minsize.width += get_theme_constant(SNAME("hseparation"));
+ minsize.width += MAX(0, get_theme_constant(SNAME("h_separation")));
}
} else {
minsize.width = MAX(minsize.width, p_icon->get_width());
diff --git a/scene/gui/check_box.cpp b/scene/gui/check_box.cpp
index cb80f5b5ef..26edc1f1b0 100644
--- a/scene/gui/check_box.cpp
+++ b/scene/gui/check_box.cpp
@@ -75,7 +75,7 @@ Size2 CheckBox::get_minimum_size() const {
Size2 tex_size = get_icon_size();
minsize.width += tex_size.width;
if (get_text().length() > 0) {
- minsize.width += get_theme_constant(SNAME("h_separation"));
+ minsize.width += MAX(0, get_theme_constant(SNAME("h_separation")));
}
Ref<StyleBox> sb = get_theme_stylebox(SNAME("normal"));
minsize.height = MAX(minsize.height, tex_size.height + sb->get_margin(SIDE_TOP) + sb->get_margin(SIDE_BOTTOM));
diff --git a/scene/gui/check_button.cpp b/scene/gui/check_button.cpp
index a09873ea4f..b9674ca41e 100644
--- a/scene/gui/check_button.cpp
+++ b/scene/gui/check_button.cpp
@@ -52,7 +52,7 @@ Size2 CheckButton::get_minimum_size() const {
Size2 tex_size = get_icon_size();
minsize.width += tex_size.width;
if (get_text().length() > 0) {
- minsize.width += get_theme_constant(SNAME("h_separation"));
+ minsize.width += MAX(0, get_theme_constant(SNAME("h_separation")));
}
Ref<StyleBox> sb = get_theme_stylebox(SNAME("normal"));
minsize.height = MAX(minsize.height, tex_size.height + sb->get_margin(SIDE_TOP) + sb->get_margin(SIDE_BOTTOM));
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index 8968c1cc17..e54ba7ce13 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -1280,8 +1280,8 @@ void CodeEdit::clear_breakpointed_lines() {
}
}
-Array CodeEdit::get_breakpointed_lines() const {
- Array ret;
+PackedInt32Array CodeEdit::get_breakpointed_lines() const {
+ PackedInt32Array ret;
for (int i = 0; i < get_line_count(); i++) {
if (is_line_breakpointed(i)) {
ret.append(i);
@@ -1309,8 +1309,8 @@ void CodeEdit::clear_bookmarked_lines() {
}
}
-Array CodeEdit::get_bookmarked_lines() const {
- Array ret;
+PackedInt32Array CodeEdit::get_bookmarked_lines() const {
+ PackedInt32Array ret;
for (int i = 0; i < get_line_count(); i++) {
if (is_line_bookmarked(i)) {
ret.append(i);
@@ -1338,8 +1338,8 @@ void CodeEdit::clear_executing_lines() {
}
}
-Array CodeEdit::get_executing_lines() const {
- Array ret;
+PackedInt32Array CodeEdit::get_executing_lines() const {
+ PackedInt32Array ret;
for (int i = 0; i < get_line_count(); i++) {
if (is_line_executing(i)) {
ret.append(i);
@@ -2769,7 +2769,7 @@ void CodeEdit::_filter_code_completion_candidates_impl() {
i++;
}
- Array completion_options;
+ TypedArray<Dictionary> completion_options;
GDVIRTUAL_CALL(_filter_code_completion_candidates, completion_options_sources, completion_options);
diff --git a/scene/gui/code_edit.h b/scene/gui/code_edit.h
index 08bd91a368..2065f3e681 100644
--- a/scene/gui/code_edit.h
+++ b/scene/gui/code_edit.h
@@ -266,7 +266,7 @@ protected:
GDVIRTUAL1(_confirm_code_completion, bool)
GDVIRTUAL1(_request_code_completion, bool)
- GDVIRTUAL1RC(Array, _filter_code_completion_candidates, TypedArray<Dictionary>)
+ GDVIRTUAL1RC(TypedArray<Dictionary>, _filter_code_completion_candidates, TypedArray<Dictionary>)
public:
/* General overrides */
@@ -322,19 +322,19 @@ public:
void set_line_as_breakpoint(int p_line, bool p_breakpointed);
bool is_line_breakpointed(int p_line) const;
void clear_breakpointed_lines();
- Array get_breakpointed_lines() const;
+ PackedInt32Array get_breakpointed_lines() const;
// bookmarks
void set_line_as_bookmarked(int p_line, bool p_bookmarked);
bool is_line_bookmarked(int p_line) const;
void clear_bookmarked_lines();
- Array get_bookmarked_lines() const;
+ PackedInt32Array get_bookmarked_lines() const;
// executing lines
void set_line_as_executing(int p_line, bool p_executing);
bool is_line_executing(int p_line) const;
void clear_executing_lines();
- Array get_executing_lines() const;
+ PackedInt32Array get_executing_lines() const;
/* Line numbers */
void set_draw_line_numbers(bool p_draw);
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index 8cbe14c492..9eef45f412 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -292,6 +292,9 @@ bool ColorPicker::is_displaying_old_color() const {
}
void ColorPicker::set_edit_alpha(bool p_show) {
+ if (edit_alpha == p_show) {
+ return;
+ }
edit_alpha = p_show;
_update_controls();
@@ -509,6 +512,9 @@ Color ColorPicker::get_pick_color() const {
void ColorPicker::set_picker_shape(PickerShapeType p_shape) {
ERR_FAIL_INDEX(p_shape, SHAPE_MAX);
+ if (current_shape == p_shape) {
+ return;
+ }
current_shape = p_shape;
_copy_color_to_hsv();
@@ -1131,6 +1137,9 @@ void ColorPicker::_html_focus_exit() {
}
void ColorPicker::set_presets_enabled(bool p_enabled) {
+ if (presets_enabled == p_enabled) {
+ return;
+ }
presets_enabled = p_enabled;
if (!p_enabled) {
btn_add_preset->set_disabled(true);
@@ -1146,6 +1155,9 @@ bool ColorPicker::are_presets_enabled() const {
}
void ColorPicker::set_presets_visible(bool p_visible) {
+ if (presets_visible == p_visible) {
+ return;
+ }
presets_visible = p_visible;
preset_separator->set_visible(p_visible);
preset_container->set_visible(p_visible);
@@ -1419,6 +1431,9 @@ void ColorPickerButton::_notification(int p_what) {
}
void ColorPickerButton::set_pick_color(const Color &p_color) {
+ if (color == p_color) {
+ return;
+ }
color = p_color;
if (picker) {
picker->set_pick_color(p_color);
@@ -1432,6 +1447,9 @@ Color ColorPickerButton::get_pick_color() const {
}
void ColorPickerButton::set_edit_alpha(bool p_show) {
+ if (edit_alpha == p_show) {
+ return;
+ }
edit_alpha = p_show;
if (picker) {
picker->set_edit_alpha(p_show);
diff --git a/scene/gui/color_rect.cpp b/scene/gui/color_rect.cpp
index 2955f74a0c..c30fa8461a 100644
--- a/scene/gui/color_rect.cpp
+++ b/scene/gui/color_rect.cpp
@@ -31,6 +31,9 @@
#include "color_rect.h"
void ColorRect::set_color(const Color &p_color) {
+ if (color == p_color) {
+ return;
+ }
color = p_color;
update();
}
diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp
index 6d0380c898..03fcef17f5 100644
--- a/scene/gui/control.cpp
+++ b/scene/gui/control.cpp
@@ -422,9 +422,9 @@ void Control::_get_property_list(List<PropertyInfo> *p_list) const {
}
}
-void Control::_validate_property(PropertyInfo &property) const {
+void Control::_validate_property(PropertyInfo &p_property) const {
// Update theme type variation options.
- if (property.name == "theme_type_variation") {
+ if (p_property.name == "theme_type_variation") {
List<StringName> names;
// Only the default theme and the project theme are used for the list of options.
@@ -447,18 +447,18 @@ void Control::_validate_property(PropertyInfo &property) const {
unique_names.append(E);
}
- property.hint_string = hint_string;
+ p_property.hint_string = hint_string;
}
- if (property.name == "mouse_force_pass_scroll_events") {
+ if (p_property.name == "mouse_force_pass_scroll_events") {
// Disable force pass if the control is not stopping the event.
if (data.mouse_filter != MOUSE_FILTER_STOP) {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
}
- if (property.name == "scale") {
- property.hint = PROPERTY_HINT_LINK;
+ if (p_property.name == "scale") {
+ p_property.hint = PROPERTY_HINT_LINK;
}
// Validate which positioning properties should be displayed depending on the parent and the layout mode.
@@ -467,33 +467,33 @@ void Control::_validate_property(PropertyInfo &property) const {
// If there is no parent, display both anchor and container options.
// Set the layout mode to be disabled with the proper value.
- if (property.name == "layout_mode") {
- property.hint_string = "Position,Anchors,Container,Uncontrolled";
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ if (p_property.name == "layout_mode") {
+ p_property.hint_string = "Position,Anchors,Container,Uncontrolled";
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
// Use the layout mode to display or hide advanced anchoring properties.
bool use_custom_anchors = _get_anchors_layout_preset() == -1; // Custom "preset".
- if (!use_custom_anchors && (property.name.begins_with("anchor_") || property.name.begins_with("offset_") || property.name.begins_with("grow_"))) {
- property.usage ^= PROPERTY_USAGE_EDITOR;
+ if (!use_custom_anchors && (p_property.name.begins_with("anchor_") || p_property.name.begins_with("offset_") || p_property.name.begins_with("grow_"))) {
+ p_property.usage ^= PROPERTY_USAGE_EDITOR;
}
} else if (Object::cast_to<Container>(parent_node)) {
// If the parent is a container, display only container-related properties.
- if (property.name.begins_with("anchor_") || property.name.begins_with("offset_") || property.name.begins_with("grow_") || property.name == "anchors_preset" ||
- property.name == "position" || property.name == "rotation" || property.name == "scale" || property.name == "size" || property.name == "pivot_offset") {
- property.usage ^= PROPERTY_USAGE_EDITOR;
+ if (p_property.name.begins_with("anchor_") || p_property.name.begins_with("offset_") || p_property.name.begins_with("grow_") || p_property.name == "anchors_preset" ||
+ p_property.name == "position" || p_property.name == "rotation" || p_property.name == "scale" || p_property.name == "size" || p_property.name == "pivot_offset") {
+ p_property.usage ^= PROPERTY_USAGE_EDITOR;
- } else if (property.name == "layout_mode") {
+ } else if (p_property.name == "layout_mode") {
// Set the layout mode to be disabled with the proper value.
- property.hint_string = "Position,Anchors,Container,Uncontrolled";
- property.usage |= PROPERTY_USAGE_READ_ONLY;
- } else if (property.name == "size_flags_horizontal" || property.name == "size_flags_vertical") {
+ p_property.hint_string = "Position,Anchors,Container,Uncontrolled";
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
+ } else if (p_property.name == "size_flags_horizontal" || p_property.name == "size_flags_vertical") {
// Filter allowed size flags based on the parent container configuration.
Container *parent_container = Object::cast_to<Container>(parent_node);
Vector<int> size_flags;
- if (property.name == "size_flags_horizontal") {
+ if (p_property.name == "size_flags_horizontal") {
size_flags = parent_container->get_allowed_size_flags_horizontal();
- } else if (property.name == "size_flags_vertical") {
+ } else if (p_property.name == "size_flags_vertical") {
size_flags = parent_container->get_allowed_size_flags_vertical();
}
@@ -522,30 +522,30 @@ void Control::_validate_property(PropertyInfo &property) const {
}
if (hint_string.is_empty()) {
- property.hint_string = "";
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.hint_string = "";
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
} else {
- property.hint_string = hint_string;
+ p_property.hint_string = hint_string;
}
}
} else {
// If the parent is NOT a container or not a control at all, display only anchoring-related properties.
- if (property.name.begins_with("size_flags_")) {
- property.usage ^= PROPERTY_USAGE_EDITOR;
+ if (p_property.name.begins_with("size_flags_")) {
+ p_property.usage ^= PROPERTY_USAGE_EDITOR;
- } else if (property.name == "layout_mode") {
+ } else if (p_property.name == "layout_mode") {
// Set the layout mode to be enabled with proper options.
- property.hint_string = "Position,Anchors";
+ p_property.hint_string = "Position,Anchors";
}
// Use the layout mode to display or hide advanced anchoring properties.
bool use_anchors = _get_layout_mode() == LayoutMode::LAYOUT_MODE_ANCHORS;
- if (!use_anchors && property.name == "anchors_preset") {
- property.usage ^= PROPERTY_USAGE_EDITOR;
+ if (!use_anchors && p_property.name == "anchors_preset") {
+ p_property.usage ^= PROPERTY_USAGE_EDITOR;
}
bool use_custom_anchors = use_anchors && _get_anchors_layout_preset() == -1; // Custom "preset".
- if (!use_custom_anchors && (property.name.begins_with("anchor_") || property.name.begins_with("offset_") || property.name.begins_with("grow_"))) {
- property.usage ^= PROPERTY_USAGE_EDITOR;
+ if (!use_custom_anchors && (p_property.name.begins_with("anchor_") || p_property.name.begins_with("offset_") || p_property.name.begins_with("grow_"))) {
+ p_property.usage ^= PROPERTY_USAGE_EDITOR;
}
}
@@ -555,16 +555,36 @@ void Control::_validate_property(PropertyInfo &property) const {
}
bool property_is_managed_by_container = false;
for (unsigned i = 0; i < properties_managed_by_container_count; i++) {
- property_is_managed_by_container = properties_managed_by_container[i] == property.name;
+ property_is_managed_by_container = properties_managed_by_container[i] == p_property.name;
if (property_is_managed_by_container) {
break;
}
}
if (property_is_managed_by_container) {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
}
+bool Control::_property_can_revert(const StringName &p_name) const {
+ if (p_name == "layout_mode" || p_name == "anchors_preset") {
+ return true;
+ }
+
+ return false;
+}
+
+bool Control::_property_get_revert(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "layout_mode") {
+ r_property = _get_default_layout_mode();
+ return true;
+ } else if (p_name == "anchors_preset") {
+ r_property = LayoutPreset::PRESET_TOP_LEFT;
+ return true;
+ }
+
+ return false;
+}
+
// Global relations.
bool Control::is_top_level_control() const {
@@ -703,6 +723,9 @@ real_t Control::get_anchor(Side p_side) const {
void Control::set_offset(Side p_side, real_t p_value) {
ERR_FAIL_INDEX((int)p_side, 4);
+ if (data.offset[p_side] == p_value) {
+ return;
+ }
data.offset[p_side] = p_value;
_size_changed();
@@ -720,6 +743,10 @@ void Control::set_anchor_and_offset(Side p_side, real_t p_anchor, real_t p_pos,
}
void Control::set_begin(const Size2 &p_point) {
+ if (data.offset[0] == p_point.x && data.offset[1] == p_point.y) {
+ return;
+ }
+
data.offset[0] = p_point.x;
data.offset[1] = p_point.y;
_size_changed();
@@ -730,6 +757,10 @@ Size2 Control::get_begin() const {
}
void Control::set_end(const Size2 &p_point) {
+ if (data.offset[2] == p_point.x && data.offset[3] == p_point.y) {
+ return;
+ }
+
data.offset[2] = p_point.x;
data.offset[3] = p_point.y;
_size_changed();
@@ -740,6 +771,10 @@ Size2 Control::get_end() const {
}
void Control::set_h_grow_direction(GrowDirection p_direction) {
+ if (data.h_grow == p_direction) {
+ return;
+ }
+
ERR_FAIL_INDEX((int)p_direction, 3);
data.h_grow = p_direction;
@@ -751,6 +786,10 @@ Control::GrowDirection Control::get_h_grow_direction() const {
}
void Control::set_v_grow_direction(GrowDirection p_direction) {
+ if (data.v_grow == p_direction) {
+ return;
+ }
+
ERR_FAIL_INDEX((int)p_direction, 3);
data.v_grow = p_direction;
@@ -794,24 +833,15 @@ void Control::_compute_offsets(Rect2 p_rect, const real_t p_anchors[4], real_t (
void Control::_set_layout_mode(LayoutMode p_mode) {
bool list_changed = false;
- if (p_mode == LayoutMode::LAYOUT_MODE_POSITION || p_mode == LayoutMode::LAYOUT_MODE_ANCHORS) {
- if ((int)get_meta("_edit_layout_mode", p_mode) != (int)p_mode) {
- list_changed = true;
- }
-
- set_meta("_edit_layout_mode", (int)p_mode);
+ if (data.stored_layout_mode != p_mode) {
+ list_changed = true;
+ data.stored_layout_mode = p_mode;
+ }
- if (p_mode == LayoutMode::LAYOUT_MODE_POSITION) {
- remove_meta("_edit_layout_mode");
- remove_meta("_edit_use_custom_anchors");
- set_anchors_and_offsets_preset(LayoutPreset::PRESET_TOP_LEFT, LayoutPresetMode::PRESET_MODE_KEEP_SIZE);
- set_grow_direction_preset(LayoutPreset::PRESET_TOP_LEFT);
- }
- } else {
- if (has_meta("_edit_layout_mode")) {
- remove_meta("_edit_layout_mode");
- list_changed = true;
- }
+ if (data.stored_layout_mode == LayoutMode::LAYOUT_MODE_POSITION) {
+ data.stored_use_custom_anchors = false;
+ set_anchors_and_offsets_preset(LayoutPreset::PRESET_TOP_LEFT, LayoutPresetMode::PRESET_MODE_KEEP_SIZE);
+ set_grow_direction_preset(LayoutPreset::PRESET_TOP_LEFT);
}
if (list_changed) {
@@ -832,33 +862,43 @@ Control::LayoutMode Control::_get_layout_mode() const {
if (_get_anchors_layout_preset() != (int)LayoutPreset::PRESET_TOP_LEFT) {
return LayoutMode::LAYOUT_MODE_ANCHORS;
}
- // Otherwise check what was saved.
- if (has_meta("_edit_layout_mode")) {
- return (LayoutMode)(int)get_meta("_edit_layout_mode");
+
+ // Otherwise fallback on what's stored.
+ return data.stored_layout_mode;
+}
+
+Control::LayoutMode Control::_get_default_layout_mode() const {
+ Node *parent_node = get_parent_control();
+ // In these modes the property is read-only.
+ if (!parent_node) {
+ return LayoutMode::LAYOUT_MODE_UNCONTROLLED;
+ } else if (Object::cast_to<Container>(parent_node)) {
+ return LayoutMode::LAYOUT_MODE_CONTAINER;
}
- // Or fallback on default.
+
+ // Otherwise fallback on the position mode.
return LayoutMode::LAYOUT_MODE_POSITION;
}
void Control::_set_anchors_layout_preset(int p_preset) {
bool list_changed = false;
- if (get_meta("_edit_layout_mode", LayoutMode::LAYOUT_MODE_ANCHORS).operator int() != LayoutMode::LAYOUT_MODE_ANCHORS) {
+ if (data.stored_layout_mode != LayoutMode::LAYOUT_MODE_ANCHORS) {
list_changed = true;
- set_meta("_edit_layout_mode", LayoutMode::LAYOUT_MODE_ANCHORS);
+ data.stored_layout_mode = LayoutMode::LAYOUT_MODE_ANCHORS;
}
if (p_preset == -1) {
- if (!get_meta("_edit_use_custom_anchors", false)) {
- set_meta("_edit_use_custom_anchors", true);
+ if (!data.stored_use_custom_anchors) {
+ data.stored_use_custom_anchors = true;
notify_property_list_changed();
}
return; // Keep settings as is.
}
- if (get_meta("_edit_use_custom_anchors", true)) {
+ if (data.stored_use_custom_anchors) {
list_changed = true;
- remove_meta("_edit_use_custom_anchors");
+ data.stored_use_custom_anchors = false;
}
LayoutPreset preset = (LayoutPreset)p_preset;
@@ -899,7 +939,7 @@ void Control::_set_anchors_layout_preset(int p_preset) {
int Control::_get_anchors_layout_preset() const {
// If the custom preset was selected by user, use it.
- if ((bool)get_meta("_edit_use_custom_anchors", false)) {
+ if (data.stored_use_custom_anchors) {
return -1;
}
@@ -1406,6 +1446,10 @@ Rect2 Control::get_anchorable_rect() const {
}
void Control::set_scale(const Vector2 &p_scale) {
+ if (data.scale == p_scale) {
+ return;
+ }
+
data.scale = p_scale;
// Avoid having 0 scale values, can lead to errors in physics and rendering.
if (data.scale.x == 0) {
@@ -1423,6 +1467,10 @@ Vector2 Control::get_scale() const {
}
void Control::set_rotation(real_t p_radians) {
+ if (data.rotation == p_radians) {
+ return;
+ }
+
data.rotation = p_radians;
update();
_notify_transform();
@@ -1433,6 +1481,10 @@ real_t Control::get_rotation() const {
}
void Control::set_pivot_offset(const Vector2 &p_pivot) {
+ if (data.pivot_offset == p_pivot) {
+ return;
+ }
+
data.pivot_offset = p_pivot;
update();
_notify_transform();
@@ -2183,6 +2235,9 @@ Control::CursorShape Control::get_cursor_shape(const Point2 &p_pos) const {
}
void Control::set_disable_visibility_clip(bool p_ignore) {
+ if (data.disable_visibility_clip == p_ignore) {
+ return;
+ }
data.disable_visibility_clip = p_ignore;
update();
}
@@ -2192,6 +2247,9 @@ bool Control::is_visibility_clip_disabled() const {
}
void Control::set_clip_contents(bool p_clip) {
+ if (data.clip_contents == p_clip) {
+ return;
+ }
data.clip_contents = p_clip;
update();
}
@@ -2310,6 +2368,9 @@ Ref<Theme> Control::get_theme() const {
}
void Control::set_theme_type_variation(const StringName &p_theme_type) {
+ if (data.theme_type_variation == p_theme_type) {
+ return;
+ }
data.theme_type_variation = p_theme_type;
_propagate_theme_changed(this, data.theme_owner, data.theme_owner_window);
}
@@ -2925,13 +2986,13 @@ void Control::end_bulk_theme_override() {
// Internationalization.
-Array Control::structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
+TypedArray<Vector2i> Control::structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
if (p_parser_type == TextServer::STRUCTURED_TEXT_CUSTOM) {
- Array ret;
+ TypedArray<Vector2i> ret;
if (GDVIRTUAL_CALL(_structured_text_parser, p_args, p_text, ret)) {
return ret;
} else {
- return Array();
+ return TypedArray<Vector2i>();
}
} else {
return TS->parse_structured_text(p_parser_type, p_args, p_text);
@@ -2939,6 +3000,9 @@ Array Control::structured_text_parser(TextServer::StructuredTextParser p_parser_
}
void Control::set_layout_direction(Control::LayoutDirection p_direction) {
+ if (data.layout_dir == p_direction) {
+ return;
+ }
ERR_FAIL_INDEX((int)p_direction, 4);
data.layout_dir = p_direction;
@@ -3391,7 +3455,7 @@ void Control::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_contents"), "set_clip_contents", "is_clipping_contents");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "custom_minimum_size", PROPERTY_HINT_NONE, "suffix:px"), "set_custom_minimum_size", "get_custom_minimum_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "layout_direction", PROPERTY_HINT_ENUM, "Inherited,Locale,Left-to-Right,Right-to-Left"), "set_layout_direction", "get_layout_direction");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "layout_mode", PROPERTY_HINT_ENUM, "Position,Anchors,Container,Uncontrolled", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_layout_mode", "_get_layout_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "layout_mode", PROPERTY_HINT_ENUM, "Position,Anchors,Container,Uncontrolled", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL), "_set_layout_mode", "_get_layout_mode");
ADD_PROPERTY_DEFAULT("layout_mode", LayoutMode::LAYOUT_MODE_POSITION);
const String anchors_presets_options = "Custom:-1,PresetFullRect:15,"
@@ -3399,7 +3463,7 @@ void Control::_bind_methods() {
"PresetCenterLeft:4,PresetCenterTop:5,PresetCenterRight:6,PresetCenterBottom:7,PresetCenter:8,"
"PresetLeftWide:9,PresetTopWide:10,PresetRightWide:11,PresetBottomWide:12,PresetVCenterWide:13,PresetHCenterWide:14";
- ADD_PROPERTY(PropertyInfo(Variant::INT, "anchors_preset", PROPERTY_HINT_ENUM, anchors_presets_options, PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_anchors_layout_preset", "_get_anchors_layout_preset");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "anchors_preset", PROPERTY_HINT_ENUM, anchors_presets_options, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL), "_set_anchors_layout_preset", "_get_anchors_layout_preset");
ADD_PROPERTY_DEFAULT("anchors_preset", -1);
ADD_SUBGROUP_INDENT("Anchor Points", "anchor_", 1);
@@ -3558,3 +3622,24 @@ void Control::_bind_methods() {
GDVIRTUAL_BIND(_gui_input, "event");
}
+
+Control::~Control() {
+ // Resources need to be disconnected.
+ for (KeyValue<StringName, Ref<Texture2D>> &E : data.icon_override) {
+ E.value->disconnect("changed", callable_mp(this, &Control::_theme_property_override_changed));
+ }
+ for (KeyValue<StringName, Ref<StyleBox>> &E : data.style_override) {
+ E.value->disconnect("changed", callable_mp(this, &Control::_theme_property_override_changed));
+ }
+ for (KeyValue<StringName, Ref<Font>> &E : data.font_override) {
+ E.value->disconnect("changed", callable_mp(this, &Control::_theme_property_override_changed));
+ }
+
+ // Then override maps can be simply cleared.
+ data.icon_override.clear();
+ data.style_override.clear();
+ data.font_override.clear();
+ data.font_size_override.clear();
+ data.color_override.clear();
+ data.constant_override.clear();
+}
diff --git a/scene/gui/control.h b/scene/gui/control.h
index db19d09b11..c69067f82f 100644
--- a/scene/gui/control.h
+++ b/scene/gui/control.h
@@ -170,6 +170,9 @@ private:
// Positioning and sizing.
+ LayoutMode stored_layout_mode = LayoutMode::LAYOUT_MODE_POSITION;
+ bool stored_use_custom_anchors = false;
+
real_t offset[4] = { 0.0, 0.0, 0.0, 0.0 };
real_t anchor[4] = { ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_BEGIN };
FocusMode focus_mode = FOCUS_NONE;
@@ -275,6 +278,7 @@ private:
void _set_layout_mode(LayoutMode p_mode);
LayoutMode _get_layout_mode() const;
+ LayoutMode _get_default_layout_mode() const;
void _set_anchors_layout_preset(int p_preset);
int _get_anchors_layout_preset() const;
@@ -317,11 +321,14 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
+
+ bool _property_can_revert(const StringName &p_name) const;
+ bool _property_get_revert(const StringName &p_name, Variant &r_property) const;
// Internationalization.
- virtual Array structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
+ virtual TypedArray<Vector2i> structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
// Base object overrides.
@@ -334,7 +341,7 @@ protected:
// Exposed virtual methods.
GDVIRTUAL1RC(bool, _has_point, Vector2)
- GDVIRTUAL2RC(Array, _structured_text_parser, Array, String)
+ GDVIRTUAL2RC(TypedArray<Vector2i>, _structured_text_parser, Array, String)
GDVIRTUAL0RC(Vector2, _get_minimum_size)
GDVIRTUAL1RC(Variant, _get_drag_data, Vector2)
@@ -603,6 +610,7 @@ public:
virtual Control *make_custom_tooltip(const String &p_text) const;
Control() {}
+ ~Control();
};
VARIANT_ENUM_CAST(Control::FocusMode);
diff --git a/scene/gui/dialogs.cpp b/scene/gui/dialogs.cpp
index f075510aa4..b4e0747ab8 100644
--- a/scene/gui/dialogs.cpp
+++ b/scene/gui/dialogs.cpp
@@ -130,6 +130,9 @@ String AcceptDialog::get_text() const {
}
void AcceptDialog::set_text(String p_text) {
+ if (label->get_text() == p_text) {
+ return;
+ }
label->set_text(p_text);
child_controls_changed();
if (is_visible()) {
diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp
index e26976a402..7965b12edd 100644
--- a/scene/gui/file_dialog.cpp
+++ b/scene/gui/file_dialog.cpp
@@ -685,6 +685,9 @@ void FileDialog::add_filter(const String &p_filter, const String &p_description)
}
void FileDialog::set_filters(const Vector<String> &p_filters) {
+ if (filters == p_filters) {
+ return;
+ }
filters = p_filters;
update_filters();
invalidate();
@@ -708,10 +711,14 @@ String FileDialog::get_current_path() const {
void FileDialog::set_current_dir(const String &p_dir) {
_change_dir(p_dir);
+
_push_history();
}
void FileDialog::set_current_file(const String &p_file) {
+ if (file->get_text() == p_file) {
+ return;
+ }
file->set_text(p_file);
update_dir();
invalidate();
@@ -764,7 +771,9 @@ bool FileDialog::is_mode_overriding_title() const {
void FileDialog::set_file_mode(FileMode p_mode) {
ERR_FAIL_INDEX((int)p_mode, 5);
-
+ if (mode == p_mode) {
+ return;
+ }
mode = p_mode;
switch (mode) {
case FILE_MODE_OPEN_FILE:
@@ -977,6 +986,9 @@ void FileDialog::_bind_methods() {
}
void FileDialog::set_show_hidden_files(bool p_show) {
+ if (show_hidden_files == p_show) {
+ return;
+ }
show_hidden_files = p_show;
invalidate();
}
diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp
index 09efee71a3..e6198b44ff 100644
--- a/scene/gui/graph_edit.cpp
+++ b/scene/gui/graph_edit.cpp
@@ -1591,10 +1591,10 @@ void GraphEdit::remove_valid_left_disconnect_type(int p_type) {
valid_left_disconnect_types.erase(p_type);
}
-Array GraphEdit::_get_connection_list() const {
+TypedArray<Dictionary> GraphEdit::_get_connection_list() const {
List<Connection> conns;
get_connection_list(&conns);
- Array arr;
+ TypedArray<Dictionary> arr;
for (const Connection &E : conns) {
Dictionary d;
d["from"] = E.from;
@@ -1640,6 +1640,9 @@ bool GraphEdit::is_valid_connection_type(int p_type, int p_with_type) const {
}
void GraphEdit::set_use_snap(bool p_enable) {
+ if (snap_button->is_pressed() == p_enable) {
+ return;
+ }
snap_button->set_pressed(p_enable);
update();
}
@@ -1683,6 +1686,9 @@ Vector2 GraphEdit::get_minimap_size() const {
}
void GraphEdit::set_minimap_opacity(float p_opacity) {
+ if (minimap->get_modulate().a == p_opacity) {
+ return;
+ }
minimap->set_modulate(Color(1, 1, 1, p_opacity));
minimap->update();
}
@@ -1693,6 +1699,9 @@ float GraphEdit::get_minimap_opacity() const {
}
void GraphEdit::set_minimap_enabled(bool p_enable) {
+ if (minimap_button->is_pressed() == p_enable) {
+ return;
+ }
minimap_button->set_pressed(p_enable);
_minimap_toggled();
minimap->update();
@@ -1721,6 +1730,9 @@ float GraphEdit::get_connection_lines_curvature() const {
}
void GraphEdit::set_connection_lines_thickness(float p_thickness) {
+ if (lines_thickness == p_thickness) {
+ return;
+ }
lines_thickness = p_thickness;
update();
}
@@ -1730,6 +1742,9 @@ float GraphEdit::get_connection_lines_thickness() const {
}
void GraphEdit::set_connection_lines_antialiased(bool p_antialiased) {
+ if (lines_antialiased == p_antialiased) {
+ return;
+ }
lines_antialiased = p_antialiased;
update();
}
@@ -2381,7 +2396,7 @@ void GraphEdit::_bind_methods() {
ADD_SIGNAL(MethodInfo("begin_node_move"));
ADD_SIGNAL(MethodInfo("end_node_move"));
ADD_SIGNAL(MethodInfo("scroll_offset_changed", PropertyInfo(Variant::VECTOR2, "offset")));
- ADD_SIGNAL(MethodInfo("connection_drag_started", PropertyInfo(Variant::STRING, "from"), PropertyInfo(Variant::STRING, "slot"), PropertyInfo(Variant::BOOL, "is_output")));
+ ADD_SIGNAL(MethodInfo("connection_drag_started", PropertyInfo(Variant::STRING, "from"), PropertyInfo(Variant::INT, "slot"), PropertyInfo(Variant::BOOL, "is_output")));
ADD_SIGNAL(MethodInfo("connection_drag_ended"));
BIND_ENUM_CONSTANT(SCROLL_ZOOMS);
diff --git a/scene/gui/graph_edit.h b/scene/gui/graph_edit.h
index cf35aeb8b2..b8c9be9983 100644
--- a/scene/gui/graph_edit.h
+++ b/scene/gui/graph_edit.h
@@ -206,7 +206,7 @@ private:
void _minimap_draw();
void _update_scroll_offset();
- Array _get_connection_list() const;
+ TypedArray<Dictionary> _get_connection_list() const;
bool lines_on_bg = false;
diff --git a/scene/gui/graph_node.cpp b/scene/gui/graph_node.cpp
index 112b8c74af..7d31e929dc 100644
--- a/scene/gui/graph_node.cpp
+++ b/scene/gui/graph_node.cpp
@@ -32,9 +32,7 @@
#include "core/string/translation.h"
-#ifdef TOOLS_ENABLED
#include "graph_edit.h"
-#endif
struct _MinSizeCache {
int min_size;
@@ -445,17 +443,16 @@ void GraphNode::_edit_set_position(const Point2 &p_position) {
}
set_position(p_position);
}
+#endif
-void GraphNode::_validate_property(PropertyInfo &property) const {
- Control::_validate_property(property);
+void GraphNode::_validate_property(PropertyInfo &p_property) const {
GraphEdit *graph = Object::cast_to<GraphEdit>(get_parent());
if (graph) {
- if (property.name == "position") {
- property.usage |= PROPERTY_USAGE_READ_ONLY;
+ if (p_property.name == "position") {
+ p_property.usage |= PROPERTY_USAGE_READ_ONLY;
}
}
}
-#endif
void GraphNode::set_slot(int p_idx, bool p_enable_left, int p_type_left, const Color &p_color_left, bool p_enable_right, int p_type_right, const Color &p_color_right, const Ref<Texture2D> &p_custom_left, const Ref<Texture2D> &p_custom_right, bool p_draw_stylebox) {
ERR_FAIL_COND_MSG(p_idx < 0, vformat("Cannot set slot with p_idx (%d) lesser than zero.", p_idx));
@@ -506,6 +503,10 @@ bool GraphNode::is_slot_enabled_left(int p_idx) const {
void GraphNode::set_slot_enabled_left(int p_idx, bool p_enable_left) {
ERR_FAIL_COND_MSG(p_idx < 0, vformat("Cannot set enable_left for the slot with p_idx (%d) lesser than zero.", p_idx));
+ if (slot_info[p_idx].enable_left == p_enable_left) {
+ return;
+ }
+
slot_info[p_idx].enable_left = p_enable_left;
update();
connpos_dirty = true;
@@ -516,6 +517,10 @@ void GraphNode::set_slot_enabled_left(int p_idx, bool p_enable_left) {
void GraphNode::set_slot_type_left(int p_idx, int p_type_left) {
ERR_FAIL_COND_MSG(!slot_info.has(p_idx), vformat("Cannot set type_left for the slot '%d' because it hasn't been enabled.", p_idx));
+ if (slot_info[p_idx].type_left == p_type_left) {
+ return;
+ }
+
slot_info[p_idx].type_left = p_type_left;
update();
connpos_dirty = true;
@@ -533,6 +538,10 @@ int GraphNode::get_slot_type_left(int p_idx) const {
void GraphNode::set_slot_color_left(int p_idx, const Color &p_color_left) {
ERR_FAIL_COND_MSG(!slot_info.has(p_idx), vformat("Cannot set color_left for the slot '%d' because it hasn't been enabled.", p_idx));
+ if (slot_info[p_idx].color_left == p_color_left) {
+ return;
+ }
+
slot_info[p_idx].color_left = p_color_left;
update();
connpos_dirty = true;
@@ -557,6 +566,10 @@ bool GraphNode::is_slot_enabled_right(int p_idx) const {
void GraphNode::set_slot_enabled_right(int p_idx, bool p_enable_right) {
ERR_FAIL_COND_MSG(p_idx < 0, vformat("Cannot set enable_right for the slot with p_idx (%d) lesser than zero.", p_idx));
+ if (slot_info[p_idx].enable_right == p_enable_right) {
+ return;
+ }
+
slot_info[p_idx].enable_right = p_enable_right;
update();
connpos_dirty = true;
@@ -567,6 +580,10 @@ void GraphNode::set_slot_enabled_right(int p_idx, bool p_enable_right) {
void GraphNode::set_slot_type_right(int p_idx, int p_type_right) {
ERR_FAIL_COND_MSG(!slot_info.has(p_idx), vformat("Cannot set type_right for the slot '%d' because it hasn't been enabled.", p_idx));
+ if (slot_info[p_idx].type_right == p_type_right) {
+ return;
+ }
+
slot_info[p_idx].type_right = p_type_right;
update();
connpos_dirty = true;
@@ -584,6 +601,10 @@ int GraphNode::get_slot_type_right(int p_idx) const {
void GraphNode::set_slot_color_right(int p_idx, const Color &p_color_right) {
ERR_FAIL_COND_MSG(!slot_info.has(p_idx), vformat("Cannot set color_right for the slot '%d' because it hasn't been enabled.", p_idx));
+ if (slot_info[p_idx].color_right == p_color_right) {
+ return;
+ }
+
slot_info[p_idx].color_right = p_color_right;
update();
connpos_dirty = true;
@@ -701,6 +722,10 @@ String GraphNode::get_language() const {
}
void GraphNode::set_position_offset(const Vector2 &p_offset) {
+ if (position_offset == p_offset) {
+ return;
+ }
+
position_offset = p_offset;
emit_signal(SNAME("position_offset_changed"));
update();
@@ -711,6 +736,10 @@ Vector2 GraphNode::get_position_offset() const {
}
void GraphNode::set_selected(bool p_selected) {
+ if (selected == p_selected) {
+ return;
+ }
+
selected = p_selected;
update();
}
@@ -732,6 +761,10 @@ Vector2 GraphNode::get_drag_from() {
}
void GraphNode::set_show_close_button(bool p_enable) {
+ if (show_close == p_enable) {
+ return;
+ }
+
show_close = p_enable;
update();
}
@@ -932,6 +965,10 @@ void GraphNode::gui_input(const Ref<InputEvent> &p_ev) {
}
void GraphNode::set_overlay(Overlay p_overlay) {
+ if (overlay == p_overlay) {
+ return;
+ }
+
overlay = p_overlay;
update();
}
@@ -941,6 +978,10 @@ GraphNode::Overlay GraphNode::get_overlay() const {
}
void GraphNode::set_comment(bool p_enable) {
+ if (comment == p_enable) {
+ return;
+ }
+
comment = p_enable;
update();
}
@@ -950,6 +991,10 @@ bool GraphNode::is_comment() const {
}
void GraphNode::set_resizable(bool p_enable) {
+ if (resizable == p_enable) {
+ return;
+ }
+
resizable = p_enable;
update();
}
diff --git a/scene/gui/graph_node.h b/scene/gui/graph_node.h
index 0651eb5cc9..d575b6ceed 100644
--- a/scene/gui/graph_node.h
+++ b/scene/gui/graph_node.h
@@ -101,7 +101,6 @@ private:
#ifdef TOOLS_ENABLED
void _edit_set_position(const Point2 &p_position) override;
- void _validate_property(PropertyInfo &property) const override;
#endif
protected:
@@ -112,6 +111,7 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
+ void _validate_property(PropertyInfo &p_property) const;
public:
bool has_point(const Point2 &p_point) const override;
diff --git a/scene/gui/grid_container.cpp b/scene/gui/grid_container.cpp
index eaa6943ad2..3163d17846 100644
--- a/scene/gui/grid_container.cpp
+++ b/scene/gui/grid_container.cpp
@@ -246,6 +246,11 @@ void GridContainer::_notification(int p_what) {
void GridContainer::set_columns(int p_columns) {
ERR_FAIL_COND(p_columns < 1);
+
+ if (columns == p_columns) {
+ return;
+ }
+
columns = p_columns;
queue_sort();
update_minimum_size();
diff --git a/scene/gui/item_list.cpp b/scene/gui/item_list.cpp
index d0a25972f8..086f729603 100644
--- a/scene/gui/item_list.cpp
+++ b/scene/gui/item_list.cpp
@@ -88,6 +88,10 @@ void ItemList::set_item_text(int p_idx, const String &p_text) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].text == p_text) {
+ return;
+ }
+
items.write[p_idx].text = p_text;
_shape(p_idx);
update();
@@ -153,6 +157,10 @@ void ItemList::set_item_tooltip(int p_idx, const String &p_tooltip) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].tooltip == p_tooltip) {
+ return;
+ }
+
items.write[p_idx].tooltip = p_tooltip;
update();
shape_changed = true;
@@ -169,6 +177,10 @@ void ItemList::set_item_icon(int p_idx, const Ref<Texture2D> &p_icon) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].icon == p_icon) {
+ return;
+ }
+
items.write[p_idx].icon = p_icon;
update();
shape_changed = true;
@@ -186,6 +198,10 @@ void ItemList::set_item_icon_transposed(int p_idx, const bool p_transposed) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].icon_transposed == p_transposed) {
+ return;
+ }
+
items.write[p_idx].icon_transposed = p_transposed;
update();
shape_changed = true;
@@ -203,6 +219,10 @@ void ItemList::set_item_icon_region(int p_idx, const Rect2 &p_region) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].icon_region == p_region) {
+ return;
+ }
+
items.write[p_idx].icon_region = p_region;
update();
shape_changed = true;
@@ -220,6 +240,10 @@ void ItemList::set_item_icon_modulate(int p_idx, const Color &p_modulate) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].icon_modulate == p_modulate) {
+ return;
+ }
+
items.write[p_idx].icon_modulate = p_modulate;
update();
}
@@ -236,6 +260,10 @@ void ItemList::set_item_custom_bg_color(int p_idx, const Color &p_custom_bg_colo
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].custom_bg == p_custom_bg_color) {
+ return;
+ }
+
items.write[p_idx].custom_bg = p_custom_bg_color;
update();
}
@@ -252,6 +280,10 @@ void ItemList::set_item_custom_fg_color(int p_idx, const Color &p_custom_fg_colo
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].custom_fg == p_custom_fg_color) {
+ return;
+ }
+
items.write[p_idx].custom_fg = p_custom_fg_color;
update();
}
@@ -268,6 +300,10 @@ void ItemList::set_item_tag_icon(int p_idx, const Ref<Texture2D> &p_tag_icon) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].tag_icon == p_tag_icon) {
+ return;
+ }
+
items.write[p_idx].tag_icon = p_tag_icon;
update();
shape_changed = true;
@@ -299,6 +335,10 @@ void ItemList::set_item_disabled(int p_idx, bool p_disabled) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].disabled == p_disabled) {
+ return;
+ }
+
items.write[p_idx].disabled = p_disabled;
update();
}
@@ -314,6 +354,10 @@ void ItemList::set_item_metadata(int p_idx, const Variant &p_metadata) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].metadata == p_metadata) {
+ return;
+ }
+
items.write[p_idx].metadata = p_metadata;
update();
shape_changed = true;
@@ -379,6 +423,10 @@ bool ItemList::is_selected(int p_idx) const {
void ItemList::set_current(int p_current) {
ERR_FAIL_INDEX(p_current, items.size());
+ if (current == p_current) {
+ return;
+ }
+
if (select_mode == SELECT_SINGLE) {
select(p_current, true);
} else {
@@ -410,6 +458,11 @@ void ItemList::move_item(int p_from_idx, int p_to_idx) {
void ItemList::set_item_count(int p_count) {
ERR_FAIL_COND(p_count < 0);
+
+ if (items.size() == p_count) {
+ return;
+ }
+
items.resize(p_count);
update();
shape_changed = true;
@@ -445,6 +498,11 @@ void ItemList::clear() {
void ItemList::set_fixed_column_width(int p_size) {
ERR_FAIL_COND(p_size < 0);
+
+ if (fixed_column_width == p_size) {
+ return;
+ }
+
fixed_column_width = p_size;
update();
shape_changed = true;
@@ -455,6 +513,10 @@ int ItemList::get_fixed_column_width() const {
}
void ItemList::set_same_column_width(bool p_enable) {
+ if (same_column_width == p_enable) {
+ return;
+ }
+
same_column_width = p_enable;
update();
shape_changed = true;
@@ -487,6 +549,11 @@ int ItemList::get_max_text_lines() const {
void ItemList::set_max_columns(int p_amount) {
ERR_FAIL_COND(p_amount < 0);
+
+ if (max_columns == p_amount) {
+ return;
+ }
+
max_columns = p_amount;
update();
shape_changed = true;
@@ -497,6 +564,10 @@ int ItemList::get_max_columns() const {
}
void ItemList::set_select_mode(SelectMode p_mode) {
+ if (select_mode == p_mode) {
+ return;
+ }
+
select_mode = p_mode;
update();
}
@@ -526,6 +597,10 @@ ItemList::IconMode ItemList::get_icon_mode() const {
}
void ItemList::set_fixed_icon_size(const Size2 &p_size) {
+ if (fixed_icon_size == p_size) {
+ return;
+ }
+
fixed_icon_size = p_size;
update();
}
@@ -932,11 +1007,7 @@ void ItemList::_notification(int p_what) {
scroll_bar->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -bg->get_margin(SIDE_BOTTOM));
Size2 size = get_size();
-
int width = size.width - bg->get_minimum_size().width;
- if (scroll_bar->is_visible()) {
- width -= mw;
- }
draw_style_box(bg, Rect2(Point2(), size));
@@ -1095,6 +1166,10 @@ void ItemList::_notification(int p_what) {
shape_changed = false;
}
+ if (scroll_bar->is_visible()) {
+ width -= mw;
+ }
+
//ensure_selected_visible needs to be checked before we draw the list.
if (ensure_selected_visible && current >= 0 && current < items.size()) {
Rect2 r = items[current].rect_cache;
@@ -1512,6 +1587,10 @@ void ItemList::set_autoscroll_to_bottom(const bool p_enable) {
}
void ItemList::set_auto_height(bool p_enable) {
+ if (auto_height == p_enable) {
+ return;
+ }
+
auto_height = p_enable;
shape_changed = true;
update();
diff --git a/scene/gui/label.cpp b/scene/gui/label.cpp
index e7f48beb00..7a88afaa3b 100644
--- a/scene/gui/label.cpp
+++ b/scene/gui/label.cpp
@@ -38,10 +38,12 @@
#include "servers/text_server.h"
void Label::set_autowrap_mode(TextServer::AutowrapMode p_mode) {
- if (autowrap_mode != p_mode) {
- autowrap_mode = p_mode;
- lines_dirty = true;
+ if (autowrap_mode == p_mode) {
+ return;
}
+
+ autowrap_mode = p_mode;
+ lines_dirty = true;
update();
if (clip || overrun_behavior != TextServer::OVERRUN_NO_TRIMMING) {
@@ -54,6 +56,10 @@ TextServer::AutowrapMode Label::get_autowrap_mode() const {
}
void Label::set_uppercase(bool p_uppercase) {
+ if (uppercase == p_uppercase) {
+ return;
+ }
+
uppercase = p_uppercase;
dirty = true;
@@ -608,12 +614,15 @@ int Label::get_visible_line_count() const {
void Label::set_horizontal_alignment(HorizontalAlignment p_alignment) {
ERR_FAIL_INDEX((int)p_alignment, 4);
- if (horizontal_alignment != p_alignment) {
- if (horizontal_alignment == HORIZONTAL_ALIGNMENT_FILL || p_alignment == HORIZONTAL_ALIGNMENT_FILL) {
- lines_dirty = true; // Reshape lines.
- }
- horizontal_alignment = p_alignment;
+ if (horizontal_alignment == p_alignment) {
+ return;
}
+
+ if (horizontal_alignment == HORIZONTAL_ALIGNMENT_FILL || p_alignment == HORIZONTAL_ALIGNMENT_FILL) {
+ lines_dirty = true; // Reshape lines.
+ }
+ horizontal_alignment = p_alignment;
+
update();
}
@@ -623,6 +632,11 @@ HorizontalAlignment Label::get_horizontal_alignment() const {
void Label::set_vertical_alignment(VerticalAlignment p_alignment) {
ERR_FAIL_INDEX((int)p_alignment, 4);
+
+ if (vertical_alignment == p_alignment) {
+ return;
+ }
+
vertical_alignment = p_alignment;
update();
}
@@ -689,6 +703,10 @@ TextServer::StructuredTextParser Label::get_structured_text_bidi_override() cons
}
void Label::set_structured_text_bidi_override_options(Array p_args) {
+ if (st_args == p_args) {
+ return;
+ }
+
st_args = p_args;
dirty = true;
update();
@@ -715,6 +733,10 @@ String Label::get_language() const {
}
void Label::set_clip_text(bool p_clip) {
+ if (clip == p_clip) {
+ return;
+ }
+
clip = p_clip;
update();
update_minimum_size();
@@ -725,10 +747,12 @@ bool Label::is_clipping_text() const {
}
void Label::set_text_overrun_behavior(TextServer::OverrunBehavior p_behavior) {
- if (overrun_behavior != p_behavior) {
- overrun_behavior = p_behavior;
- lines_dirty = true;
+ if (overrun_behavior == p_behavior) {
+ return;
}
+
+ overrun_behavior = p_behavior;
+ lines_dirty = true;
update();
if (clip || overrun_behavior != TextServer::OVERRUN_NO_TRIMMING) {
update_minimum_size();
@@ -764,13 +788,17 @@ int Label::get_visible_characters() const {
void Label::set_percent_visible(float p_percent) {
if (percent_visible != p_percent) {
- if (p_percent < 0 || p_percent >= 1) {
+ if (percent_visible >= 1.0) {
visible_chars = -1;
- percent_visible = 1;
+ percent_visible = 1.0;
+ } else if (percent_visible < 0.0) {
+ visible_chars = 0;
+ percent_visible = 0.0;
} else {
visible_chars = get_total_character_count() * p_percent;
percent_visible = p_percent;
}
+
if (visible_chars_behavior == TextServer::VC_CHARS_BEFORE_SHAPING) {
dirty = true;
}
@@ -796,6 +824,11 @@ void Label::set_visible_characters_behavior(TextServer::VisibleCharactersBehavio
void Label::set_lines_skipped(int p_lines) {
ERR_FAIL_COND(p_lines < 0);
+
+ if (lines_skipped == p_lines) {
+ return;
+ }
+
lines_skipped = p_lines;
_update_visible();
update();
@@ -806,6 +839,10 @@ int Label::get_lines_skipped() const {
}
void Label::set_max_lines_visible(int p_lines) {
+ if (max_lines_visible == p_lines) {
+ return;
+ }
+
max_lines_visible = p_lines;
_update_visible();
update();
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index f315b2bbf1..cc39b0e57a 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -607,10 +607,12 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
void LineEdit::set_horizontal_alignment(HorizontalAlignment p_alignment) {
ERR_FAIL_INDEX((int)p_alignment, 4);
- if (alignment != p_alignment) {
- alignment = p_alignment;
- _shape();
+ if (alignment == p_alignment) {
+ return;
}
+
+ alignment = p_alignment;
+ _shape();
update();
}
@@ -1525,6 +1527,10 @@ String LineEdit::get_text() const {
}
void LineEdit::set_placeholder(String p_text) {
+ if (placeholder == p_text) {
+ return;
+ }
+
placeholder = p_text;
placeholder_translated = atr(placeholder);
_shape();
@@ -1781,10 +1787,12 @@ bool LineEdit::is_editable() const {
}
void LineEdit::set_secret(bool p_secret) {
- if (pass != p_secret) {
- pass = p_secret;
- _shape();
+ if (pass == p_secret) {
+ return;
}
+
+ pass = p_secret;
+ _shape();
update();
}
@@ -1797,10 +1805,12 @@ void LineEdit::set_secret_character(const String &p_string) {
// It also wouldn't make sense to use multiple characters as the secret character.
ERR_FAIL_COND_MSG(p_string.length() != 1, "Secret character must be exactly one character long (" + itos(p_string.length()) + " characters given).");
- if (secret_character != p_string) {
- secret_character = p_string;
- _shape();
+ if (secret_character == p_string) {
+ return;
}
+
+ secret_character = p_string;
+ _shape();
update();
}
@@ -2057,6 +2067,10 @@ bool LineEdit::is_middle_mouse_paste_enabled() const {
}
void LineEdit::set_selecting_enabled(bool p_enabled) {
+ if (selecting_enabled == p_enabled) {
+ return;
+ }
+
selecting_enabled = p_enabled;
if (!selecting_enabled) {
@@ -2069,6 +2083,10 @@ bool LineEdit::is_selecting_enabled() const {
}
void LineEdit::set_deselect_on_focus_loss_enabled(const bool p_enabled) {
+ if (deselect_on_focus_loss_enabled == p_enabled) {
+ return;
+ }
+
deselect_on_focus_loss_enabled = p_enabled;
if (p_enabled && selection.enabled && !has_focus()) {
deselect();
@@ -2224,9 +2242,9 @@ Key LineEdit::_get_menu_action_accelerator(const String &p_action) {
}
}
-void LineEdit::_validate_property(PropertyInfo &property) const {
- if (!caret_blink_enabled && property.name == "caret_blink_speed") {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void LineEdit::_validate_property(PropertyInfo &p_property) const {
+ if (!caret_blink_enabled && p_property.name == "caret_blink_speed") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h
index 4d5ebf441c..254f842b66 100644
--- a/scene/gui/line_edit.h
+++ b/scene/gui/line_edit.h
@@ -221,7 +221,7 @@ protected:
virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override;
virtual void gui_input(const Ref<InputEvent> &p_event) override;
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_horizontal_alignment(HorizontalAlignment p_alignment);
diff --git a/scene/gui/link_button.cpp b/scene/gui/link_button.cpp
index 30c0bb3321..ee3f64e0e5 100644
--- a/scene/gui/link_button.cpp
+++ b/scene/gui/link_button.cpp
@@ -109,6 +109,10 @@ String LinkButton::get_language() const {
}
void LinkButton::set_underline_mode(UnderlineMode p_underline_mode) {
+ if (underline_mode == p_underline_mode) {
+ return;
+ }
+
underline_mode = p_underline_mode;
update();
}
diff --git a/scene/gui/menu_bar.cpp b/scene/gui/menu_bar.cpp
new file mode 100644
index 0000000000..f450222130
--- /dev/null
+++ b/scene/gui/menu_bar.cpp
@@ -0,0 +1,868 @@
+/*************************************************************************/
+/* menu_bar.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 "menu_bar.h"
+
+#include "core/os/keyboard.h"
+#include "scene/main/window.h"
+
+void MenuBar::gui_input(const Ref<InputEvent> &p_event) {
+ ERR_FAIL_COND(p_event.is_null());
+ if (is_native_menu()) {
+ // Handled by OS.
+ return;
+ }
+
+ MutexLock lock(mutex);
+ if (p_event->is_action("ui_left") && p_event->is_pressed()) {
+ int new_sel = selected_menu;
+ int old_sel = (selected_menu < 0) ? 0 : selected_menu;
+ do {
+ new_sel--;
+ if (new_sel < 0) {
+ new_sel = menu_cache.size() - 1;
+ }
+ if (old_sel == new_sel) {
+ return;
+ }
+ } while (menu_cache[new_sel].hidden || menu_cache[new_sel].disabled);
+
+ if (selected_menu != new_sel) {
+ selected_menu = new_sel;
+ focused_menu = selected_menu;
+ if (active_menu >= 0) {
+ get_menu_popup(active_menu)->hide();
+ }
+ _open_popup(selected_menu);
+ }
+ return;
+ } else if (p_event->is_action("ui_right") && p_event->is_pressed()) {
+ int new_sel = selected_menu;
+ int old_sel = (selected_menu < 0) ? menu_cache.size() - 1 : selected_menu;
+ do {
+ new_sel++;
+ if (new_sel >= menu_cache.size()) {
+ new_sel = 0;
+ }
+ if (old_sel == new_sel) {
+ return;
+ }
+ } while (menu_cache[new_sel].hidden || menu_cache[new_sel].disabled);
+
+ if (selected_menu != new_sel) {
+ selected_menu = new_sel;
+ focused_menu = selected_menu;
+ if (active_menu >= 0) {
+ get_menu_popup(active_menu)->hide();
+ }
+ _open_popup(selected_menu);
+ }
+ return;
+ }
+
+ Ref<InputEventMouseMotion> mm = p_event;
+ if (mm.is_valid()) {
+ int old_sel = selected_menu;
+ focused_menu = _get_index_at_point(mm->get_position());
+ if (focused_menu >= 0) {
+ selected_menu = focused_menu;
+ }
+ if (selected_menu != old_sel) {
+ update();
+ }
+ }
+
+ Ref<InputEventMouseButton> mb = p_event;
+ if (mb.is_valid()) {
+ if (mb->is_pressed() && (mb->get_button_index() == MouseButton::LEFT || mb->get_button_index() == MouseButton::RIGHT)) {
+ int index = _get_index_at_point(mb->get_position());
+ if (index >= 0) {
+ _open_popup(index);
+ }
+ }
+ }
+}
+
+void MenuBar::_open_popup(int p_index) {
+ ERR_FAIL_INDEX(p_index, menu_cache.size());
+
+ PopupMenu *pm = get_menu_popup(p_index);
+ if (pm->is_visible()) {
+ pm->hide();
+ return;
+ }
+
+ Rect2 item_rect = _get_menu_item_rect(p_index);
+ Point2 screen_pos = get_screen_position() + item_rect.position * get_viewport()->get_canvas_transform().get_scale();
+ Size2 screen_size = item_rect.size * get_viewport()->get_canvas_transform().get_scale();
+
+ active_menu = p_index;
+
+ pm->set_size(Size2(screen_size.x, 0));
+ screen_pos.y += screen_size.y;
+ if (is_layout_rtl()) {
+ screen_pos.x += screen_size.x - pm->get_size().width;
+ }
+ pm->set_position(screen_pos);
+ pm->set_parent_rect(Rect2(Point2(screen_pos - pm->get_position()), Size2(screen_size.x, screen_pos.y)));
+ pm->popup();
+
+ update();
+}
+
+void MenuBar::shortcut_input(const Ref<InputEvent> &p_event) {
+ ERR_FAIL_COND(p_event.is_null());
+
+ if (is_native_menu()) {
+ return;
+ }
+
+ if (!_is_focus_owner_in_shortcut_context()) {
+ return;
+ }
+
+ if (disable_shortcuts) {
+ return;
+ }
+
+ if (p_event->is_pressed() && !p_event->is_echo() && (Object::cast_to<InputEventKey>(p_event.ptr()) || Object::cast_to<InputEventJoypadButton>(p_event.ptr()) || Object::cast_to<InputEventAction>(*p_event) || Object::cast_to<InputEventShortcut>(*p_event))) {
+ if (!get_parent() || !is_visible_in_tree()) {
+ return;
+ }
+
+ Vector<PopupMenu *> popups = _get_popups();
+ for (int i = 0; i < popups.size(); i++) {
+ if (menu_cache[i].hidden || menu_cache[i].disabled) {
+ continue;
+ }
+ if (popups[i]->activate_item_by_event(p_event, false)) {
+ accept_event();
+ return;
+ }
+ }
+ }
+}
+
+void MenuBar::set_shortcut_context(Node *p_node) {
+ if (p_node != nullptr) {
+ shortcut_context = p_node->get_instance_id();
+ } else {
+ shortcut_context = ObjectID();
+ }
+}
+
+Node *MenuBar::get_shortcut_context() const {
+ Object *ctx_obj = ObjectDB::get_instance(shortcut_context);
+ Node *ctx_node = Object::cast_to<Node>(ctx_obj);
+
+ return ctx_node;
+}
+
+bool MenuBar::_is_focus_owner_in_shortcut_context() const {
+ if (shortcut_context == ObjectID()) {
+ // No context, therefore global - always "in" context.
+ return true;
+ }
+
+ Node *ctx_node = get_shortcut_context();
+ Control *vp_focus = get_viewport() ? get_viewport()->gui_get_focus_owner() : nullptr;
+
+ // If the context is valid and the viewport focus is valid, check if the context is the focus or is a parent of it.
+ return ctx_node && vp_focus && (ctx_node == vp_focus || ctx_node->is_ancestor_of(vp_focus));
+}
+
+void MenuBar::_popup_visibility_changed(bool p_visible) {
+ if (!p_visible) {
+ active_menu = -1;
+ focused_menu = -1;
+ set_process_internal(false);
+ update();
+ return;
+ }
+
+ if (switch_on_hover) {
+ Window *window = Object::cast_to<Window>(get_viewport());
+ if (window) {
+ mouse_pos_adjusted = window->get_position();
+
+ if (window->is_embedded()) {
+ Window *window_parent = Object::cast_to<Window>(window->get_parent()->get_viewport());
+ while (window_parent) {
+ if (!window_parent->is_embedded()) {
+ mouse_pos_adjusted += window_parent->get_position();
+ break;
+ }
+
+ window_parent = Object::cast_to<Window>(window_parent->get_parent()->get_viewport());
+ }
+ }
+
+ set_process_internal(true);
+ }
+ }
+}
+
+void MenuBar::_update_submenu(const String &p_menu_name, PopupMenu *p_child) {
+ int count = p_child->get_item_count();
+ global_menus.insert(p_menu_name);
+ for (int i = 0; i < count; i++) {
+ if (p_child->is_item_separator(i)) {
+ DisplayServer::get_singleton()->global_menu_add_separator(p_menu_name);
+ } else if (!p_child->get_item_submenu(i).is_empty()) {
+ Node *n = p_child->get_node(p_child->get_item_submenu(i));
+ ERR_FAIL_COND_MSG(!n, "Item subnode does not exist: " + p_child->get_item_submenu(i) + ".");
+ PopupMenu *pm = Object::cast_to<PopupMenu>(n);
+ ERR_FAIL_COND_MSG(!pm, "Item subnode is not a PopupMenu: " + p_child->get_item_submenu(i) + ".");
+
+ DisplayServer::get_singleton()->global_menu_add_submenu_item(p_menu_name, p_child->get_item_text(i), p_menu_name + "/" + itos(i));
+ _update_submenu(p_menu_name + "/" + itos(i), pm);
+ } else {
+ int index = DisplayServer::get_singleton()->global_menu_add_item(p_menu_name, p_child->get_item_text(i), callable_mp(p_child, &PopupMenu::activate_item), i);
+
+ if (p_child->is_item_checkable(i)) {
+ DisplayServer::get_singleton()->global_menu_set_item_checkable(p_menu_name, index, true);
+ }
+ if (p_child->is_item_radio_checkable(i)) {
+ DisplayServer::get_singleton()->global_menu_set_item_radio_checkable(p_menu_name, index, true);
+ }
+ DisplayServer::get_singleton()->global_menu_set_item_checked(p_menu_name, index, p_child->is_item_checked(i));
+ DisplayServer::get_singleton()->global_menu_set_item_disabled(p_menu_name, index, p_child->is_item_disabled(i));
+ DisplayServer::get_singleton()->global_menu_set_item_max_states(p_menu_name, index, p_child->get_item_max_states(i));
+ DisplayServer::get_singleton()->global_menu_set_item_icon(p_menu_name, index, p_child->get_item_icon(i));
+ DisplayServer::get_singleton()->global_menu_set_item_state(p_menu_name, index, p_child->get_item_state(i));
+ DisplayServer::get_singleton()->global_menu_set_item_indentation_level(p_menu_name, index, p_child->get_item_indent(i));
+ DisplayServer::get_singleton()->global_menu_set_item_tooltip(p_menu_name, index, p_child->get_item_tooltip(i));
+ if (!p_child->is_item_shortcut_disabled(i) && p_child->get_item_shortcut(i).is_valid() && p_child->get_item_shortcut(i)->has_valid_event()) {
+ Array events = p_child->get_item_shortcut(i)->get_events();
+ for (int j = 0; j < events.size(); j++) {
+ Ref<InputEventKey> ie = events[j];
+ if (ie.is_valid()) {
+ DisplayServer::get_singleton()->global_menu_set_item_accelerator(p_menu_name, index, ie->get_keycode_with_modifiers());
+ break;
+ }
+ }
+ } else if (p_child->get_item_accelerator(i) != Key::NONE) {
+ DisplayServer::get_singleton()->global_menu_set_item_accelerator(p_menu_name, i, p_child->get_item_accelerator(i));
+ }
+ }
+ }
+}
+
+bool MenuBar::is_native_menu() const {
+ if (!is_visible_in_tree()) {
+ return false;
+ }
+ if (Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this)) {
+ return false;
+ }
+
+ return (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU) && is_native);
+}
+
+void MenuBar::_clear_menu() {
+ if (!DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) {
+ return;
+ }
+
+ // Remove root menu items.
+ int count = DisplayServer::get_singleton()->global_menu_get_item_count("_main");
+ for (int i = count - 1; i >= 0; i--) {
+ if (global_menus.has(DisplayServer::get_singleton()->global_menu_get_item_submenu("_main", i))) {
+ DisplayServer::get_singleton()->global_menu_remove_item("_main", i);
+ }
+ }
+ // Erase submenu contents.
+ for (const String &E : global_menus) {
+ DisplayServer::get_singleton()->global_menu_clear(E);
+ }
+ global_menus.clear();
+}
+
+void MenuBar::_update_menu() {
+ _clear_menu();
+
+ if (!is_inside_tree()) {
+ return;
+ }
+
+ int index = start_index;
+ if (is_native_menu()) {
+ Vector<PopupMenu *> popups = _get_popups();
+ String root_name = "MenuBar<" + String::num_int64((uint64_t)this, 16) + ">";
+ for (int i = 0; i < popups.size(); i++) {
+ if (menu_cache[i].hidden) {
+ continue;
+ }
+ String menu_name = String(popups[i]->get_meta("_menu_name", popups[i]->get_name()));
+
+ index = DisplayServer::get_singleton()->global_menu_add_submenu_item("_main", menu_name, root_name + "/" + itos(i), index);
+ if (menu_cache[i].disabled) {
+ DisplayServer::get_singleton()->global_menu_set_item_disabled("_main", index, true);
+ }
+ _update_submenu(root_name + "/" + itos(i), popups[i]);
+ index++;
+ }
+ }
+ update_minimum_size();
+ update();
+}
+
+void MenuBar::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ if (get_menu_count() > 0) {
+ _refresh_menu_names();
+ }
+ } break;
+ case NOTIFICATION_EXIT_TREE: {
+ _clear_menu();
+ } break;
+ case NOTIFICATION_MOUSE_EXIT: {
+ focused_menu = -1;
+ update();
+ } break;
+ case NOTIFICATION_TRANSLATION_CHANGED:
+ case NOTIFICATION_LAYOUT_DIRECTION_CHANGED:
+ case NOTIFICATION_THEME_CHANGED: {
+ for (int i = 0; i < menu_cache.size(); i++) {
+ shape(menu_cache.write[i]);
+ }
+ _update_menu();
+ } break;
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ _update_menu();
+ } break;
+ case NOTIFICATION_DRAW: {
+ if (is_native_menu()) {
+ return;
+ }
+ for (int i = 0; i < menu_cache.size(); i++) {
+ _draw_menu_item(i);
+ }
+ } break;
+ case NOTIFICATION_INTERNAL_PROCESS: {
+ MutexLock lock(mutex);
+
+ Vector2 pos = DisplayServer::get_singleton()->mouse_get_position() - mouse_pos_adjusted - get_global_position();
+ int index = _get_index_at_point(pos);
+ if (index >= 0 && index != active_menu) {
+ selected_menu = index;
+ focused_menu = selected_menu;
+ get_menu_popup(active_menu)->hide();
+ _open_popup(index);
+ }
+ } break;
+ }
+}
+
+int MenuBar::_get_index_at_point(const Point2 &p_point) const {
+ Ref<StyleBox> style = get_theme_stylebox(SNAME("normal"));
+ int hsep = get_theme_constant(SNAME("h_separation"));
+ int offset = 0;
+ for (int i = 0; i < menu_cache.size(); i++) {
+ if (menu_cache[i].hidden) {
+ continue;
+ }
+ Size2 size = menu_cache[i].text_buf->get_size() + style->get_minimum_size();
+ if (p_point.x > offset && p_point.x < offset + size.x) {
+ if (p_point.y > 0 && p_point.y < size.y) {
+ return i;
+ }
+ }
+ offset += size.x + hsep;
+ }
+ return -1;
+}
+
+Rect2 MenuBar::_get_menu_item_rect(int p_index) const {
+ ERR_FAIL_INDEX_V(p_index, menu_cache.size(), Rect2());
+
+ Ref<StyleBox> style = get_theme_stylebox(SNAME("normal"));
+ int hsep = get_theme_constant(SNAME("h_separation"));
+
+ int offset = 0;
+ for (int i = 0; i < p_index; i++) {
+ if (menu_cache[i].hidden) {
+ continue;
+ }
+ Size2 size = menu_cache[i].text_buf->get_size() + style->get_minimum_size();
+ offset += size.x + hsep;
+ }
+
+ return Rect2(Point2(offset, 0), menu_cache[p_index].text_buf->get_size() + style->get_minimum_size());
+}
+
+void MenuBar::_draw_menu_item(int p_index) {
+ ERR_FAIL_INDEX(p_index, menu_cache.size());
+
+ RID ci = get_canvas_item();
+ bool hovered = (focused_menu == p_index);
+ bool pressed = (active_menu == p_index);
+ bool rtl = is_layout_rtl();
+
+ if (menu_cache[p_index].hidden) {
+ return;
+ }
+
+ Color color;
+ Ref<StyleBox> style = get_theme_stylebox(SNAME("normal"));
+ Rect2 item_rect = _get_menu_item_rect(p_index);
+
+ if (menu_cache[p_index].disabled) {
+ if (rtl && has_theme_stylebox(SNAME("disabled_mirrored"))) {
+ style = get_theme_stylebox(SNAME("disabled_mirrored"));
+ } else {
+ style = get_theme_stylebox(SNAME("disabled"));
+ }
+ if (!flat) {
+ style->draw(ci, item_rect);
+ }
+ color = get_theme_color(SNAME("font_disabled_color"));
+ } else if (hovered && pressed && has_theme_stylebox("hover_pressed")) {
+ if (rtl && has_theme_stylebox(SNAME("hover_pressed_mirrored"))) {
+ style = get_theme_stylebox(SNAME("hover_pressed_mirrored"));
+ } else {
+ style = get_theme_stylebox(SNAME("hover_pressed"));
+ }
+ if (!flat) {
+ style->draw(ci, item_rect);
+ }
+ if (has_theme_color(SNAME("font_hover_pressed_color"))) {
+ color = get_theme_color(SNAME("font_hover_pressed_color"));
+ }
+ } else if (pressed) {
+ if (rtl && has_theme_stylebox(SNAME("pressed_mirrored"))) {
+ style = get_theme_stylebox(SNAME("pressed_mirrored"));
+ } else {
+ style = get_theme_stylebox(SNAME("pressed"));
+ }
+ if (!flat) {
+ style->draw(ci, item_rect);
+ }
+ if (has_theme_color(SNAME("font_pressed_color"))) {
+ color = get_theme_color(SNAME("font_pressed_color"));
+ } else {
+ color = get_theme_color(SNAME("font_color"));
+ }
+ } else if (hovered) {
+ if (rtl && has_theme_stylebox(SNAME("hover_mirrored"))) {
+ style = get_theme_stylebox(SNAME("hover_mirrored"));
+ } else {
+ style = get_theme_stylebox(SNAME("hover"));
+ }
+ if (!flat) {
+ style->draw(ci, item_rect);
+ }
+ color = get_theme_color(SNAME("font_hover_color"));
+ } else {
+ if (rtl && has_theme_stylebox(SNAME("normal_mirrored"))) {
+ style = get_theme_stylebox(SNAME("normal_mirrored"));
+ } else {
+ style = get_theme_stylebox(SNAME("normal"));
+ }
+ if (!flat) {
+ style->draw(ci, item_rect);
+ }
+ // Focus colors only take precedence over normal state.
+ if (has_focus()) {
+ color = get_theme_color(SNAME("font_focus_color"));
+ } else {
+ color = get_theme_color(SNAME("font_color"));
+ }
+ }
+
+ Point2 text_ofs = item_rect.position + Point2(style->get_margin(SIDE_LEFT), style->get_margin(SIDE_TOP));
+
+ Color font_outline_color = get_theme_color(SNAME("font_outline_color"));
+ int outline_size = get_theme_constant(SNAME("outline_size"));
+ if (outline_size > 0 && font_outline_color.a > 0) {
+ menu_cache[p_index].text_buf->draw_outline(ci, text_ofs, outline_size, font_outline_color);
+ }
+ menu_cache[p_index].text_buf->draw(ci, text_ofs, color);
+}
+
+void MenuBar::shape(Menu &p_menu) {
+ Ref<Font> font = get_theme_font(SNAME("font"));
+ int font_size = get_theme_font_size(SNAME("font_size"));
+
+ p_menu.text_buf->clear();
+ if (text_direction == Control::TEXT_DIRECTION_INHERITED) {
+ p_menu.text_buf->set_direction(is_layout_rtl() ? TextServer::DIRECTION_RTL : TextServer::DIRECTION_LTR);
+ } else {
+ p_menu.text_buf->set_direction((TextServer::Direction)text_direction);
+ }
+ p_menu.text_buf->add_string(p_menu.name, font, font_size, language);
+}
+
+void MenuBar::_refresh_menu_names() {
+ Vector<PopupMenu *> popups = _get_popups();
+ for (int i = 0; i < popups.size(); i++) {
+ if (!popups[i]->has_meta("_menu_name") && String(popups[i]->get_name()) != get_menu_title(i)) {
+ menu_cache.write[i].name = popups[i]->get_name();
+ shape(menu_cache.write[i]);
+ }
+ }
+ _update_menu();
+}
+
+Vector<PopupMenu *> MenuBar::_get_popups() const {
+ Vector<PopupMenu *> popups;
+ for (int i = 0; i < get_child_count(); i++) {
+ PopupMenu *pm = Object::cast_to<PopupMenu>(get_child(i));
+ if (!pm) {
+ continue;
+ }
+ popups.push_back(pm);
+ }
+ return popups;
+}
+
+int MenuBar::get_menu_idx_from_control(PopupMenu *p_child) const {
+ ERR_FAIL_NULL_V(p_child, -1);
+ ERR_FAIL_COND_V(p_child->get_parent() != this, -1);
+
+ Vector<PopupMenu *> popups = _get_popups();
+ for (int i = 0; i < popups.size(); i++) {
+ if (popups[i] == p_child) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+void MenuBar::add_child_notify(Node *p_child) {
+ Control::add_child_notify(p_child);
+
+ PopupMenu *pm = Object::cast_to<PopupMenu>(p_child);
+ if (!pm) {
+ return;
+ }
+ Menu menu = Menu(p_child->get_name());
+ shape(menu);
+
+ menu_cache.push_back(menu);
+ p_child->connect("renamed", callable_mp(this, &MenuBar::_refresh_menu_names));
+ p_child->connect("menu_changed", callable_mp(this, &MenuBar::_update_menu));
+ p_child->connect("about_to_popup", callable_mp(this, &MenuBar::_popup_visibility_changed).bind(true));
+ p_child->connect("popup_hide", callable_mp(this, &MenuBar::_popup_visibility_changed).bind(false));
+
+ _update_menu();
+}
+
+void MenuBar::move_child_notify(Node *p_child) {
+ Control::move_child_notify(p_child);
+
+ PopupMenu *pm = Object::cast_to<PopupMenu>(p_child);
+ if (!pm) {
+ return;
+ }
+
+ int old_idx = -1;
+ String menu_name = String(pm->get_meta("_menu_name", pm->get_name()));
+ // Find the previous menu index of the control.
+ for (int i = 0; i < get_menu_count(); i++) {
+ if (get_menu_title(i) == menu_name) {
+ old_idx = i;
+ break;
+ }
+ }
+ Menu menu = menu_cache[old_idx];
+ menu_cache.remove_at(old_idx);
+ menu_cache.insert(get_menu_idx_from_control(pm), menu);
+
+ _update_menu();
+}
+
+void MenuBar::remove_child_notify(Node *p_child) {
+ Control::remove_child_notify(p_child);
+
+ PopupMenu *pm = Object::cast_to<PopupMenu>(p_child);
+ if (!pm) {
+ return;
+ }
+
+ int idx = get_menu_idx_from_control(pm);
+
+ menu_cache.remove_at(idx);
+
+ p_child->remove_meta("_menu_name");
+ p_child->remove_meta("_menu_tooltip");
+
+ p_child->disconnect("renamed", callable_mp(this, &MenuBar::_refresh_menu_names));
+ p_child->disconnect("menu_changed", callable_mp(this, &MenuBar::_update_menu));
+ p_child->disconnect("about_to_popup", callable_mp(this, &MenuBar::_popup_visibility_changed));
+ p_child->disconnect("popup_hide", callable_mp(this, &MenuBar::_popup_visibility_changed));
+
+ _update_menu();
+}
+
+void MenuBar::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_switch_on_hover", "enable"), &MenuBar::set_switch_on_hover);
+ ClassDB::bind_method(D_METHOD("is_switch_on_hover"), &MenuBar::is_switch_on_hover);
+ ClassDB::bind_method(D_METHOD("set_disable_shortcuts", "disabled"), &MenuBar::set_disable_shortcuts);
+
+ ClassDB::bind_method(D_METHOD("set_prefer_global_menu", "enabled"), &MenuBar::set_prefer_global_menu);
+ ClassDB::bind_method(D_METHOD("is_prefer_global_menu"), &MenuBar::is_prefer_global_menu);
+ ClassDB::bind_method(D_METHOD("is_native_menu"), &MenuBar::is_native_menu);
+
+ ClassDB::bind_method(D_METHOD("get_menu_count"), &MenuBar::get_menu_count);
+
+ ClassDB::bind_method(D_METHOD("set_text_direction", "direction"), &MenuBar::set_text_direction);
+ ClassDB::bind_method(D_METHOD("get_text_direction"), &MenuBar::get_text_direction);
+ ClassDB::bind_method(D_METHOD("set_language", "language"), &MenuBar::set_language);
+ ClassDB::bind_method(D_METHOD("get_language"), &MenuBar::get_language);
+ ClassDB::bind_method(D_METHOD("set_flat", "enabled"), &MenuBar::set_flat);
+ ClassDB::bind_method(D_METHOD("is_flat"), &MenuBar::is_flat);
+ ClassDB::bind_method(D_METHOD("set_start_index", "enabled"), &MenuBar::set_start_index);
+ ClassDB::bind_method(D_METHOD("get_start_index"), &MenuBar::get_start_index);
+
+ ClassDB::bind_method(D_METHOD("set_menu_title", "menu", "title"), &MenuBar::set_menu_title);
+ ClassDB::bind_method(D_METHOD("get_menu_title", "menu"), &MenuBar::get_menu_title);
+
+ ClassDB::bind_method(D_METHOD("set_menu_tooltip", "menu", "tooltip"), &MenuBar::set_menu_tooltip);
+ ClassDB::bind_method(D_METHOD("get_menu_tooltip", "menu"), &MenuBar::get_menu_tooltip);
+
+ ClassDB::bind_method(D_METHOD("set_menu_disabled", "menu", "disabled"), &MenuBar::set_menu_disabled);
+ ClassDB::bind_method(D_METHOD("is_menu_disabled", "menu"), &MenuBar::is_menu_disabled);
+
+ ClassDB::bind_method(D_METHOD("set_menu_hidden", "menu", "hidden"), &MenuBar::set_menu_hidden);
+ ClassDB::bind_method(D_METHOD("is_menu_hidden", "menu"), &MenuBar::is_menu_hidden);
+
+ ClassDB::bind_method(D_METHOD("set_shortcut_context", "node"), &MenuBar::set_shortcut_context);
+ ClassDB::bind_method(D_METHOD("get_shortcut_context"), &MenuBar::get_shortcut_context);
+
+ ClassDB::bind_method(D_METHOD("get_menu_popup", "menu"), &MenuBar::get_menu_popup);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "start_index"), "set_start_index", "get_start_index");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "switch_on_hover"), "set_switch_on_hover", "is_switch_on_hover");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "prefer_global_menu"), "set_prefer_global_menu", "is_prefer_global_menu");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut_context", PROPERTY_HINT_RESOURCE_TYPE, "Node"), "set_shortcut_context", "get_shortcut_context");
+
+ ADD_GROUP("BiDi", "");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "text_direction", PROPERTY_HINT_ENUM, "Auto,Left-to-Right,Right-to-Left,Inherited"), "set_text_direction", "get_text_direction");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "language", PROPERTY_HINT_LOCALE_ID, ""), "set_language", "get_language");
+}
+
+void MenuBar::set_switch_on_hover(bool p_enabled) {
+ switch_on_hover = p_enabled;
+}
+
+bool MenuBar::is_switch_on_hover() {
+ return switch_on_hover;
+}
+
+void MenuBar::set_disable_shortcuts(bool p_disabled) {
+ disable_shortcuts = p_disabled;
+}
+
+void MenuBar::set_text_direction(Control::TextDirection p_text_direction) {
+ ERR_FAIL_COND((int)p_text_direction < -1 || (int)p_text_direction > 3);
+ if (text_direction != p_text_direction) {
+ text_direction = p_text_direction;
+ _update_menu();
+ }
+}
+
+Control::TextDirection MenuBar::get_text_direction() const {
+ return text_direction;
+}
+
+void MenuBar::set_language(const String &p_language) {
+ if (language != p_language) {
+ language = p_language;
+ _update_menu();
+ }
+}
+
+String MenuBar::get_language() const {
+ return language;
+}
+
+void MenuBar::set_flat(bool p_enabled) {
+ if (flat != p_enabled) {
+ flat = p_enabled;
+ update();
+ }
+}
+
+bool MenuBar::is_flat() const {
+ return flat;
+}
+
+void MenuBar::set_start_index(int p_index) {
+ if (start_index != p_index) {
+ start_index = p_index;
+ _update_menu();
+ }
+}
+
+int MenuBar::get_start_index() const {
+ return start_index;
+}
+
+void MenuBar::set_prefer_global_menu(bool p_enabled) {
+ if (is_native != p_enabled) {
+ if (is_native) {
+ _clear_menu();
+ }
+ is_native = p_enabled;
+ _update_menu();
+ }
+}
+
+bool MenuBar::is_prefer_global_menu() const {
+ return is_native;
+}
+
+Size2 MenuBar::get_minimum_size() const {
+ if (is_native_menu()) {
+ return Size2();
+ }
+
+ Ref<StyleBox> style = get_theme_stylebox(SNAME("normal"));
+
+ Vector2 size;
+ for (int i = 0; i < menu_cache.size(); i++) {
+ if (menu_cache[i].hidden) {
+ continue;
+ }
+ Size2 sz = menu_cache[i].text_buf->get_size() + style->get_minimum_size();
+ size.y = MAX(size.y, sz.y);
+ size.x += sz.x;
+ }
+ if (menu_cache.size() > 1) {
+ size.x += get_theme_constant(SNAME("h_separation")) * (menu_cache.size() - 1);
+ }
+ return size;
+}
+
+int MenuBar::get_menu_count() const {
+ return menu_cache.size();
+}
+
+void MenuBar::set_menu_title(int p_menu, const String &p_title) {
+ ERR_FAIL_INDEX(p_menu, menu_cache.size());
+ PopupMenu *pm = get_menu_popup(p_menu);
+ if (p_title == pm->get_name()) {
+ pm->remove_meta("_menu_name");
+ } else {
+ pm->set_meta("_menu_name", p_title);
+ }
+ menu_cache.write[p_menu].name = p_title;
+ shape(menu_cache.write[p_menu]);
+ _update_menu();
+}
+
+String MenuBar::get_menu_title(int p_menu) const {
+ ERR_FAIL_INDEX_V(p_menu, menu_cache.size(), String());
+ return menu_cache[p_menu].name;
+}
+
+void MenuBar::set_menu_tooltip(int p_menu, const String &p_tooltip) {
+ ERR_FAIL_INDEX(p_menu, menu_cache.size());
+ PopupMenu *pm = get_menu_popup(p_menu);
+ pm->set_meta("_menu_tooltip", p_tooltip);
+ menu_cache.write[p_menu].name = p_tooltip;
+}
+
+String MenuBar::get_menu_tooltip(int p_menu) const {
+ ERR_FAIL_INDEX_V(p_menu, menu_cache.size(), String());
+ return menu_cache[p_menu].tooltip;
+}
+
+void MenuBar::set_menu_disabled(int p_menu, bool p_disabled) {
+ ERR_FAIL_INDEX(p_menu, menu_cache.size());
+ menu_cache.write[p_menu].disabled = p_disabled;
+ _update_menu();
+}
+
+bool MenuBar::is_menu_disabled(int p_menu) const {
+ ERR_FAIL_INDEX_V(p_menu, menu_cache.size(), false);
+ return menu_cache[p_menu].disabled;
+}
+
+void MenuBar::set_menu_hidden(int p_menu, bool p_hidden) {
+ ERR_FAIL_INDEX(p_menu, menu_cache.size());
+ menu_cache.write[p_menu].hidden = p_hidden;
+ _update_menu();
+}
+
+bool MenuBar::is_menu_hidden(int p_menu) const {
+ ERR_FAIL_INDEX_V(p_menu, menu_cache.size(), false);
+ return menu_cache[p_menu].hidden;
+}
+
+PopupMenu *MenuBar::get_menu_popup(int p_idx) const {
+ Vector<PopupMenu *> controls = _get_popups();
+ if (p_idx >= 0 && p_idx < controls.size()) {
+ return controls[p_idx];
+ } else {
+ return nullptr;
+ }
+}
+
+String MenuBar::get_tooltip(const Point2 &p_pos) const {
+ int index = _get_index_at_point(p_pos);
+ if (index >= 0 && index < menu_cache.size()) {
+ return menu_cache[index].tooltip;
+ } else {
+ return String();
+ }
+}
+
+void MenuBar::get_translatable_strings(List<String> *p_strings) const {
+ Vector<PopupMenu *> popups = _get_popups();
+ for (int i = 0; i < popups.size(); i++) {
+ PopupMenu *pm = popups[i];
+
+ if (!pm->has_meta("_menu_name") && !pm->has_meta("_menu_tooltip")) {
+ continue;
+ }
+
+ String name = pm->get_meta("_menu_name");
+ if (!name.is_empty()) {
+ p_strings->push_back(name);
+ }
+
+ String tooltip = pm->get_meta("_menu_tooltip");
+ if (!tooltip.is_empty()) {
+ p_strings->push_back(tooltip);
+ }
+ }
+}
+
+MenuBar::MenuBar() {
+ set_process_shortcut_input(true);
+}
+
+MenuBar::~MenuBar() {
+}
diff --git a/scene/gui/menu_bar.h b/scene/gui/menu_bar.h
new file mode 100644
index 0000000000..3c4a25fd06
--- /dev/null
+++ b/scene/gui/menu_bar.h
@@ -0,0 +1,156 @@
+/*************************************************************************/
+/* menu_bar.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 MENU_BAR_H
+#define MENU_BAR_H
+
+#include "scene/gui/button.h"
+#include "scene/gui/popup_menu.h"
+
+class MenuBar : public Control {
+ GDCLASS(MenuBar, Control);
+
+ Mutex mutex;
+
+ bool switch_on_hover = true;
+ bool disable_shortcuts = false;
+ bool is_native = true;
+ bool flat = false;
+ int start_index = -1;
+
+ String language;
+ TextDirection text_direction = TEXT_DIRECTION_AUTO;
+
+ struct Menu {
+ String name;
+ String tooltip;
+
+ Ref<TextLine> text_buf;
+ bool hidden = false;
+ bool disabled = false;
+
+ Menu(const String &p_name) {
+ name = p_name;
+ text_buf.instantiate();
+ }
+
+ Menu() {
+ text_buf.instantiate();
+ }
+ };
+ Vector<Menu> menu_cache;
+ HashSet<String> global_menus;
+
+ int focused_menu = -1;
+ int selected_menu = -1;
+ int active_menu = -1;
+
+ Vector2i mouse_pos_adjusted;
+ ObjectID shortcut_context;
+
+ int _get_index_at_point(const Point2 &p_point) const;
+ Rect2 _get_menu_item_rect(int p_index) const;
+ void _draw_menu_item(int p_index);
+
+ void shape(Menu &p_menu);
+ void _refresh_menu_names();
+ Vector<PopupMenu *> _get_popups() const;
+ int get_menu_idx_from_control(PopupMenu *p_child) const;
+
+ void _open_popup(int p_index);
+ void _popup_visibility_changed(bool p_visible);
+ void _update_submenu(const String &p_menu_name, PopupMenu *p_child);
+ void _clear_menu();
+ void _update_menu();
+
+ bool _is_focus_owner_in_shortcut_context() const;
+
+protected:
+ virtual void shortcut_input(const Ref<InputEvent> &p_event) override;
+
+ void _notification(int p_what);
+ virtual void add_child_notify(Node *p_child) override;
+ virtual void move_child_notify(Node *p_child) override;
+ virtual void remove_child_notify(Node *p_child) override;
+ static void _bind_methods();
+
+public:
+ virtual void gui_input(const Ref<InputEvent> &p_event) override;
+
+ void set_switch_on_hover(bool p_enabled);
+ bool is_switch_on_hover();
+ void set_disable_shortcuts(bool p_disabled);
+
+ void set_prefer_global_menu(bool p_enabled);
+ bool is_prefer_global_menu() const;
+
+ bool is_native_menu() const;
+
+ virtual Size2 get_minimum_size() const override;
+
+ int get_menu_count() const;
+
+ void set_text_direction(TextDirection p_text_direction);
+ TextDirection get_text_direction() const;
+
+ void set_language(const String &p_language);
+ String get_language() const;
+
+ void set_start_index(int p_index);
+ int get_start_index() const;
+
+ void set_flat(bool p_enabled);
+ bool is_flat() const;
+
+ void set_menu_title(int p_menu, const String &p_title);
+ String get_menu_title(int p_menu) const;
+
+ void set_menu_tooltip(int p_menu, const String &p_tooltip);
+ String get_menu_tooltip(int p_menu) const;
+
+ void set_menu_disabled(int p_menu, bool p_disabled);
+ bool is_menu_disabled(int p_menu) const;
+
+ void set_menu_hidden(int p_menu, bool p_hidden);
+ bool is_menu_hidden(int p_menu) const;
+
+ void set_shortcut_context(Node *p_node);
+ Node *get_shortcut_context() const;
+
+ PopupMenu *get_menu_popup(int p_menu) const;
+
+ virtual void get_translatable_strings(List<String> *p_strings) const override;
+ virtual String get_tooltip(const Point2 &p_pos) const override;
+
+ MenuBar();
+ ~MenuBar();
+};
+
+#endif // MENU_BAR_H
diff --git a/scene/gui/menu_button.cpp b/scene/gui/menu_button.cpp
index 069a31d9d2..a03db82332 100644
--- a/scene/gui/menu_button.cpp
+++ b/scene/gui/menu_button.cpp
@@ -99,13 +99,15 @@ void MenuButton::pressed() {
popup->set_parent_rect(Rect2(Point2(gp - popup->get_position()), size));
// If not triggered by the mouse, start the popup with its first item selected.
- if (popup->get_item_count() > 0 &&
- ((get_action_mode() == ActionMode::ACTION_MODE_BUTTON_PRESS && Input::get_singleton()->is_action_just_pressed("ui_accept")) ||
- (get_action_mode() == ActionMode::ACTION_MODE_BUTTON_RELEASE && Input::get_singleton()->is_action_just_released("ui_accept")))) {
+ if (popup->get_item_count() > 0 && !_was_pressed_by_mouse()) {
popup->set_current_index(0);
}
- popup->popup();
+ if (popup->is_visible()) {
+ popup->hide();
+ } else {
+ popup->popup();
+ }
}
void MenuButton::gui_input(const Ref<InputEvent> &p_event) {
@@ -126,6 +128,11 @@ bool MenuButton::is_switch_on_hover() {
void MenuButton::set_item_count(int p_count) {
ERR_FAIL_COND(p_count < 0);
+
+ if (popup->get_item_count() == p_count) {
+ return;
+ }
+
popup->set_item_count(p_count);
notify_property_list_changed();
}
diff --git a/scene/gui/nine_patch_rect.cpp b/scene/gui/nine_patch_rect.cpp
index 8fee10b19a..a7e86dd5de 100644
--- a/scene/gui/nine_patch_rect.cpp
+++ b/scene/gui/nine_patch_rect.cpp
@@ -105,6 +105,11 @@ Ref<Texture2D> NinePatchRect::get_texture() const {
void NinePatchRect::set_patch_margin(Side p_side, int p_size) {
ERR_FAIL_INDEX((int)p_side, 4);
+
+ if (margin[p_side] == p_size) {
+ return;
+ }
+
margin[p_side] = p_size;
update();
update_minimum_size();
@@ -130,6 +135,10 @@ Rect2 NinePatchRect::get_region_rect() const {
}
void NinePatchRect::set_draw_center(bool p_enabled) {
+ if (draw_center == p_enabled) {
+ return;
+ }
+
draw_center = p_enabled;
update();
}
@@ -139,6 +148,10 @@ bool NinePatchRect::is_draw_center_enabled() const {
}
void NinePatchRect::set_h_axis_stretch_mode(AxisStretchMode p_mode) {
+ if (axis_h == p_mode) {
+ return;
+ }
+
axis_h = p_mode;
update();
}
@@ -148,6 +161,10 @@ NinePatchRect::AxisStretchMode NinePatchRect::get_h_axis_stretch_mode() const {
}
void NinePatchRect::set_v_axis_stretch_mode(AxisStretchMode p_mode) {
+ if (axis_v == p_mode) {
+ return;
+ }
+
axis_v = p_mode;
update();
}
diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp
index b26410e318..931dffe3bb 100644
--- a/scene/gui/option_button.cpp
+++ b/scene/gui/option_button.cpp
@@ -47,7 +47,7 @@ Size2 OptionButton::get_minimum_size() const {
const Size2 arrow_size = Control::get_theme_icon(SNAME("arrow"))->get_size();
Size2 content_size = minsize - padding;
- content_size.width += arrow_size.width + get_theme_constant(SNAME("h_separation"));
+ content_size.width += arrow_size.width + MAX(0, get_theme_constant(SNAME("h_separation")));
content_size.height = MAX(content_size.height, arrow_size.height);
minsize = content_size + padding;
@@ -204,8 +204,7 @@ void OptionButton::pressed() {
// If not triggered by the mouse, start the popup with the checked item selected.
if (popup->get_item_count() > 0) {
- if ((get_action_mode() == ActionMode::ACTION_MODE_BUTTON_PRESS && Input::get_singleton()->is_action_just_pressed("ui_accept")) ||
- (get_action_mode() == ActionMode::ACTION_MODE_BUTTON_RELEASE && Input::get_singleton()->is_action_just_released("ui_accept"))) {
+ if (!_was_pressed_by_mouse()) {
popup->set_current_index(current > -1 ? current : 0);
} else {
popup->scroll_to_item(current > -1 ? current : 0);
@@ -471,9 +470,9 @@ void OptionButton::get_translatable_strings(List<String> *p_strings) const {
popup->get_translatable_strings(p_strings);
}
-void OptionButton::_validate_property(PropertyInfo &property) const {
- if (property.name == "text" || property.name == "icon") {
- property.usage = PROPERTY_USAGE_NONE;
+void OptionButton::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "text" || p_property.name == "icon") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
diff --git a/scene/gui/option_button.h b/scene/gui/option_button.h
index 49b5eee910..cd709b8f5f 100644
--- a/scene/gui/option_button.h
+++ b/scene/gui/option_button.h
@@ -58,7 +58,7 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
public:
diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp
index cd0d437051..4e2aec0278 100644
--- a/scene/gui/popup_menu.cpp
+++ b/scene/gui/popup_menu.cpp
@@ -36,6 +36,7 @@
#include "core/os/os.h"
#include "core/string/print_string.h"
#include "core/string/translation.h"
+#include "scene/gui/menu_bar.h"
String PopupMenu::_get_accel_text(const Item &p_item) const {
if (p_item.shortcut.is_valid()) {
@@ -66,7 +67,7 @@ Size2 PopupMenu::_get_contents_minimum_size() const {
size.height = _get_item_height(i);
icon_w = MAX(icon_size.width, icon_w);
- size.width += items[i].h_ofs;
+ size.width += items[i].indent * get_theme_constant(SNAME("indent"));
if (items[i].checkable_type && !items[i].separator) {
has_check = true;
@@ -343,14 +344,27 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
}
} else if (p_event->is_action("ui_left") && p_event->is_pressed()) {
Node *n = get_parent();
- if (n && Object::cast_to<PopupMenu>(n)) {
- hide();
- set_input_as_handled();
+ if (n) {
+ if (Object::cast_to<PopupMenu>(n)) {
+ hide();
+ set_input_as_handled();
+ } else if (Object::cast_to<MenuBar>(n)) {
+ Object::cast_to<MenuBar>(n)->gui_input(p_event);
+ set_input_as_handled();
+ return;
+ }
}
} else if (p_event->is_action("ui_right") && p_event->is_pressed()) {
if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator && !items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) {
_activate_submenu(mouse_over, true);
set_input_as_handled();
+ } else {
+ Node *n = get_parent();
+ if (n && Object::cast_to<MenuBar>(n)) {
+ Object::cast_to<MenuBar>(n)->gui_input(p_event);
+ set_input_as_handled();
+ return;
+ }
}
} else if (p_event->is_action("ui_accept") && p_event->is_pressed()) {
if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator) {
@@ -589,7 +603,7 @@ void PopupMenu::_draw_items() {
String text = items[i].xl_text;
// Separator
- item_ofs.x += items[i].h_ofs;
+ item_ofs.x += items[i].indent * get_theme_constant(SNAME("indent"));
if (items[i].separator) {
if (!text.is_empty() || !items[i].icon.is_null()) {
int content_size = items[i].text_buf->get_size().width + hseparation * 2;
@@ -774,6 +788,32 @@ void PopupMenu::_shape_item(int p_item) {
}
}
+void PopupMenu::_menu_changed() {
+ emit_signal(SNAME("menu_changed"));
+}
+
+void PopupMenu::add_child_notify(Node *p_child) {
+ Window::add_child_notify(p_child);
+
+ PopupMenu *pm = Object::cast_to<PopupMenu>(p_child);
+ if (!pm) {
+ return;
+ }
+ p_child->connect("menu_changed", callable_mp(this, &PopupMenu::_menu_changed));
+ _menu_changed();
+}
+
+void PopupMenu::remove_child_notify(Node *p_child) {
+ Window::remove_child_notify(p_child);
+
+ PopupMenu *pm = Object::cast_to<PopupMenu>(p_child);
+ if (!pm) {
+ return;
+ }
+ p_child->disconnect("menu_changed", callable_mp(this, &PopupMenu::_menu_changed));
+ _menu_changed();
+}
+
void PopupMenu::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -795,6 +835,7 @@ void PopupMenu::_notification(int p_what) {
}
child_controls_changed();
+ _menu_changed();
control->update();
} break;
@@ -889,6 +930,7 @@ void PopupMenu::add_item(const String &p_label, int p_id, Key p_accel) {
control->update();
child_controls_changed();
notify_property_list_changed();
+ _menu_changed();
}
void PopupMenu::add_icon_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id, Key p_accel) {
@@ -900,6 +942,7 @@ void PopupMenu::add_icon_item(const Ref<Texture2D> &p_icon, const String &p_labe
control->update();
child_controls_changed();
notify_property_list_changed();
+ _menu_changed();
}
void PopupMenu::add_check_item(const String &p_label, int p_id, Key p_accel) {
@@ -910,6 +953,7 @@ void PopupMenu::add_check_item(const String &p_label, int p_id, Key p_accel) {
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_icon_check_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id, Key p_accel) {
@@ -931,6 +975,7 @@ void PopupMenu::add_radio_check_item(const String &p_label, int p_id, Key p_acce
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_icon_radio_check_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id, Key p_accel) {
@@ -942,6 +987,7 @@ void PopupMenu::add_icon_radio_check_item(const Ref<Texture2D> &p_icon, const St
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_multistate_item(const String &p_label, int p_max_states, int p_default_state, int p_id, Key p_accel) {
@@ -953,6 +999,7 @@ void PopupMenu::add_multistate_item(const String &p_label, int p_max_states, int
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
#define ITEM_SETUP_WITH_SHORTCUT(p_shortcut, p_id, p_global) \
@@ -971,6 +1018,7 @@ void PopupMenu::add_shortcut(const Ref<Shortcut> &p_shortcut, int p_id, bool p_g
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_icon_shortcut(const Ref<Texture2D> &p_icon, const Ref<Shortcut> &p_shortcut, int p_id, bool p_global) {
@@ -981,6 +1029,7 @@ void PopupMenu::add_icon_shortcut(const Ref<Texture2D> &p_icon, const Ref<Shortc
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_check_shortcut(const Ref<Shortcut> &p_shortcut, int p_id, bool p_global) {
@@ -991,6 +1040,7 @@ void PopupMenu::add_check_shortcut(const Ref<Shortcut> &p_shortcut, int p_id, bo
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_icon_check_shortcut(const Ref<Texture2D> &p_icon, const Ref<Shortcut> &p_shortcut, int p_id, bool p_global) {
@@ -1002,6 +1052,7 @@ void PopupMenu::add_icon_check_shortcut(const Ref<Texture2D> &p_icon, const Ref<
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_radio_check_shortcut(const Ref<Shortcut> &p_shortcut, int p_id, bool p_global) {
@@ -1012,6 +1063,7 @@ void PopupMenu::add_radio_check_shortcut(const Ref<Shortcut> &p_shortcut, int p_
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_icon_radio_check_shortcut(const Ref<Texture2D> &p_icon, const Ref<Shortcut> &p_shortcut, int p_id, bool p_global) {
@@ -1023,6 +1075,7 @@ void PopupMenu::add_icon_radio_check_shortcut(const Ref<Texture2D> &p_icon, cons
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_submenu_item(const String &p_label, const String &p_submenu, int p_id) {
@@ -1035,6 +1088,7 @@ void PopupMenu::add_submenu_item(const String &p_label, const String &p_submenu,
_shape_item(items.size() - 1);
control->update();
child_controls_changed();
+ _menu_changed();
}
#undef ITEM_SETUP_WITH_ACCEL
@@ -1057,6 +1111,7 @@ void PopupMenu::set_item_text(int p_idx, const String &p_text) {
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_text_direction(int p_item, Control::TextDirection p_text_direction) {
@@ -1089,10 +1144,16 @@ void PopupMenu::set_item_icon(int p_idx, const Ref<Texture2D> &p_icon) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].icon == p_icon) {
+ return;
+ }
+
items.write[p_idx].icon = p_icon;
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_checked(int p_idx, bool p_checked) {
@@ -1101,10 +1162,15 @@ void PopupMenu::set_item_checked(int p_idx, bool p_checked) {
}
ERR_FAIL_INDEX(p_idx, items.size());
+ if (items[p_idx].checked == p_checked) {
+ return;
+ }
+
items.write[p_idx].checked = p_checked;
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_id(int p_idx, int p_id) {
@@ -1112,10 +1178,16 @@ void PopupMenu::set_item_id(int p_idx, int p_id) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].id == p_id) {
+ return;
+ }
+
items.write[p_idx].id = p_id;
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_accelerator(int p_idx, Key p_accel) {
@@ -1123,11 +1195,17 @@ void PopupMenu::set_item_accelerator(int p_idx, Key p_accel) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].accel == p_accel) {
+ return;
+ }
+
items.write[p_idx].accel = p_accel;
items.write[p_idx].dirty = true;
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_metadata(int p_idx, const Variant &p_meta) {
@@ -1135,9 +1213,15 @@ void PopupMenu::set_item_metadata(int p_idx, const Variant &p_meta) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].metadata == p_meta) {
+ return;
+ }
+
items.write[p_idx].metadata = p_meta;
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_disabled(int p_idx, bool p_disabled) {
@@ -1145,9 +1229,15 @@ void PopupMenu::set_item_disabled(int p_idx, bool p_disabled) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].disabled == p_disabled) {
+ return;
+ }
+
items.write[p_idx].disabled = p_disabled;
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_submenu(int p_idx, const String &p_submenu) {
@@ -1155,9 +1245,15 @@ void PopupMenu::set_item_submenu(int p_idx, const String &p_submenu) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].submenu == p_submenu) {
+ return;
+ }
+
items.write[p_idx].submenu = p_submenu;
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::toggle_item_checked(int p_idx) {
@@ -1165,6 +1261,7 @@ void PopupMenu::toggle_item_checked(int p_idx) {
items.write[p_idx].checked = !items[p_idx].checked;
control->update();
child_controls_changed();
+ _menu_changed();
}
String PopupMenu::get_item_text(int p_idx) const {
@@ -1247,9 +1344,14 @@ Ref<Shortcut> PopupMenu::get_item_shortcut(int p_idx) const {
return items[p_idx].shortcut;
}
-int PopupMenu::get_item_horizontal_offset(int p_idx) const {
+int PopupMenu::get_item_indent(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, items.size(), 0);
- return items[p_idx].h_ofs;
+ return items[p_idx].indent;
+}
+
+int PopupMenu::get_item_max_states(int p_idx) const {
+ ERR_FAIL_INDEX_V(p_idx, items.size(), -1);
+ return items[p_idx].max_states;
}
int PopupMenu::get_item_state(int p_idx) const {
@@ -1262,6 +1364,11 @@ void PopupMenu::set_item_as_separator(int p_idx, bool p_separator) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].separator == p_separator) {
+ return;
+ }
+
items.write[p_idx].separator = p_separator;
control->update();
}
@@ -1276,8 +1383,15 @@ void PopupMenu::set_item_as_checkable(int p_idx, bool p_checkable) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ int type = (int)(p_checkable ? Item::CHECKABLE_TYPE_CHECK_BOX : Item::CHECKABLE_TYPE_NONE);
+ if (type == items[p_idx].checkable_type) {
+ return;
+ }
+
items.write[p_idx].checkable_type = p_checkable ? Item::CHECKABLE_TYPE_CHECK_BOX : Item::CHECKABLE_TYPE_NONE;
control->update();
+ _menu_changed();
}
void PopupMenu::set_item_as_radio_checkable(int p_idx, bool p_radio_checkable) {
@@ -1285,8 +1399,15 @@ void PopupMenu::set_item_as_radio_checkable(int p_idx, bool p_radio_checkable) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ int type = (int)(p_radio_checkable ? Item::CHECKABLE_TYPE_RADIO_BUTTON : Item::CHECKABLE_TYPE_NONE);
+ if (type == items[p_idx].checkable_type) {
+ return;
+ }
+
items.write[p_idx].checkable_type = p_radio_checkable ? Item::CHECKABLE_TYPE_RADIO_BUTTON : Item::CHECKABLE_TYPE_NONE;
control->update();
+ _menu_changed();
}
void PopupMenu::set_item_tooltip(int p_idx, const String &p_tooltip) {
@@ -1294,8 +1415,14 @@ void PopupMenu::set_item_tooltip(int p_idx, const String &p_tooltip) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].tooltip == p_tooltip) {
+ return;
+ }
+
items.write[p_idx].tooltip = p_tooltip;
control->update();
+ _menu_changed();
}
void PopupMenu::set_item_shortcut(int p_idx, const Ref<Shortcut> &p_shortcut, bool p_global) {
@@ -1303,6 +1430,11 @@ void PopupMenu::set_item_shortcut(int p_idx, const Ref<Shortcut> &p_shortcut, bo
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].shortcut == p_shortcut && items[p_idx].shortcut_is_global == p_global && items[p_idx].shortcut.is_valid() == p_shortcut.is_valid()) {
+ return;
+ }
+
if (items[p_idx].shortcut.is_valid()) {
_unref_shortcut(items[p_idx].shortcut);
}
@@ -1315,16 +1447,23 @@ void PopupMenu::set_item_shortcut(int p_idx, const Ref<Shortcut> &p_shortcut, bo
}
control->update();
+ _menu_changed();
}
-void PopupMenu::set_item_horizontal_offset(int p_idx, int p_offset) {
+void PopupMenu::set_item_indent(int p_idx, int p_indent) {
if (p_idx < 0) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
- items.write[p_idx].h_ofs = p_offset;
+
+ if (items.write[p_idx].indent == p_indent) {
+ return;
+ }
+ items.write[p_idx].indent = p_indent;
+
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::set_item_multistate(int p_idx, int p_state) {
@@ -1332,8 +1471,14 @@ void PopupMenu::set_item_multistate(int p_idx, int p_state) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].state == p_state) {
+ return;
+ }
+
items.write[p_idx].state = p_state;
control->update();
+ _menu_changed();
}
void PopupMenu::set_item_shortcut_disabled(int p_idx, bool p_disabled) {
@@ -1341,8 +1486,14 @@ void PopupMenu::set_item_shortcut_disabled(int p_idx, bool p_disabled) {
p_idx += get_item_count();
}
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (items[p_idx].shortcut_is_disabled == p_disabled) {
+ return;
+ }
+
items.write[p_idx].shortcut_is_disabled = p_disabled;
control->update();
+ _menu_changed();
}
void PopupMenu::toggle_item_multistate(int p_idx) {
@@ -1357,6 +1508,7 @@ void PopupMenu::toggle_item_multistate(int p_idx) {
}
control->update();
+ _menu_changed();
}
bool PopupMenu::is_item_checkable(int p_idx) const {
@@ -1369,6 +1521,11 @@ bool PopupMenu::is_item_radio_checkable(int p_idx) const {
return items[p_idx].checkable_type == Item::CHECKABLE_TYPE_RADIO_BUTTON;
}
+bool PopupMenu::is_item_shortcut_global(int p_idx) const {
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
+ return items[p_idx].shortcut_is_global;
+}
+
bool PopupMenu::is_item_shortcut_disabled(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].shortcut_is_disabled;
@@ -1376,6 +1533,11 @@ bool PopupMenu::is_item_shortcut_disabled(int p_idx) const {
void PopupMenu::set_current_index(int p_idx) {
ERR_FAIL_INDEX(p_idx, items.size());
+
+ if (mouse_over == p_idx) {
+ return;
+ }
+
mouse_over = p_idx;
scroll_to_item(mouse_over);
control->update();
@@ -1388,6 +1550,11 @@ int PopupMenu::get_current_index() const {
void PopupMenu::set_item_count(int p_count) {
ERR_FAIL_COND(p_count < 0);
int prev_size = items.size();
+
+ if (prev_size == p_count) {
+ return;
+ }
+
items.resize(p_count);
if (prev_size < p_count) {
@@ -1399,6 +1566,7 @@ void PopupMenu::set_item_count(int p_count) {
control->update();
child_controls_changed();
notify_property_list_changed();
+ _menu_changed();
}
int PopupMenu::get_item_count() const {
@@ -1540,6 +1708,7 @@ void PopupMenu::remove_item(int p_idx) {
items.remove_at(p_idx);
control->update();
child_controls_changed();
+ _menu_changed();
}
void PopupMenu::add_separator(const String &p_text, int p_id) {
@@ -1552,6 +1721,7 @@ void PopupMenu::add_separator(const String &p_text, int p_id) {
}
items.push_back(sep);
control->update();
+ _menu_changed();
}
void PopupMenu::clear() {
@@ -1565,6 +1735,7 @@ void PopupMenu::clear() {
control->update();
child_controls_changed();
notify_property_list_changed();
+ _menu_changed();
}
void PopupMenu::_ref_shortcut(Ref<Shortcut> p_sc) {
@@ -1839,7 +2010,7 @@ void PopupMenu::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_item_as_radio_checkable", "index", "enable"), &PopupMenu::set_item_as_radio_checkable);
ClassDB::bind_method(D_METHOD("set_item_tooltip", "index", "tooltip"), &PopupMenu::set_item_tooltip);
ClassDB::bind_method(D_METHOD("set_item_shortcut", "index", "shortcut", "global"), &PopupMenu::set_item_shortcut, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("set_item_horizontal_offset", "index", "offset"), &PopupMenu::set_item_horizontal_offset);
+ ClassDB::bind_method(D_METHOD("set_item_indent", "index", "indent"), &PopupMenu::set_item_indent);
ClassDB::bind_method(D_METHOD("set_item_multistate", "index", "state"), &PopupMenu::set_item_multistate);
ClassDB::bind_method(D_METHOD("set_item_shortcut_disabled", "index", "disabled"), &PopupMenu::set_item_shortcut_disabled);
@@ -1863,7 +2034,7 @@ void PopupMenu::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_item_shortcut_disabled", "index"), &PopupMenu::is_item_shortcut_disabled);
ClassDB::bind_method(D_METHOD("get_item_tooltip", "index"), &PopupMenu::get_item_tooltip);
ClassDB::bind_method(D_METHOD("get_item_shortcut", "index"), &PopupMenu::get_item_shortcut);
- ClassDB::bind_method(D_METHOD("get_item_horizontal_offset", "index"), &PopupMenu::get_item_horizontal_offset);
+ ClassDB::bind_method(D_METHOD("get_item_indent", "index"), &PopupMenu::get_item_indent);
ClassDB::bind_method(D_METHOD("set_current_index", "index"), &PopupMenu::set_current_index);
ClassDB::bind_method(D_METHOD("get_current_index"), &PopupMenu::get_current_index);
@@ -1903,6 +2074,7 @@ void PopupMenu::_bind_methods() {
ADD_SIGNAL(MethodInfo("id_pressed", PropertyInfo(Variant::INT, "id")));
ADD_SIGNAL(MethodInfo("id_focused", PropertyInfo(Variant::INT, "id")));
ADD_SIGNAL(MethodInfo("index_pressed", PropertyInfo(Variant::INT, "index")));
+ ADD_SIGNAL(MethodInfo("menu_changed"));
}
void PopupMenu::popup(const Rect2 &p_bounds) {
diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h
index e203793c2e..d3ad0762e4 100644
--- a/scene/gui/popup_menu.h
+++ b/scene/gui/popup_menu.h
@@ -68,7 +68,7 @@ class PopupMenu : public Popup {
Key accel = Key::NONE;
int _ofs_cache = 0;
int _height_cache = 0;
- int h_ofs = 0;
+ int indent = 0;
Ref<Shortcut> shortcut;
bool shortcut_is_global = false;
bool shortcut_is_disabled = false;
@@ -134,8 +134,11 @@ class PopupMenu : public Popup {
void _minimum_lifetime_timeout();
void _close_pressed();
+ void _menu_changed();
protected:
+ virtual void add_child_notify(Node *p_child) override;
+ virtual void remove_child_notify(Node *p_child) override;
void _notification(int p_what);
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
@@ -183,7 +186,7 @@ public:
void set_item_as_radio_checkable(int p_idx, bool p_radio_checkable);
void set_item_tooltip(int p_idx, const String &p_tooltip);
void set_item_shortcut(int p_idx, const Ref<Shortcut> &p_shortcut, bool p_global = false);
- void set_item_horizontal_offset(int p_idx, int p_offset);
+ void set_item_indent(int p_idx, int p_indent);
void set_item_multistate(int p_idx, int p_state);
void toggle_item_multistate(int p_idx);
void set_item_shortcut_disabled(int p_idx, bool p_disabled);
@@ -206,9 +209,11 @@ public:
bool is_item_checkable(int p_idx) const;
bool is_item_radio_checkable(int p_idx) const;
bool is_item_shortcut_disabled(int p_idx) const;
+ bool is_item_shortcut_global(int p_idx) const;
String get_item_tooltip(int p_idx) const;
Ref<Shortcut> get_item_shortcut(int p_idx) const;
- int get_item_horizontal_offset(int p_idx) const;
+ int get_item_indent(int p_idx) const;
+ int get_item_max_states(int p_idx) const;
int get_item_state(int p_idx) const;
void set_current_index(int p_idx);
diff --git a/scene/gui/range.cpp b/scene/gui/range.cpp
index fae6688452..0fb1f27802 100644
--- a/scene/gui/range.cpp
+++ b/scene/gui/range.cpp
@@ -106,6 +106,10 @@ void Range::set_value(double p_val) {
}
void Range::set_min(double p_min) {
+ if (shared->min == p_min) {
+ return;
+ }
+
shared->min = p_min;
set_value(shared->val);
_validate_values();
@@ -116,6 +120,10 @@ void Range::set_min(double p_min) {
}
void Range::set_max(double p_max) {
+ if (shared->max == p_max) {
+ return;
+ }
+
shared->max = p_max;
set_value(shared->val);
_validate_values();
@@ -124,11 +132,19 @@ void Range::set_max(double p_max) {
}
void Range::set_step(double p_step) {
+ if (shared->step == p_step) {
+ return;
+ }
+
shared->step = p_step;
shared->emit_changed("step");
}
void Range::set_page(double p_page) {
+ if (shared->page == p_page) {
+ return;
+ }
+
shared->page = p_page;
set_value(shared->val);
_validate_values();
@@ -300,6 +316,10 @@ bool Range::is_using_rounded_values() const {
}
void Range::set_exp_ratio(bool p_enable) {
+ if (shared->exp_ratio == p_enable) {
+ return;
+ }
+
shared->exp_ratio = p_enable;
update_configuration_warnings();
diff --git a/scene/gui/reference_rect.cpp b/scene/gui/reference_rect.cpp
index 5190a5a7d2..05dfe4b118 100644
--- a/scene/gui/reference_rect.cpp
+++ b/scene/gui/reference_rect.cpp
@@ -46,6 +46,10 @@ void ReferenceRect::_notification(int p_what) {
}
void ReferenceRect::set_border_color(const Color &p_color) {
+ if (border_color == p_color) {
+ return;
+ }
+
border_color = p_color;
update();
}
@@ -55,7 +59,12 @@ Color ReferenceRect::get_border_color() const {
}
void ReferenceRect::set_border_width(float p_width) {
- border_width = MAX(0.0, p_width);
+ float width_max = MAX(0.0, p_width);
+ if (border_width == width_max) {
+ return;
+ }
+
+ border_width = width_max;
update();
}
@@ -64,6 +73,10 @@ float ReferenceRect::get_border_width() const {
}
void ReferenceRect::set_editor_only(const bool &p_enabled) {
+ if (editor_only == p_enabled) {
+ return;
+ }
+
editor_only = p_enabled;
update();
}
diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp
index 984f20ee58..6ab3cdcb69 100644
--- a/scene/gui/rich_text_label.cpp
+++ b/scene/gui/rich_text_label.cpp
@@ -1346,7 +1346,7 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o
return line_count;
}
-void RichTextLabel::_find_click(ItemFrame *p_frame, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char, bool *r_outside) {
+void RichTextLabel::_find_click(ItemFrame *p_frame, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char, bool *r_outside, bool p_meta) {
if (r_click_item) {
*r_click_item = nullptr;
}
@@ -1369,7 +1369,7 @@ void RichTextLabel::_find_click(ItemFrame *p_frame, const Point2i &p_click, Item
Point2 ofs = text_rect.get_position() + Vector2(0, main->lines[from_line].offset.y - vofs);
while (ofs.y < size.height && from_line < to_line) {
MutexLock lock(main->lines[from_line].text_buf->get_mutex());
- _find_click_in_line(p_frame, from_line, ofs, text_rect.size.x, p_click, r_click_frame, r_click_line, r_click_item, r_click_char);
+ _find_click_in_line(p_frame, from_line, ofs, text_rect.size.x, p_click, r_click_frame, r_click_line, r_click_item, r_click_char, false, p_meta);
ofs.y += main->lines[from_line].text_buf->get_size().y + main->lines[from_line].text_buf->get_line_count() * get_theme_constant(SNAME("line_separation"));
if (((r_click_item != nullptr) && ((*r_click_item) != nullptr)) || ((r_click_frame != nullptr) && ((*r_click_frame) != nullptr))) {
if (r_outside != nullptr) {
@@ -1381,7 +1381,7 @@ void RichTextLabel::_find_click(ItemFrame *p_frame, const Point2i &p_click, Item
}
}
-float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char, bool p_table) {
+float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char, bool p_table, bool p_meta) {
Vector2 off;
bool line_clicked = false;
@@ -1479,7 +1479,7 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V
}
if (crect.has_point(p_click)) {
for (int j = 0; j < (int)frame->lines.size(); j++) {
- _find_click_in_line(frame, j, rect.position + Vector2(0, frame->lines[j].offset.y), rect.size.x, p_click, &table_click_frame, &table_click_line, &table_click_item, &table_click_char, true);
+ _find_click_in_line(frame, j, rect.position + Vector2(0, frame->lines[j].offset.y), rect.size.x, p_click, &table_click_frame, &table_click_line, &table_click_item, &table_click_char, true, p_meta);
if (table_click_frame && table_click_item) {
// Save cell detected cell hit data.
table_range = Vector2i(INT32_MAX, 0);
@@ -1512,7 +1512,15 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V
if (p_click.y >= rect.position.y && p_click.y <= rect.position.y + rect.size.y) {
if ((!rtl && p_click.x >= rect.position.x) || (rtl && p_click.x <= rect.position.x + rect.size.x)) {
- char_pos = TS->shaped_text_hit_test_position(rid, p_click.x - rect.position.x);
+ if (p_meta) {
+ int64_t glyph_idx = TS->shaped_text_hit_test_grapheme(rid, p_click.x - rect.position.x);
+ if (glyph_idx >= 0) {
+ const Glyph *glyphs = TS->shaped_text_get_glyphs(rid);
+ char_pos = glyphs[glyph_idx].start;
+ }
+ } else {
+ char_pos = TS->shaped_text_hit_test_position(rid, p_click.x - rect.position.x);
+ }
}
line_clicked = true;
text_rect_begin = rtl ? rect.position.x + rect.size.x : rect.position.x;
@@ -1825,7 +1833,7 @@ Control::CursorShape RichTextLabel::get_cursor_shape(const Point2 &p_pos) const
Item *item = nullptr;
bool outside = true;
- const_cast<RichTextLabel *>(this)->_find_click(main, p_pos, nullptr, nullptr, &item, nullptr, &outside);
+ const_cast<RichTextLabel *>(this)->_find_click(main, p_pos, nullptr, nullptr, &item, nullptr, &outside, true);
if (item && !outside && const_cast<RichTextLabel *>(this)->_find_meta(item, nullptr)) {
return CURSOR_POINTING_HAND;
@@ -1850,7 +1858,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) {
selection.drag_attempt = false;
- _find_click(main, b->get_position(), &c_frame, &c_line, &c_item, &c_index, &outside);
+ _find_click(main, b->get_position(), &c_frame, &c_line, &c_item, &c_index, &outside, false);
if (c_item != nullptr) {
if (selection.enabled) {
selection.click_frame = c_frame;
@@ -1888,7 +1896,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) {
selection.drag_attempt = false;
- _find_click(main, b->get_position(), &c_frame, &c_line, &c_item, &c_index, &outside);
+ _find_click(main, b->get_position(), &c_frame, &c_line, &c_item, &c_index, &outside, false);
if (c_frame) {
const Line &l = c_frame->lines[c_line];
@@ -1938,7 +1946,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) {
Item *c_item = nullptr;
bool outside = true;
- _find_click(main, b->get_position(), nullptr, nullptr, &c_item, nullptr, &outside);
+ _find_click(main, b->get_position(), nullptr, nullptr, &c_item, nullptr, &outside, true);
if (c_item) {
Variant meta;
@@ -2044,7 +2052,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) {
int c_index = 0;
bool outside;
- _find_click(main, m->get_position(), &c_frame, &c_line, &c_item, &c_index, &outside);
+ _find_click(main, m->get_position(), &c_frame, &c_line, &c_item, &c_index, &outside, false);
if (selection.click_item && c_item) {
selection.from_frame = selection.click_frame;
selection.from_line = selection.click_line;
@@ -2102,7 +2110,7 @@ String RichTextLabel::get_tooltip(const Point2 &p_pos) const {
Item *c_item = nullptr;
bool outside;
- const_cast<RichTextLabel *>(this)->_find_click(main, p_pos, nullptr, nullptr, &c_item, nullptr, &outside);
+ const_cast<RichTextLabel *>(this)->_find_click(main, p_pos, nullptr, nullptr, &c_item, nullptr, &outside, true);
String description;
if (c_item && !outside && const_cast<RichTextLabel *>(this)->_find_hint(c_item, &description)) {
@@ -3370,6 +3378,10 @@ void RichTextLabel::clear() {
}
void RichTextLabel::set_tab_size(int p_spaces) {
+ if (tab_size == p_spaces) {
+ return;
+ }
+
_stop_thread();
tab_size = p_spaces;
@@ -3393,6 +3405,10 @@ bool RichTextLabel::is_fit_content_height_enabled() const {
}
void RichTextLabel::set_meta_underline(bool p_underline) {
+ if (underline_meta == p_underline) {
+ return;
+ }
+
underline_meta = p_underline;
update();
}
@@ -4320,6 +4336,8 @@ void RichTextLabel::append_text(const String &p_bbcode) {
}
void RichTextLabel::scroll_to_paragraph(int p_paragraph) {
+ _validate_line_caches();
+
if (p_paragraph <= 0) {
vscroll->set_value(0);
} else if (p_paragraph >= main->first_invalid_line.load()) {
@@ -4341,6 +4359,8 @@ int RichTextLabel::get_visible_paragraph_count() const {
}
void RichTextLabel::scroll_to_line(int p_line) {
+ _validate_line_caches();
+
if (p_line <= 0) {
vscroll->set_value(0);
return;
@@ -4405,6 +4425,10 @@ int RichTextLabel::get_visible_line_count() const {
}
void RichTextLabel::set_selection_enabled(bool p_enabled) {
+ if (selection.enabled == p_enabled) {
+ return;
+ }
+
selection.enabled = p_enabled;
if (!p_enabled) {
if (selection.active) {
@@ -4417,6 +4441,10 @@ void RichTextLabel::set_selection_enabled(bool p_enabled) {
}
void RichTextLabel::set_deselect_on_focus_loss_enabled(const bool p_enabled) {
+ if (deselect_on_focus_loss_enabled == p_enabled) {
+ return;
+ }
+
deselect_on_focus_loss_enabled = p_enabled;
if (p_enabled && selection.active && !has_focus()) {
deselect();
@@ -4784,6 +4812,10 @@ int RichTextLabel::get_selection_to() const {
}
void RichTextLabel::set_text(const String &p_bbcode) {
+ if (text == p_bbcode) {
+ return;
+ }
+
text = p_bbcode;
if (use_bbcode) {
parse_bbcode(p_bbcode);
@@ -4912,15 +4944,19 @@ void RichTextLabel::set_percent_visible(float p_percent) {
if (percent_visible != p_percent) {
_stop_thread();
- if (p_percent < 0 || p_percent >= 1) {
+ if (percent_visible >= 1.0) {
visible_characters = -1;
- percent_visible = 1;
+ percent_visible = 1.0;
+ } else if (percent_visible < 0.0) {
+ visible_characters = 0;
+ percent_visible = 0.0;
} else {
visible_characters = get_total_character_count() * p_percent;
percent_visible = p_percent;
}
+
if (visible_chars_behavior == TextServer::VC_CHARS_BEFORE_SHAPING) {
- main->first_invalid_line.store(0); //invalidate ALL
+ main->first_invalid_line.store(0); // Invalidate ALL.
_validate_line_caches();
}
update();
@@ -4954,6 +4990,8 @@ void RichTextLabel::install_effect(const Variant effect) {
}
int RichTextLabel::get_content_height() const {
+ const_cast<RichTextLabel *>(this)->_validate_line_caches();
+
int total_height = 0;
int to_line = main->first_invalid_line.load();
if (to_line) {
@@ -4964,6 +5002,8 @@ int RichTextLabel::get_content_height() const {
}
int RichTextLabel::get_content_width() const {
+ const_cast<RichTextLabel *>(this)->_validate_line_caches();
+
int total_width = 0;
int to_line = main->first_invalid_line.load();
for (int i = 0; i < to_line; i++) {
@@ -5312,6 +5352,10 @@ int RichTextLabel::get_total_glyph_count() const {
}
void RichTextLabel::set_fixed_size_to_width(int p_width) {
+ if (fixed_width == p_width) {
+ return;
+ }
+
fixed_width = p_width;
update_minimum_size();
}
diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h
index e5f0469c01..95e55bf1a1 100644
--- a/scene/gui/rich_text_label.h
+++ b/scene/gui/rich_text_label.h
@@ -444,7 +444,7 @@ private:
TextServer::VisibleCharactersBehavior visible_chars_behavior = TextServer::VC_CHARS_BEFORE_SHAPING;
bool _is_click_inside_selection() const;
- void _find_click(ItemFrame *p_frame, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr, bool *r_outside = nullptr);
+ void _find_click(ItemFrame *p_frame, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr, bool *r_outside = nullptr, bool p_meta = false);
String _get_line_text(ItemFrame *p_frame, int p_line, Selection p_sel) const;
bool _search_line(ItemFrame *p_frame, int p_line, const String &p_string, int p_char_idx, bool p_reverse_search);
@@ -455,7 +455,7 @@ private:
void _update_line_font(ItemFrame *p_frame, int p_line, const Ref<Font> &p_base_font, int p_base_font_size);
int _draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Color &p_base_color, int p_outline_size, const Color &p_outline_color, const Color &p_font_shadow_color, int p_shadow_outline_size, const Point2 &p_shadow_ofs, int &r_processed_glyphs);
- float _find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr, bool p_table = false);
+ float _find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr, bool p_table = false, bool p_meta = false);
String _roman(int p_num, bool p_capitalize) const;
String _letters(int p_num, bool p_capitalize) const;
diff --git a/scene/gui/slider.cpp b/scene/gui/slider.cpp
index 64c07007dc..2695ad1f14 100644
--- a/scene/gui/slider.cpp
+++ b/scene/gui/slider.cpp
@@ -227,6 +227,10 @@ double Slider::get_custom_step() const {
}
void Slider::set_ticks(int p_count) {
+ if (ticks == p_count) {
+ return;
+ }
+
ticks = p_count;
update();
}
@@ -240,11 +244,19 @@ bool Slider::get_ticks_on_borders() const {
}
void Slider::set_ticks_on_borders(bool _tob) {
+ if (ticks_on_borders == _tob) {
+ return;
+ }
+
ticks_on_borders = _tob;
update();
}
void Slider::set_editable(bool p_editable) {
+ if (editable == p_editable) {
+ return;
+ }
+
editable = p_editable;
update();
}
diff --git a/scene/gui/spin_box.cpp b/scene/gui/spin_box.cpp
index 8a7f52b0d9..517c83545c 100644
--- a/scene/gui/spin_box.cpp
+++ b/scene/gui/spin_box.cpp
@@ -250,6 +250,10 @@ HorizontalAlignment SpinBox::get_horizontal_alignment() const {
}
void SpinBox::set_suffix(const String &p_suffix) {
+ if (suffix == p_suffix) {
+ return;
+ }
+
suffix = p_suffix;
_value_changed(0);
}
@@ -259,6 +263,10 @@ String SpinBox::get_suffix() const {
}
void SpinBox::set_prefix(const String &p_prefix) {
+ if (prefix == p_prefix) {
+ return;
+ }
+
prefix = p_prefix;
_value_changed(0);
}
diff --git a/scene/gui/split_container.cpp b/scene/gui/split_container.cpp
index d7aa516ee6..b6073ce265 100644
--- a/scene/gui/split_container.cpp
+++ b/scene/gui/split_container.cpp
@@ -95,14 +95,18 @@ void SplitContainer::_resort() {
no_offset_middle_sep = ms_first[axis];
}
- // Compute the final middle separation
+ // Compute the final middle separation.
middle_sep = no_offset_middle_sep;
+ if (prev_no_offset_middle_sep != INT_MAX) {
+ split_offset -= middle_sep - prev_no_offset_middle_sep;
+ }
+ prev_no_offset_middle_sep = middle_sep;
+
if (!collapsed) {
int clamped_split_offset = CLAMP(split_offset, ms_first[axis] - no_offset_middle_sep, (get_size()[axis] - ms_second[axis] - sep) - no_offset_middle_sep);
middle_sep += clamped_split_offset;
if (should_clamp_split_offset) {
split_offset = clamped_split_offset;
-
should_clamp_split_offset = false;
}
}
@@ -327,6 +331,10 @@ void SplitContainer::set_collapsed(bool p_collapsed) {
}
void SplitContainer::set_dragger_visibility(DraggerVisibility p_visibility) {
+ if (dragger_visibility == p_visibility) {
+ return;
+ }
+
dragger_visibility = p_visibility;
queue_sort();
update();
diff --git a/scene/gui/split_container.h b/scene/gui/split_container.h
index a69ffe4de9..dd15362199 100644
--- a/scene/gui/split_container.h
+++ b/scene/gui/split_container.h
@@ -47,6 +47,7 @@ private:
bool should_clamp_split_offset = false;
int split_offset = 0;
int middle_sep = 0;
+ int prev_no_offset_middle_sep = INT_MAX;
bool vertical = false;
bool dragging = false;
int drag_from = 0;
diff --git a/scene/gui/subviewport_container.cpp b/scene/gui/subviewport_container.cpp
index 68281b6a72..869683e427 100644
--- a/scene/gui/subviewport_container.cpp
+++ b/scene/gui/subviewport_container.cpp
@@ -53,6 +53,10 @@ Size2 SubViewportContainer::get_minimum_size() const {
}
void SubViewportContainer::set_stretch(bool p_enable) {
+ if (stretch == p_enable) {
+ return;
+ }
+
stretch = p_enable;
update_minimum_size();
queue_sort();
diff --git a/scene/gui/tab_bar.cpp b/scene/gui/tab_bar.cpp
index d36a364677..e0739f909f 100644
--- a/scene/gui/tab_bar.cpp
+++ b/scene/gui/tab_bar.cpp
@@ -634,6 +634,11 @@ bool TabBar::get_offset_buttons_visible() const {
void TabBar::set_tab_title(int p_tab, const String &p_title) {
ERR_FAIL_INDEX(p_tab, tabs.size());
+
+ if (tabs[p_tab].text == p_title) {
+ return;
+ }
+
tabs.write[p_tab].text = p_title;
_shape(p_tab);
@@ -690,6 +695,11 @@ String TabBar::get_tab_language(int p_tab) const {
void TabBar::set_tab_icon(int p_tab, const Ref<Texture2D> &p_icon) {
ERR_FAIL_INDEX(p_tab, tabs.size());
+
+ if (tabs[p_tab].icon == p_icon) {
+ return;
+ }
+
tabs.write[p_tab].icon = p_icon;
_update_cache();
@@ -708,6 +718,11 @@ Ref<Texture2D> TabBar::get_tab_icon(int p_tab) const {
void TabBar::set_tab_disabled(int p_tab, bool p_disabled) {
ERR_FAIL_INDEX(p_tab, tabs.size());
+
+ if (tabs[p_tab].disabled == p_disabled) {
+ return;
+ }
+
tabs.write[p_tab].disabled = p_disabled;
_update_cache();
@@ -726,6 +741,11 @@ bool TabBar::is_tab_disabled(int p_tab) const {
void TabBar::set_tab_hidden(int p_tab, bool p_hidden) {
ERR_FAIL_INDEX(p_tab, tabs.size());
+
+ if (tabs[p_tab].hidden == p_hidden) {
+ return;
+ }
+
tabs.write[p_tab].hidden = p_hidden;
_update_cache();
@@ -744,6 +764,11 @@ bool TabBar::is_tab_hidden(int p_tab) const {
void TabBar::set_tab_button_icon(int p_tab, const Ref<Texture2D> &p_icon) {
ERR_FAIL_INDEX(p_tab, tabs.size());
+
+ if (tabs[p_tab].right_button == p_icon) {
+ return;
+ }
+
tabs.write[p_tab].right_button = p_icon;
_update_cache();
@@ -1155,6 +1180,11 @@ int TabBar::get_tab_idx_at_point(const Point2 &p_point) const {
void TabBar::set_tab_alignment(AlignmentMode p_alignment) {
ERR_FAIL_INDEX(p_alignment, ALIGNMENT_MAX);
+
+ if (tab_alignment == p_alignment) {
+ return;
+ }
+
tab_alignment = p_alignment;
_update_cache();
@@ -1374,6 +1404,11 @@ Rect2 TabBar::get_tab_rect(int p_tab) const {
void TabBar::set_tab_close_display_policy(CloseButtonDisplayPolicy p_policy) {
ERR_FAIL_INDEX(p_policy, CLOSE_BUTTON_MAX);
+
+ if (cb_displaypolicy == p_policy) {
+ return;
+ }
+
cb_displaypolicy = p_policy;
_update_cache();
@@ -1391,6 +1426,11 @@ TabBar::CloseButtonDisplayPolicy TabBar::get_tab_close_display_policy() const {
void TabBar::set_max_tab_width(int p_width) {
ERR_FAIL_COND(p_width < 0);
+
+ if (max_width == p_width) {
+ return;
+ }
+
max_width = p_width;
_update_cache();
diff --git a/scene/gui/tab_container.cpp b/scene/gui/tab_container.cpp
index 12f91a9873..10a6d18330 100644
--- a/scene/gui/tab_container.cpp
+++ b/scene/gui/tab_container.cpp
@@ -618,6 +618,10 @@ int TabContainer::get_tab_idx_from_control(Control *p_child) const {
}
void TabContainer::set_tab_alignment(TabBar::AlignmentMode p_alignment) {
+ if (tab_bar->get_tab_alignment() == p_alignment) {
+ return;
+ }
+
tab_bar->set_tab_alignment(p_alignment);
_update_margins();
}
@@ -679,6 +683,10 @@ void TabContainer::set_tab_title(int p_tab, const String &p_title) {
Control *child = get_tab_control(p_tab);
ERR_FAIL_COND(!child);
+ if (tab_bar->get_tab_title(p_tab) == p_title) {
+ return;
+ }
+
tab_bar->set_tab_title(p_tab, p_title);
if (p_title == child->get_name()) {
@@ -698,6 +706,10 @@ String TabContainer::get_tab_title(int p_tab) const {
}
void TabContainer::set_tab_icon(int p_tab, const Ref<Texture2D> &p_icon) {
+ if (tab_bar->get_tab_icon(p_tab) == p_icon) {
+ return;
+ }
+
tab_bar->set_tab_icon(p_tab, p_icon);
_update_margins();
@@ -709,6 +721,10 @@ Ref<Texture2D> TabContainer::get_tab_icon(int p_tab) const {
}
void TabContainer::set_tab_disabled(int p_tab, bool p_disabled) {
+ if (tab_bar->is_tab_disabled(p_tab) == p_disabled) {
+ return;
+ }
+
tab_bar->set_tab_disabled(p_tab, p_disabled);
_update_margins();
@@ -725,6 +741,10 @@ void TabContainer::set_tab_hidden(int p_tab, bool p_hidden) {
Control *child = get_tab_control(p_tab);
ERR_FAIL_COND(!child);
+ if (tab_bar->is_tab_hidden(p_tab) == p_hidden) {
+ return;
+ }
+
tab_bar->set_tab_hidden(p_tab, p_hidden);
child->hide();
@@ -811,7 +831,11 @@ void TabContainer::set_popup(Node *p_popup) {
bool had_popup = get_popup();
Popup *popup = Object::cast_to<Popup>(p_popup);
- popup_obj_id = popup ? popup->get_instance_id() : ObjectID();
+ ObjectID popup_id = popup ? popup->get_instance_id() : ObjectID();
+ if (popup_obj_id == popup_id) {
+ return;
+ }
+ popup_obj_id = popup_id;
if (had_popup != bool(popup)) {
update();
@@ -855,6 +879,10 @@ int TabContainer::get_tabs_rearrange_group() const {
}
void TabContainer::set_use_hidden_tabs_for_min_size(bool p_use_hidden_tabs) {
+ if (use_hidden_tabs_for_min_size == p_use_hidden_tabs) {
+ return;
+ }
+
use_hidden_tabs_for_min_size = p_use_hidden_tabs;
update_minimum_size();
}
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index 3755a8fa34..097eb1fd95 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -2889,6 +2889,10 @@ TextServer::StructuredTextParser TextEdit::get_structured_text_bidi_override() c
}
void TextEdit::set_structured_text_bidi_override_options(Array p_args) {
+ if (st_args == p_args) {
+ return;
+ }
+
st_args = p_args;
for (int i = 0; i < text.size(); i++) {
text.set(i, text[i], structured_text_parser(st_parser, st_args, text[i]));
@@ -2917,6 +2921,10 @@ int TextEdit::get_tab_size() const {
// User controls
void TextEdit::set_overtype_mode_enabled(const bool p_enabled) {
+ if (overtype_mode == p_enabled) {
+ return;
+ }
+
overtype_mode = p_enabled;
update();
}
@@ -3036,6 +3044,10 @@ int TextEdit::get_line_count() const {
}
void TextEdit::set_placeholder(const String &p_text) {
+ if (placeholder_text == p_text) {
+ return;
+ }
+
placeholder_text = p_text;
_update_placeholder();
update();
@@ -3945,6 +3957,10 @@ bool TextEdit::is_mouse_over_selection(bool p_edges) const {
/* Caret */
void TextEdit::set_caret_type(CaretType p_type) {
+ if (caret_type == p_type) {
+ return;
+ }
+
caret_type = p_type;
update();
}
@@ -3954,6 +3970,10 @@ TextEdit::CaretType TextEdit::get_caret_type() const {
}
void TextEdit::set_caret_blink_enabled(const bool p_enabled) {
+ if (caret_blink_enabled == p_enabled) {
+ return;
+ }
+
caret_blink_enabled = p_enabled;
if (has_focus()) {
@@ -4114,6 +4134,10 @@ String TextEdit::get_word_under_caret() const {
/* Selection. */
void TextEdit::set_selecting_enabled(const bool p_enabled) {
+ if (selecting_enabled == p_enabled) {
+ return;
+ }
+
selecting_enabled = p_enabled;
if (!selecting_enabled) {
@@ -4126,6 +4150,10 @@ bool TextEdit::is_selecting_enabled() const {
}
void TextEdit::set_deselect_on_focus_loss_enabled(const bool p_enabled) {
+ if (deselect_on_focus_loss_enabled == p_enabled) {
+ return;
+ }
+
deselect_on_focus_loss_enabled = p_enabled;
if (p_enabled && selection.active && !has_focus()) {
deselect();
@@ -4431,6 +4459,10 @@ bool TextEdit::is_smooth_scroll_enabled() const {
}
void TextEdit::set_scroll_past_end_of_file_enabled(const bool p_enabled) {
+ if (scroll_past_end_of_file_enabled == p_enabled) {
+ return;
+ }
+
scroll_past_end_of_file_enabled = p_enabled;
update();
}
@@ -4714,10 +4746,12 @@ void TextEdit::center_viewport_to_caret() {
/* Minimap */
void TextEdit::set_draw_minimap(bool p_enabled) {
- if (draw_minimap != p_enabled) {
- draw_minimap = p_enabled;
- _update_wrap_at_column();
+ if (draw_minimap == p_enabled) {
+ return;
}
+
+ draw_minimap = p_enabled;
+ _update_wrap_at_column();
update();
}
@@ -4726,10 +4760,12 @@ bool TextEdit::is_drawing_minimap() const {
}
void TextEdit::set_minimap_width(int p_minimap_width) {
- if (minimap_width != p_minimap_width) {
- minimap_width = p_minimap_width;
- _update_wrap_at_column();
+ if (minimap_width == p_minimap_width) {
+ return;
}
+
+ minimap_width = p_minimap_width;
+ _update_wrap_at_column();
update();
}
@@ -4780,6 +4816,11 @@ String TextEdit::get_gutter_name(int p_gutter) const {
void TextEdit::set_gutter_type(int p_gutter, GutterType p_type) {
ERR_FAIL_INDEX(p_gutter, gutters.size());
+
+ if (gutters[p_gutter].type == p_type) {
+ return;
+ }
+
gutters.write[p_gutter].type = p_type;
update();
}
@@ -4823,6 +4864,11 @@ bool TextEdit::is_gutter_drawn(int p_gutter) const {
void TextEdit::set_gutter_clickable(int p_gutter, bool p_clickable) {
ERR_FAIL_INDEX(p_gutter, gutters.size());
+
+ if (gutters[p_gutter].clickable == p_clickable) {
+ return;
+ }
+
gutters.write[p_gutter].clickable = p_clickable;
update();
}
@@ -4878,6 +4924,10 @@ void TextEdit::merge_gutters(int p_from_line, int p_to_line) {
void TextEdit::set_gutter_custom_draw(int p_gutter, const Callable &p_draw_callback) {
ERR_FAIL_INDEX(p_gutter, gutters.size());
+ if (gutters[p_gutter].custom_draw_callback == p_draw_callback) {
+ return;
+ }
+
gutters.write[p_gutter].custom_draw_callback = p_draw_callback;
update();
}
@@ -4898,6 +4948,11 @@ Variant TextEdit::get_line_gutter_metadata(int p_line, int p_gutter) const {
void TextEdit::set_line_gutter_text(int p_line, int p_gutter, const String &p_text) {
ERR_FAIL_INDEX(p_line, text.size());
ERR_FAIL_INDEX(p_gutter, gutters.size());
+
+ if (text.get_line_gutter_text(p_line, p_gutter) == p_text) {
+ return;
+ }
+
text.set_line_gutter_text(p_line, p_gutter, p_text);
update();
}
@@ -4911,6 +4966,11 @@ String TextEdit::get_line_gutter_text(int p_line, int p_gutter) const {
void TextEdit::set_line_gutter_icon(int p_line, int p_gutter, const Ref<Texture2D> &p_icon) {
ERR_FAIL_INDEX(p_line, text.size());
ERR_FAIL_INDEX(p_gutter, gutters.size());
+
+ if (text.get_line_gutter_icon(p_line, p_gutter) == p_icon) {
+ return;
+ }
+
text.set_line_gutter_icon(p_line, p_gutter, p_icon);
update();
}
@@ -4924,6 +4984,11 @@ Ref<Texture2D> TextEdit::get_line_gutter_icon(int p_line, int p_gutter) const {
void TextEdit::set_line_gutter_item_color(int p_line, int p_gutter, const Color &p_color) {
ERR_FAIL_INDEX(p_line, text.size());
ERR_FAIL_INDEX(p_gutter, gutters.size());
+
+ if (text.get_line_gutter_item_color(p_line, p_gutter) == p_color) {
+ return;
+ }
+
text.set_line_gutter_item_color(p_line, p_gutter, p_color);
update();
}
@@ -4949,6 +5014,11 @@ bool TextEdit::is_line_gutter_clickable(int p_line, int p_gutter) const {
// Line style
void TextEdit::set_line_background_color(int p_line, const Color &p_color) {
ERR_FAIL_INDEX(p_line, text.size());
+
+ if (text.get_line_background_color(p_line) == p_color) {
+ return;
+ }
+
text.set_line_background_color(p_line, p_color);
update();
}
@@ -4960,6 +5030,10 @@ Color TextEdit::get_line_background_color(int p_line) const {
/* Syntax Highlighting. */
void TextEdit::set_syntax_highlighter(Ref<SyntaxHighlighter> p_syntax_highlighter) {
+ if (syntax_highlighter == p_syntax_highlighter && syntax_highlighter.is_valid() == p_syntax_highlighter.is_valid()) {
+ return;
+ }
+
syntax_highlighter = p_syntax_highlighter;
if (syntax_highlighter.is_valid()) {
syntax_highlighter->set_text_edit(this);
@@ -4973,6 +5047,10 @@ Ref<SyntaxHighlighter> TextEdit::get_syntax_highlighter() const {
/* Visual. */
void TextEdit::set_highlight_current_line(bool p_enabled) {
+ if (highlight_current_line == p_enabled) {
+ return;
+ }
+
highlight_current_line = p_enabled;
update();
}
@@ -4982,6 +5060,10 @@ bool TextEdit::is_highlight_current_line_enabled() const {
}
void TextEdit::set_highlight_all_occurrences(const bool p_enabled) {
+ if (highlight_all_occurrences == p_enabled) {
+ return;
+ }
+
highlight_all_occurrences = p_enabled;
update();
}
@@ -5008,6 +5090,10 @@ bool TextEdit::get_draw_control_chars() const {
}
void TextEdit::set_draw_tabs(bool p_enabled) {
+ if (draw_tabs == p_enabled) {
+ return;
+ }
+
draw_tabs = p_enabled;
update();
}
@@ -5017,6 +5103,10 @@ bool TextEdit::is_drawing_tabs() const {
}
void TextEdit::set_draw_spaces(bool p_enabled) {
+ if (draw_spaces == p_enabled) {
+ return;
+ }
+
draw_spaces = p_enabled;
update();
}
@@ -5462,6 +5552,10 @@ void TextEdit::_bind_methods() {
/* Internal API for CodeEdit. */
// Line hiding.
void TextEdit::_set_hiding_enabled(bool p_enabled) {
+ if (hiding_enabled == p_enabled) {
+ return;
+ }
+
if (!p_enabled) {
_unhide_all_lines();
}
@@ -5488,6 +5582,11 @@ void TextEdit::_unhide_all_lines() {
void TextEdit::_set_line_as_hidden(int p_line, bool p_hidden) {
ERR_FAIL_INDEX(p_line, text.size());
+
+ if (text.is_hidden(p_line) == p_hidden) {
+ return;
+ }
+
if (_is_hiding_enabled() || !p_hidden) {
text.set_hidden(p_line, p_hidden);
}
@@ -5496,6 +5595,10 @@ void TextEdit::_set_line_as_hidden(int p_line, bool p_hidden) {
// Symbol lookup.
void TextEdit::_set_symbol_lookup_word(const String &p_symbol) {
+ if (lookup_symbol_word == p_symbol) {
+ return;
+ }
+
lookup_symbol_word = p_symbol;
update();
}
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index 6711cf8c7f..f97f99075c 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -195,6 +195,9 @@ private:
void set(int p_line, const String &p_text, const Array &p_bidi_override);
void set_hidden(int p_line, bool p_hidden) {
+ if (text[p_line].hidden == p_hidden) {
+ return;
+ }
text.write[p_line].hidden = p_hidden;
if (!p_hidden && text[p_line].width > max_width) {
max_width = text[p_line].width;
diff --git a/scene/gui/texture_button.cpp b/scene/gui/texture_button.cpp
index 26acfaaa70..916bb2981e 100644
--- a/scene/gui/texture_button.cpp
+++ b/scene/gui/texture_button.cpp
@@ -294,29 +294,48 @@ void TextureButton::_bind_methods() {
}
void TextureButton::set_normal_texture(const Ref<Texture2D> &p_normal) {
+ if (normal == p_normal) {
+ return;
+ }
+
normal = p_normal;
update();
update_minimum_size();
}
void TextureButton::set_pressed_texture(const Ref<Texture2D> &p_pressed) {
+ if (pressed == p_pressed) {
+ return;
+ }
+
pressed = p_pressed;
update();
update_minimum_size();
}
void TextureButton::set_hover_texture(const Ref<Texture2D> &p_hover) {
+ if (hover == p_hover) {
+ return;
+ }
+
hover = p_hover;
update();
update_minimum_size();
}
void TextureButton::set_disabled_texture(const Ref<Texture2D> &p_disabled) {
+ if (disabled == p_disabled) {
+ return;
+ }
+
disabled = p_disabled;
update();
}
void TextureButton::set_click_mask(const Ref<BitMap> &p_click_mask) {
+ if (click_mask == p_click_mask) {
+ return;
+ }
click_mask = p_click_mask;
update();
update_minimum_size();
@@ -355,12 +374,20 @@ bool TextureButton::get_ignore_texture_size() const {
}
void TextureButton::set_ignore_texture_size(bool p_ignore) {
+ if (ignore_texture_size == p_ignore) {
+ return;
+ }
+
ignore_texture_size = p_ignore;
update_minimum_size();
update();
}
void TextureButton::set_stretch_mode(StretchMode p_stretch_mode) {
+ if (stretch_mode == p_stretch_mode) {
+ return;
+ }
+
stretch_mode = p_stretch_mode;
update();
}
@@ -370,6 +397,10 @@ TextureButton::StretchMode TextureButton::get_stretch_mode() const {
}
void TextureButton::set_flip_h(bool p_flip) {
+ if (hflip == p_flip) {
+ return;
+ }
+
hflip = p_flip;
update();
}
@@ -379,6 +410,10 @@ bool TextureButton::is_flipped_h() const {
}
void TextureButton::set_flip_v(bool p_flip) {
+ if (vflip == p_flip) {
+ return;
+ }
+
vflip = p_flip;
update();
}
diff --git a/scene/gui/texture_progress_bar.cpp b/scene/gui/texture_progress_bar.cpp
index 94e0a6f226..2a9e1a8990 100644
--- a/scene/gui/texture_progress_bar.cpp
+++ b/scene/gui/texture_progress_bar.cpp
@@ -33,6 +33,10 @@
#include "core/config/engine.h"
void TextureProgressBar::set_under_texture(const Ref<Texture2D> &p_texture) {
+ if (under == p_texture) {
+ return;
+ }
+
under = p_texture;
update();
update_minimum_size();
@@ -43,6 +47,10 @@ Ref<Texture2D> TextureProgressBar::get_under_texture() const {
}
void TextureProgressBar::set_over_texture(const Ref<Texture2D> &p_texture) {
+ if (over == p_texture) {
+ return;
+ }
+
over = p_texture;
update();
if (under.is_null()) {
@@ -56,6 +64,11 @@ Ref<Texture2D> TextureProgressBar::get_over_texture() const {
void TextureProgressBar::set_stretch_margin(Side p_side, int p_size) {
ERR_FAIL_INDEX((int)p_side, 4);
+
+ if (stretch_margin[p_side] == p_size) {
+ return;
+ }
+
stretch_margin[p_side] = p_size;
update();
update_minimum_size();
@@ -67,6 +80,10 @@ int TextureProgressBar::get_stretch_margin(Side p_side) const {
}
void TextureProgressBar::set_nine_patch_stretch(bool p_stretch) {
+ if (nine_patch_stretch == p_stretch) {
+ return;
+ }
+
nine_patch_stretch = p_stretch;
update();
update_minimum_size();
@@ -91,6 +108,10 @@ Size2 TextureProgressBar::get_minimum_size() const {
}
void TextureProgressBar::set_progress_texture(const Ref<Texture2D> &p_texture) {
+ if (progress == p_texture) {
+ return;
+ }
+
progress = p_texture;
update();
update_minimum_size();
@@ -101,6 +122,10 @@ Ref<Texture2D> TextureProgressBar::get_progress_texture() const {
}
void TextureProgressBar::set_progress_offset(Point2 p_offset) {
+ if (progress_offset == p_offset) {
+ return;
+ }
+
progress_offset = p_offset;
update();
}
@@ -110,6 +135,10 @@ Point2 TextureProgressBar::get_progress_offset() const {
}
void TextureProgressBar::set_tint_under(const Color &p_tint) {
+ if (tint_under == p_tint) {
+ return;
+ }
+
tint_under = p_tint;
update();
}
@@ -119,6 +148,10 @@ Color TextureProgressBar::get_tint_under() const {
}
void TextureProgressBar::set_tint_progress(const Color &p_tint) {
+ if (tint_progress == p_tint) {
+ return;
+ }
+
tint_progress = p_tint;
update();
}
@@ -128,6 +161,10 @@ Color TextureProgressBar::get_tint_progress() const {
}
void TextureProgressBar::set_tint_over(const Color &p_tint) {
+ if (tint_over == p_tint) {
+ return;
+ }
+
tint_over = p_tint;
update();
}
@@ -548,6 +585,11 @@ void TextureProgressBar::_notification(int p_what) {
void TextureProgressBar::set_fill_mode(int p_fill) {
ERR_FAIL_INDEX(p_fill, FILL_MODE_MAX);
+
+ if (mode == (FillMode)p_fill) {
+ return;
+ }
+
mode = (FillMode)p_fill;
update();
}
@@ -563,6 +605,11 @@ void TextureProgressBar::set_radial_initial_angle(float p_angle) {
while (p_angle < 0) {
p_angle += 360;
}
+
+ if (rad_init_angle == p_angle) {
+ return;
+ }
+
rad_init_angle = p_angle;
update();
}
@@ -572,7 +619,13 @@ float TextureProgressBar::get_radial_initial_angle() {
}
void TextureProgressBar::set_fill_degrees(float p_angle) {
- rad_max_degrees = CLAMP(p_angle, 0, 360);
+ float angle_clamped = CLAMP(p_angle, 0, 360);
+
+ if (rad_max_degrees == angle_clamped) {
+ return;
+ }
+
+ rad_max_degrees = angle_clamped;
update();
}
@@ -581,6 +634,10 @@ float TextureProgressBar::get_fill_degrees() {
}
void TextureProgressBar::set_radial_center_offset(const Point2 &p_off) {
+ if (rad_center_off == p_off) {
+ return;
+ }
+
rad_center_off = p_off;
update();
}
diff --git a/scene/gui/texture_rect.cpp b/scene/gui/texture_rect.cpp
index ecdf55caf0..4dd1c74c12 100644
--- a/scene/gui/texture_rect.cpp
+++ b/scene/gui/texture_rect.cpp
@@ -179,6 +179,10 @@ Ref<Texture2D> TextureRect::get_texture() const {
}
void TextureRect::set_ignore_texture_size(bool p_ignore) {
+ if (ignore_texture_size == p_ignore) {
+ return;
+ }
+
ignore_texture_size = p_ignore;
update();
update_minimum_size();
@@ -189,6 +193,10 @@ bool TextureRect::get_ignore_texture_size() const {
}
void TextureRect::set_stretch_mode(StretchMode p_mode) {
+ if (stretch_mode == p_mode) {
+ return;
+ }
+
stretch_mode = p_mode;
update();
}
@@ -198,6 +206,10 @@ TextureRect::StretchMode TextureRect::get_stretch_mode() const {
}
void TextureRect::set_flip_h(bool p_flip) {
+ if (hflip == p_flip) {
+ return;
+ }
+
hflip = p_flip;
update();
}
@@ -207,6 +219,10 @@ bool TextureRect::is_flipped_h() const {
}
void TextureRect::set_flip_v(bool p_flip) {
+ if (vflip == p_flip) {
+ return;
+ }
+
vflip = p_flip;
update();
}
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index 1eb6c5a554..2b19ee4d0b 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -141,6 +141,10 @@ void TreeItem::_change_tree(Tree *p_tree) {
void TreeItem::set_cell_mode(int p_column, TreeCellMode p_mode) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].mode == p_mode) {
+ return;
+ }
+
Cell &c = cells.write[p_column];
c.mode = p_mode;
c.min = 0;
@@ -166,6 +170,10 @@ TreeItem::TreeCellMode TreeItem::get_cell_mode(int p_column) const {
void TreeItem::set_checked(int p_column, bool p_checked) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].checked == p_checked) {
+ return;
+ }
+
cells.write[p_column].checked = p_checked;
cells.write[p_column].indeterminate = false;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -259,6 +267,11 @@ void TreeItem::_propagate_check_through_parents(int p_column, bool p_emit_signal
void TreeItem::set_text(int p_column, String p_text) {
ERR_FAIL_INDEX(p_column, cells.size());
+
+ if (cells[p_column].text == p_text) {
+ return;
+ }
+
cells.write[p_column].text = p_text;
cells.write[p_column].dirty = true;
@@ -290,11 +303,14 @@ String TreeItem::get_text(int p_column) const {
void TreeItem::set_text_direction(int p_column, Control::TextDirection p_text_direction) {
ERR_FAIL_INDEX(p_column, cells.size());
ERR_FAIL_COND((int)p_text_direction < -1 || (int)p_text_direction > 3);
- if (cells[p_column].text_direction != p_text_direction) {
- cells.write[p_column].text_direction = p_text_direction;
- cells.write[p_column].dirty = true;
- _changed_notify(p_column);
+
+ if (cells[p_column].text_direction == p_text_direction) {
+ return;
}
+
+ cells.write[p_column].text_direction = p_text_direction;
+ cells.write[p_column].dirty = true;
+ _changed_notify(p_column);
cells.write[p_column].cached_minimum_size_dirty = true;
}
@@ -323,6 +339,10 @@ TextServer::StructuredTextParser TreeItem::get_structured_text_bidi_override(int
void TreeItem::set_structured_text_bidi_override_options(int p_column, Array p_args) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].st_args == p_args) {
+ return;
+ }
+
cells.write[p_column].st_args = p_args;
cells.write[p_column].dirty = true;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -355,6 +375,10 @@ String TreeItem::get_language(int p_column) const {
void TreeItem::set_suffix(int p_column, String p_suffix) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].suffix == p_suffix) {
+ return;
+ }
+
cells.write[p_column].suffix = p_suffix;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -369,6 +393,10 @@ String TreeItem::get_suffix(int p_column) const {
void TreeItem::set_icon(int p_column, const Ref<Texture2D> &p_icon) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].icon == p_icon) {
+ return;
+ }
+
cells.write[p_column].icon = p_icon;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -383,6 +411,10 @@ Ref<Texture2D> TreeItem::get_icon(int p_column) const {
void TreeItem::set_icon_region(int p_column, const Rect2 &p_icon_region) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].icon_region == p_icon_region) {
+ return;
+ }
+
cells.write[p_column].icon_region = p_icon_region;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -396,6 +428,11 @@ Rect2 TreeItem::get_icon_region(int p_column) const {
void TreeItem::set_icon_modulate(int p_column, const Color &p_modulate) {
ERR_FAIL_INDEX(p_column, cells.size());
+
+ if (cells[p_column].icon_color == p_modulate) {
+ return;
+ }
+
cells.write[p_column].icon_color = p_modulate;
_changed_notify(p_column);
}
@@ -408,6 +445,10 @@ Color TreeItem::get_icon_modulate(int p_column) const {
void TreeItem::set_icon_max_width(int p_column, int p_max) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].icon_max_w == p_max) {
+ return;
+ }
+
cells.write[p_column].icon_max_w = p_max;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -432,6 +473,10 @@ void TreeItem::set_range(int p_column, double p_value) {
p_value = cells[p_column].max;
}
+ if (cells[p_column].val == p_value) {
+ return;
+ }
+
cells.write[p_column].val = p_value;
cells.write[p_column].dirty = true;
_changed_notify(p_column);
@@ -449,6 +494,11 @@ bool TreeItem::is_range_exponential(int p_column) const {
void TreeItem::set_range_config(int p_column, double p_min, double p_max, double p_step, bool p_exp) {
ERR_FAIL_INDEX(p_column, cells.size());
+
+ if (cells[p_column].min == p_min && cells[p_column].max == p_max && cells[p_column].step == p_step && cells[p_column].expr == p_exp) {
+ return;
+ }
+
cells.write[p_column].min = p_min;
cells.write[p_column].max = p_max;
cells.write[p_column].step = p_step;
@@ -537,6 +587,10 @@ void TreeItem::uncollapse_tree() {
}
void TreeItem::set_custom_minimum_height(int p_height) {
+ if (custom_min_height == p_height) {
+ return;
+ }
+
custom_min_height = p_height;
for (Cell &c : cells) {
@@ -748,9 +802,10 @@ int TreeItem::get_child_count() {
return children_cache.size();
}
-Array TreeItem::get_children() {
+TypedArray<TreeItem> TreeItem::get_children() {
+ // Don't need to explicitly create children cache, because get_child_count creates it.
int size = get_child_count();
- Array arr;
+ TypedArray<TreeItem> arr;
arr.resize(size);
for (int i = 0; i < size; i++) {
arr[i] = children_cache[i];
@@ -770,6 +825,22 @@ int TreeItem::get_index() {
return idx - 1;
}
+#ifdef DEV_ENABLED
+void TreeItem::validate_cache() const {
+ if (!parent || parent->children_cache.is_empty()) {
+ return;
+ }
+ TreeItem *scan = parent->first_child;
+ int index = 0;
+ while (scan) {
+ DEV_ASSERT(parent->children_cache[index] == scan);
+ ++index;
+ scan = scan->get_next();
+ }
+ DEV_ASSERT(index == parent->children_cache.size());
+}
+#endif
+
void TreeItem::move_before(TreeItem *p_item) {
ERR_FAIL_NULL(p_item);
ERR_FAIL_COND(is_root);
@@ -797,7 +868,11 @@ void TreeItem::move_before(TreeItem *p_item) {
parent->children_cache.clear();
} else {
parent->first_child = this;
- parent->children_cache.insert(0, this);
+ // If the cache is empty, it has not been built but there
+ // are items in the tree (note p_item != nullptr,) so we cannot update it.
+ if (!parent->children_cache.is_empty()) {
+ parent->children_cache.insert(0, this);
+ }
}
prev = item_prev;
@@ -807,6 +882,8 @@ void TreeItem::move_before(TreeItem *p_item) {
if (tree && old_tree == tree) {
tree->update();
}
+
+ validate_cache();
}
void TreeItem::move_after(TreeItem *p_item) {
@@ -839,12 +916,17 @@ void TreeItem::move_after(TreeItem *p_item) {
if (next) {
parent->children_cache.clear();
} else {
- parent->children_cache.append(this);
+ // If the cache is empty, it has not been built but there
+ // are items in the tree (note p_item != nullptr,) so we cannot update it.
+ if (!parent->children_cache.is_empty()) {
+ parent->children_cache.append(this);
+ }
}
if (tree && old_tree == tree) {
tree->update();
}
+ validate_cache();
}
void TreeItem::remove_child(TreeItem *p_item) {
@@ -859,6 +941,7 @@ void TreeItem::remove_child(TreeItem *p_item) {
if (tree) {
tree->update();
}
+ validate_cache();
}
void TreeItem::set_selectable(int p_column, bool p_selectable) {
@@ -884,6 +967,9 @@ void TreeItem::set_as_cursor(int p_column) {
if (tree->select_mode != Tree::SELECT_MULTI) {
return;
}
+ if (tree->selected_col == p_column) {
+ return;
+ }
tree->selected_item = this;
tree->selected_col = p_column;
tree->update();
@@ -961,6 +1047,11 @@ void TreeItem::set_button(int p_column, int p_idx, const Ref<Texture2D> &p_butto
ERR_FAIL_COND(p_button.is_null());
ERR_FAIL_INDEX(p_column, cells.size());
ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+
+ if (cells[p_column].buttons[p_idx].texture == p_button) {
+ return;
+ }
+
cells.write[p_column].buttons.write[p_idx].texture = p_button;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -970,6 +1061,11 @@ void TreeItem::set_button(int p_column, int p_idx, const Ref<Texture2D> &p_butto
void TreeItem::set_button_color(int p_column, int p_idx, const Color &p_color) {
ERR_FAIL_INDEX(p_column, cells.size());
ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+
+ if (cells[p_column].buttons[p_idx].color == p_color) {
+ return;
+ }
+
cells.write[p_column].buttons.write[p_idx].color = p_color;
_changed_notify(p_column);
}
@@ -978,6 +1074,10 @@ void TreeItem::set_button_disabled(int p_column, int p_idx, bool p_disabled) {
ERR_FAIL_INDEX(p_column, cells.size());
ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+ if (cells[p_column].buttons[p_idx].disabled == p_disabled) {
+ return;
+ }
+
cells.write[p_column].buttons.write[p_idx].disabled = p_disabled;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -994,6 +1094,10 @@ bool TreeItem::is_button_disabled(int p_column, int p_idx) const {
void TreeItem::set_editable(int p_column, bool p_editable) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].editable == p_editable) {
+ return;
+ }
+
cells.write[p_column].editable = p_editable;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -1007,6 +1111,11 @@ bool TreeItem::is_editable(int p_column) {
void TreeItem::set_custom_color(int p_column, const Color &p_color) {
ERR_FAIL_INDEX(p_column, cells.size());
+
+ if (cells[p_column].custom_color == true) {
+ return;
+ }
+
cells.write[p_column].custom_color = true;
cells.write[p_column].color = p_color;
_changed_notify(p_column);
@@ -1063,6 +1172,11 @@ String TreeItem::get_tooltip(int p_column) const {
void TreeItem::set_custom_bg_color(int p_column, const Color &p_color, bool p_bg_outline) {
ERR_FAIL_INDEX(p_column, cells.size());
+
+ if (cells[p_column].custom_bg_color && cells[p_column].custom_bg_outline == p_bg_outline && cells[p_column].bg_color == p_color) {
+ return;
+ }
+
cells.write[p_column].custom_bg_color = true;
cells.write[p_column].custom_bg_outline = p_bg_outline;
cells.write[p_column].bg_color = p_color;
@@ -1099,6 +1213,10 @@ bool TreeItem::is_custom_set_as_button(int p_column) const {
void TreeItem::set_text_alignment(int p_column, HorizontalAlignment p_alignment) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].text_alignment == p_alignment) {
+ return;
+ }
+
cells.write[p_column].text_alignment = p_alignment;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -1113,6 +1231,10 @@ HorizontalAlignment TreeItem::get_text_alignment(int p_column) const {
void TreeItem::set_expand_right(int p_column, bool p_enable) {
ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].expand_right == p_enable) {
+ return;
+ }
+
cells.write[p_column].expand_right = p_enable;
cells.write[p_column].cached_minimum_size_dirty = true;
@@ -1125,6 +1247,10 @@ bool TreeItem::get_expand_right(int p_column) const {
}
void TreeItem::set_disable_folding(bool p_disable) {
+ if (disable_folding == p_disable) {
+ return;
+ }
+
disable_folding = p_disable;
for (Cell &c : cells) {
@@ -1396,6 +1522,7 @@ TreeItem::TreeItem(Tree *p_tree) {
TreeItem::~TreeItem() {
_unlink_from_tree();
+ validate_cache();
prev = nullptr;
clear_children();
_change_tree(nullptr);
@@ -3310,7 +3437,8 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
bool rtl = is_layout_rtl();
if (!mb->is_pressed()) {
- if (mb->get_button_index() == MouseButton::LEFT) {
+ if (mb->get_button_index() == MouseButton::LEFT ||
+ mb->get_button_index() == MouseButton::RIGHT) {
Point2 pos = mb->get_position();
if (rtl) {
pos.x = get_size().width - pos.x;
@@ -3324,14 +3452,16 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
int len = 0;
for (int i = 0; i < columns.size(); i++) {
len += get_column_width(i);
- if (pos.x < len) {
- emit_signal(SNAME("column_title_pressed"), i);
+ if (pos.x < static_cast<real_t>(len)) {
+ emit_signal(SNAME("column_title_clicked"), i, mb->get_button_index());
break;
}
}
}
}
+ }
+ if (mb->get_button_index() == MouseButton::LEFT) {
if (single_select_defer) {
select_single_item(single_select_defer, root, single_select_defer_column);
single_select_defer = nullptr;
@@ -3419,18 +3549,15 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
pos.y -= _get_title_button_height();
if (pos.y < 0) {
- if (mb->get_button_index() == MouseButton::LEFT) {
- pos.x += cache.offset.x;
- int len = 0;
- for (int i = 0; i < columns.size(); i++) {
- len += get_column_width(i);
- if (pos.x < len) {
- cache.click_type = Cache::CLICK_TITLE;
- cache.click_index = i;
- //cache.click_id=;
- update();
- break;
- }
+ pos.x += cache.offset.x;
+ int len = 0;
+ for (int i = 0; i < columns.size(); i++) {
+ len += get_column_width(i);
+ if (pos.x < static_cast<real_t>(len)) {
+ cache.click_type = Cache::CLICK_TITLE;
+ cache.click_index = i;
+ update();
+ break;
}
}
break;
@@ -3591,12 +3718,17 @@ bool Tree::edit_selected() {
} else if (c.mode == TreeItem::CELL_MODE_STRING || c.mode == TreeItem::CELL_MODE_RANGE) {
Rect2 popup_rect;
- Vector2 ofs(0, (text_editor->get_size().height - rect.size.height) / 2);
+ Vector2 ofs(0, Math::floor((text_editor->get_size().height - rect.size.height) / 2)); // "floor()" centers vertically.
Point2i textedpos = get_screen_position() + rect.position - ofs;
cache.text_editor_position = textedpos;
popup_rect.position = textedpos;
popup_rect.size = rect.size;
+
+ // Account for icon.
+ popup_rect.position.x += c.get_icon_size().x;
+ popup_rect.size.x -= c.get_icon_size().x;
+
text_editor->clear();
text_editor->set_text(c.mode == TreeItem::CELL_MODE_STRING ? c.text : String::num(c.val, Math::range_step_decimals(c.step)));
text_editor->select_all();
@@ -4068,6 +4200,10 @@ void Tree::clear() {
};
void Tree::set_hide_root(bool p_enabled) {
+ if (hide_root == p_enabled) {
+ return;
+ }
+
hide_root = p_enabled;
update();
}
@@ -4079,6 +4215,10 @@ bool Tree::is_root_hidden() const {
void Tree::set_column_custom_minimum_width(int p_column, int p_min_width) {
ERR_FAIL_INDEX(p_column, columns.size());
+ if (columns[p_column].custom_min_width == p_min_width) {
+ return;
+ }
+
if (p_min_width < 0) {
return;
}
@@ -4089,12 +4229,21 @@ void Tree::set_column_custom_minimum_width(int p_column, int p_min_width) {
void Tree::set_column_expand(int p_column, bool p_expand) {
ERR_FAIL_INDEX(p_column, columns.size());
+ if (columns[p_column].expand == p_expand) {
+ return;
+ }
+
columns.write[p_column].expand = p_expand;
update();
}
void Tree::set_column_expand_ratio(int p_column, int p_ratio) {
ERR_FAIL_INDEX(p_column, columns.size());
+
+ if (columns[p_column].expand_ratio == p_ratio) {
+ return;
+ }
+
columns.write[p_column].expand_ratio = p_ratio;
update();
}
@@ -4102,6 +4251,10 @@ void Tree::set_column_expand_ratio(int p_column, int p_ratio) {
void Tree::set_column_clip_content(int p_column, bool p_fit) {
ERR_FAIL_INDEX(p_column, columns.size());
+ if (columns[p_column].clip_content == p_fit) {
+ return;
+ }
+
columns.write[p_column].clip_content = p_fit;
update();
}
@@ -4424,6 +4577,10 @@ Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column, int p_button) const {
}
void Tree::set_column_titles_visible(bool p_show) {
+ if (show_column_titles == p_show) {
+ return;
+ }
+
show_column_titles = p_show;
update();
}
@@ -4434,6 +4591,11 @@ bool Tree::are_column_titles_visible() const {
void Tree::set_column_title(int p_column, const String &p_title) {
ERR_FAIL_INDEX(p_column, columns.size());
+
+ if (columns[p_column].title == p_title) {
+ return;
+ }
+
if (cache.font.is_null()) { // avoid a strange case that may corrupt stuff
update_cache();
}
@@ -4515,6 +4677,10 @@ void Tree::scroll_to_item(TreeItem *p_item, bool p_center_on_item) {
}
void Tree::set_h_scroll_enabled(bool p_enable) {
+ if (h_scroll_enabled == p_enable) {
+ return;
+ }
+
h_scroll_enabled = p_enable;
update_minimum_size();
}
@@ -4524,6 +4690,10 @@ bool Tree::is_h_scroll_enabled() const {
}
void Tree::set_v_scroll_enabled(bool p_enable) {
+ if (v_scroll_enabled == p_enable) {
+ return;
+ }
+
v_scroll_enabled = p_enable;
update_minimum_size();
}
@@ -4852,6 +5022,10 @@ void Tree::set_cursor_can_exit_tree(bool p_enable) {
}
void Tree::set_hide_folding(bool p_hide) {
+ if (hide_folding == p_hide) {
+ return;
+ }
+
hide_folding = p_hide;
update();
}
@@ -4997,7 +5171,7 @@ void Tree::_bind_methods() {
ADD_SIGNAL(MethodInfo("button_clicked", PropertyInfo(Variant::OBJECT, "item", PROPERTY_HINT_RESOURCE_TYPE, "TreeItem"), PropertyInfo(Variant::INT, "column"), PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "mouse_button_index")));
ADD_SIGNAL(MethodInfo("custom_popup_edited", PropertyInfo(Variant::BOOL, "arrow_clicked")));
ADD_SIGNAL(MethodInfo("item_activated"));
- ADD_SIGNAL(MethodInfo("column_title_pressed", PropertyInfo(Variant::INT, "column")));
+ ADD_SIGNAL(MethodInfo("column_title_clicked", PropertyInfo(Variant::INT, "column"), PropertyInfo(Variant::INT, "mouse_button_index")));
ADD_SIGNAL(MethodInfo("nothing_selected"));
BIND_ENUM_CONSTANT(SELECT_SINGLE);
diff --git a/scene/gui/tree.h b/scene/gui/tree.h
index f0819e2980..7f9c00b1b9 100644
--- a/scene/gui/tree.h
+++ b/scene/gui/tree.h
@@ -339,9 +339,16 @@ public:
TreeItem *get_child(int p_idx);
int get_visible_child_count();
int get_child_count();
- Array get_children();
+ TypedArray<TreeItem> get_children();
int get_index();
+#ifdef DEV_ENABLED
+ // This debugging code can be removed once the current refactoring of this class is complete.
+ void validate_cache() const;
+#else
+ void validate_cache() const {}
+#endif
+
void move_before(TreeItem *p_item);
void move_after(TreeItem *p_item);
diff --git a/scene/gui/video_stream_player.cpp b/scene/gui/video_stream_player.cpp
index f20a2ad67b..7baa4d44aa 100644
--- a/scene/gui/video_stream_player.cpp
+++ b/scene/gui/video_stream_player.cpp
@@ -208,6 +208,10 @@ Size2 VideoStreamPlayer::get_minimum_size() const {
}
void VideoStreamPlayer::set_expand(bool p_expand) {
+ if (expand == p_expand) {
+ return;
+ }
+
expand = p_expand;
update();
update_minimum_size();
@@ -306,6 +310,10 @@ bool VideoStreamPlayer::is_playing() const {
}
void VideoStreamPlayer::set_paused(bool p_paused) {
+ if (paused == p_paused) {
+ return;
+ }
+
paused = p_paused;
if (!p_paused && !can_process()) {
paused_from_tree = true;
diff --git a/scene/gui/video_stream_player.h b/scene/gui/video_stream_player.h
index 913e7905b6..9974eb8488 100644
--- a/scene/gui/video_stream_player.h
+++ b/scene/gui/video_stream_player.h
@@ -79,7 +79,7 @@ class VideoStreamPlayer : public Control {
protected:
static void _bind_methods();
void _notification(int p_notification);
- void _validate_property(PropertyInfo &p_property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
Size2 get_minimum_size() const override;
diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp
index ce204c6aeb..dcf506aafa 100644
--- a/scene/main/canvas_item.cpp
+++ b/scene/main/canvas_item.cpp
@@ -986,7 +986,7 @@ void CanvasItem::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask", "get_light_mask");
ADD_GROUP("Texture", "texture_");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Inherit,Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Aniso.,Linear Mipmap Aniso."), "set_texture_filter", "get_texture_filter");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Inherit,Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Anisotropic,Linear Mipmap Anisotropic"), "set_texture_filter", "get_texture_filter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_repeat", PROPERTY_HINT_ENUM, "Inherit,Disabled,Enabled,Mirror"), "set_texture_repeat", "get_texture_repeat");
ADD_GROUP("Material", "");
@@ -1326,7 +1326,7 @@ void CanvasTexture::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "specular_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_specular_color", "get_specular_color");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "specular_shininess", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_specular_shininess", "get_specular_shininess");
ADD_GROUP("Texture", "texture_");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Inherit,Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Aniso.,Linear Mipmap Aniso."), "set_texture_filter", "get_texture_filter");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Inherit,Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Anisotropic,Linear Mipmap Anisotropic"), "set_texture_filter", "get_texture_filter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_repeat", PROPERTY_HINT_ENUM, "Inherit,Disabled,Enabled,Mirror"), "set_texture_repeat", "get_texture_repeat");
}
diff --git a/scene/main/canvas_layer.cpp b/scene/main/canvas_layer.cpp
index 3a071ef542..4890db995a 100644
--- a/scene/main/canvas_layer.cpp
+++ b/scene/main/canvas_layer.cpp
@@ -286,9 +286,9 @@ void CanvasLayer::_update_follow_viewport(bool p_force_exit) {
}
}
-void CanvasLayer::_validate_property(PropertyInfo &property) const {
- if (!follow_viewport && property.name == "follow_viewport_scale") {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void CanvasLayer::_validate_property(PropertyInfo &p_property) const {
+ if (!follow_viewport && p_property.name == "follow_viewport_scale") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
@@ -335,7 +335,7 @@ void CanvasLayer::_bind_methods() {
ADD_GROUP("", "");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "custom_viewport", PROPERTY_HINT_RESOURCE_TYPE, "Viewport", PROPERTY_USAGE_NONE), "set_custom_viewport", "get_custom_viewport");
ADD_GROUP("Follow Viewport", "follow_viewport");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "follow_viewport_enable"), "set_follow_viewport", "is_following_viewport");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "follow_viewport_enabled"), "set_follow_viewport", "is_following_viewport");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "follow_viewport_scale", PROPERTY_HINT_RANGE, "0.001,1000,0.001,or_greater,or_lesser"), "set_follow_viewport_scale", "get_follow_viewport_scale");
ADD_SIGNAL(MethodInfo("visibility_changed"));
diff --git a/scene/main/canvas_layer.h b/scene/main/canvas_layer.h
index 2493675b31..74b5ebd453 100644
--- a/scene/main/canvas_layer.h
+++ b/scene/main/canvas_layer.h
@@ -64,7 +64,7 @@ class CanvasLayer : public Node {
protected:
void _notification(int p_what);
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_layer(int p_xform);
diff --git a/scene/main/multiplayer_api.cpp b/scene/main/multiplayer_api.cpp
index 95574042a8..2d2103f031 100644
--- a/scene/main/multiplayer_api.cpp
+++ b/scene/main/multiplayer_api.cpp
@@ -59,18 +59,18 @@ Ref<MultiplayerAPI> MultiplayerAPI::create_default_interface() {
// The variant is compressed and encoded; The first byte contains all the meta
// information and the format is:
-// - The first LSB 5 bits are used for the variant type.
+// - The first LSB 6 bits are used for the variant type.
// - The next two bits are used to store the encoding mode.
-// - The most significant is used to store the boolean value.
-#define VARIANT_META_TYPE_MASK 0x1F
-#define VARIANT_META_EMODE_MASK 0x60
+// - Boolean values uses the encoding mode to store the value.
+#define VARIANT_META_TYPE_MASK 0x3F
+#define VARIANT_META_EMODE_MASK 0xC0
#define VARIANT_META_BOOL_MASK 0x80
-#define ENCODE_8 0 << 5
-#define ENCODE_16 1 << 5
-#define ENCODE_32 2 << 5
-#define ENCODE_64 3 << 5
+#define ENCODE_8 0 << 6
+#define ENCODE_16 1 << 6
+#define ENCODE_32 2 << 6
+#define ENCODE_64 3 << 6
Error MultiplayerAPI::encode_and_compress_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bool p_allow_object_decoding) {
- // Unreachable because `VARIANT_MAX` == 27 and `ENCODE_VARIANT_MASK` == 31
+ // Unreachable because `VARIANT_MAX` == 38 and `ENCODE_VARIANT_MASK` == 77
CRASH_COND(p_variant.get_type() > VARIANT_META_TYPE_MASK);
uint8_t *buf = r_buffer;
@@ -80,9 +80,9 @@ Error MultiplayerAPI::encode_and_compress_variant(const Variant &p_variant, uint
switch (p_variant.get_type()) {
case Variant::BOOL: {
if (buf) {
- // We still have 1 free bit in the meta, so let's use it.
+ // We don't use encode_mode for booleans, so we can use it to store the value.
buf[0] = (p_variant.operator bool()) ? (1 << 7) : 0;
- buf[0] |= encode_mode | p_variant.get_type();
+ buf[0] |= p_variant.get_type();
}
r_len += 1;
} break;
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index ea9788de27..9773218574 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -1778,8 +1778,8 @@ void Node::remove_from_group(const StringName &p_identifier) {
data.grouped.remove(E);
}
-Array Node::_get_groups() const {
- Array groups;
+TypedArray<StringName> Node::_get_groups() const {
+ TypedArray<StringName> groups;
List<GroupInfo> gi;
get_groups(&gi);
for (const GroupInfo &E : gi) {
diff --git a/scene/main/node.h b/scene/main/node.h
index ccd1d561d2..52ccf3d825 100644
--- a/scene/main/node.h
+++ b/scene/main/node.h
@@ -181,7 +181,7 @@ private:
Node *_duplicate(int p_flags, HashMap<const Node *, Node *> *r_duplimap = nullptr) const;
TypedArray<Node> _get_children(bool p_include_internal = true) const;
- Array _get_groups() const;
+ TypedArray<StringName> _get_groups() const;
Error _rpc_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
Error _rpc_id_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp
index 644fb3e9cc..109799e23a 100644
--- a/scene/main/scene_tree.cpp
+++ b/scene/main/scene_tree.cpp
@@ -1000,8 +1000,8 @@ int64_t SceneTree::get_frame() const {
return current_frame;
}
-Array SceneTree::_get_nodes_in_group(const StringName &p_group) {
- Array ret;
+TypedArray<Node> SceneTree::_get_nodes_in_group(const StringName &p_group) {
+ TypedArray<Node> ret;
HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
if (!E) {
return ret;
@@ -1171,8 +1171,8 @@ Ref<Tween> SceneTree::create_tween() {
return tween;
}
-Array SceneTree::get_processed_tweens() {
- Array ret;
+TypedArray<Tween> SceneTree::get_processed_tweens() {
+ TypedArray<Tween> ret;
ret.resize(tweens.size());
int i = 0;
diff --git a/scene/main/scene_tree.h b/scene/main/scene_tree.h
index a512feacc8..e66363ab33 100644
--- a/scene/main/scene_tree.h
+++ b/scene/main/scene_tree.h
@@ -141,7 +141,7 @@ private:
_FORCE_INLINE_ void _update_group_order(Group &g, bool p_use_priority = false);
- Array _get_nodes_in_group(const StringName &p_group);
+ TypedArray<Node> _get_nodes_in_group(const StringName &p_group);
Node *current_scene = nullptr;
@@ -367,7 +367,7 @@ public:
Ref<SceneTreeTimer> create_timer(double p_delay_sec, bool p_process_always = true);
Ref<Tween> create_tween();
- Array get_processed_tweens();
+ TypedArray<Tween> get_processed_tweens();
//used by Main::start, don't use otherwise
void add_current_scene(Node *p_current);
diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp
index 584fad9648..36cc8ebfa2 100644
--- a/scene/main/viewport.cpp
+++ b/scene/main/viewport.cpp
@@ -798,6 +798,7 @@ void Viewport::_set_size(const Size2i &p_size, const Size2i &p_size_2d_override,
RS::get_singleton()->viewport_set_size(viewport, 0, 0);
}
_update_global_transform();
+ update_configuration_warnings();
update_canvas_items();
@@ -1875,7 +1876,9 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
}
- DisplayServer::get_singleton()->cursor_set_shape(ds_cursor_shape);
+ if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_CURSOR_SHAPE)) {
+ DisplayServer::get_singleton()->cursor_set_shape(ds_cursor_shape);
+ }
}
Ref<InputEventScreenTouch> touch_event = p_event;
@@ -2684,7 +2687,9 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
DisplayServer::CURSOR_FDIAGSIZE
};
- DisplayServer::get_singleton()->cursor_set_shape(shapes[resize]);
+ if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_CURSOR_SHAPE)) {
+ DisplayServer::get_singleton()->cursor_set_shape(shapes[resize]);
+ }
return true; // Reserved for showing the resize cursor.
}
@@ -2849,8 +2854,8 @@ Variant Viewport::gui_get_drag_data() const {
TypedArray<String> Viewport::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
- if (size.x == 0 || size.y == 0) {
- warnings.push_back(RTR("Viewport size must be greater than 0 to render anything."));
+ if (size.x <= 1 || size.y <= 1) {
+ warnings.push_back(RTR("The Viewport size must be greater than or equal to 2 pixels on both dimensions to render anything."));
}
return warnings;
}
@@ -3953,9 +3958,9 @@ void Viewport::_bind_methods() {
BIND_ENUM_CONSTANT(VRS_MAX);
}
-void Viewport::_validate_property(PropertyInfo &property) const {
- if (vrs_mode != VRS_TEXTURE && (property.name == "vrs_texture")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void Viewport::_validate_property(PropertyInfo &p_property) const {
+ if (vrs_mode != VRS_TEXTURE && (p_property.name == "vrs_texture")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
diff --git a/scene/main/viewport.h b/scene/main/viewport.h
index 4221baff06..a0ec2d54dd 100644
--- a/scene/main/viewport.h
+++ b/scene/main/viewport.h
@@ -709,7 +709,7 @@ public:
bool is_using_xr();
#endif // _3D_DISABLED
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
Viewport();
~Viewport();
};
diff --git a/scene/main/window.cpp b/scene/main/window.cpp
index d40b82f5eb..bf50ca0956 100644
--- a/scene/main/window.cpp
+++ b/scene/main/window.cpp
@@ -349,7 +349,9 @@ void Window::_event_callback(DisplayServer::WindowEvent p_event) {
_propagate_window_notification(this, NOTIFICATION_WM_MOUSE_ENTER);
emit_signal(SNAME("mouse_entered"));
notification(NOTIFICATION_VP_MOUSE_ENTER);
- DisplayServer::get_singleton()->cursor_set_shape(DisplayServer::CURSOR_ARROW); //restore cursor shape
+ if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_CURSOR_SHAPE)) {
+ DisplayServer::get_singleton()->cursor_set_shape(DisplayServer::CURSOR_ARROW); //restore cursor shape
+ }
} break;
case DisplayServer::WINDOW_EVENT_MOUSE_EXIT: {
notification(NOTIFICATION_VP_MOUSE_EXIT);
@@ -1510,8 +1512,8 @@ bool Window::is_auto_translating() const {
return auto_translate;
}
-void Window::_validate_property(PropertyInfo &property) const {
- if (property.name == "theme_type_variation") {
+void Window::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "theme_type_variation") {
List<StringName> names;
// Only the default theme and the project theme are used for the list of options.
@@ -1534,7 +1536,7 @@ void Window::_validate_property(PropertyInfo &property) const {
unique_names.append(E);
}
- property.hint_string = hint_string;
+ p_property.hint_string = hint_string;
}
}
diff --git a/scene/main/window.h b/scene/main/window.h
index c060f1d79d..aa32edbb04 100644
--- a/scene/main/window.h
+++ b/scene/main/window.h
@@ -158,7 +158,7 @@ protected:
virtual Size2 _get_contents_minimum_size() const;
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
virtual void add_child_notify(Node *p_child) override;
virtual void remove_child_notify(Node *p_child) override;
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index a5842106fb..62573ed3e8 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -50,6 +50,7 @@
#include "scene/2d/light_2d.h"
#include "scene/2d/light_occluder_2d.h"
#include "scene/2d/line_2d.h"
+#include "scene/2d/marker_2d.h"
#include "scene/2d/mesh_instance_2d.h"
#include "scene/2d/multimesh_instance_2d.h"
#include "scene/2d/navigation_agent_2d.h"
@@ -60,7 +61,6 @@
#include "scene/2d/physical_bone_2d.h"
#include "scene/2d/physics_body_2d.h"
#include "scene/2d/polygon_2d.h"
-#include "scene/2d/position_2d.h"
#include "scene/2d/ray_cast_2d.h"
#include "scene/2d/remote_transform_2d.h"
#include "scene/2d/shape_cast_2d.h"
@@ -100,6 +100,7 @@
#include "scene/gui/line_edit.h"
#include "scene/gui/link_button.h"
#include "scene/gui/margin_container.h"
+#include "scene/gui/menu_bar.h"
#include "scene/gui/menu_button.h"
#include "scene/gui/nine_patch_rect.h"
#include "scene/gui/option_button.h"
@@ -157,8 +158,8 @@
#include "scene/resources/immediate_mesh.h"
#include "scene/resources/label_settings.h"
#include "scene/resources/material.h"
-#include "scene/resources/mesh.h"
#include "scene/resources/mesh_data_tool.h"
+#include "scene/resources/multimesh.h"
#include "scene/resources/navigation_mesh.h"
#include "scene/resources/packed_scene.h"
#include "scene/resources/particles_material.h"
@@ -231,6 +232,7 @@
#include "scene/3d/light_3d.h"
#include "scene/3d/lightmap_gi.h"
#include "scene/3d/lightmap_probe.h"
+#include "scene/3d/marker_3d.h"
#include "scene/3d/mesh_instance_3d.h"
#include "scene/3d/multimesh_instance_3d.h"
#include "scene/3d/navigation_agent_3d.h"
@@ -240,7 +242,6 @@
#include "scene/3d/occluder_instance_3d.h"
#include "scene/3d/path_3d.h"
#include "scene/3d/physics_body_3d.h"
-#include "scene/3d/position_3d.h"
#include "scene/3d/ray_cast_3d.h"
#include "scene/3d/reflection_probe.h"
#include "scene/3d/remote_transform_3d.h"
@@ -259,7 +260,7 @@
#include "scene/resources/fog_material.h"
#include "scene/resources/importer_mesh.h"
#include "scene/resources/mesh_library.h"
-#endif
+#endif // _3D_DISABLED
static Ref<ResourceFormatSaverText> resource_saver_text;
static Ref<ResourceFormatLoaderText> resource_loader_text;
@@ -351,6 +352,7 @@ void register_scene_types() {
GDREGISTER_CLASS(VSlider);
GDREGISTER_CLASS(Popup);
GDREGISTER_CLASS(PopupPanel);
+ GDREGISTER_CLASS(MenuBar);
GDREGISTER_CLASS(MenuButton);
GDREGISTER_CLASS(CheckBox);
GDREGISTER_CLASS(CheckButton);
@@ -522,7 +524,7 @@ void register_scene_types() {
GDREGISTER_CLASS(GPUParticlesAttractorSphere3D);
GDREGISTER_CLASS(GPUParticlesAttractorVectorField3D);
GDREGISTER_CLASS(CPUParticles3D);
- GDREGISTER_CLASS(Position3D);
+ GDREGISTER_CLASS(Marker3D);
GDREGISTER_CLASS(RootMotionView);
OS::get_singleton()->yield(); // may take time to init
@@ -573,7 +575,7 @@ void register_scene_types() {
GDREGISTER_CLASS(NavigationObstacle3D);
OS::get_singleton()->yield(); // may take time to init
-#endif
+#endif // _3D_DISABLED
/* REGISTER SHADER */
@@ -694,7 +696,7 @@ void register_scene_types() {
GDREGISTER_CLASS(Sprite2D);
GDREGISTER_CLASS(SpriteFrames);
GDREGISTER_CLASS(AnimatedSprite2D);
- GDREGISTER_CLASS(Position2D);
+ GDREGISTER_CLASS(Marker2D);
GDREGISTER_CLASS(Line2D);
GDREGISTER_CLASS(MeshInstance2D);
GDREGISTER_CLASS(MultiMeshInstance2D);
@@ -763,10 +765,6 @@ void register_scene_types() {
SceneTree::add_idle_callback(ParticlesMaterial::flush_changes);
ParticlesMaterial::init_shaders();
- GDREGISTER_CLASS(ProceduralSkyMaterial);
- GDREGISTER_CLASS(PanoramaSkyMaterial);
- GDREGISTER_CLASS(PhysicalSkyMaterial);
-
GDREGISTER_VIRTUAL_CLASS(Mesh);
GDREGISTER_CLASS(ArrayMesh);
GDREGISTER_CLASS(PlaceholderMesh);
@@ -782,7 +780,6 @@ void register_scene_types() {
GDREGISTER_CLASS(CylinderMesh);
GDREGISTER_CLASS(PlaneMesh);
GDREGISTER_CLASS(PrismMesh);
- GDREGISTER_CLASS(QuadMesh);
GDREGISTER_CLASS(SphereMesh);
GDREGISTER_CLASS(TextMesh);
GDREGISTER_CLASS(TorusMesh);
@@ -794,6 +791,9 @@ void register_scene_types() {
GDREGISTER_CLASS(StandardMaterial3D);
GDREGISTER_CLASS(ORMMaterial3D);
GDREGISTER_CLASS(PlaceholderMaterial);
+ GDREGISTER_CLASS(ProceduralSkyMaterial);
+ GDREGISTER_CLASS(PanoramaSkyMaterial);
+ GDREGISTER_CLASS(PhysicalSkyMaterial);
SceneTree::add_idle_callback(BaseMaterial3D::flush_changes);
BaseMaterial3D::init_shaders();
@@ -822,9 +822,7 @@ void register_scene_types() {
ClassDB::register_class<SkeletonModification3DStackHolder>();
OS::get_singleton()->yield(); // may take time to init
-
- GDREGISTER_CLASS(VelocityTracker3D);
-#endif
+#endif // _3D_DISABLED
GDREGISTER_CLASS(PhysicsMaterial);
GDREGISTER_CLASS(World3D);
@@ -843,7 +841,6 @@ void register_scene_types() {
GDREGISTER_CLASS(CurveXYZTexture);
GDREGISTER_CLASS(GradientTexture1D);
GDREGISTER_CLASS(GradientTexture2D);
- GDREGISTER_CLASS(ProxyTexture);
GDREGISTER_CLASS(AnimatedTexture);
GDREGISTER_CLASS(CameraTexture);
GDREGISTER_VIRTUAL_CLASS(TextureLayered);
@@ -945,6 +942,7 @@ void register_scene_types() {
ClassDB::add_compatibility_class("Navigation3D", "Node3D");
ClassDB::add_compatibility_class("Navigation2D", "Node2D");
ClassDB::add_compatibility_class("OpenSimplexNoise", "FastNoiseLite");
+ ClassDB::add_compatibility_class("QuadMesh", "PlaneMesh");
ClassDB::add_compatibility_class("ToolButton", "Button");
ClassDB::add_compatibility_class("YSort", "Node2D");
// Portal and room occlusion was replaced by raster occlusion (OccluderInstance3D node).
@@ -1036,6 +1034,8 @@ void register_scene_types() {
ClassDB::add_compatibility_class("PhysicsShapeQueryParameters", "PhysicsShapeQueryParameters3D");
ClassDB::add_compatibility_class("PinJoint", "PinJoint3D");
ClassDB::add_compatibility_class("PlaneShape", "WorldBoundaryShape3D");
+ ClassDB::add_compatibility_class("Position2D", "Marker2D");
+ ClassDB::add_compatibility_class("Position3D", "Marker3D");
ClassDB::add_compatibility_class("ProceduralSky", "Sky");
ClassDB::add_compatibility_class("RayCast", "RayCast3D");
ClassDB::add_compatibility_class("RayShape", "SeparationRayShape3D");
@@ -1052,7 +1052,6 @@ void register_scene_types() {
ClassDB::add_compatibility_class("Spatial", "Node3D");
ClassDB::add_compatibility_class("SpatialGizmo", "Node3DGizmo");
ClassDB::add_compatibility_class("SpatialMaterial", "StandardMaterial3D");
- ClassDB::add_compatibility_class("SpatialVelocityTracker", "VelocityTracker3D");
ClassDB::add_compatibility_class("SphereShape", "SphereShape3D");
ClassDB::add_compatibility_class("SpotLight", "SpotLight3D");
ClassDB::add_compatibility_class("SpringArm", "SpringArm3D");
@@ -1205,11 +1204,10 @@ void unregister_scene_types() {
// StandardMaterial3D is not initialised when 3D is disabled, so it shouldn't be cleaned up either
#ifndef _3D_DISABLED
BaseMaterial3D::finish_shaders();
-#endif // _3D_DISABLED
-
PhysicalSkyMaterial::cleanup_shader();
PanoramaSkyMaterial::cleanup_shader();
ProceduralSkyMaterial::cleanup_shader();
+#endif // _3D_DISABLED
ParticlesMaterial::finish_shaders();
CanvasItemMaterial::finish_shaders();
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index 69b30b72b0..da59c4dbd1 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -313,29 +313,37 @@ bool Animation::_set(const StringName &p_name, const Variant &p_value) {
Dictionary d = p_value;
ERR_FAIL_COND_V(!d.has("times"), false);
ERR_FAIL_COND_V(!d.has("points"), false);
-
Vector<real_t> times = d["times"];
Vector<real_t> values = d["points"];
+#ifdef TOOLS_ENABLED
+ ERR_FAIL_COND_V(!d.has("handle_modes"), false);
+ Vector<int> handle_modes = d["handle_modes"];
+#endif // TOOLS_ENABLED
- ERR_FAIL_COND_V(times.size() * 6 != values.size(), false);
+ ERR_FAIL_COND_V(times.size() * 5 != values.size(), false);
if (times.size()) {
int valcount = times.size();
const real_t *rt = times.ptr();
const real_t *rv = values.ptr();
+#ifdef TOOLS_ENABLED
+ const int *rh = handle_modes.ptr();
+#endif // TOOLS_ENABLED
bt->values.resize(valcount);
for (int i = 0; i < valcount; i++) {
bt->values.write[i].time = rt[i];
bt->values.write[i].transition = 0; //unused in bezier
- bt->values.write[i].value.value = rv[i * 6 + 0];
- bt->values.write[i].value.in_handle.x = rv[i * 6 + 1];
- bt->values.write[i].value.in_handle.y = rv[i * 6 + 2];
- bt->values.write[i].value.out_handle.x = rv[i * 6 + 3];
- bt->values.write[i].value.out_handle.y = rv[i * 6 + 4];
- bt->values.write[i].value.handle_mode = static_cast<HandleMode>((int)rv[i * 6 + 5]);
+ bt->values.write[i].value.value = rv[i * 5 + 0];
+ bt->values.write[i].value.in_handle.x = rv[i * 5 + 1];
+ bt->values.write[i].value.in_handle.y = rv[i * 5 + 2];
+ bt->values.write[i].value.out_handle.x = rv[i * 5 + 3];
+ bt->values.write[i].value.out_handle.y = rv[i * 5 + 4];
+#ifdef TOOLS_ENABLED
+ bt->values.write[i].value.handle_mode = static_cast<HandleMode>(rh[i]);
+#endif // TOOLS_ENABLED
}
}
@@ -699,28 +707,39 @@ bool Animation::_get(const StringName &p_name, Variant &r_ret) const {
int kk = bt->values.size();
key_times.resize(kk);
- key_points.resize(kk * 6);
+ key_points.resize(kk * 5);
real_t *wti = key_times.ptrw();
real_t *wpo = key_points.ptrw();
+#ifdef TOOLS_ENABLED
+ Vector<int> handle_modes;
+ handle_modes.resize(kk);
+ int *whm = handle_modes.ptrw();
+#endif // TOOLS_ENABLED
+
int idx = 0;
const TKey<BezierKey> *vls = bt->values.ptr();
for (int i = 0; i < kk; i++) {
wti[idx] = vls[i].time;
- wpo[idx * 6 + 0] = vls[i].value.value;
- wpo[idx * 6 + 1] = vls[i].value.in_handle.x;
- wpo[idx * 6 + 2] = vls[i].value.in_handle.y;
- wpo[idx * 6 + 3] = vls[i].value.out_handle.x;
- wpo[idx * 6 + 4] = vls[i].value.out_handle.y;
- wpo[idx * 6 + 5] = (double)vls[i].value.handle_mode;
+ wpo[idx * 5 + 0] = vls[i].value.value;
+ wpo[idx * 5 + 1] = vls[i].value.in_handle.x;
+ wpo[idx * 5 + 2] = vls[i].value.in_handle.y;
+ wpo[idx * 5 + 3] = vls[i].value.out_handle.x;
+ wpo[idx * 5 + 4] = vls[i].value.out_handle.y;
+#ifdef TOOLS_ENABLED
+ whm[idx] = static_cast<int>(vls[i].value.handle_mode);
+#endif // TOOLS_ENABLED
idx++;
}
d["times"] = key_times;
d["points"] = key_points;
+#ifdef TOOLS_ENABLED
+ d["handle_modes"] = handle_modes;
+#endif // TOOLS_ENABLED
r_ret = d;
@@ -967,7 +986,6 @@ int Animation::find_track(const NodePath &p_path, const TrackType p_type) const
void Animation::track_set_interpolation_type(int p_track, InterpolationType p_interp) {
ERR_FAIL_INDEX(p_track, tracks.size());
- ERR_FAIL_INDEX(p_interp, 3);
tracks[p_track]->interpolation = p_interp;
emit_changed();
}
@@ -1627,7 +1645,7 @@ int Animation::track_insert_key(int p_track, double p_time, const Variant &p_key
BezierTrack *bt = static_cast<BezierTrack *>(t);
Array arr = p_key;
- ERR_FAIL_COND_V(arr.size() != 6, -1);
+ ERR_FAIL_COND_V(arr.size() != 5, -1);
TKey<BezierKey> k;
k.time = p_time;
@@ -1636,9 +1654,16 @@ int Animation::track_insert_key(int p_track, double p_time, const Variant &p_key
k.value.in_handle.y = arr[2];
k.value.out_handle.x = arr[3];
k.value.out_handle.y = arr[4];
- k.value.handle_mode = static_cast<HandleMode>((int)arr[5]);
ret = _insert(p_time, bt->values, k);
+ Vector<int> key_neighborhood;
+ key_neighborhood.push_back(ret);
+ if (ret > 0) {
+ key_neighborhood.push_back(ret - 1);
+ }
+ if (ret < track_get_key_count(p_track) - 1) {
+ key_neighborhood.push_back(ret + 1);
+ }
} break;
case TYPE_AUDIO: {
AudioTrack *at = static_cast<AudioTrack *>(t);
@@ -1777,13 +1802,12 @@ Variant Animation::track_get_key_value(int p_track, int p_key_idx) const {
ERR_FAIL_INDEX_V(p_key_idx, bt->values.size(), Variant());
Array arr;
- arr.resize(6);
+ arr.resize(5);
arr[0] = bt->values[p_key_idx].value.value;
arr[1] = bt->values[p_key_idx].value.in_handle.x;
arr[2] = bt->values[p_key_idx].value.in_handle.y;
arr[3] = bt->values[p_key_idx].value.out_handle.x;
arr[4] = bt->values[p_key_idx].value.out_handle.y;
- arr[5] = (double)bt->values[p_key_idx].value.handle_mode;
return arr;
} break;
@@ -2152,14 +2176,13 @@ void Animation::track_set_key_value(int p_track, int p_key_idx, const Variant &p
ERR_FAIL_INDEX(p_key_idx, bt->values.size());
Array arr = p_value;
- ERR_FAIL_COND(arr.size() != 6);
+ ERR_FAIL_COND(arr.size() != 5);
bt->values.write[p_key_idx].value.value = arr[0];
bt->values.write[p_key_idx].value.in_handle.x = arr[1];
bt->values.write[p_key_idx].value.in_handle.y = arr[2];
bt->values.write[p_key_idx].value.out_handle.x = arr[3];
bt->values.write[p_key_idx].value.out_handle.y = arr[4];
- bt->values.write[p_key_idx].value.handle_mode = static_cast<HandleMode>((int)arr[5]);
} break;
case TYPE_AUDIO: {
@@ -2283,6 +2306,8 @@ int Animation::_find(const Vector<K> &p_keys, double p_time, bool p_backward) co
return middle;
}
+// Linear interpolation for anytype.
+
Vector3 Animation::_interpolate(const Vector3 &p_a, const Vector3 &p_b, real_t p_c) const {
return p_a.lerp(p_b, p_c);
}
@@ -2301,6 +2326,8 @@ real_t Animation::_interpolate(const real_t &p_a, const real_t &p_b, real_t p_c)
return p_a * (1.0 - p_c) + p_b * p_c;
}
+// Cubic interpolation for anytype.
+
Vector3 Animation::_cubic_interpolate(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, real_t p_c) const {
return p_a.cubic_interpolate(p_b, p_pre_a, p_post_b, p_c);
}
@@ -2389,6 +2416,96 @@ real_t Animation::_cubic_interpolate(const real_t &p_pre_a, const real_t &p_a, c
return _interpolate(p_a, p_b, p_c);
}
+// Cubic interpolation in time for anytype.
+
+Vector3 Animation::_cubic_interpolate_in_time(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const {
+ return p_a.cubic_interpolate_in_time(p_b, p_pre_a, p_post_b, p_c, p_b_t, p_pre_a_t, p_post_b_t);
+}
+
+Quaternion Animation::_cubic_interpolate_in_time(const Quaternion &p_pre_a, const Quaternion &p_a, const Quaternion &p_b, const Quaternion &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const {
+ return p_a.spherical_cubic_interpolate_in_time(p_b, p_pre_a, p_post_b, p_c, p_b_t, p_pre_a_t, p_post_b_t);
+}
+
+Variant Animation::_cubic_interpolate_in_time(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const {
+ Variant::Type type_a = p_a.get_type();
+ Variant::Type type_b = p_b.get_type();
+ Variant::Type type_pa = p_pre_a.get_type();
+ Variant::Type type_pb = p_post_b.get_type();
+
+ //make int and real play along
+
+ uint32_t vformat = 1 << type_a;
+ vformat |= 1 << type_b;
+ vformat |= 1 << type_pa;
+ vformat |= 1 << type_pb;
+
+ if (vformat == ((1 << Variant::INT) | (1 << Variant::FLOAT)) || vformat == (1 << Variant::FLOAT)) {
+ //mix of real and int
+ real_t a = p_a;
+ real_t b = p_b;
+ real_t pa = p_pre_a;
+ real_t pb = p_post_b;
+
+ return Math::cubic_interpolate_in_time(a, b, pa, pb, p_c, p_b_t, p_pre_a_t, p_post_b_t);
+ } else if ((vformat & (vformat - 1))) {
+ return p_a; //can't interpolate, mix of types
+ }
+
+ switch (type_a) {
+ case Variant::VECTOR2: {
+ Vector2 a = p_a;
+ Vector2 b = p_b;
+ Vector2 pa = p_pre_a;
+ Vector2 pb = p_post_b;
+
+ return a.cubic_interpolate_in_time(b, pa, pb, p_c, p_b_t, p_pre_a_t, p_post_b_t);
+ }
+ case Variant::RECT2: {
+ Rect2 a = p_a;
+ Rect2 b = p_b;
+ Rect2 pa = p_pre_a;
+ Rect2 pb = p_post_b;
+
+ return Rect2(
+ a.position.cubic_interpolate_in_time(b.position, pa.position, pb.position, p_c, p_b_t, p_pre_a_t, p_post_b_t),
+ a.size.cubic_interpolate_in_time(b.size, pa.size, pb.size, p_c, p_b_t, p_pre_a_t, p_post_b_t));
+ }
+ case Variant::VECTOR3: {
+ Vector3 a = p_a;
+ Vector3 b = p_b;
+ Vector3 pa = p_pre_a;
+ Vector3 pb = p_post_b;
+
+ return a.cubic_interpolate_in_time(b, pa, pb, p_c, p_b_t, p_pre_a_t, p_post_b_t);
+ }
+ case Variant::QUATERNION: {
+ Quaternion a = p_a;
+ Quaternion b = p_b;
+ Quaternion pa = p_pre_a;
+ Quaternion pb = p_post_b;
+
+ return a.spherical_cubic_interpolate_in_time(b, pa, pb, p_c, p_b_t, p_pre_a_t, p_post_b_t);
+ }
+ case Variant::AABB: {
+ AABB a = p_a;
+ AABB b = p_b;
+ AABB pa = p_pre_a;
+ AABB pb = p_post_b;
+
+ return AABB(
+ a.position.cubic_interpolate_in_time(b.position, pa.position, pb.position, p_c, p_b_t, p_pre_a_t, p_post_b_t),
+ a.size.cubic_interpolate_in_time(b.size, pa.size, pb.size, p_c, p_b_t, p_pre_a_t, p_post_b_t));
+ }
+ default: {
+ return _interpolate(p_a, p_b, p_c);
+ }
+ }
+}
+
+real_t Animation::_cubic_interpolate_in_time(const real_t &p_pre_a, const real_t &p_a, const real_t &p_b, const real_t &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const {
+ return _interpolate(p_a, p_b, p_c);
+}
+
template <class T>
T Animation::_interpolate(const Vector<TKey<T>> &p_keys, double p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok, bool p_backward) const {
int len = _find(p_keys, length) + 1; // try to find last key (there may be more past the end)
@@ -2568,26 +2685,65 @@ T Animation::_interpolate(const Vector<TKey<T>> &p_keys, double p_time, Interpol
case INTERPOLATION_LINEAR: {
return _interpolate(p_keys[idx].value, p_keys[next].value, c);
} break;
- case INTERPOLATION_CUBIC: {
- int pre = idx - 1;
- if (pre < 0) {
- if (loop_mode == LOOP_LINEAR && p_loop_wrap) {
- pre = len - 1;
- } else {
- pre = 0;
+ case INTERPOLATION_CUBIC:
+ case INTERPOLATION_CUBIC_IN_TIME: {
+ int pre = 0;
+ int post = 0;
+ if (!p_backward) {
+ pre = idx - 1;
+ if (pre < 0) {
+ if (loop_mode == LOOP_LINEAR && p_loop_wrap) {
+ pre = len - 1;
+ } else {
+ pre = 0;
+ }
}
- }
- int post = next + 1;
- if (post >= len) {
- if (loop_mode == LOOP_LINEAR && p_loop_wrap) {
- post = 0;
- } else {
- post = next;
+ post = next + 1;
+ if (post >= len) {
+ if (loop_mode == LOOP_LINEAR && p_loop_wrap) {
+ post = 0;
+ } else {
+ post = next;
+ }
+ }
+ } else {
+ pre = idx + 1;
+ if (pre >= len) {
+ if (loop_mode == LOOP_LINEAR && p_loop_wrap) {
+ pre = 0;
+ } else {
+ pre = idx;
+ }
+ }
+ post = next - 1;
+ if (post < 0) {
+ if (loop_mode == LOOP_LINEAR && p_loop_wrap) {
+ post = len - 1;
+ } else {
+ post = 0;
+ }
}
}
- return _cubic_interpolate(p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c);
+ if (loop_mode == LOOP_LINEAR && p_loop_wrap) {
+ if (p_interp == INTERPOLATION_CUBIC) {
+ return _cubic_interpolate(p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c);
+ }
+ return _cubic_interpolate_in_time(
+ p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c,
+ pre > idx ? -length + p_keys[pre].time - p_keys[idx].time : p_keys[pre].time - p_keys[idx].time,
+ next < idx ? length + p_keys[next].time - p_keys[idx].time : p_keys[next].time - p_keys[idx].time,
+ next < idx || post <= idx ? length + p_keys[post].time - p_keys[idx].time : p_keys[post].time - p_keys[idx].time);
+ }
+ if (p_interp == INTERPOLATION_CUBIC) {
+ return _cubic_interpolate(p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c);
+ }
+ return _cubic_interpolate_in_time(
+ p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c,
+ p_keys[pre].time - p_keys[idx].time,
+ p_keys[next].time - p_keys[idx].time,
+ p_keys[post].time - p_keys[idx].time);
} break;
default:
return p_keys[idx].value;
@@ -3215,7 +3371,7 @@ StringName Animation::method_track_get_name(int p_track, int p_key_idx) const {
return pm->methods[p_key_idx].method;
}
-int Animation::bezier_track_insert_key(int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const HandleMode p_handle_mode) {
+int Animation::bezier_track_insert_key(int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle) {
ERR_FAIL_INDEX_V(p_track, tracks.size(), -1);
Track *t = tracks[p_track];
ERR_FAIL_COND_V(t->type != TYPE_BEZIER, -1);
@@ -3233,7 +3389,6 @@ int Animation::bezier_track_insert_key(int p_track, double p_time, real_t p_valu
if (k.value.out_handle.x < 0) {
k.value.out_handle.x = 0;
}
- k.value.handle_mode = p_handle_mode;
int key = _insert(p_time, bt->values, k);
@@ -3242,30 +3397,6 @@ int Animation::bezier_track_insert_key(int p_track, double p_time, real_t p_valu
return key;
}
-void Animation::bezier_track_set_key_handle_mode(int p_track, int p_index, HandleMode p_mode, double p_balanced_value_time_ratio) {
- ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t = tracks[p_track];
- ERR_FAIL_COND(t->type != TYPE_BEZIER);
-
- BezierTrack *bt = static_cast<BezierTrack *>(t);
-
- ERR_FAIL_INDEX(p_index, bt->values.size());
-
- bt->values.write[p_index].value.handle_mode = p_mode;
-
- if (p_mode == HANDLE_MODE_BALANCED) {
- Transform2D xform;
- xform.set_scale(Vector2(1.0, 1.0 / p_balanced_value_time_ratio));
-
- Vector2 vec_in = xform.xform(bt->values[p_index].value.in_handle);
- Vector2 vec_out = xform.xform(bt->values[p_index].value.out_handle);
-
- bt->values.write[p_index].value.in_handle = xform.affine_inverse().xform(-vec_out.normalized() * vec_in.length());
- }
-
- emit_changed();
-}
-
void Animation::bezier_track_set_key_value(int p_track, int p_index, real_t p_value) {
ERR_FAIL_INDEX(p_track, tracks.size());
Track *t = tracks[p_track];
@@ -3276,10 +3407,11 @@ void Animation::bezier_track_set_key_value(int p_track, int p_index, real_t p_va
ERR_FAIL_INDEX(p_index, bt->values.size());
bt->values.write[p_index].value.value = p_value;
+
emit_changed();
}
-void Animation::bezier_track_set_key_in_handle(int p_track, int p_index, const Vector2 &p_handle, double p_balanced_value_time_ratio) {
+void Animation::bezier_track_set_key_in_handle(int p_track, int p_index, const Vector2 &p_handle, real_t p_balanced_value_time_ratio) {
ERR_FAIL_INDEX(p_track, tracks.size());
Track *t = tracks[p_track];
ERR_FAIL_COND(t->type != TYPE_BEZIER);
@@ -3294,7 +3426,11 @@ void Animation::bezier_track_set_key_in_handle(int p_track, int p_index, const V
}
bt->values.write[p_index].value.in_handle = in_handle;
- if (bt->values[p_index].value.handle_mode == HANDLE_MODE_BALANCED) {
+#ifdef TOOLS_ENABLED
+ if (bt->values[p_index].value.handle_mode == HANDLE_MODE_LINEAR) {
+ bt->values.write[p_index].value.in_handle = Vector2();
+ bt->values.write[p_index].value.out_handle = Vector2();
+ } else if (bt->values[p_index].value.handle_mode == HANDLE_MODE_BALANCED) {
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / p_balanced_value_time_ratio));
@@ -3302,12 +3438,15 @@ void Animation::bezier_track_set_key_in_handle(int p_track, int p_index, const V
Vector2 vec_in = xform.xform(in_handle);
bt->values.write[p_index].value.out_handle = xform.affine_inverse().xform(-vec_in.normalized() * vec_out.length());
+ } else if (bt->values[p_index].value.handle_mode == HANDLE_MODE_MIRRORED) {
+ bt->values.write[p_index].value.out_handle = -in_handle;
}
+#endif // TOOLS_ENABLED
emit_changed();
}
-void Animation::bezier_track_set_key_out_handle(int p_track, int p_index, const Vector2 &p_handle, double p_balanced_value_time_ratio) {
+void Animation::bezier_track_set_key_out_handle(int p_track, int p_index, const Vector2 &p_handle, real_t p_balanced_value_time_ratio) {
ERR_FAIL_INDEX(p_track, tracks.size());
Track *t = tracks[p_track];
ERR_FAIL_COND(t->type != TYPE_BEZIER);
@@ -3322,7 +3461,11 @@ void Animation::bezier_track_set_key_out_handle(int p_track, int p_index, const
}
bt->values.write[p_index].value.out_handle = out_handle;
- if (bt->values[p_index].value.handle_mode == HANDLE_MODE_BALANCED) {
+#ifdef TOOLS_ENABLED
+ if (bt->values[p_index].value.handle_mode == HANDLE_MODE_LINEAR) {
+ bt->values.write[p_index].value.in_handle = Vector2();
+ bt->values.write[p_index].value.out_handle = Vector2();
+ } else if (bt->values[p_index].value.handle_mode == HANDLE_MODE_BALANCED) {
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / p_balanced_value_time_ratio));
@@ -3330,7 +3473,10 @@ void Animation::bezier_track_set_key_out_handle(int p_track, int p_index, const
Vector2 vec_out = xform.xform(out_handle);
bt->values.write[p_index].value.in_handle = xform.affine_inverse().xform(-vec_out.normalized() * vec_in.length());
+ } else if (bt->values[p_index].value.handle_mode == HANDLE_MODE_MIRRORED) {
+ bt->values.write[p_index].value.in_handle = -out_handle;
}
+#endif // TOOLS_ENABLED
emit_changed();
}
@@ -3347,18 +3493,6 @@ real_t Animation::bezier_track_get_key_value(int p_track, int p_index) const {
return bt->values[p_index].value.value;
}
-int Animation::bezier_track_get_key_handle_mode(int p_track, int p_index) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(), 0);
- Track *t = tracks[p_track];
- ERR_FAIL_COND_V(t->type != TYPE_BEZIER, 0);
-
- BezierTrack *bt = static_cast<BezierTrack *>(t);
-
- ERR_FAIL_INDEX_V(p_index, bt->values.size(), 0);
-
- return bt->values[p_index].value.handle_mode;
-}
-
Vector2 Animation::bezier_track_get_key_in_handle(int p_track, int p_index) const {
ERR_FAIL_INDEX_V(p_track, tracks.size(), Vector2());
Track *t = tracks[p_track];
@@ -3383,6 +3517,109 @@ Vector2 Animation::bezier_track_get_key_out_handle(int p_track, int p_index) con
return bt->values[p_index].value.out_handle;
}
+#ifdef TOOLS_ENABLED
+void Animation::bezier_track_set_key_handle_mode(int p_track, int p_index, HandleMode p_mode, HandleSetMode p_set_mode) {
+ ERR_FAIL_INDEX(p_track, tracks.size());
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND(t->type != TYPE_BEZIER);
+
+ BezierTrack *bt = static_cast<BezierTrack *>(t);
+
+ ERR_FAIL_INDEX(p_index, bt->values.size());
+
+ bt->values.write[p_index].value.handle_mode = p_mode;
+
+ switch (p_mode) {
+ case HANDLE_MODE_LINEAR: {
+ bt->values.write[p_index].value.in_handle = Vector2(0, 0);
+ bt->values.write[p_index].value.out_handle = Vector2(0, 0);
+ } break;
+ case HANDLE_MODE_BALANCED:
+ case HANDLE_MODE_MIRRORED: {
+ int prev_key = MAX(0, p_index - 1);
+ int next_key = MIN(bt->values.size() - 1, p_index + 1);
+ if (prev_key == next_key) {
+ break; // Exists only one key.
+ }
+ real_t in_handle_x = 0;
+ real_t in_handle_y = 0;
+ real_t out_handle_x = 0;
+ real_t out_handle_y = 0;
+ if (p_mode == HANDLE_MODE_BALANCED) {
+ // Note:
+ // If p_set_mode == HANDLE_SET_MODE_NONE, I don't know if it should change the Tangent implicitly.
+ // At the least, we need to avoid corrupting the handles when loading animation from the resource.
+ // However, changes made by the Inspector do not go through the BezierEditor,
+ // so if you change from Free to Balanced or Mirrored in Inspector, there is no guarantee that
+ // it is Balanced or Mirrored until there is a handle operation.
+ if (p_set_mode == HANDLE_SET_MODE_RESET) {
+ real_t handle_length = 1.0 / 3.0;
+ in_handle_x = (bt->values[prev_key].time - bt->values[p_index].time) * handle_length;
+ in_handle_y = 0;
+ out_handle_x = (bt->values[next_key].time - bt->values[p_index].time) * handle_length;
+ out_handle_y = 0;
+ bt->values.write[p_index].value.in_handle = Vector2(in_handle_x, in_handle_y);
+ bt->values.write[p_index].value.out_handle = Vector2(out_handle_x, out_handle_y);
+ } else if (p_set_mode == HANDLE_SET_MODE_AUTO) {
+ real_t handle_length = 1.0 / 6.0;
+ real_t tangent = (bt->values[next_key].value.value - bt->values[prev_key].value.value) / (bt->values[next_key].time - bt->values[prev_key].time);
+ in_handle_x = (bt->values[prev_key].time - bt->values[p_index].time) * handle_length;
+ in_handle_y = in_handle_x * tangent;
+ out_handle_x = (bt->values[next_key].time - bt->values[p_index].time) * handle_length;
+ out_handle_y = out_handle_x * tangent;
+ bt->values.write[p_index].value.in_handle = Vector2(in_handle_x, in_handle_y);
+ bt->values.write[p_index].value.out_handle = Vector2(out_handle_x, out_handle_y);
+ }
+ } else {
+ real_t handle_length = 1.0 / 4.0;
+ real_t prev_interval = Math::abs(bt->values[p_index].time - bt->values[prev_key].time);
+ real_t next_interval = Math::abs(bt->values[p_index].time - bt->values[next_key].time);
+ real_t min_time = 0;
+ if (Math::is_zero_approx(prev_interval)) {
+ min_time = next_interval;
+ } else if (Math::is_zero_approx(next_interval)) {
+ min_time = prev_interval;
+ } else {
+ min_time = MIN(prev_interval, next_interval);
+ }
+ if (p_set_mode == HANDLE_SET_MODE_RESET) {
+ in_handle_x = -min_time * handle_length;
+ in_handle_y = 0;
+ out_handle_x = min_time * handle_length;
+ out_handle_y = 0;
+ bt->values.write[p_index].value.in_handle = Vector2(in_handle_x, in_handle_y);
+ bt->values.write[p_index].value.out_handle = Vector2(out_handle_x, out_handle_y);
+ } else if (p_set_mode == HANDLE_SET_MODE_AUTO) {
+ real_t tangent = (bt->values[next_key].value.value - bt->values[prev_key].value.value) / min_time;
+ in_handle_x = -min_time * handle_length;
+ in_handle_y = in_handle_x * tangent;
+ out_handle_x = min_time * handle_length;
+ out_handle_y = out_handle_x * tangent;
+ bt->values.write[p_index].value.in_handle = Vector2(in_handle_x, in_handle_y);
+ bt->values.write[p_index].value.out_handle = Vector2(out_handle_x, out_handle_y);
+ }
+ }
+ } break;
+ default: {
+ } break;
+ }
+
+ emit_changed();
+}
+
+Animation::HandleMode Animation::bezier_track_get_key_handle_mode(int p_track, int p_index) const {
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), HANDLE_MODE_FREE);
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_BEZIER, HANDLE_MODE_FREE);
+
+ BezierTrack *bt = static_cast<BezierTrack *>(t);
+
+ ERR_FAIL_INDEX_V(p_index, bt->values.size(), HANDLE_MODE_FREE);
+
+ return bt->values[p_index].value.handle_mode;
+}
+#endif // TOOLS_ENABLED
+
real_t Animation::bezier_track_interpolate(int p_track, double p_time) const {
//this uses a different interpolation scheme
ERR_FAIL_INDEX_V(p_track, tracks.size(), 0);
@@ -3779,7 +4016,7 @@ void Animation::_bind_methods() {
ClassDB::bind_method(D_METHOD("method_track_get_name", "track_idx", "key_idx"), &Animation::method_track_get_name);
ClassDB::bind_method(D_METHOD("method_track_get_params", "track_idx", "key_idx"), &Animation::method_track_get_params);
- ClassDB::bind_method(D_METHOD("bezier_track_insert_key", "track_idx", "time", "value", "in_handle", "out_handle", "handle_mode"), &Animation::bezier_track_insert_key, DEFVAL(Vector2()), DEFVAL(Vector2()), DEFVAL(Animation::HandleMode::HANDLE_MODE_BALANCED));
+ ClassDB::bind_method(D_METHOD("bezier_track_insert_key", "track_idx", "time", "value", "in_handle", "out_handle"), &Animation::bezier_track_insert_key, DEFVAL(Vector2()), DEFVAL(Vector2()));
ClassDB::bind_method(D_METHOD("bezier_track_set_key_value", "track_idx", "key_idx", "value"), &Animation::bezier_track_set_key_value);
ClassDB::bind_method(D_METHOD("bezier_track_set_key_in_handle", "track_idx", "key_idx", "in_handle", "balanced_value_time_ratio"), &Animation::bezier_track_set_key_in_handle, DEFVAL(1.0));
@@ -3799,9 +4036,6 @@ void Animation::_bind_methods() {
ClassDB::bind_method(D_METHOD("audio_track_get_key_start_offset", "track_idx", "key_idx"), &Animation::audio_track_get_key_start_offset);
ClassDB::bind_method(D_METHOD("audio_track_get_key_end_offset", "track_idx", "key_idx"), &Animation::audio_track_get_key_end_offset);
- ClassDB::bind_method(D_METHOD("bezier_track_set_key_handle_mode", "track_idx", "key_idx", "key_handle_mode", "balanced_value_time_ratio"), &Animation::bezier_track_set_key_handle_mode, DEFVAL(1.0));
- ClassDB::bind_method(D_METHOD("bezier_track_get_key_handle_mode", "track_idx", "key_idx"), &Animation::bezier_track_get_key_handle_mode);
-
ClassDB::bind_method(D_METHOD("animation_track_insert_key", "track_idx", "time", "animation"), &Animation::animation_track_insert_key);
ClassDB::bind_method(D_METHOD("animation_track_set_key_animation", "track_idx", "key_idx", "animation"), &Animation::animation_track_set_key_animation);
ClassDB::bind_method(D_METHOD("animation_track_get_key_animation", "track_idx", "key_idx"), &Animation::animation_track_get_key_animation);
@@ -3839,6 +4073,7 @@ void Animation::_bind_methods() {
BIND_ENUM_CONSTANT(INTERPOLATION_NEAREST);
BIND_ENUM_CONSTANT(INTERPOLATION_LINEAR);
BIND_ENUM_CONSTANT(INTERPOLATION_CUBIC);
+ BIND_ENUM_CONSTANT(INTERPOLATION_CUBIC_IN_TIME);
BIND_ENUM_CONSTANT(UPDATE_CONTINUOUS);
BIND_ENUM_CONSTANT(UPDATE_DISCRETE);
@@ -3848,9 +4083,6 @@ void Animation::_bind_methods() {
BIND_ENUM_CONSTANT(LOOP_NONE);
BIND_ENUM_CONSTANT(LOOP_LINEAR);
BIND_ENUM_CONSTANT(LOOP_PINGPONG);
-
- BIND_ENUM_CONSTANT(HANDLE_MODE_FREE);
- BIND_ENUM_CONSTANT(HANDLE_MODE_BALANCED);
}
void Animation::clear() {
@@ -3868,316 +4100,208 @@ void Animation::clear() {
emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
-bool Animation::_position_track_optimize_key(const TKey<Vector3> &t0, const TKey<Vector3> &t1, const TKey<Vector3> &t2, real_t p_allowed_linear_err, real_t p_allowed_angular_error, const Vector3 &p_norm) {
- const Vector3 &v0 = t0.value;
- const Vector3 &v1 = t1.value;
- const Vector3 &v2 = t2.value;
-
- if (v0.is_equal_approx(v2)) {
- //0 and 2 are close, let's see if 1 is close
- if (!v0.is_equal_approx(v1)) {
- //not close, not optimizable
- return false;
- }
-
- } else {
- Vector3 pd = (v2 - v0);
- real_t d0 = pd.dot(v0);
- real_t d1 = pd.dot(v1);
- real_t d2 = pd.dot(v2);
- if (d1 < d0 || d1 > d2) {
- return false;
- }
-
- Vector3 s[2] = { v0, v2 };
- real_t d = Geometry3D::get_closest_point_to_segment(v1, s).distance_to(v1);
-
- if (d > pd.length() * p_allowed_linear_err) {
- return false; //beyond allowed error for collinearity
- }
-
- if (p_norm != Vector3() && Math::acos(pd.normalized().dot(p_norm)) > p_allowed_angular_error) {
- return false;
- }
+bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+ // Remove overlapping keys.
+ if (Math::is_equal_approx(t0.time, t1.time) || Math::is_equal_approx(t1.time, t2.time)) {
+ return true;
}
-
- return true;
-}
-
-bool Animation::_rotation_track_optimize_key(const TKey<Quaternion> &t0, const TKey<Quaternion> &t1, const TKey<Quaternion> &t2, real_t p_allowed_angular_error, float p_max_optimizable_angle) {
- const Quaternion &q0 = t0.value;
- const Quaternion &q1 = t1.value;
- const Quaternion &q2 = t2.value;
-
- //localize both to rotation from q0
-
- if (q0.is_equal_approx(q2)) {
- if (!q0.is_equal_approx(q1)) {
- return false;
- }
-
- } else {
- Quaternion r02 = (q0.inverse() * q2).normalized();
- Quaternion r01 = (q0.inverse() * q1).normalized();
-
- Vector3 v02, v01;
- real_t a02, a01;
-
- r02.get_axis_angle(v02, a02);
- r01.get_axis_angle(v01, a01);
-
- if (Math::abs(a02) > p_max_optimizable_angle) {
- return false;
- }
-
- if (v01.dot(v02) < 0) {
- //make sure both rotations go the same way to compare
- v02 = -v02;
- a02 = -a02;
- }
-
- real_t err_01 = Math::acos(v01.normalized().dot(v02.normalized())) / Math_PI;
- if (err_01 > p_allowed_angular_error) {
- //not rotating in the same axis
- return false;
- }
-
- if (a01 * a02 < 0) {
- //not rotating in the same direction
- return false;
- }
-
- real_t tr = a01 / a02;
- if (tr < 0 || tr > 1) {
- return false; //rotating too much or too less
+ if ((t0.value - t1.value).length() < p_allowed_precision_error && (t1.value - t2.value).length() < p_allowed_precision_error) {
+ return true;
+ }
+ // Calc velocities.
+ Vector3 vc0 = (t1.value - t0.value) / (t1.time - t0.time);
+ Vector3 vc1 = (t2.value - t1.value) / (t2.time - t1.time);
+ real_t v0 = vc0.length();
+ real_t v1 = vc1.length();
+ // Avoid zero div but check equality.
+ if (abs(v0 - v1) < p_allowed_precision_error) {
+ return true;
+ } else if (abs(v0) < p_allowed_precision_error || abs(v1) < p_allowed_precision_error) {
+ return false;
+ }
+ // Check axis.
+ if (vc0.normalized().dot(vc1.normalized()) >= 1.0 - p_allowed_angular_error * 2.0) {
+ real_t ratio = v0 < v1 ? v0 / v1 : v1 / v0;
+ if (ratio >= 1.0 - p_allowed_velocity_err) {
+ return true;
}
}
-
- return true;
+ return false;
}
-bool Animation::_scale_track_optimize_key(const TKey<Vector3> &t0, const TKey<Vector3> &t1, const TKey<Vector3> &t2, real_t p_allowed_linear_error) {
- const Vector3 &v0 = t0.value;
- const Vector3 &v1 = t1.value;
- const Vector3 &v2 = t2.value;
-
- if (v0.is_equal_approx(v2)) {
- //0 and 2 are close, let's see if 1 is close
- if (!v0.is_equal_approx(v1)) {
- //not close, not optimizable
+bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+ // Remove overlapping keys.
+ if (Math::is_equal_approx(t0.time, t1.time) || Math::is_equal_approx(t1.time, t2.time)) {
+ return true;
+ }
+ if ((t0.value - t1.value).length() < p_allowed_precision_error && (t1.value - t2.value).length() < p_allowed_precision_error) {
+ return true;
+ }
+ // Check axis.
+ Quaternion q0 = t0.value * t1.value * t0.value.inverse();
+ Quaternion q1 = t1.value * t2.value * t1.value.inverse();
+ if (q0.get_axis().dot(q1.get_axis()) >= 1.0 - p_allowed_angular_error * 2.0) {
+ // Calc velocities.
+ real_t v0 = Math::acos(t0.value.dot(t1.value)) / (t1.time - t0.time);
+ real_t v1 = Math::acos(t1.value.dot(t2.value)) / (t2.time - t1.time);
+ // Avoid zero div but check equality.
+ if (abs(v0 - v1) < p_allowed_precision_error) {
+ return true;
+ } else if (abs(v0) < p_allowed_precision_error || abs(v1) < p_allowed_precision_error) {
return false;
}
-
- } else {
- Vector3 pd = (v2 - v0);
- real_t d0 = pd.dot(v0);
- real_t d1 = pd.dot(v1);
- real_t d2 = pd.dot(v2);
- if (d1 < d0 || d1 > d2) {
- return false; //beyond segment range
- }
-
- Vector3 s[2] = { v0, v2 };
- real_t d = Geometry3D::get_closest_point_to_segment(v1, s).distance_to(v1);
-
- if (d > pd.length() * p_allowed_linear_error) {
- return false; //beyond allowed error for colinearity
+ real_t ratio = v0 < v1 ? v0 / v1 : v1 / v0;
+ if (ratio >= 1.0 - p_allowed_velocity_err) {
+ return true;
}
}
-
- return true;
+ return false;
}
-bool Animation::_blend_shape_track_optimize_key(const TKey<float> &t0, const TKey<float> &t1, const TKey<float> &t2, real_t p_allowed_unit_error) {
- float v0 = t0.value;
- float v1 = t1.value;
- float v2 = t2.value;
-
- if (Math::is_equal_approx(v1, v2, (float)p_allowed_unit_error)) {
- //0 and 2 are close, let's see if 1 is close
- if (!Math::is_equal_approx(v0, v1, (float)p_allowed_unit_error)) {
- //not close, not optimizable
- return false;
- }
- } else {
- /*
- TODO eventually discuss a way to optimize these better.
- float pd = (v2 - v0);
- real_t d0 = pd.dot(v0);
- real_t d1 = pd.dot(v1);
- real_t d2 = pd.dot(v2);
- if (d1 < d0 || d1 > d2) {
- return false; //beyond segment range
- }
-
- float s[2] = { v0, v2 };
- real_t d = Geometry3D::get_closest_point_to_segment(v1, s).distance_to(v1);
-
- if (d > pd.length() * p_allowed_linear_error) {
- return false; //beyond allowed error for colinearity
+bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error) {
+ // Remove overlapping keys.
+ if (Math::is_equal_approx(t0.time, t1.time) || Math::is_equal_approx(t1.time, t2.time)) {
+ return true;
+ }
+ if (abs(t0.value - t1.value) < p_allowed_precision_error && abs(t1.value - t2.value) < p_allowed_precision_error) {
+ return true;
+ }
+ // Calc velocities.
+ real_t v0 = (t1.value - t0.value) / (t1.time - t0.time);
+ real_t v1 = (t2.value - t1.value) / (t2.time - t1.time);
+ // Avoid zero div but check equality.
+ if (abs(v0 - v1) < p_allowed_precision_error) {
+ return true;
+ } else if (abs(v0) < p_allowed_precision_error || abs(v1) < p_allowed_precision_error) {
+ return false;
+ }
+ if (!signbit(v0 * v1)) {
+ real_t ratio = v0 < v1 ? v0 / v1 : v1 / v0;
+ if (ratio >= 1.0 - p_allowed_velocity_err) {
+ return true;
}
-*/
}
-
- return true;
+ return false;
}
-void Animation::_position_track_optimize(int p_idx, real_t p_allowed_linear_err, real_t p_allowed_angular_err) {
+void Animation::_position_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_POSITION_3D);
PositionTrack *tt = static_cast<PositionTrack *>(tracks[p_idx]);
- bool prev_erased = false;
- TKey<Vector3> first_erased;
-
- Vector3 norm;
- for (int i = 1; i < tt->positions.size() - 1; i++) {
- TKey<Vector3> &t0 = tt->positions.write[i - 1];
- TKey<Vector3> &t1 = tt->positions.write[i];
- TKey<Vector3> &t2 = tt->positions.write[i + 1];
-
- bool erase = _position_track_optimize_key(t0, t1, t2, p_allowed_linear_err, p_allowed_angular_err, norm);
- if (erase && !prev_erased) {
- norm = (t2.value - t1.value).normalized();
- }
-
- if (prev_erased && !_position_track_optimize_key(t0, first_erased, t2, p_allowed_linear_err, p_allowed_angular_err, norm)) {
- //avoid error to go beyond first erased key
- erase = false;
- }
+ int i = 0;
+ while (i < tt->positions.size() - 2) {
+ TKey<Vector3> t0 = tt->positions[i];
+ TKey<Vector3> t1 = tt->positions[i + 1];
+ TKey<Vector3> t2 = tt->positions[i + 2];
+ bool erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
if (erase) {
- if (!prev_erased) {
- first_erased = t1;
- prev_erased = true;
- }
-
- tt->positions.remove_at(i);
- i--;
-
+ tt->positions.remove_at(i + 1);
} else {
- prev_erased = false;
- norm = Vector3();
+ i++;
+ }
+ }
+
+ if (tt->positions.size() == 2) {
+ if ((tt->positions[0].value - tt->positions[1].value).length() < p_allowed_precision_error) {
+ tt->positions.remove_at(1);
}
}
}
-void Animation::_rotation_track_optimize(int p_idx, real_t p_allowed_angular_err, real_t p_max_optimizable_angle) {
+void Animation::_rotation_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_ROTATION_3D);
RotationTrack *tt = static_cast<RotationTrack *>(tracks[p_idx]);
- bool prev_erased = false;
- TKey<Quaternion> first_erased;
-
- for (int i = 1; i < tt->rotations.size() - 1; i++) {
- TKey<Quaternion> &t0 = tt->rotations.write[i - 1];
- TKey<Quaternion> &t1 = tt->rotations.write[i];
- TKey<Quaternion> &t2 = tt->rotations.write[i + 1];
- bool erase = _rotation_track_optimize_key(t0, t1, t2, p_allowed_angular_err, p_max_optimizable_angle);
-
- if (prev_erased && !_rotation_track_optimize_key(t0, first_erased, t2, p_allowed_angular_err, p_max_optimizable_angle)) {
- //avoid error to go beyond first erased key
- erase = false;
- }
+ int i = 0;
+ while (i < tt->rotations.size() - 2) {
+ TKey<Quaternion> t0 = tt->rotations[i];
+ TKey<Quaternion> t1 = tt->rotations[i + 1];
+ TKey<Quaternion> t2 = tt->rotations[i + 2];
+ bool erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
if (erase) {
- if (!prev_erased) {
- first_erased = t1;
- prev_erased = true;
- }
-
- tt->rotations.remove_at(i);
- i--;
-
+ tt->rotations.remove_at(i + 1);
} else {
- prev_erased = false;
+ i++;
+ }
+ }
+
+ if (tt->rotations.size() == 2) {
+ if ((tt->rotations[0].value - tt->rotations[1].value).length() < p_allowed_precision_error) {
+ tt->rotations.remove_at(1);
}
}
}
-void Animation::_scale_track_optimize(int p_idx, real_t p_allowed_linear_err) {
+void Animation::_scale_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_SCALE_3D);
ScaleTrack *tt = static_cast<ScaleTrack *>(tracks[p_idx]);
- bool prev_erased = false;
- TKey<Vector3> first_erased;
-
- for (int i = 1; i < tt->scales.size() - 1; i++) {
- TKey<Vector3> &t0 = tt->scales.write[i - 1];
- TKey<Vector3> &t1 = tt->scales.write[i];
- TKey<Vector3> &t2 = tt->scales.write[i + 1];
- bool erase = _scale_track_optimize_key(t0, t1, t2, p_allowed_linear_err);
-
- if (prev_erased && !_scale_track_optimize_key(t0, first_erased, t2, p_allowed_linear_err)) {
- //avoid error to go beyond first erased key
- erase = false;
- }
+ int i = 0;
+ while (i < tt->scales.size() - 2) {
+ TKey<Vector3> t0 = tt->scales[i];
+ TKey<Vector3> t1 = tt->scales[i + 1];
+ TKey<Vector3> t2 = tt->scales[i + 2];
+ bool erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
if (erase) {
- if (!prev_erased) {
- first_erased = t1;
- prev_erased = true;
- }
-
- tt->scales.remove_at(i);
- i--;
-
+ tt->scales.remove_at(i + 1);
} else {
- prev_erased = false;
+ i++;
+ }
+ }
+
+ if (tt->scales.size() == 2) {
+ if ((tt->scales[0].value - tt->scales[1].value).length() < p_allowed_precision_error) {
+ tt->scales.remove_at(1);
}
}
}
-void Animation::_blend_shape_track_optimize(int p_idx, real_t p_allowed_linear_err) {
+void Animation::_blend_shape_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_BLEND_SHAPE);
BlendShapeTrack *tt = static_cast<BlendShapeTrack *>(tracks[p_idx]);
- bool prev_erased = false;
- TKey<float> first_erased;
- first_erased.value = 0.0;
-
- for (int i = 1; i < tt->blend_shapes.size() - 1; i++) {
- TKey<float> &t0 = tt->blend_shapes.write[i - 1];
- TKey<float> &t1 = tt->blend_shapes.write[i];
- TKey<float> &t2 = tt->blend_shapes.write[i + 1];
- bool erase = _blend_shape_track_optimize_key(t0, t1, t2, p_allowed_linear_err);
-
- if (prev_erased && !_blend_shape_track_optimize_key(t0, first_erased, t2, p_allowed_linear_err)) {
- //avoid error to go beyond first erased key
- erase = false;
- }
+ int i = 0;
+ while (i < tt->blend_shapes.size() - 2) {
+ TKey<float> t0 = tt->blend_shapes[i];
+ TKey<float> t1 = tt->blend_shapes[i + 1];
+ TKey<float> t2 = tt->blend_shapes[i + 2];
+ bool erase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error);
if (erase) {
- if (!prev_erased) {
- first_erased = t1;
- prev_erased = true;
- }
-
- tt->blend_shapes.remove_at(i);
- i--;
-
+ tt->blend_shapes.remove_at(i + 1);
} else {
- prev_erased = false;
+ i++;
+ }
+ }
+
+ if (tt->blend_shapes.size() == 2) {
+ if (abs(tt->blend_shapes[0].value - tt->blend_shapes[1].value) < p_allowed_precision_error) {
+ tt->blend_shapes.remove_at(1);
}
}
}
-void Animation::optimize(real_t p_allowed_linear_err, real_t p_allowed_angular_err, real_t p_max_optimizable_angle) {
+void Animation::optimize(real_t p_allowed_velocity_err, real_t p_allowed_angular_err, int p_precision) {
+ real_t precision = Math::pow(0.1, p_precision);
for (int i = 0; i < tracks.size(); i++) {
if (track_is_compressed(i)) {
continue; //not possible to optimize compressed track
}
if (tracks[i]->type == TYPE_POSITION_3D) {
- _position_track_optimize(i, p_allowed_linear_err, p_allowed_angular_err);
+ _position_track_optimize(i, p_allowed_velocity_err, p_allowed_angular_err, precision);
} else if (tracks[i]->type == TYPE_ROTATION_3D) {
- _rotation_track_optimize(i, p_allowed_angular_err, p_max_optimizable_angle);
+ _rotation_track_optimize(i, p_allowed_velocity_err, p_allowed_angular_err, precision);
} else if (tracks[i]->type == TYPE_SCALE_3D) {
- _scale_track_optimize(i, p_allowed_linear_err);
+ _scale_track_optimize(i, p_allowed_velocity_err, p_allowed_angular_err, precision);
} else if (tracks[i]->type == TYPE_BLEND_SHAPE) {
- _blend_shape_track_optimize(i, p_allowed_linear_err);
+ _blend_shape_track_optimize(i, p_allowed_velocity_err, precision);
}
}
}
diff --git a/scene/resources/animation.h b/scene/resources/animation.h
index bf9f786a0d..5e88980397 100644
--- a/scene/resources/animation.h
+++ b/scene/resources/animation.h
@@ -56,7 +56,8 @@ public:
enum InterpolationType {
INTERPOLATION_NEAREST,
INTERPOLATION_LINEAR,
- INTERPOLATION_CUBIC
+ INTERPOLATION_CUBIC,
+ INTERPOLATION_CUBIC_IN_TIME,
};
enum UpdateMode {
@@ -72,10 +73,19 @@ public:
LOOP_PINGPONG,
};
+#ifdef TOOLS_ENABLED
enum HandleMode {
HANDLE_MODE_FREE,
+ HANDLE_MODE_LINEAR,
HANDLE_MODE_BALANCED,
+ HANDLE_MODE_MIRRORED,
};
+ enum HandleSetMode {
+ HANDLE_SET_MODE_NONE,
+ HANDLE_SET_MODE_RESET,
+ HANDLE_SET_MODE_AUTO,
+ };
+#endif // TOOLS_ENABLED
private:
struct Track {
@@ -165,8 +175,10 @@ private:
struct BezierKey {
Vector2 in_handle; //relative (x always <0)
Vector2 out_handle; //relative (x always >0)
- HandleMode handle_mode = HANDLE_MODE_BALANCED;
real_t value = 0.0;
+#ifdef TOOLS_ENABLED
+ HandleMode handle_mode = HANDLE_MODE_FREE;
+#endif // TOOLS_ENABLED
};
struct BezierTrack : public Track {
@@ -231,6 +243,11 @@ private:
_FORCE_INLINE_ Variant _cubic_interpolate(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, real_t p_c) const;
_FORCE_INLINE_ real_t _cubic_interpolate(const real_t &p_pre_a, const real_t &p_a, const real_t &p_b, const real_t &p_post_b, real_t p_c) const;
+ _FORCE_INLINE_ Vector3 _cubic_interpolate_in_time(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const;
+ _FORCE_INLINE_ Quaternion _cubic_interpolate_in_time(const Quaternion &p_pre_a, const Quaternion &p_a, const Quaternion &p_b, const Quaternion &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const;
+ _FORCE_INLINE_ Variant _cubic_interpolate_in_time(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const;
+ _FORCE_INLINE_ real_t _cubic_interpolate_in_time(const real_t &p_pre_a, const real_t &p_a, const real_t &p_b, const real_t &p_post_b, real_t p_c, real_t p_pre_a_t, real_t p_b_t, real_t p_post_b_t) const;
+
template <class T>
_FORCE_INLINE_ T _interpolate(const Vector<TKey<T>> &p_keys, double p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok, bool p_backward = false) const;
@@ -351,15 +368,14 @@ private:
return idxr;
}
- bool _position_track_optimize_key(const TKey<Vector3> &t0, const TKey<Vector3> &t1, const TKey<Vector3> &t2, real_t p_alowed_linear_err, real_t p_allowed_angular_error, const Vector3 &p_norm);
- bool _rotation_track_optimize_key(const TKey<Quaternion> &t0, const TKey<Quaternion> &t1, const TKey<Quaternion> &t2, real_t p_allowed_angular_error, float p_max_optimizable_angle);
- bool _scale_track_optimize_key(const TKey<Vector3> &t0, const TKey<Vector3> &t1, const TKey<Vector3> &t2, real_t p_allowed_linear_error);
- bool _blend_shape_track_optimize_key(const TKey<float> &t0, const TKey<float> &t1, const TKey<float> &t2, real_t p_allowed_unit_error);
+ bool _vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_alowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
+ bool _quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
+ bool _float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error);
- void _position_track_optimize(int p_idx, real_t p_allowed_linear_err, real_t p_allowed_angular_err);
- void _rotation_track_optimize(int p_idx, real_t p_allowed_angular_err, real_t p_max_optimizable_angle);
- void _scale_track_optimize(int p_idx, real_t p_allowed_linear_err);
- void _blend_shape_track_optimize(int p_idx, real_t p_allowed_unit_error);
+ void _position_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error);
+ void _rotation_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
+ void _scale_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error);
+ void _blend_shape_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_precision_error);
protected:
bool _set(const StringName &p_name, const Variant &p_value);
@@ -424,15 +440,17 @@ public:
void track_set_interpolation_type(int p_track, InterpolationType p_interp);
InterpolationType track_get_interpolation_type(int p_track) const;
- int bezier_track_insert_key(int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const HandleMode p_handle_mode = HandleMode::HANDLE_MODE_BALANCED);
- void bezier_track_set_key_handle_mode(int p_track, int p_index, HandleMode p_mode, double p_balanced_value_time_ratio = 1.0);
+ int bezier_track_insert_key(int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle);
void bezier_track_set_key_value(int p_track, int p_index, real_t p_value);
- void bezier_track_set_key_in_handle(int p_track, int p_index, const Vector2 &p_handle, double p_balanced_value_time_ratio = 1.0);
- void bezier_track_set_key_out_handle(int p_track, int p_index, const Vector2 &p_handle, double p_balanced_value_time_ratio = 1.0);
+ void bezier_track_set_key_in_handle(int p_track, int p_index, const Vector2 &p_handle, real_t p_balanced_value_time_ratio = 1.0);
+ void bezier_track_set_key_out_handle(int p_track, int p_index, const Vector2 &p_handle, real_t p_balanced_value_time_ratio = 1.0);
real_t bezier_track_get_key_value(int p_track, int p_index) const;
- int bezier_track_get_key_handle_mode(int p_track, int p_index) const;
Vector2 bezier_track_get_key_in_handle(int p_track, int p_index) const;
Vector2 bezier_track_get_key_out_handle(int p_track, int p_index) const;
+#ifdef TOOLS_ENABLED
+ void bezier_track_set_key_handle_mode(int p_track, int p_index, HandleMode p_mode, HandleSetMode p_set_mode = HANDLE_SET_MODE_NONE);
+ HandleMode bezier_track_get_key_handle_mode(int p_track, int p_index) const;
+#endif // TOOLS_ENABLED
real_t bezier_track_interpolate(int p_track, double p_time) const;
@@ -475,7 +493,7 @@ public:
void clear();
- void optimize(real_t p_allowed_linear_err = 0.05, real_t p_allowed_angular_err = 0.01, real_t p_max_optimizable_angle = Math_PI * 0.125);
+ void optimize(real_t p_allowed_velocity_err = 0.01, real_t p_allowed_angular_err = 0.01, int p_precision = 3);
void compress(uint32_t p_page_size = 8192, uint32_t p_fps = 120, float p_split_tolerance = 4.0); // 4.0 seems to be the split tolerance sweet spot from many tests
Animation();
@@ -485,7 +503,10 @@ public:
VARIANT_ENUM_CAST(Animation::TrackType);
VARIANT_ENUM_CAST(Animation::InterpolationType);
VARIANT_ENUM_CAST(Animation::UpdateMode);
-VARIANT_ENUM_CAST(Animation::HandleMode);
VARIANT_ENUM_CAST(Animation::LoopMode);
+#ifdef TOOLS_ENABLED
+VARIANT_ENUM_CAST(Animation::HandleMode);
+VARIANT_ENUM_CAST(Animation::HandleSetMode);
+#endif // TOOLS_ENABLED
#endif // ANIMATION_H
diff --git a/scene/resources/bit_map.cpp b/scene/resources/bit_map.cpp
index bef431e980..9b1adde00a 100644
--- a/scene/resources/bit_map.cpp
+++ b/scene/resources/bit_map.cpp
@@ -31,6 +31,7 @@
#include "bit_map.h"
#include "core/io/image_loader.h"
+#include "core/variant/typed_array.h"
void BitMap::create(const Size2 &p_size) {
ERR_FAIL_COND(p_size.width < 1);
@@ -576,12 +577,12 @@ void BitMap::shrink_mask(int p_pixels, const Rect2 &p_rect) {
grow_mask(-p_pixels, p_rect);
}
-Array BitMap::_opaque_to_polygons_bind(const Rect2 &p_rect, float p_epsilon) const {
+TypedArray<PackedVector2Array> BitMap::_opaque_to_polygons_bind(const Rect2 &p_rect, float p_epsilon) const {
Vector<Vector<Vector2>> result = clip_opaque_to_polygons(p_rect, p_epsilon);
// Convert result to bindable types
- Array result_array;
+ TypedArray<PackedVector2Array> result_array;
result_array.resize(result.size());
for (int i = 0; i < result.size(); i++) {
const Vector<Vector2> &polygon = result[i];
diff --git a/scene/resources/bit_map.h b/scene/resources/bit_map.h
index 0d0d779c32..d8507dfa8b 100644
--- a/scene/resources/bit_map.h
+++ b/scene/resources/bit_map.h
@@ -35,6 +35,9 @@
#include "core/io/resource.h"
#include "core/io/resource_loader.h"
+template <typename T>
+class TypedArray;
+
class BitMap : public Resource {
GDCLASS(BitMap, Resource);
OBJ_SAVE_TYPE(BitMap);
@@ -45,7 +48,7 @@ class BitMap : public Resource {
Vector<Vector2> _march_square(const Rect2i &rect, const Point2i &start) const;
- Array _opaque_to_polygons_bind(const Rect2 &p_rect, float p_epsilon) const;
+ TypedArray<PackedVector2Array> _opaque_to_polygons_bind(const Rect2 &p_rect, float p_epsilon) const;
protected:
void _set_data(const Dictionary &p_d);
diff --git a/scene/resources/bone_map.cpp b/scene/resources/bone_map.cpp
index aff917b2d4..dfaf82f36a 100644
--- a/scene/resources/bone_map.cpp
+++ b/scene/resources/bone_map.cpp
@@ -82,9 +82,13 @@ StringName BoneMap::get_skeleton_bone_name(StringName p_profile_bone_name) const
return bone_map.get(p_profile_bone_name);
}
-void BoneMap::set_skeleton_bone_name(StringName p_profile_bone_name, const StringName p_skeleton_bone_name) {
+void BoneMap::_set_skeleton_bone_name(StringName p_profile_bone_name, const StringName p_skeleton_bone_name) {
ERR_FAIL_COND(!bone_map.has(p_profile_bone_name));
bone_map.insert(p_profile_bone_name, p_skeleton_bone_name);
+}
+
+void BoneMap::set_skeleton_bone_name(StringName p_profile_bone_name, const StringName p_skeleton_bone_name) {
+ _set_skeleton_bone_name(p_profile_bone_name, p_skeleton_bone_name);
emit_signal("bone_map_updated");
}
@@ -168,7 +172,9 @@ void BoneMap::_bind_methods() {
}
void BoneMap::_validate_property(PropertyInfo &property) const {
- //
+ if (property.name == "bonemap" || property.name == "profile") {
+ property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
}
BoneMap::BoneMap() {
diff --git a/scene/resources/bone_map.h b/scene/resources/bone_map.h
index 17452dfc73..a07a776e27 100644
--- a/scene/resources/bone_map.h
+++ b/scene/resources/bone_map.h
@@ -45,14 +45,11 @@ class BoneMap : public Resource {
protected:
bool _get(const StringName &p_path, Variant &r_ret) const;
bool _set(const StringName &p_path, const Variant &p_value);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
- int get_profile_type() const;
- void set_profile_type(const int p_profile_type);
-
Ref<SkeletonProfile> get_profile() const;
void set_profile(const Ref<SkeletonProfile> &p_profile);
@@ -60,6 +57,7 @@ public:
StringName get_skeleton_bone_name(StringName p_profile_bone_name) const;
void set_skeleton_bone_name(StringName p_profile_bone_name, const StringName p_skeleton_bone_name);
+ void _set_skeleton_bone_name(StringName p_profile_bone_name, const StringName p_skeleton_bone_name); // Avoid to emit signal for editor.
StringName find_profile_bone_name(StringName p_skeleton_bone_name) const;
diff --git a/scene/resources/camera_effects.cpp b/scene/resources/camera_effects.cpp
index 97617adbae..0b11366591 100644
--- a/scene/resources/camera_effects.cpp
+++ b/scene/resources/camera_effects.cpp
@@ -145,11 +145,11 @@ void CameraEffects::_update_override_exposure() {
// Private methods, constructor and destructor
-void CameraEffects::_validate_property(PropertyInfo &property) const {
- if ((!dof_blur_far_enabled && (property.name == "dof_blur_far_distance" || property.name == "dof_blur_far_transition")) ||
- (!dof_blur_near_enabled && (property.name == "dof_blur_near_distance" || property.name == "dof_blur_near_transition")) ||
- (!override_exposure_enabled && property.name == "override_exposure")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void CameraEffects::_validate_property(PropertyInfo &p_property) const {
+ if ((!dof_blur_far_enabled && (p_property.name == "dof_blur_far_distance" || p_property.name == "dof_blur_far_transition")) ||
+ (!dof_blur_near_enabled && (p_property.name == "dof_blur_near_distance" || p_property.name == "dof_blur_near_transition")) ||
+ (!override_exposure_enabled && p_property.name == "override_exposure")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
diff --git a/scene/resources/camera_effects.h b/scene/resources/camera_effects.h
index 85ae64cdf5..7353931d16 100644
--- a/scene/resources/camera_effects.h
+++ b/scene/resources/camera_effects.h
@@ -59,7 +59,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
virtual RID get_rid() const override;
diff --git a/scene/resources/canvas_item_material.cpp b/scene/resources/canvas_item_material.cpp
index aa6cc4aded..b16059c218 100644
--- a/scene/resources/canvas_item_material.cpp
+++ b/scene/resources/canvas_item_material.cpp
@@ -227,9 +227,9 @@ bool CanvasItemMaterial::get_particles_anim_loop() const {
return particles_anim_loop;
}
-void CanvasItemMaterial::_validate_property(PropertyInfo &property) const {
- if (property.name.begins_with("particles_anim_") && !particles_animation) {
- property.usage = PROPERTY_USAGE_NONE;
+void CanvasItemMaterial::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name.begins_with("particles_anim_") && !particles_animation) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
diff --git a/scene/resources/canvas_item_material.h b/scene/resources/canvas_item_material.h
index 160c67d6b1..7eaf5051d4 100644
--- a/scene/resources/canvas_item_material.h
+++ b/scene/resources/canvas_item_material.h
@@ -117,7 +117,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_blend_mode(BlendMode p_blend_mode);
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index f29cfec92f..6d99073fa4 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -84,7 +84,7 @@ static Ref<ImageTexture> generate_icon(int p_index) {
// with integer scales.
const bool upsample = !Math::is_equal_approx(Math::round(scale), scale);
ImageLoaderSVG img_loader;
- img_loader.create_image_from_string(img, default_theme_icons_sources[p_index], scale, upsample, false);
+ img_loader.create_image_from_string(img, default_theme_icons_sources[p_index], scale, upsample, HashMap<Color, Color>());
#endif
return ImageTexture::create_from_image(img);
@@ -177,6 +177,27 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
theme->set_constant("h_separation", "Button", 2 * scale);
+ // MenuBar
+ theme->set_stylebox("normal", "MenuBar", button_normal);
+ theme->set_stylebox("hover", "MenuBar", button_hover);
+ theme->set_stylebox("pressed", "MenuBar", button_pressed);
+ theme->set_stylebox("disabled", "MenuBar", button_disabled);
+ theme->set_stylebox("focus", "MenuBar", focus);
+
+ theme->set_font("font", "MenuBar", Ref<Font>());
+ theme->set_font_size("font_size", "MenuBar", -1);
+ theme->set_constant("outline_size", "MenuBar", 0 * scale);
+
+ theme->set_color("font_color", "MenuBar", control_font_color);
+ theme->set_color("font_pressed_color", "MenuBar", control_font_pressed_color);
+ theme->set_color("font_hover_color", "MenuBar", control_font_hover_color);
+ theme->set_color("font_focus_color", "MenuBar", control_font_focus_color);
+ theme->set_color("font_hover_pressed_color", "MenuBar", control_font_pressed_color);
+ theme->set_color("font_disabled_color", "MenuBar", control_font_disabled_color);
+ theme->set_color("font_outline_color", "MenuBar", Color(1, 1, 1));
+
+ theme->set_constant("h_separation", "MenuBar", 4 * scale);
+
// LinkButton
theme->set_stylebox("focus", "LinkButton", focus);
@@ -669,6 +690,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
theme->set_color("font_outline_color", "PopupMenu", Color(1, 1, 1));
theme->set_color("font_separator_outline_color", "PopupMenu", Color(1, 1, 1));
+ theme->set_constant("indent", "PopupMenu", 10 * scale);
theme->set_constant("h_separation", "PopupMenu", 4 * scale);
theme->set_constant("v_separation", "PopupMenu", 4 * scale);
theme->set_constant("outline_size", "PopupMenu", 0);
diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp
index d361b34da8..f7a7818b3b 100644
--- a/scene/resources/environment.cpp
+++ b/scene/resources/environment.cpp
@@ -1037,46 +1037,46 @@ void Environment::_update_adjustment() {
// Private methods, constructor and destructor
-void Environment::_validate_property(PropertyInfo &property) const {
- if (property.name == "sky" || property.name == "sky_custom_fov" || property.name == "sky_rotation" || property.name == "ambient_light/sky_contribution") {
+void Environment::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "sky" || p_property.name == "sky_custom_fov" || p_property.name == "sky_rotation" || p_property.name == "ambient_light_sky_contribution") {
if (bg_mode != BG_SKY && ambient_source != AMBIENT_SOURCE_SKY && reflection_source != REFLECTION_SOURCE_SKY) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- if (property.name == "fog_aerial_perspective") {
+ if (p_property.name == "fog_aerial_perspective") {
if (bg_mode != BG_SKY) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- if (property.name == "tonemap_white" && tone_mapper == TONE_MAPPER_LINEAR) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "tonemap_white" && tone_mapper == TONE_MAPPER_LINEAR) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "glow_intensity" && glow_blend_mode == GLOW_BLEND_MODE_MIX) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "glow_intensity" && glow_blend_mode == GLOW_BLEND_MODE_MIX) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "glow_mix" && glow_blend_mode != GLOW_BLEND_MODE_MIX) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name == "glow_mix" && glow_blend_mode != GLOW_BLEND_MODE_MIX) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "background_color") {
+ if (p_property.name == "background_color") {
if (bg_mode != BG_COLOR && ambient_source != AMBIENT_SOURCE_COLOR) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- if (property.name == "background_canvas_max_layer") {
+ if (p_property.name == "background_canvas_max_layer") {
if (bg_mode != BG_CANVAS) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
- if (property.name == "background_camera_feed_id") {
+ if (p_property.name == "background_camera_feed_id") {
if (bg_mode != BG_CAMERA_FEED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
@@ -1107,8 +1107,8 @@ void Environment::_validate_property(PropertyInfo &property) const {
String prefix = String(*prefixes);
String enabled = prefix + "enabled";
- if (property.name.begins_with(prefix) && property.name != enabled && !bool(get(enabled))) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name.begins_with(prefix) && p_property.name != enabled && !bool(get(enabled))) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
return;
}
@@ -1120,8 +1120,8 @@ void Environment::_validate_property(PropertyInfo &property) const {
while (*prefixes) {
String prefix = String(*prefixes);
- if (property.name.begins_with(prefix)) {
- property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ if (p_property.name.begins_with(prefix)) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
return;
}
diff --git a/scene/resources/environment.h b/scene/resources/environment.h
index 385d815230..d39cb1acd8 100644
--- a/scene/resources/environment.h
+++ b/scene/resources/environment.h
@@ -211,7 +211,7 @@ private:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
#ifndef DISABLE_DEPRECATED
// Kept for compatibility from 3.x to 4.0.
bool _set(const StringName &p_name, const Variant &p_value);
diff --git a/scene/resources/font.cpp b/scene/resources/font.cpp
index 880876baed..f8651fecd6 100644
--- a/scene/resources/font.cpp
+++ b/scene/resources/font.cpp
@@ -1267,7 +1267,7 @@ void FontFile::_get_property_list(List<PropertyInfo> *p_list) const {
}
for (int i = 0; i < cache.size(); i++) {
String prefix = "cache/" + itos(i) + "/";
- Array sizes = get_size_cache_list(i);
+ TypedArray<Vector2i> sizes = get_size_cache_list(i);
p_list->push_back(PropertyInfo(Variant::DICTIONARY, prefix + "variation_coordinates", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
p_list->push_back(PropertyInfo(Variant::INT, "face_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
p_list->push_back(PropertyInfo(Variant::FLOAT, "embolden", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
@@ -1289,7 +1289,7 @@ void FontFile::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::PACKED_INT32_ARRAY, prefix_sz + "textures/" + itos(k) + "/offsets", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
p_list->push_back(PropertyInfo(Variant::OBJECT, prefix_sz + "textures/" + itos(k) + "/image", PROPERTY_HINT_RESOURCE_TYPE, "Image", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT));
}
- Array glyphs = get_glyph_list(i, sz);
+ PackedInt32Array glyphs = get_glyph_list(i, sz);
for (int k = 0; k < glyphs.size(); k++) {
const int32_t &gl = glyphs[k];
if (sz.y == 0) {
@@ -1301,7 +1301,7 @@ void FontFile::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::INT, prefix_sz + "glyphs/" + itos(gl) + "/texture_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
}
if (sz.y == 0) {
- Array kerning_map = get_kerning_list(i, sz.x);
+ TypedArray<Vector2i> kerning_map = get_kerning_list(i, sz.x);
for (int k = 0; k < kerning_map.size(); k++) {
const Vector2i &gl_pair = kerning_map[k];
p_list->push_back(PropertyInfo(Variant::VECTOR2, prefix_sz + "kerning_overrides/" + itos(gl_pair.x) + "/" + itos(gl_pair.y), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
@@ -2089,7 +2089,7 @@ void FontFile::remove_cache(int p_cache_index) {
emit_changed();
}
-Array FontFile::get_size_cache_list(int p_cache_index) const {
+TypedArray<Vector2i> FontFile::get_size_cache_list(int p_cache_index) const {
ERR_FAIL_COND_V(p_cache_index < 0, Array());
_ensure_rid(p_cache_index);
return TS->font_get_size_cache_list(cache[p_cache_index]);
@@ -2260,8 +2260,8 @@ PackedInt32Array FontFile::get_texture_offsets(int p_cache_index, const Vector2i
return TS->font_get_texture_offsets(cache[p_cache_index], p_size, p_texture_index);
}
-Array FontFile::get_glyph_list(int p_cache_index, const Vector2i &p_size) const {
- ERR_FAIL_COND_V(p_cache_index < 0, Array());
+PackedInt32Array FontFile::get_glyph_list(int p_cache_index, const Vector2i &p_size) const {
+ ERR_FAIL_COND_V(p_cache_index < 0, PackedInt32Array());
_ensure_rid(p_cache_index);
return TS->font_get_glyph_list(cache[p_cache_index], p_size);
}
@@ -2338,7 +2338,7 @@ int FontFile::get_glyph_texture_idx(int p_cache_index, const Vector2i &p_size, i
return TS->font_get_glyph_texture_idx(cache[p_cache_index], p_size, p_glyph);
}
-Array FontFile::get_kerning_list(int p_cache_index, int p_size) const {
+TypedArray<Vector2i> FontFile::get_kerning_list(int p_cache_index, int p_size) const {
ERR_FAIL_COND_V(p_cache_index < 0, Array());
_ensure_rid(p_cache_index);
return TS->font_get_kerning_list(cache[p_cache_index], p_size);
@@ -2714,6 +2714,9 @@ void SystemFont::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_subpixel_positioning", "subpixel_positioning"), &SystemFont::set_subpixel_positioning);
ClassDB::bind_method(D_METHOD("get_subpixel_positioning"), &SystemFont::get_subpixel_positioning);
+ ClassDB::bind_method(D_METHOD("set_multichannel_signed_distance_field", "msdf"), &SystemFont::set_multichannel_signed_distance_field);
+ ClassDB::bind_method(D_METHOD("is_multichannel_signed_distance_field"), &SystemFont::is_multichannel_signed_distance_field);
+
ClassDB::bind_method(D_METHOD("set_oversampling", "oversampling"), &SystemFont::set_oversampling);
ClassDB::bind_method(D_METHOD("get_oversampling"), &SystemFont::get_oversampling);
@@ -2729,6 +2732,7 @@ void SystemFont::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "force_autohinter"), "set_force_autohinter", "is_force_autohinter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "hinting", PROPERTY_HINT_ENUM, "None,Light,Normal"), "set_hinting", "get_hinting");
ADD_PROPERTY(PropertyInfo(Variant::INT, "subpixel_positioning", PROPERTY_HINT_ENUM, "Disabled,Auto,One half of a pixel,One quarter of a pixel"), "set_subpixel_positioning", "get_subpixel_positioning");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multichannel_signed_distance_field"), "set_multichannel_signed_distance_field", "is_multichannel_signed_distance_field");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "oversampling", PROPERTY_HINT_RANGE, "0,10,0.1"), "set_oversampling", "get_oversampling");
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "Font")), "set_fallbacks", "get_fallbacks");
}
@@ -2805,6 +2809,7 @@ void SystemFont::_update_base_font() {
file->set_force_autohinter(force_autohinter);
file->set_hinting(hinting);
file->set_subpixel_positioning(subpixel_positioning);
+ file->set_multichannel_signed_distance_field(msdf);
file->set_oversampling(oversampling);
base_font = file;
@@ -2842,6 +2847,7 @@ void SystemFont::reset_state() {
hinting = TextServer::HINTING_LIGHT;
subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_DISABLED;
oversampling = 0.f;
+ msdf = false;
Font::reset_state();
}
@@ -2971,6 +2977,20 @@ TextServer::SubpixelPositioning SystemFont::get_subpixel_positioning() const {
return subpixel_positioning;
}
+void SystemFont::set_multichannel_signed_distance_field(bool p_msdf) {
+ if (msdf != p_msdf) {
+ msdf = p_msdf;
+ if (base_font.is_valid()) {
+ base_font->set_multichannel_signed_distance_field(msdf);
+ }
+ emit_changed();
+ }
+}
+
+bool SystemFont::is_multichannel_signed_distance_field() const {
+ return msdf;
+}
+
void SystemFont::set_oversampling(real_t p_oversampling) {
if (oversampling != p_oversampling) {
oversampling = p_oversampling;
diff --git a/scene/resources/font.h b/scene/resources/font.h
index 260b4e521f..decbcfbb69 100644
--- a/scene/resources/font.h
+++ b/scene/resources/font.h
@@ -230,7 +230,7 @@ public:
virtual void clear_cache();
virtual void remove_cache(int p_cache_index);
- virtual Array get_size_cache_list(int p_cache_index) const;
+ virtual TypedArray<Vector2i> get_size_cache_list(int p_cache_index) const;
virtual void clear_size_cache(int p_cache_index);
virtual void remove_size_cache(int p_cache_index, const Vector2i &p_size);
@@ -271,7 +271,7 @@ public:
virtual void set_texture_offsets(int p_cache_index, const Vector2i &p_size, int p_texture_index, const PackedInt32Array &p_offset);
virtual PackedInt32Array get_texture_offsets(int p_cache_index, const Vector2i &p_size, int p_texture_index) const;
- virtual Array get_glyph_list(int p_cache_index, const Vector2i &p_size) const;
+ virtual PackedInt32Array get_glyph_list(int p_cache_index, const Vector2i &p_size) const;
virtual void clear_glyphs(int p_cache_index, const Vector2i &p_size);
virtual void remove_glyph(int p_cache_index, const Vector2i &p_size, int32_t p_glyph);
@@ -290,7 +290,7 @@ public:
virtual void set_glyph_texture_idx(int p_cache_index, const Vector2i &p_size, int32_t p_glyph, int p_texture_idx);
virtual int get_glyph_texture_idx(int p_cache_index, const Vector2i &p_size, int32_t p_glyph) const;
- virtual Array get_kerning_list(int p_cache_index, int p_size) const;
+ virtual TypedArray<Vector2i> get_kerning_list(int p_cache_index, int p_size) const;
virtual void clear_kerning_map(int p_cache_index, int p_size);
virtual void remove_kerning(int p_cache_index, int p_size, const Vector2i &p_glyph_pair);
@@ -404,6 +404,7 @@ class SystemFont : public Font {
TextServer::Hinting hinting = TextServer::HINTING_LIGHT;
TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO;
real_t oversampling = 0.f;
+ bool msdf = false;
protected:
static void _bind_methods();
@@ -434,6 +435,9 @@ public:
virtual void set_oversampling(real_t p_oversampling);
virtual real_t get_oversampling() const;
+ virtual void set_multichannel_signed_distance_field(bool p_msdf);
+ virtual bool is_multichannel_signed_distance_field() const;
+
virtual void set_font_names(const PackedStringArray &p_names);
virtual PackedStringArray get_font_names() const;
diff --git a/scene/resources/immediate_mesh.cpp b/scene/resources/immediate_mesh.cpp
index 044477e744..90cc3ea5f4 100644
--- a/scene/resources/immediate_mesh.cpp
+++ b/scene/resources/immediate_mesh.cpp
@@ -340,8 +340,8 @@ Array ImmediateMesh::surface_get_arrays(int p_surface) const {
ERR_FAIL_INDEX_V(p_surface, int(surfaces.size()), Array());
return RS::get_singleton()->mesh_surface_get_arrays(mesh, p_surface);
}
-Array ImmediateMesh::surface_get_blend_shape_arrays(int p_surface) const {
- return Array();
+TypedArray<Array> ImmediateMesh::surface_get_blend_shape_arrays(int p_surface) const {
+ return TypedArray<Array>();
}
Dictionary ImmediateMesh::surface_get_lods(int p_surface) const {
return Dictionary();
diff --git a/scene/resources/immediate_mesh.h b/scene/resources/immediate_mesh.h
index de10fdbfbe..0dad62f555 100644
--- a/scene/resources/immediate_mesh.h
+++ b/scene/resources/immediate_mesh.h
@@ -97,7 +97,7 @@ public:
virtual int surface_get_array_len(int p_idx) const override;
virtual int surface_get_array_index_len(int p_idx) const override;
virtual Array surface_get_arrays(int p_surface) const override;
- virtual Array surface_get_blend_shape_arrays(int p_surface) const override;
+ virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override;
virtual Dictionary surface_get_lods(int p_surface) const override;
virtual uint32_t surface_get_format(int p_idx) const override;
virtual PrimitiveType surface_get_primitive_type(int p_idx) const override;
diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp
index 88bc01fb25..bd0e470112 100644
--- a/scene/resources/material.cpp
+++ b/scene/resources/material.cpp
@@ -71,12 +71,12 @@ RID Material::get_rid() const {
return material;
}
-void Material::_validate_property(PropertyInfo &property) const {
- if (!_can_do_next_pass() && property.name == "next_pass") {
- property.usage = PROPERTY_USAGE_NONE;
+void Material::_validate_property(PropertyInfo &p_property) const {
+ if (!_can_do_next_pass() && p_property.name == "next_pass") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (!_can_use_render_priority() && property.name == "render_priority") {
- property.usage = PROPERTY_USAGE_NONE;
+ if (!_can_use_render_priority() && p_property.name == "render_priority") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
@@ -297,7 +297,7 @@ void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const {
}
}
-bool ShaderMaterial::property_can_revert(const String &p_name) {
+bool ShaderMaterial::_property_can_revert(const StringName &p_name) const {
if (shader.is_valid()) {
StringName pr = shader->remap_uniform(p_name);
if (pr) {
@@ -310,15 +310,15 @@ bool ShaderMaterial::property_can_revert(const String &p_name) {
return false;
}
-Variant ShaderMaterial::property_get_revert(const String &p_name) {
- Variant r_ret;
+bool ShaderMaterial::_property_get_revert(const StringName &p_name, Variant &r_property) const {
if (shader.is_valid()) {
StringName pr = shader->remap_uniform(p_name);
if (pr) {
- r_ret = RenderingServer::get_singleton()->shader_get_param_default(shader->get_rid(), pr);
+ r_property = RenderingServer::get_singleton()->shader_get_param_default(shader->get_rid(), pr);
+ return true;
}
}
- return r_ret;
+ return false;
}
void ShaderMaterial::set_shader(const Ref<Shader> &p_shader) {
@@ -386,8 +386,6 @@ void ShaderMaterial::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_shader"), &ShaderMaterial::get_shader);
ClassDB::bind_method(D_METHOD("set_shader_uniform", "param", "value"), &ShaderMaterial::set_shader_uniform);
ClassDB::bind_method(D_METHOD("get_shader_uniform", "param"), &ShaderMaterial::get_shader_uniform);
- ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &ShaderMaterial::property_can_revert);
- ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &ShaderMaterial::property_get_revert);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shader", PROPERTY_HINT_RESOURCE_TYPE, "Shader"), "set_shader", "get_shader");
}
@@ -1869,61 +1867,61 @@ void BaseMaterial3D::_validate_high_end(const String &text, PropertyInfo &proper
}
}
-void BaseMaterial3D::_validate_property(PropertyInfo &property) const {
- _validate_feature("normal", FEATURE_NORMAL_MAPPING, property);
- _validate_feature("emission", FEATURE_EMISSION, property);
- _validate_feature("rim", FEATURE_RIM, property);
- _validate_feature("clearcoat", FEATURE_CLEARCOAT, property);
- _validate_feature("anisotropy", FEATURE_ANISOTROPY, property);
- _validate_feature("ao", FEATURE_AMBIENT_OCCLUSION, property);
- _validate_feature("heightmap", FEATURE_HEIGHT_MAPPING, property);
- _validate_feature("subsurf_scatter", FEATURE_SUBSURFACE_SCATTERING, property);
- _validate_feature("backlight", FEATURE_BACKLIGHT, property);
- _validate_feature("refraction", FEATURE_REFRACTION, property);
- _validate_feature("detail", FEATURE_DETAIL, property);
+void BaseMaterial3D::_validate_property(PropertyInfo &p_property) const {
+ _validate_feature("normal", FEATURE_NORMAL_MAPPING, p_property);
+ _validate_feature("emission", FEATURE_EMISSION, p_property);
+ _validate_feature("rim", FEATURE_RIM, p_property);
+ _validate_feature("clearcoat", FEATURE_CLEARCOAT, p_property);
+ _validate_feature("anisotropy", FEATURE_ANISOTROPY, p_property);
+ _validate_feature("ao", FEATURE_AMBIENT_OCCLUSION, p_property);
+ _validate_feature("heightmap", FEATURE_HEIGHT_MAPPING, p_property);
+ _validate_feature("subsurf_scatter", FEATURE_SUBSURFACE_SCATTERING, p_property);
+ _validate_feature("backlight", FEATURE_BACKLIGHT, p_property);
+ _validate_feature("refraction", FEATURE_REFRACTION, p_property);
+ _validate_feature("detail", FEATURE_DETAIL, p_property);
- _validate_high_end("refraction", property);
- _validate_high_end("subsurf_scatter", property);
- _validate_high_end("heightmap", property);
+ _validate_high_end("refraction", p_property);
+ _validate_high_end("subsurf_scatter", p_property);
+ _validate_high_end("heightmap", p_property);
- if (property.name.begins_with("particles_anim_") && billboard_mode != BILLBOARD_PARTICLES) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("particles_anim_") && billboard_mode != BILLBOARD_PARTICLES) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "billboard_keep_scale" && billboard_mode == BILLBOARD_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "billboard_keep_scale" && billboard_mode == BILLBOARD_DISABLED) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "grow_amount" && !grow_enabled) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "grow_amount" && !grow_enabled) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "point_size" && !flags[FLAG_USE_POINT_SIZE]) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "point_size" && !flags[FLAG_USE_POINT_SIZE]) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "proximity_fade_distance" && !proximity_fade_enabled) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "proximity_fade_distance" && !proximity_fade_enabled) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "msdf_pixel_range" && !flags[FLAG_ALBEDO_TEXTURE_MSDF]) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "msdf_pixel_range" && !flags[FLAG_ALBEDO_TEXTURE_MSDF]) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (property.name == "msdf_outline_size" && !flags[FLAG_ALBEDO_TEXTURE_MSDF]) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "msdf_outline_size" && !flags[FLAG_ALBEDO_TEXTURE_MSDF]) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if ((property.name == "distance_fade_max_distance" || property.name == "distance_fade_min_distance") && distance_fade == DISTANCE_FADE_DISABLED) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if ((p_property.name == "distance_fade_max_distance" || p_property.name == "distance_fade_min_distance") && distance_fade == DISTANCE_FADE_DISABLED) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if ((property.name == "uv1_triplanar_sharpness" || property.name == "uv1_world_triplanar") && !flags[FLAG_UV1_USE_TRIPLANAR]) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if ((p_property.name == "uv1_triplanar_sharpness" || p_property.name == "uv1_world_triplanar") && !flags[FLAG_UV1_USE_TRIPLANAR]) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if ((property.name == "uv2_triplanar_sharpness" || property.name == "uv2_world_triplanar") && !flags[FLAG_UV2_USE_TRIPLANAR]) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if ((p_property.name == "uv2_triplanar_sharpness" || p_property.name == "uv2_world_triplanar") && !flags[FLAG_UV2_USE_TRIPLANAR]) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
// you can only enable anti-aliasing (in materials) on alpha scissor and alpha hash
@@ -1932,96 +1930,96 @@ void BaseMaterial3D::_validate_property(PropertyInfo &property) const {
const bool alpha_aa_enabled = (alpha_antialiasing_mode != ALPHA_ANTIALIASING_OFF) && can_select_aa;
// alpha scissor slider isn't needed when alpha antialiasing is enabled
- if (property.name == "alpha_scissor_threshold" && transparency != TRANSPARENCY_ALPHA_SCISSOR) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "alpha_scissor_threshold" && transparency != TRANSPARENCY_ALPHA_SCISSOR) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
// alpha hash scale slider is only needed if transparency is alpha hash
- if (property.name == "alpha_hash_scale" && transparency != TRANSPARENCY_ALPHA_HASH) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "alpha_hash_scale" && transparency != TRANSPARENCY_ALPHA_HASH) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "alpha_antialiasing_mode" && !can_select_aa) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "alpha_antialiasing_mode" && !can_select_aa) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
// we can't choose an antialiasing mode if alpha isn't possible
- if (property.name == "alpha_antialiasing_edge" && !alpha_aa_enabled) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "alpha_antialiasing_edge" && !alpha_aa_enabled) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "blend_mode" && alpha_aa_enabled) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "blend_mode" && alpha_aa_enabled) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if ((property.name == "heightmap_min_layers" || property.name == "heightmap_max_layers") && !deep_parallax) {
- property.usage = PROPERTY_USAGE_NONE;
+ if ((p_property.name == "heightmap_min_layers" || p_property.name == "heightmap_max_layers") && !deep_parallax) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (flags[FLAG_SUBSURFACE_MODE_SKIN] && (property.name == "subsurf_scatter_transmittance_color" || property.name == "subsurf_scatter_transmittance_texture")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (flags[FLAG_SUBSURFACE_MODE_SKIN] && (p_property.name == "subsurf_scatter_transmittance_color" || p_property.name == "subsurf_scatter_transmittance_texture")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
if (orm) {
- if (property.name == "shading_mode") {
+ if (p_property.name == "shading_mode") {
// Vertex not supported in ORM mode, since no individual roughness.
- property.hint_string = "Unshaded,Per-Pixel";
+ p_property.hint_string = "Unshaded,Per-Pixel";
}
- if (property.name.begins_with("roughness") || property.name.begins_with("metallic") || property.name.begins_with("ao_texture")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("roughness") || p_property.name.begins_with("metallic") || p_property.name.begins_with("ao_texture")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
} else {
- if (property.name == "orm_texture") {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "orm_texture") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
if (shading_mode != SHADING_MODE_PER_PIXEL) {
if (shading_mode != SHADING_MODE_PER_VERTEX) {
//these may still work per vertex
- if (property.name.begins_with("ao")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("ao")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("emission")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("emission")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("metallic")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("metallic")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("rim")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("rim")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("roughness")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("roughness")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("subsurf_scatter")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("subsurf_scatter")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
//these definitely only need per pixel
- if (property.name.begins_with("anisotropy")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("anisotropy")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("clearcoat")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("clearcoat")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("normal")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("normal")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("backlight")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("backlight")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("transmittance")) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("transmittance")) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
}
@@ -2054,8 +2052,9 @@ Vector3 BaseMaterial3D::get_uv1_offset() const {
}
void BaseMaterial3D::set_uv1_triplanar_blend_sharpness(float p_sharpness) {
- uv1_triplanar_sharpness = p_sharpness;
- RS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_blend_sharpness, p_sharpness);
+ // Negative values or values higher than 150 can result in NaNs, leading to broken rendering.
+ uv1_triplanar_sharpness = CLAMP(p_sharpness, 0.0, 150.0);
+ RS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_blend_sharpness, uv1_triplanar_sharpness);
}
float BaseMaterial3D::get_uv1_triplanar_blend_sharpness() const {
@@ -2081,8 +2080,9 @@ Vector3 BaseMaterial3D::get_uv2_offset() const {
}
void BaseMaterial3D::set_uv2_triplanar_blend_sharpness(float p_sharpness) {
- uv2_triplanar_sharpness = p_sharpness;
- RS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_blend_sharpness, p_sharpness);
+ // Negative values or values higher than 150 can result in NaNs, leading to broken rendering.
+ uv2_triplanar_sharpness = CLAMP(p_sharpness, 0.0, 150.0);
+ RS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_blend_sharpness, uv2_triplanar_sharpness);
}
float BaseMaterial3D::get_uv2_triplanar_blend_sharpness() const {
diff --git a/scene/resources/material.h b/scene/resources/material.h
index ca5b17dd07..c6be1b8766 100644
--- a/scene/resources/material.h
+++ b/scene/resources/material.h
@@ -54,7 +54,7 @@ protected:
virtual bool _can_do_next_pass() const;
virtual bool _can_use_render_priority() const;
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
GDVIRTUAL0RC(RID, _get_shader_rid)
GDVIRTUAL0RC(Shader::Mode, _get_shader_mode)
@@ -99,8 +99,8 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
- bool property_can_revert(const String &p_name);
- Variant property_get_revert(const String &p_name);
+ bool _property_can_revert(const StringName &p_name) const;
+ bool _property_get_revert(const StringName &p_name, Variant &r_property) const;
static void _bind_methods();
@@ -553,7 +553,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
virtual bool _can_do_next_pass() const override { return true; }
virtual bool _can_use_render_priority() const override { return true; }
diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp
index ec9db89794..7f318af899 100644
--- a/scene/resources/mesh.cpp
+++ b/scene/resources/mesh.cpp
@@ -32,11 +32,10 @@
#include "core/math/convex_hull.h"
#include "core/templates/pair.h"
+#include "scene/resources/surface_tool.h"
+
#include "scene/resources/concave_polygon_shape_3d.h"
#include "scene/resources/convex_polygon_shape_3d.h"
-#include "surface_tool.h"
-
-#include <stdlib.h>
Mesh::ConvexDecompositionFunc Mesh::convex_decomposition_function = nullptr;
@@ -72,13 +71,13 @@ Array Mesh::surface_get_arrays(int p_surface) const {
return Array();
}
-Array Mesh::surface_get_blend_shape_arrays(int p_surface) const {
- Array ret;
+TypedArray<Array> Mesh::surface_get_blend_shape_arrays(int p_surface) const {
+ TypedArray<Array> ret;
if (GDVIRTUAL_REQUIRED_CALL(_surface_get_blend_shape_arrays, p_surface, ret)) {
return ret;
}
- return Array();
+ return TypedArray<Array>();
}
Dictionary Mesh::surface_get_lods(int p_surface) const {
@@ -201,7 +200,9 @@ Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
continue;
}
int len = (surface_get_format(i) & ARRAY_FORMAT_INDEX) ? surface_get_array_index_len(i) : surface_get_array_len(i);
- if ((primitive == PRIMITIVE_TRIANGLES && (len == 0 || (len % 3) != 0)) || (primitive == PRIMITIVE_TRIANGLE_STRIP && len < 3)) {
+ if ((primitive == PRIMITIVE_TRIANGLES && (len == 0 || (len % 3) != 0)) ||
+ (primitive == PRIMITIVE_TRIANGLE_STRIP && len < 3) ||
+ (surface_get_format(i) & ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY)) {
// Error was already shown, just skip (including zero).
continue;
}
@@ -211,6 +212,7 @@ Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
int vc = surface_get_array_len(i);
Vector<Vector3> vertices = a[ARRAY_VERTEX];
+ ERR_FAIL_COND_V(vertices.is_empty(), Ref<TriangleMesh>());
const Vector3 *vr = vertices.ptr();
int32_t from_index = widx / 3;
@@ -863,27 +865,6 @@ static Mesh::PrimitiveType _old_primitives[7] = {
};
#endif // DISABLE_DEPRECATED
-// Convert Octahedron-mapped normalized vector back to Cartesian
-// Assumes normalized format (elements of v within range [-1, 1])
-Vector3 _oct_to_norm(const Vector2 v) {
- Vector3 res(v.x, v.y, 1 - (Math::absf(v.x) + Math::absf(v.y)));
- float t = MAX(-res.z, 0.0f);
- res.x += t * -SIGN(res.x);
- res.y += t * -SIGN(res.y);
- return res.normalized();
-}
-
-// Convert Octahedron-mapped normalized tangent vector back to Cartesian
-// out_sign provides the direction for the original cartesian tangent
-// Assumes normalized format (elements of v within range [-1, 1])
-Vector3 _oct_to_tangent(const Vector2 v, float *out_sign) {
- Vector2 v_decompressed = v;
- v_decompressed.y = Math::absf(v_decompressed.y) * 2 - 1;
- Vector3 res = _oct_to_norm(v_decompressed);
- *out_sign = SIGN(v[1]);
- return res;
-}
-
void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_format, uint32_t p_new_format, uint32_t p_elements, Vector<uint8_t> &vertex_data, Vector<uint8_t> &attribute_data, Vector<uint8_t> &skin_data) {
uint32_t dst_vertex_stride;
uint32_t dst_attribute_stride;
@@ -954,127 +935,93 @@ void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_forma
if ((p_old_format & OLD_ARRAY_COMPRESS_NORMAL) && (p_old_format & OLD_ARRAY_FORMAT_TANGENT) && (p_old_format & OLD_ARRAY_COMPRESS_TANGENT)) {
for (uint32_t i = 0; i < p_elements; i++) {
const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
- const Vector2 src_vec(src[0] / 127.0f, src[1] / 127.0f);
-
- const Vector3 res = _oct_to_norm(src_vec) * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
- *dst = 0;
- *dst |= CLAMP(int(res.x * 1023.0f), 0, 1023);
- *dst |= CLAMP(int(res.y * 1023.0f), 0, 1023) << 10;
- *dst |= CLAMP(int(res.z * 1023.0f), 0, 1023) << 20;
+ int16_t *dst = (int16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+
+ dst[0] = (int16_t)CLAMP(src[0] / 127.0f * 32767, -32768, 32767);
+ dst[1] = (int16_t)CLAMP(src[1] / 127.0f * 32767, -32768, 32767);
}
- src_offset += sizeof(int8_t) * 2;
+ src_offset += sizeof(int16_t) * 2;
} else {
for (uint32_t i = 0; i < p_elements; i++) {
const int16_t *src = (const int16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
- const Vector2 src_vec(src[0] / 32767.0f, src[1] / 32767.0f);
-
- const Vector3 res = _oct_to_norm(src_vec) * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
- *dst = 0;
- *dst |= CLAMP(int(res.x * 1023.0f), 0, 1023);
- *dst |= CLAMP(int(res.y * 1023.0f), 0, 1023) << 10;
- *dst |= CLAMP(int(res.z * 1023.0f), 0, 1023) << 20;
+ int16_t *dst = (int16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+
+ dst[0] = src[0];
+ dst[1] = src[1];
}
src_offset += sizeof(int16_t) * 2;
}
} else { // No Octahedral compression
if (p_old_format & OLD_ARRAY_COMPRESS_NORMAL) {
- const float multiplier = 1.f / 127.f * 1023.0f;
-
for (uint32_t i = 0; i < p_elements; i++) {
const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+ const Vector3 original_normal(src[0], src[1], src[2]);
+ Vector2 res = original_normal.octahedron_encode();
- *dst = 0;
- *dst |= CLAMP(int(src[0] * multiplier), 0, 1023);
- *dst |= CLAMP(int(src[1] * multiplier), 0, 1023) << 10;
- *dst |= CLAMP(int(src[2] * multiplier), 0, 1023) << 20;
+ uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+ dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(uint32_t);
+ src_offset += sizeof(uint16_t) * 2;
} else {
for (uint32_t i = 0; i < p_elements; i++) {
const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+ const Vector3 original_normal(src[0], src[1], src[2]);
+ Vector2 res = original_normal.octahedron_encode();
- *dst = 0;
- *dst |= CLAMP(int(src[0] * 1023.0), 0, 1023);
- *dst |= CLAMP(int(src[1] * 1023.0), 0, 1023) << 10;
- *dst |= CLAMP(int(src[2] * 1023.0), 0, 1023) << 20;
+ uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+ dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(float) * 3;
+ src_offset += sizeof(uint16_t) * 2;
}
}
} break;
case OLD_ARRAY_TANGENT: {
if (p_old_format & OLD_ARRAY_FLAG_USE_OCTAHEDRAL_COMPRESSION) {
- if (p_old_format & OLD_ARRAY_COMPRESS_TANGENT) { // int8
+ if (p_old_format & OLD_ARRAY_COMPRESS_TANGENT) { // int8 SNORM -> uint16 UNORM
for (uint32_t i = 0; i < p_elements; i++) {
const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
- const Vector2 src_vec(src[0] / 127.0f, src[1] / 127.0f);
- float out_sign;
- const Vector3 res = _oct_to_tangent(src_vec, &out_sign) * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
-
- *dst = 0;
- *dst |= CLAMP(int(res.x * 1023.0), 0, 1023);
- *dst |= CLAMP(int(res.y * 1023.0), 0, 1023) << 10;
- *dst |= CLAMP(int(res.z * 1023.0), 0, 1023) << 20;
- if (out_sign > 0) {
- *dst |= 3 << 30;
- }
+ uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
+
+ dst[0] = (uint16_t)CLAMP((src[0] / 127.0f * .5f + .5f) * 65535, 0, 65535);
+ dst[1] = (uint16_t)CLAMP((src[1] / 127.0f * .5f + .5f) * 65535, 0, 65535);
}
- src_offset += sizeof(int8_t) * 2;
- } else { // int16
+ src_offset += sizeof(uint16_t) * 2;
+ } else { // int16 SNORM -> uint16 UNORM
for (uint32_t i = 0; i < p_elements; i++) {
const int16_t *src = (const int16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
- const Vector2 src_vec(src[0] / 32767.0f, src[1] / 32767.0f);
- float out_sign;
- Vector3 res = _oct_to_tangent(src_vec, &out_sign) * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
-
- *dst = 0;
- *dst |= CLAMP(int(res.x * 1023.0), 0, 1023);
- *dst |= CLAMP(int(res.y * 1023.0), 0, 1023) << 10;
- *dst |= CLAMP(int(res.z * 1023.0), 0, 1023) << 20;
- if (out_sign > 0) {
- *dst |= 3 << 30;
- }
+ uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
+
+ dst[0] = (uint16_t)CLAMP((src[0] / 32767.0f * .5f + .5f) * 65535, 0, 65535);
+ dst[1] = (uint16_t)CLAMP((src[1] / 32767.0f * .5f + .5f) * 65535, 0, 65535);
}
- src_offset += sizeof(int16_t) * 2;
+ src_offset += sizeof(uint16_t) * 2;
}
} else { // No Octahedral compression
if (p_old_format & OLD_ARRAY_COMPRESS_TANGENT) {
- const float multiplier = 1.f / 127.f * 1023.0f;
-
for (uint32_t i = 0; i < p_elements; i++) {
const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
-
- *dst = 0;
- *dst |= CLAMP(int(src[0] * multiplier), 0, 1023);
- *dst |= CLAMP(int(src[1] * multiplier), 0, 1023) << 10;
- *dst |= CLAMP(int(src[2] * multiplier), 0, 1023) << 20;
- if (src[3] > 0) {
- *dst |= 3 << 30;
- }
+ const Vector3 original_tangent(src[0], src[1], src[2]);
+ Vector2 res = original_tangent.octahedron_tangent_encode(src[3]);
+
+ uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+ dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(uint32_t);
+ src_offset += sizeof(uint16_t) * 2;
} else {
for (uint32_t i = 0; i < p_elements; i++) {
const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
- uint32_t *dst = (uint32_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
-
- *dst = 0;
- *dst |= CLAMP(int(src[0] * 1023.0), 0, 1023);
- *dst |= CLAMP(int(src[1] * 1023.0), 0, 1023) << 10;
- *dst |= CLAMP(int(src[2] * 1023.0), 0, 1023) << 20;
- if (src[3] > 0) {
- *dst |= 3 << 30;
- }
+ const Vector3 original_tangent(src[0], src[1], src[2]);
+ Vector2 res = original_tangent.octahedron_tangent_encode(src[3]);
+
+ uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
+ dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
+ dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(float) * 4;
+ src_offset += sizeof(uint16_t) * 2;
}
}
} break;
@@ -1693,8 +1640,8 @@ Array ArrayMesh::surface_get_arrays(int p_surface) const {
return RenderingServer::get_singleton()->mesh_surface_get_arrays(mesh, p_surface);
}
-Array ArrayMesh::surface_get_blend_shape_arrays(int p_surface) const {
- ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
+TypedArray<Array> ArrayMesh::surface_get_blend_shape_arrays(int p_surface) const {
+ ERR_FAIL_INDEX_V(p_surface, surfaces.size(), TypedArray<Array>());
return RenderingServer::get_singleton()->mesh_surface_get_blend_shape_arrays(mesh, p_surface);
}
diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h
index 142373ce7f..fd3c2c4fa4 100644
--- a/scene/resources/mesh.h
+++ b/scene/resources/mesh.h
@@ -63,7 +63,7 @@ protected:
GDVIRTUAL1RC(int, _surface_get_array_len, int)
GDVIRTUAL1RC(int, _surface_get_array_index_len, int)
GDVIRTUAL1RC(Array, _surface_get_arrays, int)
- GDVIRTUAL1RC(Array, _surface_get_blend_shape_arrays, int)
+ GDVIRTUAL1RC(TypedArray<Array>, _surface_get_blend_shape_arrays, int)
GDVIRTUAL1RC(Dictionary, _surface_get_lods, int)
GDVIRTUAL1RC(uint32_t, _surface_get_format, int)
GDVIRTUAL1RC(uint32_t, _surface_get_primitive_type, int)
@@ -144,13 +144,14 @@ public:
ARRAY_FLAG_USE_DYNAMIC_UPDATE = RS::ARRAY_FLAG_USE_DYNAMIC_UPDATE,
ARRAY_FLAG_USE_8_BONE_WEIGHTS = RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS,
+ ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY = RS::ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY,
};
virtual int get_surface_count() const;
virtual int surface_get_array_len(int p_idx) const;
virtual int surface_get_array_index_len(int p_idx) const;
virtual Array surface_get_arrays(int p_surface) const;
- virtual Array surface_get_blend_shape_arrays(int p_surface) const;
+ virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const;
virtual Dictionary surface_get_lods(int p_surface) const;
virtual uint32_t surface_get_format(int p_idx) const;
virtual PrimitiveType surface_get_primitive_type(int p_idx) const;
@@ -168,9 +169,6 @@ public:
void generate_debug_mesh_lines(Vector<Vector3> &r_lines);
void generate_debug_mesh_indices(Vector<Vector3> &r_points);
- Ref<Shape3D> create_trimesh_shape() const;
- Ref<Shape3D> create_convex_shape(bool p_clean = true, bool p_simplify = false) const;
-
Ref<Mesh> create_outline(float p_margin) const;
void set_lightmap_size_hint(const Size2i &p_size);
@@ -213,6 +211,8 @@ public:
static ConvexDecompositionFunc convex_decomposition_function;
Vector<Ref<Shape3D>> convex_decompose(const ConvexDecompositionSettings &p_settings) const;
+ Ref<Shape3D> create_convex_shape(bool p_clean = true, bool p_simplify = false) const;
+ Ref<Shape3D> create_trimesh_shape() const;
virtual int get_builtin_bind_pose_count() const;
virtual Transform3D get_builtin_bind_pose(int p_index) const;
@@ -270,7 +270,7 @@ public:
void add_surface(uint32_t p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data = Vector<uint8_t>(), const Vector<AABB> &p_bone_aabbs = Vector<AABB>(), const Vector<RS::SurfaceData::LOD> &p_lods = Vector<RS::SurfaceData::LOD>());
Array surface_get_arrays(int p_surface) const override;
- Array surface_get_blend_shape_arrays(int p_surface) const override;
+ TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override;
Dictionary surface_get_lods(int p_surface) const override;
void add_blend_shape(const StringName &p_name);
@@ -345,7 +345,7 @@ public:
virtual int surface_get_array_len(int p_idx) const override { return 0; }
virtual int surface_get_array_index_len(int p_idx) const override { return 0; }
virtual Array surface_get_arrays(int p_surface) const override { return Array(); }
- virtual Array surface_get_blend_shape_arrays(int p_surface) const override { return Array(); }
+ virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override { return TypedArray<Array>(); }
virtual Dictionary surface_get_lods(int p_surface) const override { return Dictionary(); }
virtual uint32_t surface_get_format(int p_idx) const override { return 0; }
virtual PrimitiveType surface_get_primitive_type(int p_idx) const override { return PRIMITIVE_TRIANGLES; }
diff --git a/scene/resources/mesh_library.h b/scene/resources/mesh_library.h
index 4105bd6960..79acb41c4e 100644
--- a/scene/resources/mesh_library.h
+++ b/scene/resources/mesh_library.h
@@ -33,8 +33,8 @@
#include "core/io/resource.h"
#include "core/templates/rb_map.h"
-#include "mesh.h"
#include "scene/3d/navigation_region_3d.h"
+#include "scene/resources/mesh.h"
#include "shape_3d.h"
class MeshLibrary : public Resource {
diff --git a/scene/resources/navigation_mesh.cpp b/scene/resources/navigation_mesh.cpp
index ac5493efdc..6c9c8ffdba 100644
--- a/scene/resources/navigation_mesh.cpp
+++ b/scene/resources/navigation_mesh.cpp
@@ -614,8 +614,10 @@ void NavigationMesh::_bind_methods() {
ADD_GROUP("Geometry", "geometry_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "geometry_parsed_geometry_type", PROPERTY_HINT_ENUM, "Mesh Instances,Static Colliders,Both"), "set_parsed_geometry_type", "get_parsed_geometry_type");
ADD_PROPERTY(PropertyInfo(Variant::INT, "geometry_collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
+ ADD_PROPERTY_DEFAULT("geometry_collision_mask", 0xFFFFFFFF);
ADD_PROPERTY(PropertyInfo(Variant::INT, "geometry_source_geometry_mode", PROPERTY_HINT_ENUM, "NavMesh Children, Group With Children, Group Explicit"), "set_source_geometry_mode", "get_source_geometry_mode");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "geometry_source_group_name"), "set_source_group_name", "get_source_group_name");
+ ADD_PROPERTY_DEFAULT("geometry_source_group_name", StringName("navmesh"));
ADD_GROUP("Cells", "cell_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "cell_size", PROPERTY_HINT_RANGE, "0.01,500.0,0.01,or_greater,suffix:m"), "set_cell_size", "get_cell_size");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "cell_height", PROPERTY_HINT_RANGE, "0.01,500.0,0.01,or_greater,suffix:m"), "set_cell_height", "get_cell_height");
@@ -658,17 +660,17 @@ void NavigationMesh::_bind_methods() {
BIND_ENUM_CONSTANT(SOURCE_GEOMETRY_MAX);
}
-void NavigationMesh::_validate_property(PropertyInfo &property) const {
- if (property.name == "geometry/collision_mask") {
+void NavigationMesh::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "geometry_collision_mask") {
if (parsed_geometry_type == PARSED_GEOMETRY_MESH_INSTANCES) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
return;
}
}
- if (property.name == "geometry/source_group_name") {
+ if (p_property.name == "geometry_source_group_name") {
if (source_geometry_mode == SOURCE_GEOMETRY_NAVMESH_CHILDREN) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
return;
}
}
diff --git a/scene/resources/navigation_mesh.h b/scene/resources/navigation_mesh.h
index 79d8962d24..c66025dc6d 100644
--- a/scene/resources/navigation_mesh.h
+++ b/scene/resources/navigation_mesh.h
@@ -33,8 +33,6 @@
#include "scene/resources/mesh.h"
-class Mesh;
-
class NavigationMesh : public Resource {
GDCLASS(NavigationMesh, Resource);
@@ -60,7 +58,7 @@ class NavigationMesh : public Resource {
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
#ifndef DISABLE_DEPRECATED
bool _set(const StringName &p_name, const Variant &p_value);
diff --git a/scene/resources/particles_material.cpp b/scene/resources/particles_material.cpp
index 4b2e029f47..29a06622a3 100644
--- a/scene/resources/particles_material.cpp
+++ b/scene/resources/particles_material.cpp
@@ -287,7 +287,7 @@ void ParticlesMaterial::_update_shader() {
code += "uniform sampler2D anim_offset_texture : repeat_disable;\n";
}
- if (collision_enabled) {
+ if (collision_mode == COLLISION_RIGID) {
code += "uniform float collision_friction;\n";
code += "uniform float collision_bounce;\n";
}
@@ -695,8 +695,10 @@ void ParticlesMaterial::_update_shader() {
}
code += " vec3 noise_direction = get_noise_direction(TRANSFORM[3].xyz, EMISSION_TRANSFORM[3].xyz, time_noise);\n";
// If collision happened, turbulence is no longer applied.
+ // We don't need this check when the collision mode is "hide on contact",
+ // as the particle will be hidden anyway.
String extra_tab = "";
- if (collision_enabled) {
+ if (collision_mode != COLLISION_RIGID) {
code += " if (!COLLIDED) {\n";
extra_tab = " ";
}
@@ -704,7 +706,7 @@ void ParticlesMaterial::_update_shader() {
code += extra_tab + " float vel_mag = length(VELOCITY);\n";
code += extra_tab + " float vel_infl = clamp(mix(turbulence_influence_min, turbulence_influence_max, rand_from_seed(alt_seed)) * turbulence_influence, 0.0, 1.0);\n";
code += extra_tab + " VELOCITY = mix(VELOCITY, normalize(noise_direction) * vel_mag * (1.0 + (1.0 - vel_infl) * 0.2), vel_infl);\n";
- if (collision_enabled) {
+ if (collision_mode != COLLISION_RIGID) {
code += " }";
}
}
@@ -828,7 +830,7 @@ void ParticlesMaterial::_update_shader() {
code += " TRANSFORM[3].z = 0.0;\n";
}
- if (collision_enabled) {
+ if (collision_mode == COLLISION_RIGID) {
code += " if (COLLIDED) {\n";
code += " if (length(VELOCITY) > 3.0) {\n";
code += " TRANSFORM[3].xyz += COLLISION_NORMAL * COLLISION_DEPTH;\n";
@@ -851,6 +853,18 @@ void ParticlesMaterial::_update_shader() {
code += " TRANSFORM[1].xyz *= base_scale * sign(tex_scale.g) * max(abs(tex_scale.g), 0.001);\n";
code += " TRANSFORM[2].xyz *= base_scale * sign(tex_scale.b) * max(abs(tex_scale.b), 0.001);\n";
+ if (collision_mode == COLLISION_RIGID) {
+ code += " if (COLLIDED) {\n";
+ code += " TRANSFORM[3].xyz+=COLLISION_NORMAL * COLLISION_DEPTH;\n";
+ code += " VELOCITY -= COLLISION_NORMAL * dot(COLLISION_NORMAL, VELOCITY) * (1.0 + collision_bounce);\n";
+ code += " VELOCITY = mix(VELOCITY,vec3(0.0),collision_friction * DELTA * 100.0);\n";
+ code += " }\n";
+ } else if (collision_mode == COLLISION_HIDE_ON_CONTACT) {
+ code += " if (COLLIDED) {\n";
+ code += " ACTIVE = false;\n";
+ code += " }\n";
+ }
+
if (sub_emitter_mode != SUB_EMITTER_DISABLED) {
code += " int emit_count = 0;\n";
switch (sub_emitter_mode) {
@@ -1386,56 +1400,64 @@ RID ParticlesMaterial::get_shader_rid() const {
return shader_map[current_key].shader;
}
-void ParticlesMaterial::_validate_property(PropertyInfo &property) const {
- if (property.name == "emission_sphere_radius" && (emission_shape != EMISSION_SHAPE_SPHERE && emission_shape != EMISSION_SHAPE_SPHERE_SURFACE)) {
- property.usage = PROPERTY_USAGE_NONE;
+void ParticlesMaterial::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "emission_sphere_radius" && (emission_shape != EMISSION_SHAPE_SPHERE && emission_shape != EMISSION_SHAPE_SPHERE_SURFACE)) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_box_extents" && emission_shape != EMISSION_SHAPE_BOX) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_box_extents" && emission_shape != EMISSION_SHAPE_BOX) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if ((property.name == "emission_point_texture" || property.name == "emission_color_texture") && (emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS)) {
- property.usage = PROPERTY_USAGE_NONE;
+ if ((p_property.name == "emission_point_texture" || p_property.name == "emission_color_texture") && (emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS)) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_normal_texture" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_normal_texture" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "emission_point_count" && (emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS)) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "emission_point_count" && (emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS)) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("emission_ring_") && emission_shape != EMISSION_SHAPE_RING) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("emission_ring_") && emission_shape != EMISSION_SHAPE_RING) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "sub_emitter_frequency" && sub_emitter_mode != SUB_EMITTER_CONSTANT) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "sub_emitter_frequency" && sub_emitter_mode != SUB_EMITTER_CONSTANT) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name == "sub_emitter_amount_at_end" && sub_emitter_mode != SUB_EMITTER_AT_END) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name == "sub_emitter_amount_at_end" && sub_emitter_mode != SUB_EMITTER_AT_END) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
- if (property.name.begins_with("orbit_") && !particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
- property.usage = PROPERTY_USAGE_NONE;
+ if (p_property.name.begins_with("orbit_") && !particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
if (!turbulence_enabled) {
- if (property.name == "turbulence_noise_strength" ||
- property.name == "turbulence_noise_scale" ||
- property.name == "turbulence_noise_speed" ||
- property.name == "turbulence_noise_speed_random" ||
- property.name == "turbulence_influence_over_life" ||
- property.name == "turbulence_influence_min" ||
- property.name == "turbulence_influence_max" ||
- property.name == "turbulence_initial_displacement_min" ||
- property.name == "turbulence_initial_displacement_max") {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == "turbulence_noise_strength" ||
+ p_property.name == "turbulence_noise_scale" ||
+ p_property.name == "turbulence_noise_speed" ||
+ p_property.name == "turbulence_noise_speed_random" ||
+ p_property.name == "turbulence_influence_over_life" ||
+ p_property.name == "turbulence_influence_min" ||
+ p_property.name == "turbulence_influence_max" ||
+ p_property.name == "turbulence_initial_displacement_min" ||
+ p_property.name == "turbulence_initial_displacement_max") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
+
+ if (p_property.name == "collision_friction" && collision_mode != COLLISION_RIGID) {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+
+ if (p_property.name == "collision_bounce" && collision_mode != COLLISION_RIGID) {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
}
void ParticlesMaterial::set_sub_emitter_mode(SubEmitterMode p_sub_emitter_mode) {
@@ -1483,13 +1505,14 @@ bool ParticlesMaterial::is_attractor_interaction_enabled() const {
return attractor_interaction_enabled;
}
-void ParticlesMaterial::set_collision_enabled(bool p_enabled) {
- collision_enabled = p_enabled;
+void ParticlesMaterial::set_collision_mode(CollisionMode p_collision_mode) {
+ collision_mode = p_collision_mode;
_queue_shader_change();
+ notify_property_list_changed();
}
-bool ParticlesMaterial::is_collision_enabled() const {
- return collision_enabled;
+ParticlesMaterial::CollisionMode ParticlesMaterial::get_collision_mode() const {
+ return collision_mode;
}
void ParticlesMaterial::set_collision_use_scale(bool p_scale) {
@@ -1623,8 +1646,8 @@ void ParticlesMaterial::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_attractor_interaction_enabled", "enabled"), &ParticlesMaterial::set_attractor_interaction_enabled);
ClassDB::bind_method(D_METHOD("is_attractor_interaction_enabled"), &ParticlesMaterial::is_attractor_interaction_enabled);
- ClassDB::bind_method(D_METHOD("set_collision_enabled", "enabled"), &ParticlesMaterial::set_collision_enabled);
- ClassDB::bind_method(D_METHOD("is_collision_enabled"), &ParticlesMaterial::is_collision_enabled);
+ ClassDB::bind_method(D_METHOD("set_collision_mode", "mode"), &ParticlesMaterial::set_collision_mode);
+ ClassDB::bind_method(D_METHOD("get_collision_mode"), &ParticlesMaterial::get_collision_mode);
ClassDB::bind_method(D_METHOD("set_collision_use_scale", "radius"), &ParticlesMaterial::set_collision_use_scale);
ClassDB::bind_method(D_METHOD("is_collision_using_scale"), &ParticlesMaterial::is_collision_using_scale);
@@ -1734,7 +1757,7 @@ void ParticlesMaterial::_bind_methods() {
ADD_GROUP("Attractor Interaction", "attractor_interaction_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "attractor_interaction_enabled"), "set_attractor_interaction_enabled", "is_attractor_interaction_enabled");
ADD_GROUP("Collision", "collision_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_enabled"), "set_collision_enabled", "is_collision_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mode", PROPERTY_HINT_ENUM, "Disabled,Rigid,Hide On Contact"), "set_collision_mode", "get_collision_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_collision_friction", "get_collision_friction");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_collision_bounce", "get_collision_bounce");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_use_scale"), "set_collision_use_scale", "is_collision_using_scale");
@@ -1776,6 +1799,11 @@ void ParticlesMaterial::_bind_methods() {
BIND_ENUM_CONSTANT(SUB_EMITTER_AT_END);
BIND_ENUM_CONSTANT(SUB_EMITTER_AT_COLLISION);
BIND_ENUM_CONSTANT(SUB_EMITTER_MAX);
+
+ BIND_ENUM_CONSTANT(COLLISION_DISABLED);
+ BIND_ENUM_CONSTANT(COLLISION_RIGID);
+ BIND_ENUM_CONSTANT(COLLISION_HIDE_ON_CONTACT);
+ BIND_ENUM_CONSTANT(COLLISION_MAX);
}
ParticlesMaterial::ParticlesMaterial() :
@@ -1834,7 +1862,7 @@ ParticlesMaterial::ParticlesMaterial() :
set_sub_emitter_keep_velocity(false);
set_attractor_interaction_enabled(true);
- set_collision_enabled(false);
+ set_collision_mode(COLLISION_DISABLED);
set_collision_bounce(0.0);
set_collision_friction(0.0);
set_collision_use_scale(false);
diff --git a/scene/resources/particles_material.h b/scene/resources/particles_material.h
index 7fb46d6ac5..2e94e7e01a 100644
--- a/scene/resources/particles_material.h
+++ b/scene/resources/particles_material.h
@@ -93,6 +93,14 @@ public:
SUB_EMITTER_MAX
};
+ // When extending, make sure not to overflow the size of the MaterialKey below.
+ enum CollisionMode {
+ COLLISION_DISABLED,
+ COLLISION_RIGID,
+ COLLISION_HIDE_ON_CONTACT,
+ COLLISION_MAX
+ };
+
private:
union MaterialKey {
// The bit size of the struct must be kept below or equal to 32 bits.
@@ -106,7 +114,7 @@ private:
uint32_t has_emission_color : 1;
uint32_t sub_emitter : 2;
uint32_t attractor_enabled : 1;
- uint32_t collision_enabled : 1;
+ uint32_t collision_mode : 2;
uint32_t collision_scale : 1;
uint32_t turbulence_enabled : 1;
};
@@ -153,7 +161,7 @@ private:
mk.emission_shape = emission_shape;
mk.has_emission_color = emission_shape >= EMISSION_SHAPE_POINTS && emission_color_texture.is_valid();
mk.sub_emitter = sub_emitter_mode;
- mk.collision_enabled = collision_enabled;
+ mk.collision_mode = collision_mode;
mk.attractor_enabled = attractor_interaction_enabled;
mk.collision_scale = collision_scale;
mk.turbulence_enabled = turbulence_enabled;
@@ -300,14 +308,14 @@ private:
//do not save emission points here
bool attractor_interaction_enabled = false;
- bool collision_enabled = false;
+ CollisionMode collision_mode;
bool collision_scale = false;
float collision_friction = 0.0f;
float collision_bounce = 0.0f;
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_direction(Vector3 p_direction);
@@ -385,8 +393,8 @@ public:
void set_attractor_interaction_enabled(bool p_enable);
bool is_attractor_interaction_enabled() const;
- void set_collision_enabled(bool p_enabled);
- bool is_collision_enabled() const;
+ void set_collision_mode(CollisionMode p_collision_mode);
+ CollisionMode get_collision_mode() const;
void set_collision_use_scale(bool p_scale);
bool is_collision_using_scale() const;
@@ -425,5 +433,6 @@ VARIANT_ENUM_CAST(ParticlesMaterial::Parameter)
VARIANT_ENUM_CAST(ParticlesMaterial::ParticleFlags)
VARIANT_ENUM_CAST(ParticlesMaterial::EmissionShape)
VARIANT_ENUM_CAST(ParticlesMaterial::SubEmitterMode)
+VARIANT_ENUM_CAST(ParticlesMaterial::CollisionMode)
#endif // PARTICLES_MATERIAL_H
diff --git a/scene/resources/primitive_meshes.cpp b/scene/resources/primitive_meshes.cpp
index f038a79b8f..7847acb318 100644
--- a/scene/resources/primitive_meshes.cpp
+++ b/scene/resources/primitive_meshes.cpp
@@ -152,8 +152,8 @@ Dictionary PrimitiveMesh::surface_get_lods(int p_surface) const {
return Dictionary(); //not really supported
}
-Array PrimitiveMesh::surface_get_blend_shape_arrays(int p_surface) const {
- return Array(); //not really supported
+TypedArray<Array> PrimitiveMesh::surface_get_blend_shape_arrays(int p_surface) const {
+ return TypedArray<Array>(); //not really supported
}
uint32_t PrimitiveMesh::surface_get_format(int p_idx) const {
@@ -990,6 +990,13 @@ void PlaneMesh::_create_mesh_array(Array &p_arr) const {
Size2 start_pos = size * -0.5;
+ Vector3 normal = Vector3(0.0, 1.0, 0.0);
+ if (orientation == FACE_X) {
+ normal = Vector3(1.0, 0.0, 0.0);
+ } else if (orientation == FACE_Z) {
+ normal = Vector3(0.0, 0.0, 1.0);
+ }
+
Vector<Vector3> points;
Vector<Vector3> normals;
Vector<float> tangents;
@@ -1015,8 +1022,14 @@ void PlaneMesh::_create_mesh_array(Array &p_arr) const {
u /= (subdivide_w + 1.0);
v /= (subdivide_d + 1.0);
- points.push_back(Vector3(-x, 0.0, -z) + center_offset);
- normals.push_back(Vector3(0.0, 1.0, 0.0));
+ if (orientation == FACE_X) {
+ points.push_back(Vector3(0.0, z, x) + center_offset);
+ } else if (orientation == FACE_Y) {
+ points.push_back(Vector3(-x, 0.0, -z) + center_offset);
+ } else if (orientation == FACE_Z) {
+ points.push_back(Vector3(-x, z, 0.0) + center_offset);
+ }
+ normals.push_back(normal);
ADD_TANGENT(1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(1.0 - u, 1.0 - v)); /* 1.0 - uv to match orientation with Quad */
point++;
@@ -1053,13 +1066,22 @@ void PlaneMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_subdivide_width"), &PlaneMesh::get_subdivide_width);
ClassDB::bind_method(D_METHOD("set_subdivide_depth", "subdivide"), &PlaneMesh::set_subdivide_depth);
ClassDB::bind_method(D_METHOD("get_subdivide_depth"), &PlaneMesh::get_subdivide_depth);
+
ClassDB::bind_method(D_METHOD("set_center_offset", "offset"), &PlaneMesh::set_center_offset);
ClassDB::bind_method(D_METHOD("get_center_offset"), &PlaneMesh::get_center_offset);
+ ClassDB::bind_method(D_METHOD("set_orientation", "orientation"), &PlaneMesh::set_orientation);
+ ClassDB::bind_method(D_METHOD("get_orientation"), &PlaneMesh::get_orientation);
+
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size", PROPERTY_HINT_NONE, "suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "subdivide_width", PROPERTY_HINT_RANGE, "0,100,1,or_greater"), "set_subdivide_width", "get_subdivide_width");
ADD_PROPERTY(PropertyInfo(Variant::INT, "subdivide_depth", PROPERTY_HINT_RANGE, "0,100,1,or_greater"), "set_subdivide_depth", "get_subdivide_depth");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "center_offset", PROPERTY_HINT_NONE, "suffix:m"), "set_center_offset", "get_center_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "orientation", PROPERTY_HINT_ENUM, "Face X, Face Y, Face Z"), "set_orientation", "get_orientation");
+
+ BIND_ENUM_CONSTANT(FACE_X)
+ BIND_ENUM_CONSTANT(FACE_Y)
+ BIND_ENUM_CONSTANT(FACE_Z)
}
void PlaneMesh::set_size(const Size2 &p_size) {
@@ -1098,6 +1120,15 @@ Vector3 PlaneMesh::get_center_offset() const {
return center_offset;
}
+void PlaneMesh::set_orientation(const Orientation p_orientation) {
+ orientation = p_orientation;
+ _request_update();
+}
+
+PlaneMesh::Orientation PlaneMesh::get_orientation() const {
+ return orientation;
+}
+
PlaneMesh::PlaneMesh() {}
/**
@@ -1381,98 +1412,6 @@ int PrismMesh::get_subdivide_depth() const {
PrismMesh::PrismMesh() {}
/**
- QuadMesh
-*/
-
-void QuadMesh::_create_mesh_array(Array &p_arr) const {
- Vector<Vector3> faces;
- Vector<Vector3> normals;
- Vector<float> tangents;
- Vector<Vector2> uvs;
-
- faces.resize(6);
- normals.resize(6);
- tangents.resize(6 * 4);
- uvs.resize(6);
-
- Vector2 _size = Vector2(size.x / 2.0f, size.y / 2.0f);
-
- Vector3 quad_faces[4] = {
- Vector3(-_size.x, -_size.y, 0) + center_offset,
- Vector3(-_size.x, _size.y, 0) + center_offset,
- Vector3(_size.x, _size.y, 0) + center_offset,
- Vector3(_size.x, -_size.y, 0) + center_offset,
- };
-
- static const int indices[6] = {
- 0, 1, 2,
- 0, 2, 3
- };
-
- for (int i = 0; i < 6; i++) {
- int j = indices[i];
- faces.set(i, quad_faces[j]);
- normals.set(i, Vector3(0, 0, 1));
- tangents.set(i * 4 + 0, 1.0);
- tangents.set(i * 4 + 1, 0.0);
- tangents.set(i * 4 + 2, 0.0);
- tangents.set(i * 4 + 3, 1.0);
-
- static const Vector2 quad_uv[4] = {
- Vector2(0, 1),
- Vector2(0, 0),
- Vector2(1, 0),
- Vector2(1, 1),
- };
-
- uvs.set(i, quad_uv[j]);
- }
-
- p_arr[RS::ARRAY_VERTEX] = faces;
- p_arr[RS::ARRAY_NORMAL] = normals;
- p_arr[RS::ARRAY_TANGENT] = tangents;
- p_arr[RS::ARRAY_TEX_UV] = uvs;
-}
-
-void QuadMesh::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_size", "size"), &QuadMesh::set_size);
- ClassDB::bind_method(D_METHOD("get_size"), &QuadMesh::get_size);
- ClassDB::bind_method(D_METHOD("set_center_offset", "center_offset"), &QuadMesh::set_center_offset);
- ClassDB::bind_method(D_METHOD("get_center_offset"), &QuadMesh::get_center_offset);
-
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size", PROPERTY_HINT_NONE, "suffix:m"), "set_size", "get_size");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "center_offset", PROPERTY_HINT_NONE, "suffix:m"), "set_center_offset", "get_center_offset");
-}
-
-uint32_t QuadMesh::surface_get_format(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx, 1, 0);
-
- return RS::ARRAY_FORMAT_VERTEX | RS::ARRAY_FORMAT_NORMAL | RS::ARRAY_FORMAT_TANGENT | RS::ARRAY_FORMAT_TEX_UV;
-}
-
-QuadMesh::QuadMesh() {
- primitive_type = PRIMITIVE_TRIANGLES;
-}
-
-void QuadMesh::set_size(const Size2 &p_size) {
- size = p_size;
- _request_update();
-}
-
-Size2 QuadMesh::get_size() const {
- return size;
-}
-
-void QuadMesh::set_center_offset(Vector3 p_center_offset) {
- center_offset = p_center_offset;
- _request_update();
-}
-
-Vector3 QuadMesh::get_center_offset() const {
- return center_offset;
-}
-
-/**
SphereMesh
*/
diff --git a/scene/resources/primitive_meshes.h b/scene/resources/primitive_meshes.h
index 64eefd2c07..3cf161db00 100644
--- a/scene/resources/primitive_meshes.h
+++ b/scene/resources/primitive_meshes.h
@@ -75,7 +75,7 @@ public:
virtual int surface_get_array_len(int p_idx) const override;
virtual int surface_get_array_index_len(int p_idx) const override;
virtual Array surface_get_arrays(int p_surface) const override;
- virtual Array surface_get_blend_shape_arrays(int p_surface) const override;
+ virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override;
virtual Dictionary surface_get_lods(int p_surface) const override;
virtual uint32_t surface_get_format(int p_idx) const override;
virtual Mesh::PrimitiveType surface_get_primitive_type(int p_idx) const override;
@@ -217,17 +217,25 @@ public:
CylinderMesh();
};
-/**
- Similar to quadmesh but with tessellation support
+/*
+ A flat rectangle, can be used as quad or heightmap.
*/
class PlaneMesh : public PrimitiveMesh {
GDCLASS(PlaneMesh, PrimitiveMesh);
+public:
+ enum Orientation {
+ FACE_X,
+ FACE_Y,
+ FACE_Z,
+ };
+
private:
Size2 size = Size2(2.0, 2.0);
int subdivide_w = 0;
int subdivide_d = 0;
Vector3 center_offset;
+ Orientation orientation = FACE_Y;
protected:
static void _bind_methods();
@@ -246,9 +254,14 @@ public:
void set_center_offset(const Vector3 p_offset);
Vector3 get_center_offset() const;
+ void set_orientation(const Orientation p_orientation);
+ Orientation get_orientation() const;
+
PlaneMesh();
};
+VARIANT_ENUM_CAST(PlaneMesh::Orientation)
+
/**
A prism shapen, handy for ramps, triangles, etc.
*/
@@ -286,33 +299,6 @@ public:
};
/**
- Our original quadmesh...
-*/
-
-class QuadMesh : public PrimitiveMesh {
- GDCLASS(QuadMesh, PrimitiveMesh);
-
-private:
- Size2 size = Size2(1.0, 1.0);
- Vector3 center_offset;
-
-protected:
- static void _bind_methods();
- virtual void _create_mesh_array(Array &p_arr) const override;
-
-public:
- virtual uint32_t surface_get_format(int p_idx) const override;
-
- QuadMesh();
-
- void set_size(const Size2 &p_size);
- Size2 get_size() const;
-
- void set_center_offset(const Vector3 p_offset);
- Vector3 get_center_offset() const;
-};
-
-/**
A sphere..
*/
class SphereMesh : public PrimitiveMesh {
diff --git a/scene/resources/shape_2d.cpp b/scene/resources/shape_2d.cpp
index 16ef45829f..fe43f345d4 100644
--- a/scene/resources/shape_2d.cpp
+++ b/scene/resources/shape_2d.cpp
@@ -59,39 +59,39 @@ bool Shape2D::collide(const Transform2D &p_local_xform, const Ref<Shape2D> &p_sh
return PhysicsServer2D::get_singleton()->shape_collide(get_rid(), p_local_xform, Vector2(), p_shape->get_rid(), p_shape_xform, Vector2(), nullptr, 0, r);
}
-Array Shape2D::collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion) {
- ERR_FAIL_COND_V(p_shape.is_null(), Array());
+PackedVector2Array Shape2D::collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion) {
+ ERR_FAIL_COND_V(p_shape.is_null(), PackedVector2Array());
const int max_contacts = 16;
Vector2 result[max_contacts * 2];
int contacts = 0;
if (!PhysicsServer2D::get_singleton()->shape_collide(get_rid(), p_local_xform, p_local_motion, p_shape->get_rid(), p_shape_xform, p_shape_motion, result, max_contacts, contacts)) {
- return Array();
+ return PackedVector2Array();
}
- Array results;
+ PackedVector2Array results;
results.resize(contacts * 2);
for (int i = 0; i < contacts * 2; i++) {
- results[i] = result[i];
+ results.write[i] = result[i];
}
return results;
}
-Array Shape2D::collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform) {
- ERR_FAIL_COND_V(p_shape.is_null(), Array());
+PackedVector2Array Shape2D::collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform) {
+ ERR_FAIL_COND_V(p_shape.is_null(), PackedVector2Array());
const int max_contacts = 16;
Vector2 result[max_contacts * 2];
int contacts = 0;
if (!PhysicsServer2D::get_singleton()->shape_collide(get_rid(), p_local_xform, Vector2(), p_shape->get_rid(), p_shape_xform, Vector2(), result, max_contacts, contacts)) {
- return Array();
+ return PackedVector2Array();
}
- Array results;
+ PackedVector2Array results;
results.resize(contacts * 2);
for (int i = 0; i < contacts * 2; i++) {
- results[i] = result[i];
+ results.write[i] = result[i];
}
return results;
diff --git a/scene/resources/shape_2d.h b/scene/resources/shape_2d.h
index e9dc10eeae..a15aecee93 100644
--- a/scene/resources/shape_2d.h
+++ b/scene/resources/shape_2d.h
@@ -53,8 +53,8 @@ public:
bool collide_with_motion(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion);
bool collide(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform);
- Array collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion);
- Array collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform);
+ PackedVector2Array collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion);
+ PackedVector2Array collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform);
virtual void draw(const RID &p_to_rid, const Color &p_color) {}
virtual Rect2 get_rect() const { return Rect2(); }
diff --git a/scene/resources/skeleton_modification_3d_ccdik.h b/scene/resources/skeleton_modification_3d_ccdik.h
index 7098794038..1fe53e94b6 100644
--- a/scene/resources/skeleton_modification_3d_ccdik.h
+++ b/scene/resources/skeleton_modification_3d_ccdik.h
@@ -28,13 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
+#ifndef SKELETON_MODIFICATION_3D_CCDIK_H
+#define SKELETON_MODIFICATION_3D_CCDIK_H
+
#include "core/templates/local_vector.h"
#include "scene/3d/skeleton_3d.h"
#include "scene/resources/skeleton_modification_3d.h"
-#ifndef SKELETON_MODIFICATION_3D_CCDIK_H
-#define SKELETON_MODIFICATION_3D_CCDIK_H
-
class SkeletonModification3DCCDIK : public SkeletonModification3D {
GDCLASS(SkeletonModification3DCCDIK, SkeletonModification3D);
diff --git a/scene/resources/skeleton_modification_3d_fabrik.h b/scene/resources/skeleton_modification_3d_fabrik.h
index 3d66bb6d99..e2e490d636 100644
--- a/scene/resources/skeleton_modification_3d_fabrik.h
+++ b/scene/resources/skeleton_modification_3d_fabrik.h
@@ -28,13 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
+#ifndef SKELETON_MODIFICATION_3D_FABRIK_H
+#define SKELETON_MODIFICATION_3D_FABRIK_H
+
#include "core/templates/local_vector.h"
#include "scene/3d/skeleton_3d.h"
#include "scene/resources/skeleton_modification_3d.h"
-#ifndef SKELETON_MODIFICATION_3D_FABRIK_H
-#define SKELETON_MODIFICATION_3D_FABRIK_H
-
class SkeletonModification3DFABRIK : public SkeletonModification3D {
GDCLASS(SkeletonModification3DFABRIK, SkeletonModification3D);
diff --git a/scene/resources/skeleton_modification_3d_jiggle.h b/scene/resources/skeleton_modification_3d_jiggle.h
index f41ffcd58d..bd1ee51d93 100644
--- a/scene/resources/skeleton_modification_3d_jiggle.h
+++ b/scene/resources/skeleton_modification_3d_jiggle.h
@@ -28,13 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
+#ifndef SKELETON_MODIFICATION_3D_JIGGLE_H
+#define SKELETON_MODIFICATION_3D_JIGGLE_H
+
#include "core/templates/local_vector.h"
#include "scene/3d/skeleton_3d.h"
#include "scene/resources/skeleton_modification_3d.h"
-#ifndef SKELETON_MODIFICATION_3D_JIGGLE_H
-#define SKELETON_MODIFICATION_3D_JIGGLE_H
-
class SkeletonModification3DJiggle : public SkeletonModification3D {
GDCLASS(SkeletonModification3DJiggle, SkeletonModification3D);
diff --git a/scene/resources/skeleton_modification_3d_lookat.h b/scene/resources/skeleton_modification_3d_lookat.h
index 4e5714b5dc..cea63fc34f 100644
--- a/scene/resources/skeleton_modification_3d_lookat.h
+++ b/scene/resources/skeleton_modification_3d_lookat.h
@@ -28,12 +28,12 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
#ifndef SKELETON_MODIFICATION_3D_LOOKAT_H
#define SKELETON_MODIFICATION_3D_LOOKAT_H
+#include "scene/3d/skeleton_3d.h"
+#include "scene/resources/skeleton_modification_3d.h"
+
class SkeletonModification3DLookAt : public SkeletonModification3D {
GDCLASS(SkeletonModification3DLookAt, SkeletonModification3D);
diff --git a/scene/resources/skeleton_modification_3d_stackholder.h b/scene/resources/skeleton_modification_3d_stackholder.h
index ae22099158..2071de5457 100644
--- a/scene/resources/skeleton_modification_3d_stackholder.h
+++ b/scene/resources/skeleton_modification_3d_stackholder.h
@@ -28,12 +28,12 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
#ifndef SKELETON_MODIFICATION_3D_STACKHOLDER_H
#define SKELETON_MODIFICATION_3D_STACKHOLDER_H
+#include "scene/3d/skeleton_3d.h"
+#include "scene/resources/skeleton_modification_3d.h"
+
class SkeletonModification3DStackHolder : public SkeletonModification3D {
GDCLASS(SkeletonModification3DStackHolder, SkeletonModification3D);
diff --git a/scene/resources/skeleton_modification_3d_twoboneik.h b/scene/resources/skeleton_modification_3d_twoboneik.h
index 57e8237511..7bd7c8291d 100644
--- a/scene/resources/skeleton_modification_3d_twoboneik.h
+++ b/scene/resources/skeleton_modification_3d_twoboneik.h
@@ -28,12 +28,12 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
#ifndef SKELETON_MODIFICATION_3D_TWOBONEIK_H
#define SKELETON_MODIFICATION_3D_TWOBONEIK_H
+#include "scene/3d/skeleton_3d.h"
+#include "scene/resources/skeleton_modification_3d.h"
+
class SkeletonModification3DTwoBoneIK : public SkeletonModification3D {
GDCLASS(SkeletonModification3DTwoBoneIK, SkeletonModification3D);
diff --git a/scene/resources/skeleton_profile.cpp b/scene/resources/skeleton_profile.cpp
index bfb4bb6e2b..1367ea86dd 100644
--- a/scene/resources/skeleton_profile.cpp
+++ b/scene/resources/skeleton_profile.cpp
@@ -121,26 +121,26 @@ bool SkeletonProfile::_get(const StringName &p_path, Variant &r_ret) const {
return true;
}
-void SkeletonProfile::_validate_property(PropertyInfo &property) const {
+void SkeletonProfile::_validate_property(PropertyInfo &p_property) const {
if (is_read_only) {
- if (property.name == ("group_size") || property.name == ("bone_size") || property.name == ("root_bone") || property.name == ("scale_base_bone")) {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+ if (p_property.name == ("group_size") || p_property.name == ("bone_size") || p_property.name == ("root_bone") || p_property.name == ("scale_base_bone")) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
return;
}
}
- if (property.name == ("root_bone") || property.name == ("scale_base_bone")) {
+ if (p_property.name == ("root_bone") || p_property.name == ("scale_base_bone")) {
String hint = "";
for (int i = 0; i < bones.size(); i++) {
hint += i == 0 ? String(bones[i].bone_name) : "," + String(bones[i].bone_name);
}
- property.hint_string = hint;
+ p_property.hint_string = hint;
}
- PackedStringArray split = property.name.split("/");
+ PackedStringArray split = p_property.name.split("/");
if (split.size() == 3 && split[0] == "bones") {
if (split[2] == "bone_tail" && get_tail_direction(split[1].to_int()) != TAIL_DIRECTION_SPECIFIC_CHILD) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
}
@@ -506,7 +506,7 @@ SkeletonProfileHumanoid::SkeletonProfileHumanoid() {
bones.write[5].reference_pose = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.1, 0);
bones.write[5].handle_offset = Vector2(0.5, 0.23);
bones.write[5].group = "Body";
- bones.write[5].require = true;
+ bones.write[5].require = false;
bones.write[6].bone_name = "Head";
bones.write[6].bone_parent = "Neck";
diff --git a/scene/resources/skeleton_profile.h b/scene/resources/skeleton_profile.h
index 84dfca458e..66344d954d 100644
--- a/scene/resources/skeleton_profile.h
+++ b/scene/resources/skeleton_profile.h
@@ -72,7 +72,7 @@ protected:
bool _get(const StringName &p_path, Variant &r_ret) const;
bool _set(const StringName &p_path, const Variant &p_value);
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp
index a53c299d00..ff5210f1b3 100644
--- a/scene/resources/style_box.cpp
+++ b/scene/resources/style_box.cpp
@@ -842,9 +842,9 @@ float StyleBoxFlat::get_style_margin(Side p_side) const {
return border_width[p_side];
}
-void StyleBoxFlat::_validate_property(PropertyInfo &property) const {
- if (!anti_aliased && property.name == "anti_aliasing_size") {
- property.usage = PROPERTY_USAGE_NO_EDITOR;
+void StyleBoxFlat::_validate_property(PropertyInfo &p_property) const {
+ if (!anti_aliased && p_property.name == "anti_aliasing_size") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
diff --git a/scene/resources/style_box.h b/scene/resources/style_box.h
index 9f4f69d3ba..88db4f5fbd 100644
--- a/scene/resources/style_box.h
+++ b/scene/resources/style_box.h
@@ -166,7 +166,7 @@ class StyleBoxFlat : public StyleBox {
protected:
virtual float get_style_margin(Side p_side) const override;
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_bg_color(const Color &p_color);
diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp
index 05ed9238b8..25f5006c4f 100644
--- a/scene/resources/texture.cpp
+++ b/scene/resources/texture.cpp
@@ -35,8 +35,8 @@
#include "core/io/marshalls.h"
#include "core/math/geometry_2d.h"
#include "core/os/os.h"
-#include "mesh.h"
#include "scene/resources/bit_map.h"
+#include "scene/resources/mesh.h"
#include "servers/camera/camera_feed.h"
int Texture2D::get_width() const {
int ret;
@@ -1038,7 +1038,7 @@ void CompressedTexture2D::reload_from_file() {
load(path);
}
-void CompressedTexture2D::_validate_property(PropertyInfo &property) const {
+void CompressedTexture2D::_validate_property(PropertyInfo &p_property) const {
}
void CompressedTexture2D::_bind_methods() {
@@ -1394,7 +1394,7 @@ void CompressedTexture3D::reload_from_file() {
load(path);
}
-void CompressedTexture3D::_validate_property(PropertyInfo &property) const {
+void CompressedTexture3D::_validate_property(PropertyInfo &p_property) const {
}
void CompressedTexture3D::_bind_methods() {
@@ -2537,13 +2537,6 @@ void GradientTexture2D::_bind_methods() {
//////////////////////////////////////
-void ProxyTexture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_base", "base"), &ProxyTexture::set_base);
- ClassDB::bind_method(D_METHOD("get_base"), &ProxyTexture::get_base);
-
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "base", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_base", "get_base");
-}
-
void ProxyTexture::set_base(const Ref<Texture2D> &p_texture) {
ERR_FAIL_COND(p_texture == this);
@@ -2796,12 +2789,12 @@ bool AnimatedTexture::is_pixel_opaque(int p_x, int p_y) const {
return true;
}
-void AnimatedTexture::_validate_property(PropertyInfo &property) const {
- String prop = property.name;
+void AnimatedTexture::_validate_property(PropertyInfo &p_property) const {
+ String prop = p_property.name;
if (prop.begins_with("frame_")) {
int frame = prop.get_slicec('/', 0).get_slicec('_', 1).to_int();
if (frame >= frame_count) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
}
@@ -3221,7 +3214,7 @@ void CompressedTextureLayered::reload_from_file() {
load(path);
}
-void CompressedTextureLayered::_validate_property(PropertyInfo &property) const {
+void CompressedTextureLayered::_validate_property(PropertyInfo &p_property) const {
}
void CompressedTextureLayered::_bind_methods() {
diff --git a/scene/resources/texture.h b/scene/resources/texture.h
index 36b193c5d4..133b312d27 100644
--- a/scene/resources/texture.h
+++ b/scene/resources/texture.h
@@ -251,7 +251,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
static Ref<Image> load_image_from_file(Ref<FileAccess> p_file, int p_size_limit);
@@ -506,7 +506,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
Image::Format get_format() const override;
@@ -651,7 +651,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
Image::Format get_format() const override;
@@ -883,8 +883,6 @@ VARIANT_ENUM_CAST(GradientTexture2D::Fill);
VARIANT_ENUM_CAST(GradientTexture2D::Repeat);
class ProxyTexture : public Texture2D {
- GDCLASS(ProxyTexture, Texture2D);
-
private:
mutable RID proxy_ph;
mutable RID proxy;
@@ -942,7 +940,7 @@ private:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
void set_frames(int p_frames);
diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp
index b0b9f1228f..552d856034 100644
--- a/scene/resources/tile_set.cpp
+++ b/scene/resources/tile_set.cpp
@@ -3302,11 +3302,11 @@ void TileSet::_get_property_list(List<PropertyInfo> *p_list) const {
}
}
-void TileSet::_validate_property(PropertyInfo &property) const {
- if (property.name == "tile_layout" && tile_shape == TILE_SHAPE_SQUARE) {
- property.usage ^= PROPERTY_USAGE_READ_ONLY;
- } else if (property.name == "tile_offset_axis" && tile_shape == TILE_SHAPE_SQUARE) {
- property.usage ^= PROPERTY_USAGE_READ_ONLY;
+void TileSet::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "tile_layout" && tile_shape == TILE_SHAPE_SQUARE) {
+ p_property.usage ^= PROPERTY_USAGE_READ_ONLY;
+ } else if (p_property.name == "tile_offset_axis" && tile_shape == TILE_SHAPE_SQUARE) {
+ p_property.usage ^= PROPERTY_USAGE_READ_ONLY;
}
}
diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h
index 6ea3889fce..4c0823cdf2 100644
--- a/scene/resources/tile_set.h
+++ b/scene/resources/tile_set.h
@@ -295,7 +295,7 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
- virtual void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
private:
// --- TileSet data ---
diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp
index a67716d52b..90f1a1bff1 100644
--- a/scene/resources/visual_shader.cpp
+++ b/scene/resources/visual_shader.cpp
@@ -1036,11 +1036,11 @@ void VisualShader::disconnect_nodes(Type p_type, int p_from_node, int p_from_por
}
}
-Array VisualShader::_get_node_connections(Type p_type) const {
+TypedArray<Dictionary> VisualShader::_get_node_connections(Type p_type) const {
ERR_FAIL_INDEX_V(p_type, TYPE_MAX, Array());
const Graph *g = &graph[p_type];
- Array ret;
+ TypedArray<Dictionary> ret;
for (const Connection &E : g->connections) {
Dictionary d;
d["from_node"] = E.from_node;
@@ -1698,13 +1698,13 @@ Error VisualShader::_write_node(Type type, StringBuilder *global_code, StringBui
inputs[i] = "(" + src_var + " ? 1.0 : 0.0)";
} break;
case VisualShaderNode::PORT_TYPE_VECTOR_2D: {
- inputs[i] = "dot(" + src_var + ", vec2(0.5, 0.5))";
+ inputs[i] = src_var + ".x";
} break;
case VisualShaderNode::PORT_TYPE_VECTOR_3D: {
- inputs[i] = "dot(" + src_var + ", vec3(0.333333, 0.333333, 0.333333))";
+ inputs[i] = src_var + ".x";
} break;
case VisualShaderNode::PORT_TYPE_VECTOR_4D: {
- inputs[i] = "dot(" + src_var + ", vec4(0.25, 0.25, 0.25, 0.25))";
+ inputs[i] = src_var + ".x";
} break;
default:
break;
@@ -2214,6 +2214,12 @@ void VisualShader::_update_shader() const {
case VaryingType::VARYING_TYPE_FLOAT:
global_code += "float ";
break;
+ case VaryingType::VARYING_TYPE_INT:
+ if (E.value.mode == VaryingMode::VARYING_MODE_VERTEX_TO_FRAG_LIGHT) {
+ global_code += "flat ";
+ }
+ global_code += "int ";
+ break;
case VaryingType::VARYING_TYPE_VECTOR_2D:
global_code += "vec2 ";
break;
@@ -2223,8 +2229,11 @@ void VisualShader::_update_shader() const {
case VaryingType::VARYING_TYPE_VECTOR_4D:
global_code += "vec4 ";
break;
- case VaryingType::VARYING_TYPE_COLOR:
- global_code += "vec4 ";
+ case VaryingType::VARYING_TYPE_BOOLEAN:
+ if (E.value.mode == VaryingMode::VARYING_MODE_VERTEX_TO_FRAG_LIGHT) {
+ global_code += "flat ";
+ }
+ global_code += "bool ";
break;
case VaryingType::VARYING_TYPE_TRANSFORM:
global_code += "mat4 ";
@@ -2277,6 +2286,9 @@ void VisualShader::_update_shader() const {
case VaryingType::VARYING_TYPE_FLOAT:
code2 += "0.0";
break;
+ case VaryingType::VARYING_TYPE_INT:
+ code2 += "0";
+ break;
case VaryingType::VARYING_TYPE_VECTOR_2D:
code2 += "vec2(0.0)";
break;
@@ -2286,8 +2298,8 @@ void VisualShader::_update_shader() const {
case VaryingType::VARYING_TYPE_VECTOR_4D:
code2 += "vec4(0.0)";
break;
- case VaryingType::VARYING_TYPE_COLOR:
- code2 += "vec4(0.0)";
+ case VaryingType::VARYING_TYPE_BOOLEAN:
+ code2 += "false";
break;
case VaryingType::VARYING_TYPE_TRANSFORM:
code2 += "mat4(1.0)";
@@ -2585,10 +2597,11 @@ void VisualShader::_bind_methods() {
BIND_ENUM_CONSTANT(VARYING_MODE_MAX);
BIND_ENUM_CONSTANT(VARYING_TYPE_FLOAT);
+ BIND_ENUM_CONSTANT(VARYING_TYPE_INT);
BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_2D);
BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_3D);
BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_4D);
- BIND_ENUM_CONSTANT(VARYING_TYPE_COLOR);
+ BIND_ENUM_CONSTANT(VARYING_TYPE_BOOLEAN);
BIND_ENUM_CONSTANT(VARYING_TYPE_TRANSFORM);
BIND_ENUM_CONSTANT(VARYING_TYPE_MAX);
@@ -3153,8 +3166,8 @@ String VisualShaderNodeInput::get_input_index_name(int p_index) const {
return "";
}
-void VisualShaderNodeInput::_validate_property(PropertyInfo &property) const {
- if (property.name == "input_name") {
+void VisualShaderNodeInput::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "input_name") {
String port_list;
int idx = 0;
@@ -3172,7 +3185,7 @@ void VisualShaderNodeInput::_validate_property(PropertyInfo &property) const {
if (port_list.is_empty()) {
port_list = RTR("None");
}
- property.hint_string = port_list;
+ p_property.hint_string = port_list;
}
}
@@ -4632,21 +4645,23 @@ void VisualShaderNodeVarying::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_varying_type"), &VisualShaderNodeVarying::get_varying_type);
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "varying_name"), "set_varying_name", "get_varying_name");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "varying_type", PROPERTY_HINT_ENUM, "Float,Vector,Transform"), "set_varying_type", "get_varying_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "varying_type", PROPERTY_HINT_ENUM, "Float,Int,Vector2,Vector3,Vector4,Boolean,Transform"), "set_varying_type", "get_varying_type");
}
String VisualShaderNodeVarying::get_type_str() const {
switch (varying_type) {
case VisualShader::VARYING_TYPE_FLOAT:
return "float";
+ case VisualShader::VARYING_TYPE_INT:
+ return "int";
case VisualShader::VARYING_TYPE_VECTOR_2D:
return "vec2";
case VisualShader::VARYING_TYPE_VECTOR_3D:
return "vec3";
case VisualShader::VARYING_TYPE_VECTOR_4D:
return "vec4";
- case VisualShader::VARYING_TYPE_COLOR:
- return "vec4";
+ case VisualShader::VARYING_TYPE_BOOLEAN:
+ return "bool";
case VisualShader::VARYING_TYPE_TRANSFORM:
return "mat4";
default:
@@ -4657,17 +4672,16 @@ String VisualShaderNodeVarying::get_type_str() const {
VisualShaderNodeVarying::PortType VisualShaderNodeVarying::get_port_type(VisualShader::VaryingType p_type, int p_port) const {
switch (p_type) {
+ case VisualShader::VARYING_TYPE_INT:
+ return PORT_TYPE_SCALAR_INT;
case VisualShader::VARYING_TYPE_VECTOR_2D:
return PORT_TYPE_VECTOR_2D;
case VisualShader::VARYING_TYPE_VECTOR_3D:
return PORT_TYPE_VECTOR_3D;
case VisualShader::VARYING_TYPE_VECTOR_4D:
return PORT_TYPE_VECTOR_4D;
- case VisualShader::VARYING_TYPE_COLOR:
- if (p_port == 1) {
- break; // scalar
- }
- return PORT_TYPE_VECTOR_3D;
+ case VisualShader::VARYING_TYPE_BOOLEAN:
+ return PORT_TYPE_BOOLEAN;
case VisualShader::VARYING_TYPE_TRANSFORM:
return PORT_TYPE_TRANSFORM;
default:
@@ -4711,9 +4725,6 @@ String VisualShaderNodeVaryingSetter::get_caption() const {
}
int VisualShaderNodeVaryingSetter::get_input_port_count() const {
- if (varying_type == VisualShader::VARYING_TYPE_COLOR) {
- return 2;
- }
return 1;
}
@@ -4722,13 +4733,6 @@ VisualShaderNodeVaryingSetter::PortType VisualShaderNodeVaryingSetter::get_input
}
String VisualShaderNodeVaryingSetter::get_input_port_name(int p_port) const {
- if (varying_type == VisualShader::VARYING_TYPE_COLOR) {
- if (p_port == 0) {
- return "color";
- } else {
- return "alpha";
- }
- }
return "";
}
@@ -4744,20 +4748,12 @@ String VisualShaderNodeVaryingSetter::get_output_port_name(int p_port) const {
return "";
}
-String VisualShaderNodeVaryingSetter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
- return vformat("varying %s %s;\n", get_type_str(), varying_name);
-}
-
String VisualShaderNodeVaryingSetter::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
if (varying_name == "[None]") {
return code;
}
- if (varying_type == VisualShader::VARYING_TYPE_COLOR) {
- code += vformat(" %s = vec4(%s, %s);\n", varying_name, p_input_vars[0], p_input_vars[1]);
- } else {
- code += vformat(" %s = %s;\n", varying_name, p_input_vars[0]);
- }
+ code += vformat(" %s = %s;\n", varying_name, p_input_vars[0]);
return code;
}
@@ -4783,9 +4779,6 @@ String VisualShaderNodeVaryingGetter::get_input_port_name(int p_port) const {
}
int VisualShaderNodeVaryingGetter::get_output_port_count() const {
- if (varying_type == VisualShader::VARYING_TYPE_COLOR) {
- return 2;
- }
return 1;
}
@@ -4794,13 +4787,6 @@ VisualShaderNodeVaryingGetter::PortType VisualShaderNodeVaryingGetter::get_outpu
}
String VisualShaderNodeVaryingGetter::get_output_port_name(int p_port) const {
- if (varying_type == VisualShader::VARYING_TYPE_COLOR) {
- if (p_port == 0) {
- return "color";
- } else {
- return "alpha";
- }
- }
return "";
}
@@ -4817,6 +4803,9 @@ String VisualShaderNodeVaryingGetter::generate_code(Shader::Mode p_mode, VisualS
case VisualShader::VARYING_TYPE_FLOAT:
from = "0.0";
break;
+ case VisualShader::VARYING_TYPE_INT:
+ from = "0";
+ break;
case VisualShader::VARYING_TYPE_VECTOR_2D:
from = "vec2(0.0)";
break;
@@ -4826,9 +4815,8 @@ String VisualShaderNodeVaryingGetter::generate_code(Shader::Mode p_mode, VisualS
case VisualShader::VARYING_TYPE_VECTOR_4D:
from = "vec4(0.0)";
break;
- case VisualShader::VARYING_TYPE_COLOR:
- from = "vec3(0.0)";
- from2 = "0.0";
+ case VisualShader::VARYING_TYPE_BOOLEAN:
+ from = "false";
break;
case VisualShader::VARYING_TYPE_TRANSFORM:
from = "mat4(1.0)";
@@ -4836,16 +4824,6 @@ String VisualShaderNodeVaryingGetter::generate_code(Shader::Mode p_mode, VisualS
default:
break;
}
- } else if (varying_type == VisualShader::VARYING_TYPE_COLOR) {
- from = varying_name + ".rgb";
- from2 = varying_name + ".a";
- }
-
- if (varying_type == VisualShader::VARYING_TYPE_COLOR) {
- String code;
- code += vformat(" %s = %s;\n", p_output_vars[0], from);
- code += vformat(" %s = %s;\n", p_output_vars[1], from2);
- return code;
}
return vformat(" %s = %s;\n", p_output_vars[0], from);
}
diff --git a/scene/resources/visual_shader.h b/scene/resources/visual_shader.h
index 7ca4e5fc4a..09a3917a16 100644
--- a/scene/resources/visual_shader.h
+++ b/scene/resources/visual_shader.h
@@ -79,10 +79,11 @@ public:
enum VaryingType {
VARYING_TYPE_FLOAT,
+ VARYING_TYPE_INT,
VARYING_TYPE_VECTOR_2D,
VARYING_TYPE_VECTOR_3D,
VARYING_TYPE_VECTOR_4D,
- VARYING_TYPE_COLOR,
+ VARYING_TYPE_BOOLEAN,
VARYING_TYPE_TRANSFORM,
VARYING_TYPE_MAX,
};
@@ -132,7 +133,7 @@ private:
Shader::Mode shader_mode = Shader::MODE_SPATIAL;
mutable String previous_code;
- Array _get_node_connections(Type p_type) const;
+ TypedArray<Dictionary> _get_node_connections(Type p_type) const;
Vector2 graph_offset;
@@ -428,7 +429,7 @@ public:
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
public:
virtual int get_input_port_count() const override;
@@ -828,7 +829,6 @@ public:
virtual PortType get_output_port_type(int p_port) const override;
virtual String get_output_port_name(int p_port) const override;
- virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override;
VisualShaderNodeVaryingSetter();
diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp
index b422d298b2..2911d726b4 100644
--- a/scene/resources/visual_shader_nodes.cpp
+++ b/scene/resources/visual_shader_nodes.cpp
@@ -1015,7 +1015,7 @@ Vector<StringName> VisualShaderNodeCurveTexture::get_editable_properties() const
}
String VisualShaderNodeCurveTexture::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
- return "uniform sampler2D " + make_unique_id(p_type, p_id, "curve") + ";\n";
+ return "uniform sampler2D " + make_unique_id(p_type, p_id, "curve") + " : repeat_disable;\n";
}
String VisualShaderNodeCurveTexture::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
@@ -6830,23 +6830,23 @@ void VisualShaderNodeMultiplyAdd::set_op_type(OpType p_op_type) {
switch (p_op_type) {
case OP_TYPE_SCALAR: {
set_input_port_default_value(0, 0.0, get_input_port_default_value(0));
- set_input_port_default_value(1, 0.0, get_input_port_default_value(1));
+ set_input_port_default_value(1, 1.0, get_input_port_default_value(1));
set_input_port_default_value(2, 0.0, get_input_port_default_value(2));
} break;
case OP_TYPE_VECTOR_2D: {
set_input_port_default_value(0, Vector2(), get_input_port_default_value(0));
- set_input_port_default_value(1, Vector2(), get_input_port_default_value(1));
+ set_input_port_default_value(1, Vector2(1.0, 1.0), get_input_port_default_value(1));
set_input_port_default_value(2, Vector2(), get_input_port_default_value(2));
} break;
case OP_TYPE_VECTOR_3D: {
set_input_port_default_value(0, Vector3(), get_input_port_default_value(0));
- set_input_port_default_value(1, Vector3(), get_input_port_default_value(1));
+ set_input_port_default_value(1, Vector3(1.0, 1.0, 1.0), get_input_port_default_value(1));
set_input_port_default_value(2, Vector3(), get_input_port_default_value(2));
} break;
case OP_TYPE_VECTOR_4D: {
- set_input_port_default_value(0, Quaternion(), get_input_port_default_value(0));
- set_input_port_default_value(1, Quaternion(), get_input_port_default_value(1));
- set_input_port_default_value(2, Quaternion(), get_input_port_default_value(2));
+ set_input_port_default_value(0, Vector4(), get_input_port_default_value(0));
+ set_input_port_default_value(1, Vector4(1.0, 1.0, 1.0, 1.0), get_input_port_default_value(1));
+ set_input_port_default_value(2, Vector4(), get_input_port_default_value(2));
} break;
default:
break;
@@ -6880,7 +6880,7 @@ void VisualShaderNodeMultiplyAdd::_bind_methods() {
VisualShaderNodeMultiplyAdd::VisualShaderNodeMultiplyAdd() {
set_input_port_default_value(0, 0.0);
- set_input_port_default_value(1, 0.0);
+ set_input_port_default_value(1, 1.0);
set_input_port_default_value(2, 0.0);
}
diff --git a/servers/audio/audio_driver_dummy.cpp b/servers/audio/audio_driver_dummy.cpp
index 60eb657923..729f278d4b 100644
--- a/servers/audio/audio_driver_dummy.cpp
+++ b/servers/audio/audio_driver_dummy.cpp
@@ -36,9 +36,8 @@
AudioDriverDummy *AudioDriverDummy::singleton = nullptr;
Error AudioDriverDummy::init() {
- active = false;
- thread_exited = false;
- exit_thread = false;
+ active.clear();
+ exit_thread.clear();
samples_in = nullptr;
if (mix_rate == -1) {
@@ -60,23 +59,23 @@ void AudioDriverDummy::thread_func(void *p_udata) {
uint64_t usdelay = (ad->buffer_frames / float(ad->mix_rate)) * 1000000;
- while (!ad->exit_thread) {
- if (ad->active) {
+ while (!ad->exit_thread.is_set()) {
+ if (ad->active.is_set()) {
ad->lock();
+ ad->start_counting_ticks();
ad->audio_server_process(ad->buffer_frames, ad->samples_in);
+ ad->stop_counting_ticks();
ad->unlock();
};
OS::get_singleton()->delay_usec(usdelay);
};
-
- ad->thread_exited = true;
};
void AudioDriverDummy::start() {
- active = true;
+ active.set();
};
int AudioDriverDummy::get_mix_rate() const {
@@ -113,7 +112,7 @@ uint32_t AudioDriverDummy::get_channels() const {
}
void AudioDriverDummy::mix_audio(int p_frames, int32_t *p_buffer) {
- ERR_FAIL_COND(!active); // If not active, should not mix.
+ ERR_FAIL_COND(!active.is_set()); // If not active, should not mix.
ERR_FAIL_COND(use_threads == true); // If using threads, this will not work well.
uint32_t todo = p_frames;
@@ -136,7 +135,7 @@ void AudioDriverDummy::mix_audio(int p_frames, int32_t *p_buffer) {
void AudioDriverDummy::finish() {
if (use_threads) {
- exit_thread = true;
+ exit_thread.set();
thread.wait_to_finish();
}
diff --git a/servers/audio/audio_driver_dummy.h b/servers/audio/audio_driver_dummy.h
index 8f47e64d8b..46dd2e1439 100644
--- a/servers/audio/audio_driver_dummy.h
+++ b/servers/audio/audio_driver_dummy.h
@@ -35,6 +35,7 @@
#include "core/os/mutex.h"
#include "core/os/thread.h"
+#include "core/templates/safe_refcount.h"
class AudioDriverDummy : public AudioDriver {
Thread thread;
@@ -50,9 +51,8 @@ class AudioDriverDummy : public AudioDriver {
int channels;
- bool active;
- bool thread_exited;
- mutable bool exit_thread;
+ SafeFlag active;
+ SafeFlag exit_thread;
bool use_threads = true;
diff --git a/servers/audio/effects/audio_effect_chorus.cpp b/servers/audio/effects/audio_effect_chorus.cpp
index e5434eac02..54c08ef644 100644
--- a/servers/audio/effects/audio_effect_chorus.cpp
+++ b/servers/audio/effects/audio_effect_chorus.cpp
@@ -272,11 +272,11 @@ float AudioEffectChorus::get_dry() const {
return dry;
}
-void AudioEffectChorus::_validate_property(PropertyInfo &property) const {
- if (property.name.begins_with("voice/")) {
- int voice_idx = property.name.get_slice("/", 1).to_int();
+void AudioEffectChorus::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name.begins_with("voice/")) {
+ int voice_idx = p_property.name.get_slice("/", 1).to_int();
if (voice_idx > voice_count) {
- property.usage = PROPERTY_USAGE_NONE;
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
}
diff --git a/servers/audio/effects/audio_effect_chorus.h b/servers/audio/effects/audio_effect_chorus.h
index 72b495f7f9..dd4b431e7a 100644
--- a/servers/audio/effects/audio_effect_chorus.h
+++ b/servers/audio/effects/audio_effect_chorus.h
@@ -96,7 +96,7 @@ private:
float dry;
protected:
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
diff --git a/servers/audio/effects/audio_effect_compressor.cpp b/servers/audio/effects/audio_effect_compressor.cpp
index ee71a6dba7..0e1accba16 100644
--- a/servers/audio/effects/audio_effect_compressor.cpp
+++ b/servers/audio/effects/audio_effect_compressor.cpp
@@ -184,15 +184,15 @@ StringName AudioEffectCompressor::get_sidechain() const {
return sidechain;
}
-void AudioEffectCompressor::_validate_property(PropertyInfo &property) const {
- if (property.name == "sidechain") {
+void AudioEffectCompressor::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "sidechain") {
String buses = "";
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
buses += ",";
buses += AudioServer::get_singleton()->get_bus_name(i);
}
- property.hint_string = buses;
+ p_property.hint_string = buses;
}
}
diff --git a/servers/audio/effects/audio_effect_compressor.h b/servers/audio/effects/audio_effect_compressor.h
index 998bd3c978..886255b958 100644
--- a/servers/audio/effects/audio_effect_compressor.h
+++ b/servers/audio/effects/audio_effect_compressor.h
@@ -61,7 +61,7 @@ class AudioEffectCompressor : public AudioEffect {
StringName sidechain;
protected:
- void _validate_property(PropertyInfo &property) const override;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
public:
diff --git a/servers/audio/effects/audio_effect_delay.cpp b/servers/audio/effects/audio_effect_delay.cpp
index 80e7a8223c..ae8c58f654 100644
--- a/servers/audio/effects/audio_effect_delay.cpp
+++ b/servers/audio/effects/audio_effect_delay.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "audio_effect_delay.h"
+
#include "core/math/math_funcs.h"
#include "servers/audio_server.h"
@@ -286,37 +287,21 @@ void AudioEffectDelay::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dry", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dry", "get_dry");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap1/active"), "set_tap1_active", "is_tap1_active");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap1/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1,suffix:ms"), "set_tap1_delay_ms", "get_tap1_delay_ms");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap1/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01,suffix:dB"), "set_tap1_level_db", "get_tap1_level_db");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap1/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap1_pan", "get_tap1_pan");
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap2/active"), "set_tap2_active", "is_tap2_active");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap2/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1,suffix:ms"), "set_tap2_delay_ms", "get_tap2_delay_ms");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap2/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01,suffix:dB"), "set_tap2_level_db", "get_tap2_level_db");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap2/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap2_pan", "get_tap2_pan");
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "feedback/active"), "set_feedback_active", "is_feedback_active");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "feedback/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1,suffix:ms"), "set_feedback_delay_ms", "get_feedback_delay_ms");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "feedback/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01,suffix:dB"), "set_feedback_level_db", "get_feedback_level_db");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "feedback/lowpass", PROPERTY_HINT_RANGE, "1,16000,1"), "set_feedback_lowpass", "get_feedback_lowpass");
-}
-
-AudioEffectDelay::AudioEffectDelay() {
- tap_1_active = true;
- tap_1_delay_ms = 250;
- tap_1_level = -6;
- tap_1_pan = 0.2;
-
- tap_2_active = true;
- tap_2_delay_ms = 500;
- tap_2_level = -12;
- tap_2_pan = -0.4;
-
- feedback_active = false;
- feedback_delay_ms = 340;
- feedback_level = -6;
- feedback_lowpass = 16000;
-
- dry = 1.0;
+ ADD_GROUP("Tap 1", "tap1_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap1_active"), "set_tap1_active", "is_tap1_active");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap1_delay_ms", PROPERTY_HINT_RANGE, "0,1500,1,suffix:ms"), "set_tap1_delay_ms", "get_tap1_delay_ms");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap1_level_db", PROPERTY_HINT_RANGE, "-60,0,0.01,suffix:dB"), "set_tap1_level_db", "get_tap1_level_db");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap1_pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap1_pan", "get_tap1_pan");
+
+ ADD_GROUP("Tap 2", "tap2_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap2_active"), "set_tap2_active", "is_tap2_active");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap2_delay_ms", PROPERTY_HINT_RANGE, "0,1500,1,suffix:ms"), "set_tap2_delay_ms", "get_tap2_delay_ms");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap2_level_db", PROPERTY_HINT_RANGE, "-60,0,0.01,suffix:dB"), "set_tap2_level_db", "get_tap2_level_db");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap2_pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap2_pan", "get_tap2_pan");
+
+ ADD_GROUP("Feedback", "feedback_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "feedback_active"), "set_feedback_active", "is_feedback_active");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "feedback_delay_ms", PROPERTY_HINT_RANGE, "0,1500,1,suffix:ms"), "set_feedback_delay_ms", "get_feedback_delay_ms");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "feedback_level_db", PROPERTY_HINT_RANGE, "-60,0,0.01,suffix:dB"), "set_feedback_level_db", "get_feedback_level_db");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "feedback_lowpass", PROPERTY_HINT_RANGE, "1,16000,1"), "set_feedback_lowpass", "get_feedback_lowpass");
}
diff --git a/servers/audio/effects/audio_effect_delay.h b/servers/audio/effects/audio_effect_delay.h
index 137a4e7dbe..020d45e79b 100644
--- a/servers/audio/effects/audio_effect_delay.h
+++ b/servers/audio/effects/audio_effect_delay.h
@@ -37,6 +37,7 @@ class AudioEffectDelay;
class AudioEffectDelayInstance : public AudioEffectInstance {
GDCLASS(AudioEffectDelayInstance, AudioEffectInstance);
+
friend class AudioEffectDelay;
Ref<AudioEffectDelay> base;
@@ -66,22 +67,22 @@ class AudioEffectDelay : public AudioEffect {
MAX_TAPS = 2
};
- float dry;
+ float dry = 1.0f;
- bool tap_1_active;
- float tap_1_delay_ms;
- float tap_1_level;
- float tap_1_pan;
+ bool tap_1_active = true;
+ float tap_1_delay_ms = 250.0f;
+ float tap_1_level = -6.0f;
+ float tap_1_pan = 0.2f;
- bool tap_2_active;
- float tap_2_delay_ms;
- float tap_2_level;
- float tap_2_pan;
+ bool tap_2_active = true;
+ float tap_2_delay_ms = 500.0f;
+ float tap_2_level = -12.0f;
+ float tap_2_pan = -0.4f;
- bool feedback_active;
- float feedback_delay_ms;
- float feedback_level;
- float feedback_lowpass;
+ bool feedback_active = false;
+ float feedback_delay_ms = 340.0f;
+ float feedback_level = -6.0f;
+ float feedback_lowpass = 16000.0f;
protected:
static void _bind_methods();
@@ -128,7 +129,7 @@ public:
Ref<AudioEffectInstance> instantiate() override;
- AudioEffectDelay();
+ AudioEffectDelay() {}
};
#endif // AUDIO_EFFECT_DELAY_H
diff --git a/servers/audio/effects/audio_effect_filter.h b/servers/audio/effects/audio_effect_filter.h
index a40af2f13c..1510ee2af7 100644
--- a/servers/audio/effects/audio_effect_filter.h
+++ b/servers/audio/effects/audio_effect_filter.h
@@ -98,9 +98,9 @@ VARIANT_ENUM_CAST(AudioEffectFilter::FilterDB)
class AudioEffectLowPassFilter : public AudioEffectFilter {
GDCLASS(AudioEffectLowPassFilter, AudioEffectFilter);
- void _validate_property(PropertyInfo &property) const override {
- if (property.name == "gain") {
- property.usage = PROPERTY_USAGE_NONE;
+ void _validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "gain") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
@@ -111,9 +111,9 @@ public:
class AudioEffectHighPassFilter : public AudioEffectFilter {
GDCLASS(AudioEffectHighPassFilter, AudioEffectFilter);
- void _validate_property(PropertyInfo &property) const override {
- if (property.name == "gain") {
- property.usage = PROPERTY_USAGE_NONE;
+ void _validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "gain") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
@@ -124,9 +124,9 @@ public:
class AudioEffectBandPassFilter : public AudioEffectFilter {
GDCLASS(AudioEffectBandPassFilter, AudioEffectFilter);
- void _validate_property(PropertyInfo &property) const override {
- if (property.name == "gain") {
- property.usage = PROPERTY_USAGE_NONE;
+ void _validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "gain") {
+ p_property.usage = PROPERTY_USAGE_NONE;
}
}
diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp
index 9052f8e05e..64695557aa 100644
--- a/servers/audio_server.cpp
+++ b/servers/audio_server.cpp
@@ -144,8 +144,8 @@ int AudioDriver::get_total_channels_by_speaker_mode(AudioDriver::SpeakerMode p_m
ERR_FAIL_V(2);
}
-Array AudioDriver::get_device_list() {
- Array list;
+PackedStringArray AudioDriver::get_device_list() {
+ PackedStringArray list;
list.push_back("Default");
@@ -156,8 +156,8 @@ String AudioDriver::get_device() {
return "Default";
}
-Array AudioDriver::capture_get_device_list() {
- Array list;
+PackedStringArray AudioDriver::capture_get_device_list() {
+ PackedStringArray list;
list.push_back("Default");
@@ -1637,7 +1637,7 @@ Ref<AudioBusLayout> AudioServer::generate_bus_layout() const {
return state;
}
-Array AudioServer::get_device_list() {
+PackedStringArray AudioServer::get_device_list() {
return AudioDriver::get_singleton()->get_device_list();
}
@@ -1649,7 +1649,7 @@ void AudioServer::set_device(String device) {
AudioDriver::get_singleton()->set_device(device);
}
-Array AudioServer::capture_get_device_list() {
+PackedStringArray AudioServer::capture_get_device_list() {
return AudioDriver::get_singleton()->capture_get_device_list();
}
diff --git a/servers/audio_server.h b/servers/audio_server.h
index 5613267909..588107c25d 100644
--- a/servers/audio_server.h
+++ b/servers/audio_server.h
@@ -94,7 +94,7 @@ public:
virtual void start() = 0;
virtual int get_mix_rate() const = 0;
virtual SpeakerMode get_speaker_mode() const = 0;
- virtual Array get_device_list();
+ virtual PackedStringArray get_device_list();
virtual String get_device();
virtual void set_device(String device) {}
virtual void lock() = 0;
@@ -105,7 +105,7 @@ public:
virtual Error capture_stop() { return FAILED; }
virtual void capture_set_device(const String &p_name) {}
virtual String capture_get_device() { return "Default"; }
- virtual Array capture_get_device_list(); // TODO: convert this and get_device_list to PackedStringArray
+ virtual PackedStringArray capture_get_device_list();
virtual float get_latency() { return 0; }
@@ -419,11 +419,11 @@ public:
void set_bus_layout(const Ref<AudioBusLayout> &p_bus_layout);
Ref<AudioBusLayout> generate_bus_layout() const;
- Array get_device_list();
+ PackedStringArray get_device_list();
String get_device();
void set_device(String device);
- Array capture_get_device_list();
+ PackedStringArray capture_get_device_list();
String capture_get_device();
void capture_set_device(const String &p_name);
diff --git a/servers/camera_server.cpp b/servers/camera_server.cpp
index 91df3afadd..b83b41a571 100644
--- a/servers/camera_server.cpp
+++ b/servers/camera_server.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "camera_server.h"
+#include "core/variant/typed_array.h"
#include "rendering_server.h"
#include "servers/camera/camera_feed.h"
@@ -143,8 +144,8 @@ int CameraServer::get_feed_count() {
return feeds.size();
};
-Array CameraServer::get_feeds() {
- Array return_feeds;
+TypedArray<CameraFeed> CameraServer::get_feeds() {
+ TypedArray<CameraFeed> return_feeds;
int cc = get_feed_count();
return_feeds.resize(cc);
diff --git a/servers/camera_server.h b/servers/camera_server.h
index b70938c34f..c6fb906b3c 100644
--- a/servers/camera_server.h
+++ b/servers/camera_server.h
@@ -43,6 +43,8 @@
**/
class CameraFeed;
+template <typename T>
+class TypedArray;
class CameraServer : public Object {
GDCLASS(CameraServer, Object);
@@ -100,7 +102,7 @@ public:
// Get our feeds.
Ref<CameraFeed> get_feed(int p_index);
int get_feed_count();
- Array get_feeds();
+ TypedArray<CameraFeed> get_feeds();
// Intended for use with custom CameraServer implementation.
RID feed_texture(int p_id, FeedImage p_texture);
diff --git a/servers/display_server.cpp b/servers/display_server.cpp
index 4e7db7d0a5..0c05570b23 100644
--- a/servers/display_server.cpp
+++ b/servers/display_server.cpp
@@ -44,40 +44,49 @@ DisplayServer::DisplayServerCreate DisplayServer::server_create_functions[Displa
int DisplayServer::server_create_count = 1;
-void DisplayServer::global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServer::global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServer::global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServer::global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServer::global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServer::global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServer::global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
+int DisplayServer::global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback, const Variant &p_tag, Key p_accel, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index) {
+int DisplayServer::global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
-void DisplayServer::global_menu_add_separator(const String &p_menu_root, int p_index) {
+int DisplayServer::global_menu_add_separator(const String &p_menu_root, int p_index) {
WARN_PRINT("Global menus not supported by this display server.");
+ return -1;
}
int DisplayServer::global_menu_get_item_index_from_text(const String &p_menu_root, const String &p_text) const {
@@ -159,6 +168,11 @@ Ref<Texture2D> DisplayServer::global_menu_get_item_icon(const String &p_menu_roo
return Ref<Texture2D>();
}
+int DisplayServer::global_menu_get_item_indentation_level(const String &p_menu_root, int p_idx) const {
+ WARN_PRINT("Global menus not supported by this display server.");
+ return 0;
+}
+
void DisplayServer::global_menu_set_item_checked(const String &p_menu_root, int p_idx, bool p_checked) {
WARN_PRINT("Global menus not supported by this display server.");
}
@@ -207,6 +221,10 @@ void DisplayServer::global_menu_set_item_icon(const String &p_menu_root, int p_i
WARN_PRINT("Global menus not supported by this display server.");
}
+void DisplayServer::global_menu_set_item_indentation_level(const String &p_menu_root, int p_idx, int p_level) {
+ WARN_PRINT("Global menus not supported by this display server.");
+}
+
int DisplayServer::global_menu_get_item_count(const String &p_menu_root) const {
WARN_PRINT("Global menus not supported by this display server.");
return 0;
@@ -238,14 +256,14 @@ void DisplayServer::tts_resume() {
WARN_PRINT("TTS is not supported by this display server.");
}
-Array DisplayServer::tts_get_voices() const {
+TypedArray<Dictionary> DisplayServer::tts_get_voices() const {
WARN_PRINT("TTS is not supported by this display server.");
- return Array();
+ return TypedArray<Dictionary>();
}
PackedStringArray DisplayServer::tts_get_voices_for_language(const String &p_language) const {
PackedStringArray ret;
- Array voices = tts_get_voices();
+ TypedArray<Dictionary> voices = tts_get_voices();
for (int i = 0; i < voices.size(); i++) {
const Dictionary &voice = voices[i];
if (voice.has("id") && voice.has("language") && voice["language"].operator String().begins_with(p_language)) {
@@ -535,6 +553,7 @@ void DisplayServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("global_menu_get_item_state", "menu_root", "idx"), &DisplayServer::global_menu_get_item_state);
ClassDB::bind_method(D_METHOD("global_menu_get_item_max_states", "menu_root", "idx"), &DisplayServer::global_menu_get_item_max_states);
ClassDB::bind_method(D_METHOD("global_menu_get_item_icon", "menu_root", "idx"), &DisplayServer::global_menu_get_item_icon);
+ ClassDB::bind_method(D_METHOD("global_menu_get_item_indentation_level", "menu_root", "idx"), &DisplayServer::global_menu_get_item_indentation_level);
ClassDB::bind_method(D_METHOD("global_menu_set_item_checked", "menu_root", "idx", "checked"), &DisplayServer::global_menu_set_item_checked);
ClassDB::bind_method(D_METHOD("global_menu_set_item_checkable", "menu_root", "idx", "checkable"), &DisplayServer::global_menu_set_item_checkable);
@@ -549,6 +568,7 @@ void DisplayServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("global_menu_set_item_state", "menu_root", "idx", "state"), &DisplayServer::global_menu_set_item_state);
ClassDB::bind_method(D_METHOD("global_menu_set_item_max_states", "menu_root", "idx", "max_states"), &DisplayServer::global_menu_set_item_max_states);
ClassDB::bind_method(D_METHOD("global_menu_set_item_icon", "menu_root", "idx", "icon"), &DisplayServer::global_menu_set_item_icon);
+ ClassDB::bind_method(D_METHOD("global_menu_set_item_indentation_level", "menu_root", "idx", "level"), &DisplayServer::global_menu_set_item_indentation_level);
ClassDB::bind_method(D_METHOD("global_menu_remove_item", "menu_root", "idx"), &DisplayServer::global_menu_remove_item);
ClassDB::bind_method(D_METHOD("global_menu_clear", "menu_root"), &DisplayServer::global_menu_clear);
diff --git a/servers/display_server.h b/servers/display_server.h
index 8632b53f7b..4e52c58633 100644
--- a/servers/display_server.h
+++ b/servers/display_server.h
@@ -127,15 +127,15 @@ public:
virtual bool has_feature(Feature p_feature) const = 0;
virtual String get_name() const = 0;
- virtual void global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
- virtual void global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
- virtual void global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
- virtual void global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
- virtual void global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
- virtual void global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
- virtual void global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
- virtual void global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index = -1);
- virtual void global_menu_add_separator(const String &p_menu_root, int p_index = -1);
+ virtual int global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
+ virtual int global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
+ virtual int global_menu_add_icon_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
+ virtual int global_menu_add_icon_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
+ virtual int global_menu_add_radio_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
+ virtual int global_menu_add_icon_radio_check_item(const String &p_menu_root, const Ref<Texture2D> &p_icon, const String &p_label, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
+ virtual int global_menu_add_multistate_item(const String &p_menu_root, const String &p_label, int p_max_states, int p_default_state, const Callable &p_callback = Callable(), const Variant &p_tag = Variant(), Key p_accel = Key::NONE, int p_index = -1);
+ virtual int global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index = -1);
+ virtual int global_menu_add_separator(const String &p_menu_root, int p_index = -1);
virtual int global_menu_get_item_index_from_text(const String &p_menu_root, const String &p_text) const;
virtual int global_menu_get_item_index_from_tag(const String &p_menu_root, const Variant &p_tag) const;
@@ -153,6 +153,7 @@ public:
virtual int global_menu_get_item_state(const String &p_menu_root, int p_idx) const;
virtual int global_menu_get_item_max_states(const String &p_menu_root, int p_idx) const;
virtual Ref<Texture2D> global_menu_get_item_icon(const String &p_menu_root, int p_idx) const;
+ virtual int global_menu_get_item_indentation_level(const String &p_menu_root, int p_idx) const;
virtual void global_menu_set_item_checked(const String &p_menu_root, int p_idx, bool p_checked);
virtual void global_menu_set_item_checkable(const String &p_menu_root, int p_idx, bool p_checkable);
@@ -167,6 +168,7 @@ public:
virtual void global_menu_set_item_state(const String &p_menu_root, int p_idx, int p_state);
virtual void global_menu_set_item_max_states(const String &p_menu_root, int p_idx, int p_max_states);
virtual void global_menu_set_item_icon(const String &p_menu_root, int p_idx, const Ref<Texture2D> &p_icon);
+ virtual void global_menu_set_item_indentation_level(const String &p_menu_root, int p_idx, int p_level);
virtual int global_menu_get_item_count(const String &p_menu_root) const;
@@ -196,7 +198,7 @@ private:
public:
virtual bool tts_is_speaking() const;
virtual bool tts_is_paused() const;
- virtual Array tts_get_voices() const;
+ virtual TypedArray<Dictionary> tts_get_voices() const;
virtual PackedStringArray tts_get_voices_for_language(const String &p_language) const;
virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false);
@@ -228,7 +230,7 @@ public:
virtual void clipboard_set_primary(const String &p_text);
virtual String clipboard_get_primary() const;
- virtual Array get_display_cutouts() const { return Array(); }
+ virtual TypedArray<Rect2> get_display_cutouts() const { return TypedArray<Rect2>(); }
virtual Rect2i get_display_safe_area() const { return screen_get_usable_rect(); }
enum {
diff --git a/servers/extensions/physics_server_3d_extension.cpp b/servers/extensions/physics_server_3d_extension.cpp
index 3694dcdb9a..7d797bf611 100644
--- a/servers/extensions/physics_server_3d_extension.cpp
+++ b/servers/extensions/physics_server_3d_extension.cpp
@@ -196,6 +196,9 @@ void PhysicsServer3DExtension::_bind_methods() {
GDVIRTUAL_BIND(_body_set_collision_mask, "body", "mask");
GDVIRTUAL_BIND(_body_get_collision_mask, "body");
+ GDVIRTUAL_BIND(_body_set_collision_priority, "body", "priority");
+ GDVIRTUAL_BIND(_body_get_collision_priority, "body");
+
GDVIRTUAL_BIND(_body_add_shape, "body", "shape", "transform", "disabled");
GDVIRTUAL_BIND(_body_set_shape, "body", "shape_idx", "shape");
GDVIRTUAL_BIND(_body_set_shape_transform, "body", "shape_idx", "transform");
diff --git a/servers/extensions/physics_server_3d_extension.h b/servers/extensions/physics_server_3d_extension.h
index c4b4a00eaf..3200438253 100644
--- a/servers/extensions/physics_server_3d_extension.h
+++ b/servers/extensions/physics_server_3d_extension.h
@@ -319,6 +319,9 @@ public:
EXBIND2(body_set_collision_mask, RID, uint32_t)
EXBIND1RC(uint32_t, body_get_collision_mask, RID)
+ EXBIND2(body_set_collision_priority, RID, real_t)
+ EXBIND1RC(real_t, body_get_collision_priority, RID)
+
EXBIND2(body_set_user_flags, RID, uint32_t)
EXBIND1RC(uint32_t, body_get_user_flags, RID)
diff --git a/servers/navigation_server_2d.cpp b/servers/navigation_server_2d.cpp
index 126bb08c94..0f73df8894 100644
--- a/servers/navigation_server_2d.cpp
+++ b/servers/navigation_server_2d.cpp
@@ -204,7 +204,7 @@ void NavigationServer2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("map_create"), &NavigationServer2D::map_create);
ClassDB::bind_method(D_METHOD("map_set_active", "map", "active"), &NavigationServer2D::map_set_active);
- ClassDB::bind_method(D_METHOD("map_is_active", "nap"), &NavigationServer2D::map_is_active);
+ ClassDB::bind_method(D_METHOD("map_is_active", "map"), &NavigationServer2D::map_is_active);
ClassDB::bind_method(D_METHOD("map_set_cell_size", "map", "cell_size"), &NavigationServer2D::map_set_cell_size);
ClassDB::bind_method(D_METHOD("map_get_cell_size", "map"), &NavigationServer2D::map_get_cell_size);
ClassDB::bind_method(D_METHOD("map_set_edge_connection_margin", "map", "margin"), &NavigationServer2D::map_set_edge_connection_margin);
@@ -237,7 +237,7 @@ void NavigationServer2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("agent_create"), &NavigationServer2D::agent_create);
ClassDB::bind_method(D_METHOD("agent_set_map", "agent", "map"), &NavigationServer2D::agent_set_map);
ClassDB::bind_method(D_METHOD("agent_get_map", "agent"), &NavigationServer2D::agent_get_map);
- ClassDB::bind_method(D_METHOD("agent_set_neighbor_dist", "agent", "dist"), &NavigationServer2D::agent_set_neighbor_dist);
+ ClassDB::bind_method(D_METHOD("agent_set_neighbor_distance", "agent", "distance"), &NavigationServer2D::agent_set_neighbor_distance);
ClassDB::bind_method(D_METHOD("agent_set_max_neighbors", "agent", "count"), &NavigationServer2D::agent_set_max_neighbors);
ClassDB::bind_method(D_METHOD("agent_set_time_horizon", "agent", "time"), &NavigationServer2D::agent_set_time_horizon);
ClassDB::bind_method(D_METHOD("agent_set_radius", "agent", "radius"), &NavigationServer2D::agent_set_radius);
@@ -263,11 +263,11 @@ NavigationServer2D::~NavigationServer2D() {
singleton = nullptr;
}
-Array FORWARD_0_C(get_maps);
+TypedArray<RID> FORWARD_0_C(get_maps);
-Array FORWARD_1_C(map_get_regions, RID, p_map, rid_to_rid);
+TypedArray<RID> FORWARD_1_C(map_get_regions, RID, p_map, rid_to_rid);
-Array FORWARD_1_C(map_get_agents, RID, p_map, rid_to_rid);
+TypedArray<RID> FORWARD_1_C(map_get_agents, RID, p_map, rid_to_rid);
RID FORWARD_1_C(region_get_map, RID, p_region, rid_to_rid);
@@ -323,7 +323,7 @@ RID NavigationServer2D::agent_create() const {
void FORWARD_2_C(agent_set_map, RID, p_agent, RID, p_map, rid_to_rid, rid_to_rid);
-void FORWARD_2_C(agent_set_neighbor_dist, RID, p_agent, real_t, p_dist, rid_to_rid, real_to_real);
+void FORWARD_2_C(agent_set_neighbor_distance, RID, p_agent, real_t, p_dist, rid_to_rid, real_to_real);
void FORWARD_2_C(agent_set_max_neighbors, RID, p_agent, int, p_count, rid_to_rid, int_to_int);
diff --git a/servers/navigation_server_2d.h b/servers/navigation_server_2d.h
index 83271f990e..5e96466d66 100644
--- a/servers/navigation_server_2d.h
+++ b/servers/navigation_server_2d.h
@@ -53,7 +53,7 @@ public:
/// MUST be used in single thread!
static NavigationServer2D *get_singleton_mut() { return singleton; }
- virtual Array get_maps() const;
+ virtual TypedArray<RID> get_maps() const;
/// Create a new map.
virtual RID map_create() const;
@@ -82,8 +82,8 @@ public:
virtual Vector2 map_get_closest_point(RID p_map, const Vector2 &p_point) const;
virtual RID map_get_closest_point_owner(RID p_map, const Vector2 &p_point) const;
- virtual Array map_get_regions(RID p_map) const;
- virtual Array map_get_agents(RID p_map) const;
+ virtual TypedArray<RID> map_get_regions(RID p_map) const;
+ virtual TypedArray<RID> map_get_agents(RID p_map) const;
virtual void map_force_update(RID p_map);
@@ -133,7 +133,7 @@ public:
/// time of the simulation. If the number is too
/// low, the simulation will not be safe.
/// Must be non-negative.
- virtual void agent_set_neighbor_dist(RID p_agent, real_t p_dist) const;
+ virtual void agent_set_neighbor_distance(RID p_agent, real_t p_distance) const;
/// The maximum number of other agents this
/// agent takes into account in the navigation.
diff --git a/servers/navigation_server_3d.cpp b/servers/navigation_server_3d.cpp
index 115eda7b30..466b74bc64 100644
--- a/servers/navigation_server_3d.cpp
+++ b/servers/navigation_server_3d.cpp
@@ -41,7 +41,7 @@ void NavigationServer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("map_create"), &NavigationServer3D::map_create);
ClassDB::bind_method(D_METHOD("map_set_active", "map", "active"), &NavigationServer3D::map_set_active);
- ClassDB::bind_method(D_METHOD("map_is_active", "nap"), &NavigationServer3D::map_is_active);
+ ClassDB::bind_method(D_METHOD("map_is_active", "map"), &NavigationServer3D::map_is_active);
ClassDB::bind_method(D_METHOD("map_set_up", "map", "up"), &NavigationServer3D::map_set_up);
ClassDB::bind_method(D_METHOD("map_get_up", "map"), &NavigationServer3D::map_get_up);
ClassDB::bind_method(D_METHOD("map_set_cell_size", "map", "cell_size"), &NavigationServer3D::map_set_cell_size);
@@ -79,7 +79,7 @@ void NavigationServer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("agent_create"), &NavigationServer3D::agent_create);
ClassDB::bind_method(D_METHOD("agent_set_map", "agent", "map"), &NavigationServer3D::agent_set_map);
ClassDB::bind_method(D_METHOD("agent_get_map", "agent"), &NavigationServer3D::agent_get_map);
- ClassDB::bind_method(D_METHOD("agent_set_neighbor_dist", "agent", "dist"), &NavigationServer3D::agent_set_neighbor_dist);
+ ClassDB::bind_method(D_METHOD("agent_set_neighbor_distance", "agent", "distance"), &NavigationServer3D::agent_set_neighbor_distance);
ClassDB::bind_method(D_METHOD("agent_set_max_neighbors", "agent", "count"), &NavigationServer3D::agent_set_max_neighbors);
ClassDB::bind_method(D_METHOD("agent_set_time_horizon", "agent", "time"), &NavigationServer3D::agent_set_time_horizon);
ClassDB::bind_method(D_METHOD("agent_set_radius", "agent", "radius"), &NavigationServer3D::agent_set_radius);
diff --git a/servers/navigation_server_3d.h b/servers/navigation_server_3d.h
index f24c0117d1..3213da3d84 100644
--- a/servers/navigation_server_3d.h
+++ b/servers/navigation_server_3d.h
@@ -56,7 +56,7 @@ public:
/// MUST be used in single thread!
static NavigationServer3D *get_singleton_mut();
- virtual Array get_maps() const = 0;
+ virtual TypedArray<RID> get_maps() const = 0;
/// Create a new map.
virtual RID map_create() const = 0;
@@ -93,8 +93,8 @@ public:
virtual Vector3 map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const = 0;
virtual RID map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const = 0;
- virtual Array map_get_regions(RID p_map) const = 0;
- virtual Array map_get_agents(RID p_map) const = 0;
+ virtual TypedArray<RID> map_get_regions(RID p_map) const = 0;
+ virtual TypedArray<RID> map_get_agents(RID p_map) const = 0;
virtual void map_force_update(RID p_map) = 0;
@@ -147,7 +147,7 @@ public:
/// time of the simulation. If the number is too
/// low, the simulation will not be safe.
/// Must be non-negative.
- virtual void agent_set_neighbor_dist(RID p_agent, real_t p_dist) const = 0;
+ virtual void agent_set_neighbor_distance(RID p_agent, real_t p_distance) const = 0;
/// The maximum number of other agents this
/// agent takes into account in the navigation.
diff --git a/servers/physics_2d/godot_collision_object_2d.h b/servers/physics_2d/godot_collision_object_2d.h
index 1a683a7b0f..7965e8a94d 100644
--- a/servers/physics_2d/godot_collision_object_2d.h
+++ b/servers/physics_2d/godot_collision_object_2d.h
@@ -70,6 +70,7 @@ private:
Transform2D inv_transform;
uint32_t collision_mask = 1;
uint32_t collision_layer = 1;
+ real_t collision_priority = 1.0;
bool _static = true;
SelfList<GodotCollisionObject2D> pending_shape_update_list;
@@ -166,6 +167,13 @@ public:
}
_FORCE_INLINE_ uint32_t get_collision_layer() const { return collision_layer; }
+ _FORCE_INLINE_ void set_collision_priority(real_t p_priority) {
+ ERR_FAIL_COND_MSG(p_priority <= 0, "Priority must be greater than 0.");
+ collision_priority = p_priority;
+ _shape_changed();
+ }
+ _FORCE_INLINE_ real_t get_collision_priority() const { return collision_priority; }
+
void remove_shape(GodotShape2D *p_shape) override;
void remove_shape(int p_index);
diff --git a/servers/physics_2d/godot_physics_server_2d.cpp b/servers/physics_2d/godot_physics_server_2d.cpp
index 99e68de07c..c728dccd4f 100644
--- a/servers/physics_2d/godot_physics_server_2d.cpp
+++ b/servers/physics_2d/godot_physics_server_2d.cpp
@@ -718,6 +718,20 @@ uint32_t GodotPhysicsServer2D::body_get_collision_mask(RID p_body) const {
return body->get_collision_mask();
}
+void GodotPhysicsServer2D::body_set_collision_priority(RID p_body, real_t p_priority) {
+ GodotBody2D *body = body_owner.get_or_null(p_body);
+ ERR_FAIL_COND(!body);
+
+ body->set_collision_priority(p_priority);
+}
+
+real_t GodotPhysicsServer2D::body_get_collision_priority(RID p_body) const {
+ const GodotBody2D *body = body_owner.get_or_null(p_body);
+ ERR_FAIL_COND_V(!body, 0);
+
+ return body->get_collision_priority();
+}
+
void GodotPhysicsServer2D::body_set_param(RID p_body, BodyParameter p_param, const Variant &p_value) {
GodotBody2D *body = body_owner.get_or_null(p_body);
ERR_FAIL_COND(!body);
diff --git a/servers/physics_2d/godot_physics_server_2d.h b/servers/physics_2d/godot_physics_server_2d.h
index 2af6e5c97c..20e492d87a 100644
--- a/servers/physics_2d/godot_physics_server_2d.h
+++ b/servers/physics_2d/godot_physics_server_2d.h
@@ -199,6 +199,9 @@ public:
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;
+ virtual void body_set_collision_priority(RID p_body, real_t p_priority) override;
+ virtual real_t body_get_collision_priority(RID p_body) const override;
+
virtual void body_set_param(RID p_body, BodyParameter p_param, const Variant &p_value) override;
virtual Variant body_get_param(RID p_body, BodyParameter p_param) const override;
diff --git a/servers/physics_2d/godot_space_2d.cpp b/servers/physics_2d/godot_space_2d.cpp
index 166ec3049e..4166191be8 100644
--- a/servers/physics_2d/godot_space_2d.cpp
+++ b/servers/physics_2d/godot_space_2d.cpp
@@ -594,6 +594,7 @@ bool GodotSpace2D::test_body_motion(GodotBody2D *p_body, const PhysicsServer2D::
const int max_results = 32;
int recover_attempts = 4;
Vector2 sr[max_results * 2];
+ real_t priorities[max_results];
do {
GodotPhysicsServer2D::CollCbkData cbk;
@@ -606,6 +607,7 @@ bool GodotSpace2D::test_body_motion(GodotBody2D *p_body, const PhysicsServer2D::
GodotPhysicsServer2D::CollCbkData *cbkptr = &cbk;
GodotCollisionSolver2D::CallbackResult cbkres = GodotPhysicsServer2D::_shape_col_cbk;
+ int priority_amount = 0;
bool collided = false;
@@ -664,6 +666,10 @@ bool GodotSpace2D::test_body_motion(GodotBody2D *p_body, const PhysicsServer2D::
if (GodotCollisionSolver2D::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, nullptr, margin)) {
did_collide = cbk.passed > current_passed; //more passed, so collision actually existed
}
+ while (cbk.amount > priority_amount) {
+ priorities[priority_amount] = col_obj->get_collision_priority();
+ priority_amount++;
+ }
if (!did_collide && cbk.invalid_by_dir > 0) {
//this shape must be excluded
@@ -686,6 +692,12 @@ bool GodotSpace2D::test_body_motion(GodotBody2D *p_body, const PhysicsServer2D::
break;
}
+ real_t inv_total_weight = 0.0;
+ for (int i = 0; i < cbk.amount; i++) {
+ inv_total_weight += priorities[i];
+ }
+ inv_total_weight = Math::is_zero_approx(inv_total_weight) ? 1.0 : (real_t)cbk.amount / inv_total_weight;
+
recovered = true;
Vector2 recover_motion;
@@ -701,7 +713,7 @@ bool GodotSpace2D::test_body_motion(GodotBody2D *p_body, const PhysicsServer2D::
real_t depth = n.dot(a + recover_motion) - d;
if (depth > min_contact_depth + CMP_EPSILON) {
// Only recover if there is penetration.
- recover_motion -= n * (depth - min_contact_depth) * 0.4;
+ recover_motion -= n * (depth - min_contact_depth) * 0.4 * priorities[i] * inv_total_weight;
}
}
diff --git a/servers/physics_3d/godot_collision_object_3d.h b/servers/physics_3d/godot_collision_object_3d.h
index 0f09f21962..2d342f65f3 100644
--- a/servers/physics_3d/godot_collision_object_3d.h
+++ b/servers/physics_3d/godot_collision_object_3d.h
@@ -59,6 +59,7 @@ private:
ObjectID instance_id;
uint32_t collision_layer = 1;
uint32_t collision_mask = 1;
+ real_t collision_priority = 1.0;
struct Shape {
Transform3D xform;
@@ -165,6 +166,13 @@ public:
}
_FORCE_INLINE_ uint32_t get_collision_mask() const { return collision_mask; }
+ _FORCE_INLINE_ void set_collision_priority(real_t p_priority) {
+ ERR_FAIL_COND_MSG(p_priority <= 0, "Priority must be greater than 0.");
+ collision_priority = p_priority;
+ _shape_changed();
+ }
+ _FORCE_INLINE_ real_t get_collision_priority() const { return collision_priority; }
+
_FORCE_INLINE_ bool collides_with(GodotCollisionObject3D *p_other) const {
return p_other->collision_layer & collision_mask;
}
diff --git a/servers/physics_3d/godot_physics_server_3d.cpp b/servers/physics_3d/godot_physics_server_3d.cpp
index b735283ebe..9c1535f561 100644
--- a/servers/physics_3d/godot_physics_server_3d.cpp
+++ b/servers/physics_3d/godot_physics_server_3d.cpp
@@ -593,6 +593,20 @@ uint32_t GodotPhysicsServer3D::body_get_collision_mask(RID p_body) const {
return body->get_collision_mask();
}
+void GodotPhysicsServer3D::body_set_collision_priority(RID p_body, real_t p_priority) {
+ GodotBody3D *body = body_owner.get_or_null(p_body);
+ ERR_FAIL_COND(!body);
+
+ body->set_collision_priority(p_priority);
+}
+
+real_t GodotPhysicsServer3D::body_get_collision_priority(RID p_body) const {
+ const GodotBody3D *body = body_owner.get_or_null(p_body);
+ ERR_FAIL_COND_V(!body, 0);
+
+ return body->get_collision_priority();
+}
+
void GodotPhysicsServer3D::body_attach_object_instance_id(RID p_body, ObjectID p_id) {
GodotBody3D *body = body_owner.get_or_null(p_body);
if (body) {
diff --git a/servers/physics_3d/godot_physics_server_3d.h b/servers/physics_3d/godot_physics_server_3d.h
index 1d57451925..b429f23a0c 100644
--- a/servers/physics_3d/godot_physics_server_3d.h
+++ b/servers/physics_3d/godot_physics_server_3d.h
@@ -192,6 +192,9 @@ public:
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;
+ virtual void body_set_collision_priority(RID p_body, real_t p_priority) override;
+ virtual real_t body_get_collision_priority(RID p_body) const override;
+
virtual void body_set_user_flags(RID p_body, uint32_t p_flags) override;
virtual uint32_t body_get_user_flags(RID p_body) const override;
diff --git a/servers/physics_3d/godot_space_3d.cpp b/servers/physics_3d/godot_space_3d.cpp
index 13e9a89b2e..074232dd66 100644
--- a/servers/physics_3d/godot_space_3d.cpp
+++ b/servers/physics_3d/godot_space_3d.cpp
@@ -701,6 +701,7 @@ bool GodotSpace3D::test_body_motion(GodotBody3D *p_body, const PhysicsServer3D::
const int max_results = 32;
int recover_attempts = 4;
Vector3 sr[max_results * 2];
+ real_t priorities[max_results];
do {
GodotPhysicsServer3D::CollCbkData cbk;
@@ -710,6 +711,7 @@ bool GodotSpace3D::test_body_motion(GodotBody3D *p_body, const PhysicsServer3D::
GodotPhysicsServer3D::CollCbkData *cbkptr = &cbk;
GodotCollisionSolver3D::CallbackResult cbkres = GodotPhysicsServer3D::_shape_col_cbk;
+ int priority_amount = 0;
bool collided = false;
@@ -737,6 +739,10 @@ bool GodotSpace3D::test_body_motion(GodotBody3D *p_body, const PhysicsServer3D::
if (GodotCollisionSolver3D::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, nullptr, margin)) {
collided = cbk.amount > 0;
}
+ while (cbk.amount > priority_amount) {
+ priorities[priority_amount] = col_obj->get_collision_priority();
+ priority_amount++;
+ }
}
}
@@ -744,6 +750,12 @@ bool GodotSpace3D::test_body_motion(GodotBody3D *p_body, const PhysicsServer3D::
break;
}
+ real_t inv_total_weight = 0.0;
+ for (int i = 0; i < cbk.amount; i++) {
+ inv_total_weight += priorities[i];
+ }
+ inv_total_weight = Math::is_zero_approx(inv_total_weight) ? 1.0 : (real_t)cbk.amount / inv_total_weight;
+
recovered = true;
Vector3 recover_motion;
@@ -759,7 +771,7 @@ bool GodotSpace3D::test_body_motion(GodotBody3D *p_body, const PhysicsServer3D::
real_t depth = n.dot(a + recover_motion) - d;
if (depth > min_contact_depth + CMP_EPSILON) {
// Only recover if there is penetration.
- recover_motion -= n * (depth - min_contact_depth) * 0.4;
+ recover_motion -= n * (depth - min_contact_depth) * 0.4 * priorities[i] * inv_total_weight;
}
}
diff --git a/servers/physics_server_2d.cpp b/servers/physics_server_2d.cpp
index 26768e300c..bfb5cd8106 100644
--- a/servers/physics_server_2d.cpp
+++ b/servers/physics_server_2d.cpp
@@ -32,6 +32,7 @@
#include "core/config/project_settings.h"
#include "core/string/print_string.h"
+#include "core/variant/typed_array.h"
PhysicsServer2D *PhysicsServer2D::singleton = nullptr;
@@ -347,7 +348,7 @@ Dictionary PhysicsDirectSpaceState2D::_intersect_ray(const Ref<PhysicsRayQueryPa
return d;
}
-Array PhysicsDirectSpaceState2D::_intersect_point(const Ref<PhysicsPointQueryParameters2D> &p_point_query, int p_max_results) {
+TypedArray<Dictionary> PhysicsDirectSpaceState2D::_intersect_point(const Ref<PhysicsPointQueryParameters2D> &p_point_query, int p_max_results) {
ERR_FAIL_COND_V(p_point_query.is_null(), Array());
Vector<ShapeResult> ret;
@@ -356,10 +357,10 @@ Array PhysicsDirectSpaceState2D::_intersect_point(const Ref<PhysicsPointQueryPar
int rc = intersect_point(p_point_query->get_parameters(), ret.ptrw(), ret.size());
if (rc == 0) {
- return Array();
+ return TypedArray<Dictionary>();
}
- Array r;
+ TypedArray<Dictionary> r;
r.resize(rc);
for (int i = 0; i < rc; i++) {
Dictionary d;
@@ -372,13 +373,13 @@ Array PhysicsDirectSpaceState2D::_intersect_point(const Ref<PhysicsPointQueryPar
return r;
}
-Array PhysicsDirectSpaceState2D::_intersect_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results) {
- ERR_FAIL_COND_V(!p_shape_query.is_valid(), Array());
+TypedArray<Dictionary> PhysicsDirectSpaceState2D::_intersect_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results) {
+ ERR_FAIL_COND_V(!p_shape_query.is_valid(), TypedArray<Dictionary>());
Vector<ShapeResult> sr;
sr.resize(p_max_results);
int rc = intersect_shape(p_shape_query->get_parameters(), sr.ptrw(), sr.size());
- Array ret;
+ TypedArray<Dictionary> ret;
ret.resize(rc);
for (int i = 0; i < rc; i++) {
Dictionary d;
@@ -392,22 +393,22 @@ Array PhysicsDirectSpaceState2D::_intersect_shape(const Ref<PhysicsShapeQueryPar
return ret;
}
-Array PhysicsDirectSpaceState2D::_cast_motion(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query) {
- ERR_FAIL_COND_V(!p_shape_query.is_valid(), Array());
+Vector<real_t> PhysicsDirectSpaceState2D::_cast_motion(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query) {
+ ERR_FAIL_COND_V(!p_shape_query.is_valid(), Vector<real_t>());
real_t closest_safe, closest_unsafe;
bool res = cast_motion(p_shape_query->get_parameters(), closest_safe, closest_unsafe);
if (!res) {
- return Array();
+ return Vector<real_t>();
}
- Array ret;
+ Vector<real_t> ret;
ret.resize(2);
- ret[0] = closest_safe;
- ret[1] = closest_unsafe;
+ ret.write[0] = closest_safe;
+ ret.write[1] = closest_unsafe;
return ret;
}
-Array PhysicsDirectSpaceState2D::_collide_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results) {
+TypedArray<PackedVector2Array> PhysicsDirectSpaceState2D::_collide_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results) {
ERR_FAIL_COND_V(!p_shape_query.is_valid(), Array());
Vector<Vector2> ret;
@@ -415,9 +416,9 @@ Array PhysicsDirectSpaceState2D::_collide_shape(const Ref<PhysicsShapeQueryParam
int rc = 0;
bool res = collide_shape(p_shape_query->get_parameters(), ret.ptrw(), p_max_results, rc);
if (!res) {
- return Array();
+ return TypedArray<PackedVector2Array>();
}
- Array r;
+ TypedArray<PackedVector2Array> r;
r.resize(rc * 2);
for (int i = 0; i < rc * 2; i++) {
r[i] = ret[i];
@@ -706,6 +707,9 @@ void PhysicsServer2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("body_set_collision_mask", "body", "mask"), &PhysicsServer2D::body_set_collision_mask);
ClassDB::bind_method(D_METHOD("body_get_collision_mask", "body"), &PhysicsServer2D::body_get_collision_mask);
+ ClassDB::bind_method(D_METHOD("body_set_collision_priority", "body", "priority"), &PhysicsServer2D::body_set_collision_priority);
+ ClassDB::bind_method(D_METHOD("body_get_collision_priority", "body"), &PhysicsServer2D::body_get_collision_priority);
+
ClassDB::bind_method(D_METHOD("body_set_param", "body", "param", "value"), &PhysicsServer2D::body_set_param);
ClassDB::bind_method(D_METHOD("body_get_param", "body", "param"), &PhysicsServer2D::body_get_param);
diff --git a/servers/physics_server_2d.h b/servers/physics_server_2d.h
index 6d95c591c2..d0c5a7189b 100644
--- a/servers/physics_server_2d.h
+++ b/servers/physics_server_2d.h
@@ -36,6 +36,8 @@
#include "core/object/ref_counted.h"
class PhysicsDirectSpaceState2D;
+template <typename T>
+class TypedArray;
class PhysicsDirectBodyState2D : public Object {
GDCLASS(PhysicsDirectBodyState2D, Object);
@@ -114,10 +116,10 @@ class PhysicsDirectSpaceState2D : public Object {
GDCLASS(PhysicsDirectSpaceState2D, Object);
Dictionary _intersect_ray(const Ref<PhysicsRayQueryParameters2D> &p_ray_query);
- Array _intersect_point(const Ref<PhysicsPointQueryParameters2D> &p_point_query, int p_max_results = 32);
- Array _intersect_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results = 32);
- Array _cast_motion(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query);
- Array _collide_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results = 32);
+ TypedArray<Dictionary> _intersect_point(const Ref<PhysicsPointQueryParameters2D> &p_point_query, int p_max_results = 32);
+ TypedArray<Dictionary> _intersect_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results = 32);
+ Vector<real_t> _cast_motion(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query);
+ TypedArray<PackedVector2Array> _collide_shape(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query, int p_max_results = 32);
Dictionary _get_rest_info(const Ref<PhysicsShapeQueryParameters2D> &p_shape_query);
protected:
@@ -393,6 +395,9 @@ public:
virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) = 0;
virtual uint32_t body_get_collision_mask(RID p_body) const = 0;
+ virtual void body_set_collision_priority(RID p_body, real_t p_priority) = 0;
+ virtual real_t body_get_collision_priority(RID p_body) const = 0;
+
// common body variables
enum BodyParameter {
BODY_PARAM_BOUNCE,
diff --git a/servers/physics_server_2d_wrap_mt.h b/servers/physics_server_2d_wrap_mt.h
index ddb071f603..d080aac438 100644
--- a/servers/physics_server_2d_wrap_mt.h
+++ b/servers/physics_server_2d_wrap_mt.h
@@ -205,6 +205,9 @@ public:
FUNC2(body_set_collision_mask, RID, uint32_t);
FUNC1RC(uint32_t, body_get_collision_mask, RID);
+ FUNC2(body_set_collision_priority, RID, real_t);
+ FUNC1RC(real_t, body_get_collision_priority, RID);
+
FUNC3(body_set_param, RID, BodyParameter, const Variant &);
FUNC2RC(Variant, body_get_param, RID, BodyParameter);
diff --git a/servers/physics_server_3d.cpp b/servers/physics_server_3d.cpp
index f25db22e66..6dd5be9ea8 100644
--- a/servers/physics_server_3d.cpp
+++ b/servers/physics_server_3d.cpp
@@ -32,6 +32,7 @@
#include "core/config/project_settings.h"
#include "core/string/print_string.h"
+#include "core/variant/typed_array.h"
void PhysicsServer3DRenderingServerHandler::set_vertex(int p_vertex_id, const void *p_vector3) {
GDVIRTUAL_REQUIRED_CALL(_set_vertex, p_vertex_id, p_vector3);
@@ -366,8 +367,8 @@ Dictionary PhysicsDirectSpaceState3D::_intersect_ray(const Ref<PhysicsRayQueryPa
return d;
}
-Array PhysicsDirectSpaceState3D::_intersect_point(const Ref<PhysicsPointQueryParameters3D> &p_point_query, int p_max_results) {
- ERR_FAIL_COND_V(p_point_query.is_null(), Array());
+TypedArray<Dictionary> PhysicsDirectSpaceState3D::_intersect_point(const Ref<PhysicsPointQueryParameters3D> &p_point_query, int p_max_results) {
+ ERR_FAIL_COND_V(p_point_query.is_null(), TypedArray<Dictionary>());
Vector<ShapeResult> ret;
ret.resize(p_max_results);
@@ -375,10 +376,10 @@ Array PhysicsDirectSpaceState3D::_intersect_point(const Ref<PhysicsPointQueryPar
int rc = intersect_point(p_point_query->get_parameters(), ret.ptrw(), ret.size());
if (rc == 0) {
- return Array();
+ return TypedArray<Dictionary>();
}
- Array r;
+ TypedArray<Dictionary> r;
r.resize(rc);
for (int i = 0; i < rc; i++) {
Dictionary d;
@@ -391,13 +392,13 @@ Array PhysicsDirectSpaceState3D::_intersect_point(const Ref<PhysicsPointQueryPar
return r;
}
-Array PhysicsDirectSpaceState3D::_intersect_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results) {
- ERR_FAIL_COND_V(!p_shape_query.is_valid(), Array());
+TypedArray<Dictionary> PhysicsDirectSpaceState3D::_intersect_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results) {
+ ERR_FAIL_COND_V(!p_shape_query.is_valid(), TypedArray<Dictionary>());
Vector<ShapeResult> sr;
sr.resize(p_max_results);
int rc = intersect_shape(p_shape_query->get_parameters(), sr.ptrw(), sr.size());
- Array ret;
+ TypedArray<Dictionary> ret;
ret.resize(rc);
for (int i = 0; i < rc; i++) {
Dictionary d;
@@ -411,22 +412,22 @@ Array PhysicsDirectSpaceState3D::_intersect_shape(const Ref<PhysicsShapeQueryPar
return ret;
}
-Array PhysicsDirectSpaceState3D::_cast_motion(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query) {
- ERR_FAIL_COND_V(!p_shape_query.is_valid(), Array());
+Vector<real_t> PhysicsDirectSpaceState3D::_cast_motion(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query) {
+ ERR_FAIL_COND_V(!p_shape_query.is_valid(), Vector<real_t>());
real_t closest_safe = 1.0f, closest_unsafe = 1.0f;
bool res = cast_motion(p_shape_query->get_parameters(), closest_safe, closest_unsafe);
if (!res) {
- return Array();
+ return Vector<real_t>();
}
- Array ret;
+ Vector<real_t> ret;
ret.resize(2);
- ret[0] = closest_safe;
- ret[1] = closest_unsafe;
+ ret.write[0] = closest_safe;
+ ret.write[1] = closest_unsafe;
return ret;
}
-Array PhysicsDirectSpaceState3D::_collide_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results) {
+TypedArray<PackedVector2Array> PhysicsDirectSpaceState3D::_collide_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results) {
ERR_FAIL_COND_V(!p_shape_query.is_valid(), Array());
Vector<Vector3> ret;
@@ -434,9 +435,9 @@ Array PhysicsDirectSpaceState3D::_collide_shape(const Ref<PhysicsShapeQueryParam
int rc = 0;
bool res = collide_shape(p_shape_query->get_parameters(), ret.ptrw(), p_max_results, rc);
if (!res) {
- return Array();
+ return TypedArray<PackedVector2Array>();
}
- Array r;
+ TypedArray<PackedVector2Array> r;
r.resize(rc * 2);
for (int i = 0; i < rc * 2; i++) {
r[i] = ret[i];
@@ -750,6 +751,9 @@ void PhysicsServer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("body_set_collision_mask", "body", "mask"), &PhysicsServer3D::body_set_collision_mask);
ClassDB::bind_method(D_METHOD("body_get_collision_mask", "body"), &PhysicsServer3D::body_get_collision_mask);
+ ClassDB::bind_method(D_METHOD("body_set_collision_priority", "body", "priority"), &PhysicsServer3D::body_set_collision_priority);
+ ClassDB::bind_method(D_METHOD("body_get_collision_priority", "body"), &PhysicsServer3D::body_get_collision_priority);
+
ClassDB::bind_method(D_METHOD("body_add_shape", "body", "shape", "transform", "disabled"), &PhysicsServer3D::body_add_shape, DEFVAL(Transform3D()), DEFVAL(false));
ClassDB::bind_method(D_METHOD("body_set_shape", "body", "shape_idx", "shape"), &PhysicsServer3D::body_set_shape);
ClassDB::bind_method(D_METHOD("body_set_shape_transform", "body", "shape_idx", "transform"), &PhysicsServer3D::body_set_shape_transform);
diff --git a/servers/physics_server_3d.h b/servers/physics_server_3d.h
index 12497c0bdf..d5c4d9713b 100644
--- a/servers/physics_server_3d.h
+++ b/servers/physics_server_3d.h
@@ -38,6 +38,8 @@
#include "core/variant/native_ptr.h"
class PhysicsDirectSpaceState3D;
+template <typename T>
+class TypedArray;
class PhysicsDirectBodyState3D : public Object {
GDCLASS(PhysicsDirectBodyState3D, Object);
@@ -120,10 +122,10 @@ class PhysicsDirectSpaceState3D : public Object {
private:
Dictionary _intersect_ray(const Ref<PhysicsRayQueryParameters3D> &p_ray_query);
- Array _intersect_point(const Ref<PhysicsPointQueryParameters3D> &p_point_query, int p_max_results = 32);
- Array _intersect_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results = 32);
- Array _cast_motion(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query);
- Array _collide_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results = 32);
+ TypedArray<Dictionary> _intersect_point(const Ref<PhysicsPointQueryParameters3D> &p_point_query, int p_max_results = 32);
+ TypedArray<Dictionary> _intersect_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results = 32);
+ Vector<real_t> _cast_motion(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query);
+ TypedArray<PackedVector2Array> _collide_shape(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query, int p_max_results = 32);
Dictionary _get_rest_info(const Ref<PhysicsShapeQueryParameters3D> &p_shape_query);
protected:
@@ -421,6 +423,9 @@ public:
virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) = 0;
virtual uint32_t body_get_collision_mask(RID p_body) const = 0;
+ virtual void body_set_collision_priority(RID p_body, real_t p_priority) = 0;
+ virtual real_t body_get_collision_priority(RID p_body) const = 0;
+
virtual void body_set_user_flags(RID p_body, uint32_t p_flags) = 0;
virtual uint32_t body_get_user_flags(RID p_body) const = 0;
diff --git a/servers/physics_server_3d_wrap_mt.h b/servers/physics_server_3d_wrap_mt.h
index d4a4ad3132..ed4546b240 100644
--- a/servers/physics_server_3d_wrap_mt.h
+++ b/servers/physics_server_3d_wrap_mt.h
@@ -202,6 +202,9 @@ public:
FUNC2(body_set_collision_mask, RID, uint32_t);
FUNC1RC(uint32_t, body_get_collision_mask, RID);
+ FUNC2(body_set_collision_priority, RID, real_t);
+ FUNC1RC(real_t, body_get_collision_priority, RID);
+
FUNC2(body_set_user_flags, RID, uint32_t);
FUNC1RC(uint32_t, body_get_user_flags, RID);
diff --git a/servers/rendering/renderer_rd/environment/sky.cpp b/servers/rendering/renderer_rd/environment/sky.cpp
index 6433a39863..d3601274b5 100644
--- a/servers/rendering/renderer_rd/environment/sky.cpp
+++ b/servers/rendering/renderer_rd/environment/sky.cpp
@@ -114,12 +114,16 @@ void SkyRD::SkyShaderData::set_code(const String &p_code) {
for (int i = 0; i < gen_code.defines.size(); i++) {
print_line(gen_code.defines[i]);
}
+
+ HashMap<String, String>::Iterator el = gen_code.code.begin();
+ while (el) {
+ print_line("\n**code " + el->key + ":\n" + el->value);
+ ++el;
+ }
+
print_line("\n**uniforms:\n" + gen_code.uniforms);
- // print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
- // print_line("\n**vertex_code:\n" + gen_code.vertex);
- print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
- print_line("\n**fragment_code:\n" + gen_code.fragment);
- print_line("\n**light_code:\n" + gen_code.light);
+ print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
+ print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
#endif
scene_singleton->sky.sky_shader.shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines);
diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp
index 556db086b2..0911ee595f 100644
--- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp
+++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp
@@ -150,6 +150,7 @@ void SceneShaderForwardClustered::ShaderData::set_code(const String &p_code) {
depth_draw = DepthDraw(depth_drawi);
depth_test = DepthTest(depth_testi);
cull_mode = Cull(cull_modei);
+ uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;
#if 0
print_line("**compiling shader:");
@@ -158,11 +159,10 @@ void SceneShaderForwardClustered::ShaderData::set_code(const String &p_code) {
print_line(gen_code.defines[i]);
}
- RBMap<String, String>::Element *el = gen_code.code.front();
+ HashMap<String, String>::Iterator el = gen_code.code.begin();
while (el) {
- print_line("\n**code " + el->key() + ":\n" + el->value());
-
- el = el->next();
+ print_line("\n**code " + el->key + ":\n" + el->value);
+ ++el;
}
print_line("\n**uniforms:\n" + gen_code.uniforms);
@@ -396,7 +396,11 @@ void SceneShaderForwardClustered::ShaderData::get_shader_uniform_list(List<Prope
HashMap<int, StringName> order;
for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
- if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
+ if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ // Don't expose any of these.
continue;
}
diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h
index fa9ebde1b2..d6b526fa4a 100644
--- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h
+++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h
@@ -174,6 +174,7 @@ public:
bool uses_time = false;
bool writes_modelview_or_projection = false;
bool uses_world_coordinates = false;
+ bool uses_screen_texture_mipmaps = false;
Cull cull_mode = CULL_DISABLED;
uint64_t last_pass = 0;
diff --git a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp
index 01b54607bc..85c9e1db2a 100644
--- a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp
+++ b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp
@@ -158,11 +158,10 @@ void SceneShaderForwardMobile::ShaderData::set_code(const String &p_code) {
print_line(gen_code.defines[i]);
}
- RBMap<String, String>::Element * el = gen_code.code.front();
+ HashMap<String, String>::Iterator el = gen_code.code.begin();
while (el) {
- print_line("\n**code " + el->key() + ":\n" + el->value());
-
- el = el->next();
+ print_line("\n**code " + el->key + ":\n" + el->value);
+ ++el;
}
print_line("\n**uniforms:\n" + gen_code.uniforms);
@@ -353,7 +352,10 @@ void SceneShaderForwardMobile::ShaderData::get_shader_uniform_list(List<Property
HashMap<int, StringName> order;
for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
- if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
+ if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
continue;
}
diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
index c1b08ee4c9..38a2340d40 100644
--- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
@@ -1361,6 +1361,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p
Item *ci = p_item_list;
Rect2 back_buffer_rect;
bool backbuffer_copy = false;
+ bool backbuffer_gen_mipmaps = false;
Item *canvas_group_owner = nullptr;
@@ -1389,6 +1390,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p
if (!material_screen_texture_found) {
backbuffer_copy = true;
back_buffer_rect = Rect2();
+ backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
}
}
@@ -1474,9 +1476,10 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p
_render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list);
item_count = 0;
- texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, true);
+ texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, backbuffer_gen_mipmaps);
backbuffer_copy = false;
+ backbuffer_gen_mipmaps = false;
material_screen_texture_found = true; //after a backbuffer copy, screen texture makes no further copies
}
@@ -1980,6 +1983,7 @@ void RendererCanvasRenderRD::CanvasShaderData::set_code(const String &p_code) {
ubo_size = 0;
uniforms.clear();
uses_screen_texture = false;
+ uses_screen_texture_mipmaps = false;
uses_sdf = false;
uses_time = false;
@@ -1990,7 +1994,6 @@ void RendererCanvasRenderRD::CanvasShaderData::set_code(const String &p_code) {
ShaderCompiler::GeneratedCode gen_code;
int blend_mode = BLEND_MODE_MIX;
- uses_screen_texture = false;
ShaderCompiler::IdentifierActions actions;
actions.entry_point_stages["vertex"] = ShaderCompiler::STAGE_VERTEX;
@@ -2015,6 +2018,8 @@ void RendererCanvasRenderRD::CanvasShaderData::set_code(const String &p_code) {
Error err = canvas_singleton->shader.compiler.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code);
ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
+ uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;
+
if (version.is_null()) {
version = canvas_singleton->shader.canvas_shader.version_create();
}
@@ -2025,12 +2030,16 @@ void RendererCanvasRenderRD::CanvasShaderData::set_code(const String &p_code) {
for (int i = 0; i < gen_code.defines.size(); i++) {
print_line(gen_code.defines[i]);
}
+
+ HashMap<String, String>::Iterator el = gen_code.code.begin();
+ while (el) {
+ print_line("\n**code " + el->key + ":\n" + el->value);
+ ++el;
+ }
+
print_line("\n**uniforms:\n" + gen_code.uniforms);
- print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
- print_line("\n**vertex_code:\n" + gen_code.vertex);
- print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
- print_line("\n**fragment_code:\n" + gen_code.fragment);
- print_line("\n**light_code:\n" + gen_code.light);
+ print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
+ print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
#endif
canvas_singleton->shader.canvas_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines);
ERR_FAIL_COND(!canvas_singleton->shader.canvas_shader.version_is_valid(version));
@@ -2175,7 +2184,11 @@ void RendererCanvasRenderRD::CanvasShaderData::get_shader_uniform_list(List<Prop
HashMap<int, StringName> order;
for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
- if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
+ if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ // Don't expose any of these.
continue;
}
if (E.value.texture_order >= 0) {
diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.h b/servers/rendering/renderer_rd/renderer_canvas_render_rd.h
index 5eb4cee4c6..bcbbbaa1a0 100644
--- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.h
+++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.h
@@ -174,6 +174,7 @@ class RendererCanvasRenderRD : public RendererCanvasRender {
HashMap<StringName, HashMap<int, RID>> default_texture_params;
bool uses_screen_texture = false;
+ bool uses_screen_texture_mipmaps = false;
bool uses_sdf = false;
bool uses_time = false;
diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
index 6c219933b0..d8499681ad 100644
--- a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
@@ -2868,7 +2868,9 @@ void RendererSceneRenderRD::_setup_lights(const PagedArray<RID> &p_lights, const
WARN_PRINT_ONCE("The DirectionalLight3D PSSM splits debug draw mode is not reimplemented yet.");
}
- light_data.shadow_opacity = p_using_shadows && light_storage->light_has_shadow(base) ? light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY) : 0.0;
+ light_data.shadow_opacity = (p_using_shadows && light_storage->light_has_shadow(base))
+ ? light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY)
+ : 0.0;
float angular_diameter = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
if (angular_diameter > 0.0) {
@@ -3122,7 +3124,11 @@ void RendererSceneRenderRD::_setup_lights(const PagedArray<RID> &p_lights, const
light_data.projector_rect[3] = 0;
}
- const bool needs_shadow = shadow_atlas && shadow_atlas->shadow_owners.has(li->self);
+ const bool needs_shadow =
+ shadow_atlas &&
+ shadow_atlas->shadow_owners.has(li->self) &&
+ p_using_shadows &&
+ light_storage->light_has_shadow(base);
bool in_shadow_range = true;
if (needs_shadow && light_storage->light_is_distance_fade_enabled(li->light)) {
diff --git a/servers/rendering/renderer_rd/shaders/effects/bokeh_dof.glsl b/servers/rendering/renderer_rd/shaders/effects/bokeh_dof.glsl
index 0438671dd2..0b43af7738 100644
--- a/servers/rendering/renderer_rd/shaders/effects/bokeh_dof.glsl
+++ b/servers/rendering/renderer_rd/shaders/effects/bokeh_dof.glsl
@@ -30,7 +30,7 @@ layout(set = 1, binding = 0) uniform sampler2D source_bokeh;
#ifdef MODE_GEN_BLUR_SIZE
float get_depth_at_pos(vec2 uv) {
- float depth = textureLod(source_depth, uv, 0.0).x;
+ float depth = textureLod(source_depth, uv, 0.0).x * 2.0 - 1.0;
if (params.orthogonal) {
depth = ((depth + (params.z_far + params.z_near) / (params.z_far - params.z_near)) * (params.z_far - params.z_near)) / 2.0;
} else {
diff --git a/servers/rendering/renderer_rd/shaders/effects/bokeh_dof_raster.glsl b/servers/rendering/renderer_rd/shaders/effects/bokeh_dof_raster.glsl
index a3b3938ee9..a06cacfabe 100644
--- a/servers/rendering/renderer_rd/shaders/effects/bokeh_dof_raster.glsl
+++ b/servers/rendering/renderer_rd/shaders/effects/bokeh_dof_raster.glsl
@@ -52,7 +52,7 @@ layout(set = 2, binding = 0) uniform sampler2D original_weight;
#ifdef MODE_GEN_BLUR_SIZE
float get_depth_at_pos(vec2 uv) {
- float depth = textureLod(source_depth, uv, 0.0).x;
+ float depth = textureLod(source_depth, uv, 0.0).x * 2.0 - 1.0;
if (params.orthogonal) {
depth = ((depth + (params.z_far + params.z_near) / (params.z_far - params.z_near)) * (params.z_far - params.z_near)) / 2.0;
} else {
diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl
index e9515c7670..6b4e4a5a16 100644
--- a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl
+++ b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl
@@ -15,11 +15,11 @@ layout(location = 0) in vec3 vertex_attrib;
//only for pure render depth when normal is not used
#ifdef NORMAL_USED
-layout(location = 1) in vec3 normal_attrib;
+layout(location = 1) in vec2 normal_attrib;
#endif
#if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
-layout(location = 2) in vec4 tangent_attrib;
+layout(location = 2) in vec2 tangent_attrib;
#endif
#if defined(COLOR_USED)
@@ -58,6 +58,13 @@ layout(location = 10) in uvec4 bone_attrib;
layout(location = 11) in vec4 weight_attrib;
#endif
+vec3 oct_to_vec3(vec2 e) {
+ vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));
+ float t = max(-v.z, 0.0);
+ v.xy += t * -sign(v.xy);
+ return v;
+}
+
/* Varyings */
layout(location = 0) out vec3 vertex_interp;
@@ -231,12 +238,13 @@ void vertex_shader(in uint instance_index, in bool is_multimesh, in SceneData sc
vec3 vertex = vertex_attrib;
#ifdef NORMAL_USED
- vec3 normal = normal_attrib * 2.0 - 1.0;
+ vec3 normal = oct_to_vec3(normal_attrib * 2.0 - 1.0);
#endif
#if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
- vec3 tangent = tangent_attrib.xyz * 2.0 - 1.0;
- float binormalf = tangent_attrib.a * 2.0 - 1.0;
+ vec2 signed_tangent_attrib = tangent_attrib * 2.0 - 1.0;
+ vec3 tangent = oct_to_vec3(vec2(signed_tangent_attrib.x, abs(signed_tangent_attrib.y) * 2.0 - 1.0));
+ float binormalf = sign(signed_tangent_attrib.y);
vec3 binormal = normalize(cross(normal, tangent) * binormalf);
#endif
diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl
index 6548793bee..0960533917 100644
--- a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl
+++ b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl
@@ -16,11 +16,11 @@ layout(location = 0) in vec3 vertex_attrib;
//only for pure render depth when normal is not used
#ifdef NORMAL_USED
-layout(location = 1) in vec3 normal_attrib;
+layout(location = 1) in vec2 normal_attrib;
#endif
#if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
-layout(location = 2) in vec4 tangent_attrib;
+layout(location = 2) in vec2 tangent_attrib;
#endif
#if defined(COLOR_USED)
@@ -59,6 +59,13 @@ layout(location = 10) in uvec4 bone_attrib;
layout(location = 11) in vec4 weight_attrib;
#endif
+vec3 oct_to_vec3(vec2 e) {
+ vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));
+ float t = max(-v.z, 0.0);
+ v.xy += t * -sign(v.xy);
+ return v;
+}
+
/* Varyings */
layout(location = 0) highp out vec3 vertex_interp;
@@ -229,12 +236,13 @@ void main() {
vec3 vertex = vertex_attrib;
#ifdef NORMAL_USED
- vec3 normal = normal_attrib * 2.0 - 1.0;
+ vec3 normal = oct_to_vec3(normal_attrib * 2.0 - 1.0);
#endif
#if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
- vec3 tangent = tangent_attrib.xyz * 2.0 - 1.0;
- float binormalf = tangent_attrib.a * 2.0 - 1.0;
+ vec3 signed_tangent_attrib = tangent_attrib * 2.0 - 1.0;
+ vec3 tangent = oct_to_vec3(vec2(signed_tangent_attrib.x, abs(signed_tangent_attrib.y) * 2.0 - 1.0));
+ float binormalf = sign(signed_tangent_attrib.y);
vec3 binormal = normalize(cross(normal, tangent) * binormalf);
#endif
diff --git a/servers/rendering/renderer_rd/shaders/skeleton.glsl b/servers/rendering/renderer_rd/shaders/skeleton.glsl
index a893a66c94..75bea9300b 100644
--- a/servers/rendering/renderer_rd/shaders/skeleton.glsl
+++ b/servers/rendering/renderer_rd/shaders/skeleton.glsl
@@ -54,14 +54,54 @@ layout(push_constant, std430) uniform Params {
}
params;
-vec4 decode_abgr_2_10_10_10(uint base) {
- uvec4 abgr_2_10_10_10 = (uvec4(base) >> uvec4(0, 10, 20, 30)) & uvec4(0x3FF, 0x3FF, 0x3FF, 0x3);
- return vec4(abgr_2_10_10_10) / vec4(1023.0, 1023.0, 1023.0, 3.0) * 2.0 - 1.0;
+vec2 uint_to_vec2(uint base) {
+ uvec2 decode = (uvec2(base) >> uvec2(0, 16)) & uvec2(0xFFFF, 0xFFFF);
+ return vec2(decode) / vec2(65535.0, 65535.0) * 2.0 - 1.0;
}
-uint encode_abgr_2_10_10_10(vec4 base) {
- uvec4 abgr_2_10_10_10 = uvec4(clamp(ivec4((base * 0.5 + 0.5) * vec4(1023.0, 1023.0, 1023.0, 3.0)), ivec4(0), ivec4(0x3FF, 0x3FF, 0x3FF, 0x3))) << uvec4(0, 10, 20, 30);
- return abgr_2_10_10_10.x | abgr_2_10_10_10.y | abgr_2_10_10_10.z | abgr_2_10_10_10.w;
+vec3 oct_to_vec3(vec2 oct) {
+ vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));
+ float t = max(-v.z, 0.0);
+ v.xy += t * -sign(v.xy);
+ return v;
+}
+
+vec3 decode_uint_oct_to_norm(uint base) {
+ return oct_to_vec3(uint_to_vec2(base));
+}
+
+vec4 decode_uint_oct_to_tang(uint base) {
+ vec2 oct_sign_encoded = uint_to_vec2(base);
+ // Binormal sign encoded in y component
+ vec2 oct = vec2(oct_sign_encoded.x, abs(oct_sign_encoded.y) * 2.0 - 1.0);
+ return vec4(oct_to_vec3(oct), sign(oct_sign_encoded.y));
+}
+
+vec2 signNotZero(vec2 v) {
+ return mix(vec2(-1.0), vec2(1.0), greaterThanEqual(v.xy, vec2(0.0)));
+}
+
+uint vec2_to_uint(vec2 base) {
+ uvec2 enc = uvec2(clamp(ivec2(base * vec2(65535, 65535)), ivec2(0), ivec2(0xFFFF, 0xFFFF))) << uvec2(0, 16);
+ return enc.x | enc.y;
+}
+
+vec2 vec3_to_oct(vec3 e) {
+ e /= abs(e.x) + abs(e.y) + abs(e.z);
+ vec2 oct = e.z >= 0.0f ? e.xy : (vec2(1.0f) - abs(e.yx)) * signNotZero(e.xy);
+ return oct * 0.5f + 0.5f;
+}
+
+uint encode_norm_to_uint_oct(vec3 base) {
+ return vec2_to_uint(vec3_to_oct(base));
+}
+
+uint encode_tang_to_uint_oct(vec4 base) {
+ vec2 oct = vec3_to_oct(base.xyz);
+ // Encode binormal sign in y component
+ oct.y = oct.y * 0.5f + 0.5f;
+ oct.y = base.w >= 0.0f ? oct.y : 1 - oct.y;
+ return vec2_to_uint(oct);
}
void main() {
@@ -131,12 +171,12 @@ void main() {
src_offset += 3;
if (params.has_normal) {
- normal = decode_abgr_2_10_10_10(src_vertices.data[src_offset]).rgb;
+ normal = decode_uint_oct_to_norm(src_vertices.data[src_offset]);
src_offset++;
}
if (params.has_tangent) {
- tangent = decode_abgr_2_10_10_10(src_vertices.data[src_offset]);
+ tangent = decode_uint_oct_to_tang(src_vertices.data[src_offset]);
}
if (params.has_blend_shape) {
@@ -155,12 +195,12 @@ void main() {
base_offset += 3;
if (params.has_normal) {
- blend_normal += decode_abgr_2_10_10_10(src_blend_shapes.data[base_offset]).rgb * w;
+ blend_normal += decode_uint_oct_to_norm(src_blend_shapes.data[base_offset]) * w;
base_offset++;
}
if (params.has_tangent) {
- blend_tangent += decode_abgr_2_10_10_10(src_blend_shapes.data[base_offset]).rgb * w;
+ blend_tangent += decode_uint_oct_to_tang(src_blend_shapes.data[base_offset]).rgb * w;
}
blend_total += w;
@@ -234,12 +274,12 @@ void main() {
dst_offset += 3;
if (params.has_normal) {
- dst_vertices.data[dst_offset] = encode_abgr_2_10_10_10(vec4(normal, 0.0));
+ dst_vertices.data[dst_offset] = encode_norm_to_uint_oct(normal);
dst_offset++;
}
if (params.has_tangent) {
- dst_vertices.data[dst_offset] = encode_abgr_2_10_10_10(tangent);
+ dst_vertices.data[dst_offset] = encode_tang_to_uint_oct(tangent);
}
#endif
diff --git a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
index 41dd1ccc40..fa8406e7a1 100644
--- a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
@@ -941,6 +941,12 @@ void MaterialStorage::MaterialData::update_uniform_buffer(const HashMap<StringNa
continue; //instance uniforms don't appear in the buffer
}
+ if (E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ continue;
+ }
+
if (E.value.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) {
//this is a global variable, get the index to it
GlobalShaderUniforms::Variable *gv = material_storage->global_shader_uniforms.variables.getptr(E.key);
@@ -1052,6 +1058,12 @@ void MaterialStorage::MaterialData::update_textures(const HashMap<StringName, Va
Vector<RID> textures;
+ if (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ continue;
+ }
+
if (p_texture_uniforms[i].global) {
uses_global_textures = true;
@@ -1307,7 +1319,7 @@ bool MaterialStorage::MaterialData::update_parameters_uniform_set(const HashMap<
update_textures(p_parameters, p_default_texture_params, p_texture_uniforms, texture_cache.ptrw(), true);
}
- if (p_ubo_size == 0 && p_texture_uniforms.size() == 0) {
+ if (p_ubo_size == 0 && (p_texture_uniforms.size() == 0)) {
// This material does not require an uniform set, so don't create it.
return false;
}
diff --git a/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp b/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp
index 08cfeb2019..49d7198ec2 100644
--- a/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp
@@ -327,8 +327,10 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
bool use_as_storage = (p_surface.skin_data.size() || mesh->blend_shape_count > 0);
- s->vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.vertex_data.size(), p_surface.vertex_data, use_as_storage);
- s->vertex_buffer_size = p_surface.vertex_data.size();
+ if (p_surface.vertex_data.size()) {
+ s->vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.vertex_data.size(), p_surface.vertex_data, use_as_storage);
+ s->vertex_buffer_size = p_surface.vertex_data.size();
+ }
if (p_surface.attribute_data.size()) {
s->attribute_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.attribute_data.size(), p_surface.attribute_data);
@@ -345,7 +347,7 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
}
if (p_surface.index_count) {
- bool is_index_16 = p_surface.vertex_count <= 65536;
+ bool is_index_16 = p_surface.vertex_count <= 65536 && p_surface.vertex_count > 0;
s->index_buffer = RD::get_singleton()->index_buffer_create(p_surface.index_count, is_index_16 ? RD::INDEX_BUFFER_FORMAT_UINT16 : RD::INDEX_BUFFER_FORMAT_UINT32, p_surface.index_data, false);
s->index_count = p_surface.index_count;
@@ -364,6 +366,8 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
}
}
+ ERR_FAIL_COND_MSG(!p_surface.index_count && !p_surface.vertex_count, "Meshes must contain a vertex array, an index array, or both");
+
s->aabb = p_surface.aabb;
s->bone_aabbs = p_surface.bone_aabbs; //only really useful for returning them.
@@ -377,7 +381,11 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
RD::Uniform u;
u.binding = 0;
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
- u.append_id(s->vertex_buffer);
+ if (s->vertex_buffer.is_valid()) {
+ u.append_id(s->vertex_buffer);
+ } else {
+ u.append_id(default_rd_storage_buffer);
+ }
uniforms.push_back(u);
}
{
@@ -416,9 +424,9 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
mesh->bone_aabbs.resize(p_surface.bone_aabbs.size());
}
for (int i = 0; i < p_surface.bone_aabbs.size(); i++) {
- AABB bone = p_surface.bone_aabbs[i];
+ const AABB &bone = p_surface.bone_aabbs[i];
if (!bone.has_no_volume()) {
- mesh->bone_aabbs.write[i].merge_with(p_surface.bone_aabbs[i]);
+ mesh->bone_aabbs.write[i].merge_with(bone);
}
}
mesh->aabb.merge_with(p_surface.aabb);
@@ -470,6 +478,7 @@ void MeshStorage::mesh_surface_update_vertex_region(RID p_mesh, int p_surface, i
ERR_FAIL_COND(!mesh);
ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count);
ERR_FAIL_COND(p_data.size() == 0);
+ ERR_FAIL_COND(mesh->surfaces[p_surface]->vertex_buffer.is_null());
uint64_t data_size = p_data.size();
const uint8_t *r = p_data.ptr();
@@ -527,7 +536,9 @@ RS::SurfaceData MeshStorage::mesh_get_surface(RID p_mesh, int p_surface) const {
RS::SurfaceData sd;
sd.format = s.format;
- sd.vertex_data = RD::get_singleton()->buffer_get_data(s.vertex_buffer);
+ if (s.vertex_buffer.is_valid()) {
+ sd.vertex_data = RD::get_singleton()->buffer_get_data(s.vertex_buffer);
+ }
if (s.attribute_buffer.is_valid()) {
sd.attribute_data = RD::get_singleton()->buffer_get_data(s.attribute_buffer);
}
@@ -705,7 +716,9 @@ void MeshStorage::mesh_clear(RID p_mesh) {
ERR_FAIL_COND(!mesh);
for (uint32_t i = 0; i < mesh->surface_count; i++) {
Mesh::Surface &s = *mesh->surfaces[i];
- RD::get_singleton()->free(s.vertex_buffer); //clears arrays as dependency automatically, including all versions
+ if (s.vertex_buffer.is_valid()) {
+ RD::get_singleton()->free(s.vertex_buffer); //clears arrays as dependency automatically, including all versions
+ }
if (s.attribute_buffer.is_valid()) {
RD::get_singleton()->free(s.attribute_buffer);
}
@@ -851,7 +864,7 @@ void MeshStorage::_mesh_instance_add_surface(MeshInstance *mi, Mesh *mesh, uint3
}
MeshInstance::Surface s;
- if (mesh->blend_shape_count > 0 || (mesh->surfaces[p_surface]->format & RS::ARRAY_FORMAT_BONES)) {
+ if ((mesh->blend_shape_count > 0 || (mesh->surfaces[p_surface]->format & RS::ARRAY_FORMAT_BONES)) && mesh->surfaces[p_surface]->vertex_buffer_size > 0) {
//surface warrants transform
s.vertex_buffer = RD::get_singleton()->vertex_buffer_create(mesh->surfaces[p_surface]->vertex_buffer_size, Vector<uint8_t>(), true);
@@ -1060,10 +1073,9 @@ void MeshStorage::_mesh_surface_generate_version_for_input_mask(Mesh::Surface::V
} break;
case RS::ARRAY_NORMAL: {
vd.offset = stride;
+ vd.format = RD::DATA_FORMAT_R16G16_UNORM;
+ stride += sizeof(uint16_t) * 2;
- vd.format = RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32;
-
- stride += sizeof(uint32_t);
if (mis) {
buffer = mis->vertex_buffer;
} else {
@@ -1072,9 +1084,9 @@ void MeshStorage::_mesh_surface_generate_version_for_input_mask(Mesh::Surface::V
} break;
case RS::ARRAY_TANGENT: {
vd.offset = stride;
+ vd.format = RD::DATA_FORMAT_R16G16_UNORM;
+ stride += sizeof(uint16_t) * 2;
- vd.format = RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32;
- stride += sizeof(uint32_t);
if (mis) {
buffer = mis->vertex_buffer;
} else {
diff --git a/servers/rendering/renderer_scene_cull.cpp b/servers/rendering/renderer_scene_cull.cpp
index 0b20bb372a..9f5eb85c2f 100644
--- a/servers/rendering/renderer_scene_cull.cpp
+++ b/servers/rendering/renderer_scene_cull.cpp
@@ -506,7 +506,7 @@ void RendererSceneCull::instance_set_base(RID p_instance, RID p_base) {
}
if (instance->mesh_instance.is_valid()) {
- RSG::mesh_storage->mesh_free(instance->mesh_instance);
+ RSG::mesh_storage->mesh_instance_free(instance->mesh_instance);
instance->mesh_instance = RID();
// no need to set instance data flag here, as it was freed above
}
diff --git a/servers/rendering/renderer_viewport.cpp b/servers/rendering/renderer_viewport.cpp
index 73b03966c5..bfb81925bc 100644
--- a/servers/rendering/renderer_viewport.cpp
+++ b/servers/rendering/renderer_viewport.cpp
@@ -72,6 +72,41 @@ static Transform2D _canvas_get_transform(RendererViewport::Viewport *p_viewport,
return xf;
}
+Vector<RendererViewport::Viewport *> RendererViewport::_sort_active_viewports() {
+ // We need to sort the viewports in a "topological order",
+ // children first and parents last, we use the Kahn's algorithm to achieve that.
+
+ Vector<Viewport *> result;
+ List<Viewport *> nodes;
+
+ for (Viewport *viewport : active_viewports) {
+ if (viewport->parent.is_valid()) {
+ continue;
+ }
+
+ nodes.push_back(viewport);
+ }
+
+ while (!nodes.is_empty()) {
+ Viewport *node = nodes[0];
+ nodes.pop_front();
+
+ result.insert(0, node);
+
+ for (Viewport *child : active_viewports) {
+ if (child->parent != node->self) {
+ continue;
+ }
+
+ if (!nodes.find(child)) {
+ nodes.push_back(child);
+ }
+ }
+ }
+
+ return result;
+}
+
void RendererViewport::_configure_3d_render_buffers(Viewport *p_viewport) {
if (p_viewport->render_buffers.is_valid()) {
if (p_viewport->size.width == 0 || p_viewport->size.height == 0) {
@@ -548,8 +583,10 @@ void RendererViewport::draw_viewports() {
set_default_clear_color(GLOBAL_GET("rendering/environment/defaults/default_clear_color"));
}
- //sort viewports
- active_viewports.sort_custom<ViewportSort>();
+ if (sorted_active_viewports_dirty) {
+ sorted_active_viewports = _sort_active_viewports();
+ sorted_active_viewports_dirty = false;
+ }
HashMap<DisplayServer::WindowID, Vector<BlitToScreen>> blit_to_screen_list;
//draw viewports
@@ -558,9 +595,9 @@ void RendererViewport::draw_viewports() {
//determine what is visible
draw_viewports_pass++;
- for (int i = active_viewports.size() - 1; i >= 0; i--) { //to compute parent dependency, must go in reverse draw order
+ for (int i = sorted_active_viewports.size() - 1; i >= 0; i--) { //to compute parent dependency, must go in reverse draw order
- Viewport *vp = active_viewports[i];
+ Viewport *vp = sorted_active_viewports[i];
if (vp->update_mode == RS::VIEWPORT_UPDATE_DISABLED) {
continue;
@@ -621,8 +658,8 @@ void RendererViewport::draw_viewports() {
int objects_drawn = 0;
int draw_calls_used = 0;
- for (int i = 0; i < active_viewports.size(); i++) {
- Viewport *vp = active_viewports[i];
+ for (int i = 0; i < sorted_active_viewports.size(); i++) {
+ Viewport *vp = sorted_active_viewports[i];
if (vp->last_pass != draw_viewports_pass) {
continue; //should not draw
@@ -814,6 +851,8 @@ void RendererViewport::viewport_set_active(RID p_viewport, bool p_active) {
} else {
active_viewports.erase(viewport);
}
+
+ sorted_active_viewports_dirty = true;
}
void RendererViewport::viewport_set_parent_viewport(RID p_viewport, RID p_parent_viewport) {
@@ -1243,6 +1282,7 @@ bool RendererViewport::free(RID p_rid) {
viewport_set_scenario(p_rid, RID());
active_viewports.erase(viewport);
+ sorted_active_viewports_dirty = true;
if (viewport->use_occlusion_culling) {
RendererSceneOcclusionCull::get_singleton()->remove_buffer(p_rid);
diff --git a/servers/rendering/renderer_viewport.h b/servers/rendering/renderer_viewport.h
index 5e37c96336..ab4893a908 100644
--- a/servers/rendering/renderer_viewport.h
+++ b/servers/rendering/renderer_viewport.h
@@ -185,25 +185,16 @@ public:
mutable RID_Owner<Viewport, true> viewport_owner;
- struct ViewportSort {
- _FORCE_INLINE_ bool operator()(const Viewport *p_left, const Viewport *p_right) const {
- bool left_to_screen = p_left->viewport_to_screen_rect.size != Size2();
- bool right_to_screen = p_right->viewport_to_screen_rect.size != Size2();
-
- if (left_to_screen == right_to_screen) {
- return p_right->parent == p_left->self;
- }
- return (right_to_screen ? 0 : 1) < (left_to_screen ? 0 : 1);
- }
- };
-
Vector<Viewport *> active_viewports;
+ Vector<Viewport *> sorted_active_viewports;
+ bool sorted_active_viewports_dirty = false;
int total_objects_drawn = 0;
int total_vertices_drawn = 0;
int total_draw_calls_used = 0;
private:
+ Vector<Viewport *> _sort_active_viewports();
void _configure_3d_render_buffers(Viewport *p_viewport);
void _draw_3d(Viewport *p_viewport);
void _draw_viewport(Viewport *p_viewport);
diff --git a/servers/rendering/rendering_device_binds.h b/servers/rendering/rendering_device_binds.h
index 8bdd3deea1..a56b7eb241 100644
--- a/servers/rendering/rendering_device_binds.h
+++ b/servers/rendering/rendering_device_binds.h
@@ -443,8 +443,8 @@ public:
void add_id(const RID &p_id) { base.append_id(p_id); }
void clear_ids() { base.clear_ids(); }
- Array get_ids() const {
- Array ids;
+ TypedArray<RID> get_ids() const {
+ TypedArray<RID> ids;
for (uint32_t i = 0; i < base.get_id_count(); i++) {
ids.push_back(base.get_id(i));
}
@@ -452,7 +452,7 @@ public:
}
protected:
- void _set_ids(const Array &p_ids) {
+ void _set_ids(const TypedArray<RID> &p_ids) {
base.clear_ids();
for (int i = 0; i < p_ids.size(); i++) {
RID id = p_ids[i];
diff --git a/servers/rendering/shader_compiler.cpp b/servers/rendering/shader_compiler.cpp
index c2cf08812c..f14350305a 100644
--- a/servers/rendering/shader_compiler.cpp
+++ b/servers/rendering/shader_compiler.cpp
@@ -498,6 +498,11 @@ String ShaderCompiler::_dump_node_code(const SL::Node *p_node, int p_level, Gene
for (const KeyValue<StringName, SL::ShaderNode::Uniform> &E : pnode->uniforms) {
if (SL::is_sampler_type(E.value.type)) {
+ if (E.value.hint == SL::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ E.value.hint == SL::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ E.value.hint == SL::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ continue; // Don't create uniforms in the generated code for these.
+ }
max_texture_uniforms++;
} else {
if (E.value.scope == SL::ShaderNode::Uniform::SCOPE_INSTANCE) {
@@ -537,6 +542,13 @@ String ShaderCompiler::_dump_node_code(const SL::Node *p_node, int p_level, Gene
p_actions.uniforms->insert(uniform_name, uniform);
continue; // Instances are indexed directly, don't need index uniforms.
}
+
+ if (uniform.hint == SL::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
+ uniform.hint == SL::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
+ uniform.hint == SL::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ continue; // Don't create uniforms in the generated code for these.
+ }
+
if (SL::is_sampler_type(uniform.type)) {
// Texture layouts are different for OpenGL GLSL and Vulkan GLSL
if (!RS::get_singleton()->is_low_end()) {
@@ -892,12 +904,39 @@ String ShaderCompiler::_dump_node_code(const SL::Node *p_node, int p_level, Gene
if (p_default_actions.renames.has(vnode->name)) {
code = p_default_actions.renames[vnode->name];
+ if (vnode->name == "SCREEN_TEXTURE") {
+ r_gen_code.uses_screen_texture_mipmaps = true;
+ }
} else {
if (shader->uniforms.has(vnode->name)) {
//its a uniform!
const ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[vnode->name];
if (u.texture_order >= 0) {
- code = _mkid(vnode->name); //texture, use as is
+ StringName name = vnode->name;
+ if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE) {
+ name = "SCREEN_TEXTURE";
+ if (u.filter >= ShaderLanguage::FILTER_NEAREST_MIPMAP) {
+ r_gen_code.uses_screen_texture_mipmaps = true;
+ }
+ } else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE) {
+ name = "NORMAL_ROUGHNESS_TEXTURE";
+ } else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
+ name = "DEPTH_TEXTURE";
+ } else {
+ name = _mkid(vnode->name); //texture, use as is
+ }
+
+ if (p_default_actions.renames.has(name)) {
+ code = p_default_actions.renames[name];
+ } else {
+ code = name;
+ }
+
+ if (p_actions.usage_flag_pointers.has(name) && !used_flag_pointers.has(name)) {
+ *p_actions.usage_flag_pointers[name] = true;
+ used_flag_pointers.insert(name);
+ }
+
} else {
//a scalar or vector
if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) {
@@ -1155,6 +1194,7 @@ String ShaderCompiler::_dump_node_code(const SL::Node *p_node, int p_level, Gene
}
if (correct_texture_uniform) {
+ //TODO Needs to detect screen_texture hint as well
is_screen_texture = (texture_uniform == "SCREEN_TEXTURE");
String sampler_name;
@@ -1404,6 +1444,7 @@ Error ShaderCompiler::compile(RS::ShaderMode p_mode, const String &p_code, Ident
r_gen_code.uses_fragment_time = false;
r_gen_code.uses_vertex_time = false;
r_gen_code.uses_global_textures = false;
+ r_gen_code.uses_screen_texture_mipmaps = false;
used_name_defines.clear();
used_rmode_defines.clear();
diff --git a/servers/rendering/shader_compiler.h b/servers/rendering/shader_compiler.h
index 06f42e9f0f..1ad43daf5f 100644
--- a/servers/rendering/shader_compiler.h
+++ b/servers/rendering/shader_compiler.h
@@ -80,6 +80,7 @@ public:
bool uses_global_textures;
bool uses_fragment_time;
bool uses_vertex_time;
+ bool uses_screen_texture_mipmaps;
};
struct DefaultIdentifierActions {
diff --git a/servers/rendering/shader_language.cpp b/servers/rendering/shader_language.cpp
index 81e4d5e217..2bbc5e4dfb 100644
--- a/servers/rendering/shader_language.cpp
+++ b/servers/rendering/shader_language.cpp
@@ -200,6 +200,9 @@ const char *ShaderLanguage::token_names[TK_MAX] = {
"HINT_ANISOTROPY_TEXTURE",
"HINT_RANGE",
"HINT_INSTANCE_INDEX",
+ "HINT_SCREEN_TEXTURE",
+ "HINT_NORMAL_ROUGHNESS_TEXTURE",
+ "HINT_DEPTH_TEXTURE",
"FILTER_NEAREST",
"FILTER_LINEAR",
"FILTER_NEAREST_MIPMAP",
@@ -363,6 +366,10 @@ const ShaderLanguage::KeyWord ShaderLanguage::keyword_list[] = {
{ TK_HINT_ROUGHNESS_A, "hint_roughness_a", CF_UNSPECIFIED, {}, {} },
{ TK_HINT_ROUGHNESS_NORMAL_TEXTURE, "hint_roughness_normal", CF_UNSPECIFIED, {}, {} },
{ TK_HINT_ROUGHNESS_GRAY, "hint_roughness_gray", CF_UNSPECIFIED, {}, {} },
+ { TK_HINT_SCREEN_TEXTURE, "hint_screen_texture", CF_UNSPECIFIED, {}, {} },
+ { TK_HINT_NORMAL_ROUGHNESS_TEXTURE, "hint_normal_roughness_texture", CF_UNSPECIFIED, {}, {} },
+ { TK_HINT_DEPTH_TEXTURE, "hint_depth_texture", CF_UNSPECIFIED, {}, {} },
+
{ TK_FILTER_NEAREST, "filter_nearest", CF_UNSPECIFIED, {}, {} },
{ TK_FILTER_LINEAR, "filter_linear", CF_UNSPECIFIED, {}, {} },
{ TK_FILTER_NEAREST_MIPMAP, "filter_nearest_mipmap", CF_UNSPECIFIED, {}, {} },
@@ -1096,6 +1103,15 @@ String ShaderLanguage::get_uniform_hint_name(ShaderNode::Uniform::Hint p_hint) {
case ShaderNode::Uniform::HINT_ANISOTROPY: {
result = "hint_anisotropy";
} break;
+ case ShaderNode::Uniform::HINT_SCREEN_TEXTURE: {
+ result = "hint_screen_texture";
+ } break;
+ case ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE: {
+ result = "hint_normal_roughness_texture";
+ } break;
+ case ShaderNode::Uniform::HINT_DEPTH_TEXTURE: {
+ result = "hint_depth_texture";
+ } break;
default:
break;
}
@@ -5361,6 +5377,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons
}
_set_tkpos(prev_pos);
+ ShaderNode::Varying &var = shader->varyings[identifier];
String error;
if (is_token_operator_assign(next_token.type)) {
if (!_validate_varying_assign(shader->varyings[identifier], &error)) {
@@ -5368,8 +5385,6 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons
return nullptr;
}
} else {
- ShaderNode::Varying &var = shader->varyings[identifier];
-
switch (var.stage) {
case ShaderNode::Varying::STAGE_VERTEX:
if (current_function == varying_function_names.fragment || current_function == varying_function_names.light) {
@@ -5385,6 +5400,12 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons
break;
}
}
+
+ if ((var.stage != ShaderNode::Varying::STAGE_FRAGMENT && var.stage != ShaderNode::Varying::STAGE_FRAGMENT_TO_LIGHT) && var.type < TYPE_FLOAT && var.interpolation != INTERPOLATION_FLAT) {
+ _set_tkpos(var.tkpos);
+ _set_error(RTR("Varying with integer data type must be declared with `flat` interpolation qualifier."));
+ return nullptr;
+ }
}
if (ident_type == IDENTIFIER_FUNCTION) {
@@ -8283,8 +8304,8 @@ Error ShaderLanguage::_parse_shader(const HashMap<StringName, FunctionInfo> &p_f
return ERR_PARSE_ERROR;
}
- if (!is_uniform && (type < TYPE_FLOAT || type > TYPE_MAT4)) {
- _set_error(RTR("Invalid type for varying, only 'float', 'vec2', 'vec3', 'vec4', 'mat2', 'mat3', 'mat4', or arrays of these types are allowed."));
+ if (!is_uniform && type > TYPE_MAT4) {
+ _set_error(RTR("Invalid data type for varying."));
return ERR_PARSE_ERROR;
}
@@ -8605,6 +8626,15 @@ Error ShaderLanguage::_parse_shader(const HashMap<StringName, FunctionInfo> &p_f
return ERR_PARSE_ERROR;
}
} break;
+ case TK_HINT_SCREEN_TEXTURE: {
+ new_hint = ShaderNode::Uniform::HINT_SCREEN_TEXTURE;
+ } break;
+ case TK_HINT_NORMAL_ROUGHNESS_TEXTURE: {
+ new_hint = ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE;
+ } break;
+ case TK_HINT_DEPTH_TEXTURE: {
+ new_hint = ShaderNode::Uniform::HINT_DEPTH_TEXTURE;
+ } break;
case TK_FILTER_NEAREST: {
new_filter = FILTER_NEAREST;
} break;
@@ -8629,6 +8659,7 @@ Error ShaderLanguage::_parse_shader(const HashMap<StringName, FunctionInfo> &p_f
case TK_REPEAT_ENABLE: {
new_repeat = REPEAT_ENABLE;
} break;
+
default:
break;
}
@@ -8653,9 +8684,9 @@ Error ShaderLanguage::_parse_shader(const HashMap<StringName, FunctionInfo> &p_f
if (new_filter != FILTER_DEFAULT) {
if (uniform.filter != FILTER_DEFAULT) {
if (uniform.filter == new_filter) {
- _set_error(vformat(RTR("Duplicated hint: '%s'."), get_texture_filter_name(new_filter)));
+ _set_error(vformat(RTR("Duplicated filter mode: '%s'."), get_texture_filter_name(new_filter)));
} else {
- _set_error(vformat(RTR("Redefinition of hint: '%s'. The filter mode has already been set to '%s'."), get_texture_filter_name(new_filter), get_texture_filter_name(uniform.filter)));
+ _set_error(vformat(RTR("Redefinition of filter mode: '%s'. The filter mode has already been set to '%s'."), get_texture_filter_name(new_filter), get_texture_filter_name(uniform.filter)));
}
return ERR_PARSE_ERROR;
} else {
@@ -8666,9 +8697,9 @@ Error ShaderLanguage::_parse_shader(const HashMap<StringName, FunctionInfo> &p_f
if (new_repeat != REPEAT_DEFAULT) {
if (uniform.repeat != REPEAT_DEFAULT) {
if (uniform.repeat == new_repeat) {
- _set_error(vformat(RTR("Duplicated hint: '%s'."), get_texture_repeat_name(new_repeat)));
+ _set_error(vformat(RTR("Duplicated repeat mode: '%s'."), get_texture_repeat_name(new_repeat)));
} else {
- _set_error(vformat(RTR("Redefinition of hint: '%s'. The repeat mode has already been set to '%s'."), get_texture_repeat_name(new_repeat), get_texture_repeat_name(uniform.repeat)));
+ _set_error(vformat(RTR("Redefinition of repeat mode: '%s'. The repeat mode has already been set to '%s'."), get_texture_repeat_name(new_repeat), get_texture_repeat_name(uniform.repeat)));
}
return ERR_PARSE_ERROR;
} else {
@@ -10309,6 +10340,9 @@ Error ShaderLanguage::complete(const String &p_code, const ShaderCompileInfo &p_
options.push_back("hint_roughness_gray");
options.push_back("hint_roughness_normal");
options.push_back("hint_roughness_r");
+ options.push_back("hint_screen_texture");
+ options.push_back("hint_normal_roughness_texture");
+ options.push_back("hint_depth_texture");
options.push_back("source_color");
options.push_back("repeat_enable");
options.push_back("repeat_disable");
diff --git a/servers/rendering/shader_language.h b/servers/rendering/shader_language.h
index bfec6e1df6..75b713d167 100644
--- a/servers/rendering/shader_language.h
+++ b/servers/rendering/shader_language.h
@@ -176,6 +176,9 @@ public:
TK_HINT_SOURCE_COLOR,
TK_HINT_RANGE,
TK_HINT_INSTANCE_INDEX,
+ TK_HINT_SCREEN_TEXTURE,
+ TK_HINT_NORMAL_ROUGHNESS_TEXTURE,
+ TK_HINT_DEPTH_TEXTURE,
TK_FILTER_NEAREST,
TK_FILTER_LINEAR,
TK_FILTER_NEAREST_MIPMAP,
@@ -667,6 +670,9 @@ public:
HINT_DEFAULT_WHITE,
HINT_DEFAULT_TRANSPARENT,
HINT_ANISOTROPY,
+ HINT_SCREEN_TEXTURE,
+ HINT_NORMAL_ROUGHNESS_TEXTURE,
+ HINT_DEPTH_TEXTURE,
HINT_MAX
};
diff --git a/servers/rendering/shader_preprocessor.cpp b/servers/rendering/shader_preprocessor.cpp
index d118c73c4a..3766477070 100644
--- a/servers/rendering/shader_preprocessor.cpp
+++ b/servers/rendering/shader_preprocessor.cpp
@@ -349,6 +349,8 @@ void ShaderPreprocessor::process_directive(Tokenizer *p_tokenizer) {
process_ifdef(p_tokenizer);
} else if (directive == "ifndef") {
process_ifndef(p_tokenizer);
+ } else if (directive == "elif") {
+ process_elif(p_tokenizer);
} else if (directive == "else") {
process_else(p_tokenizer);
} else if (directive == "endif") {
@@ -415,10 +417,67 @@ void ShaderPreprocessor::process_define(Tokenizer *p_tokenizer) {
}
}
+void ShaderPreprocessor::process_elif(Tokenizer *p_tokenizer) {
+ const int line = p_tokenizer->get_line();
+
+ if (state->current_branch == nullptr || state->current_branch->else_defined) {
+ set_error(RTR("Unmatched elif."), line);
+ return;
+ }
+ if (state->previous_region != nullptr) {
+ state->previous_region->to_line = line - 1;
+ }
+
+ String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
+ if (body.is_empty()) {
+ set_error(RTR("Missing condition."), line);
+ return;
+ }
+
+ Error error = expand_condition(body, line, body);
+ if (error != OK) {
+ return;
+ }
+
+ error = expand_macros(body, line, body);
+ if (error != OK) {
+ return;
+ }
+
+ Expression expression;
+ Vector<String> names;
+ error = expression.parse(body, names);
+ if (error != OK) {
+ set_error(expression.get_error_text(), line);
+ return;
+ }
+
+ Variant v = expression.execute(Array(), nullptr, false);
+ if (v.get_type() == Variant::NIL) {
+ set_error(RTR("Condition evaluation error."), line);
+ return;
+ }
+
+ bool skip = false;
+ for (int i = 0; i < state->current_branch->conditions.size(); i++) {
+ if (state->current_branch->conditions[i]) {
+ skip = true;
+ break;
+ }
+ }
+
+ bool success = !skip && v.booleanize();
+ start_branch_condition(p_tokenizer, success, true);
+
+ if (state->save_regions) {
+ add_region(line + 1, success, state->previous_region->parent);
+ }
+}
+
void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
const int line = p_tokenizer->get_line();
- if (state->skip_stack_else.is_empty()) {
+ if (state->current_branch == nullptr || state->current_branch->else_defined) {
set_error(RTR("Unmatched else."), line);
return;
}
@@ -428,17 +487,14 @@ void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
p_tokenizer->advance('\n');
- bool skip = state->skip_stack_else[state->skip_stack_else.size() - 1];
- state->skip_stack_else.remove_at(state->skip_stack_else.size() - 1);
-
- Vector<SkippedCondition *> vec = state->skipped_conditions[state->current_filename];
- int index = vec.size() - 1;
- if (index >= 0) {
- SkippedCondition *cond = vec[index];
- if (cond->end_line == -1) {
- cond->end_line = p_tokenizer->get_line();
+ bool skip = false;
+ for (int i = 0; i < state->current_branch->conditions.size(); i++) {
+ if (state->current_branch->conditions[i]) {
+ skip = true;
+ break;
}
}
+ state->current_branch->else_defined = true;
if (state->save_regions) {
add_region(line + 1, !skip, state->previous_region->parent);
@@ -462,16 +518,10 @@ void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
state->previous_region = state->previous_region->parent;
}
- Vector<SkippedCondition *> vec = state->skipped_conditions[state->current_filename];
- int index = vec.size() - 1;
- if (index >= 0) {
- SkippedCondition *cond = vec[index];
- if (cond->end_line == -1) {
- cond->end_line = p_tokenizer->get_line();
- }
- }
-
p_tokenizer->advance('\n');
+
+ state->current_branch = state->current_branch->parent;
+ state->branches.pop_back();
}
void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
@@ -483,7 +533,12 @@ void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
return;
}
- Error error = expand_macros(body, line, body);
+ Error error = expand_condition(body, line, body);
+ if (error != OK) {
+ return;
+ }
+
+ error = expand_macros(body, line, body);
if (error != OK) {
return;
}
@@ -703,24 +758,19 @@ void ShaderPreprocessor::add_region(int p_line, bool p_enabled, Region *p_parent
state->previous_region = &state->regions[region.file].push_back(region)->get();
}
-void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success) {
- state->condition_depth++;
-
- if (p_success) {
- state->skip_stack_else.push_back(true);
+void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue) {
+ if (!p_continue) {
+ state->condition_depth++;
+ state->current_branch = &state->branches.push_back(Branch(p_success, state->current_branch))->get();
} else {
- SkippedCondition *cond = memnew(SkippedCondition());
- cond->start_line = p_tokenizer->get_line();
- state->skipped_conditions[state->current_filename].push_back(cond);
-
+ state->current_branch->conditions.push_back(p_success);
+ }
+ if (!p_success) {
Vector<String> ends;
+ ends.push_back("elif");
ends.push_back("else");
ends.push_back("endif");
- if (next_directive(p_tokenizer, ends) == "else") {
- state->skip_stack_else.push_back(false);
- } else {
- state->skip_stack_else.push_back(true);
- }
+ next_directive(p_tokenizer, ends);
}
}
@@ -737,47 +787,173 @@ void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
add_to_output(line);
}
-Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
- Vector<Pair<String, Define *>> active_defines;
- active_defines.resize(state->defines.size());
- int index = 0;
- for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
- active_defines.set(index++, Pair<String, Define *>(E->key(), E->get()));
+Error ShaderPreprocessor::expand_condition(const String &p_string, int p_line, String &r_expanded) {
+ // Checks bracket count to be even + check the cursor position.
+ {
+ int bracket_start_count = 0;
+ int bracket_end_count = 0;
+
+ for (int i = 0; i < p_string.size(); i++) {
+ switch (p_string[i]) {
+ case CURSOR:
+ state->completion_type = COMPLETION_TYPE_CONDITION;
+ break;
+ case '(':
+ bracket_start_count++;
+ break;
+ case ')':
+ bracket_end_count++;
+ break;
+ }
+ }
+ if (bracket_start_count > bracket_end_count) {
+ _set_expected_error(")", p_line);
+ return FAILED;
+ }
+ if (bracket_end_count > bracket_start_count) {
+ _set_expected_error("(", p_line);
+ return FAILED;
+ }
}
- return expand_macros(p_string, p_line, active_defines, r_expanded);
+ String result = p_string;
+
+ int index = 0;
+ int index_start = 0;
+ int index_end = 0;
+
+ while (find_match(result, "defined", index, index_start)) {
+ bool open_bracket = false;
+ bool found_word = false;
+ bool word_completed = false;
+
+ LocalVector<char32_t> text;
+ int post_bracket_index = -1;
+ int size = result.size();
+
+ for (int i = (index_start - 1); i < size; i++) {
+ char32_t c = result[i];
+ if (c == 0) {
+ if (found_word) {
+ word_completed = true;
+ }
+ break;
+ }
+ char32_t cs[] = { c, '\0' };
+ String s = String(cs);
+ bool is_space = is_char_space(c);
+
+ if (word_completed) {
+ if (c == ')') {
+ continue;
+ }
+ if (c == '|' || c == '&') {
+ if (open_bracket) {
+ _set_unexpected_token_error(s, p_line);
+ return FAILED;
+ }
+ break;
+ } else if (!is_space) {
+ _set_unexpected_token_error(s, p_line);
+ return FAILED;
+ }
+ } else if (is_space) {
+ if (found_word && !open_bracket) {
+ index_end = i;
+ word_completed = true;
+ }
+ } else if (c == '(') {
+ if (open_bracket) {
+ _set_unexpected_token_error(s, p_line);
+ return FAILED;
+ }
+ open_bracket = true;
+ } else if (c == ')') {
+ if (open_bracket) {
+ if (!found_word) {
+ _set_unexpected_token_error(s, p_line);
+ return FAILED;
+ }
+ open_bracket = false;
+ post_bracket_index = i + 1;
+ } else {
+ index_end = i;
+ }
+ word_completed = true;
+ } else if (is_char_word(c)) {
+ text.push_back(c);
+ found_word = true;
+ } else {
+ _set_unexpected_token_error(s, p_line);
+ return FAILED;
+ }
+ }
+
+ if (word_completed) {
+ if (open_bracket) {
+ _set_expected_error(")", p_line);
+ return FAILED;
+ }
+ if (post_bracket_index != -1) {
+ index_end = post_bracket_index;
+ }
+
+ String body = state->defines.has(vector_to_string(text)) ? "true" : "false";
+ String temp = result;
+
+ result = result.substr(0, index) + body;
+ index_start = result.length();
+ if (index_end > 0) {
+ result += temp.substr(index_end);
+ }
+ } else {
+ set_error(RTR("Invalid macro name."), p_line);
+ return FAILED;
+ }
+ }
+ r_expanded = result;
+ return OK;
}
-Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, Vector<Pair<String, Define *>> p_defines, String &r_expanded) {
- r_expanded = p_string;
- // When expanding macros we must only evaluate them once.
- // Later we continue expanding but with the already
- // evaluated macros removed.
- for (int i = 0; i < p_defines.size(); i++) {
- Pair<String, Define *> define_pair = p_defines[i];
-
- Error error = expand_macros_once(r_expanded, p_line, define_pair, r_expanded);
- if (error != OK) {
- return error;
+Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
+ String iterative = p_string;
+ int pass_count = 0;
+ bool expanded = true;
+
+ while (expanded) {
+ expanded = false;
+
+ // As long as we find something to expand, keep going.
+ for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
+ if (expand_macros_once(iterative, p_line, E, iterative)) {
+ expanded = true;
+ }
}
- // Remove expanded macro and recursively replace remaining.
- p_defines.remove_at(i);
- return expand_macros(r_expanded, p_line, p_defines, r_expanded);
+ pass_count++;
+ if (pass_count > 50) {
+ set_error(RTR("Macro expansion limit exceeded."), p_line);
+ break;
+ }
}
+ r_expanded = iterative;
+
+ if (!state->error.is_empty()) {
+ return FAILED;
+ }
return OK;
}
-Error ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, Pair<String, Define *> p_define_pair, String &r_expanded) {
+bool ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, const RBMap<String, Define *>::Element *p_define_pair, String &r_expanded) {
String result = p_line;
- const String &key = p_define_pair.first;
- const Define *define = p_define_pair.second;
+ const String &key = p_define_pair->key();
+ const Define *define = p_define_pair->value();
int index_start = 0;
int index = 0;
- while (find_match(result, key, index, index_start)) {
+ if (find_match(result, key, index, index_start)) {
String body = define->body;
if (define->arguments.size() > 0) {
// Complex macro with arguments.
@@ -785,14 +961,14 @@ Error ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_nu
int args_end = p_line.find(")", args_start);
if (args_start == -1 || args_end == -1) {
set_error(RTR("Missing macro argument parenthesis."), p_line_number);
- return FAILED;
+ return false;
}
String values = result.substr(args_start + 1, args_end - (args_start + 1));
Vector<String> args = values.split(",");
if (args.size() != define->arguments.size()) {
set_error(RTR("Invalid macro argument count."), p_line_number);
- return FAILED;
+ return false;
}
// Insert macro arguments into the body.
@@ -814,11 +990,13 @@ Error ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_nu
// Manually reset index_start to where the body value of the define finishes.
// This ensures we don't skip another instance of this macro in the string.
index_start = index + body.length() + 1;
- break;
}
+
+ r_expanded = result;
+ return true;
}
- r_expanded = result;
- return OK;
+
+ return false;
}
bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
@@ -909,12 +1087,6 @@ void ShaderPreprocessor::clear() {
memdelete(E->get());
}
- for (const RBMap<String, Vector<SkippedCondition *>>::Element *E = state->skipped_conditions.front(); E; E = E->next()) {
- for (SkippedCondition *condition : E->get()) {
- memdelete(condition);
- }
- }
-
memdelete(state);
}
state_owner = false;
@@ -1030,7 +1202,7 @@ Error ShaderPreprocessor::preprocess(const String &p_code, const String &p_filen
switch (pp_state.completion_type) {
case COMPLETION_TYPE_DIRECTIVE: {
List<String> options;
- get_keyword_list(&options, true);
+ get_keyword_list(&options, true, true);
for (const String &E : options) {
ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
@@ -1049,6 +1221,11 @@ Error ShaderPreprocessor::preprocess(const String &p_code, const String &p_filen
}
} break;
+ case COMPLETION_TYPE_CONDITION: {
+ ScriptLanguage::CodeCompletionOption option("defined", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
+ r_completion_options->push_back(option);
+
+ } break;
case COMPLETION_TYPE_INCLUDE_PATH: {
if (p_include_completion_func && r_completion_options) {
p_include_completion_func(r_completion_options);
@@ -1062,8 +1239,12 @@ Error ShaderPreprocessor::preprocess(const String &p_code, const String &p_filen
return err;
}
-void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords) {
+void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords, bool p_ignore_context_keywords) {
r_keywords->push_back("define");
+ if (!p_ignore_context_keywords) {
+ r_keywords->push_back("defined");
+ }
+ r_keywords->push_back("elif");
if (p_include_shader_keywords) {
r_keywords->push_back("else");
}
diff --git a/servers/rendering/shader_preprocessor.h b/servers/rendering/shader_preprocessor.h
index 41b574298d..b4e7c7199f 100644
--- a/servers/rendering/shader_preprocessor.h
+++ b/servers/rendering/shader_preprocessor.h
@@ -50,6 +50,7 @@ public:
COMPLETION_TYPE_DIRECTIVE,
COMPLETION_TYPE_PRAGMA_DIRECTIVE,
COMPLETION_TYPE_PRAGMA,
+ COMPLETION_TYPE_CONDITION,
COMPLETION_TYPE_INCLUDE_PATH,
};
@@ -130,14 +131,23 @@ private:
String body;
};
- struct SkippedCondition {
- int start_line = -1;
- int end_line = -1;
+ struct Branch {
+ Vector<bool> conditions;
+ Branch *parent = nullptr;
+ bool else_defined = false;
+
+ Branch() {}
+
+ Branch(bool p_condition, Branch *p_parent) :
+ parent(p_parent) {
+ conditions.push_back(p_condition);
+ }
};
struct State {
RBMap<String, Define *> defines;
- Vector<bool> skip_stack_else;
+ List<Branch> branches;
+ Branch *current_branch = nullptr;
int condition_depth = 0;
RBSet<String> includes;
List<uint64_t> cyclic_include_hashes; // Holds code hash of includes.
@@ -149,7 +159,6 @@ private:
bool save_regions = false;
RBMap<String, List<Region>> regions;
Region *previous_region = nullptr;
- RBMap<String, Vector<SkippedCondition *>> skipped_conditions;
bool disabled = false;
CompletionType completion_type = COMPLETION_TYPE_NONE;
HashSet<Ref<ShaderInclude>> shader_includes;
@@ -167,8 +176,17 @@ private:
static String vector_to_string(const LocalVector<char32_t> &p_v, int p_start = 0, int p_end = -1);
static String tokens_to_string(const LocalVector<Token> &p_tokens);
+ void _set_expected_error(const String &p_what, int p_line) {
+ set_error(vformat(RTR("Expected a '%s'."), p_what), p_line);
+ }
+
+ void _set_unexpected_token_error(const String &p_what, int p_line) {
+ set_error(vformat(RTR("Unexpected token '%s'."), p_what), p_line);
+ }
+
void process_directive(Tokenizer *p_tokenizer);
void process_define(Tokenizer *p_tokenizer);
+ void process_elif(Tokenizer *p_tokenizer);
void process_else(Tokenizer *p_tokenizer);
void process_endif(Tokenizer *p_tokenizer);
void process_if(Tokenizer *p_tokenizer);
@@ -179,12 +197,12 @@ private:
void process_undef(Tokenizer *p_tokenizer);
void add_region(int p_line, bool p_enabled, Region *p_parent_region);
- void start_branch_condition(Tokenizer *p_tokenizer, bool p_success);
+ void start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue = false);
+ Error expand_condition(const String &p_string, int p_line, String &r_result);
void expand_output_macros(int p_start, int p_line);
Error expand_macros(const String &p_string, int p_line, String &r_result);
- Error expand_macros(const String &p_string, int p_line, Vector<Pair<String, Define *>> p_defines, String &r_result);
- Error expand_macros_once(const String &p_line, int p_line_number, Pair<String, Define *> p_define_pair, String &r_expanded);
+ bool expand_macros_once(const String &p_line, int p_line_number, const RBMap<String, Define *>::Element *p_define_pair, String &r_expanded);
bool find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start);
String next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives);
@@ -202,7 +220,7 @@ public:
Error preprocess(const String &p_code, const String &p_filename, String &r_result, String *r_error_text = nullptr, List<FilePosition> *r_error_position = nullptr, List<Region> *r_regions = nullptr, HashSet<Ref<ShaderInclude>> *r_includes = nullptr, List<ScriptLanguage::CodeCompletionOption> *r_completion_options = nullptr, IncludeCompletionFunction p_include_completion_func = nullptr);
- static void get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords);
+ static void get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords, bool p_ignore_context_keywords = false);
static void get_pragma_list(List<String> *r_pragmas);
ShaderPreprocessor();
diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp
index a54d4f0384..a410cf0ed8 100644
--- a/servers/rendering_server.cpp
+++ b/servers/rendering_server.cpp
@@ -31,6 +31,7 @@
#include "rendering_server.h"
#include "core/config/project_settings.h"
+#include "core/variant/typed_array.h"
#include "servers/rendering/rendering_server_globals.h"
#include "servers/rendering/shader_language.h"
@@ -69,44 +70,44 @@ Array RenderingServer::_texture_debug_usage_bind() {
return arr;
}
-static Array to_array(const Vector<ObjectID> &ids) {
- Array a;
+static PackedInt64Array to_int_array(const Vector<ObjectID> &ids) {
+ PackedInt64Array a;
a.resize(ids.size());
for (int i = 0; i < ids.size(); ++i) {
- a[i] = ids[i];
+ a.write[i] = ids[i];
}
return a;
}
-Array RenderingServer::_instances_cull_aabb_bind(const AABB &p_aabb, RID p_scenario) const {
+PackedInt64Array RenderingServer::_instances_cull_aabb_bind(const AABB &p_aabb, RID p_scenario) const {
if (RSG::threaded) {
WARN_PRINT_ONCE("Using this function with a threaded renderer hurts performance, as it causes a server stall.");
}
Vector<ObjectID> ids = instances_cull_aabb(p_aabb, p_scenario);
- return to_array(ids);
+ return to_int_array(ids);
}
-Array RenderingServer::_instances_cull_ray_bind(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
+PackedInt64Array RenderingServer::_instances_cull_ray_bind(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
if (RSG::threaded) {
WARN_PRINT_ONCE("Using this function with a threaded renderer hurts performance, as it causes a server stall.");
}
Vector<ObjectID> ids = instances_cull_ray(p_from, p_to, p_scenario);
- return to_array(ids);
+ return to_int_array(ids);
}
-Array RenderingServer::_instances_cull_convex_bind(const Array &p_convex, RID p_scenario) const {
+PackedInt64Array RenderingServer::_instances_cull_convex_bind(const Array &p_convex, RID p_scenario) const {
if (RSG::threaded) {
WARN_PRINT_ONCE("Using this function with a threaded renderer hurts performance, as it causes a server stall.");
}
Vector<Plane> planes;
for (int i = 0; i < p_convex.size(); ++i) {
Variant v = p_convex[i];
- ERR_FAIL_COND_V(v.get_type() != Variant::PLANE, Array());
+ ERR_FAIL_COND_V(v.get_type() != Variant::PLANE, PackedInt64Array());
planes.push_back(v);
}
Vector<ObjectID> ids = instances_cull_convex(planes, p_scenario);
- return to_array(ids);
+ return to_int_array(ids);
}
RID RenderingServer::get_test_texture() {
@@ -398,16 +399,14 @@ Error RenderingServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint
const Vector3 *src = array.ptr();
for (int i = 0; i < p_vertex_array_len; i++) {
- Vector3 n = src[i] * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
-
- uint32_t value = 0;
- value |= CLAMP(int(n.x * 1023.0), 0, 1023);
- value |= CLAMP(int(n.y * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int(n.z * 1023.0), 0, 1023) << 20;
+ Vector2 res = src[i].octahedron_encode();
+ int16_t vector[2] = {
+ (int16_t)CLAMP(res.x * 65535, 0, 65535),
+ (int16_t)CLAMP(res.y * 65535, 0, 65535),
+ };
- memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], &value, 4);
+ memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], vector, 4);
}
-
} break;
case RS::ARRAY_TANGENT: {
@@ -416,33 +415,32 @@ Error RenderingServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint
if (type == Variant::PACKED_FLOAT32_ARRAY) {
Vector<float> array = p_arrays[ai];
ERR_FAIL_COND_V(array.size() != p_vertex_array_len * 4, ERR_INVALID_PARAMETER);
- const float *src = array.ptr();
+ const float *src_ptr = array.ptr();
for (int i = 0; i < p_vertex_array_len; i++) {
- uint32_t value = 0;
- value |= CLAMP(int((src[i * 4 + 0] * 0.5 + 0.5) * 1023.0), 0, 1023);
- value |= CLAMP(int((src[i * 4 + 1] * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int((src[i * 4 + 2] * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
- if (src[i * 4 + 3] > 0) {
- value |= 3UL << 30;
- }
-
- memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], &value, 4);
+ const Vector3 src(src_ptr[i * 4 + 0], src_ptr[i * 4 + 1], src_ptr[i * 4 + 2]);
+ Vector2 res = src.octahedron_tangent_encode(src_ptr[i * 4 + 3]);
+ int16_t vector[2] = {
+ (int16_t)CLAMP(res.x * 65535, 0, 65535),
+ (int16_t)CLAMP(res.y * 65535, 0, 65535),
+ };
+
+ memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], vector, 4);
}
} else { // PACKED_FLOAT64_ARRAY
Vector<double> array = p_arrays[ai];
ERR_FAIL_COND_V(array.size() != p_vertex_array_len * 4, ERR_INVALID_PARAMETER);
- const double *src = array.ptr();
+ const double *src_ptr = array.ptr();
for (int i = 0; i < p_vertex_array_len; i++) {
- uint32_t value = 0;
- value |= CLAMP(int((src[i * 4 + 0] * 0.5 + 0.5) * 1023.0), 0, 1023);
- value |= CLAMP(int((src[i * 4 + 1] * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int((src[i * 4 + 2] * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
- if (src[i * 4 + 3] > 0) {
- value |= 3UL << 30;
- }
- memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], &value, 4);
+ const Vector3 src(src_ptr[i * 4 + 0], src_ptr[i * 4 + 1], src_ptr[i * 4 + 2]);
+ Vector2 res = src.octahedron_tangent_encode(src_ptr[i * 4 + 3]);
+ int16_t vector[2] = {
+ (int16_t)CLAMP(res.x * 65535, 0, 65535),
+ (int16_t)CLAMP(res.y * 65535, 0, 65535),
+ };
+
+ memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], vector, 4);
}
}
} break;
@@ -627,7 +625,7 @@ Error RenderingServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint
const int *src = indices.ptr();
for (int i = 0; i < p_index_array_len; i++) {
- if (p_vertex_array_len < (1 << 16)) {
+ if (p_vertex_array_len < (1 << 16) && p_vertex_array_len > 0) {
uint16_t v = src[i];
memcpy(&iw[i * 2], &v, 2);
@@ -836,9 +834,8 @@ void RenderingServer::mesh_surface_make_offsets_from_format(uint32_t p_format, i
break;
}
/* determine whether using 16 or 32 bits indices */
- if (p_vertex_len >= (1 << 16)) {
+ if (p_vertex_len >= (1 << 16) || p_vertex_len == 0) {
elem_size = 4;
-
} else {
elem_size = 2;
}
@@ -909,8 +906,6 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa
}
}
- ERR_FAIL_COND_V((format & RS::ARRAY_FORMAT_VERTEX) == 0, ERR_INVALID_PARAMETER); // Mandatory
-
if (p_blend_shapes.size()) {
// Validate format for morphs.
for (int i = 0; i < p_blend_shapes.size(); i++) {
@@ -944,6 +939,12 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa
uint32_t mask = (1 << ARRAY_MAX) - 1;
format |= (~mask) & p_compress_format; // Make the full format.
+ if ((format & RS::ARRAY_FORMAT_VERTEX) == 0 && !(format & RS::ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY)) {
+ ERR_PRINT("Mesh created without vertex array. This mesh will not be visible with the default shader. If using an empty vertex array is intentional, create the mesh with the ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY flag to silence this error.");
+ // Set the flag here after warning to suppress errors down the pipeline.
+ format |= RS::ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY;
+ }
+
int vertex_array_size = vertex_element_size * array_len;
int attrib_array_size = attrib_element_size * array_len;
int skin_array_size = skin_element_size * array_len;
@@ -1337,7 +1338,7 @@ Dictionary RenderingServer::mesh_surface_get_lods(RID p_mesh, int p_surface) con
return ret;
}
-Array RenderingServer::mesh_surface_get_blend_shape_arrays(RID p_mesh, int p_surface) const {
+TypedArray<Array> RenderingServer::mesh_surface_get_blend_shape_arrays(RID p_mesh, int p_surface) const {
SurfaceData sd = mesh_get_surface(p_mesh, p_surface);
ERR_FAIL_COND_V(sd.vertex_count == 0, Array());
@@ -1359,7 +1360,7 @@ Array RenderingServer::mesh_surface_get_blend_shape_arrays(RID p_mesh, int p_sur
ERR_FAIL_COND_V(blend_shape_count != (uint32_t)mesh_get_blend_shape_count(p_mesh), Array());
- Array blend_shape_array;
+ TypedArray<Array> blend_shape_array;
blend_shape_array.resize(mesh_get_blend_shape_count(p_mesh));
for (uint32_t i = 0; i < blend_shape_count; i++) {
Vector<uint8_t> bs_data = blend_shape_data.slice(i * divisor, (i + 1) * divisor);
@@ -1369,7 +1370,7 @@ Array RenderingServer::mesh_surface_get_blend_shape_arrays(RID p_mesh, int p_sur
return blend_shape_array;
} else {
- return Array();
+ return TypedArray<Array>();
}
}
@@ -1378,7 +1379,7 @@ Array RenderingServer::mesh_create_arrays_from_surface_data(const SurfaceData &p
Vector<uint8_t> attrib_data = p_data.attribute_data;
Vector<uint8_t> skin_data = p_data.skin_data;
- ERR_FAIL_COND_V(vertex_data.size() == 0, Array());
+ ERR_FAIL_COND_V(vertex_data.size() == 0 && (p_data.format & RS::ARRAY_FORMAT_VERTEX), Array());
int vertex_len = p_data.vertex_count;
Vector<uint8_t> index_data = p_data.index_data;
@@ -1625,7 +1626,7 @@ Dictionary RenderingServer::_mesh_get_surface(RID p_mesh, int p_idx) {
return d;
}
-Array RenderingServer::_instance_geometry_get_shader_uniform_list(RID p_instance) const {
+TypedArray<Dictionary> RenderingServer::_instance_geometry_get_shader_uniform_list(RID p_instance) const {
List<PropertyInfo> params;
instance_geometry_get_shader_uniform_list(p_instance, &params);
return convert_property_list(&params);
diff --git a/servers/rendering_server.h b/servers/rendering_server.h
index a2fe9caf19..59887d7d37 100644
--- a/servers/rendering_server.h
+++ b/servers/rendering_server.h
@@ -42,6 +42,9 @@
#include "servers/display_server.h"
#include "servers/rendering/rendering_device.h"
+template <typename T>
+class TypedArray;
+
class RenderingServer : public Object {
GDCLASS(RenderingServer, Object);
@@ -244,7 +247,7 @@ public:
enum ArrayFormat {
/* ARRAY FORMAT FLAGS */
- ARRAY_FORMAT_VERTEX = 1 << ARRAY_VERTEX, // Mandatory
+ ARRAY_FORMAT_VERTEX = 1 << ARRAY_VERTEX,
ARRAY_FORMAT_NORMAL = 1 << ARRAY_NORMAL,
ARRAY_FORMAT_TANGENT = 1 << ARRAY_TANGENT,
ARRAY_FORMAT_COLOR = 1 << ARRAY_COLOR,
@@ -262,17 +265,19 @@ public:
ARRAY_FORMAT_CUSTOM_BASE = (ARRAY_INDEX + 1),
ARRAY_FORMAT_CUSTOM_BITS = 3,
+ ARRAY_FORMAT_CUSTOM_MASK = 0x7,
ARRAY_FORMAT_CUSTOM0_SHIFT = (ARRAY_FORMAT_CUSTOM_BASE + 0),
ARRAY_FORMAT_CUSTOM1_SHIFT = (ARRAY_FORMAT_CUSTOM_BASE + ARRAY_FORMAT_CUSTOM_BITS),
ARRAY_FORMAT_CUSTOM2_SHIFT = (ARRAY_FORMAT_CUSTOM_BASE + ARRAY_FORMAT_CUSTOM_BITS * 2),
ARRAY_FORMAT_CUSTOM3_SHIFT = (ARRAY_FORMAT_CUSTOM_BASE + ARRAY_FORMAT_CUSTOM_BITS * 3),
- ARRAY_FORMAT_CUSTOM_MASK = 0x7,
ARRAY_COMPRESS_FLAGS_BASE = (ARRAY_INDEX + 1 + 12),
ARRAY_FLAG_USE_2D_VERTICES = 1 << (ARRAY_COMPRESS_FLAGS_BASE + 0),
ARRAY_FLAG_USE_DYNAMIC_UPDATE = 1 << (ARRAY_COMPRESS_FLAGS_BASE + 1),
ARRAY_FLAG_USE_8_BONE_WEIGHTS = 1 << (ARRAY_COMPRESS_FLAGS_BASE + 2),
+
+ ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY = 1 << (ARRAY_INDEX + 1 + 15),
};
enum PrimitiveType {
@@ -323,7 +328,7 @@ public:
virtual Error mesh_create_surface_data_from_arrays(SurfaceData *r_surface_data, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), const Dictionary &p_lods = Dictionary(), uint32_t p_compress_format = 0);
Array mesh_create_arrays_from_surface_data(const SurfaceData &p_data) const;
Array mesh_surface_get_arrays(RID p_mesh, int p_surface) const;
- Array mesh_surface_get_blend_shape_arrays(RID p_mesh, int p_surface) const;
+ TypedArray<Array> mesh_surface_get_blend_shape_arrays(RID p_mesh, int p_surface) const;
Dictionary mesh_surface_get_lods(RID p_mesh, int p_surface) const;
virtual void mesh_add_surface_from_arrays(RID p_mesh, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), const Dictionary &p_lods = Dictionary(), uint32_t p_compress_format = 0);
@@ -1211,9 +1216,9 @@ public:
virtual Vector<ObjectID> instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const = 0;
virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario = RID()) const = 0;
- Array _instances_cull_aabb_bind(const AABB &p_aabb, RID p_scenario = RID()) const;
- Array _instances_cull_ray_bind(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const;
- Array _instances_cull_convex_bind(const Array &p_convex, RID p_scenario = RID()) const;
+ PackedInt64Array _instances_cull_aabb_bind(const AABB &p_aabb, RID p_scenario = RID()) const;
+ PackedInt64Array _instances_cull_ray_bind(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const;
+ PackedInt64Array _instances_cull_convex_bind(const Array &p_convex, RID p_scenario = RID()) const;
enum InstanceFlags {
INSTANCE_FLAG_USE_BAKED_LIGHT,
@@ -1576,7 +1581,7 @@ private:
RID _mesh_create_from_surfaces(const TypedArray<Dictionary> &p_surfaces, int p_blend_shape_count);
void _mesh_add_surface(RID p_mesh, const Dictionary &p_surface);
Dictionary _mesh_get_surface(RID p_mesh, int p_idx);
- Array _instance_geometry_get_shader_uniform_list(RID p_instance) const;
+ TypedArray<Dictionary> _instance_geometry_get_shader_uniform_list(RID p_instance) const;
TypedArray<Image> _bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size);
void _particles_set_trail_bind_poses(RID p_particles, const TypedArray<Transform3D> &p_bind_poses);
};
diff --git a/servers/text/text_server_extension.cpp b/servers/text/text_server_extension.cpp
index 59310ab69b..855267e428 100644
--- a/servers/text/text_server_extension.cpp
+++ b/servers/text/text_server_extension.cpp
@@ -634,12 +634,12 @@ double TextServerExtension::font_get_oversampling(const RID &p_font_rid) const {
return 0.0;
}
-Array TextServerExtension::font_get_size_cache_list(const RID &p_font_rid) const {
- Array ret;
+TypedArray<Vector2i> TextServerExtension::font_get_size_cache_list(const RID &p_font_rid) const {
+ TypedArray<Vector2i> ret;
if (GDVIRTUAL_CALL(font_get_size_cache_list, p_font_rid, ret)) {
return ret;
}
- return Array();
+ return TypedArray<Vector2i>();
}
void TextServerExtension::font_clear_size_cache(const RID &p_font_rid) {
@@ -750,12 +750,12 @@ PackedInt32Array TextServerExtension::font_get_texture_offsets(const RID &p_font
return PackedInt32Array();
}
-Array TextServerExtension::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
- Array ret;
+PackedInt32Array TextServerExtension::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
+ PackedInt32Array ret;
if (GDVIRTUAL_CALL(font_get_glyph_list, p_font_rid, p_size, ret)) {
return ret;
}
- return Array();
+ return PackedInt32Array();
}
void TextServerExtension::font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) {
@@ -850,12 +850,12 @@ Dictionary TextServerExtension::font_get_glyph_contours(const RID &p_font_rid, i
return Dictionary();
}
-Array TextServerExtension::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
- Array ret;
+TypedArray<Vector2i> TextServerExtension::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
+ TypedArray<Vector2i> ret;
if (GDVIRTUAL_CALL(font_get_kerning_list, p_font_rid, p_size, ret)) {
return ret;
}
- return Array();
+ return TypedArray<Vector2i>();
}
void TextServerExtension::font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) {
@@ -1534,12 +1534,12 @@ String TextServerExtension::string_to_lower(const String &p_string, const String
return p_string;
}
-Array TextServerExtension::parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
- Array ret;
+TypedArray<Vector2i> TextServerExtension::parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
+ TypedArray<Vector2i> ret;
if (GDVIRTUAL_CALL(parse_structured_text, p_parser_type, p_args, p_text, ret)) {
return ret;
}
- return Array();
+ return TypedArray<Vector2i>();
}
PackedInt32Array TextServerExtension::string_get_word_breaks(const String &p_string, const String &p_language) const {
diff --git a/servers/text/text_server_extension.h b/servers/text/text_server_extension.h
index 81af1b60e5..7e1ed22390 100644
--- a/servers/text/text_server_extension.h
+++ b/servers/text/text_server_extension.h
@@ -35,6 +35,7 @@
#include "core/object/script_language.h"
#include "core/os/thread_safe.h"
#include "core/variant/native_ptr.h"
+#include "core/variant/typed_array.h"
#include "servers/text_server.h"
class TextServerExtension : public TextServer {
@@ -172,10 +173,10 @@ public:
GDVIRTUAL2(font_set_oversampling, RID, double);
GDVIRTUAL1RC(double, font_get_oversampling, RID);
- virtual Array font_get_size_cache_list(const RID &p_font_rid) const override;
+ virtual TypedArray<Vector2i> font_get_size_cache_list(const RID &p_font_rid) const override;
virtual void font_clear_size_cache(const RID &p_font_rid) override;
virtual void font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) override;
- GDVIRTUAL1RC(Array, font_get_size_cache_list, RID);
+ GDVIRTUAL1RC(TypedArray<Vector2i>, font_get_size_cache_list, RID);
GDVIRTUAL1(font_clear_size_cache, RID);
GDVIRTUAL2(font_remove_size_cache, RID, const Vector2i &);
@@ -221,10 +222,10 @@ public:
GDVIRTUAL4(font_set_texture_offsets, RID, const Vector2i &, int64_t, const PackedInt32Array &);
GDVIRTUAL3RC(PackedInt32Array, font_get_texture_offsets, RID, const Vector2i &, int64_t);
- virtual Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override;
+ virtual PackedInt32Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override;
virtual void font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) override;
virtual void font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) override;
- GDVIRTUAL2RC(Array, font_get_glyph_list, RID, const Vector2i &);
+ GDVIRTUAL2RC(PackedInt32Array, font_get_glyph_list, RID, const Vector2i &);
GDVIRTUAL2(font_clear_glyphs, RID, const Vector2i &);
GDVIRTUAL3(font_remove_glyph, RID, const Vector2i &, int64_t);
@@ -262,10 +263,10 @@ public:
virtual Dictionary font_get_glyph_contours(const RID &p_font, int64_t p_size, int64_t p_index) const override;
GDVIRTUAL3RC(Dictionary, font_get_glyph_contours, RID, int64_t, int64_t);
- virtual Array font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override;
+ virtual TypedArray<Vector2i> font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override;
virtual void font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) override;
virtual void font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) override;
- GDVIRTUAL2RC(Array, font_get_kerning_list, RID, int64_t);
+ GDVIRTUAL2RC(TypedArray<Vector2i>, font_get_kerning_list, RID, int64_t);
GDVIRTUAL2(font_clear_kerning_map, RID, int64_t);
GDVIRTUAL3(font_remove_kerning, RID, int64_t, const Vector2i &);
@@ -504,8 +505,8 @@ public:
GDVIRTUAL2RC(String, string_to_upper, const String &, const String &);
GDVIRTUAL2RC(String, string_to_lower, const String &, const String &);
- Array parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
- GDVIRTUAL3RC(Array, parse_structured_text, StructuredTextParser, const Array &, const String &);
+ TypedArray<Vector2i> parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
+ GDVIRTUAL3RC(TypedArray<Vector2i>, parse_structured_text, StructuredTextParser, const Array &, const String &);
virtual int is_confusable(const String &p_string, const PackedStringArray &p_dict) const override;
virtual bool spoof_check(const String &p_string) const override;
diff --git a/servers/text_server.cpp b/servers/text_server.cpp
index 2bf0837d88..66b32dba84 100644
--- a/servers/text_server.cpp
+++ b/servers/text_server.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "servers/text_server.h"
+#include "core/variant/typed_array.h"
#include "servers/rendering_server.h"
TextServerManager *TextServerManager::singleton = nullptr;
@@ -103,8 +104,8 @@ Ref<TextServer> TextServerManager::find_interface(const String &p_name) const {
return interfaces[idx];
}
-Array TextServerManager::get_interfaces() const {
- Array ret;
+TypedArray<Dictionary> TextServerManager::get_interfaces() const {
+ TypedArray<Dictionary> ret;
for (int i = 0; i < interfaces.size(); i++) {
Dictionary iface_info;
@@ -1585,8 +1586,8 @@ String TextServer::strip_diacritics(const String &p_string) const {
return result;
}
-Array TextServer::parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
- Array ret;
+TypedArray<Vector2i> TextServer::parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
+ TypedArray<Vector2i> ret;
switch (p_parser_type) {
case STRUCTURED_TEXT_URI: {
int prev = 0;
@@ -1627,7 +1628,7 @@ Array TextServer::parse_structured_text(StructuredTextParser p_parser_type, cons
ret.push_back(Vector2i(prev, i));
ret.push_back(Vector2i(i, i + 1));
prev = i + 1;
- } else if (!local & (p_text[i] == '.')) { // Add each dot separated "domain" part as context.
+ } else if (!local && (p_text[i] == '.')) { // Add each dot separated "domain" part as context.
if (prev != i) {
ret.push_back(Vector2i(prev, i));
}
@@ -1662,8 +1663,8 @@ Array TextServer::parse_structured_text(StructuredTextParser p_parser_type, cons
return ret;
}
-Array TextServer::_shaped_text_get_glyphs_wrapper(const RID &p_shaped) const {
- Array ret;
+TypedArray<Dictionary> TextServer::_shaped_text_get_glyphs_wrapper(const RID &p_shaped) const {
+ TypedArray<Dictionary> ret;
const Glyph *glyphs = shaped_text_get_glyphs(p_shaped);
int gl_size = shaped_text_get_glyph_count(p_shaped);
@@ -1687,7 +1688,7 @@ Array TextServer::_shaped_text_get_glyphs_wrapper(const RID &p_shaped) const {
return ret;
}
-Array TextServer::_shaped_text_sort_logical_wrapper(const RID &p_shaped) {
+TypedArray<Dictionary> TextServer::_shaped_text_sort_logical_wrapper(const RID &p_shaped) {
Array ret;
const Glyph *glyphs = shaped_text_sort_logical(p_shaped);
@@ -1712,8 +1713,8 @@ Array TextServer::_shaped_text_sort_logical_wrapper(const RID &p_shaped) {
return ret;
}
-Array TextServer::_shaped_text_get_ellipsis_glyphs_wrapper(const RID &p_shaped) const {
- Array ret;
+TypedArray<Dictionary> TextServer::_shaped_text_get_ellipsis_glyphs_wrapper(const RID &p_shaped) const {
+ TypedArray<Dictionary> ret;
const Glyph *glyphs = shaped_text_get_ellipsis_glyphs(p_shaped);
int gl_size = shaped_text_get_ellipsis_glyph_count(p_shaped);
diff --git a/servers/text_server.h b/servers/text_server.h
index d45bea3271..9ffc2984d1 100644
--- a/servers/text_server.h
+++ b/servers/text_server.h
@@ -37,6 +37,9 @@
#include "core/variant/native_ptr.h"
#include "core/variant/variant.h"
+template <typename T>
+class TypedArray;
+
struct Glyph;
struct CaretInfo;
@@ -269,7 +272,7 @@ public:
virtual void font_set_oversampling(const RID &p_font_rid, double p_oversampling) = 0;
virtual double font_get_oversampling(const RID &p_font_rid) const = 0;
- virtual Array font_get_size_cache_list(const RID &p_font_rid) const = 0;
+ virtual TypedArray<Vector2i> font_get_size_cache_list(const RID &p_font_rid) const = 0;
virtual void font_clear_size_cache(const RID &p_font_rid) = 0;
virtual void font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) = 0;
@@ -298,7 +301,7 @@ public:
virtual void font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) = 0;
virtual PackedInt32Array font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const = 0;
- virtual Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const = 0;
+ virtual PackedInt32Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const = 0;
virtual void font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) = 0;
virtual void font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) = 0;
@@ -321,7 +324,7 @@ public:
virtual Dictionary font_get_glyph_contours(const RID &p_font, int64_t p_size, int64_t p_index) const = 0;
- virtual Array font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const = 0;
+ virtual TypedArray<Vector2i> font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const = 0;
virtual void font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) = 0;
virtual void font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) = 0;
@@ -411,9 +414,9 @@ public:
virtual bool shaped_text_is_ready(const RID &p_shaped) const = 0;
virtual const Glyph *shaped_text_get_glyphs(const RID &p_shaped) const = 0;
- Array _shaped_text_get_glyphs_wrapper(const RID &p_shaped) const;
+ TypedArray<Dictionary> _shaped_text_get_glyphs_wrapper(const RID &p_shaped) const;
virtual const Glyph *shaped_text_sort_logical(const RID &p_shaped) = 0;
- Array _shaped_text_sort_logical_wrapper(const RID &p_shaped);
+ TypedArray<Dictionary> _shaped_text_sort_logical_wrapper(const RID &p_shaped);
virtual int64_t shaped_text_get_glyph_count(const RID &p_shaped) const = 0;
virtual Vector2i shaped_text_get_range(const RID &p_shaped) const = 0;
@@ -425,7 +428,7 @@ public:
virtual int64_t shaped_text_get_trim_pos(const RID &p_shaped) const = 0;
virtual int64_t shaped_text_get_ellipsis_pos(const RID &p_shaped) const = 0;
virtual const Glyph *shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const = 0;
- Array _shaped_text_get_ellipsis_glyphs_wrapper(const RID &p_shaped) const;
+ TypedArray<Dictionary> _shaped_text_get_ellipsis_glyphs_wrapper(const RID &p_shaped) const;
virtual int64_t shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const = 0;
virtual void shaped_text_overrun_trim_to_width(const RID &p_shaped, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) = 0;
@@ -476,7 +479,7 @@ public:
virtual String string_to_upper(const String &p_string, const String &p_language = "") const = 0;
virtual String string_to_lower(const String &p_string, const String &p_language = "") const = 0;
- Array parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
+ TypedArray<Vector2i> parse_structured_text(StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
TextServer();
~TextServer();
@@ -538,7 +541,7 @@ public:
int get_interface_count() const;
Ref<TextServer> get_interface(int p_index) const;
Ref<TextServer> find_interface(const String &p_name) const;
- Array get_interfaces() const;
+ TypedArray<Dictionary> get_interfaces() const;
_FORCE_INLINE_ Ref<TextServer> get_primary_interface() const {
return primary_interface;
diff --git a/servers/xr_server.cpp b/servers/xr_server.cpp
index 990281d96d..e26212ada1 100644
--- a/servers/xr_server.cpp
+++ b/servers/xr_server.cpp
@@ -226,7 +226,7 @@ Ref<XRInterface> XRServer::find_interface(const String &p_name) const {
return interfaces[idx];
};
-Array XRServer::get_interfaces() const {
+TypedArray<Dictionary> XRServer::get_interfaces() const {
Array ret;
for (int i = 0; i < interfaces.size(); i++) {
diff --git a/servers/xr_server.h b/servers/xr_server.h
index 74128bfb54..57e42deccb 100644
--- a/servers/xr_server.h
+++ b/servers/xr_server.h
@@ -157,7 +157,7 @@ public:
int get_interface_count() const;
Ref<XRInterface> get_interface(int p_index) const;
Ref<XRInterface> find_interface(const String &p_name) const;
- Array get_interfaces() const;
+ TypedArray<Dictionary> get_interfaces() const;
/*
note, more then one interface can technically be active, especially on mobile, but only one interface is used for
diff --git a/tests/core/object/test_object.h b/tests/core/object/test_object.h
index 88a3e4ccad..f5c5de7fdf 100644
--- a/tests/core/object/test_object.h
+++ b/tests/core/object/test_object.h
@@ -82,6 +82,12 @@ public:
Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override {
return Variant::PACKED_FLOAT32_ARRAY;
}
+ bool property_can_revert(const StringName &p_name) const override {
+ return false;
+ };
+ bool property_get_revert(const StringName &p_name, Variant &r_ret) const override {
+ return false;
+ };
void get_method_list(List<MethodInfo> *p_list) const override {
}
bool has_method(const StringName &p_method) const override {
diff --git a/tests/core/string/test_string.h b/tests/core/string/test_string.h
index 8914dbfd9a..62d2051eee 100644
--- a/tests/core/string/test_string.h
+++ b/tests/core/string/test_string.h
@@ -619,7 +619,7 @@ TEST_CASE("[String] sprintf") {
output = format.sprintf(args, &error);
REQUIRE(error == false);
CHECK(output == String("fish % frog"));
- //////// INTS
+ ///// Ints
// Int
format = "fish %d frog";
@@ -727,7 +727,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
CHECK(output == String("fish 143 frog"));
- ////// REALS
+ ///// Reals
// Real
format = "fish %f frog";
@@ -737,7 +737,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
CHECK(output == String("fish 99.990000 frog"));
- // Real left-padded
+ // Real left-padded.
format = "fish %11f frog";
args.clear();
args.push_back(99.99);
@@ -745,7 +745,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
CHECK(output == String("fish 99.990000 frog"));
- // Real right-padded
+ // Real right-padded.
format = "fish %-11f frog";
args.clear();
args.push_back(99.99);
@@ -769,7 +769,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
CHECK(output == String("fish +99.990000 frog"));
- // Real with 1 decimals.
+ // Real with 1 decimal.
format = "fish %.1f frog";
args.clear();
args.push_back(99.99);
@@ -803,7 +803,97 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
CHECK(output == String("fish -99.990000 frog"));
- /////// Strings.
+ ///// Vectors
+
+ // Vector2
+ format = "fish %v frog";
+ args.clear();
+ args.push_back(Variant(Vector2(19.99, 1.00)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (19.990000, 1.000000) frog"));
+
+ // Vector3
+ format = "fish %v frog";
+ args.clear();
+ args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (19.990000, 1.000000, -2.050000) frog"));
+
+ // Vector4
+ format = "fish %v frog";
+ args.clear();
+ args.push_back(Variant(Vector4(19.99, 1.00, -2.05, 5.5)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (19.990000, 1.000000, -2.050000, 5.500000) frog"));
+
+ // Vector with negative values.
+ format = "fish %v frog";
+ args.clear();
+ args.push_back(Variant(Vector2(-19.99, -1.00)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (-19.990000, -1.000000) frog"));
+
+ // Vector left-padded.
+ format = "fish %11v frog";
+ args.clear();
+ args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish ( 19.990000, 1.000000, -2.050000) frog"));
+
+ // Vector right-padded.
+ format = "fish %-11v frog";
+ args.clear();
+ args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (19.990000 , 1.000000 , -2.050000 ) frog"));
+
+ // Vector left-padded with zeros.
+ format = "fish %011v frog";
+ args.clear();
+ args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (0019.990000, 0001.000000, -002.050000) frog"));
+
+ // Vector given Vector3i.
+ format = "fish %v frog";
+ args.clear();
+ args.push_back(Variant(Vector3i(19, 1, -2)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (19.000000, 1.000000, -2.000000) frog"));
+
+ // Vector with 1 decimal.
+ format = "fish %.1v frog";
+ args.clear();
+ args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (20.0, 1.0, -2.0) frog"));
+
+ // Vector with 12 decimals.
+ format = "fish %.12v frog";
+ args.clear();
+ args.push_back(Variant(Vector3(19.00, 1.00, -2.00)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (19.000000000000, 1.000000000000, -2.000000000000) frog"));
+
+ // Vector with no decimals.
+ format = "fish %.v frog";
+ args.clear();
+ args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
+ output = format.sprintf(args, &error);
+ REQUIRE(error == false);
+ CHECK(output == String("fish (20, 1, -2) frog"));
+
+ ///// Strings
// String
format = "fish %s frog";
@@ -813,7 +903,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
CHECK(output == String("fish cheese frog"));
- // String left-padded
+ // String left-padded.
format = "fish %10s frog";
args.clear();
args.push_back("cheese");
@@ -821,7 +911,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
CHECK(output == String("fish cheese frog"));
- // String right-padded
+ // String right-padded.
format = "fish %-10s frog";
args.clear();
args.push_back("cheese");
@@ -849,7 +939,7 @@ TEST_CASE("[String] sprintf") {
///// Dynamic width
- // String dynamic width
+ // String dynamic width.
format = "fish %*s frog";
args.clear();
args.push_back(10);
@@ -858,7 +948,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
REQUIRE(output == String("fish cheese frog"));
- // Int dynamic width
+ // Int dynamic width.
format = "fish %*d frog";
args.clear();
args.push_back(10);
@@ -867,7 +957,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error == false);
REQUIRE(output == String("fish 99 frog"));
- // Float dynamic width
+ // Float dynamic width.
format = "fish %*.*f frog";
args.clear();
args.push_back(10);
@@ -904,7 +994,7 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error);
CHECK(output == "incomplete format");
- // Bad character in format string
+ // Bad character in format string.
format = "fish %&f frog";
args.clear();
args.push_back("cheese");
@@ -920,14 +1010,14 @@ TEST_CASE("[String] sprintf") {
REQUIRE(error);
CHECK(output == "too many decimal points in format");
- // * not a number
+ // * not a number or vector.
format = "fish %*f frog";
args.clear();
args.push_back("cheese");
args.push_back(99.99);
output = format.sprintf(args, &error);
REQUIRE(error);
- CHECK(output == "* wants number");
+ CHECK(output == "* wants number or vector");
// Character too long.
format = "fish %c frog";
diff --git a/tests/create_test.py b/tests/create_test.py
new file mode 100644
index 0000000000..5a0439084f
--- /dev/null
+++ b/tests/create_test.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python3
+
+import argparse
+import os
+import re
+import sys
+from subprocess import call
+
+
+def main():
+ # Change to the directory where the script is located,
+ # so that the script can be run from any location.
+ os.chdir(os.path.dirname(os.path.realpath(__file__)))
+
+ parser = argparse.ArgumentParser(description="Creates a new unit test file.")
+ parser.add_argument("name", type=str, help="The unit test name in PascalCase notation")
+ parser.add_argument(
+ "path",
+ type=str,
+ nargs="?",
+ help="The path to the unit test file relative to the tests folder (default: .)",
+ default=".",
+ )
+ parser.add_argument(
+ "-i",
+ "--invasive",
+ action="store_true",
+ help="if set, the script will automatically insert the include directive in test_main.cpp. Use with caution!",
+ )
+ args = parser.parse_args()
+
+ snake_case_regex = re.compile(r"(?<!^)(?=[A-Z])")
+ name_snake_case = snake_case_regex.sub("_", args.name).lower()
+
+ file_path = os.path.normpath(os.path.join(args.path, f"test_{name_snake_case}.h"))
+
+ print(file_path)
+ if os.path.isfile(file_path):
+ print(f'ERROR: The file "{file_path}" already exists.')
+ sys.exit(1)
+ with open(file_path, "w") as file:
+ file.write(
+ """/*************************************************************************/
+/* test_{name_snake_case}.h {padding} */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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_{name_upper_snake_case}_H
+#define TEST_{name_upper_snake_case}_H
+
+#include "tests/test_macros.h"
+
+namespace Test{name_pascal_case} {{
+
+TEST_CASE("[{name_pascal_case}] Example test case") {{
+ // TODO: Remove this comment and write your test code here.
+}}
+
+}} // namespace Test{name_pascal_case}
+
+#endif // TEST_{name_upper_snake_case}_H
+""".format(
+ name_snake_case=name_snake_case,
+ # Capitalize the first letter but keep capitalization for the rest of the string.
+ # This is done in case the user passes a camelCase string instead of PascalCase.
+ name_pascal_case=args.name[0].upper() + args.name[1:],
+ name_upper_snake_case=name_snake_case.upper(),
+ # The padding length depends on the test name length.
+ padding=" " * (60 - len(name_snake_case)),
+ )
+ )
+
+ # Print an absolute path so it can be Ctrl + clicked in some IDEs and terminal emulators.
+ print("Test header file created:")
+ print(os.path.abspath(file_path))
+
+ if args.invasive:
+ print("Trying to insert include directive in test_main.cpp...")
+ with open("test_main.cpp", "r") as file:
+ contents = file.read()
+ match = re.search(r'#include "tests.*\n', contents)
+
+ if match:
+ new_string = contents[: match.start()] + f'#include "tests/{file_path}"\n' + contents[match.start() :]
+
+ with open("test_main.cpp", "w") as file:
+ file.write(new_string)
+ print("Done.")
+ # Use clang format to sort include directives afster insertion.
+ clang_format_args = ["clang-format", "test_main.cpp", "-i"]
+ retcode = call(clang_format_args)
+ if retcode != 0:
+ print(
+ "Include directives in test_main.cpp could not be sorted automatically using clang-format. Please sort them manually."
+ )
+ else:
+ print("Could not find a valid position in test_main.cpp to insert the include directive.")
+
+ else:
+ print("\nRemember to #include the new test header in this file (following alphabetical order):")
+ print(os.path.abspath("test_main.cpp"))
+ print("Insert the following line in the appropriate place:")
+ print(f'#include "tests/{file_path}"')
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/python_build/conftest.py b/tests/python_build/conftest.py
new file mode 100644
index 0000000000..617230926a
--- /dev/null
+++ b/tests/python_build/conftest.py
@@ -0,0 +1,26 @@
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+CWD = Path(__file__).parent
+ROOT = CWD.parent.parent
+# append directory with build files to sys.path to import them
+sys.path.append(str(ROOT))
+
+
+@pytest.fixture
+def shader_files(request):
+ shader_path = request.param
+
+ res = {
+ "path_input": str(CWD / "fixtures" / f"{shader_path}.glsl"),
+ "path_output": str(CWD / "fixtures" / f"{shader_path}.glsl.gen.h"),
+ "path_expected_full": str(CWD / "fixtures" / f"{shader_path}_expected_full.glsl"),
+ "path_expected_parts": str(CWD / "fixtures" / f"{shader_path}_expected_parts.json"),
+ }
+ yield res
+
+ if not os.getenv("PYTEST_KEEP_GENERATED_FILES"):
+ os.remove(res["path_output"])
diff --git a/tests/python_build/fixtures/gles3/_included.glsl b/tests/python_build/fixtures/gles3/_included.glsl
new file mode 100644
index 0000000000..adf5f702d3
--- /dev/null
+++ b/tests/python_build/fixtures/gles3/_included.glsl
@@ -0,0 +1 @@
+#define M_PI 3.14159265359
diff --git a/tests/python_build/fixtures/gles3/vertex_fragment.glsl b/tests/python_build/fixtures/gles3/vertex_fragment.glsl
new file mode 100644
index 0000000000..3004e22f25
--- /dev/null
+++ b/tests/python_build/fixtures/gles3/vertex_fragment.glsl
@@ -0,0 +1,34 @@
+#include "_included.glsl"
+
+#[modes]
+
+mode_ninepatch = #define USE_NINEPATCH
+
+#[specializations]
+
+DISABLE_LIGHTING = false
+
+#[vertex]
+
+precision highp float;
+precision highp int;
+
+layout(location = 0) in highp vec3 vertex;
+
+out highp vec4 position_interp;
+
+void main() {
+ position_interp = vec4(vertex.x,1,0,1);
+}
+
+#[fragment]
+
+precision highp float;
+precision highp int;
+
+in highp vec4 position_interp;
+
+void main() {
+ highp float depth = ((position_interp.z / position_interp.w) + 1.0);
+ frag_color = vec4(depth);
+}
diff --git a/tests/python_build/fixtures/gles3/vertex_fragment_expected_full.glsl b/tests/python_build/fixtures/gles3/vertex_fragment_expected_full.glsl
new file mode 100644
index 0000000000..7bf56e73cd
--- /dev/null
+++ b/tests/python_build/fixtures/gles3/vertex_fragment_expected_full.glsl
@@ -0,0 +1,50 @@
+/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
+#ifndef VERTEX_FRAGMENT_GLSL_GEN_HGLES3_GLES3
+#define VERTEX_FRAGMENT_GLSL_GEN_HGLES3_GLES3
+
+
+#include "drivers/gles3/shader_gles3.h"
+
+
+class VertexFragmentShaderGLES3 : public ShaderGLES3 {
+
+public:
+
+ enum ShaderVariant {
+ MODE_NINEPATCH,
+ };
+
+ enum Specializations {
+ DISABLE_LIGHTING=1,
+ };
+
+ _FORCE_INLINE_ void version_bind_shader(RID p_version,ShaderVariant p_variant,uint64_t p_specialization=0) { _version_bind_shader(p_version,p_variant,p_specialization); }
+
+protected:
+
+ virtual void _init() override {
+
+ static const char **_uniform_strings=nullptr;
+ static const char* _variant_defines[]={
+ "#define USE_NINEPATCH",
+ };
+
+ static TexUnitPair *_texunit_pairs=nullptr;
+ static UBOPair *_ubo_pairs=nullptr;
+ static Specialization _spec_pairs[]={
+ {"DISABLE_LIGHTING",false},
+ };
+
+ static const char _vertex_code[]={
+10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,102,108,111,97,116,59,10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,105,110,116,59,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,105,110,32,104,105,103,104,112,32,118,101,99,51,32,118,101,114,116,101,120,59,10,10,111,117,116,32,104,105,103,104,112,32,118,101,99,52,32,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,32,61,32,118,101,99,52,40,118,101,114,116,101,120,46,120,44,49,44,48,44,49,41,59,10,125,10,10, 0};
+
+ static const char _fragment_code[]={
+10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,102,108,111,97,116,59,10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,105,110,116,59,10,10,105,110,32,104,105,103,104,112,32,118,101,99,52,32,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,104,105,103,104,112,32,102,108,111,97,116,32,100,101,112,116,104,32,61,32,40,40,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,46,122,32,47,32,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,46,119,41,32,43,32,49,46,48,41,59,10,9,102,114,97,103,95,99,111,108,111,114,32,61,32,118,101,99,52,40,100,101,112,116,104,41,59,10,125,10, 0};
+
+ _setup(_vertex_code,_fragment_code,"VertexFragmentShaderGLES3",0,_uniform_strings,0,_ubo_pairs,0,_texunit_pairs,1,_spec_pairs,1,_variant_defines);
+ }
+
+};
+
+#endif
+
diff --git a/tests/python_build/fixtures/gles3/vertex_fragment_expected_parts.json b/tests/python_build/fixtures/gles3/vertex_fragment_expected_parts.json
new file mode 100644
index 0000000000..eaeb5981c0
--- /dev/null
+++ b/tests/python_build/fixtures/gles3/vertex_fragment_expected_parts.json
@@ -0,0 +1,52 @@
+{
+ "vertex_lines": [
+ "",
+ "precision highp float;",
+ "precision highp int;",
+ "",
+ "layout(location = 0) in highp vec3 vertex;",
+ "",
+ "out highp vec4 position_interp;",
+ "",
+ "void main() {",
+ "\tposition_interp = vec4(vertex.x,1,0,1);",
+ "}",
+ ""
+ ],
+ "fragment_lines": [
+ "",
+ "precision highp float;",
+ "precision highp int;",
+ "",
+ "in highp vec4 position_interp;",
+ "",
+ "void main() {",
+ "\thighp float depth = ((position_interp.z / position_interp.w) + 1.0);",
+ "\tfrag_color = vec4(depth);",
+ "}"
+ ],
+ "uniforms": [],
+ "fbos": [],
+ "texunits": [],
+ "texunit_names": [],
+ "ubos": [],
+ "ubo_names": [],
+ "vertex_included_files": [],
+ "fragment_included_files": [],
+ "reading": "fragment",
+ "line_offset": 33,
+ "vertex_offset": 10,
+ "fragment_offset": 23,
+ "variant_defines": [
+ "#define USE_NINEPATCH"
+ ],
+ "variant_names": [
+ "MODE_NINEPATCH"
+ ],
+ "specialization_names": [
+ "DISABLE_LIGHTING"
+ ],
+ "specialization_values": [
+ " false\n"
+ ]
+}
diff --git a/tests/python_build/fixtures/glsl/_included.glsl b/tests/python_build/fixtures/glsl/_included.glsl
new file mode 100644
index 0000000000..adf5f702d3
--- /dev/null
+++ b/tests/python_build/fixtures/glsl/_included.glsl
@@ -0,0 +1 @@
+#define M_PI 3.14159265359
diff --git a/tests/python_build/fixtures/glsl/compute.glsl b/tests/python_build/fixtures/glsl/compute.glsl
new file mode 100644
index 0000000000..e81f48d463
--- /dev/null
+++ b/tests/python_build/fixtures/glsl/compute.glsl
@@ -0,0 +1,12 @@
+#[compute]
+
+#version 450
+
+#VERSION_DEFINES
+
+
+#include "_included.glsl"
+
+void main() {
+ vec3 static_light = vec3(0, 1, 0);
+}
diff --git a/tests/python_build/fixtures/glsl/compute_expected_full.glsl b/tests/python_build/fixtures/glsl/compute_expected_full.glsl
new file mode 100644
index 0000000000..b937d732c8
--- /dev/null
+++ b/tests/python_build/fixtures/glsl/compute_expected_full.glsl
@@ -0,0 +1,8 @@
+/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
+#ifndef COMPUTE_SHADER_GLSL_RAW_H
+#define COMPUTE_SHADER_GLSL_RAW_H
+
+static const char compute_shader_glsl[] = {
+ 35,91,99,111,109,112,117,116,101,93,10,10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,118,101,99,51,32,115,116,97,116,105,99,95,108,105,103,104,116,32,61,32,118,101,99,51,40,48,44,32,49,44,32,48,41,59,10,125,10,0
+};
+#endif
diff --git a/tests/python_build/fixtures/glsl/compute_expected_parts.json b/tests/python_build/fixtures/glsl/compute_expected_parts.json
new file mode 100644
index 0000000000..025c568ae0
--- /dev/null
+++ b/tests/python_build/fixtures/glsl/compute_expected_parts.json
@@ -0,0 +1,3 @@
+{
+ "code": "#[compute]\n\n#version 450\n\n#VERSION_DEFINES\n\n\n#define M_PI 3.14159265359\n\nvoid main() {\n\tvec3 static_light = vec3(0, 1, 0);\n}\n"
+}
diff --git a/tests/python_build/fixtures/glsl/vertex_fragment.glsl b/tests/python_build/fixtures/glsl/vertex_fragment.glsl
new file mode 100644
index 0000000000..0bdce783d7
--- /dev/null
+++ b/tests/python_build/fixtures/glsl/vertex_fragment.glsl
@@ -0,0 +1,32 @@
+#[versions]
+
+lines = "#define MODE_LINES";
+
+#[vertex]
+
+#version 450
+
+#VERSION_DEFINES
+
+layout(location = 0) out vec3 uv_interp;
+
+void main() {
+
+#ifdef MODE_LINES
+ uv_interp = vec3(0,0,1);
+#endif
+}
+
+#[fragment]
+
+#version 450
+
+#VERSION_DEFINES
+
+#include "_included.glsl"
+
+layout(location = 0) out vec4 dst_color;
+
+void main() {
+ dst_color = vec4(1,1,0,0);
+}
diff --git a/tests/python_build/fixtures/glsl/vertex_fragment_expected_full.glsl b/tests/python_build/fixtures/glsl/vertex_fragment_expected_full.glsl
new file mode 100644
index 0000000000..3f53a17fac
--- /dev/null
+++ b/tests/python_build/fixtures/glsl/vertex_fragment_expected_full.glsl
@@ -0,0 +1,8 @@
+/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
+#ifndef VERTEX_FRAGMENT_SHADER_GLSL_RAW_H
+#define VERTEX_FRAGMENT_SHADER_GLSL_RAW_H
+
+static const char vertex_fragment_shader_glsl[] = {
+ 35,91,118,101,114,115,105,111,110,115,93,10,10,108,105,110,101,115,32,61,32,34,35,100,101,102,105,110,101,32,77,79,68,69,95,76,73,78,69,83,34,59,10,10,35,91,118,101,114,116,101,120,93,10,10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,111,117,116,32,118,101,99,51,32,117,118,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,10,35,105,102,100,101,102,32,77,79,68,69,95,76,73,78,69,83,10,9,117,118,95,105,110,116,101,114,112,32,61,32,118,101,99,51,40,48,44,48,44,49,41,59,10,35,101,110,100,105,102,10,125,10,10,35,91,102,114,97,103,109,101,110,116,93,10,10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,111,117,116,32,118,101,99,52,32,100,115,116,95,99,111,108,111,114,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,100,115,116,95,99,111,108,111,114,32,61,32,118,101,99,52,40,49,44,49,44,48,44,48,41,59,10,125,10,0
+};
+#endif
diff --git a/tests/python_build/fixtures/glsl/vertex_fragment_expected_parts.json b/tests/python_build/fixtures/glsl/vertex_fragment_expected_parts.json
new file mode 100644
index 0000000000..38312367a0
--- /dev/null
+++ b/tests/python_build/fixtures/glsl/vertex_fragment_expected_parts.json
@@ -0,0 +1,3 @@
+{
+ "code": "#[versions]\n\nlines = \"#define MODE_LINES\";\n\n#[vertex]\n\n#version 450\n\n#VERSION_DEFINES\n\nlayout(location = 0) out vec3 uv_interp;\n\nvoid main() {\n\n#ifdef MODE_LINES\n\tuv_interp = vec3(0,0,1);\n#endif\n}\n\n#[fragment]\n\n#version 450\n\n#VERSION_DEFINES\n\n#define M_PI 3.14159265359\n\nlayout(location = 0) out vec4 dst_color;\n\nvoid main() {\n\tdst_color = vec4(1,1,0,0);\n}\n"
+}
diff --git a/tests/python_build/fixtures/rd_glsl/_included.glsl b/tests/python_build/fixtures/rd_glsl/_included.glsl
new file mode 100644
index 0000000000..adf5f702d3
--- /dev/null
+++ b/tests/python_build/fixtures/rd_glsl/_included.glsl
@@ -0,0 +1 @@
+#define M_PI 3.14159265359
diff --git a/tests/python_build/fixtures/rd_glsl/compute.glsl b/tests/python_build/fixtures/rd_glsl/compute.glsl
new file mode 100644
index 0000000000..66fbbeb401
--- /dev/null
+++ b/tests/python_build/fixtures/rd_glsl/compute.glsl
@@ -0,0 +1,13 @@
+#[compute]
+
+#version 450
+
+#VERSION_DEFINES
+
+#define BLOCK_SIZE 8
+
+#include "_included.glsl"
+
+void main() {
+ uint t = BLOCK_SIZE + 1;
+}
diff --git a/tests/python_build/fixtures/rd_glsl/compute_expected_full.glsl b/tests/python_build/fixtures/rd_glsl/compute_expected_full.glsl
new file mode 100644
index 0000000000..b59923e28a
--- /dev/null
+++ b/tests/python_build/fixtures/rd_glsl/compute_expected_full.glsl
@@ -0,0 +1,20 @@
+/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
+#ifndef COMPUTE_GLSL_GEN_H_RD
+#define COMPUTE_GLSL_GEN_H_RD
+
+#include "servers/rendering/renderer_rd/shader_rd.h"
+
+class ComputeShaderRD : public ShaderRD {
+
+public:
+
+ ComputeShaderRD() {
+
+ static const char _compute_code[] = {
+10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,35,100,101,102,105,110,101,32,66,76,79,67,75,95,83,73,90,69,32,56,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,117,105,110,116,32,116,32,61,32,66,76,79,67,75,95,83,73,90,69,32,43,32,49,59,10,125,10,0
+ };
+ setup(nullptr, nullptr, _compute_code, "ComputeShaderRD");
+ }
+};
+
+#endif
diff --git a/tests/python_build/fixtures/rd_glsl/compute_expected_parts.json b/tests/python_build/fixtures/rd_glsl/compute_expected_parts.json
new file mode 100644
index 0000000000..26ba9e4fc4
--- /dev/null
+++ b/tests/python_build/fixtures/rd_glsl/compute_expected_parts.json
@@ -0,0 +1,28 @@
+{
+ "vertex_lines": [],
+ "fragment_lines": [],
+ "compute_lines": [
+ "",
+ "#version 450",
+ "",
+ "#VERSION_DEFINES",
+ "",
+ "#define BLOCK_SIZE 8",
+ "",
+ "#define M_PI 3.14159265359",
+ "",
+ "void main() {",
+ "\tuint t = BLOCK_SIZE + 1;",
+ "}"
+ ],
+ "vertex_included_files": [],
+ "fragment_included_files": [],
+ "compute_included_files": [
+ "tests/python_build/fixtures/rd_glsl/_included.glsl"
+ ],
+ "reading": "compute",
+ "line_offset": 13,
+ "vertex_offset": 0,
+ "fragment_offset": 0,
+ "compute_offset": 1
+}
diff --git a/tests/python_build/fixtures/rd_glsl/vertex_fragment.glsl b/tests/python_build/fixtures/rd_glsl/vertex_fragment.glsl
new file mode 100644
index 0000000000..27be08a857
--- /dev/null
+++ b/tests/python_build/fixtures/rd_glsl/vertex_fragment.glsl
@@ -0,0 +1,25 @@
+#[vertex]
+
+#version 450
+
+#VERSION_DEFINES
+
+#include "_included.glsl"
+
+layout(location = 0) out vec2 uv_interp;
+
+void main() {
+ uv_interp = vec2(0, 1);
+}
+
+#[fragment]
+
+#version 450
+
+#VERSION_DEFINES
+
+layout(location = 0) in vec2 uv_interp;
+
+void main() {
+ uv_interp = vec2(1, 0);
+}
diff --git a/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_full.glsl b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_full.glsl
new file mode 100644
index 0000000000..ff804dbf89
--- /dev/null
+++ b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_full.glsl
@@ -0,0 +1,23 @@
+/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
+#ifndef VERTEX_FRAGMENT_GLSL_GEN_H_RD
+#define VERTEX_FRAGMENT_GLSL_GEN_H_RD
+
+#include "servers/rendering/renderer_rd/shader_rd.h"
+
+class VertexFragmentShaderRD : public ShaderRD {
+
+public:
+
+ VertexFragmentShaderRD() {
+
+ static const char _vertex_code[] = {
+10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,111,117,116,32,118,101,99,50,32,117,118,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,117,118,95,105,110,116,101,114,112,32,61,32,118,101,99,50,40,48,44,32,49,41,59,10,125,10,10,0
+ };
+ static const char _fragment_code[] = {
+10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,105,110,32,118,101,99,50,32,117,118,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,117,118,95,105,110,116,101,114,112,32,61,32,118,101,99,50,40,49,44,32,48,41,59,10,125,10,0
+ };
+ setup(_vertex_code, _fragment_code, nullptr, "VertexFragmentShaderRD");
+ }
+};
+
+#endif
diff --git a/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_parts.json b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_parts.json
new file mode 100644
index 0000000000..dbf833edea
--- /dev/null
+++ b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_parts.json
@@ -0,0 +1,40 @@
+{
+ "vertex_lines": [
+ "",
+ "#version 450",
+ "",
+ "#VERSION_DEFINES",
+ "",
+ "#define M_PI 3.14159265359",
+ "",
+ "layout(location = 0) out vec2 uv_interp;",
+ "",
+ "void main() {",
+ "\tuv_interp = vec2(0, 1);",
+ "}",
+ ""
+ ],
+ "fragment_lines": [
+ "",
+ "#version 450",
+ "",
+ "#VERSION_DEFINES",
+ "",
+ "layout(location = 0) in vec2 uv_interp;",
+ "",
+ "void main() {",
+ "\tuv_interp = vec2(1, 0);",
+ "}"
+ ],
+ "compute_lines": [],
+ "vertex_included_files": [
+ "tests/python_build/fixtures/rd_glsl/_included.glsl"
+ ],
+ "fragment_included_files": [],
+ "compute_included_files": [],
+ "reading": "fragment",
+ "line_offset": 25,
+ "vertex_offset": 1,
+ "fragment_offset": 15,
+ "compute_offset": 0
+}
diff --git a/tests/python_build/test_gles3_builder.py b/tests/python_build/test_gles3_builder.py
new file mode 100644
index 0000000000..861e0b84c4
--- /dev/null
+++ b/tests/python_build/test_gles3_builder.py
@@ -0,0 +1,31 @@
+import json
+
+import pytest
+
+from gles3_builders import build_gles3_header, GLES3HeaderStruct
+
+
+@pytest.mark.parametrize(
+ ["shader_files", "builder", "header_struct"],
+ [
+ ("gles3/vertex_fragment", build_gles3_header, GLES3HeaderStruct),
+ ],
+ indirect=["shader_files"],
+)
+def test_gles3_builder(shader_files, builder, header_struct):
+ header = header_struct()
+
+ builder(shader_files["path_input"], "drivers/gles3/shader_gles3.h", "GLES3", header_data=header)
+
+ with open(shader_files["path_expected_parts"], "r") as f:
+ expected_parts = json.load(f)
+ assert expected_parts == header.__dict__
+
+ with open(shader_files["path_output"], "r") as f:
+ actual_output = f.read()
+ assert actual_output
+
+ with open(shader_files["path_expected_full"], "r") as f:
+ expected_output = f.read()
+
+ assert actual_output == expected_output
diff --git a/tests/python_build/test_glsl_builder.py b/tests/python_build/test_glsl_builder.py
new file mode 100644
index 0000000000..b9dcef48ac
--- /dev/null
+++ b/tests/python_build/test_glsl_builder.py
@@ -0,0 +1,37 @@
+import json
+
+import pytest
+
+from glsl_builders import build_raw_header, RAWHeaderStruct, build_rd_header, RDHeaderStruct
+
+
+@pytest.mark.parametrize(
+ [
+ "shader_files",
+ "builder",
+ "header_struct",
+ ],
+ [
+ ("glsl/vertex_fragment", build_raw_header, RAWHeaderStruct),
+ ("glsl/compute", build_raw_header, RAWHeaderStruct),
+ ("rd_glsl/vertex_fragment", build_rd_header, RDHeaderStruct),
+ ("rd_glsl/compute", build_rd_header, RDHeaderStruct),
+ ],
+ indirect=["shader_files"],
+)
+def test_glsl_builder(shader_files, builder, header_struct):
+ header = header_struct()
+ builder(shader_files["path_input"], header_data=header)
+
+ with open(shader_files["path_expected_parts"], "r") as f:
+ expected_parts = json.load(f)
+ assert expected_parts == header.__dict__
+
+ with open(shader_files["path_output"], "r") as f:
+ actual_output = f.read()
+ assert actual_output
+
+ with open(shader_files["path_expected_full"], "r") as f:
+ expected_output = f.read()
+
+ assert actual_output == expected_output
diff --git a/tests/scene/test_code_edit.h b/tests/scene/test_code_edit.h
index 7605f24cf8..4fc88f398f 100644
--- a/tests/scene/test_code_edit.h
+++ b/tests/scene/test_code_edit.h
@@ -74,7 +74,7 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") {
code_edit->set_line_as_breakpoint(0, true);
CHECK(code_edit->is_line_breakpointed(0));
- CHECK(code_edit->get_breakpointed_lines()[0] == Variant(0));
+ CHECK(code_edit->get_breakpointed_lines()[0] == 0);
SIGNAL_CHECK("breakpoint_toggled", args);
code_edit->set_line_as_breakpoint(0, false);
@@ -451,7 +451,7 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") {
ERR_PRINT_ON;
code_edit->set_line_as_bookmarked(0, true);
- CHECK(code_edit->get_bookmarked_lines()[0] == Variant(0));
+ CHECK(code_edit->get_bookmarked_lines()[0] == 0);
CHECK(code_edit->is_line_bookmarked(0));
code_edit->set_line_as_bookmarked(0, false);
@@ -657,7 +657,7 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") {
ERR_PRINT_ON;
code_edit->set_line_as_executing(0, true);
- CHECK(code_edit->get_executing_lines()[0] == Variant(0));
+ CHECK(code_edit->get_executing_lines()[0] == 0);
CHECK(code_edit->is_line_executing(0));
code_edit->set_line_as_executing(0, false);
diff --git a/tests/scene/test_path_follow_2d.h b/tests/scene/test_path_follow_2d.h
index abd12fe862..57261116a2 100644
--- a/tests/scene/test_path_follow_2d.h
+++ b/tests/scene/test_path_follow_2d.h
@@ -37,7 +37,7 @@
namespace TestPathFollow2D {
-TEST_CASE("[PathFollow2D] Sampling with unit offset") {
+TEST_CASE("[PathFollow2D] Sampling with progress ratio") {
const Ref<Curve2D> &curve = memnew(Curve2D());
curve->add_point(Vector2(0, 0));
curve->add_point(Vector2(100, 0));
@@ -49,37 +49,37 @@ TEST_CASE("[PathFollow2D] Sampling with unit offset") {
const PathFollow2D *path_follow_2d = memnew(PathFollow2D);
path->add_child(path_follow_2d);
- path_follow_2d->set_unit_offset(0);
+ path_follow_2d->set_progress_ratio(0);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0)));
- path_follow_2d->set_unit_offset(0.125);
+ path_follow_2d->set_progress_ratio(0.125);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 0)));
- path_follow_2d->set_unit_offset(0.25);
+ path_follow_2d->set_progress_ratio(0.25);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 0)));
- path_follow_2d->set_unit_offset(0.375);
+ path_follow_2d->set_progress_ratio(0.375);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 50)));
- path_follow_2d->set_unit_offset(0.5);
+ path_follow_2d->set_progress_ratio(0.5);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 100)));
- path_follow_2d->set_unit_offset(0.625);
+ path_follow_2d->set_progress_ratio(0.625);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 100)));
- path_follow_2d->set_unit_offset(0.75);
+ path_follow_2d->set_progress_ratio(0.75);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 100)));
- path_follow_2d->set_unit_offset(0.875);
+ path_follow_2d->set_progress_ratio(0.875);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 50)));
- path_follow_2d->set_unit_offset(1);
+ path_follow_2d->set_progress_ratio(1);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0)));
memdelete(path);
}
-TEST_CASE("[PathFollow2D] Sampling with offset") {
+TEST_CASE("[PathFollow2D] Sampling with progress") {
const Ref<Curve2D> &curve = memnew(Curve2D());
curve->add_point(Vector2(0, 0));
curve->add_point(Vector2(100, 0));
@@ -91,31 +91,31 @@ TEST_CASE("[PathFollow2D] Sampling with offset") {
const PathFollow2D *path_follow_2d = memnew(PathFollow2D);
path->add_child(path_follow_2d);
- path_follow_2d->set_offset(0);
+ path_follow_2d->set_progress(0);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0)));
- path_follow_2d->set_offset(50);
+ path_follow_2d->set_progress(50);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 0)));
- path_follow_2d->set_offset(100);
+ path_follow_2d->set_progress(100);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 0)));
- path_follow_2d->set_offset(150);
+ path_follow_2d->set_progress(150);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 50)));
- path_follow_2d->set_offset(200);
+ path_follow_2d->set_progress(200);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 100)));
- path_follow_2d->set_offset(250);
+ path_follow_2d->set_progress(250);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 100)));
- path_follow_2d->set_offset(300);
+ path_follow_2d->set_progress(300);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 100)));
- path_follow_2d->set_offset(350);
+ path_follow_2d->set_progress(350);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 50)));
- path_follow_2d->set_offset(400);
+ path_follow_2d->set_progress(400);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0)));
memdelete(path);
@@ -131,7 +131,7 @@ TEST_CASE("[PathFollow2D] Removal of a point in curve") {
const PathFollow2D *path_follow_2d = memnew(PathFollow2D);
path->add_child(path_follow_2d);
- path_follow_2d->set_unit_offset(0.5);
+ path_follow_2d->set_progress_ratio(0.5);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 0)));
curve->remove_point(1);
@@ -152,7 +152,7 @@ TEST_CASE("[PathFollow2D] Setting h_offset and v_offset") {
const PathFollow2D *path_follow_2d = memnew(PathFollow2D);
path->add_child(path_follow_2d);
- path_follow_2d->set_unit_offset(0.5);
+ path_follow_2d->set_progress_ratio(0.5);
CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 0)));
path_follow_2d->set_h_offset(25);
@@ -175,32 +175,32 @@ TEST_CASE("[PathFollow2D] Unit offset out of range") {
path_follow_2d->set_loop(true);
- path_follow_2d->set_unit_offset(-0.3);
+ path_follow_2d->set_progress_ratio(-0.3);
CHECK_MESSAGE(
- path_follow_2d->get_unit_offset() == 0.7,
- "Unit Offset should loop back from the end in the opposite direction");
+ path_follow_2d->get_progress_ratio() == 0.7,
+ "Progress Ratio should loop back from the end in the opposite direction");
- path_follow_2d->set_unit_offset(1.3);
+ path_follow_2d->set_progress_ratio(1.3);
CHECK_MESSAGE(
- path_follow_2d->get_unit_offset() == 0.3,
- "Unit Offset should loop back from the end in the opposite direction");
+ path_follow_2d->get_progress_ratio() == 0.3,
+ "Progress Ratio should loop back from the end in the opposite direction");
path_follow_2d->set_loop(false);
- path_follow_2d->set_unit_offset(-0.3);
+ path_follow_2d->set_progress_ratio(-0.3);
CHECK_MESSAGE(
- path_follow_2d->get_unit_offset() == 0,
- "Unit Offset should be clamped at 0");
+ path_follow_2d->get_progress_ratio() == 0,
+ "Progress Ratio should be clamped at 0");
- path_follow_2d->set_unit_offset(1.3);
+ path_follow_2d->set_progress_ratio(1.3);
CHECK_MESSAGE(
- path_follow_2d->get_unit_offset() == 1,
- "Unit Offset should be clamped at 1");
+ path_follow_2d->get_progress_ratio() == 1,
+ "Progress Ratio should be clamped at 1");
memdelete(path);
}
-TEST_CASE("[PathFollow2D] Offset out of range") {
+TEST_CASE("[PathFollow2D] Progress out of range") {
const Ref<Curve2D> &curve = memnew(Curve2D());
curve->add_point(Vector2(0, 0));
curve->add_point(Vector2(100, 0));
@@ -211,27 +211,27 @@ TEST_CASE("[PathFollow2D] Offset out of range") {
path_follow_2d->set_loop(true);
- path_follow_2d->set_offset(-50);
+ path_follow_2d->set_progress(-50);
CHECK_MESSAGE(
- path_follow_2d->get_offset() == 50,
- "Offset should loop back from the end in the opposite direction");
+ path_follow_2d->get_progress() == 50,
+ "Progress should loop back from the end in the opposite direction");
- path_follow_2d->set_offset(150);
+ path_follow_2d->set_progress(150);
CHECK_MESSAGE(
- path_follow_2d->get_offset() == 50,
- "Offset should loop back from the end in the opposite direction");
+ path_follow_2d->get_progress() == 50,
+ "Progress should loop back from the end in the opposite direction");
path_follow_2d->set_loop(false);
- path_follow_2d->set_offset(-50);
+ path_follow_2d->set_progress(-50);
CHECK_MESSAGE(
- path_follow_2d->get_offset() == 0,
- "Offset should be clamped at 0");
+ path_follow_2d->get_progress() == 0,
+ "Progress should be clamped at 0");
- path_follow_2d->set_offset(150);
+ path_follow_2d->set_progress(150);
CHECK_MESSAGE(
- path_follow_2d->get_offset() == 100,
- "Offset should be clamped at 1");
+ path_follow_2d->get_progress() == 100,
+ "Progress should be clamped at 1");
memdelete(path);
}
diff --git a/tests/scene/test_path_follow_3d.h b/tests/scene/test_path_follow_3d.h
index 9ffe49e3d6..6334fa56de 100644
--- a/tests/scene/test_path_follow_3d.h
+++ b/tests/scene/test_path_follow_3d.h
@@ -37,7 +37,7 @@
namespace TestPathFollow3D {
-TEST_CASE("[PathFollow3D] Sampling with unit offset") {
+TEST_CASE("[PathFollow3D] Sampling with progress ratio") {
const Ref<Curve3D> &curve = memnew(Curve3D());
curve->add_point(Vector3(0, 0, 0));
curve->add_point(Vector3(100, 0, 0));
@@ -49,37 +49,37 @@ TEST_CASE("[PathFollow3D] Sampling with unit offset") {
const PathFollow3D *path_follow_3d = memnew(PathFollow3D);
path->add_child(path_follow_3d);
- path_follow_3d->set_unit_offset(0);
+ path_follow_3d->set_progress_ratio(0);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(0, 0, 0));
- path_follow_3d->set_unit_offset(0.125);
+ path_follow_3d->set_progress_ratio(0.125);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(50, 0, 0));
- path_follow_3d->set_unit_offset(0.25);
+ path_follow_3d->set_progress_ratio(0.25);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 0);
- path_follow_3d->set_unit_offset(0.375);
+ path_follow_3d->set_progress_ratio(0.375);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 0)));
- path_follow_3d->set_unit_offset(0.5);
+ path_follow_3d->set_progress_ratio(0.5);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 0)));
- path_follow_3d->set_unit_offset(0.625);
+ path_follow_3d->set_progress_ratio(0.625);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 50)));
- path_follow_3d->set_unit_offset(0.75);
+ path_follow_3d->set_progress_ratio(0.75);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 100)));
- path_follow_3d->set_unit_offset(0.875);
+ path_follow_3d->set_progress_ratio(0.875);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 100)));
- path_follow_3d->set_unit_offset(1);
+ path_follow_3d->set_progress_ratio(1);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 100)));
memdelete(path);
}
-TEST_CASE("[PathFollow3D] Sampling with offset") {
+TEST_CASE("[PathFollow3D] Sampling with progress") {
const Ref<Curve3D> &curve = memnew(Curve3D());
curve->add_point(Vector3(0, 0, 0));
curve->add_point(Vector3(100, 0, 0));
@@ -91,31 +91,31 @@ TEST_CASE("[PathFollow3D] Sampling with offset") {
const PathFollow3D *path_follow_3d = memnew(PathFollow3D);
path->add_child(path_follow_3d);
- path_follow_3d->set_offset(0);
+ path_follow_3d->set_progress(0);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(0, 0, 0));
- path_follow_3d->set_offset(50);
+ path_follow_3d->set_progress(50);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(50, 0, 0));
- path_follow_3d->set_offset(100);
+ path_follow_3d->set_progress(100);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 0);
- path_follow_3d->set_offset(150);
+ path_follow_3d->set_progress(150);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 0)));
- path_follow_3d->set_offset(200);
+ path_follow_3d->set_progress(200);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 0)));
- path_follow_3d->set_offset(250);
+ path_follow_3d->set_progress(250);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 50)));
- path_follow_3d->set_offset(300);
+ path_follow_3d->set_progress(300);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 100)));
- path_follow_3d->set_offset(350);
+ path_follow_3d->set_progress(350);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 100)));
- path_follow_3d->set_offset(400);
+ path_follow_3d->set_progress(400);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 100)));
memdelete(path);
@@ -131,7 +131,7 @@ TEST_CASE("[PathFollow3D] Removal of a point in curve") {
const PathFollow3D *path_follow_3d = memnew(PathFollow3D);
path->add_child(path_follow_3d);
- path_follow_3d->set_unit_offset(0.5);
+ path_follow_3d->set_progress_ratio(0.5);
CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector2(100, 0, 0)));
curve->remove_point(1);
@@ -143,7 +143,7 @@ TEST_CASE("[PathFollow3D] Removal of a point in curve") {
memdelete(path);
}
-TEST_CASE("[PathFollow3D] Unit offset out of range") {
+TEST_CASE("[PathFollow3D] Progress ratio out of range") {
const Ref<Curve3D> &curve = memnew(Curve3D());
curve->add_point(Vector3(0, 0, 0));
curve->add_point(Vector3(100, 0, 0));
@@ -154,32 +154,32 @@ TEST_CASE("[PathFollow3D] Unit offset out of range") {
path_follow_3d->set_loop(true);
- path_follow_3d->set_unit_offset(-0.3);
+ path_follow_3d->set_progress_ratio(-0.3);
CHECK_MESSAGE(
- path_follow_3d->get_unit_offset() == 0.7,
- "Unit Offset should loop back from the end in the opposite direction");
+ path_follow_3d->get_progress_ratio() == 0.7,
+ "Progress Ratio should loop back from the end in the opposite direction");
- path_follow_3d->set_unit_offset(1.3);
+ path_follow_3d->set_progress_ratio(1.3);
CHECK_MESSAGE(
- path_follow_3d->get_unit_offset() == 0.3,
- "Unit Offset should loop back from the end in the opposite direction");
+ path_follow_3d->get_progress_ratio() == 0.3,
+ "Progress Ratio should loop back from the end in the opposite direction");
path_follow_3d->set_loop(false);
- path_follow_3d->set_unit_offset(-0.3);
+ path_follow_3d->set_progress_ratio(-0.3);
CHECK_MESSAGE(
- path_follow_3d->get_unit_offset() == 0,
- "Unit Offset should be clamped at 0");
+ path_follow_3d->get_progress_ratio() == 0,
+ "Progress Ratio should be clamped at 0");
- path_follow_3d->set_unit_offset(1.3);
+ path_follow_3d->set_progress_ratio(1.3);
CHECK_MESSAGE(
- path_follow_3d->get_unit_offset() == 1,
- "Unit Offset should be clamped at 1");
+ path_follow_3d->get_progress_ratio() == 1,
+ "Progress Ratio should be clamped at 1");
memdelete(path);
}
-TEST_CASE("[PathFollow3D] Offset out of range") {
+TEST_CASE("[PathFollow3D] Progress out of range") {
const Ref<Curve3D> &curve = memnew(Curve3D());
curve->add_point(Vector3(0, 0, 0));
curve->add_point(Vector3(100, 0, 0));
@@ -190,27 +190,27 @@ TEST_CASE("[PathFollow3D] Offset out of range") {
path_follow_3d->set_loop(true);
- path_follow_3d->set_offset(-50);
+ path_follow_3d->set_progress(-50);
CHECK_MESSAGE(
- path_follow_3d->get_offset() == 50,
- "Offset should loop back from the end in the opposite direction");
+ path_follow_3d->get_progress() == 50,
+ "Progress should loop back from the end in the opposite direction");
- path_follow_3d->set_offset(150);
+ path_follow_3d->set_progress(150);
CHECK_MESSAGE(
- path_follow_3d->get_offset() == 50,
- "Offset should loop back from the end in the opposite direction");
+ path_follow_3d->get_progress() == 50,
+ "Progress should loop back from the end in the opposite direction");
path_follow_3d->set_loop(false);
- path_follow_3d->set_offset(-50);
+ path_follow_3d->set_progress(-50);
CHECK_MESSAGE(
- path_follow_3d->get_offset() == 0,
- "Offset should be clamped at 0");
+ path_follow_3d->get_progress() == 0,
+ "Progress should be clamped at 0");
- path_follow_3d->set_offset(150);
+ path_follow_3d->set_progress(150);
CHECK_MESSAGE(
- path_follow_3d->get_offset() == 100,
- "Offset should be clamped at max value of curve");
+ path_follow_3d->get_progress() == 100,
+ "Progress should be clamped at max value of curve");
memdelete(path);
}
diff --git a/thirdparty/README.md b/thirdparty/README.md
index 664401fca6..4514217dd8 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -195,6 +195,7 @@ Files extracted from upstream source:
to `glslang/build_info.h`
- `LICENSE.txt`
- Unnecessary files like `CMakeLists.txt`, `*.m4` and `updateGrammar` removed.
+- Patch in `patches/unused_cleanup.diff` must be applied.
## graphite
@@ -319,12 +320,12 @@ Files extracted from upstream source:
## libwebp
- Upstream: https://chromium.googlesource.com/webm/libwebp/
-- Version: 1.2.2 (b0a860891dcd4c0c2d7c6149e5cccb6eb881cc21, 2022)
+- Version: 1.2.4 (0d1f12546bd803099a60c070517a552483f3790e, 2022)
- License: BSD-3-Clause
Files extracted from upstream source:
-- `src/*` except from: `.am`, `.rc` and `.in` files
+- `src/` and `sharpyuv/` except from: `.am`, `.rc` and `.in` files
- `AUTHORS`, `COPYING`, `PATENTS`
diff --git a/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp b/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp
index 81da99c2c4..1cbd616e98 100644
--- a/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp
+++ b/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp
@@ -66,43 +66,6 @@ static void DetachThreadLinux(void *)
}
//
-// Registers cleanup handler, sets cancel type and state, and executes the thread specific
-// cleanup handler. This function will be called in the Standalone.cpp for regression
-// testing. When OpenGL applications are run with the driver code, Linux OS does the
-// thread cleanup.
-//
-void OS_CleanupThreadData(void)
-{
-#if defined(__ANDROID__) || defined(__Fuchsia__)
- DetachThreadLinux(NULL);
-#else
- int old_cancel_state, old_cancel_type;
- void *cleanupArg = NULL;
-
- //
- // Set thread cancel state and push cleanup handler.
- //
- pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancel_state);
- pthread_cleanup_push(DetachThreadLinux, (void *) cleanupArg);
-
- //
- // Put the thread in deferred cancellation mode.
- //
- pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &old_cancel_type);
-
- //
- // Pop cleanup handler and execute it prior to unregistering the cleanup handler.
- //
- pthread_cleanup_pop(1);
-
- //
- // Restore the thread's previous cancellation mode.
- //
- pthread_setcanceltype(old_cancel_state, NULL);
-#endif
-}
-
-//
// Thread Local Storage Operations
//
inline OS_TLSIndex PthreadKeyToTLSIndex(pthread_key_t key)
diff --git a/thirdparty/glslang/glslang/OSDependent/osinclude.h b/thirdparty/glslang/glslang/OSDependent/osinclude.h
index 218abe4f23..fcfeff2cc4 100644
--- a/thirdparty/glslang/glslang/OSDependent/osinclude.h
+++ b/thirdparty/glslang/glslang/OSDependent/osinclude.h
@@ -54,8 +54,6 @@ void ReleaseGlobalLock();
typedef unsigned int (*TThreadEntrypoint)(void*);
-void OS_CleanupThreadData(void);
-
void OS_DumpMemoryCounters();
} // end namespace glslang
diff --git a/thirdparty/glslang/patches/unused_cleanup.diff b/thirdparty/glslang/patches/unused_cleanup.diff
new file mode 100644
index 0000000000..3e9a9c23f9
--- /dev/null
+++ b/thirdparty/glslang/patches/unused_cleanup.diff
@@ -0,0 +1,61 @@
+diff --git a/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp b/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp
+index 81da99c2c4..1cbd616e98 100644
+--- a/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp
++++ b/thirdparty/glslang/glslang/OSDependent/Unix/ossource.cpp
+@@ -65,43 +65,6 @@ static void DetachThreadLinux(void *)
+ DetachThread();
+ }
+
+-//
+-// Registers cleanup handler, sets cancel type and state, and executes the thread specific
+-// cleanup handler. This function will be called in the Standalone.cpp for regression
+-// testing. When OpenGL applications are run with the driver code, Linux OS does the
+-// thread cleanup.
+-//
+-void OS_CleanupThreadData(void)
+-{
+-#if defined(__ANDROID__) || defined(__Fuchsia__)
+- DetachThreadLinux(NULL);
+-#else
+- int old_cancel_state, old_cancel_type;
+- void *cleanupArg = NULL;
+-
+- //
+- // Set thread cancel state and push cleanup handler.
+- //
+- pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancel_state);
+- pthread_cleanup_push(DetachThreadLinux, (void *) cleanupArg);
+-
+- //
+- // Put the thread in deferred cancellation mode.
+- //
+- pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &old_cancel_type);
+-
+- //
+- // Pop cleanup handler and execute it prior to unregistering the cleanup handler.
+- //
+- pthread_cleanup_pop(1);
+-
+- //
+- // Restore the thread's previous cancellation mode.
+- //
+- pthread_setcanceltype(old_cancel_state, NULL);
+-#endif
+-}
+-
+ //
+ // Thread Local Storage Operations
+ //
+diff --git a/thirdparty/glslang/glslang/OSDependent/osinclude.h b/thirdparty/glslang/glslang/OSDependent/osinclude.h
+index 218abe4f23..fcfeff2cc4 100644
+--- a/thirdparty/glslang/glslang/OSDependent/osinclude.h
++++ b/thirdparty/glslang/glslang/OSDependent/osinclude.h
+@@ -54,8 +54,6 @@ void ReleaseGlobalLock();
+
+ typedef unsigned int (*TThreadEntrypoint)(void*);
+
+-void OS_CleanupThreadData(void);
+-
+ void OS_DumpMemoryCounters();
+
+ } // end namespace glslang
diff --git a/thirdparty/libwebp/AUTHORS b/thirdparty/libwebp/AUTHORS
index 8307c2099d..3efcbe25b6 100644
--- a/thirdparty/libwebp/AUTHORS
+++ b/thirdparty/libwebp/AUTHORS
@@ -1,12 +1,15 @@
Contributors:
- Aidan O'Loan (aidanol at gmail dot com)
- Alan Browning (browning at google dot com)
+- Alexandru Ardelean (ardeleanalex at gmail dot com)
+- Brian Ledger (brianpl at google dot com)
- Charles Munger (clm at google dot com)
- Cheng Yi (cyi at google dot com)
- Christian Duvivier (cduvivier at google dot com)
- Christopher Degawa (ccom at randomderp dot com)
- Clement Courbet (courbet at google dot com)
- Djordje Pesut (djordje dot pesut at imgtec dot com)
+- Frank Barchard (fbarchard at google dot com)
- Hui Su (huisu at google dot com)
- Ilya Kurdyukov (jpegqs at gmail dot com)
- Ingvar Stepanyan (rreverser at google dot com)
@@ -22,6 +25,7 @@ Contributors:
- Mans Rullgard (mans at mansr dot com)
- Marcin Kowalczyk (qrczak at google dot com)
- Martin Olsson (mnemo at minimum dot se)
+- Maryla Ustarroz-Calonge (maryla at google dot com)
- Mikołaj Zalewski (mikolajz at google dot com)
- Mislav Bradac (mislavm at google dot com)
- Nico Weber (thakis at chromium dot org)
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv.c b/thirdparty/libwebp/sharpyuv/sharpyuv.c
new file mode 100644
index 0000000000..8b3ab7216b
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv.c
@@ -0,0 +1,498 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Sharp RGB to YUV conversion.
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#include "sharpyuv/sharpyuv.h"
+
+#include <assert.h>
+#include <limits.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "src/webp/types.h"
+#include "src/dsp/cpu.h"
+#include "sharpyuv/sharpyuv_dsp.h"
+#include "sharpyuv/sharpyuv_gamma.h"
+
+//------------------------------------------------------------------------------
+// Sharp RGB->YUV conversion
+
+static const int kNumIterations = 4;
+
+#define YUV_FIX 16 // fixed-point precision for RGB->YUV
+static const int kYuvHalf = 1 << (YUV_FIX - 1);
+
+// Max bit depth so that intermediate calculations fit in 16 bits.
+static const int kMaxBitDepth = 14;
+
+// Returns the precision shift to use based on the input rgb_bit_depth.
+static int GetPrecisionShift(int rgb_bit_depth) {
+ // Try to add 2 bits of precision if it fits in kMaxBitDepth. Otherwise remove
+ // bits if needed.
+ return ((rgb_bit_depth + 2) <= kMaxBitDepth) ? 2
+ : (kMaxBitDepth - rgb_bit_depth);
+}
+
+typedef int16_t fixed_t; // signed type with extra precision for UV
+typedef uint16_t fixed_y_t; // unsigned type with extra precision for W
+
+//------------------------------------------------------------------------------
+
+static uint8_t clip_8b(fixed_t v) {
+ return (!(v & ~0xff)) ? (uint8_t)v : (v < 0) ? 0u : 255u;
+}
+
+static uint16_t clip(fixed_t v, int max) {
+ return (v < 0) ? 0 : (v > max) ? max : (uint16_t)v;
+}
+
+static fixed_y_t clip_bit_depth(int y, int bit_depth) {
+ const int max = (1 << bit_depth) - 1;
+ return (!(y & ~max)) ? (fixed_y_t)y : (y < 0) ? 0 : max;
+}
+
+//------------------------------------------------------------------------------
+
+static int RGBToGray(int64_t r, int64_t g, int64_t b) {
+ const int64_t luma = 13933 * r + 46871 * g + 4732 * b + kYuvHalf;
+ return (int)(luma >> YUV_FIX);
+}
+
+static uint32_t ScaleDown(uint16_t a, uint16_t b, uint16_t c, uint16_t d,
+ int rgb_bit_depth) {
+ const int bit_depth = rgb_bit_depth + GetPrecisionShift(rgb_bit_depth);
+ const uint32_t A = SharpYuvGammaToLinear(a, bit_depth);
+ const uint32_t B = SharpYuvGammaToLinear(b, bit_depth);
+ const uint32_t C = SharpYuvGammaToLinear(c, bit_depth);
+ const uint32_t D = SharpYuvGammaToLinear(d, bit_depth);
+ return SharpYuvLinearToGamma((A + B + C + D + 2) >> 2, bit_depth);
+}
+
+static WEBP_INLINE void UpdateW(const fixed_y_t* src, fixed_y_t* dst, int w,
+ int rgb_bit_depth) {
+ const int bit_depth = rgb_bit_depth + GetPrecisionShift(rgb_bit_depth);
+ int i;
+ for (i = 0; i < w; ++i) {
+ const uint32_t R = SharpYuvGammaToLinear(src[0 * w + i], bit_depth);
+ const uint32_t G = SharpYuvGammaToLinear(src[1 * w + i], bit_depth);
+ const uint32_t B = SharpYuvGammaToLinear(src[2 * w + i], bit_depth);
+ const uint32_t Y = RGBToGray(R, G, B);
+ dst[i] = (fixed_y_t)SharpYuvLinearToGamma(Y, bit_depth);
+ }
+}
+
+static void UpdateChroma(const fixed_y_t* src1, const fixed_y_t* src2,
+ fixed_t* dst, int uv_w, int rgb_bit_depth) {
+ int i;
+ for (i = 0; i < uv_w; ++i) {
+ const int r =
+ ScaleDown(src1[0 * uv_w + 0], src1[0 * uv_w + 1], src2[0 * uv_w + 0],
+ src2[0 * uv_w + 1], rgb_bit_depth);
+ const int g =
+ ScaleDown(src1[2 * uv_w + 0], src1[2 * uv_w + 1], src2[2 * uv_w + 0],
+ src2[2 * uv_w + 1], rgb_bit_depth);
+ const int b =
+ ScaleDown(src1[4 * uv_w + 0], src1[4 * uv_w + 1], src2[4 * uv_w + 0],
+ src2[4 * uv_w + 1], rgb_bit_depth);
+ const int W = RGBToGray(r, g, b);
+ dst[0 * uv_w] = (fixed_t)(r - W);
+ dst[1 * uv_w] = (fixed_t)(g - W);
+ dst[2 * uv_w] = (fixed_t)(b - W);
+ dst += 1;
+ src1 += 2;
+ src2 += 2;
+ }
+}
+
+static void StoreGray(const fixed_y_t* rgb, fixed_y_t* y, int w) {
+ int i;
+ assert(w > 0);
+ for (i = 0; i < w; ++i) {
+ y[i] = RGBToGray(rgb[0 * w + i], rgb[1 * w + i], rgb[2 * w + i]);
+ }
+}
+
+//------------------------------------------------------------------------------
+
+static WEBP_INLINE fixed_y_t Filter2(int A, int B, int W0, int bit_depth) {
+ const int v0 = (A * 3 + B + 2) >> 2;
+ return clip_bit_depth(v0 + W0, bit_depth);
+}
+
+//------------------------------------------------------------------------------
+
+static WEBP_INLINE int Shift(int v, int shift) {
+ return (shift >= 0) ? (v << shift) : (v >> -shift);
+}
+
+static void ImportOneRow(const uint8_t* const r_ptr,
+ const uint8_t* const g_ptr,
+ const uint8_t* const b_ptr,
+ int rgb_step,
+ int rgb_bit_depth,
+ int pic_width,
+ fixed_y_t* const dst) {
+ // Convert the rgb_step from a number of bytes to a number of uint8_t or
+ // uint16_t values depending the bit depth.
+ const int step = (rgb_bit_depth > 8) ? rgb_step / 2 : rgb_step;
+ int i;
+ const int w = (pic_width + 1) & ~1;
+ for (i = 0; i < pic_width; ++i) {
+ const int off = i * step;
+ const int shift = GetPrecisionShift(rgb_bit_depth);
+ if (rgb_bit_depth == 8) {
+ dst[i + 0 * w] = Shift(r_ptr[off], shift);
+ dst[i + 1 * w] = Shift(g_ptr[off], shift);
+ dst[i + 2 * w] = Shift(b_ptr[off], shift);
+ } else {
+ dst[i + 0 * w] = Shift(((uint16_t*)r_ptr)[off], shift);
+ dst[i + 1 * w] = Shift(((uint16_t*)g_ptr)[off], shift);
+ dst[i + 2 * w] = Shift(((uint16_t*)b_ptr)[off], shift);
+ }
+ }
+ if (pic_width & 1) { // replicate rightmost pixel
+ dst[pic_width + 0 * w] = dst[pic_width + 0 * w - 1];
+ dst[pic_width + 1 * w] = dst[pic_width + 1 * w - 1];
+ dst[pic_width + 2 * w] = dst[pic_width + 2 * w - 1];
+ }
+}
+
+static void InterpolateTwoRows(const fixed_y_t* const best_y,
+ const fixed_t* prev_uv,
+ const fixed_t* cur_uv,
+ const fixed_t* next_uv,
+ int w,
+ fixed_y_t* out1,
+ fixed_y_t* out2,
+ int rgb_bit_depth) {
+ const int uv_w = w >> 1;
+ const int len = (w - 1) >> 1; // length to filter
+ int k = 3;
+ const int bit_depth = rgb_bit_depth + GetPrecisionShift(rgb_bit_depth);
+ while (k-- > 0) { // process each R/G/B segments in turn
+ // special boundary case for i==0
+ out1[0] = Filter2(cur_uv[0], prev_uv[0], best_y[0], bit_depth);
+ out2[0] = Filter2(cur_uv[0], next_uv[0], best_y[w], bit_depth);
+
+ SharpYuvFilterRow(cur_uv, prev_uv, len, best_y + 0 + 1, out1 + 1,
+ bit_depth);
+ SharpYuvFilterRow(cur_uv, next_uv, len, best_y + w + 1, out2 + 1,
+ bit_depth);
+
+ // special boundary case for i == w - 1 when w is even
+ if (!(w & 1)) {
+ out1[w - 1] = Filter2(cur_uv[uv_w - 1], prev_uv[uv_w - 1],
+ best_y[w - 1 + 0], bit_depth);
+ out2[w - 1] = Filter2(cur_uv[uv_w - 1], next_uv[uv_w - 1],
+ best_y[w - 1 + w], bit_depth);
+ }
+ out1 += w;
+ out2 += w;
+ prev_uv += uv_w;
+ cur_uv += uv_w;
+ next_uv += uv_w;
+ }
+}
+
+static WEBP_INLINE int RGBToYUVComponent(int r, int g, int b,
+ const int coeffs[4], int sfix) {
+ const int srounder = 1 << (YUV_FIX + sfix - 1);
+ const int luma = coeffs[0] * r + coeffs[1] * g + coeffs[2] * b +
+ coeffs[3] + srounder;
+ return (luma >> (YUV_FIX + sfix));
+}
+
+static int ConvertWRGBToYUV(const fixed_y_t* best_y, const fixed_t* best_uv,
+ uint8_t* y_ptr, int y_stride, uint8_t* u_ptr,
+ int u_stride, uint8_t* v_ptr, int v_stride,
+ int rgb_bit_depth,
+ int yuv_bit_depth, int width, int height,
+ const SharpYuvConversionMatrix* yuv_matrix) {
+ int i, j;
+ const fixed_t* const best_uv_base = best_uv;
+ const int w = (width + 1) & ~1;
+ const int h = (height + 1) & ~1;
+ const int uv_w = w >> 1;
+ const int uv_h = h >> 1;
+ const int sfix = GetPrecisionShift(rgb_bit_depth);
+ const int yuv_max = (1 << yuv_bit_depth) - 1;
+
+ for (best_uv = best_uv_base, j = 0; j < height; ++j) {
+ for (i = 0; i < width; ++i) {
+ const int off = (i >> 1);
+ const int W = best_y[i];
+ const int r = best_uv[off + 0 * uv_w] + W;
+ const int g = best_uv[off + 1 * uv_w] + W;
+ const int b = best_uv[off + 2 * uv_w] + W;
+ const int y = RGBToYUVComponent(r, g, b, yuv_matrix->rgb_to_y, sfix);
+ if (yuv_bit_depth <= 8) {
+ y_ptr[i] = clip_8b(y);
+ } else {
+ ((uint16_t*)y_ptr)[i] = clip(y, yuv_max);
+ }
+ }
+ best_y += w;
+ best_uv += (j & 1) * 3 * uv_w;
+ y_ptr += y_stride;
+ }
+ for (best_uv = best_uv_base, j = 0; j < uv_h; ++j) {
+ for (i = 0; i < uv_w; ++i) {
+ const int off = i;
+ // Note r, g and b values here are off by W, but a constant offset on all
+ // 3 components doesn't change the value of u and v with a YCbCr matrix.
+ const int r = best_uv[off + 0 * uv_w];
+ const int g = best_uv[off + 1 * uv_w];
+ const int b = best_uv[off + 2 * uv_w];
+ const int u = RGBToYUVComponent(r, g, b, yuv_matrix->rgb_to_u, sfix);
+ const int v = RGBToYUVComponent(r, g, b, yuv_matrix->rgb_to_v, sfix);
+ if (yuv_bit_depth <= 8) {
+ u_ptr[i] = clip_8b(u);
+ v_ptr[i] = clip_8b(v);
+ } else {
+ ((uint16_t*)u_ptr)[i] = clip(u, yuv_max);
+ ((uint16_t*)v_ptr)[i] = clip(v, yuv_max);
+ }
+ }
+ best_uv += 3 * uv_w;
+ u_ptr += u_stride;
+ v_ptr += v_stride;
+ }
+ return 1;
+}
+
+//------------------------------------------------------------------------------
+// Main function
+
+static void* SafeMalloc(uint64_t nmemb, size_t size) {
+ const uint64_t total_size = nmemb * (uint64_t)size;
+ if (total_size != (size_t)total_size) return NULL;
+ return malloc((size_t)total_size);
+}
+
+#define SAFE_ALLOC(W, H, T) ((T*)SafeMalloc((W) * (H), sizeof(T)))
+
+static int DoSharpArgbToYuv(const uint8_t* r_ptr, const uint8_t* g_ptr,
+ const uint8_t* b_ptr, int rgb_step, int rgb_stride,
+ int rgb_bit_depth, uint8_t* y_ptr, int y_stride,
+ uint8_t* u_ptr, int u_stride, uint8_t* v_ptr,
+ int v_stride, int yuv_bit_depth, int width,
+ int height,
+ const SharpYuvConversionMatrix* yuv_matrix) {
+ // we expand the right/bottom border if needed
+ const int w = (width + 1) & ~1;
+ const int h = (height + 1) & ~1;
+ const int uv_w = w >> 1;
+ const int uv_h = h >> 1;
+ uint64_t prev_diff_y_sum = ~0;
+ int j, iter;
+
+ // TODO(skal): allocate one big memory chunk. But for now, it's easier
+ // for valgrind debugging to have several chunks.
+ fixed_y_t* const tmp_buffer = SAFE_ALLOC(w * 3, 2, fixed_y_t); // scratch
+ fixed_y_t* const best_y_base = SAFE_ALLOC(w, h, fixed_y_t);
+ fixed_y_t* const target_y_base = SAFE_ALLOC(w, h, fixed_y_t);
+ fixed_y_t* const best_rgb_y = SAFE_ALLOC(w, 2, fixed_y_t);
+ fixed_t* const best_uv_base = SAFE_ALLOC(uv_w * 3, uv_h, fixed_t);
+ fixed_t* const target_uv_base = SAFE_ALLOC(uv_w * 3, uv_h, fixed_t);
+ fixed_t* const best_rgb_uv = SAFE_ALLOC(uv_w * 3, 1, fixed_t);
+ fixed_y_t* best_y = best_y_base;
+ fixed_y_t* target_y = target_y_base;
+ fixed_t* best_uv = best_uv_base;
+ fixed_t* target_uv = target_uv_base;
+ const uint64_t diff_y_threshold = (uint64_t)(3.0 * w * h);
+ int ok;
+ assert(w > 0);
+ assert(h > 0);
+
+ if (best_y_base == NULL || best_uv_base == NULL ||
+ target_y_base == NULL || target_uv_base == NULL ||
+ best_rgb_y == NULL || best_rgb_uv == NULL ||
+ tmp_buffer == NULL) {
+ ok = 0;
+ goto End;
+ }
+
+ // Import RGB samples to W/RGB representation.
+ for (j = 0; j < height; j += 2) {
+ const int is_last_row = (j == height - 1);
+ fixed_y_t* const src1 = tmp_buffer + 0 * w;
+ fixed_y_t* const src2 = tmp_buffer + 3 * w;
+
+ // prepare two rows of input
+ ImportOneRow(r_ptr, g_ptr, b_ptr, rgb_step, rgb_bit_depth, width,
+ src1);
+ if (!is_last_row) {
+ ImportOneRow(r_ptr + rgb_stride, g_ptr + rgb_stride, b_ptr + rgb_stride,
+ rgb_step, rgb_bit_depth, width, src2);
+ } else {
+ memcpy(src2, src1, 3 * w * sizeof(*src2));
+ }
+ StoreGray(src1, best_y + 0, w);
+ StoreGray(src2, best_y + w, w);
+
+ UpdateW(src1, target_y, w, rgb_bit_depth);
+ UpdateW(src2, target_y + w, w, rgb_bit_depth);
+ UpdateChroma(src1, src2, target_uv, uv_w, rgb_bit_depth);
+ memcpy(best_uv, target_uv, 3 * uv_w * sizeof(*best_uv));
+ best_y += 2 * w;
+ best_uv += 3 * uv_w;
+ target_y += 2 * w;
+ target_uv += 3 * uv_w;
+ r_ptr += 2 * rgb_stride;
+ g_ptr += 2 * rgb_stride;
+ b_ptr += 2 * rgb_stride;
+ }
+
+ // Iterate and resolve clipping conflicts.
+ for (iter = 0; iter < kNumIterations; ++iter) {
+ const fixed_t* cur_uv = best_uv_base;
+ const fixed_t* prev_uv = best_uv_base;
+ uint64_t diff_y_sum = 0;
+
+ best_y = best_y_base;
+ best_uv = best_uv_base;
+ target_y = target_y_base;
+ target_uv = target_uv_base;
+ for (j = 0; j < h; j += 2) {
+ fixed_y_t* const src1 = tmp_buffer + 0 * w;
+ fixed_y_t* const src2 = tmp_buffer + 3 * w;
+ {
+ const fixed_t* const next_uv = cur_uv + ((j < h - 2) ? 3 * uv_w : 0);
+ InterpolateTwoRows(best_y, prev_uv, cur_uv, next_uv, w,
+ src1, src2, rgb_bit_depth);
+ prev_uv = cur_uv;
+ cur_uv = next_uv;
+ }
+
+ UpdateW(src1, best_rgb_y + 0 * w, w, rgb_bit_depth);
+ UpdateW(src2, best_rgb_y + 1 * w, w, rgb_bit_depth);
+ UpdateChroma(src1, src2, best_rgb_uv, uv_w, rgb_bit_depth);
+
+ // update two rows of Y and one row of RGB
+ diff_y_sum +=
+ SharpYuvUpdateY(target_y, best_rgb_y, best_y, 2 * w,
+ rgb_bit_depth + GetPrecisionShift(rgb_bit_depth));
+ SharpYuvUpdateRGB(target_uv, best_rgb_uv, best_uv, 3 * uv_w);
+
+ best_y += 2 * w;
+ best_uv += 3 * uv_w;
+ target_y += 2 * w;
+ target_uv += 3 * uv_w;
+ }
+ // test exit condition
+ if (iter > 0) {
+ if (diff_y_sum < diff_y_threshold) break;
+ if (diff_y_sum > prev_diff_y_sum) break;
+ }
+ prev_diff_y_sum = diff_y_sum;
+ }
+
+ // final reconstruction
+ ok = ConvertWRGBToYUV(best_y_base, best_uv_base, y_ptr, y_stride, u_ptr,
+ u_stride, v_ptr, v_stride, rgb_bit_depth, yuv_bit_depth,
+ width, height, yuv_matrix);
+
+ End:
+ free(best_y_base);
+ free(best_uv_base);
+ free(target_y_base);
+ free(target_uv_base);
+ free(best_rgb_y);
+ free(best_rgb_uv);
+ free(tmp_buffer);
+ return ok;
+}
+#undef SAFE_ALLOC
+
+// Hidden exported init function.
+// By default SharpYuvConvert calls it with NULL. If needed, users can declare
+// it as extern and call it with a VP8CPUInfo function.
+extern void SharpYuvInit(VP8CPUInfo cpu_info_func);
+void SharpYuvInit(VP8CPUInfo cpu_info_func) {
+ static volatile VP8CPUInfo sharpyuv_last_cpuinfo_used =
+ (VP8CPUInfo)&sharpyuv_last_cpuinfo_used;
+ const int initialized =
+ (sharpyuv_last_cpuinfo_used != (VP8CPUInfo)&sharpyuv_last_cpuinfo_used);
+ if (cpu_info_func == NULL && initialized) return;
+ if (sharpyuv_last_cpuinfo_used == cpu_info_func) return;
+
+ SharpYuvInitDsp(cpu_info_func);
+ if (!initialized) {
+ SharpYuvInitGammaTables();
+ }
+
+ sharpyuv_last_cpuinfo_used = cpu_info_func;
+}
+
+int SharpYuvConvert(const void* r_ptr, const void* g_ptr,
+ const void* b_ptr, int rgb_step, int rgb_stride,
+ int rgb_bit_depth, void* y_ptr, int y_stride,
+ void* u_ptr, int u_stride, void* v_ptr,
+ int v_stride, int yuv_bit_depth, int width,
+ int height, const SharpYuvConversionMatrix* yuv_matrix) {
+ SharpYuvConversionMatrix scaled_matrix;
+ const int rgb_max = (1 << rgb_bit_depth) - 1;
+ const int rgb_round = 1 << (rgb_bit_depth - 1);
+ const int yuv_max = (1 << yuv_bit_depth) - 1;
+ const int sfix = GetPrecisionShift(rgb_bit_depth);
+
+ if (width < 1 || height < 1 || width == INT_MAX || height == INT_MAX ||
+ r_ptr == NULL || g_ptr == NULL || b_ptr == NULL || y_ptr == NULL ||
+ u_ptr == NULL || v_ptr == NULL) {
+ return 0;
+ }
+ if (rgb_bit_depth != 8 && rgb_bit_depth != 10 && rgb_bit_depth != 12 &&
+ rgb_bit_depth != 16) {
+ return 0;
+ }
+ if (yuv_bit_depth != 8 && yuv_bit_depth != 10 && yuv_bit_depth != 12) {
+ return 0;
+ }
+ if (rgb_bit_depth > 8 && (rgb_step % 2 != 0 || rgb_stride %2 != 0)) {
+ // Step/stride should be even for uint16_t buffers.
+ return 0;
+ }
+ if (yuv_bit_depth > 8 &&
+ (y_stride % 2 != 0 || u_stride % 2 != 0 || v_stride % 2 != 0)) {
+ // Stride should be even for uint16_t buffers.
+ return 0;
+ }
+ SharpYuvInit(NULL);
+
+ // Add scaling factor to go from rgb_bit_depth to yuv_bit_depth, to the
+ // rgb->yuv conversion matrix.
+ if (rgb_bit_depth == yuv_bit_depth) {
+ memcpy(&scaled_matrix, yuv_matrix, sizeof(scaled_matrix));
+ } else {
+ int i;
+ for (i = 0; i < 3; ++i) {
+ scaled_matrix.rgb_to_y[i] =
+ (yuv_matrix->rgb_to_y[i] * yuv_max + rgb_round) / rgb_max;
+ scaled_matrix.rgb_to_u[i] =
+ (yuv_matrix->rgb_to_u[i] * yuv_max + rgb_round) / rgb_max;
+ scaled_matrix.rgb_to_v[i] =
+ (yuv_matrix->rgb_to_v[i] * yuv_max + rgb_round) / rgb_max;
+ }
+ }
+ // Also incorporate precision change scaling.
+ scaled_matrix.rgb_to_y[3] = Shift(yuv_matrix->rgb_to_y[3], sfix);
+ scaled_matrix.rgb_to_u[3] = Shift(yuv_matrix->rgb_to_u[3], sfix);
+ scaled_matrix.rgb_to_v[3] = Shift(yuv_matrix->rgb_to_v[3], sfix);
+
+ return DoSharpArgbToYuv(r_ptr, g_ptr, b_ptr, rgb_step, rgb_stride,
+ rgb_bit_depth, y_ptr, y_stride, u_ptr, u_stride,
+ v_ptr, v_stride, yuv_bit_depth, width, height,
+ &scaled_matrix);
+}
+
+//------------------------------------------------------------------------------
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv.h b/thirdparty/libwebp/sharpyuv/sharpyuv.h
new file mode 100644
index 0000000000..9386ea2185
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv.h
@@ -0,0 +1,81 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Sharp RGB to YUV conversion.
+
+#ifndef WEBP_SHARPYUV_SHARPYUV_H_
+#define WEBP_SHARPYUV_SHARPYUV_H_
+
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// SharpYUV API version following the convention from semver.org
+#define SHARPYUV_VERSION_MAJOR 0
+#define SHARPYUV_VERSION_MINOR 1
+#define SHARPYUV_VERSION_PATCH 0
+// Version as a uint32_t. The major number is the high 8 bits.
+// The minor number is the middle 8 bits. The patch number is the low 16 bits.
+#define SHARPYUV_MAKE_VERSION(MAJOR, MINOR, PATCH) \
+ (((MAJOR) << 24) | ((MINOR) << 16) | (PATCH))
+#define SHARPYUV_VERSION \
+ SHARPYUV_MAKE_VERSION(SHARPYUV_VERSION_MAJOR, SHARPYUV_VERSION_MINOR, \
+ SHARPYUV_VERSION_PATCH)
+
+// RGB to YUV conversion matrix, in 16 bit fixed point.
+// y = rgb_to_y[0] * r + rgb_to_y[1] * g + rgb_to_y[2] * b + rgb_to_y[3]
+// u = rgb_to_u[0] * r + rgb_to_u[1] * g + rgb_to_u[2] * b + rgb_to_u[3]
+// v = rgb_to_v[0] * r + rgb_to_v[1] * g + rgb_to_v[2] * b + rgb_to_v[3]
+// Then y, u and v values are divided by 1<<16 and rounded.
+typedef struct {
+ int rgb_to_y[4];
+ int rgb_to_u[4];
+ int rgb_to_v[4];
+} SharpYuvConversionMatrix;
+
+// Converts RGB to YUV420 using a downsampling algorithm that minimizes
+// artefacts caused by chroma subsampling.
+// This is slower than standard downsampling (averaging of 4 UV values).
+// Assumes that the image will be upsampled using a bilinear filter. If nearest
+// neighbor is used instead, the upsampled image might look worse than with
+// standard downsampling.
+// r_ptr, g_ptr, b_ptr: pointers to the source r, g and b channels. Should point
+// to uint8_t buffers if rgb_bit_depth is 8, or uint16_t buffers otherwise.
+// rgb_step: distance in bytes between two horizontally adjacent pixels on the
+// r, g and b channels. If rgb_bit_depth is > 8, it should be a
+// multiple of 2.
+// rgb_stride: distance in bytes between two vertically adjacent pixels on the
+// r, g, and b channels. If rgb_bit_depth is > 8, it should be a
+// multiple of 2.
+// rgb_bit_depth: number of bits for each r/g/b value. One of: 8, 10, 12, 16.
+// Note: 16 bit input is truncated to 14 bits before conversion to yuv.
+// yuv_bit_depth: number of bits for each y/u/v value. One of: 8, 10, 12.
+// y_ptr, u_ptr, v_ptr: pointers to the destination y, u and v channels. Should
+// point to uint8_t buffers if yuv_bit_depth is 8, or uint16_t buffers
+// otherwise.
+// y_stride, u_stride, v_stride: distance in bytes between two vertically
+// adjacent pixels on the y, u and v channels. If yuv_bit_depth > 8, they
+// should be multiples of 2.
+// width, height: width and height of the image in pixels
+int SharpYuvConvert(const void* r_ptr, const void* g_ptr, const void* b_ptr,
+ int rgb_step, int rgb_stride, int rgb_bit_depth,
+ void* y_ptr, int y_stride, void* u_ptr, int u_stride,
+ void* v_ptr, int v_stride, int yuv_bit_depth, int width,
+ int height, const SharpYuvConversionMatrix* yuv_matrix);
+
+// TODO(b/194336375): Add YUV444 to YUV420 conversion. Maybe also add 422
+// support (it's rarely used in practice, especially for images).
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WEBP_SHARPYUV_SHARPYUV_H_
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_csp.c b/thirdparty/libwebp/sharpyuv/sharpyuv_csp.c
new file mode 100644
index 0000000000..5334fa64fa
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_csp.c
@@ -0,0 +1,110 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Colorspace utilities.
+
+#include "sharpyuv/sharpyuv_csp.h"
+
+#include <assert.h>
+#include <math.h>
+#include <string.h>
+
+static int ToFixed16(float f) { return (int)floor(f * (1 << 16) + 0.5f); }
+
+void SharpYuvComputeConversionMatrix(const SharpYuvColorSpace* yuv_color_space,
+ SharpYuvConversionMatrix* matrix) {
+ const float kr = yuv_color_space->kr;
+ const float kb = yuv_color_space->kb;
+ const float kg = 1.0f - kr - kb;
+ const float cr = 0.5f / (1.0f - kb);
+ const float cb = 0.5f / (1.0f - kr);
+
+ const int shift = yuv_color_space->bit_depth - 8;
+
+ const float denom = (float)((1 << yuv_color_space->bit_depth) - 1);
+ float scale_y = 1.0f;
+ float add_y = 0.0f;
+ float scale_u = cr;
+ float scale_v = cb;
+ float add_uv = (float)(128 << shift);
+ assert(yuv_color_space->bit_depth >= 8);
+
+ if (yuv_color_space->range == kSharpYuvRangeLimited) {
+ scale_y *= (219 << shift) / denom;
+ scale_u *= (224 << shift) / denom;
+ scale_v *= (224 << shift) / denom;
+ add_y = (float)(16 << shift);
+ }
+
+ matrix->rgb_to_y[0] = ToFixed16(kr * scale_y);
+ matrix->rgb_to_y[1] = ToFixed16(kg * scale_y);
+ matrix->rgb_to_y[2] = ToFixed16(kb * scale_y);
+ matrix->rgb_to_y[3] = ToFixed16(add_y);
+
+ matrix->rgb_to_u[0] = ToFixed16(-kr * scale_u);
+ matrix->rgb_to_u[1] = ToFixed16(-kg * scale_u);
+ matrix->rgb_to_u[2] = ToFixed16((1 - kb) * scale_u);
+ matrix->rgb_to_u[3] = ToFixed16(add_uv);
+
+ matrix->rgb_to_v[0] = ToFixed16((1 - kr) * scale_v);
+ matrix->rgb_to_v[1] = ToFixed16(-kg * scale_v);
+ matrix->rgb_to_v[2] = ToFixed16(-kb * scale_v);
+ matrix->rgb_to_v[3] = ToFixed16(add_uv);
+}
+
+// Matrices are in YUV_FIX fixed point precision.
+// WebP's matrix, similar but not identical to kRec601LimitedMatrix.
+static const SharpYuvConversionMatrix kWebpMatrix = {
+ {16839, 33059, 6420, 16 << 16},
+ {-9719, -19081, 28800, 128 << 16},
+ {28800, -24116, -4684, 128 << 16},
+};
+// Kr=0.2990f Kb=0.1140f bits=8 range=kSharpYuvRangeLimited
+static const SharpYuvConversionMatrix kRec601LimitedMatrix = {
+ {16829, 33039, 6416, 16 << 16},
+ {-9714, -19071, 28784, 128 << 16},
+ {28784, -24103, -4681, 128 << 16},
+};
+// Kr=0.2990f Kb=0.1140f bits=8 range=kSharpYuvRangeFull
+static const SharpYuvConversionMatrix kRec601FullMatrix = {
+ {19595, 38470, 7471, 0},
+ {-11058, -21710, 32768, 128 << 16},
+ {32768, -27439, -5329, 128 << 16},
+};
+// Kr=0.2126f Kb=0.0722f bits=8 range=kSharpYuvRangeLimited
+static const SharpYuvConversionMatrix kRec709LimitedMatrix = {
+ {11966, 40254, 4064, 16 << 16},
+ {-6596, -22189, 28784, 128 << 16},
+ {28784, -26145, -2639, 128 << 16},
+};
+// Kr=0.2126f Kb=0.0722f bits=8 range=kSharpYuvRangeFull
+static const SharpYuvConversionMatrix kRec709FullMatrix = {
+ {13933, 46871, 4732, 0},
+ {-7509, -25259, 32768, 128 << 16},
+ {32768, -29763, -3005, 128 << 16},
+};
+
+const SharpYuvConversionMatrix* SharpYuvGetConversionMatrix(
+ SharpYuvMatrixType matrix_type) {
+ switch (matrix_type) {
+ case kSharpYuvMatrixWebp:
+ return &kWebpMatrix;
+ case kSharpYuvMatrixRec601Limited:
+ return &kRec601LimitedMatrix;
+ case kSharpYuvMatrixRec601Full:
+ return &kRec601FullMatrix;
+ case kSharpYuvMatrixRec709Limited:
+ return &kRec709LimitedMatrix;
+ case kSharpYuvMatrixRec709Full:
+ return &kRec709FullMatrix;
+ case kSharpYuvMatrixNum:
+ return NULL;
+ }
+ return NULL;
+}
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_csp.h b/thirdparty/libwebp/sharpyuv/sharpyuv_csp.h
new file mode 100644
index 0000000000..63c99ef5cd
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_csp.h
@@ -0,0 +1,59 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Colorspace utilities.
+
+#ifndef WEBP_SHARPYUV_SHARPYUV_CSP_H_
+#define WEBP_SHARPYUV_SHARPYUV_CSP_H_
+
+#include "sharpyuv/sharpyuv.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Range of YUV values.
+typedef enum {
+ kSharpYuvRangeFull, // YUV values between [0;255] (for 8 bit)
+ kSharpYuvRangeLimited // Y in [16;235], YUV in [16;240] (for 8 bit)
+} SharpYuvRange;
+
+// Constants that define a YUV color space.
+typedef struct {
+ // Kr and Kb are defined such that:
+ // Y = Kr * r + Kg * g + Kb * b where Kg = 1 - Kr - Kb.
+ float kr;
+ float kb;
+ int bit_depth; // 8, 10 or 12
+ SharpYuvRange range;
+} SharpYuvColorSpace;
+
+// Fills in 'matrix' for the given YUVColorSpace.
+void SharpYuvComputeConversionMatrix(const SharpYuvColorSpace* yuv_color_space,
+ SharpYuvConversionMatrix* matrix);
+
+// Enums for precomputed conversion matrices.
+typedef enum {
+ kSharpYuvMatrixWebp = 0,
+ kSharpYuvMatrixRec601Limited,
+ kSharpYuvMatrixRec601Full,
+ kSharpYuvMatrixRec709Limited,
+ kSharpYuvMatrixRec709Full,
+ kSharpYuvMatrixNum
+} SharpYuvMatrixType;
+
+// Returns a pointer to a matrix for one of the predefined colorspaces.
+const SharpYuvConversionMatrix* SharpYuvGetConversionMatrix(
+ SharpYuvMatrixType matrix_type);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WEBP_SHARPYUV_SHARPYUV_CSP_H_
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_dsp.c b/thirdparty/libwebp/sharpyuv/sharpyuv_dsp.c
new file mode 100644
index 0000000000..956fa7ce55
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_dsp.c
@@ -0,0 +1,102 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Speed-critical functions for Sharp YUV.
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#include "sharpyuv/sharpyuv_dsp.h"
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "src/dsp/cpu.h"
+
+//-----------------------------------------------------------------------------
+
+#if !WEBP_NEON_OMIT_C_CODE
+static uint16_t clip(int v, int max) {
+ return (v < 0) ? 0 : (v > max) ? max : (uint16_t)v;
+}
+
+static uint64_t SharpYuvUpdateY_C(const uint16_t* ref, const uint16_t* src,
+ uint16_t* dst, int len, int bit_depth) {
+ uint64_t diff = 0;
+ int i;
+ const int max_y = (1 << bit_depth) - 1;
+ for (i = 0; i < len; ++i) {
+ const int diff_y = ref[i] - src[i];
+ const int new_y = (int)dst[i] + diff_y;
+ dst[i] = clip(new_y, max_y);
+ diff += (uint64_t)abs(diff_y);
+ }
+ return diff;
+}
+
+static void SharpYuvUpdateRGB_C(const int16_t* ref, const int16_t* src,
+ int16_t* dst, int len) {
+ int i;
+ for (i = 0; i < len; ++i) {
+ const int diff_uv = ref[i] - src[i];
+ dst[i] += diff_uv;
+ }
+}
+
+static void SharpYuvFilterRow_C(const int16_t* A, const int16_t* B, int len,
+ const uint16_t* best_y, uint16_t* out,
+ int bit_depth) {
+ int i;
+ const int max_y = (1 << bit_depth) - 1;
+ for (i = 0; i < len; ++i, ++A, ++B) {
+ const int v0 = (A[0] * 9 + A[1] * 3 + B[0] * 3 + B[1] + 8) >> 4;
+ const int v1 = (A[1] * 9 + A[0] * 3 + B[1] * 3 + B[0] + 8) >> 4;
+ out[2 * i + 0] = clip(best_y[2 * i + 0] + v0, max_y);
+ out[2 * i + 1] = clip(best_y[2 * i + 1] + v1, max_y);
+ }
+}
+#endif // !WEBP_NEON_OMIT_C_CODE
+
+//-----------------------------------------------------------------------------
+
+uint64_t (*SharpYuvUpdateY)(const uint16_t* src, const uint16_t* ref,
+ uint16_t* dst, int len, int bit_depth);
+void (*SharpYuvUpdateRGB)(const int16_t* src, const int16_t* ref, int16_t* dst,
+ int len);
+void (*SharpYuvFilterRow)(const int16_t* A, const int16_t* B, int len,
+ const uint16_t* best_y, uint16_t* out,
+ int bit_depth);
+
+extern void InitSharpYuvSSE2(void);
+extern void InitSharpYuvNEON(void);
+
+void SharpYuvInitDsp(VP8CPUInfo cpu_info_func) {
+ (void)cpu_info_func;
+
+#if !WEBP_NEON_OMIT_C_CODE
+ SharpYuvUpdateY = SharpYuvUpdateY_C;
+ SharpYuvUpdateRGB = SharpYuvUpdateRGB_C;
+ SharpYuvFilterRow = SharpYuvFilterRow_C;
+#endif
+
+#if defined(WEBP_HAVE_SSE2)
+ if (cpu_info_func == NULL || cpu_info_func(kSSE2)) {
+ InitSharpYuvSSE2();
+ }
+#endif // WEBP_HAVE_SSE2
+
+#if defined(WEBP_HAVE_NEON)
+ if (WEBP_NEON_OMIT_C_CODE || cpu_info_func == NULL || cpu_info_func(kNEON)) {
+ InitSharpYuvNEON();
+ }
+#endif // WEBP_HAVE_NEON
+
+ assert(SharpYuvUpdateY != NULL);
+ assert(SharpYuvUpdateRGB != NULL);
+ assert(SharpYuvFilterRow != NULL);
+}
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_dsp.h b/thirdparty/libwebp/sharpyuv/sharpyuv_dsp.h
new file mode 100644
index 0000000000..e561d8d3d0
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_dsp.h
@@ -0,0 +1,29 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Speed-critical functions for Sharp YUV.
+
+#ifndef WEBP_SHARPYUV_SHARPYUV_DSP_H_
+#define WEBP_SHARPYUV_SHARPYUV_DSP_H_
+
+#include <stdint.h>
+
+#include "src/dsp/cpu.h"
+
+extern uint64_t (*SharpYuvUpdateY)(const uint16_t* src, const uint16_t* ref,
+ uint16_t* dst, int len, int bit_depth);
+extern void (*SharpYuvUpdateRGB)(const int16_t* src, const int16_t* ref,
+ int16_t* dst, int len);
+extern void (*SharpYuvFilterRow)(const int16_t* A, const int16_t* B, int len,
+ const uint16_t* best_y, uint16_t* out,
+ int bit_depth);
+
+void SharpYuvInitDsp(VP8CPUInfo cpu_info_func);
+
+#endif // WEBP_SHARPYUV_SHARPYUV_DSP_H_
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_gamma.c b/thirdparty/libwebp/sharpyuv/sharpyuv_gamma.c
new file mode 100644
index 0000000000..05b5436f83
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_gamma.c
@@ -0,0 +1,114 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Gamma correction utilities.
+
+#include "sharpyuv/sharpyuv_gamma.h"
+
+#include <assert.h>
+#include <math.h>
+#include <stdint.h>
+
+#include "src/webp/types.h"
+
+// Gamma correction compensates loss of resolution during chroma subsampling.
+// Size of pre-computed table for converting from gamma to linear.
+#define GAMMA_TO_LINEAR_TAB_BITS 10
+#define GAMMA_TO_LINEAR_TAB_SIZE (1 << GAMMA_TO_LINEAR_TAB_BITS)
+static uint32_t kGammaToLinearTabS[GAMMA_TO_LINEAR_TAB_SIZE + 2];
+#define LINEAR_TO_GAMMA_TAB_BITS 9
+#define LINEAR_TO_GAMMA_TAB_SIZE (1 << LINEAR_TO_GAMMA_TAB_BITS)
+static uint32_t kLinearToGammaTabS[LINEAR_TO_GAMMA_TAB_SIZE + 2];
+
+static const double kGammaF = 1. / 0.45;
+#define GAMMA_TO_LINEAR_BITS 16
+
+static volatile int kGammaTablesSOk = 0;
+void SharpYuvInitGammaTables(void) {
+ assert(GAMMA_TO_LINEAR_BITS <= 16);
+ if (!kGammaTablesSOk) {
+ int v;
+ const double a = 0.09929682680944;
+ const double thresh = 0.018053968510807;
+ const double final_scale = 1 << GAMMA_TO_LINEAR_BITS;
+ // Precompute gamma to linear table.
+ {
+ const double norm = 1. / GAMMA_TO_LINEAR_TAB_SIZE;
+ const double a_rec = 1. / (1. + a);
+ for (v = 0; v <= GAMMA_TO_LINEAR_TAB_SIZE; ++v) {
+ const double g = norm * v;
+ double value;
+ if (g <= thresh * 4.5) {
+ value = g / 4.5;
+ } else {
+ value = pow(a_rec * (g + a), kGammaF);
+ }
+ kGammaToLinearTabS[v] = (uint32_t)(value * final_scale + .5);
+ }
+ // to prevent small rounding errors to cause read-overflow:
+ kGammaToLinearTabS[GAMMA_TO_LINEAR_TAB_SIZE + 1] =
+ kGammaToLinearTabS[GAMMA_TO_LINEAR_TAB_SIZE];
+ }
+ // Precompute linear to gamma table.
+ {
+ const double scale = 1. / LINEAR_TO_GAMMA_TAB_SIZE;
+ for (v = 0; v <= LINEAR_TO_GAMMA_TAB_SIZE; ++v) {
+ const double g = scale * v;
+ double value;
+ if (g <= thresh) {
+ value = 4.5 * g;
+ } else {
+ value = (1. + a) * pow(g, 1. / kGammaF) - a;
+ }
+ kLinearToGammaTabS[v] =
+ (uint32_t)(final_scale * value + 0.5);
+ }
+ // to prevent small rounding errors to cause read-overflow:
+ kLinearToGammaTabS[LINEAR_TO_GAMMA_TAB_SIZE + 1] =
+ kLinearToGammaTabS[LINEAR_TO_GAMMA_TAB_SIZE];
+ }
+ kGammaTablesSOk = 1;
+ }
+}
+
+static WEBP_INLINE int Shift(int v, int shift) {
+ return (shift >= 0) ? (v << shift) : (v >> -shift);
+}
+
+static WEBP_INLINE uint32_t FixedPointInterpolation(int v, uint32_t* tab,
+ int tab_pos_shift_right,
+ int tab_value_shift) {
+ const uint32_t tab_pos = Shift(v, -tab_pos_shift_right);
+ // fractional part, in 'tab_pos_shift' fixed-point precision
+ const uint32_t x = v - (tab_pos << tab_pos_shift_right); // fractional part
+ // v0 / v1 are in kGammaToLinearBits fixed-point precision (range [0..1])
+ const uint32_t v0 = Shift(tab[tab_pos + 0], tab_value_shift);
+ const uint32_t v1 = Shift(tab[tab_pos + 1], tab_value_shift);
+ // Final interpolation.
+ const uint32_t v2 = (v1 - v0) * x; // note: v1 >= v0.
+ const int half =
+ (tab_pos_shift_right > 0) ? 1 << (tab_pos_shift_right - 1) : 0;
+ const uint32_t result = v0 + ((v2 + half) >> tab_pos_shift_right);
+ return result;
+}
+
+uint32_t SharpYuvGammaToLinear(uint16_t v, int bit_depth) {
+ const int shift = GAMMA_TO_LINEAR_TAB_BITS - bit_depth;
+ if (shift > 0) {
+ return kGammaToLinearTabS[v << shift];
+ }
+ return FixedPointInterpolation(v, kGammaToLinearTabS, -shift, 0);
+}
+
+uint16_t SharpYuvLinearToGamma(uint32_t value, int bit_depth) {
+ return FixedPointInterpolation(
+ value, kLinearToGammaTabS,
+ (GAMMA_TO_LINEAR_BITS - LINEAR_TO_GAMMA_TAB_BITS),
+ bit_depth - GAMMA_TO_LINEAR_BITS);
+}
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_gamma.h b/thirdparty/libwebp/sharpyuv/sharpyuv_gamma.h
new file mode 100644
index 0000000000..2f1a3ff4a0
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_gamma.h
@@ -0,0 +1,35 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Gamma correction utilities.
+
+#ifndef WEBP_SHARPYUV_SHARPYUV_GAMMA_H_
+#define WEBP_SHARPYUV_SHARPYUV_GAMMA_H_
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Initializes precomputed tables. Must be called once before calling
+// SharpYuvGammaToLinear or SharpYuvLinearToGamma.
+void SharpYuvInitGammaTables(void);
+
+// Converts a gamma color value on 'bit_depth' bits to a 16 bit linear value.
+uint32_t SharpYuvGammaToLinear(uint16_t v, int bit_depth);
+
+// Converts a 16 bit linear color value to a gamma value on 'bit_depth' bits.
+uint16_t SharpYuvLinearToGamma(uint32_t value, int bit_depth);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WEBP_SHARPYUV_SHARPYUV_GAMMA_H_
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_neon.c b/thirdparty/libwebp/sharpyuv/sharpyuv_neon.c
new file mode 100644
index 0000000000..5cf6aaffb0
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_neon.c
@@ -0,0 +1,182 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Speed-critical functions for Sharp YUV.
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#include "sharpyuv/sharpyuv_dsp.h"
+
+#if defined(WEBP_USE_NEON)
+#include <assert.h>
+#include <stdlib.h>
+#include <arm_neon.h>
+#endif
+
+extern void InitSharpYuvNEON(void);
+
+#if defined(WEBP_USE_NEON)
+
+static uint16_t clip_NEON(int v, int max) {
+ return (v < 0) ? 0 : (v > max) ? max : (uint16_t)v;
+}
+
+static uint64_t SharpYuvUpdateY_NEON(const uint16_t* ref, const uint16_t* src,
+ uint16_t* dst, int len, int bit_depth) {
+ const int max_y = (1 << bit_depth) - 1;
+ int i;
+ const int16x8_t zero = vdupq_n_s16(0);
+ const int16x8_t max = vdupq_n_s16(max_y);
+ uint64x2_t sum = vdupq_n_u64(0);
+ uint64_t diff;
+
+ for (i = 0; i + 8 <= len; i += 8) {
+ const int16x8_t A = vreinterpretq_s16_u16(vld1q_u16(ref + i));
+ const int16x8_t B = vreinterpretq_s16_u16(vld1q_u16(src + i));
+ const int16x8_t C = vreinterpretq_s16_u16(vld1q_u16(dst + i));
+ const int16x8_t D = vsubq_s16(A, B); // diff_y
+ const int16x8_t F = vaddq_s16(C, D); // new_y
+ const uint16x8_t H =
+ vreinterpretq_u16_s16(vmaxq_s16(vminq_s16(F, max), zero));
+ const int16x8_t I = vabsq_s16(D); // abs(diff_y)
+ vst1q_u16(dst + i, H);
+ sum = vpadalq_u32(sum, vpaddlq_u16(vreinterpretq_u16_s16(I)));
+ }
+ diff = vgetq_lane_u64(sum, 0) + vgetq_lane_u64(sum, 1);
+ for (; i < len; ++i) {
+ const int diff_y = ref[i] - src[i];
+ const int new_y = (int)(dst[i]) + diff_y;
+ dst[i] = clip_NEON(new_y, max_y);
+ diff += (uint64_t)(abs(diff_y));
+ }
+ return diff;
+}
+
+static void SharpYuvUpdateRGB_NEON(const int16_t* ref, const int16_t* src,
+ int16_t* dst, int len) {
+ int i;
+ for (i = 0; i + 8 <= len; i += 8) {
+ const int16x8_t A = vld1q_s16(ref + i);
+ const int16x8_t B = vld1q_s16(src + i);
+ const int16x8_t C = vld1q_s16(dst + i);
+ const int16x8_t D = vsubq_s16(A, B); // diff_uv
+ const int16x8_t E = vaddq_s16(C, D); // new_uv
+ vst1q_s16(dst + i, E);
+ }
+ for (; i < len; ++i) {
+ const int diff_uv = ref[i] - src[i];
+ dst[i] += diff_uv;
+ }
+}
+
+static void SharpYuvFilterRow16_NEON(const int16_t* A, const int16_t* B,
+ int len, const uint16_t* best_y,
+ uint16_t* out, int bit_depth) {
+ const int max_y = (1 << bit_depth) - 1;
+ int i;
+ const int16x8_t max = vdupq_n_s16(max_y);
+ const int16x8_t zero = vdupq_n_s16(0);
+ for (i = 0; i + 8 <= len; i += 8) {
+ const int16x8_t a0 = vld1q_s16(A + i + 0);
+ const int16x8_t a1 = vld1q_s16(A + i + 1);
+ const int16x8_t b0 = vld1q_s16(B + i + 0);
+ const int16x8_t b1 = vld1q_s16(B + i + 1);
+ const int16x8_t a0b1 = vaddq_s16(a0, b1);
+ const int16x8_t a1b0 = vaddq_s16(a1, b0);
+ const int16x8_t a0a1b0b1 = vaddq_s16(a0b1, a1b0); // A0+A1+B0+B1
+ const int16x8_t a0b1_2 = vaddq_s16(a0b1, a0b1); // 2*(A0+B1)
+ const int16x8_t a1b0_2 = vaddq_s16(a1b0, a1b0); // 2*(A1+B0)
+ const int16x8_t c0 = vshrq_n_s16(vaddq_s16(a0b1_2, a0a1b0b1), 3);
+ const int16x8_t c1 = vshrq_n_s16(vaddq_s16(a1b0_2, a0a1b0b1), 3);
+ const int16x8_t e0 = vrhaddq_s16(c1, a0);
+ const int16x8_t e1 = vrhaddq_s16(c0, a1);
+ const int16x8x2_t f = vzipq_s16(e0, e1);
+ const int16x8_t g0 = vreinterpretq_s16_u16(vld1q_u16(best_y + 2 * i + 0));
+ const int16x8_t g1 = vreinterpretq_s16_u16(vld1q_u16(best_y + 2 * i + 8));
+ const int16x8_t h0 = vaddq_s16(g0, f.val[0]);
+ const int16x8_t h1 = vaddq_s16(g1, f.val[1]);
+ const int16x8_t i0 = vmaxq_s16(vminq_s16(h0, max), zero);
+ const int16x8_t i1 = vmaxq_s16(vminq_s16(h1, max), zero);
+ vst1q_u16(out + 2 * i + 0, vreinterpretq_u16_s16(i0));
+ vst1q_u16(out + 2 * i + 8, vreinterpretq_u16_s16(i1));
+ }
+ for (; i < len; ++i) {
+ const int a0b1 = A[i + 0] + B[i + 1];
+ const int a1b0 = A[i + 1] + B[i + 0];
+ const int a0a1b0b1 = a0b1 + a1b0 + 8;
+ const int v0 = (8 * A[i + 0] + 2 * a1b0 + a0a1b0b1) >> 4;
+ const int v1 = (8 * A[i + 1] + 2 * a0b1 + a0a1b0b1) >> 4;
+ out[2 * i + 0] = clip_NEON(best_y[2 * i + 0] + v0, max_y);
+ out[2 * i + 1] = clip_NEON(best_y[2 * i + 1] + v1, max_y);
+ }
+}
+
+static void SharpYuvFilterRow32_NEON(const int16_t* A, const int16_t* B,
+ int len, const uint16_t* best_y,
+ uint16_t* out, int bit_depth) {
+ const int max_y = (1 << bit_depth) - 1;
+ int i;
+ const uint16x8_t max = vdupq_n_u16(max_y);
+ for (i = 0; i + 4 <= len; i += 4) {
+ const int16x4_t a0 = vld1_s16(A + i + 0);
+ const int16x4_t a1 = vld1_s16(A + i + 1);
+ const int16x4_t b0 = vld1_s16(B + i + 0);
+ const int16x4_t b1 = vld1_s16(B + i + 1);
+ const int32x4_t a0b1 = vaddl_s16(a0, b1);
+ const int32x4_t a1b0 = vaddl_s16(a1, b0);
+ const int32x4_t a0a1b0b1 = vaddq_s32(a0b1, a1b0); // A0+A1+B0+B1
+ const int32x4_t a0b1_2 = vaddq_s32(a0b1, a0b1); // 2*(A0+B1)
+ const int32x4_t a1b0_2 = vaddq_s32(a1b0, a1b0); // 2*(A1+B0)
+ const int32x4_t c0 = vshrq_n_s32(vaddq_s32(a0b1_2, a0a1b0b1), 3);
+ const int32x4_t c1 = vshrq_n_s32(vaddq_s32(a1b0_2, a0a1b0b1), 3);
+ const int32x4_t e0 = vrhaddq_s32(c1, vmovl_s16(a0));
+ const int32x4_t e1 = vrhaddq_s32(c0, vmovl_s16(a1));
+ const int32x4x2_t f = vzipq_s32(e0, e1);
+
+ const int16x8_t g = vreinterpretq_s16_u16(vld1q_u16(best_y + 2 * i));
+ const int32x4_t h0 = vaddw_s16(f.val[0], vget_low_s16(g));
+ const int32x4_t h1 = vaddw_s16(f.val[1], vget_high_s16(g));
+ const uint16x8_t i_16 = vcombine_u16(vqmovun_s32(h0), vqmovun_s32(h1));
+ const uint16x8_t i_clamped = vminq_u16(i_16, max);
+ vst1q_u16(out + 2 * i + 0, i_clamped);
+ }
+ for (; i < len; ++i) {
+ const int a0b1 = A[i + 0] + B[i + 1];
+ const int a1b0 = A[i + 1] + B[i + 0];
+ const int a0a1b0b1 = a0b1 + a1b0 + 8;
+ const int v0 = (8 * A[i + 0] + 2 * a1b0 + a0a1b0b1) >> 4;
+ const int v1 = (8 * A[i + 1] + 2 * a0b1 + a0a1b0b1) >> 4;
+ out[2 * i + 0] = clip_NEON(best_y[2 * i + 0] + v0, max_y);
+ out[2 * i + 1] = clip_NEON(best_y[2 * i + 1] + v1, max_y);
+ }
+}
+
+static void SharpYuvFilterRow_NEON(const int16_t* A, const int16_t* B, int len,
+ const uint16_t* best_y, uint16_t* out,
+ int bit_depth) {
+ if (bit_depth <= 10) {
+ SharpYuvFilterRow16_NEON(A, B, len, best_y, out, bit_depth);
+ } else {
+ SharpYuvFilterRow32_NEON(A, B, len, best_y, out, bit_depth);
+ }
+}
+
+//------------------------------------------------------------------------------
+
+WEBP_TSAN_IGNORE_FUNCTION void InitSharpYuvNEON(void) {
+ SharpYuvUpdateY = SharpYuvUpdateY_NEON;
+ SharpYuvUpdateRGB = SharpYuvUpdateRGB_NEON;
+ SharpYuvFilterRow = SharpYuvFilterRow_NEON;
+}
+
+#else // !WEBP_USE_NEON
+
+void InitSharpYuvNEON(void) {}
+
+#endif // WEBP_USE_NEON
diff --git a/thirdparty/libwebp/sharpyuv/sharpyuv_sse2.c b/thirdparty/libwebp/sharpyuv/sharpyuv_sse2.c
new file mode 100644
index 0000000000..1943873748
--- /dev/null
+++ b/thirdparty/libwebp/sharpyuv/sharpyuv_sse2.c
@@ -0,0 +1,204 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// Speed-critical functions for Sharp YUV.
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#include "sharpyuv/sharpyuv_dsp.h"
+
+#if defined(WEBP_USE_SSE2)
+#include <stdlib.h>
+#include <emmintrin.h>
+#endif
+
+extern void InitSharpYuvSSE2(void);
+
+#if defined(WEBP_USE_SSE2)
+
+static uint16_t clip_SSE2(int v, int max) {
+ return (v < 0) ? 0 : (v > max) ? max : (uint16_t)v;
+}
+
+static uint64_t SharpYuvUpdateY_SSE2(const uint16_t* ref, const uint16_t* src,
+ uint16_t* dst, int len, int bit_depth) {
+ const int max_y = (1 << bit_depth) - 1;
+ uint64_t diff = 0;
+ uint32_t tmp[4];
+ int i;
+ const __m128i zero = _mm_setzero_si128();
+ const __m128i max = _mm_set1_epi16(max_y);
+ const __m128i one = _mm_set1_epi16(1);
+ __m128i sum = zero;
+
+ for (i = 0; i + 8 <= len; i += 8) {
+ const __m128i A = _mm_loadu_si128((const __m128i*)(ref + i));
+ const __m128i B = _mm_loadu_si128((const __m128i*)(src + i));
+ const __m128i C = _mm_loadu_si128((const __m128i*)(dst + i));
+ const __m128i D = _mm_sub_epi16(A, B); // diff_y
+ const __m128i E = _mm_cmpgt_epi16(zero, D); // sign (-1 or 0)
+ const __m128i F = _mm_add_epi16(C, D); // new_y
+ const __m128i G = _mm_or_si128(E, one); // -1 or 1
+ const __m128i H = _mm_max_epi16(_mm_min_epi16(F, max), zero);
+ const __m128i I = _mm_madd_epi16(D, G); // sum(abs(...))
+ _mm_storeu_si128((__m128i*)(dst + i), H);
+ sum = _mm_add_epi32(sum, I);
+ }
+ _mm_storeu_si128((__m128i*)tmp, sum);
+ diff = tmp[3] + tmp[2] + tmp[1] + tmp[0];
+ for (; i < len; ++i) {
+ const int diff_y = ref[i] - src[i];
+ const int new_y = (int)dst[i] + diff_y;
+ dst[i] = clip_SSE2(new_y, max_y);
+ diff += (uint64_t)abs(diff_y);
+ }
+ return diff;
+}
+
+static void SharpYuvUpdateRGB_SSE2(const int16_t* ref, const int16_t* src,
+ int16_t* dst, int len) {
+ int i = 0;
+ for (i = 0; i + 8 <= len; i += 8) {
+ const __m128i A = _mm_loadu_si128((const __m128i*)(ref + i));
+ const __m128i B = _mm_loadu_si128((const __m128i*)(src + i));
+ const __m128i C = _mm_loadu_si128((const __m128i*)(dst + i));
+ const __m128i D = _mm_sub_epi16(A, B); // diff_uv
+ const __m128i E = _mm_add_epi16(C, D); // new_uv
+ _mm_storeu_si128((__m128i*)(dst + i), E);
+ }
+ for (; i < len; ++i) {
+ const int diff_uv = ref[i] - src[i];
+ dst[i] += diff_uv;
+ }
+}
+
+static void SharpYuvFilterRow16_SSE2(const int16_t* A, const int16_t* B,
+ int len, const uint16_t* best_y,
+ uint16_t* out, int bit_depth) {
+ const int max_y = (1 << bit_depth) - 1;
+ int i;
+ const __m128i kCst8 = _mm_set1_epi16(8);
+ const __m128i max = _mm_set1_epi16(max_y);
+ const __m128i zero = _mm_setzero_si128();
+ for (i = 0; i + 8 <= len; i += 8) {
+ const __m128i a0 = _mm_loadu_si128((const __m128i*)(A + i + 0));
+ const __m128i a1 = _mm_loadu_si128((const __m128i*)(A + i + 1));
+ const __m128i b0 = _mm_loadu_si128((const __m128i*)(B + i + 0));
+ const __m128i b1 = _mm_loadu_si128((const __m128i*)(B + i + 1));
+ const __m128i a0b1 = _mm_add_epi16(a0, b1);
+ const __m128i a1b0 = _mm_add_epi16(a1, b0);
+ const __m128i a0a1b0b1 = _mm_add_epi16(a0b1, a1b0); // A0+A1+B0+B1
+ const __m128i a0a1b0b1_8 = _mm_add_epi16(a0a1b0b1, kCst8);
+ const __m128i a0b1_2 = _mm_add_epi16(a0b1, a0b1); // 2*(A0+B1)
+ const __m128i a1b0_2 = _mm_add_epi16(a1b0, a1b0); // 2*(A1+B0)
+ const __m128i c0 = _mm_srai_epi16(_mm_add_epi16(a0b1_2, a0a1b0b1_8), 3);
+ const __m128i c1 = _mm_srai_epi16(_mm_add_epi16(a1b0_2, a0a1b0b1_8), 3);
+ const __m128i d0 = _mm_add_epi16(c1, a0);
+ const __m128i d1 = _mm_add_epi16(c0, a1);
+ const __m128i e0 = _mm_srai_epi16(d0, 1);
+ const __m128i e1 = _mm_srai_epi16(d1, 1);
+ const __m128i f0 = _mm_unpacklo_epi16(e0, e1);
+ const __m128i f1 = _mm_unpackhi_epi16(e0, e1);
+ const __m128i g0 = _mm_loadu_si128((const __m128i*)(best_y + 2 * i + 0));
+ const __m128i g1 = _mm_loadu_si128((const __m128i*)(best_y + 2 * i + 8));
+ const __m128i h0 = _mm_add_epi16(g0, f0);
+ const __m128i h1 = _mm_add_epi16(g1, f1);
+ const __m128i i0 = _mm_max_epi16(_mm_min_epi16(h0, max), zero);
+ const __m128i i1 = _mm_max_epi16(_mm_min_epi16(h1, max), zero);
+ _mm_storeu_si128((__m128i*)(out + 2 * i + 0), i0);
+ _mm_storeu_si128((__m128i*)(out + 2 * i + 8), i1);
+ }
+ for (; i < len; ++i) {
+ // (9 * A0 + 3 * A1 + 3 * B0 + B1 + 8) >> 4 =
+ // = (8 * A0 + 2 * (A1 + B0) + (A0 + A1 + B0 + B1 + 8)) >> 4
+ // We reuse the common sub-expressions.
+ const int a0b1 = A[i + 0] + B[i + 1];
+ const int a1b0 = A[i + 1] + B[i + 0];
+ const int a0a1b0b1 = a0b1 + a1b0 + 8;
+ const int v0 = (8 * A[i + 0] + 2 * a1b0 + a0a1b0b1) >> 4;
+ const int v1 = (8 * A[i + 1] + 2 * a0b1 + a0a1b0b1) >> 4;
+ out[2 * i + 0] = clip_SSE2(best_y[2 * i + 0] + v0, max_y);
+ out[2 * i + 1] = clip_SSE2(best_y[2 * i + 1] + v1, max_y);
+ }
+}
+
+static WEBP_INLINE __m128i s16_to_s32(__m128i in) {
+ return _mm_srai_epi32(_mm_unpacklo_epi16(in, in), 16);
+}
+
+static void SharpYuvFilterRow32_SSE2(const int16_t* A, const int16_t* B,
+ int len, const uint16_t* best_y,
+ uint16_t* out, int bit_depth) {
+ const int max_y = (1 << bit_depth) - 1;
+ int i;
+ const __m128i kCst8 = _mm_set1_epi32(8);
+ const __m128i max = _mm_set1_epi16(max_y);
+ const __m128i zero = _mm_setzero_si128();
+ for (i = 0; i + 4 <= len; i += 4) {
+ const __m128i a0 = s16_to_s32(_mm_loadl_epi64((const __m128i*)(A + i + 0)));
+ const __m128i a1 = s16_to_s32(_mm_loadl_epi64((const __m128i*)(A + i + 1)));
+ const __m128i b0 = s16_to_s32(_mm_loadl_epi64((const __m128i*)(B + i + 0)));
+ const __m128i b1 = s16_to_s32(_mm_loadl_epi64((const __m128i*)(B + i + 1)));
+ const __m128i a0b1 = _mm_add_epi32(a0, b1);
+ const __m128i a1b0 = _mm_add_epi32(a1, b0);
+ const __m128i a0a1b0b1 = _mm_add_epi32(a0b1, a1b0); // A0+A1+B0+B1
+ const __m128i a0a1b0b1_8 = _mm_add_epi32(a0a1b0b1, kCst8);
+ const __m128i a0b1_2 = _mm_add_epi32(a0b1, a0b1); // 2*(A0+B1)
+ const __m128i a1b0_2 = _mm_add_epi32(a1b0, a1b0); // 2*(A1+B0)
+ const __m128i c0 = _mm_srai_epi32(_mm_add_epi32(a0b1_2, a0a1b0b1_8), 3);
+ const __m128i c1 = _mm_srai_epi32(_mm_add_epi32(a1b0_2, a0a1b0b1_8), 3);
+ const __m128i d0 = _mm_add_epi32(c1, a0);
+ const __m128i d1 = _mm_add_epi32(c0, a1);
+ const __m128i e0 = _mm_srai_epi32(d0, 1);
+ const __m128i e1 = _mm_srai_epi32(d1, 1);
+ const __m128i f0 = _mm_unpacklo_epi32(e0, e1);
+ const __m128i f1 = _mm_unpackhi_epi32(e0, e1);
+ const __m128i g = _mm_loadu_si128((const __m128i*)(best_y + 2 * i + 0));
+ const __m128i h_16 = _mm_add_epi16(g, _mm_packs_epi32(f0, f1));
+ const __m128i final = _mm_max_epi16(_mm_min_epi16(h_16, max), zero);
+ _mm_storeu_si128((__m128i*)(out + 2 * i + 0), final);
+ }
+ for (; i < len; ++i) {
+ // (9 * A0 + 3 * A1 + 3 * B0 + B1 + 8) >> 4 =
+ // = (8 * A0 + 2 * (A1 + B0) + (A0 + A1 + B0 + B1 + 8)) >> 4
+ // We reuse the common sub-expressions.
+ const int a0b1 = A[i + 0] + B[i + 1];
+ const int a1b0 = A[i + 1] + B[i + 0];
+ const int a0a1b0b1 = a0b1 + a1b0 + 8;
+ const int v0 = (8 * A[i + 0] + 2 * a1b0 + a0a1b0b1) >> 4;
+ const int v1 = (8 * A[i + 1] + 2 * a0b1 + a0a1b0b1) >> 4;
+ out[2 * i + 0] = clip_SSE2(best_y[2 * i + 0] + v0, max_y);
+ out[2 * i + 1] = clip_SSE2(best_y[2 * i + 1] + v1, max_y);
+ }
+}
+
+static void SharpYuvFilterRow_SSE2(const int16_t* A, const int16_t* B, int len,
+ const uint16_t* best_y, uint16_t* out,
+ int bit_depth) {
+ if (bit_depth <= 10) {
+ SharpYuvFilterRow16_SSE2(A, B, len, best_y, out, bit_depth);
+ } else {
+ SharpYuvFilterRow32_SSE2(A, B, len, best_y, out, bit_depth);
+ }
+}
+
+//------------------------------------------------------------------------------
+
+extern void InitSharpYuvSSE2(void);
+
+WEBP_TSAN_IGNORE_FUNCTION void InitSharpYuvSSE2(void) {
+ SharpYuvUpdateY = SharpYuvUpdateY_SSE2;
+ SharpYuvUpdateRGB = SharpYuvUpdateRGB_SSE2;
+ SharpYuvFilterRow = SharpYuvFilterRow_SSE2;
+}
+#else // !WEBP_USE_SSE2
+
+void InitSharpYuvSSE2(void) {}
+
+#endif // WEBP_USE_SSE2
diff --git a/thirdparty/libwebp/src/dec/vp8i_dec.h b/thirdparty/libwebp/src/dec/vp8i_dec.h
index 9af22f8cc6..30c1bd3ef9 100644
--- a/thirdparty/libwebp/src/dec/vp8i_dec.h
+++ b/thirdparty/libwebp/src/dec/vp8i_dec.h
@@ -32,7 +32,7 @@ extern "C" {
// version numbers
#define DEC_MAJ_VERSION 1
#define DEC_MIN_VERSION 2
-#define DEC_REV_VERSION 2
+#define DEC_REV_VERSION 4
// YUV-cache parameters. Cache is 32-bytes wide (= one cacheline).
// Constraints are: We need to store one 16x16 block of luma samples (y),
diff --git a/thirdparty/libwebp/src/dec/vp8l_dec.c b/thirdparty/libwebp/src/dec/vp8l_dec.c
index 78db014030..1348055128 100644
--- a/thirdparty/libwebp/src/dec/vp8l_dec.c
+++ b/thirdparty/libwebp/src/dec/vp8l_dec.c
@@ -178,7 +178,7 @@ static WEBP_INLINE int PlaneCodeToDistance(int xsize, int plane_code) {
//------------------------------------------------------------------------------
// Decodes the next Huffman code from bit-stream.
-// FillBitWindow(br) needs to be called at minimum every second call
+// VP8LFillBitWindow(br) needs to be called at minimum every second call
// to ReadSymbol, in order to pre-fetch enough bits.
static WEBP_INLINE int ReadSymbol(const HuffmanCode* table,
VP8LBitReader* const br) {
@@ -321,7 +321,7 @@ static int ReadHuffmanCode(int alphabet_size, VP8LDecoder* const dec,
// The first code is either 1 bit or 8 bit code.
int symbol = VP8LReadBits(br, (first_symbol_len_code == 0) ? 1 : 8);
code_lengths[symbol] = 1;
- // The second code (if present), is always 8 bit long.
+ // The second code (if present), is always 8 bits long.
if (num_symbols == 2) {
symbol = VP8LReadBits(br, 8);
code_lengths[symbol] = 1;
@@ -1281,7 +1281,7 @@ static int ExpandColorMap(int num_colors, VP8LTransform* const transform) {
uint8_t* const new_data = (uint8_t*)new_color_map;
new_color_map[0] = transform->data_[0];
for (i = 4; i < 4 * num_colors; ++i) {
- // Equivalent to AddPixelEq(), on a byte-basis.
+ // Equivalent to VP8LAddPixels(), on a byte-basis.
new_data[i] = (data[i] + new_data[i - 4]) & 0xff;
}
for (; i < 4 * final_num_colors; ++i) {
diff --git a/thirdparty/libwebp/src/demux/demux.c b/thirdparty/libwebp/src/demux/demux.c
index f04a2b8450..41387ec2d6 100644
--- a/thirdparty/libwebp/src/demux/demux.c
+++ b/thirdparty/libwebp/src/demux/demux.c
@@ -25,7 +25,7 @@
#define DMUX_MAJ_VERSION 1
#define DMUX_MIN_VERSION 2
-#define DMUX_REV_VERSION 2
+#define DMUX_REV_VERSION 4
typedef struct {
size_t start_; // start location of the data
@@ -614,7 +614,6 @@ static int IsValidExtendedFormat(const WebPDemuxer* const dmux) {
while (f != NULL) {
const int cur_frame_set = f->frame_num_;
- int frame_count = 0;
// Check frame properties.
for (; f != NULL && f->frame_num_ == cur_frame_set; f = f->next_) {
@@ -649,8 +648,6 @@ static int IsValidExtendedFormat(const WebPDemuxer* const dmux) {
dmux->canvas_width_, dmux->canvas_height_)) {
return 0;
}
-
- ++frame_count;
}
}
return 1;
diff --git a/thirdparty/libwebp/src/dsp/alpha_processing_neon.c b/thirdparty/libwebp/src/dsp/alpha_processing_neon.c
index 9e0ace9421..6716fb77f0 100644
--- a/thirdparty/libwebp/src/dsp/alpha_processing_neon.c
+++ b/thirdparty/libwebp/src/dsp/alpha_processing_neon.c
@@ -83,7 +83,7 @@ static void ApplyAlphaMultiply_NEON(uint8_t* rgba, int alpha_first,
static int DispatchAlpha_NEON(const uint8_t* WEBP_RESTRICT alpha,
int alpha_stride, int width, int height,
uint8_t* WEBP_RESTRICT dst, int dst_stride) {
- uint32_t alpha_mask = 0xffffffffu;
+ uint32_t alpha_mask = 0xffu;
uint8x8_t mask8 = vdup_n_u8(0xff);
uint32_t tmp[2];
int i, j;
@@ -107,6 +107,7 @@ static int DispatchAlpha_NEON(const uint8_t* WEBP_RESTRICT alpha,
dst += dst_stride;
}
vst1_u8((uint8_t*)tmp, mask8);
+ alpha_mask *= 0x01010101;
alpha_mask &= tmp[0];
alpha_mask &= tmp[1];
return (alpha_mask != 0xffffffffu);
@@ -135,7 +136,7 @@ static void DispatchAlphaToGreen_NEON(const uint8_t* WEBP_RESTRICT alpha,
static int ExtractAlpha_NEON(const uint8_t* WEBP_RESTRICT argb, int argb_stride,
int width, int height,
uint8_t* WEBP_RESTRICT alpha, int alpha_stride) {
- uint32_t alpha_mask = 0xffffffffu;
+ uint32_t alpha_mask = 0xffu;
uint8x8_t mask8 = vdup_n_u8(0xff);
uint32_t tmp[2];
int i, j;
@@ -157,6 +158,7 @@ static int ExtractAlpha_NEON(const uint8_t* WEBP_RESTRICT argb, int argb_stride,
alpha += alpha_stride;
}
vst1_u8((uint8_t*)tmp, mask8);
+ alpha_mask *= 0x01010101;
alpha_mask &= tmp[0];
alpha_mask &= tmp[1];
return (alpha_mask == 0xffffffffu);
diff --git a/thirdparty/libwebp/src/dsp/cpu.c b/thirdparty/libwebp/src/dsp/cpu.c
index 3145e190a4..a4ba7f2cb7 100644
--- a/thirdparty/libwebp/src/dsp/cpu.c
+++ b/thirdparty/libwebp/src/dsp/cpu.c
@@ -11,7 +11,7 @@
//
// Author: Christian Duvivier (cduvivier@google.com)
-#include "src/dsp/dsp.h"
+#include "src/dsp/cpu.h"
#if defined(WEBP_HAVE_NEON_RTCD)
#include <stdio.h>
diff --git a/thirdparty/libwebp/src/dsp/cpu.h b/thirdparty/libwebp/src/dsp/cpu.h
new file mode 100644
index 0000000000..57a40d87d4
--- /dev/null
+++ b/thirdparty/libwebp/src/dsp/cpu.h
@@ -0,0 +1,254 @@
+// Copyright 2022 Google Inc. All Rights Reserved.
+//
+// Use of this source code is governed by a BSD-style license
+// that can be found in the COPYING file in the root of the source
+// tree. An additional intellectual property rights grant can be found
+// in the file PATENTS. All contributing project authors may
+// be found in the AUTHORS file in the root of the source tree.
+// -----------------------------------------------------------------------------
+//
+// CPU detection functions and macros.
+//
+// Author: Skal (pascal.massimino@gmail.com)
+
+#ifndef WEBP_DSP_CPU_H_
+#define WEBP_DSP_CPU_H_
+
+#ifdef HAVE_CONFIG_H
+#include "src/webp/config.h"
+#endif
+
+#include "src/webp/types.h"
+
+#if defined(__GNUC__)
+#define LOCAL_GCC_VERSION ((__GNUC__ << 8) | __GNUC_MINOR__)
+#define LOCAL_GCC_PREREQ(maj, min) (LOCAL_GCC_VERSION >= (((maj) << 8) | (min)))
+#else
+#define LOCAL_GCC_VERSION 0
+#define LOCAL_GCC_PREREQ(maj, min) 0
+#endif
+
+#if defined(__clang__)
+#define LOCAL_CLANG_VERSION ((__clang_major__ << 8) | __clang_minor__)
+#define LOCAL_CLANG_PREREQ(maj, min) \
+ (LOCAL_CLANG_VERSION >= (((maj) << 8) | (min)))
+#else
+#define LOCAL_CLANG_VERSION 0
+#define LOCAL_CLANG_PREREQ(maj, min) 0
+#endif
+
+#ifndef __has_builtin
+#define __has_builtin(x) 0
+#endif
+
+#if !defined(HAVE_CONFIG_H)
+#if defined(_MSC_VER) && _MSC_VER > 1310 && \
+ (defined(_M_X64) || defined(_M_IX86))
+#define WEBP_MSC_SSE2 // Visual C++ SSE2 targets
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER >= 1500 && \
+ (defined(_M_X64) || defined(_M_IX86))
+#define WEBP_MSC_SSE41 // Visual C++ SSE4.1 targets
+#endif
+#endif
+
+// WEBP_HAVE_* are used to indicate the presence of the instruction set in dsp
+// files without intrinsics, allowing the corresponding Init() to be called.
+// Files containing intrinsics will need to be built targeting the instruction
+// set so should succeed on one of the earlier tests.
+#if (defined(__SSE2__) || defined(WEBP_MSC_SSE2)) && \
+ (!defined(HAVE_CONFIG_H) || defined(WEBP_HAVE_SSE2))
+#define WEBP_USE_SSE2
+#endif
+
+#if defined(WEBP_USE_SSE2) && !defined(WEBP_HAVE_SSE2)
+#define WEBP_HAVE_SSE2
+#endif
+
+#if (defined(__SSE4_1__) || defined(WEBP_MSC_SSE41)) && \
+ (!defined(HAVE_CONFIG_H) || defined(WEBP_HAVE_SSE41))
+#define WEBP_USE_SSE41
+#endif
+
+#if defined(WEBP_USE_SSE41) && !defined(WEBP_HAVE_SSE41)
+#define WEBP_HAVE_SSE41
+#endif
+
+#undef WEBP_MSC_SSE41
+#undef WEBP_MSC_SSE2
+
+// The intrinsics currently cause compiler errors with arm-nacl-gcc and the
+// inline assembly would need to be modified for use with Native Client.
+#if ((defined(__ARM_NEON__) || defined(__aarch64__)) && \
+ (!defined(HAVE_CONFIG_H) || defined(WEBP_HAVE_NEON))) && \
+ !defined(__native_client__)
+#define WEBP_USE_NEON
+#endif
+
+#if !defined(WEBP_USE_NEON) && defined(__ANDROID__) && \
+ defined(__ARM_ARCH_7A__) && defined(HAVE_CPU_FEATURES_H)
+#define WEBP_ANDROID_NEON // Android targets that may have NEON
+#define WEBP_USE_NEON
+#endif
+
+// Note: ARM64 is supported in Visual Studio 2017, but requires the direct
+// inclusion of arm64_neon.h; Visual Studio 2019 includes this file in
+// arm_neon.h. Compile errors were seen with Visual Studio 2019 16.4 with
+// vtbl4_u8(); a fix was made in 16.6.
+#if defined(_MSC_VER) && ((_MSC_VER >= 1700 && defined(_M_ARM)) || \
+ (_MSC_VER >= 1926 && defined(_M_ARM64)))
+#define WEBP_USE_NEON
+#define WEBP_USE_INTRINSICS
+#endif
+
+#if defined(WEBP_USE_NEON) && !defined(WEBP_HAVE_NEON)
+#define WEBP_HAVE_NEON
+#endif
+
+#if defined(__mips__) && !defined(__mips64) && defined(__mips_isa_rev) && \
+ (__mips_isa_rev >= 1) && (__mips_isa_rev < 6)
+#define WEBP_USE_MIPS32
+#if (__mips_isa_rev >= 2)
+#define WEBP_USE_MIPS32_R2
+#if defined(__mips_dspr2) || (defined(__mips_dsp_rev) && __mips_dsp_rev >= 2)
+#define WEBP_USE_MIPS_DSP_R2
+#endif
+#endif
+#endif
+
+#if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
+#define WEBP_USE_MSA
+#endif
+
+#ifndef WEBP_DSP_OMIT_C_CODE
+#define WEBP_DSP_OMIT_C_CODE 1
+#endif
+
+#if defined(WEBP_USE_NEON) && WEBP_DSP_OMIT_C_CODE
+#define WEBP_NEON_OMIT_C_CODE 1
+#else
+#define WEBP_NEON_OMIT_C_CODE 0
+#endif
+
+#if !(LOCAL_CLANG_PREREQ(3, 8) || LOCAL_GCC_PREREQ(4, 8) || \
+ defined(__aarch64__))
+#define WEBP_NEON_WORK_AROUND_GCC 1
+#else
+#define WEBP_NEON_WORK_AROUND_GCC 0
+#endif
+
+// This macro prevents thread_sanitizer from reporting known concurrent writes.
+#define WEBP_TSAN_IGNORE_FUNCTION
+#if defined(__has_feature)
+#if __has_feature(thread_sanitizer)
+#undef WEBP_TSAN_IGNORE_FUNCTION
+#define WEBP_TSAN_IGNORE_FUNCTION __attribute__((no_sanitize_thread))
+#endif
+#endif
+
+#if defined(__has_feature)
+#if __has_feature(memory_sanitizer)
+#define WEBP_MSAN
+#endif
+#endif
+
+#if defined(WEBP_USE_THREAD) && !defined(_WIN32)
+#include <pthread.h> // NOLINT
+
+#define WEBP_DSP_INIT(func) \
+ do { \
+ static volatile VP8CPUInfo func##_last_cpuinfo_used = \
+ (VP8CPUInfo)&func##_last_cpuinfo_used; \
+ static pthread_mutex_t func##_lock = PTHREAD_MUTEX_INITIALIZER; \
+ if (pthread_mutex_lock(&func##_lock)) break; \
+ if (func##_last_cpuinfo_used != VP8GetCPUInfo) func(); \
+ func##_last_cpuinfo_used = VP8GetCPUInfo; \
+ (void)pthread_mutex_unlock(&func##_lock); \
+ } while (0)
+#else // !(defined(WEBP_USE_THREAD) && !defined(_WIN32))
+#define WEBP_DSP_INIT(func) \
+ do { \
+ static volatile VP8CPUInfo func##_last_cpuinfo_used = \
+ (VP8CPUInfo)&func##_last_cpuinfo_used; \
+ if (func##_last_cpuinfo_used == VP8GetCPUInfo) break; \
+ func(); \
+ func##_last_cpuinfo_used = VP8GetCPUInfo; \
+ } while (0)
+#endif // defined(WEBP_USE_THREAD) && !defined(_WIN32)
+
+// Defines an Init + helper function that control multiple initialization of
+// function pointers / tables.
+/* Usage:
+ WEBP_DSP_INIT_FUNC(InitFunc) {
+ ...function body
+ }
+*/
+#define WEBP_DSP_INIT_FUNC(name) \
+ static WEBP_TSAN_IGNORE_FUNCTION void name##_body(void); \
+ WEBP_TSAN_IGNORE_FUNCTION void name(void) { WEBP_DSP_INIT(name##_body); } \
+ static WEBP_TSAN_IGNORE_FUNCTION void name##_body(void)
+
+#define WEBP_UBSAN_IGNORE_UNDEF
+#define WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW
+#if defined(__clang__) && defined(__has_attribute)
+#if __has_attribute(no_sanitize)
+// This macro prevents the undefined behavior sanitizer from reporting
+// failures. This is only meant to silence unaligned loads on platforms that
+// are known to support them.
+#undef WEBP_UBSAN_IGNORE_UNDEF
+#define WEBP_UBSAN_IGNORE_UNDEF __attribute__((no_sanitize("undefined")))
+
+// This macro prevents the undefined behavior sanitizer from reporting
+// failures related to unsigned integer overflows. This is only meant to
+// silence cases where this well defined behavior is expected.
+#undef WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW
+#define WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW \
+ __attribute__((no_sanitize("unsigned-integer-overflow")))
+#endif
+#endif
+
+// If 'ptr' is NULL, returns NULL. Otherwise returns 'ptr + off'.
+// Prevents undefined behavior sanitizer nullptr-with-nonzero-offset warning.
+#if !defined(WEBP_OFFSET_PTR)
+#define WEBP_OFFSET_PTR(ptr, off) (((ptr) == NULL) ? NULL : ((ptr) + (off)))
+#endif
+
+// Regularize the definition of WEBP_SWAP_16BIT_CSP (backward compatibility)
+#if !defined(WEBP_SWAP_16BIT_CSP)
+#define WEBP_SWAP_16BIT_CSP 0
+#endif
+
+// some endian fix (e.g.: mips-gcc doesn't define __BIG_ENDIAN__)
+#if !defined(WORDS_BIGENDIAN) && \
+ (defined(__BIG_ENDIAN__) || defined(_M_PPC) || \
+ (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)))
+#define WORDS_BIGENDIAN
+#endif
+
+typedef enum {
+ kSSE2,
+ kSSE3,
+ kSlowSSSE3, // special feature for slow SSSE3 architectures
+ kSSE4_1,
+ kAVX,
+ kAVX2,
+ kNEON,
+ kMIPS32,
+ kMIPSdspR2,
+ kMSA
+} CPUFeature;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// returns true if the CPU supports the feature.
+typedef int (*VP8CPUInfo)(CPUFeature feature);
+WEBP_EXTERN VP8CPUInfo VP8GetCPUInfo;
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WEBP_DSP_CPU_H_
diff --git a/thirdparty/libwebp/src/dsp/dsp.h b/thirdparty/libwebp/src/dsp/dsp.h
index c4f57e4d5b..d2000b8efc 100644
--- a/thirdparty/libwebp/src/dsp/dsp.h
+++ b/thirdparty/libwebp/src/dsp/dsp.h
@@ -18,6 +18,7 @@
#include "src/webp/config.h"
#endif
+#include "src/dsp/cpu.h"
#include "src/webp/types.h"
#ifdef __cplusplus
@@ -43,225 +44,6 @@ extern "C" {
#define WEBP_RESTRICT
#endif
-//------------------------------------------------------------------------------
-// CPU detection
-
-#if defined(__GNUC__)
-# define LOCAL_GCC_VERSION ((__GNUC__ << 8) | __GNUC_MINOR__)
-# define LOCAL_GCC_PREREQ(maj, min) \
- (LOCAL_GCC_VERSION >= (((maj) << 8) | (min)))
-#else
-# define LOCAL_GCC_VERSION 0
-# define LOCAL_GCC_PREREQ(maj, min) 0
-#endif
-
-#if defined(__clang__)
-# define LOCAL_CLANG_VERSION ((__clang_major__ << 8) | __clang_minor__)
-# define LOCAL_CLANG_PREREQ(maj, min) \
- (LOCAL_CLANG_VERSION >= (((maj) << 8) | (min)))
-#else
-# define LOCAL_CLANG_VERSION 0
-# define LOCAL_CLANG_PREREQ(maj, min) 0
-#endif
-
-#ifndef __has_builtin
-# define __has_builtin(x) 0
-#endif
-
-#if !defined(HAVE_CONFIG_H)
-#if defined(_MSC_VER) && _MSC_VER > 1310 && \
- (defined(_M_X64) || defined(_M_IX86))
-#define WEBP_MSC_SSE2 // Visual C++ SSE2 targets
-#endif
-
-#if defined(_MSC_VER) && _MSC_VER >= 1500 && \
- (defined(_M_X64) || defined(_M_IX86))
-#define WEBP_MSC_SSE41 // Visual C++ SSE4.1 targets
-#endif
-#endif
-
-// WEBP_HAVE_* are used to indicate the presence of the instruction set in dsp
-// files without intrinsics, allowing the corresponding Init() to be called.
-// Files containing intrinsics will need to be built targeting the instruction
-// set so should succeed on one of the earlier tests.
-#if (defined(__SSE2__) || defined(WEBP_MSC_SSE2)) && \
- (!defined(HAVE_CONFIG_H) || defined(WEBP_HAVE_SSE2))
-#define WEBP_USE_SSE2
-#endif
-
-#if defined(WEBP_USE_SSE2) && !defined(WEBP_HAVE_SSE2)
-#define WEBP_HAVE_SSE2
-#endif
-
-#if (defined(__SSE4_1__) || defined(WEBP_MSC_SSE41)) && \
- (!defined(HAVE_CONFIG_H) || defined(WEBP_HAVE_SSE41))
-#define WEBP_USE_SSE41
-#endif
-
-#if defined(WEBP_USE_SSE41) && !defined(WEBP_HAVE_SSE41)
-#define WEBP_HAVE_SSE41
-#endif
-
-#undef WEBP_MSC_SSE41
-#undef WEBP_MSC_SSE2
-
-// The intrinsics currently cause compiler errors with arm-nacl-gcc and the
-// inline assembly would need to be modified for use with Native Client.
-#if ((defined(__ARM_NEON__) || defined(__aarch64__)) && \
- (!defined(HAVE_CONFIG_H) || defined(WEBP_HAVE_NEON))) && \
- !defined(__native_client__)
-#define WEBP_USE_NEON
-#endif
-
-#if !defined(WEBP_USE_NEON) && defined(__ANDROID__) && \
- defined(__ARM_ARCH_7A__) && defined(HAVE_CPU_FEATURES_H)
-#define WEBP_ANDROID_NEON // Android targets that may have NEON
-#define WEBP_USE_NEON
-#endif
-
-// Note: ARM64 is supported in Visual Studio 2017, but requires the direct
-// inclusion of arm64_neon.h; Visual Studio 2019 includes this file in
-// arm_neon.h.
-#if defined(_MSC_VER) && \
- ((_MSC_VER >= 1700 && defined(_M_ARM)) || \
- (_MSC_VER >= 1920 && defined(_M_ARM64)))
-#define WEBP_USE_NEON
-#define WEBP_USE_INTRINSICS
-#endif
-
-#if defined(WEBP_USE_NEON) && !defined(WEBP_HAVE_NEON)
-#define WEBP_HAVE_NEON
-#endif
-
-#if defined(__mips__) && !defined(__mips64) && \
- defined(__mips_isa_rev) && (__mips_isa_rev >= 1) && (__mips_isa_rev < 6)
-#define WEBP_USE_MIPS32
-#if (__mips_isa_rev >= 2)
-#define WEBP_USE_MIPS32_R2
-#if defined(__mips_dspr2) || (defined(__mips_dsp_rev) && __mips_dsp_rev >= 2)
-#define WEBP_USE_MIPS_DSP_R2
-#endif
-#endif
-#endif
-
-#if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
-#define WEBP_USE_MSA
-#endif
-
-#ifndef WEBP_DSP_OMIT_C_CODE
-#define WEBP_DSP_OMIT_C_CODE 1
-#endif
-
-#if defined(WEBP_USE_NEON) && WEBP_DSP_OMIT_C_CODE
-#define WEBP_NEON_OMIT_C_CODE 1
-#else
-#define WEBP_NEON_OMIT_C_CODE 0
-#endif
-
-#if !(LOCAL_CLANG_PREREQ(3,8) || LOCAL_GCC_PREREQ(4,8) || defined(__aarch64__))
-#define WEBP_NEON_WORK_AROUND_GCC 1
-#else
-#define WEBP_NEON_WORK_AROUND_GCC 0
-#endif
-
-// This macro prevents thread_sanitizer from reporting known concurrent writes.
-#define WEBP_TSAN_IGNORE_FUNCTION
-#if defined(__has_feature)
-#if __has_feature(thread_sanitizer)
-#undef WEBP_TSAN_IGNORE_FUNCTION
-#define WEBP_TSAN_IGNORE_FUNCTION __attribute__((no_sanitize_thread))
-#endif
-#endif
-
-#if defined(WEBP_USE_THREAD) && !defined(_WIN32)
-#include <pthread.h> // NOLINT
-
-#define WEBP_DSP_INIT(func) do { \
- static volatile VP8CPUInfo func ## _last_cpuinfo_used = \
- (VP8CPUInfo)&func ## _last_cpuinfo_used; \
- static pthread_mutex_t func ## _lock = PTHREAD_MUTEX_INITIALIZER; \
- if (pthread_mutex_lock(&func ## _lock)) break; \
- if (func ## _last_cpuinfo_used != VP8GetCPUInfo) func(); \
- func ## _last_cpuinfo_used = VP8GetCPUInfo; \
- (void)pthread_mutex_unlock(&func ## _lock); \
-} while (0)
-#else // !(defined(WEBP_USE_THREAD) && !defined(_WIN32))
-#define WEBP_DSP_INIT(func) do { \
- static volatile VP8CPUInfo func ## _last_cpuinfo_used = \
- (VP8CPUInfo)&func ## _last_cpuinfo_used; \
- if (func ## _last_cpuinfo_used == VP8GetCPUInfo) break; \
- func(); \
- func ## _last_cpuinfo_used = VP8GetCPUInfo; \
-} while (0)
-#endif // defined(WEBP_USE_THREAD) && !defined(_WIN32)
-
-// Defines an Init + helper function that control multiple initialization of
-// function pointers / tables.
-/* Usage:
- WEBP_DSP_INIT_FUNC(InitFunc) {
- ...function body
- }
-*/
-#define WEBP_DSP_INIT_FUNC(name) \
- static WEBP_TSAN_IGNORE_FUNCTION void name ## _body(void); \
- WEBP_TSAN_IGNORE_FUNCTION void name(void) { \
- WEBP_DSP_INIT(name ## _body); \
- } \
- static WEBP_TSAN_IGNORE_FUNCTION void name ## _body(void)
-
-#define WEBP_UBSAN_IGNORE_UNDEF
-#define WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW
-#if defined(__clang__) && defined(__has_attribute)
-#if __has_attribute(no_sanitize)
-// This macro prevents the undefined behavior sanitizer from reporting
-// failures. This is only meant to silence unaligned loads on platforms that
-// are known to support them.
-#undef WEBP_UBSAN_IGNORE_UNDEF
-#define WEBP_UBSAN_IGNORE_UNDEF \
- __attribute__((no_sanitize("undefined")))
-
-// This macro prevents the undefined behavior sanitizer from reporting
-// failures related to unsigned integer overflows. This is only meant to
-// silence cases where this well defined behavior is expected.
-#undef WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW
-#define WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW \
- __attribute__((no_sanitize("unsigned-integer-overflow")))
-#endif
-#endif
-
-// If 'ptr' is NULL, returns NULL. Otherwise returns 'ptr + off'.
-// Prevents undefined behavior sanitizer nullptr-with-nonzero-offset warning.
-#if !defined(WEBP_OFFSET_PTR)
-#define WEBP_OFFSET_PTR(ptr, off) (((ptr) == NULL) ? NULL : ((ptr) + (off)))
-#endif
-
-// Regularize the definition of WEBP_SWAP_16BIT_CSP (backward compatibility)
-#if !defined(WEBP_SWAP_16BIT_CSP)
-#define WEBP_SWAP_16BIT_CSP 0
-#endif
-
-// some endian fix (e.g.: mips-gcc doesn't define __BIG_ENDIAN__)
-#if !defined(WORDS_BIGENDIAN) && \
- (defined(__BIG_ENDIAN__) || defined(_M_PPC) || \
- (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)))
-#define WORDS_BIGENDIAN
-#endif
-
-typedef enum {
- kSSE2,
- kSSE3,
- kSlowSSSE3, // special feature for slow SSSE3 architectures
- kSSE4_1,
- kAVX,
- kAVX2,
- kNEON,
- kMIPS32,
- kMIPSdspR2,
- kMSA
-} CPUFeature;
-// returns true if the CPU supports the feature.
-typedef int (*VP8CPUInfo)(CPUFeature feature);
-WEBP_EXTERN VP8CPUInfo VP8GetCPUInfo;
//------------------------------------------------------------------------------
// Init stub generator
@@ -550,15 +332,6 @@ extern void WebPConvertARGBToUV_C(const uint32_t* argb, uint8_t* u, uint8_t* v,
extern void WebPConvertRGBA32ToUV_C(const uint16_t* rgb,
uint8_t* u, uint8_t* v, int width);
-// utilities for accurate RGB->YUV conversion
-extern uint64_t (*WebPSharpYUVUpdateY)(const uint16_t* src, const uint16_t* ref,
- uint16_t* dst, int len);
-extern void (*WebPSharpYUVUpdateRGB)(const int16_t* src, const int16_t* ref,
- int16_t* dst, int len);
-extern void (*WebPSharpYUVFilterRow)(const int16_t* A, const int16_t* B,
- int len,
- const uint16_t* best_y, uint16_t* out);
-
// Must be called before using the above.
void WebPInitConvertARGBToYUV(void);
diff --git a/thirdparty/libwebp/src/dsp/lossless.h b/thirdparty/libwebp/src/dsp/lossless.h
index c26c6bca07..de60d95d0b 100644
--- a/thirdparty/libwebp/src/dsp/lossless.h
+++ b/thirdparty/libwebp/src/dsp/lossless.h
@@ -182,9 +182,9 @@ extern VP8LPredictorAddSubFunc VP8LPredictorsSub_C[16];
// -----------------------------------------------------------------------------
// Huffman-cost related functions.
-typedef double (*VP8LCostFunc)(const uint32_t* population, int length);
-typedef double (*VP8LCostCombinedFunc)(const uint32_t* X, const uint32_t* Y,
- int length);
+typedef float (*VP8LCostFunc)(const uint32_t* population, int length);
+typedef float (*VP8LCostCombinedFunc)(const uint32_t* X, const uint32_t* Y,
+ int length);
typedef float (*VP8LCombinedShannonEntropyFunc)(const int X[256],
const int Y[256]);
@@ -198,7 +198,7 @@ typedef struct { // small struct to hold counters
} VP8LStreaks;
typedef struct { // small struct to hold bit entropy results
- double entropy; // entropy
+ float entropy; // entropy
uint32_t sum; // sum of the population
int nonzeros; // number of non-zero elements in the population
uint32_t max_val; // maximum value in the population
diff --git a/thirdparty/libwebp/src/dsp/lossless_enc.c b/thirdparty/libwebp/src/dsp/lossless_enc.c
index 1580631e38..de6c4ace5f 100644
--- a/thirdparty/libwebp/src/dsp/lossless_enc.c
+++ b/thirdparty/libwebp/src/dsp/lossless_enc.c
@@ -402,7 +402,7 @@ static float FastLog2Slow_C(uint32_t v) {
// Compute the combined Shanon's entropy for distribution {X} and {X+Y}
static float CombinedShannonEntropy_C(const int X[256], const int Y[256]) {
int i;
- double retval = 0.;
+ float retval = 0.f;
int sumX = 0, sumXY = 0;
for (i = 0; i < 256; ++i) {
const int x = X[i];
@@ -418,7 +418,7 @@ static float CombinedShannonEntropy_C(const int X[256], const int Y[256]) {
}
}
retval += VP8LFastSLog2(sumX) + VP8LFastSLog2(sumXY);
- return (float)retval;
+ return retval;
}
void VP8LBitEntropyInit(VP8LBitEntropy* const entropy) {
@@ -636,17 +636,17 @@ void VP8LBundleColorMap_C(const uint8_t* const row, int width, int xbits,
//------------------------------------------------------------------------------
-static double ExtraCost_C(const uint32_t* population, int length) {
+static float ExtraCost_C(const uint32_t* population, int length) {
int i;
- double cost = 0.;
+ float cost = 0.f;
for (i = 2; i < length - 2; ++i) cost += (i >> 1) * population[i + 2];
return cost;
}
-static double ExtraCostCombined_C(const uint32_t* X, const uint32_t* Y,
+static float ExtraCostCombined_C(const uint32_t* X, const uint32_t* Y,
int length) {
int i;
- double cost = 0.;
+ float cost = 0.f;
for (i = 2; i < length - 2; ++i) {
const int xy = X[i + 2] + Y[i + 2];
cost += (i >> 1) * xy;
diff --git a/thirdparty/libwebp/src/dsp/lossless_enc_mips32.c b/thirdparty/libwebp/src/dsp/lossless_enc_mips32.c
index 0412a093cf..639f786631 100644
--- a/thirdparty/libwebp/src/dsp/lossless_enc_mips32.c
+++ b/thirdparty/libwebp/src/dsp/lossless_enc_mips32.c
@@ -103,8 +103,8 @@ static float FastLog2Slow_MIPS32(uint32_t v) {
// cost += i * *(pop + 1);
// pop += 2;
// }
-// return (double)cost;
-static double ExtraCost_MIPS32(const uint32_t* const population, int length) {
+// return (float)cost;
+static float ExtraCost_MIPS32(const uint32_t* const population, int length) {
int i, temp0, temp1;
const uint32_t* pop = &population[4];
const uint32_t* const LoopEnd = &population[length];
@@ -130,7 +130,7 @@ static double ExtraCost_MIPS32(const uint32_t* const population, int length) {
: "memory", "hi", "lo"
);
- return (double)((int64_t)temp0 << 32 | temp1);
+ return (float)((int64_t)temp0 << 32 | temp1);
}
// C version of this function:
@@ -148,9 +148,9 @@ static double ExtraCost_MIPS32(const uint32_t* const population, int length) {
// pX += 2;
// pY += 2;
// }
-// return (double)cost;
-static double ExtraCostCombined_MIPS32(const uint32_t* const X,
- const uint32_t* const Y, int length) {
+// return (float)cost;
+static float ExtraCostCombined_MIPS32(const uint32_t* const X,
+ const uint32_t* const Y, int length) {
int i, temp0, temp1, temp2, temp3;
const uint32_t* pX = &X[4];
const uint32_t* pY = &Y[4];
@@ -183,7 +183,7 @@ static double ExtraCostCombined_MIPS32(const uint32_t* const X,
: "memory", "hi", "lo"
);
- return (double)((int64_t)temp0 << 32 | temp1);
+ return (float)((int64_t)temp0 << 32 | temp1);
}
#define HUFFMAN_COST_PASS \
@@ -347,24 +347,24 @@ static void GetCombinedEntropyUnrefined_MIPS32(const uint32_t X[],
static void AddVector_MIPS32(const uint32_t* pa, const uint32_t* pb,
uint32_t* pout, int size) {
uint32_t temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
- const uint32_t end = ((size) / 4) * 4;
+ const int end = ((size) / 4) * 4;
const uint32_t* const LoopEnd = pa + end;
int i;
ASM_START
ADD_TO_OUT(0, 4, 8, 12, 1, pa, pb, pout)
ASM_END_0
- for (i = end; i < size; ++i) pout[i] = pa[i] + pb[i];
+ for (i = 0; i < size - end; ++i) pout[i] = pa[i] + pb[i];
}
static void AddVectorEq_MIPS32(const uint32_t* pa, uint32_t* pout, int size) {
uint32_t temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
- const uint32_t end = ((size) / 4) * 4;
+ const int end = ((size) / 4) * 4;
const uint32_t* const LoopEnd = pa + end;
int i;
ASM_START
ADD_TO_OUT(0, 4, 8, 12, 0, pa, pout, pout)
ASM_END_1
- for (i = end; i < size; ++i) pout[i] += pa[i];
+ for (i = 0; i < size - end; ++i) pout[i] += pa[i];
}
#undef ASM_END_1
diff --git a/thirdparty/libwebp/src/dsp/lossless_enc_sse2.c b/thirdparty/libwebp/src/dsp/lossless_enc_sse2.c
index b2f83b871c..948001a3d5 100644
--- a/thirdparty/libwebp/src/dsp/lossless_enc_sse2.c
+++ b/thirdparty/libwebp/src/dsp/lossless_enc_sse2.c
@@ -239,7 +239,7 @@ static void AddVectorEq_SSE2(const uint32_t* a, uint32_t* out, int size) {
static float CombinedShannonEntropy_SSE2(const int X[256], const int Y[256]) {
int i;
- double retval = 0.;
+ float retval = 0.f;
int sumX = 0, sumXY = 0;
const __m128i zero = _mm_setzero_si128();
@@ -273,7 +273,7 @@ static float CombinedShannonEntropy_SSE2(const int X[256], const int Y[256]) {
}
}
retval += VP8LFastSLog2(sumX) + VP8LFastSLog2(sumXY);
- return (float)retval;
+ return retval;
}
#else
diff --git a/thirdparty/libwebp/src/dsp/yuv.c b/thirdparty/libwebp/src/dsp/yuv.c
index 48466f8b11..d16c13d3ca 100644
--- a/thirdparty/libwebp/src/dsp/yuv.c
+++ b/thirdparty/libwebp/src/dsp/yuv.c
@@ -194,50 +194,6 @@ void WebPConvertRGBA32ToUV_C(const uint16_t* rgb,
//-----------------------------------------------------------------------------
-#if !WEBP_NEON_OMIT_C_CODE
-#define MAX_Y ((1 << 10) - 1) // 10b precision over 16b-arithmetic
-static uint16_t clip_y(int v) {
- return (v < 0) ? 0 : (v > MAX_Y) ? MAX_Y : (uint16_t)v;
-}
-
-static uint64_t SharpYUVUpdateY_C(const uint16_t* ref, const uint16_t* src,
- uint16_t* dst, int len) {
- uint64_t diff = 0;
- int i;
- for (i = 0; i < len; ++i) {
- const int diff_y = ref[i] - src[i];
- const int new_y = (int)dst[i] + diff_y;
- dst[i] = clip_y(new_y);
- diff += (uint64_t)abs(diff_y);
- }
- return diff;
-}
-
-static void SharpYUVUpdateRGB_C(const int16_t* ref, const int16_t* src,
- int16_t* dst, int len) {
- int i;
- for (i = 0; i < len; ++i) {
- const int diff_uv = ref[i] - src[i];
- dst[i] += diff_uv;
- }
-}
-
-static void SharpYUVFilterRow_C(const int16_t* A, const int16_t* B, int len,
- const uint16_t* best_y, uint16_t* out) {
- int i;
- for (i = 0; i < len; ++i, ++A, ++B) {
- const int v0 = (A[0] * 9 + A[1] * 3 + B[0] * 3 + B[1] + 8) >> 4;
- const int v1 = (A[1] * 9 + A[0] * 3 + B[1] * 3 + B[0] + 8) >> 4;
- out[2 * i + 0] = clip_y(best_y[2 * i + 0] + v0);
- out[2 * i + 1] = clip_y(best_y[2 * i + 1] + v1);
- }
-}
-#endif // !WEBP_NEON_OMIT_C_CODE
-
-#undef MAX_Y
-
-//-----------------------------------------------------------------------------
-
void (*WebPConvertRGB24ToY)(const uint8_t* rgb, uint8_t* y, int width);
void (*WebPConvertBGR24ToY)(const uint8_t* bgr, uint8_t* y, int width);
void (*WebPConvertRGBA32ToUV)(const uint16_t* rgb,
@@ -247,18 +203,9 @@ void (*WebPConvertARGBToY)(const uint32_t* argb, uint8_t* y, int width);
void (*WebPConvertARGBToUV)(const uint32_t* argb, uint8_t* u, uint8_t* v,
int src_width, int do_store);
-uint64_t (*WebPSharpYUVUpdateY)(const uint16_t* ref, const uint16_t* src,
- uint16_t* dst, int len);
-void (*WebPSharpYUVUpdateRGB)(const int16_t* ref, const int16_t* src,
- int16_t* dst, int len);
-void (*WebPSharpYUVFilterRow)(const int16_t* A, const int16_t* B, int len,
- const uint16_t* best_y, uint16_t* out);
-
extern void WebPInitConvertARGBToYUVSSE2(void);
extern void WebPInitConvertARGBToYUVSSE41(void);
extern void WebPInitConvertARGBToYUVNEON(void);
-extern void WebPInitSharpYUVSSE2(void);
-extern void WebPInitSharpYUVNEON(void);
WEBP_DSP_INIT_FUNC(WebPInitConvertARGBToYUV) {
WebPConvertARGBToY = ConvertARGBToY_C;
@@ -269,17 +216,10 @@ WEBP_DSP_INIT_FUNC(WebPInitConvertARGBToYUV) {
WebPConvertRGBA32ToUV = WebPConvertRGBA32ToUV_C;
-#if !WEBP_NEON_OMIT_C_CODE
- WebPSharpYUVUpdateY = SharpYUVUpdateY_C;
- WebPSharpYUVUpdateRGB = SharpYUVUpdateRGB_C;
- WebPSharpYUVFilterRow = SharpYUVFilterRow_C;
-#endif
-
if (VP8GetCPUInfo != NULL) {
#if defined(WEBP_HAVE_SSE2)
if (VP8GetCPUInfo(kSSE2)) {
WebPInitConvertARGBToYUVSSE2();
- WebPInitSharpYUVSSE2();
}
#endif // WEBP_HAVE_SSE2
#if defined(WEBP_HAVE_SSE41)
@@ -293,7 +233,6 @@ WEBP_DSP_INIT_FUNC(WebPInitConvertARGBToYUV) {
if (WEBP_NEON_OMIT_C_CODE ||
(VP8GetCPUInfo != NULL && VP8GetCPUInfo(kNEON))) {
WebPInitConvertARGBToYUVNEON();
- WebPInitSharpYUVNEON();
}
#endif // WEBP_HAVE_NEON
@@ -302,7 +241,4 @@ WEBP_DSP_INIT_FUNC(WebPInitConvertARGBToYUV) {
assert(WebPConvertRGB24ToY != NULL);
assert(WebPConvertBGR24ToY != NULL);
assert(WebPConvertRGBA32ToUV != NULL);
- assert(WebPSharpYUVUpdateY != NULL);
- assert(WebPSharpYUVUpdateRGB != NULL);
- assert(WebPSharpYUVFilterRow != NULL);
}
diff --git a/thirdparty/libwebp/src/dsp/yuv_neon.c b/thirdparty/libwebp/src/dsp/yuv_neon.c
index a34d60248f..ff77b00980 100644
--- a/thirdparty/libwebp/src/dsp/yuv_neon.c
+++ b/thirdparty/libwebp/src/dsp/yuv_neon.c
@@ -173,116 +173,8 @@ WEBP_TSAN_IGNORE_FUNCTION void WebPInitConvertARGBToYUVNEON(void) {
WebPConvertRGBA32ToUV = ConvertRGBA32ToUV_NEON;
}
-//------------------------------------------------------------------------------
-
-#define MAX_Y ((1 << 10) - 1) // 10b precision over 16b-arithmetic
-static uint16_t clip_y_NEON(int v) {
- return (v < 0) ? 0 : (v > MAX_Y) ? MAX_Y : (uint16_t)v;
-}
-
-static uint64_t SharpYUVUpdateY_NEON(const uint16_t* ref, const uint16_t* src,
- uint16_t* dst, int len) {
- int i;
- const int16x8_t zero = vdupq_n_s16(0);
- const int16x8_t max = vdupq_n_s16(MAX_Y);
- uint64x2_t sum = vdupq_n_u64(0);
- uint64_t diff;
-
- for (i = 0; i + 8 <= len; i += 8) {
- const int16x8_t A = vreinterpretq_s16_u16(vld1q_u16(ref + i));
- const int16x8_t B = vreinterpretq_s16_u16(vld1q_u16(src + i));
- const int16x8_t C = vreinterpretq_s16_u16(vld1q_u16(dst + i));
- const int16x8_t D = vsubq_s16(A, B); // diff_y
- const int16x8_t F = vaddq_s16(C, D); // new_y
- const uint16x8_t H =
- vreinterpretq_u16_s16(vmaxq_s16(vminq_s16(F, max), zero));
- const int16x8_t I = vabsq_s16(D); // abs(diff_y)
- vst1q_u16(dst + i, H);
- sum = vpadalq_u32(sum, vpaddlq_u16(vreinterpretq_u16_s16(I)));
- }
- diff = vgetq_lane_u64(sum, 0) + vgetq_lane_u64(sum, 1);
- for (; i < len; ++i) {
- const int diff_y = ref[i] - src[i];
- const int new_y = (int)(dst[i]) + diff_y;
- dst[i] = clip_y_NEON(new_y);
- diff += (uint64_t)(abs(diff_y));
- }
- return diff;
-}
-
-static void SharpYUVUpdateRGB_NEON(const int16_t* ref, const int16_t* src,
- int16_t* dst, int len) {
- int i;
- for (i = 0; i + 8 <= len; i += 8) {
- const int16x8_t A = vld1q_s16(ref + i);
- const int16x8_t B = vld1q_s16(src + i);
- const int16x8_t C = vld1q_s16(dst + i);
- const int16x8_t D = vsubq_s16(A, B); // diff_uv
- const int16x8_t E = vaddq_s16(C, D); // new_uv
- vst1q_s16(dst + i, E);
- }
- for (; i < len; ++i) {
- const int diff_uv = ref[i] - src[i];
- dst[i] += diff_uv;
- }
-}
-
-static void SharpYUVFilterRow_NEON(const int16_t* A, const int16_t* B, int len,
- const uint16_t* best_y, uint16_t* out) {
- int i;
- const int16x8_t max = vdupq_n_s16(MAX_Y);
- const int16x8_t zero = vdupq_n_s16(0);
- for (i = 0; i + 8 <= len; i += 8) {
- const int16x8_t a0 = vld1q_s16(A + i + 0);
- const int16x8_t a1 = vld1q_s16(A + i + 1);
- const int16x8_t b0 = vld1q_s16(B + i + 0);
- const int16x8_t b1 = vld1q_s16(B + i + 1);
- const int16x8_t a0b1 = vaddq_s16(a0, b1);
- const int16x8_t a1b0 = vaddq_s16(a1, b0);
- const int16x8_t a0a1b0b1 = vaddq_s16(a0b1, a1b0); // A0+A1+B0+B1
- const int16x8_t a0b1_2 = vaddq_s16(a0b1, a0b1); // 2*(A0+B1)
- const int16x8_t a1b0_2 = vaddq_s16(a1b0, a1b0); // 2*(A1+B0)
- const int16x8_t c0 = vshrq_n_s16(vaddq_s16(a0b1_2, a0a1b0b1), 3);
- const int16x8_t c1 = vshrq_n_s16(vaddq_s16(a1b0_2, a0a1b0b1), 3);
- const int16x8_t d0 = vaddq_s16(c1, a0);
- const int16x8_t d1 = vaddq_s16(c0, a1);
- const int16x8_t e0 = vrshrq_n_s16(d0, 1);
- const int16x8_t e1 = vrshrq_n_s16(d1, 1);
- const int16x8x2_t f = vzipq_s16(e0, e1);
- const int16x8_t g0 = vreinterpretq_s16_u16(vld1q_u16(best_y + 2 * i + 0));
- const int16x8_t g1 = vreinterpretq_s16_u16(vld1q_u16(best_y + 2 * i + 8));
- const int16x8_t h0 = vaddq_s16(g0, f.val[0]);
- const int16x8_t h1 = vaddq_s16(g1, f.val[1]);
- const int16x8_t i0 = vmaxq_s16(vminq_s16(h0, max), zero);
- const int16x8_t i1 = vmaxq_s16(vminq_s16(h1, max), zero);
- vst1q_u16(out + 2 * i + 0, vreinterpretq_u16_s16(i0));
- vst1q_u16(out + 2 * i + 8, vreinterpretq_u16_s16(i1));
- }
- for (; i < len; ++i) {
- const int a0b1 = A[i + 0] + B[i + 1];
- const int a1b0 = A[i + 1] + B[i + 0];
- const int a0a1b0b1 = a0b1 + a1b0 + 8;
- const int v0 = (8 * A[i + 0] + 2 * a1b0 + a0a1b0b1) >> 4;
- const int v1 = (8 * A[i + 1] + 2 * a0b1 + a0a1b0b1) >> 4;
- out[2 * i + 0] = clip_y_NEON(best_y[2 * i + 0] + v0);
- out[2 * i + 1] = clip_y_NEON(best_y[2 * i + 1] + v1);
- }
-}
-#undef MAX_Y
-
-//------------------------------------------------------------------------------
-
-extern void WebPInitSharpYUVNEON(void);
-
-WEBP_TSAN_IGNORE_FUNCTION void WebPInitSharpYUVNEON(void) {
- WebPSharpYUVUpdateY = SharpYUVUpdateY_NEON;
- WebPSharpYUVUpdateRGB = SharpYUVUpdateRGB_NEON;
- WebPSharpYUVFilterRow = SharpYUVFilterRow_NEON;
-}
-
#else // !WEBP_USE_NEON
WEBP_DSP_INIT_STUB(WebPInitConvertARGBToYUVNEON)
-WEBP_DSP_INIT_STUB(WebPInitSharpYUVNEON)
#endif // WEBP_USE_NEON
diff --git a/thirdparty/libwebp/src/dsp/yuv_sse2.c b/thirdparty/libwebp/src/dsp/yuv_sse2.c
index baa48d5371..970bbb7884 100644
--- a/thirdparty/libwebp/src/dsp/yuv_sse2.c
+++ b/thirdparty/libwebp/src/dsp/yuv_sse2.c
@@ -747,128 +747,9 @@ WEBP_TSAN_IGNORE_FUNCTION void WebPInitConvertARGBToYUVSSE2(void) {
WebPConvertRGBA32ToUV = ConvertRGBA32ToUV_SSE2;
}
-//------------------------------------------------------------------------------
-
-#define MAX_Y ((1 << 10) - 1) // 10b precision over 16b-arithmetic
-static uint16_t clip_y(int v) {
- return (v < 0) ? 0 : (v > MAX_Y) ? MAX_Y : (uint16_t)v;
-}
-
-static uint64_t SharpYUVUpdateY_SSE2(const uint16_t* ref, const uint16_t* src,
- uint16_t* dst, int len) {
- uint64_t diff = 0;
- uint32_t tmp[4];
- int i;
- const __m128i zero = _mm_setzero_si128();
- const __m128i max = _mm_set1_epi16(MAX_Y);
- const __m128i one = _mm_set1_epi16(1);
- __m128i sum = zero;
-
- for (i = 0; i + 8 <= len; i += 8) {
- const __m128i A = _mm_loadu_si128((const __m128i*)(ref + i));
- const __m128i B = _mm_loadu_si128((const __m128i*)(src + i));
- const __m128i C = _mm_loadu_si128((const __m128i*)(dst + i));
- const __m128i D = _mm_sub_epi16(A, B); // diff_y
- const __m128i E = _mm_cmpgt_epi16(zero, D); // sign (-1 or 0)
- const __m128i F = _mm_add_epi16(C, D); // new_y
- const __m128i G = _mm_or_si128(E, one); // -1 or 1
- const __m128i H = _mm_max_epi16(_mm_min_epi16(F, max), zero);
- const __m128i I = _mm_madd_epi16(D, G); // sum(abs(...))
- _mm_storeu_si128((__m128i*)(dst + i), H);
- sum = _mm_add_epi32(sum, I);
- }
- _mm_storeu_si128((__m128i*)tmp, sum);
- diff = tmp[3] + tmp[2] + tmp[1] + tmp[0];
- for (; i < len; ++i) {
- const int diff_y = ref[i] - src[i];
- const int new_y = (int)dst[i] + diff_y;
- dst[i] = clip_y(new_y);
- diff += (uint64_t)abs(diff_y);
- }
- return diff;
-}
-
-static void SharpYUVUpdateRGB_SSE2(const int16_t* ref, const int16_t* src,
- int16_t* dst, int len) {
- int i = 0;
- for (i = 0; i + 8 <= len; i += 8) {
- const __m128i A = _mm_loadu_si128((const __m128i*)(ref + i));
- const __m128i B = _mm_loadu_si128((const __m128i*)(src + i));
- const __m128i C = _mm_loadu_si128((const __m128i*)(dst + i));
- const __m128i D = _mm_sub_epi16(A, B); // diff_uv
- const __m128i E = _mm_add_epi16(C, D); // new_uv
- _mm_storeu_si128((__m128i*)(dst + i), E);
- }
- for (; i < len; ++i) {
- const int diff_uv = ref[i] - src[i];
- dst[i] += diff_uv;
- }
-}
-
-static void SharpYUVFilterRow_SSE2(const int16_t* A, const int16_t* B, int len,
- const uint16_t* best_y, uint16_t* out) {
- int i;
- const __m128i kCst8 = _mm_set1_epi16(8);
- const __m128i max = _mm_set1_epi16(MAX_Y);
- const __m128i zero = _mm_setzero_si128();
- for (i = 0; i + 8 <= len; i += 8) {
- const __m128i a0 = _mm_loadu_si128((const __m128i*)(A + i + 0));
- const __m128i a1 = _mm_loadu_si128((const __m128i*)(A + i + 1));
- const __m128i b0 = _mm_loadu_si128((const __m128i*)(B + i + 0));
- const __m128i b1 = _mm_loadu_si128((const __m128i*)(B + i + 1));
- const __m128i a0b1 = _mm_add_epi16(a0, b1);
- const __m128i a1b0 = _mm_add_epi16(a1, b0);
- const __m128i a0a1b0b1 = _mm_add_epi16(a0b1, a1b0); // A0+A1+B0+B1
- const __m128i a0a1b0b1_8 = _mm_add_epi16(a0a1b0b1, kCst8);
- const __m128i a0b1_2 = _mm_add_epi16(a0b1, a0b1); // 2*(A0+B1)
- const __m128i a1b0_2 = _mm_add_epi16(a1b0, a1b0); // 2*(A1+B0)
- const __m128i c0 = _mm_srai_epi16(_mm_add_epi16(a0b1_2, a0a1b0b1_8), 3);
- const __m128i c1 = _mm_srai_epi16(_mm_add_epi16(a1b0_2, a0a1b0b1_8), 3);
- const __m128i d0 = _mm_add_epi16(c1, a0);
- const __m128i d1 = _mm_add_epi16(c0, a1);
- const __m128i e0 = _mm_srai_epi16(d0, 1);
- const __m128i e1 = _mm_srai_epi16(d1, 1);
- const __m128i f0 = _mm_unpacklo_epi16(e0, e1);
- const __m128i f1 = _mm_unpackhi_epi16(e0, e1);
- const __m128i g0 = _mm_loadu_si128((const __m128i*)(best_y + 2 * i + 0));
- const __m128i g1 = _mm_loadu_si128((const __m128i*)(best_y + 2 * i + 8));
- const __m128i h0 = _mm_add_epi16(g0, f0);
- const __m128i h1 = _mm_add_epi16(g1, f1);
- const __m128i i0 = _mm_max_epi16(_mm_min_epi16(h0, max), zero);
- const __m128i i1 = _mm_max_epi16(_mm_min_epi16(h1, max), zero);
- _mm_storeu_si128((__m128i*)(out + 2 * i + 0), i0);
- _mm_storeu_si128((__m128i*)(out + 2 * i + 8), i1);
- }
- for (; i < len; ++i) {
- // (9 * A0 + 3 * A1 + 3 * B0 + B1 + 8) >> 4 =
- // = (8 * A0 + 2 * (A1 + B0) + (A0 + A1 + B0 + B1 + 8)) >> 4
- // We reuse the common sub-expressions.
- const int a0b1 = A[i + 0] + B[i + 1];
- const int a1b0 = A[i + 1] + B[i + 0];
- const int a0a1b0b1 = a0b1 + a1b0 + 8;
- const int v0 = (8 * A[i + 0] + 2 * a1b0 + a0a1b0b1) >> 4;
- const int v1 = (8 * A[i + 1] + 2 * a0b1 + a0a1b0b1) >> 4;
- out[2 * i + 0] = clip_y(best_y[2 * i + 0] + v0);
- out[2 * i + 1] = clip_y(best_y[2 * i + 1] + v1);
- }
-}
-
-#undef MAX_Y
-
-//------------------------------------------------------------------------------
-
-extern void WebPInitSharpYUVSSE2(void);
-
-WEBP_TSAN_IGNORE_FUNCTION void WebPInitSharpYUVSSE2(void) {
- WebPSharpYUVUpdateY = SharpYUVUpdateY_SSE2;
- WebPSharpYUVUpdateRGB = SharpYUVUpdateRGB_SSE2;
- WebPSharpYUVFilterRow = SharpYUVFilterRow_SSE2;
-}
-
#else // !WEBP_USE_SSE2
WEBP_DSP_INIT_STUB(WebPInitSamplersSSE2)
WEBP_DSP_INIT_STUB(WebPInitConvertARGBToYUVSSE2)
-WEBP_DSP_INIT_STUB(WebPInitSharpYUVSSE2)
#endif // WEBP_USE_SSE2
diff --git a/thirdparty/libwebp/src/enc/alpha_enc.c b/thirdparty/libwebp/src/enc/alpha_enc.c
index 0b54f3e6ec..f7c02690e3 100644
--- a/thirdparty/libwebp/src/enc/alpha_enc.c
+++ b/thirdparty/libwebp/src/enc/alpha_enc.c
@@ -86,7 +86,7 @@ static int EncodeLossless(const uint8_t* const data, int width, int height,
// a decoder bug related to alpha with color cache.
// See: https://code.google.com/p/webp/issues/detail?id=239
// Need to re-enable this later.
- ok = (VP8LEncodeStream(&config, &picture, bw, 0 /*use_cache*/) == VP8_ENC_OK);
+ ok = VP8LEncodeStream(&config, &picture, bw, /*use_cache=*/0);
WebPPictureFree(&picture);
ok = ok && !bw->error_;
if (!ok) {
diff --git a/thirdparty/libwebp/src/enc/backward_references_cost_enc.c b/thirdparty/libwebp/src/enc/backward_references_cost_enc.c
index 516abd73eb..6968ef3c9f 100644
--- a/thirdparty/libwebp/src/enc/backward_references_cost_enc.c
+++ b/thirdparty/libwebp/src/enc/backward_references_cost_enc.c
@@ -15,10 +15,11 @@
//
#include <assert.h>
+#include <float.h>
+#include "src/dsp/lossless_common.h"
#include "src/enc/backward_references_enc.h"
#include "src/enc/histogram_enc.h"
-#include "src/dsp/lossless_common.h"
#include "src/utils/color_cache_utils.h"
#include "src/utils/utils.h"
@@ -30,15 +31,15 @@ extern void VP8LBackwardRefsCursorAdd(VP8LBackwardRefs* const refs,
const PixOrCopy v);
typedef struct {
- double alpha_[VALUES_IN_BYTE];
- double red_[VALUES_IN_BYTE];
- double blue_[VALUES_IN_BYTE];
- double distance_[NUM_DISTANCE_CODES];
- double* literal_;
+ float alpha_[VALUES_IN_BYTE];
+ float red_[VALUES_IN_BYTE];
+ float blue_[VALUES_IN_BYTE];
+ float distance_[NUM_DISTANCE_CODES];
+ float* literal_;
} CostModel;
static void ConvertPopulationCountTableToBitEstimates(
- int num_symbols, const uint32_t population_counts[], double output[]) {
+ int num_symbols, const uint32_t population_counts[], float output[]) {
uint32_t sum = 0;
int nonzeros = 0;
int i;
@@ -51,7 +52,7 @@ static void ConvertPopulationCountTableToBitEstimates(
if (nonzeros <= 1) {
memset(output, 0, num_symbols * sizeof(*output));
} else {
- const double logsum = VP8LFastLog2(sum);
+ const float logsum = VP8LFastLog2(sum);
for (i = 0; i < num_symbols; ++i) {
output[i] = logsum - VP8LFastLog2(population_counts[i]);
}
@@ -75,8 +76,8 @@ static int CostModelBuild(CostModel* const m, int xsize, int cache_bits,
}
ConvertPopulationCountTableToBitEstimates(
- VP8LHistogramNumCodes(histo->palette_code_bits_),
- histo->literal_, m->literal_);
+ VP8LHistogramNumCodes(histo->palette_code_bits_), histo->literal_,
+ m->literal_);
ConvertPopulationCountTableToBitEstimates(
VALUES_IN_BYTE, histo->red_, m->red_);
ConvertPopulationCountTableToBitEstimates(
@@ -92,27 +93,27 @@ static int CostModelBuild(CostModel* const m, int xsize, int cache_bits,
return ok;
}
-static WEBP_INLINE double GetLiteralCost(const CostModel* const m, uint32_t v) {
+static WEBP_INLINE float GetLiteralCost(const CostModel* const m, uint32_t v) {
return m->alpha_[v >> 24] +
m->red_[(v >> 16) & 0xff] +
m->literal_[(v >> 8) & 0xff] +
m->blue_[v & 0xff];
}
-static WEBP_INLINE double GetCacheCost(const CostModel* const m, uint32_t idx) {
+static WEBP_INLINE float GetCacheCost(const CostModel* const m, uint32_t idx) {
const int literal_idx = VALUES_IN_BYTE + NUM_LENGTH_CODES + idx;
return m->literal_[literal_idx];
}
-static WEBP_INLINE double GetLengthCost(const CostModel* const m,
- uint32_t length) {
+static WEBP_INLINE float GetLengthCost(const CostModel* const m,
+ uint32_t length) {
int code, extra_bits;
VP8LPrefixEncodeBits(length, &code, &extra_bits);
return m->literal_[VALUES_IN_BYTE + code] + extra_bits;
}
-static WEBP_INLINE double GetDistanceCost(const CostModel* const m,
- uint32_t distance) {
+static WEBP_INLINE float GetDistanceCost(const CostModel* const m,
+ uint32_t distance) {
int code, extra_bits;
VP8LPrefixEncodeBits(distance, &code, &extra_bits);
return m->distance_[code] + extra_bits;
@@ -122,20 +123,20 @@ static WEBP_INLINE void AddSingleLiteralWithCostModel(
const uint32_t* const argb, VP8LColorCache* const hashers,
const CostModel* const cost_model, int idx, int use_color_cache,
float prev_cost, float* const cost, uint16_t* const dist_array) {
- double cost_val = prev_cost;
+ float cost_val = prev_cost;
const uint32_t color = argb[idx];
const int ix = use_color_cache ? VP8LColorCacheContains(hashers, color) : -1;
if (ix >= 0) {
// use_color_cache is true and hashers contains color
- const double mul0 = 0.68;
+ const float mul0 = 0.68f;
cost_val += GetCacheCost(cost_model, ix) * mul0;
} else {
- const double mul1 = 0.82;
+ const float mul1 = 0.82f;
if (use_color_cache) VP8LColorCacheInsert(hashers, color);
cost_val += GetLiteralCost(cost_model, color) * mul1;
}
if (cost[idx] > cost_val) {
- cost[idx] = (float)cost_val;
+ cost[idx] = cost_val;
dist_array[idx] = 1; // only one is inserted.
}
}
@@ -172,7 +173,7 @@ struct CostInterval {
// The GetLengthCost(cost_model, k) are cached in a CostCacheInterval.
typedef struct {
- double cost_;
+ float cost_;
int start_;
int end_; // Exclusive.
} CostCacheInterval;
@@ -187,7 +188,7 @@ typedef struct {
int count_; // The number of stored intervals.
CostCacheInterval* cache_intervals_;
size_t cache_intervals_size_;
- double cost_cache_[MAX_LENGTH]; // Contains the GetLengthCost(cost_model, k).
+ float cost_cache_[MAX_LENGTH]; // Contains the GetLengthCost(cost_model, k).
float* costs_;
uint16_t* dist_array_;
// Most of the time, we only need few intervals -> use a free-list, to avoid
@@ -262,10 +263,13 @@ static int CostManagerInit(CostManager* const manager,
CostManagerInitFreeList(manager);
// Fill in the cost_cache_.
+ // Has to be done in two passes due to a GCC bug on i686
+ // related to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323
+ for (i = 0; i < cost_cache_size; ++i) {
+ manager->cost_cache_[i] = GetLengthCost(cost_model, i);
+ }
manager->cache_intervals_size_ = 1;
- manager->cost_cache_[0] = GetLengthCost(cost_model, 0);
for (i = 1; i < cost_cache_size; ++i) {
- manager->cost_cache_[i] = GetLengthCost(cost_model, i);
// Get the number of bound intervals.
if (manager->cost_cache_[i] != manager->cost_cache_[i - 1]) {
++manager->cache_intervals_size_;
@@ -294,7 +298,7 @@ static int CostManagerInit(CostManager* const manager,
cur->end_ = 1;
cur->cost_ = manager->cost_cache_[0];
for (i = 1; i < cost_cache_size; ++i) {
- const double cost_val = manager->cost_cache_[i];
+ const float cost_val = manager->cost_cache_[i];
if (cost_val != cur->cost_) {
++cur;
// Initialize an interval.
@@ -303,6 +307,8 @@ static int CostManagerInit(CostManager* const manager,
}
cur->end_ = i + 1;
}
+ assert((size_t)(cur - manager->cache_intervals_) + 1 ==
+ manager->cache_intervals_size_);
}
manager->costs_ = (float*)WebPSafeMalloc(pix_count, sizeof(*manager->costs_));
@@ -311,7 +317,7 @@ static int CostManagerInit(CostManager* const manager,
return 0;
}
// Set the initial costs_ high for every pixel as we will keep the minimum.
- for (i = 0; i < pix_count; ++i) manager->costs_[i] = 1e38f;
+ for (i = 0; i < pix_count; ++i) manager->costs_[i] = FLT_MAX;
return 1;
}
@@ -457,7 +463,7 @@ static WEBP_INLINE void InsertInterval(CostManager* const manager,
// If handling the interval or one of its subintervals becomes to heavy, its
// contribution is added to the costs right away.
static WEBP_INLINE void PushInterval(CostManager* const manager,
- double distance_cost, int position,
+ float distance_cost, int position,
int len) {
size_t i;
CostInterval* interval = manager->head_;
@@ -474,7 +480,7 @@ static WEBP_INLINE void PushInterval(CostManager* const manager,
const int k = j - position;
float cost_tmp;
assert(k >= 0 && k < MAX_LENGTH);
- cost_tmp = (float)(distance_cost + manager->cost_cache_[k]);
+ cost_tmp = distance_cost + manager->cost_cache_[k];
if (manager->costs_[j] > cost_tmp) {
manager->costs_[j] = cost_tmp;
@@ -492,7 +498,7 @@ static WEBP_INLINE void PushInterval(CostManager* const manager,
const int end = position + (cost_cache_intervals[i].end_ > len
? len
: cost_cache_intervals[i].end_);
- const float cost = (float)(distance_cost + cost_cache_intervals[i].cost_);
+ const float cost = distance_cost + cost_cache_intervals[i].cost_;
for (; interval != NULL && interval->start_ < end;
interval = interval_next) {
@@ -570,22 +576,21 @@ static int BackwardReferencesHashChainDistanceOnly(
const int pix_count = xsize * ysize;
const int use_color_cache = (cache_bits > 0);
const size_t literal_array_size =
- sizeof(double) * (NUM_LITERAL_CODES + NUM_LENGTH_CODES +
- ((cache_bits > 0) ? (1 << cache_bits) : 0));
+ sizeof(float) * (VP8LHistogramNumCodes(cache_bits));
const size_t cost_model_size = sizeof(CostModel) + literal_array_size;
CostModel* const cost_model =
(CostModel*)WebPSafeCalloc(1ULL, cost_model_size);
VP8LColorCache hashers;
CostManager* cost_manager =
- (CostManager*)WebPSafeMalloc(1ULL, sizeof(*cost_manager));
+ (CostManager*)WebPSafeCalloc(1ULL, sizeof(*cost_manager));
int offset_prev = -1, len_prev = -1;
- double offset_cost = -1;
+ float offset_cost = -1.f;
int first_offset_is_constant = -1; // initialized with 'impossible' value
int reach = 0;
if (cost_model == NULL || cost_manager == NULL) goto Error;
- cost_model->literal_ = (double*)(cost_model + 1);
+ cost_model->literal_ = (float*)(cost_model + 1);
if (use_color_cache) {
cc_init = VP8LColorCacheInit(&hashers, cache_bits);
if (!cc_init) goto Error;
@@ -675,7 +680,7 @@ static int BackwardReferencesHashChainDistanceOnly(
}
ok = !refs->error_;
-Error:
+ Error:
if (cc_init) VP8LColorCacheClear(&hashers);
CostManagerClear(cost_manager);
WebPSafeFree(cost_model);
diff --git a/thirdparty/libwebp/src/enc/backward_references_enc.c b/thirdparty/libwebp/src/enc/backward_references_enc.c
index 519b36a091..49a0fac034 100644
--- a/thirdparty/libwebp/src/enc/backward_references_enc.c
+++ b/thirdparty/libwebp/src/enc/backward_references_enc.c
@@ -10,6 +10,8 @@
// Author: Jyrki Alakuijala (jyrki@google.com)
//
+#include "src/enc/backward_references_enc.h"
+
#include <assert.h>
#include <float.h>
#include <math.h>
@@ -17,10 +19,11 @@
#include "src/dsp/dsp.h"
#include "src/dsp/lossless.h"
#include "src/dsp/lossless_common.h"
-#include "src/enc/backward_references_enc.h"
#include "src/enc/histogram_enc.h"
+#include "src/enc/vp8i_enc.h"
#include "src/utils/color_cache_utils.h"
#include "src/utils/utils.h"
+#include "src/webp/encode.h"
#define MIN_BLOCK_SIZE 256 // minimum block size for backward references
@@ -255,10 +258,13 @@ static WEBP_INLINE int MaxFindCopyLength(int len) {
int VP8LHashChainFill(VP8LHashChain* const p, int quality,
const uint32_t* const argb, int xsize, int ysize,
- int low_effort) {
+ int low_effort, const WebPPicture* const pic,
+ int percent_range, int* const percent) {
const int size = xsize * ysize;
const int iter_max = GetMaxItersForQuality(quality);
const uint32_t window_size = GetWindowSizeForHashChain(quality, xsize);
+ int remaining_percent = percent_range;
+ int percent_start = *percent;
int pos;
int argb_comp;
uint32_t base_position;
@@ -276,7 +282,13 @@ int VP8LHashChainFill(VP8LHashChain* const p, int quality,
hash_to_first_index =
(int32_t*)WebPSafeMalloc(HASH_SIZE, sizeof(*hash_to_first_index));
- if (hash_to_first_index == NULL) return 0;
+ if (hash_to_first_index == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
+ }
+
+ percent_range = remaining_percent / 2;
+ remaining_percent -= percent_range;
// Set the int32_t array to -1.
memset(hash_to_first_index, 0xff, HASH_SIZE * sizeof(*hash_to_first_index));
@@ -323,12 +335,22 @@ int VP8LHashChainFill(VP8LHashChain* const p, int quality,
hash_to_first_index[hash_code] = pos++;
argb_comp = argb_comp_next;
}
+
+ if (!WebPReportProgress(
+ pic, percent_start + percent_range * pos / (size - 2), percent)) {
+ WebPSafeFree(hash_to_first_index);
+ return 0;
+ }
}
// Process the penultimate pixel.
chain[pos] = hash_to_first_index[GetPixPairHash64(argb + pos)];
WebPSafeFree(hash_to_first_index);
+ percent_start += percent_range;
+ if (!WebPReportProgress(pic, percent_start, percent)) return 0;
+ percent_range = remaining_percent;
+
// Find the best match interval at each pixel, defined by an offset to the
// pixel and a length. The right-most pixel cannot match anything to the right
// (hence a best length of 0) and the left-most pixel nothing to the left
@@ -417,8 +439,17 @@ int VP8LHashChainFill(VP8LHashChain* const p, int quality,
max_base_position = base_position;
}
}
+
+ if (!WebPReportProgress(pic,
+ percent_start + percent_range *
+ (size - 2 - base_position) /
+ (size - 2),
+ percent)) {
+ return 0;
+ }
}
- return 1;
+
+ return WebPReportProgress(pic, percent_start + percent_range, percent);
}
static WEBP_INLINE void AddSingleLiteral(uint32_t pixel, int use_color_cache,
@@ -728,7 +759,7 @@ static int CalculateBestCacheSize(const uint32_t* argb, int quality,
int* const best_cache_bits) {
int i;
const int cache_bits_max = (quality <= 25) ? 0 : *best_cache_bits;
- double entropy_min = MAX_ENTROPY;
+ float entropy_min = MAX_ENTROPY;
int cc_init[MAX_COLOR_CACHE_BITS + 1] = { 0 };
VP8LColorCache hashers[MAX_COLOR_CACHE_BITS + 1];
VP8LRefsCursor c = VP8LRefsCursorInit(refs);
@@ -813,14 +844,14 @@ static int CalculateBestCacheSize(const uint32_t* argb, int quality,
}
for (i = 0; i <= cache_bits_max; ++i) {
- const double entropy = VP8LHistogramEstimateBits(histos[i]);
+ const float entropy = VP8LHistogramEstimateBits(histos[i]);
if (i == 0 || entropy < entropy_min) {
entropy_min = entropy;
*best_cache_bits = i;
}
}
ok = 1;
-Error:
+ Error:
for (i = 0; i <= cache_bits_max; ++i) {
if (cc_init[i]) VP8LColorCacheClear(&hashers[i]);
VP8LFreeHistogram(histos[i]);
@@ -890,7 +921,7 @@ static int GetBackwardReferences(int width, int height,
int i, lz77_type;
// Index 0 is for a color cache, index 1 for no cache (if needed).
int lz77_types_best[2] = {0, 0};
- double bit_costs_best[2] = {DBL_MAX, DBL_MAX};
+ float bit_costs_best[2] = {FLT_MAX, FLT_MAX};
VP8LHashChain hash_chain_box;
VP8LBackwardRefs* const refs_tmp = &refs[do_no_cache ? 2 : 1];
int status = 0;
@@ -902,7 +933,7 @@ static int GetBackwardReferences(int width, int height,
for (lz77_type = 1; lz77_types_to_try;
lz77_types_to_try &= ~lz77_type, lz77_type <<= 1) {
int res = 0;
- double bit_cost = 0.;
+ float bit_cost = 0.f;
if ((lz77_types_to_try & lz77_type) == 0) continue;
switch (lz77_type) {
case kLZ77RLE:
@@ -976,15 +1007,16 @@ static int GetBackwardReferences(int width, int height,
const VP8LHashChain* const hash_chain_tmp =
(lz77_types_best[i] == kLZ77Standard) ? hash_chain : &hash_chain_box;
const int cache_bits = (i == 1) ? 0 : *cache_bits_best;
- if (VP8LBackwardReferencesTraceBackwards(width, height, argb, cache_bits,
- hash_chain_tmp, &refs[i],
- refs_tmp)) {
- double bit_cost_trace;
- VP8LHistogramCreate(histo, refs_tmp, cache_bits);
- bit_cost_trace = VP8LHistogramEstimateBits(histo);
- if (bit_cost_trace < bit_costs_best[i]) {
- BackwardRefsSwap(refs_tmp, &refs[i]);
- }
+ float bit_cost_trace;
+ if (!VP8LBackwardReferencesTraceBackwards(width, height, argb, cache_bits,
+ hash_chain_tmp, &refs[i],
+ refs_tmp)) {
+ goto Error;
+ }
+ VP8LHistogramCreate(histo, refs_tmp, cache_bits);
+ bit_cost_trace = VP8LHistogramEstimateBits(histo);
+ if (bit_cost_trace < bit_costs_best[i]) {
+ BackwardRefsSwap(refs_tmp, &refs[i]);
}
}
@@ -1000,31 +1032,37 @@ static int GetBackwardReferences(int width, int height,
}
status = 1;
-Error:
+ Error:
VP8LHashChainClear(&hash_chain_box);
VP8LFreeHistogram(histo);
return status;
}
-WebPEncodingError VP8LGetBackwardReferences(
+int VP8LGetBackwardReferences(
int width, int height, const uint32_t* const argb, int quality,
int low_effort, int lz77_types_to_try, int cache_bits_max, int do_no_cache,
const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs,
- int* const cache_bits_best) {
+ int* const cache_bits_best, const WebPPicture* const pic, int percent_range,
+ int* const percent) {
if (low_effort) {
VP8LBackwardRefs* refs_best;
*cache_bits_best = cache_bits_max;
refs_best = GetBackwardReferencesLowEffort(
width, height, argb, cache_bits_best, hash_chain, refs);
- if (refs_best == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
+ if (refs_best == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
+ }
// Set it in first position.
BackwardRefsSwap(refs_best, &refs[0]);
} else {
if (!GetBackwardReferences(width, height, argb, quality, lz77_types_to_try,
cache_bits_max, do_no_cache, hash_chain, refs,
cache_bits_best)) {
- return VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
}
}
- return VP8_ENC_OK;
+
+ return WebPReportProgress(pic, *percent + percent_range, percent);
}
diff --git a/thirdparty/libwebp/src/enc/backward_references_enc.h b/thirdparty/libwebp/src/enc/backward_references_enc.h
index 4c0267b41e..4dff1c27b5 100644
--- a/thirdparty/libwebp/src/enc/backward_references_enc.h
+++ b/thirdparty/libwebp/src/enc/backward_references_enc.h
@@ -134,10 +134,11 @@ struct VP8LHashChain {
// Must be called first, to set size.
int VP8LHashChainInit(VP8LHashChain* const p, int size);
-// Pre-compute the best matches for argb.
+// Pre-compute the best matches for argb. pic and percent are for progress.
int VP8LHashChainFill(VP8LHashChain* const p, int quality,
const uint32_t* const argb, int xsize, int ysize,
- int low_effort);
+ int low_effort, const WebPPicture* const pic,
+ int percent_range, int* const percent);
void VP8LHashChainClear(VP8LHashChain* const p); // release memory
static WEBP_INLINE int VP8LHashChainFindOffset(const VP8LHashChain* const p,
@@ -227,11 +228,14 @@ enum VP8LLZ77Type {
// VP8LBackwardRefs is put in the first element, the best value with no-cache in
// the second element.
// In both cases, the last element is used as temporary internally.
-WebPEncodingError VP8LGetBackwardReferences(
+// pic and percent are for progress.
+// Returns false in case of error (stored in pic->error_code).
+int VP8LGetBackwardReferences(
int width, int height, const uint32_t* const argb, int quality,
int low_effort, int lz77_types_to_try, int cache_bits_max, int do_no_cache,
const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs,
- int* const cache_bits_best);
+ int* const cache_bits_best, const WebPPicture* const pic, int percent_range,
+ int* const percent);
#ifdef __cplusplus
}
diff --git a/thirdparty/libwebp/src/enc/histogram_enc.c b/thirdparty/libwebp/src/enc/histogram_enc.c
index 38a0cebcab..8418def2e1 100644
--- a/thirdparty/libwebp/src/enc/histogram_enc.c
+++ b/thirdparty/libwebp/src/enc/histogram_enc.c
@@ -13,15 +13,17 @@
#include "src/webp/config.h"
#endif
+#include <float.h>
#include <math.h>
-#include "src/enc/backward_references_enc.h"
-#include "src/enc/histogram_enc.h"
#include "src/dsp/lossless.h"
#include "src/dsp/lossless_common.h"
+#include "src/enc/backward_references_enc.h"
+#include "src/enc/histogram_enc.h"
+#include "src/enc/vp8i_enc.h"
#include "src/utils/utils.h"
-#define MAX_COST 1.e38
+#define MAX_BIT_COST FLT_MAX
// Number of partitions for the three dominant (literal, red and blue) symbol
// costs.
@@ -228,8 +230,8 @@ void VP8LHistogramAddSinglePixOrCopy(VP8LHistogram* const histo,
// -----------------------------------------------------------------------------
// Entropy-related functions.
-static WEBP_INLINE double BitsEntropyRefine(const VP8LBitEntropy* entropy) {
- double mix;
+static WEBP_INLINE float BitsEntropyRefine(const VP8LBitEntropy* entropy) {
+ float mix;
if (entropy->nonzeros < 5) {
if (entropy->nonzeros <= 1) {
return 0;
@@ -238,67 +240,67 @@ static WEBP_INLINE double BitsEntropyRefine(const VP8LBitEntropy* entropy) {
// Let's mix in a bit of entropy to favor good clustering when
// distributions of these are combined.
if (entropy->nonzeros == 2) {
- return 0.99 * entropy->sum + 0.01 * entropy->entropy;
+ return 0.99f * entropy->sum + 0.01f * entropy->entropy;
}
// No matter what the entropy says, we cannot be better than min_limit
// with Huffman coding. I am mixing a bit of entropy into the
// min_limit since it produces much better (~0.5 %) compression results
// perhaps because of better entropy clustering.
if (entropy->nonzeros == 3) {
- mix = 0.95;
+ mix = 0.95f;
} else {
- mix = 0.7; // nonzeros == 4.
+ mix = 0.7f; // nonzeros == 4.
}
} else {
- mix = 0.627;
+ mix = 0.627f;
}
{
- double min_limit = 2 * entropy->sum - entropy->max_val;
- min_limit = mix * min_limit + (1.0 - mix) * entropy->entropy;
+ float min_limit = 2.f * entropy->sum - entropy->max_val;
+ min_limit = mix * min_limit + (1.f - mix) * entropy->entropy;
return (entropy->entropy < min_limit) ? min_limit : entropy->entropy;
}
}
-double VP8LBitsEntropy(const uint32_t* const array, int n) {
+float VP8LBitsEntropy(const uint32_t* const array, int n) {
VP8LBitEntropy entropy;
VP8LBitsEntropyUnrefined(array, n, &entropy);
return BitsEntropyRefine(&entropy);
}
-static double InitialHuffmanCost(void) {
+static float InitialHuffmanCost(void) {
// Small bias because Huffman code length is typically not stored in
// full length.
static const int kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3;
- static const double kSmallBias = 9.1;
+ static const float kSmallBias = 9.1f;
return kHuffmanCodeOfHuffmanCodeSize - kSmallBias;
}
// Finalize the Huffman cost based on streak numbers and length type (<3 or >=3)
-static double FinalHuffmanCost(const VP8LStreaks* const stats) {
+static float FinalHuffmanCost(const VP8LStreaks* const stats) {
// The constants in this function are experimental and got rounded from
// their original values in 1/8 when switched to 1/1024.
- double retval = InitialHuffmanCost();
+ float retval = InitialHuffmanCost();
// Second coefficient: Many zeros in the histogram are covered efficiently
// by a run-length encode. Originally 2/8.
- retval += stats->counts[0] * 1.5625 + 0.234375 * stats->streaks[0][1];
+ retval += stats->counts[0] * 1.5625f + 0.234375f * stats->streaks[0][1];
// Second coefficient: Constant values are encoded less efficiently, but still
// RLE'ed. Originally 6/8.
- retval += stats->counts[1] * 2.578125 + 0.703125 * stats->streaks[1][1];
+ retval += stats->counts[1] * 2.578125f + 0.703125f * stats->streaks[1][1];
// 0s are usually encoded more efficiently than non-0s.
// Originally 15/8.
- retval += 1.796875 * stats->streaks[0][0];
+ retval += 1.796875f * stats->streaks[0][0];
// Originally 26/8.
- retval += 3.28125 * stats->streaks[1][0];
+ retval += 3.28125f * stats->streaks[1][0];
return retval;
}
// Get the symbol entropy for the distribution 'population'.
// Set 'trivial_sym', if there's only one symbol present in the distribution.
-static double PopulationCost(const uint32_t* const population, int length,
- uint32_t* const trivial_sym,
- uint8_t* const is_used) {
+static float PopulationCost(const uint32_t* const population, int length,
+ uint32_t* const trivial_sym,
+ uint8_t* const is_used) {
VP8LBitEntropy bit_entropy;
VP8LStreaks stats;
VP8LGetEntropyUnrefined(population, length, &bit_entropy, &stats);
@@ -314,11 +316,10 @@ static double PopulationCost(const uint32_t* const population, int length,
// trivial_at_end is 1 if the two histograms only have one element that is
// non-zero: both the zero-th one, or both the last one.
-static WEBP_INLINE double GetCombinedEntropy(const uint32_t* const X,
- const uint32_t* const Y,
- int length, int is_X_used,
- int is_Y_used,
- int trivial_at_end) {
+static WEBP_INLINE float GetCombinedEntropy(const uint32_t* const X,
+ const uint32_t* const Y, int length,
+ int is_X_used, int is_Y_used,
+ int trivial_at_end) {
VP8LStreaks stats;
if (trivial_at_end) {
// This configuration is due to palettization that transforms an indexed
@@ -356,7 +357,7 @@ static WEBP_INLINE double GetCombinedEntropy(const uint32_t* const X,
}
// Estimates the Entropy + Huffman + other block overhead size cost.
-double VP8LHistogramEstimateBits(VP8LHistogram* const p) {
+float VP8LHistogramEstimateBits(VP8LHistogram* const p) {
return
PopulationCost(p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_),
NULL, &p->is_used_[0])
@@ -373,8 +374,7 @@ double VP8LHistogramEstimateBits(VP8LHistogram* const p) {
static int GetCombinedHistogramEntropy(const VP8LHistogram* const a,
const VP8LHistogram* const b,
- double cost_threshold,
- double* cost) {
+ float cost_threshold, float* cost) {
const int palette_code_bits = a->palette_code_bits_;
int trivial_at_end = 0;
assert(a->palette_code_bits_ == b->palette_code_bits_);
@@ -439,12 +439,11 @@ static WEBP_INLINE void HistogramAdd(const VP8LHistogram* const a,
// Since the previous score passed is 'cost_threshold', we only need to compare
// the partial cost against 'cost_threshold + C(a) + C(b)' to possibly bail-out
// early.
-static double HistogramAddEval(const VP8LHistogram* const a,
- const VP8LHistogram* const b,
- VP8LHistogram* const out,
- double cost_threshold) {
- double cost = 0;
- const double sum_cost = a->bit_cost_ + b->bit_cost_;
+static float HistogramAddEval(const VP8LHistogram* const a,
+ const VP8LHistogram* const b,
+ VP8LHistogram* const out, float cost_threshold) {
+ float cost = 0;
+ const float sum_cost = a->bit_cost_ + b->bit_cost_;
cost_threshold += sum_cost;
if (GetCombinedHistogramEntropy(a, b, cost_threshold, &cost)) {
@@ -459,10 +458,10 @@ static double HistogramAddEval(const VP8LHistogram* const a,
// Same as HistogramAddEval(), except that the resulting histogram
// is not stored. Only the cost C(a+b) - C(a) is evaluated. We omit
// the term C(b) which is constant over all the evaluations.
-static double HistogramAddThresh(const VP8LHistogram* const a,
- const VP8LHistogram* const b,
- double cost_threshold) {
- double cost;
+static float HistogramAddThresh(const VP8LHistogram* const a,
+ const VP8LHistogram* const b,
+ float cost_threshold) {
+ float cost;
assert(a != NULL && b != NULL);
cost = -a->bit_cost_;
GetCombinedHistogramEntropy(a, b, cost_threshold, &cost);
@@ -473,24 +472,22 @@ static double HistogramAddThresh(const VP8LHistogram* const a,
// The structure to keep track of cost range for the three dominant entropy
// symbols.
-// TODO(skal): Evaluate if float can be used here instead of double for
-// representing the entropy costs.
typedef struct {
- double literal_max_;
- double literal_min_;
- double red_max_;
- double red_min_;
- double blue_max_;
- double blue_min_;
+ float literal_max_;
+ float literal_min_;
+ float red_max_;
+ float red_min_;
+ float blue_max_;
+ float blue_min_;
} DominantCostRange;
static void DominantCostRangeInit(DominantCostRange* const c) {
c->literal_max_ = 0.;
- c->literal_min_ = MAX_COST;
+ c->literal_min_ = MAX_BIT_COST;
c->red_max_ = 0.;
- c->red_min_ = MAX_COST;
+ c->red_min_ = MAX_BIT_COST;
c->blue_max_ = 0.;
- c->blue_min_ = MAX_COST;
+ c->blue_min_ = MAX_BIT_COST;
}
static void UpdateDominantCostRange(
@@ -505,10 +502,9 @@ static void UpdateDominantCostRange(
static void UpdateHistogramCost(VP8LHistogram* const h) {
uint32_t alpha_sym, red_sym, blue_sym;
- const double alpha_cost =
- PopulationCost(h->alpha_, NUM_LITERAL_CODES, &alpha_sym,
- &h->is_used_[3]);
- const double distance_cost =
+ const float alpha_cost =
+ PopulationCost(h->alpha_, NUM_LITERAL_CODES, &alpha_sym, &h->is_used_[3]);
+ const float distance_cost =
PopulationCost(h->distance_, NUM_DISTANCE_CODES, NULL, &h->is_used_[4]) +
VP8LExtraCost(h->distance_, NUM_DISTANCE_CODES);
const int num_codes = VP8LHistogramNumCodes(h->palette_code_bits_);
@@ -529,10 +525,10 @@ static void UpdateHistogramCost(VP8LHistogram* const h) {
}
}
-static int GetBinIdForEntropy(double min, double max, double val) {
- const double range = max - min;
+static int GetBinIdForEntropy(float min, float max, float val) {
+ const float range = max - min;
if (range > 0.) {
- const double delta = val - min;
+ const float delta = val - min;
return (int)((NUM_PARTITIONS - 1e-6) * delta / range);
} else {
return 0;
@@ -641,15 +637,11 @@ static void HistogramAnalyzeEntropyBin(VP8LHistogramSet* const image_histo,
// Merges some histograms with same bin_id together if it's advantageous.
// Sets the remaining histograms to NULL.
-static void HistogramCombineEntropyBin(VP8LHistogramSet* const image_histo,
- int* num_used,
- const uint16_t* const clusters,
- uint16_t* const cluster_mappings,
- VP8LHistogram* cur_combo,
- const uint16_t* const bin_map,
- int num_bins,
- double combine_cost_factor,
- int low_effort) {
+static void HistogramCombineEntropyBin(
+ VP8LHistogramSet* const image_histo, int* num_used,
+ const uint16_t* const clusters, uint16_t* const cluster_mappings,
+ VP8LHistogram* cur_combo, const uint16_t* const bin_map, int num_bins,
+ float combine_cost_factor, int low_effort) {
VP8LHistogram** const histograms = image_histo->histograms;
int idx;
struct {
@@ -679,11 +671,10 @@ static void HistogramCombineEntropyBin(VP8LHistogramSet* const image_histo,
cluster_mappings[clusters[idx]] = clusters[first];
} else {
// try to merge #idx into #first (both share the same bin_id)
- const double bit_cost = histograms[idx]->bit_cost_;
- const double bit_cost_thresh = -bit_cost * combine_cost_factor;
- const double curr_cost_diff =
- HistogramAddEval(histograms[first], histograms[idx],
- cur_combo, bit_cost_thresh);
+ const float bit_cost = histograms[idx]->bit_cost_;
+ const float bit_cost_thresh = -bit_cost * combine_cost_factor;
+ const float curr_cost_diff = HistogramAddEval(
+ histograms[first], histograms[idx], cur_combo, bit_cost_thresh);
if (curr_cost_diff < bit_cost_thresh) {
// Try to merge two histograms only if the combo is a trivial one or
// the two candidate histograms are already non-trivial.
@@ -731,8 +722,8 @@ static uint32_t MyRand(uint32_t* const seed) {
typedef struct {
int idx1;
int idx2;
- double cost_diff;
- double cost_combo;
+ float cost_diff;
+ float cost_combo;
} HistogramPair;
typedef struct {
@@ -787,10 +778,9 @@ static void HistoQueueUpdateHead(HistoQueue* const histo_queue,
// Update the cost diff and combo of a pair of histograms. This needs to be
// called when the the histograms have been merged with a third one.
static void HistoQueueUpdatePair(const VP8LHistogram* const h1,
- const VP8LHistogram* const h2,
- double threshold,
+ const VP8LHistogram* const h2, float threshold,
HistogramPair* const pair) {
- const double sum_cost = h1->bit_cost_ + h2->bit_cost_;
+ const float sum_cost = h1->bit_cost_ + h2->bit_cost_;
pair->cost_combo = 0.;
GetCombinedHistogramEntropy(h1, h2, sum_cost + threshold, &pair->cost_combo);
pair->cost_diff = pair->cost_combo - sum_cost;
@@ -799,9 +789,9 @@ static void HistoQueueUpdatePair(const VP8LHistogram* const h1,
// Create a pair from indices "idx1" and "idx2" provided its cost
// is inferior to "threshold", a negative entropy.
// It returns the cost of the pair, or 0. if it superior to threshold.
-static double HistoQueuePush(HistoQueue* const histo_queue,
- VP8LHistogram** const histograms, int idx1,
- int idx2, double threshold) {
+static float HistoQueuePush(HistoQueue* const histo_queue,
+ VP8LHistogram** const histograms, int idx1,
+ int idx2, float threshold) {
const VP8LHistogram* h1;
const VP8LHistogram* h2;
HistogramPair pair;
@@ -945,8 +935,8 @@ static int HistogramCombineStochastic(VP8LHistogramSet* const image_histo,
++tries_with_no_success < num_tries_no_success;
++iter) {
int* mapping_index;
- double best_cost =
- (histo_queue.size == 0) ? 0. : histo_queue.queue[0].cost_diff;
+ float best_cost =
+ (histo_queue.size == 0) ? 0.f : histo_queue.queue[0].cost_diff;
int best_idx1 = -1, best_idx2 = 1;
const uint32_t rand_range = (*num_used - 1) * (*num_used);
// (*num_used) / 2 was chosen empirically. Less means faster but worse
@@ -955,7 +945,7 @@ static int HistogramCombineStochastic(VP8LHistogramSet* const image_histo,
// Pick random samples.
for (j = 0; *num_used >= 2 && j < num_tries; ++j) {
- double curr_cost;
+ float curr_cost;
// Choose two different histograms at random and try to combine them.
const uint32_t tmp = MyRand(&seed) % rand_range;
uint32_t idx1 = tmp / (*num_used - 1);
@@ -1034,7 +1024,7 @@ static int HistogramCombineStochastic(VP8LHistogramSet* const image_histo,
*do_greedy = (*num_used <= min_cluster_size);
ok = 1;
-End:
+ End:
HistoQueueClear(&histo_queue);
WebPSafeFree(mappings);
return ok;
@@ -1057,7 +1047,7 @@ static void HistogramRemap(const VP8LHistogramSet* const in,
if (out_size > 1) {
for (i = 0; i < in_size; ++i) {
int best_out = 0;
- double best_bits = MAX_COST;
+ float best_bits = MAX_BIT_COST;
int k;
if (in_histo[i] == NULL) {
// Arbitrarily set to the previous value if unused to help future LZ77.
@@ -1065,7 +1055,7 @@ static void HistogramRemap(const VP8LHistogramSet* const in,
continue;
}
for (k = 0; k < out_size; ++k) {
- double cur_bits;
+ float cur_bits;
cur_bits = HistogramAddThresh(out_histo[k], in_histo[i], best_bits);
if (k == 0 || cur_bits < best_bits) {
best_bits = cur_bits;
@@ -1093,13 +1083,13 @@ static void HistogramRemap(const VP8LHistogramSet* const in,
}
}
-static double GetCombineCostFactor(int histo_size, int quality) {
- double combine_cost_factor = 0.16;
+static float GetCombineCostFactor(int histo_size, int quality) {
+ float combine_cost_factor = 0.16f;
if (quality < 90) {
- if (histo_size > 256) combine_cost_factor /= 2.;
- if (histo_size > 512) combine_cost_factor /= 2.;
- if (histo_size > 1024) combine_cost_factor /= 2.;
- if (quality <= 50) combine_cost_factor /= 2.;
+ if (histo_size > 256) combine_cost_factor /= 2.f;
+ if (histo_size > 512) combine_cost_factor /= 2.f;
+ if (histo_size > 1024) combine_cost_factor /= 2.f;
+ if (quality <= 50) combine_cost_factor /= 2.f;
}
return combine_cost_factor;
}
@@ -1169,13 +1159,13 @@ static void RemoveEmptyHistograms(VP8LHistogramSet* const image_histo) {
}
int VP8LGetHistoImageSymbols(int xsize, int ysize,
- const VP8LBackwardRefs* const refs,
- int quality, int low_effort,
- int histogram_bits, int cache_bits,
+ const VP8LBackwardRefs* const refs, int quality,
+ int low_effort, int histogram_bits, int cache_bits,
VP8LHistogramSet* const image_histo,
VP8LHistogram* const tmp_histo,
- uint16_t* const histogram_symbols) {
- int ok = 0;
+ uint16_t* const histogram_symbols,
+ const WebPPicture* const pic, int percent_range,
+ int* const percent) {
const int histo_xsize =
histogram_bits ? VP8LSubSampleSize(xsize, histogram_bits) : 1;
const int histo_ysize =
@@ -1192,7 +1182,10 @@ int VP8LGetHistoImageSymbols(int xsize, int ysize,
WebPSafeMalloc(2 * image_histo_raw_size, sizeof(map_tmp));
uint16_t* const cluster_mappings = map_tmp + image_histo_raw_size;
int num_used = image_histo_raw_size;
- if (orig_histo == NULL || map_tmp == NULL) goto Error;
+ if (orig_histo == NULL || map_tmp == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ goto Error;
+ }
// Construct the histograms from backward references.
HistogramBuild(xsize, histogram_bits, refs, orig_histo);
@@ -1206,16 +1199,15 @@ int VP8LGetHistoImageSymbols(int xsize, int ysize,
if (entropy_combine) {
uint16_t* const bin_map = map_tmp;
- const double combine_cost_factor =
+ const float combine_cost_factor =
GetCombineCostFactor(image_histo_raw_size, quality);
const uint32_t num_clusters = num_used;
HistogramAnalyzeEntropyBin(image_histo, bin_map, low_effort);
// Collapse histograms with similar entropy.
- HistogramCombineEntropyBin(image_histo, &num_used, histogram_symbols,
- cluster_mappings, tmp_histo, bin_map,
- entropy_combine_num_bins, combine_cost_factor,
- low_effort);
+ HistogramCombineEntropyBin(
+ image_histo, &num_used, histogram_symbols, cluster_mappings, tmp_histo,
+ bin_map, entropy_combine_num_bins, combine_cost_factor, low_effort);
OptimizeHistogramSymbols(image_histo, cluster_mappings, num_clusters,
map_tmp, histogram_symbols);
}
@@ -1229,11 +1221,13 @@ int VP8LGetHistoImageSymbols(int xsize, int ysize,
int do_greedy;
if (!HistogramCombineStochastic(image_histo, &num_used, threshold_size,
&do_greedy)) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
if (do_greedy) {
RemoveEmptyHistograms(image_histo);
if (!HistogramCombineGreedy(image_histo, &num_used)) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
}
@@ -1243,10 +1237,12 @@ int VP8LGetHistoImageSymbols(int xsize, int ysize,
RemoveEmptyHistograms(image_histo);
HistogramRemap(orig_histo, image_histo, histogram_symbols);
- ok = 1;
+ if (!WebPReportProgress(pic, *percent + percent_range, percent)) {
+ goto Error;
+ }
Error:
VP8LFreeHistogramSet(orig_histo);
WebPSafeFree(map_tmp);
- return ok;
+ return (pic->error_code == VP8_ENC_OK);
}
diff --git a/thirdparty/libwebp/src/enc/histogram_enc.h b/thirdparty/libwebp/src/enc/histogram_enc.h
index c3428b5d55..4c0bb97464 100644
--- a/thirdparty/libwebp/src/enc/histogram_enc.h
+++ b/thirdparty/libwebp/src/enc/histogram_enc.h
@@ -40,10 +40,10 @@ typedef struct {
int palette_code_bits_;
uint32_t trivial_symbol_; // True, if histograms for Red, Blue & Alpha
// literal symbols are single valued.
- double bit_cost_; // cached value of bit cost.
- double literal_cost_; // Cached values of dominant entropy costs:
- double red_cost_; // literal, red & blue.
- double blue_cost_;
+ float bit_cost_; // cached value of bit cost.
+ float literal_cost_; // Cached values of dominant entropy costs:
+ float red_cost_; // literal, red & blue.
+ float blue_cost_;
uint8_t is_used_[5]; // 5 for literal, red, blue, alpha, distance
} VP8LHistogram;
@@ -105,21 +105,23 @@ static WEBP_INLINE int VP8LHistogramNumCodes(int palette_code_bits) {
((palette_code_bits > 0) ? (1 << palette_code_bits) : 0);
}
-// Builds the histogram image.
+// Builds the histogram image. pic and percent are for progress.
+// Returns false in case of error (stored in pic->error_code).
int VP8LGetHistoImageSymbols(int xsize, int ysize,
- const VP8LBackwardRefs* const refs,
- int quality, int low_effort,
- int histogram_bits, int cache_bits,
+ const VP8LBackwardRefs* const refs, int quality,
+ int low_effort, int histogram_bits, int cache_bits,
VP8LHistogramSet* const image_histo,
VP8LHistogram* const tmp_histo,
- uint16_t* const histogram_symbols);
+ uint16_t* const histogram_symbols,
+ const WebPPicture* const pic, int percent_range,
+ int* const percent);
// Returns the entropy for the symbols in the input array.
-double VP8LBitsEntropy(const uint32_t* const array, int n);
+float VP8LBitsEntropy(const uint32_t* const array, int n);
// Estimate how many bits the combined entropy of literals and distance
// approximately maps to.
-double VP8LHistogramEstimateBits(VP8LHistogram* const p);
+float VP8LHistogramEstimateBits(VP8LHistogram* const p);
#ifdef __cplusplus
}
diff --git a/thirdparty/libwebp/src/enc/picture_csp_enc.c b/thirdparty/libwebp/src/enc/picture_csp_enc.c
index 35eede9635..fabebcf202 100644
--- a/thirdparty/libwebp/src/enc/picture_csp_enc.c
+++ b/thirdparty/libwebp/src/enc/picture_csp_enc.c
@@ -15,12 +15,19 @@
#include <stdlib.h>
#include <math.h>
+#include "sharpyuv/sharpyuv.h"
+#include "sharpyuv/sharpyuv_csp.h"
#include "src/enc/vp8i_enc.h"
#include "src/utils/random_utils.h"
#include "src/utils/utils.h"
#include "src/dsp/dsp.h"
#include "src/dsp/lossless.h"
#include "src/dsp/yuv.h"
+#include "src/dsp/cpu.h"
+
+#if defined(WEBP_USE_THREAD) && !defined(_WIN32)
+#include <pthread.h>
+#endif
// Uncomment to disable gamma-compression during RGB->U/V averaging
#define USE_GAMMA_COMPRESSION
@@ -76,16 +83,16 @@ int WebPPictureHasTransparency(const WebPPicture* picture) {
#if defined(USE_GAMMA_COMPRESSION)
-// gamma-compensates loss of resolution during chroma subsampling
-#define kGamma 0.80 // for now we use a different gamma value than kGammaF
-#define kGammaFix 12 // fixed-point precision for linear values
-#define kGammaScale ((1 << kGammaFix) - 1)
-#define kGammaTabFix 7 // fixed-point fractional bits precision
-#define kGammaTabScale (1 << kGammaTabFix)
-#define kGammaTabRounder (kGammaTabScale >> 1)
-#define kGammaTabSize (1 << (kGammaFix - kGammaTabFix))
+// Gamma correction compensates loss of resolution during chroma subsampling.
+#define GAMMA_FIX 12 // fixed-point precision for linear values
+#define GAMMA_TAB_FIX 7 // fixed-point fractional bits precision
+#define GAMMA_TAB_SIZE (1 << (GAMMA_FIX - GAMMA_TAB_FIX))
+static const double kGamma = 0.80;
+static const int kGammaScale = ((1 << GAMMA_FIX) - 1);
+static const int kGammaTabScale = (1 << GAMMA_TAB_FIX);
+static const int kGammaTabRounder = (1 << GAMMA_TAB_FIX >> 1);
-static int kLinearToGammaTab[kGammaTabSize + 1];
+static int kLinearToGammaTab[GAMMA_TAB_SIZE + 1];
static uint16_t kGammaToLinearTab[256];
static volatile int kGammaTablesOk = 0;
static void InitGammaTables(void);
@@ -93,13 +100,13 @@ static void InitGammaTables(void);
WEBP_DSP_INIT_FUNC(InitGammaTables) {
if (!kGammaTablesOk) {
int v;
- const double scale = (double)(1 << kGammaTabFix) / kGammaScale;
+ const double scale = (double)(1 << GAMMA_TAB_FIX) / kGammaScale;
const double norm = 1. / 255.;
for (v = 0; v <= 255; ++v) {
kGammaToLinearTab[v] =
(uint16_t)(pow(norm * v, kGamma) * kGammaScale + .5);
}
- for (v = 0; v <= kGammaTabSize; ++v) {
+ for (v = 0; v <= GAMMA_TAB_SIZE; ++v) {
kLinearToGammaTab[v] = (int)(255. * pow(scale * v, 1. / kGamma) + .5);
}
kGammaTablesOk = 1;
@@ -111,12 +118,12 @@ static WEBP_INLINE uint32_t GammaToLinear(uint8_t v) {
}
static WEBP_INLINE int Interpolate(int v) {
- const int tab_pos = v >> (kGammaTabFix + 2); // integer part
+ const int tab_pos = v >> (GAMMA_TAB_FIX + 2); // integer part
const int x = v & ((kGammaTabScale << 2) - 1); // fractional part
const int v0 = kLinearToGammaTab[tab_pos];
const int v1 = kLinearToGammaTab[tab_pos + 1];
const int y = v1 * x + v0 * ((kGammaTabScale << 2) - x); // interpolate
- assert(tab_pos + 1 < kGammaTabSize + 1);
+ assert(tab_pos + 1 < GAMMA_TAB_SIZE + 1);
return y;
}
@@ -124,7 +131,7 @@ static WEBP_INLINE int Interpolate(int v) {
// U/V value, suitable for RGBToU/V calls.
static WEBP_INLINE int LinearToGamma(uint32_t base_value, int shift) {
const int y = Interpolate(base_value << shift); // final uplifted value
- return (y + kGammaTabRounder) >> kGammaTabFix; // descale
+ return (y + kGammaTabRounder) >> GAMMA_TAB_FIX; // descale
}
#else
@@ -158,415 +165,41 @@ static int RGBToV(int r, int g, int b, VP8Random* const rg) {
//------------------------------------------------------------------------------
// Sharp RGB->YUV conversion
-static const int kNumIterations = 4;
static const int kMinDimensionIterativeConversion = 4;
-// We could use SFIX=0 and only uint8_t for fixed_y_t, but it produces some
-// banding sometimes. Better use extra precision.
-#define SFIX 2 // fixed-point precision of RGB and Y/W
-typedef int16_t fixed_t; // signed type with extra SFIX precision for UV
-typedef uint16_t fixed_y_t; // unsigned type with extra SFIX precision for W
-
-#define SHALF (1 << SFIX >> 1)
-#define MAX_Y_T ((256 << SFIX) - 1)
-#define SROUNDER (1 << (YUV_FIX + SFIX - 1))
-
-#if defined(USE_GAMMA_COMPRESSION)
-
-// We use tables of different size and precision for the Rec709 / BT2020
-// transfer function.
-#define kGammaF (1./0.45)
-static uint32_t kLinearToGammaTabS[kGammaTabSize + 2];
-#define GAMMA_TO_LINEAR_BITS 14
-static uint32_t kGammaToLinearTabS[MAX_Y_T + 1]; // size scales with Y_FIX
-static volatile int kGammaTablesSOk = 0;
-static void InitGammaTablesS(void);
-
-WEBP_DSP_INIT_FUNC(InitGammaTablesS) {
- assert(2 * GAMMA_TO_LINEAR_BITS < 32); // we use uint32_t intermediate values
- if (!kGammaTablesSOk) {
- int v;
- const double norm = 1. / MAX_Y_T;
- const double scale = 1. / kGammaTabSize;
- const double a = 0.09929682680944;
- const double thresh = 0.018053968510807;
- const double final_scale = 1 << GAMMA_TO_LINEAR_BITS;
- for (v = 0; v <= MAX_Y_T; ++v) {
- const double g = norm * v;
- double value;
- if (g <= thresh * 4.5) {
- value = g / 4.5;
- } else {
- const double a_rec = 1. / (1. + a);
- value = pow(a_rec * (g + a), kGammaF);
- }
- kGammaToLinearTabS[v] = (uint32_t)(value * final_scale + .5);
- }
- for (v = 0; v <= kGammaTabSize; ++v) {
- const double g = scale * v;
- double value;
- if (g <= thresh) {
- value = 4.5 * g;
- } else {
- value = (1. + a) * pow(g, 1. / kGammaF) - a;
- }
- // we already incorporate the 1/2 rounding constant here
- kLinearToGammaTabS[v] =
- (uint32_t)(MAX_Y_T * value) + (1 << GAMMA_TO_LINEAR_BITS >> 1);
- }
- // to prevent small rounding errors to cause read-overflow:
- kLinearToGammaTabS[kGammaTabSize + 1] = kLinearToGammaTabS[kGammaTabSize];
- kGammaTablesSOk = 1;
- }
-}
-
-// return value has a fixed-point precision of GAMMA_TO_LINEAR_BITS
-static WEBP_INLINE uint32_t GammaToLinearS(int v) {
- return kGammaToLinearTabS[v];
-}
-
-static WEBP_INLINE uint32_t LinearToGammaS(uint32_t value) {
- // 'value' is in GAMMA_TO_LINEAR_BITS fractional precision
- const uint32_t v = value * kGammaTabSize;
- const uint32_t tab_pos = v >> GAMMA_TO_LINEAR_BITS;
- // fractional part, in GAMMA_TO_LINEAR_BITS fixed-point precision
- const uint32_t x = v - (tab_pos << GAMMA_TO_LINEAR_BITS); // fractional part
- // v0 / v1 are in GAMMA_TO_LINEAR_BITS fixed-point precision (range [0..1])
- const uint32_t v0 = kLinearToGammaTabS[tab_pos + 0];
- const uint32_t v1 = kLinearToGammaTabS[tab_pos + 1];
- // Final interpolation. Note that rounding is already included.
- const uint32_t v2 = (v1 - v0) * x; // note: v1 >= v0.
- const uint32_t result = v0 + (v2 >> GAMMA_TO_LINEAR_BITS);
- return result;
-}
-
-#else
-
-static void InitGammaTablesS(void) {}
-static WEBP_INLINE uint32_t GammaToLinearS(int v) {
- return (v << GAMMA_TO_LINEAR_BITS) / MAX_Y_T;
-}
-static WEBP_INLINE uint32_t LinearToGammaS(uint32_t value) {
- return (MAX_Y_T * value) >> GAMMA_TO_LINEAR_BITS;
-}
-
-#endif // USE_GAMMA_COMPRESSION
-
-//------------------------------------------------------------------------------
-
-static uint8_t clip_8b(fixed_t v) {
- return (!(v & ~0xff)) ? (uint8_t)v : (v < 0) ? 0u : 255u;
-}
-
-static fixed_y_t clip_y(int y) {
- return (!(y & ~MAX_Y_T)) ? (fixed_y_t)y : (y < 0) ? 0 : MAX_Y_T;
-}
-
-//------------------------------------------------------------------------------
-
-static int RGBToGray(int r, int g, int b) {
- const int luma = 13933 * r + 46871 * g + 4732 * b + YUV_HALF;
- return (luma >> YUV_FIX);
-}
-
-static uint32_t ScaleDown(int a, int b, int c, int d) {
- const uint32_t A = GammaToLinearS(a);
- const uint32_t B = GammaToLinearS(b);
- const uint32_t C = GammaToLinearS(c);
- const uint32_t D = GammaToLinearS(d);
- return LinearToGammaS((A + B + C + D + 2) >> 2);
-}
-
-static WEBP_INLINE void UpdateW(const fixed_y_t* src, fixed_y_t* dst, int w) {
- int i;
- for (i = 0; i < w; ++i) {
- const uint32_t R = GammaToLinearS(src[0 * w + i]);
- const uint32_t G = GammaToLinearS(src[1 * w + i]);
- const uint32_t B = GammaToLinearS(src[2 * w + i]);
- const uint32_t Y = RGBToGray(R, G, B);
- dst[i] = (fixed_y_t)LinearToGammaS(Y);
- }
-}
-
-static void UpdateChroma(const fixed_y_t* src1, const fixed_y_t* src2,
- fixed_t* dst, int uv_w) {
- int i;
- for (i = 0; i < uv_w; ++i) {
- const int r = ScaleDown(src1[0 * uv_w + 0], src1[0 * uv_w + 1],
- src2[0 * uv_w + 0], src2[0 * uv_w + 1]);
- const int g = ScaleDown(src1[2 * uv_w + 0], src1[2 * uv_w + 1],
- src2[2 * uv_w + 0], src2[2 * uv_w + 1]);
- const int b = ScaleDown(src1[4 * uv_w + 0], src1[4 * uv_w + 1],
- src2[4 * uv_w + 0], src2[4 * uv_w + 1]);
- const int W = RGBToGray(r, g, b);
- dst[0 * uv_w] = (fixed_t)(r - W);
- dst[1 * uv_w] = (fixed_t)(g - W);
- dst[2 * uv_w] = (fixed_t)(b - W);
- dst += 1;
- src1 += 2;
- src2 += 2;
- }
-}
-
-static void StoreGray(const fixed_y_t* rgb, fixed_y_t* y, int w) {
- int i;
- for (i = 0; i < w; ++i) {
- y[i] = RGBToGray(rgb[0 * w + i], rgb[1 * w + i], rgb[2 * w + i]);
- }
-}
-
-//------------------------------------------------------------------------------
-
-static WEBP_INLINE fixed_y_t Filter2(int A, int B, int W0) {
- const int v0 = (A * 3 + B + 2) >> 2;
- return clip_y(v0 + W0);
-}
-
//------------------------------------------------------------------------------
+// Main function
-static WEBP_INLINE fixed_y_t UpLift(uint8_t a) { // 8bit -> SFIX
- return ((fixed_y_t)a << SFIX) | SHALF;
-}
-
-static void ImportOneRow(const uint8_t* const r_ptr,
- const uint8_t* const g_ptr,
- const uint8_t* const b_ptr,
- int step,
- int pic_width,
- fixed_y_t* const dst) {
- int i;
- const int w = (pic_width + 1) & ~1;
- for (i = 0; i < pic_width; ++i) {
- const int off = i * step;
- dst[i + 0 * w] = UpLift(r_ptr[off]);
- dst[i + 1 * w] = UpLift(g_ptr[off]);
- dst[i + 2 * w] = UpLift(b_ptr[off]);
- }
- if (pic_width & 1) { // replicate rightmost pixel
- dst[pic_width + 0 * w] = dst[pic_width + 0 * w - 1];
- dst[pic_width + 1 * w] = dst[pic_width + 1 * w - 1];
- dst[pic_width + 2 * w] = dst[pic_width + 2 * w - 1];
- }
-}
-
-static void InterpolateTwoRows(const fixed_y_t* const best_y,
- const fixed_t* prev_uv,
- const fixed_t* cur_uv,
- const fixed_t* next_uv,
- int w,
- fixed_y_t* out1,
- fixed_y_t* out2) {
- const int uv_w = w >> 1;
- const int len = (w - 1) >> 1; // length to filter
- int k = 3;
- while (k-- > 0) { // process each R/G/B segments in turn
- // special boundary case for i==0
- out1[0] = Filter2(cur_uv[0], prev_uv[0], best_y[0]);
- out2[0] = Filter2(cur_uv[0], next_uv[0], best_y[w]);
-
- WebPSharpYUVFilterRow(cur_uv, prev_uv, len, best_y + 0 + 1, out1 + 1);
- WebPSharpYUVFilterRow(cur_uv, next_uv, len, best_y + w + 1, out2 + 1);
-
- // special boundary case for i == w - 1 when w is even
- if (!(w & 1)) {
- out1[w - 1] = Filter2(cur_uv[uv_w - 1], prev_uv[uv_w - 1],
- best_y[w - 1 + 0]);
- out2[w - 1] = Filter2(cur_uv[uv_w - 1], next_uv[uv_w - 1],
- best_y[w - 1 + w]);
- }
- out1 += w;
- out2 += w;
- prev_uv += uv_w;
- cur_uv += uv_w;
- next_uv += uv_w;
- }
-}
-
-static WEBP_INLINE uint8_t ConvertRGBToY(int r, int g, int b) {
- const int luma = 16839 * r + 33059 * g + 6420 * b + SROUNDER;
- return clip_8b(16 + (luma >> (YUV_FIX + SFIX)));
-}
+extern void SharpYuvInit(VP8CPUInfo cpu_info_func);
-static WEBP_INLINE uint8_t ConvertRGBToU(int r, int g, int b) {
- const int u = -9719 * r - 19081 * g + 28800 * b + SROUNDER;
- return clip_8b(128 + (u >> (YUV_FIX + SFIX)));
-}
+static void SafeInitSharpYuv(void) {
+#if defined(WEBP_USE_THREAD) && !defined(_WIN32)
+ static pthread_mutex_t initsharpyuv_lock = PTHREAD_MUTEX_INITIALIZER;
+ if (pthread_mutex_lock(&initsharpyuv_lock)) return;
+#endif
-static WEBP_INLINE uint8_t ConvertRGBToV(int r, int g, int b) {
- const int v = +28800 * r - 24116 * g - 4684 * b + SROUNDER;
- return clip_8b(128 + (v >> (YUV_FIX + SFIX)));
-}
+ SharpYuvInit(VP8GetCPUInfo);
-static int ConvertWRGBToYUV(const fixed_y_t* best_y, const fixed_t* best_uv,
- WebPPicture* const picture) {
- int i, j;
- uint8_t* dst_y = picture->y;
- uint8_t* dst_u = picture->u;
- uint8_t* dst_v = picture->v;
- const fixed_t* const best_uv_base = best_uv;
- const int w = (picture->width + 1) & ~1;
- const int h = (picture->height + 1) & ~1;
- const int uv_w = w >> 1;
- const int uv_h = h >> 1;
- for (best_uv = best_uv_base, j = 0; j < picture->height; ++j) {
- for (i = 0; i < picture->width; ++i) {
- const int off = (i >> 1);
- const int W = best_y[i];
- const int r = best_uv[off + 0 * uv_w] + W;
- const int g = best_uv[off + 1 * uv_w] + W;
- const int b = best_uv[off + 2 * uv_w] + W;
- dst_y[i] = ConvertRGBToY(r, g, b);
- }
- best_y += w;
- best_uv += (j & 1) * 3 * uv_w;
- dst_y += picture->y_stride;
- }
- for (best_uv = best_uv_base, j = 0; j < uv_h; ++j) {
- for (i = 0; i < uv_w; ++i) {
- const int off = i;
- const int r = best_uv[off + 0 * uv_w];
- const int g = best_uv[off + 1 * uv_w];
- const int b = best_uv[off + 2 * uv_w];
- dst_u[i] = ConvertRGBToU(r, g, b);
- dst_v[i] = ConvertRGBToV(r, g, b);
- }
- best_uv += 3 * uv_w;
- dst_u += picture->uv_stride;
- dst_v += picture->uv_stride;
- }
- return 1;
+#if defined(WEBP_USE_THREAD) && !defined(_WIN32)
+ (void)pthread_mutex_unlock(&initsharpyuv_lock);
+#endif
}
-//------------------------------------------------------------------------------
-// Main function
-
-#define SAFE_ALLOC(W, H, T) ((T*)WebPSafeMalloc((W) * (H), sizeof(T)))
-
static int PreprocessARGB(const uint8_t* r_ptr,
const uint8_t* g_ptr,
const uint8_t* b_ptr,
int step, int rgb_stride,
WebPPicture* const picture) {
- // we expand the right/bottom border if needed
- const int w = (picture->width + 1) & ~1;
- const int h = (picture->height + 1) & ~1;
- const int uv_w = w >> 1;
- const int uv_h = h >> 1;
- uint64_t prev_diff_y_sum = ~0;
- int j, iter;
-
- // TODO(skal): allocate one big memory chunk. But for now, it's easier
- // for valgrind debugging to have several chunks.
- fixed_y_t* const tmp_buffer = SAFE_ALLOC(w * 3, 2, fixed_y_t); // scratch
- fixed_y_t* const best_y_base = SAFE_ALLOC(w, h, fixed_y_t);
- fixed_y_t* const target_y_base = SAFE_ALLOC(w, h, fixed_y_t);
- fixed_y_t* const best_rgb_y = SAFE_ALLOC(w, 2, fixed_y_t);
- fixed_t* const best_uv_base = SAFE_ALLOC(uv_w * 3, uv_h, fixed_t);
- fixed_t* const target_uv_base = SAFE_ALLOC(uv_w * 3, uv_h, fixed_t);
- fixed_t* const best_rgb_uv = SAFE_ALLOC(uv_w * 3, 1, fixed_t);
- fixed_y_t* best_y = best_y_base;
- fixed_y_t* target_y = target_y_base;
- fixed_t* best_uv = best_uv_base;
- fixed_t* target_uv = target_uv_base;
- const uint64_t diff_y_threshold = (uint64_t)(3.0 * w * h);
- int ok;
-
- if (best_y_base == NULL || best_uv_base == NULL ||
- target_y_base == NULL || target_uv_base == NULL ||
- best_rgb_y == NULL || best_rgb_uv == NULL ||
- tmp_buffer == NULL) {
- ok = WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
- goto End;
- }
- assert(picture->width >= kMinDimensionIterativeConversion);
- assert(picture->height >= kMinDimensionIterativeConversion);
-
- WebPInitConvertARGBToYUV();
-
- // Import RGB samples to W/RGB representation.
- for (j = 0; j < picture->height; j += 2) {
- const int is_last_row = (j == picture->height - 1);
- fixed_y_t* const src1 = tmp_buffer + 0 * w;
- fixed_y_t* const src2 = tmp_buffer + 3 * w;
-
- // prepare two rows of input
- ImportOneRow(r_ptr, g_ptr, b_ptr, step, picture->width, src1);
- if (!is_last_row) {
- ImportOneRow(r_ptr + rgb_stride, g_ptr + rgb_stride, b_ptr + rgb_stride,
- step, picture->width, src2);
- } else {
- memcpy(src2, src1, 3 * w * sizeof(*src2));
- }
- StoreGray(src1, best_y + 0, w);
- StoreGray(src2, best_y + w, w);
-
- UpdateW(src1, target_y, w);
- UpdateW(src2, target_y + w, w);
- UpdateChroma(src1, src2, target_uv, uv_w);
- memcpy(best_uv, target_uv, 3 * uv_w * sizeof(*best_uv));
- best_y += 2 * w;
- best_uv += 3 * uv_w;
- target_y += 2 * w;
- target_uv += 3 * uv_w;
- r_ptr += 2 * rgb_stride;
- g_ptr += 2 * rgb_stride;
- b_ptr += 2 * rgb_stride;
- }
-
- // Iterate and resolve clipping conflicts.
- for (iter = 0; iter < kNumIterations; ++iter) {
- const fixed_t* cur_uv = best_uv_base;
- const fixed_t* prev_uv = best_uv_base;
- uint64_t diff_y_sum = 0;
-
- best_y = best_y_base;
- best_uv = best_uv_base;
- target_y = target_y_base;
- target_uv = target_uv_base;
- for (j = 0; j < h; j += 2) {
- fixed_y_t* const src1 = tmp_buffer + 0 * w;
- fixed_y_t* const src2 = tmp_buffer + 3 * w;
- {
- const fixed_t* const next_uv = cur_uv + ((j < h - 2) ? 3 * uv_w : 0);
- InterpolateTwoRows(best_y, prev_uv, cur_uv, next_uv, w, src1, src2);
- prev_uv = cur_uv;
- cur_uv = next_uv;
- }
-
- UpdateW(src1, best_rgb_y + 0 * w, w);
- UpdateW(src2, best_rgb_y + 1 * w, w);
- UpdateChroma(src1, src2, best_rgb_uv, uv_w);
-
- // update two rows of Y and one row of RGB
- diff_y_sum += WebPSharpYUVUpdateY(target_y, best_rgb_y, best_y, 2 * w);
- WebPSharpYUVUpdateRGB(target_uv, best_rgb_uv, best_uv, 3 * uv_w);
-
- best_y += 2 * w;
- best_uv += 3 * uv_w;
- target_y += 2 * w;
- target_uv += 3 * uv_w;
- }
- // test exit condition
- if (iter > 0) {
- if (diff_y_sum < diff_y_threshold) break;
- if (diff_y_sum > prev_diff_y_sum) break;
- }
- prev_diff_y_sum = diff_y_sum;
+ const int ok = SharpYuvConvert(
+ r_ptr, g_ptr, b_ptr, step, rgb_stride, /*rgb_bit_depth=*/8,
+ picture->y, picture->y_stride, picture->u, picture->uv_stride, picture->v,
+ picture->uv_stride, /*yuv_bit_depth=*/8, picture->width,
+ picture->height, SharpYuvGetConversionMatrix(kSharpYuvMatrixWebp));
+ if (!ok) {
+ return WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
}
- // final reconstruction
- ok = ConvertWRGBToYUV(best_y_base, best_uv_base, picture);
-
- End:
- WebPSafeFree(best_y_base);
- WebPSafeFree(best_uv_base);
- WebPSafeFree(target_y_base);
- WebPSafeFree(target_uv_base);
- WebPSafeFree(best_rgb_y);
- WebPSafeFree(best_rgb_uv);
- WebPSafeFree(tmp_buffer);
return ok;
}
-#undef SAFE_ALLOC
//------------------------------------------------------------------------------
// "Fast" regular RGB->YUV
@@ -591,8 +224,8 @@ static const int kAlphaFix = 19;
// and constant are adjusted very tightly to fit 32b arithmetic.
// In particular, they use the fact that the operands for 'v / a' are actually
// derived as v = (a0.p0 + a1.p1 + a2.p2 + a3.p3) and a = a0 + a1 + a2 + a3
-// with ai in [0..255] and pi in [0..1<<kGammaFix). The constraint to avoid
-// overflow is: kGammaFix + kAlphaFix <= 31.
+// with ai in [0..255] and pi in [0..1<<GAMMA_FIX). The constraint to avoid
+// overflow is: GAMMA_FIX + kAlphaFix <= 31.
static const uint32_t kInvAlpha[4 * 0xff + 1] = {
0, /* alpha = 0 */
524288, 262144, 174762, 131072, 104857, 87381, 74898, 65536,
@@ -818,11 +451,20 @@ static WEBP_INLINE void AccumulateRGB(const uint8_t* const r_ptr,
dst[0] = SUM4(r_ptr + j, step);
dst[1] = SUM4(g_ptr + j, step);
dst[2] = SUM4(b_ptr + j, step);
+ // MemorySanitizer may raise false positives with data that passes through
+ // RGBA32PackedToPlanar_16b_SSE41() due to incorrect modeling of shuffles.
+ // See https://crbug.com/webp/573.
+#ifdef WEBP_MSAN
+ dst[3] = 0;
+#endif
}
if (width & 1) {
dst[0] = SUM2(r_ptr + j);
dst[1] = SUM2(g_ptr + j);
dst[2] = SUM2(b_ptr + j);
+#ifdef WEBP_MSAN
+ dst[3] = 0;
+#endif
}
}
@@ -863,18 +505,18 @@ static int ImportYUVAFromRGBA(const uint8_t* r_ptr,
use_iterative_conversion = 0;
}
- if (!WebPPictureAllocYUVA(picture, width, height)) {
+ if (!WebPPictureAllocYUVA(picture)) {
return 0;
}
if (has_alpha) {
assert(step == 4);
#if defined(USE_GAMMA_COMPRESSION) && defined(USE_INVERSE_ALPHA_TABLE)
- assert(kAlphaFix + kGammaFix <= 31);
+ assert(kAlphaFix + GAMMA_FIX <= 31);
#endif
}
if (use_iterative_conversion) {
- InitGammaTablesS();
+ SafeInitSharpYuv();
if (!PreprocessARGB(r_ptr, g_ptr, b_ptr, step, rgb_stride, picture)) {
return 0;
}
@@ -1044,7 +686,7 @@ int WebPPictureYUVAToARGB(WebPPicture* picture) {
return WebPEncodingSetError(picture, VP8_ENC_ERROR_INVALID_CONFIGURATION);
}
// Allocate a new argb buffer (discarding the previous one).
- if (!WebPPictureAllocARGB(picture, picture->width, picture->height)) return 0;
+ if (!WebPPictureAllocARGB(picture)) return 0;
picture->use_argb = 1;
// Convert
@@ -1106,6 +748,8 @@ static int Import(WebPPicture* const picture,
const int width = picture->width;
const int height = picture->height;
+ if (abs(rgb_stride) < (import_alpha ? 4 : 3) * width) return 0;
+
if (!picture->use_argb) {
const uint8_t* a_ptr = import_alpha ? rgb + 3 : NULL;
return ImportYUVAFromRGBA(r_ptr, g_ptr, b_ptr, a_ptr, step, rgb_stride,
@@ -1163,24 +807,24 @@ static int Import(WebPPicture* const picture,
#if !defined(WEBP_REDUCE_CSP)
int WebPPictureImportBGR(WebPPicture* picture,
- const uint8_t* rgb, int rgb_stride) {
- return (picture != NULL && rgb != NULL)
- ? Import(picture, rgb, rgb_stride, 3, 1, 0)
+ const uint8_t* bgr, int bgr_stride) {
+ return (picture != NULL && bgr != NULL)
+ ? Import(picture, bgr, bgr_stride, 3, 1, 0)
: 0;
}
int WebPPictureImportBGRA(WebPPicture* picture,
- const uint8_t* rgba, int rgba_stride) {
- return (picture != NULL && rgba != NULL)
- ? Import(picture, rgba, rgba_stride, 4, 1, 1)
+ const uint8_t* bgra, int bgra_stride) {
+ return (picture != NULL && bgra != NULL)
+ ? Import(picture, bgra, bgra_stride, 4, 1, 1)
: 0;
}
int WebPPictureImportBGRX(WebPPicture* picture,
- const uint8_t* rgba, int rgba_stride) {
- return (picture != NULL && rgba != NULL)
- ? Import(picture, rgba, rgba_stride, 4, 1, 0)
+ const uint8_t* bgrx, int bgrx_stride) {
+ return (picture != NULL && bgrx != NULL)
+ ? Import(picture, bgrx, bgrx_stride, 4, 1, 0)
: 0;
}
@@ -1201,9 +845,9 @@ int WebPPictureImportRGBA(WebPPicture* picture,
}
int WebPPictureImportRGBX(WebPPicture* picture,
- const uint8_t* rgba, int rgba_stride) {
- return (picture != NULL && rgba != NULL)
- ? Import(picture, rgba, rgba_stride, 4, 0, 0)
+ const uint8_t* rgbx, int rgbx_stride) {
+ return (picture != NULL && rgbx != NULL)
+ ? Import(picture, rgbx, rgbx_stride, 4, 0, 0)
: 0;
}
diff --git a/thirdparty/libwebp/src/enc/picture_enc.c b/thirdparty/libwebp/src/enc/picture_enc.c
index c691622d03..3af6383d38 100644
--- a/thirdparty/libwebp/src/enc/picture_enc.c
+++ b/thirdparty/libwebp/src/enc/picture_enc.c
@@ -45,6 +45,22 @@ int WebPPictureInitInternal(WebPPicture* picture, int version) {
//------------------------------------------------------------------------------
+int WebPValidatePicture(const WebPPicture* const picture) {
+ if (picture == NULL) return 0;
+ if (picture->width <= 0 || picture->height <= 0) {
+ return WebPEncodingSetError(picture, VP8_ENC_ERROR_BAD_DIMENSION);
+ }
+ if (picture->width <= 0 || picture->width / 4 > INT_MAX / 4 ||
+ picture->height <= 0 || picture->height / 4 > INT_MAX / 4) {
+ return WebPEncodingSetError(picture, VP8_ENC_ERROR_BAD_DIMENSION);
+ }
+ if (picture->colorspace != WEBP_YUV420 &&
+ picture->colorspace != WEBP_YUV420A) {
+ return WebPEncodingSetError(picture, VP8_ENC_ERROR_INVALID_CONFIGURATION);
+ }
+ return 1;
+}
+
static void WebPPictureResetBufferARGB(WebPPicture* const picture) {
picture->memory_argb_ = NULL;
picture->argb = NULL;
@@ -63,18 +79,17 @@ void WebPPictureResetBuffers(WebPPicture* const picture) {
WebPPictureResetBufferYUVA(picture);
}
-int WebPPictureAllocARGB(WebPPicture* const picture, int width, int height) {
+int WebPPictureAllocARGB(WebPPicture* const picture) {
void* memory;
+ const int width = picture->width;
+ const int height = picture->height;
const uint64_t argb_size = (uint64_t)width * height;
- assert(picture != NULL);
+ if (!WebPValidatePicture(picture)) return 0;
WebPSafeFree(picture->memory_argb_);
WebPPictureResetBufferARGB(picture);
- if (width <= 0 || height <= 0) {
- return WebPEncodingSetError(picture, VP8_ENC_ERROR_BAD_DIMENSION);
- }
// allocate a new buffer.
memory = WebPSafeMalloc(argb_size + WEBP_ALIGN_CST, sizeof(*picture->argb));
if (memory == NULL) {
@@ -86,10 +101,10 @@ int WebPPictureAllocARGB(WebPPicture* const picture, int width, int height) {
return 1;
}
-int WebPPictureAllocYUVA(WebPPicture* const picture, int width, int height) {
- const WebPEncCSP uv_csp =
- (WebPEncCSP)((int)picture->colorspace & WEBP_CSP_UV_MASK);
+int WebPPictureAllocYUVA(WebPPicture* const picture) {
const int has_alpha = (int)picture->colorspace & WEBP_CSP_ALPHA_BIT;
+ const int width = picture->width;
+ const int height = picture->height;
const int y_stride = width;
const int uv_width = (int)(((int64_t)width + 1) >> 1);
const int uv_height = (int)(((int64_t)height + 1) >> 1);
@@ -98,15 +113,11 @@ int WebPPictureAllocYUVA(WebPPicture* const picture, int width, int height) {
uint64_t y_size, uv_size, a_size, total_size;
uint8_t* mem;
- assert(picture != NULL);
+ if (!WebPValidatePicture(picture)) return 0;
WebPSafeFree(picture->memory_);
WebPPictureResetBufferYUVA(picture);
- if (uv_csp != WEBP_YUV420) {
- return WebPEncodingSetError(picture, VP8_ENC_ERROR_INVALID_CONFIGURATION);
- }
-
// alpha
a_width = has_alpha ? width : 0;
a_stride = a_width;
@@ -152,15 +163,12 @@ int WebPPictureAllocYUVA(WebPPicture* const picture, int width, int height) {
int WebPPictureAlloc(WebPPicture* picture) {
if (picture != NULL) {
- const int width = picture->width;
- const int height = picture->height;
-
WebPPictureFree(picture); // erase previous buffer
if (!picture->use_argb) {
- return WebPPictureAllocYUVA(picture, width, height);
+ return WebPPictureAllocYUVA(picture);
} else {
- return WebPPictureAllocARGB(picture, width, height);
+ return WebPPictureAllocARGB(picture);
}
}
return 1;
diff --git a/thirdparty/libwebp/src/enc/picture_rescale_enc.c b/thirdparty/libwebp/src/enc/picture_rescale_enc.c
index a75f5d9c06..839f91cacc 100644
--- a/thirdparty/libwebp/src/enc/picture_rescale_enc.c
+++ b/thirdparty/libwebp/src/enc/picture_rescale_enc.c
@@ -13,14 +13,15 @@
#include "src/webp/encode.h"
-#if !defined(WEBP_REDUCE_SIZE)
-
#include <assert.h>
#include <stdlib.h>
#include "src/enc/vp8i_enc.h"
+
+#if !defined(WEBP_REDUCE_SIZE)
#include "src/utils/rescaler_utils.h"
#include "src/utils/utils.h"
+#endif // !defined(WEBP_REDUCE_SIZE)
#define HALVE(x) (((x) + 1) >> 1)
@@ -56,6 +57,7 @@ static int AdjustAndCheckRectangle(const WebPPicture* const pic,
return 1;
}
+#if !defined(WEBP_REDUCE_SIZE)
int WebPPictureCopy(const WebPPicture* src, WebPPicture* dst) {
if (src == NULL || dst == NULL) return 0;
if (src == dst) return 1;
@@ -81,6 +83,7 @@ int WebPPictureCopy(const WebPPicture* src, WebPPicture* dst) {
}
return 1;
}
+#endif // !defined(WEBP_REDUCE_SIZE)
int WebPPictureIsView(const WebPPicture* picture) {
if (picture == NULL) return 0;
@@ -120,6 +123,7 @@ int WebPPictureView(const WebPPicture* src,
return 1;
}
+#if !defined(WEBP_REDUCE_SIZE)
//------------------------------------------------------------------------------
// Picture cropping
@@ -198,34 +202,34 @@ static void AlphaMultiplyY(WebPPicture* const pic, int inverse) {
}
}
-int WebPPictureRescale(WebPPicture* pic, int width, int height) {
+int WebPPictureRescale(WebPPicture* picture, int width, int height) {
WebPPicture tmp;
int prev_width, prev_height;
rescaler_t* work;
- if (pic == NULL) return 0;
- prev_width = pic->width;
- prev_height = pic->height;
+ if (picture == NULL) return 0;
+ prev_width = picture->width;
+ prev_height = picture->height;
if (!WebPRescalerGetScaledDimensions(
prev_width, prev_height, &width, &height)) {
return 0;
}
- PictureGrabSpecs(pic, &tmp);
+ PictureGrabSpecs(picture, &tmp);
tmp.width = width;
tmp.height = height;
if (!WebPPictureAlloc(&tmp)) return 0;
- if (!pic->use_argb) {
+ if (!picture->use_argb) {
work = (rescaler_t*)WebPSafeMalloc(2ULL * width, sizeof(*work));
if (work == NULL) {
WebPPictureFree(&tmp);
return 0;
}
// If present, we need to rescale alpha first (for AlphaMultiplyY).
- if (pic->a != NULL) {
+ if (picture->a != NULL) {
WebPInitAlphaProcessing();
- if (!RescalePlane(pic->a, prev_width, prev_height, pic->a_stride,
+ if (!RescalePlane(picture->a, prev_width, prev_height, picture->a_stride,
tmp.a, width, height, tmp.a_stride, work, 1)) {
return 0;
}
@@ -233,17 +237,15 @@ int WebPPictureRescale(WebPPicture* pic, int width, int height) {
// We take transparency into account on the luma plane only. That's not
// totally exact blending, but still is a good approximation.
- AlphaMultiplyY(pic, 0);
- if (!RescalePlane(pic->y, prev_width, prev_height, pic->y_stride,
+ AlphaMultiplyY(picture, 0);
+ if (!RescalePlane(picture->y, prev_width, prev_height, picture->y_stride,
tmp.y, width, height, tmp.y_stride, work, 1) ||
- !RescalePlane(pic->u,
- HALVE(prev_width), HALVE(prev_height), pic->uv_stride,
- tmp.u,
- HALVE(width), HALVE(height), tmp.uv_stride, work, 1) ||
- !RescalePlane(pic->v,
- HALVE(prev_width), HALVE(prev_height), pic->uv_stride,
- tmp.v,
- HALVE(width), HALVE(height), tmp.uv_stride, work, 1)) {
+ !RescalePlane(picture->u, HALVE(prev_width), HALVE(prev_height),
+ picture->uv_stride, tmp.u, HALVE(width), HALVE(height),
+ tmp.uv_stride, work, 1) ||
+ !RescalePlane(picture->v, HALVE(prev_width), HALVE(prev_height),
+ picture->uv_stride, tmp.v, HALVE(width), HALVE(height),
+ tmp.uv_stride, work, 1)) {
return 0;
}
AlphaMultiplyY(&tmp, 1);
@@ -257,18 +259,17 @@ int WebPPictureRescale(WebPPicture* pic, int width, int height) {
// weighting first (black-matting), scale the RGB values, and remove
// the premultiplication afterward (while preserving the alpha channel).
WebPInitAlphaProcessing();
- AlphaMultiplyARGB(pic, 0);
- if (!RescalePlane((const uint8_t*)pic->argb, prev_width, prev_height,
- pic->argb_stride * 4,
- (uint8_t*)tmp.argb, width, height,
- tmp.argb_stride * 4, work, 4)) {
+ AlphaMultiplyARGB(picture, 0);
+ if (!RescalePlane((const uint8_t*)picture->argb, prev_width, prev_height,
+ picture->argb_stride * 4, (uint8_t*)tmp.argb, width,
+ height, tmp.argb_stride * 4, work, 4)) {
return 0;
}
AlphaMultiplyARGB(&tmp, 1);
}
- WebPPictureFree(pic);
+ WebPPictureFree(picture);
WebPSafeFree(work);
- *pic = tmp;
+ *picture = tmp;
return 1;
}
@@ -280,23 +281,6 @@ int WebPPictureCopy(const WebPPicture* src, WebPPicture* dst) {
return 0;
}
-int WebPPictureIsView(const WebPPicture* picture) {
- (void)picture;
- return 0;
-}
-
-int WebPPictureView(const WebPPicture* src,
- int left, int top, int width, int height,
- WebPPicture* dst) {
- (void)src;
- (void)left;
- (void)top;
- (void)width;
- (void)height;
- (void)dst;
- return 0;
-}
-
int WebPPictureCrop(WebPPicture* pic,
int left, int top, int width, int height) {
(void)pic;
diff --git a/thirdparty/libwebp/src/enc/picture_tools_enc.c b/thirdparty/libwebp/src/enc/picture_tools_enc.c
index 38cb01534a..147cc18608 100644
--- a/thirdparty/libwebp/src/enc/picture_tools_enc.c
+++ b/thirdparty/libwebp/src/enc/picture_tools_enc.c
@@ -190,27 +190,28 @@ static WEBP_INLINE uint32_t MakeARGB32(int r, int g, int b) {
return (0xff000000u | (r << 16) | (g << 8) | b);
}
-void WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb) {
+void WebPBlendAlpha(WebPPicture* picture, uint32_t background_rgb) {
const int red = (background_rgb >> 16) & 0xff;
const int green = (background_rgb >> 8) & 0xff;
const int blue = (background_rgb >> 0) & 0xff;
int x, y;
- if (pic == NULL) return;
- if (!pic->use_argb) {
- const int uv_width = (pic->width >> 1); // omit last pixel during u/v loop
+ if (picture == NULL) return;
+ if (!picture->use_argb) {
+ // omit last pixel during u/v loop
+ const int uv_width = (picture->width >> 1);
const int Y0 = VP8RGBToY(red, green, blue, YUV_HALF);
// VP8RGBToU/V expects the u/v values summed over four pixels
const int U0 = VP8RGBToU(4 * red, 4 * green, 4 * blue, 4 * YUV_HALF);
const int V0 = VP8RGBToV(4 * red, 4 * green, 4 * blue, 4 * YUV_HALF);
- const int has_alpha = pic->colorspace & WEBP_CSP_ALPHA_BIT;
- uint8_t* y_ptr = pic->y;
- uint8_t* u_ptr = pic->u;
- uint8_t* v_ptr = pic->v;
- uint8_t* a_ptr = pic->a;
+ const int has_alpha = picture->colorspace & WEBP_CSP_ALPHA_BIT;
+ uint8_t* y_ptr = picture->y;
+ uint8_t* u_ptr = picture->u;
+ uint8_t* v_ptr = picture->v;
+ uint8_t* a_ptr = picture->a;
if (!has_alpha || a_ptr == NULL) return; // nothing to do
- for (y = 0; y < pic->height; ++y) {
+ for (y = 0; y < picture->height; ++y) {
// Luma blending
- for (x = 0; x < pic->width; ++x) {
+ for (x = 0; x < picture->width; ++x) {
const uint8_t alpha = a_ptr[x];
if (alpha < 0xff) {
y_ptr[x] = BLEND(Y0, y_ptr[x], alpha);
@@ -219,7 +220,7 @@ void WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb) {
// Chroma blending every even line
if ((y & 1) == 0) {
uint8_t* const a_ptr2 =
- (y + 1 == pic->height) ? a_ptr : a_ptr + pic->a_stride;
+ (y + 1 == picture->height) ? a_ptr : a_ptr + picture->a_stride;
for (x = 0; x < uv_width; ++x) {
// Average four alpha values into a single blending weight.
// TODO(skal): might lead to visible contouring. Can we do better?
@@ -229,24 +230,24 @@ void WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb) {
u_ptr[x] = BLEND_10BIT(U0, u_ptr[x], alpha);
v_ptr[x] = BLEND_10BIT(V0, v_ptr[x], alpha);
}
- if (pic->width & 1) { // rightmost pixel
+ if (picture->width & 1) { // rightmost pixel
const uint32_t alpha = 2 * (a_ptr[2 * x + 0] + a_ptr2[2 * x + 0]);
u_ptr[x] = BLEND_10BIT(U0, u_ptr[x], alpha);
v_ptr[x] = BLEND_10BIT(V0, v_ptr[x], alpha);
}
} else {
- u_ptr += pic->uv_stride;
- v_ptr += pic->uv_stride;
+ u_ptr += picture->uv_stride;
+ v_ptr += picture->uv_stride;
}
- memset(a_ptr, 0xff, pic->width); // reset alpha value to opaque
- a_ptr += pic->a_stride;
- y_ptr += pic->y_stride;
+ memset(a_ptr, 0xff, picture->width); // reset alpha value to opaque
+ a_ptr += picture->a_stride;
+ y_ptr += picture->y_stride;
}
} else {
- uint32_t* argb = pic->argb;
+ uint32_t* argb = picture->argb;
const uint32_t background = MakeARGB32(red, green, blue);
- for (y = 0; y < pic->height; ++y) {
- for (x = 0; x < pic->width; ++x) {
+ for (y = 0; y < picture->height; ++y) {
+ for (x = 0; x < picture->width; ++x) {
const int alpha = (argb[x] >> 24) & 0xff;
if (alpha != 0xff) {
if (alpha > 0) {
@@ -262,7 +263,7 @@ void WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb) {
}
}
}
- argb += pic->argb_stride;
+ argb += picture->argb_stride;
}
}
}
diff --git a/thirdparty/libwebp/src/enc/predictor_enc.c b/thirdparty/libwebp/src/enc/predictor_enc.c
index 2b5c767280..b3d44b59d5 100644
--- a/thirdparty/libwebp/src/enc/predictor_enc.c
+++ b/thirdparty/libwebp/src/enc/predictor_enc.c
@@ -16,6 +16,7 @@
#include "src/dsp/lossless.h"
#include "src/dsp/lossless_common.h"
+#include "src/enc/vp8i_enc.h"
#include "src/enc/vp8li_enc.h"
#define MAX_DIFF_COST (1e30f)
@@ -31,10 +32,10 @@ static WEBP_INLINE int GetMin(int a, int b) { return (a > b) ? b : a; }
// Methods to calculate Entropy (Shannon).
static float PredictionCostSpatial(const int counts[256], int weight_0,
- double exp_val) {
+ float exp_val) {
const int significant_symbols = 256 >> 4;
- const double exp_decay_factor = 0.6;
- double bits = weight_0 * counts[0];
+ const float exp_decay_factor = 0.6f;
+ float bits = (float)weight_0 * counts[0];
int i;
for (i = 1; i < significant_symbols; ++i) {
bits += exp_val * (counts[i] + counts[256 - i]);
@@ -46,9 +47,9 @@ static float PredictionCostSpatial(const int counts[256], int weight_0,
static float PredictionCostSpatialHistogram(const int accumulated[4][256],
const int tile[4][256]) {
int i;
- double retval = 0;
+ float retval = 0.f;
for (i = 0; i < 4; ++i) {
- const double kExpValue = 0.94;
+ const float kExpValue = 0.94f;
retval += PredictionCostSpatial(tile[i], 1, kExpValue);
retval += VP8LCombinedShannonEntropy(tile[i], accumulated[i]);
}
@@ -472,12 +473,15 @@ static void CopyImageWithPrediction(int width, int height,
// with respect to predictions. If near_lossless_quality < 100, applies
// near lossless processing, shaving off more bits of residuals for lower
// qualities.
-void VP8LResidualImage(int width, int height, int bits, int low_effort,
- uint32_t* const argb, uint32_t* const argb_scratch,
- uint32_t* const image, int near_lossless_quality,
- int exact, int used_subtract_green) {
+int VP8LResidualImage(int width, int height, int bits, int low_effort,
+ uint32_t* const argb, uint32_t* const argb_scratch,
+ uint32_t* const image, int near_lossless_quality,
+ int exact, int used_subtract_green,
+ const WebPPicture* const pic, int percent_range,
+ int* const percent) {
const int tiles_per_row = VP8LSubSampleSize(width, bits);
const int tiles_per_col = VP8LSubSampleSize(height, bits);
+ int percent_start = *percent;
int tile_y;
int histo[4][256];
const int max_quantization = 1 << VP8LNearLosslessBits(near_lossless_quality);
@@ -491,17 +495,24 @@ void VP8LResidualImage(int width, int height, int bits, int low_effort,
for (tile_y = 0; tile_y < tiles_per_col; ++tile_y) {
int tile_x;
for (tile_x = 0; tile_x < tiles_per_row; ++tile_x) {
- const int pred = GetBestPredictorForTile(width, height, tile_x, tile_y,
- bits, histo, argb_scratch, argb, max_quantization, exact,
- used_subtract_green, image);
+ const int pred = GetBestPredictorForTile(
+ width, height, tile_x, tile_y, bits, histo, argb_scratch, argb,
+ max_quantization, exact, used_subtract_green, image);
image[tile_y * tiles_per_row + tile_x] = ARGB_BLACK | (pred << 8);
}
+
+ if (!WebPReportProgress(
+ pic, percent_start + percent_range * tile_y / tiles_per_col,
+ percent)) {
+ return 0;
+ }
}
}
CopyImageWithPrediction(width, height, bits, image, argb_scratch, argb,
low_effort, max_quantization, exact,
used_subtract_green);
+ return WebPReportProgress(pic, percent_start + percent_range, percent);
}
//------------------------------------------------------------------------------
@@ -532,7 +543,7 @@ static float PredictionCostCrossColor(const int accumulated[256],
const int counts[256]) {
// Favor low entropy, locally and globally.
// Favor small absolute values for PredictionCostSpatial
- static const double kExpValue = 2.4;
+ static const float kExpValue = 2.4f;
return VP8LCombinedShannonEntropy(counts, accumulated) +
PredictionCostSpatial(counts, 3, kExpValue);
}
@@ -714,11 +725,14 @@ static void CopyTileWithColorTransform(int xsize, int ysize,
}
}
-void VP8LColorSpaceTransform(int width, int height, int bits, int quality,
- uint32_t* const argb, uint32_t* image) {
+int VP8LColorSpaceTransform(int width, int height, int bits, int quality,
+ uint32_t* const argb, uint32_t* image,
+ const WebPPicture* const pic, int percent_range,
+ int* const percent) {
const int max_tile_size = 1 << bits;
const int tile_xsize = VP8LSubSampleSize(width, bits);
const int tile_ysize = VP8LSubSampleSize(height, bits);
+ int percent_start = *percent;
int accumulated_red_histo[256] = { 0 };
int accumulated_blue_histo[256] = { 0 };
int tile_x, tile_y;
@@ -768,5 +782,11 @@ void VP8LColorSpaceTransform(int width, int height, int bits, int quality,
}
}
}
+ if (!WebPReportProgress(
+ pic, percent_start + percent_range * tile_y / tile_ysize,
+ percent)) {
+ return 0;
+ }
}
+ return 1;
}
diff --git a/thirdparty/libwebp/src/enc/quant_enc.c b/thirdparty/libwebp/src/enc/quant_enc.c
index 6cede28ab4..6d8202d277 100644
--- a/thirdparty/libwebp/src/enc/quant_enc.c
+++ b/thirdparty/libwebp/src/enc/quant_enc.c
@@ -533,7 +533,8 @@ static void InitScore(VP8ModeScore* const rd) {
rd->score = MAX_COST;
}
-static void CopyScore(VP8ModeScore* const dst, const VP8ModeScore* const src) {
+static void CopyScore(VP8ModeScore* WEBP_RESTRICT const dst,
+ const VP8ModeScore* WEBP_RESTRICT const src) {
dst->D = src->D;
dst->SD = src->SD;
dst->R = src->R;
@@ -542,7 +543,8 @@ static void CopyScore(VP8ModeScore* const dst, const VP8ModeScore* const src) {
dst->score = src->score;
}
-static void AddScore(VP8ModeScore* const dst, const VP8ModeScore* const src) {
+static void AddScore(VP8ModeScore* WEBP_RESTRICT const dst,
+ const VP8ModeScore* WEBP_RESTRICT const src) {
dst->D += src->D;
dst->SD += src->SD;
dst->R += src->R;
@@ -588,10 +590,10 @@ static WEBP_INLINE score_t RDScoreTrellis(int lambda, score_t rate,
// Coefficient type.
enum { TYPE_I16_AC = 0, TYPE_I16_DC = 1, TYPE_CHROMA_A = 2, TYPE_I4_AC = 3 };
-static int TrellisQuantizeBlock(const VP8Encoder* const enc,
+static int TrellisQuantizeBlock(const VP8Encoder* WEBP_RESTRICT const enc,
int16_t in[16], int16_t out[16],
int ctx0, int coeff_type,
- const VP8Matrix* const mtx,
+ const VP8Matrix* WEBP_RESTRICT const mtx,
int lambda) {
const ProbaArray* const probas = enc->proba_.coeffs_[coeff_type];
CostArrayPtr const costs =
@@ -767,9 +769,9 @@ static int TrellisQuantizeBlock(const VP8Encoder* const enc,
// all at once. Output is the reconstructed block in *yuv_out, and the
// quantized levels in *levels.
-static int ReconstructIntra16(VP8EncIterator* const it,
- VP8ModeScore* const rd,
- uint8_t* const yuv_out,
+static int ReconstructIntra16(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT const rd,
+ uint8_t* WEBP_RESTRICT const yuv_out,
int mode) {
const VP8Encoder* const enc = it->enc_;
const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode];
@@ -819,10 +821,10 @@ static int ReconstructIntra16(VP8EncIterator* const it,
return nz;
}
-static int ReconstructIntra4(VP8EncIterator* const it,
+static int ReconstructIntra4(VP8EncIterator* WEBP_RESTRICT const it,
int16_t levels[16],
- const uint8_t* const src,
- uint8_t* const yuv_out,
+ const uint8_t* WEBP_RESTRICT const src,
+ uint8_t* WEBP_RESTRICT const yuv_out,
int mode) {
const VP8Encoder* const enc = it->enc_;
const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode];
@@ -855,7 +857,8 @@ static int ReconstructIntra4(VP8EncIterator* const it,
// Quantize as usual, but also compute and return the quantization error.
// Error is already divided by DSHIFT.
-static int QuantizeSingle(int16_t* const v, const VP8Matrix* const mtx) {
+static int QuantizeSingle(int16_t* WEBP_RESTRICT const v,
+ const VP8Matrix* WEBP_RESTRICT const mtx) {
int V = *v;
const int sign = (V < 0);
if (sign) V = -V;
@@ -869,9 +872,10 @@ static int QuantizeSingle(int16_t* const v, const VP8Matrix* const mtx) {
return (sign ? -V : V) >> DSCALE;
}
-static void CorrectDCValues(const VP8EncIterator* const it,
- const VP8Matrix* const mtx,
- int16_t tmp[][16], VP8ModeScore* const rd) {
+static void CorrectDCValues(const VP8EncIterator* WEBP_RESTRICT const it,
+ const VP8Matrix* WEBP_RESTRICT const mtx,
+ int16_t tmp[][16],
+ VP8ModeScore* WEBP_RESTRICT const rd) {
// | top[0] | top[1]
// --------+--------+---------
// left[0] | tmp[0] tmp[1] <-> err0 err1
@@ -902,8 +906,8 @@ static void CorrectDCValues(const VP8EncIterator* const it,
}
}
-static void StoreDiffusionErrors(VP8EncIterator* const it,
- const VP8ModeScore* const rd) {
+static void StoreDiffusionErrors(VP8EncIterator* WEBP_RESTRICT const it,
+ const VP8ModeScore* WEBP_RESTRICT const rd) {
int ch;
for (ch = 0; ch <= 1; ++ch) {
int8_t* const top = it->top_derr_[it->x_][ch];
@@ -922,8 +926,9 @@ static void StoreDiffusionErrors(VP8EncIterator* const it,
//------------------------------------------------------------------------------
-static int ReconstructUV(VP8EncIterator* const it, VP8ModeScore* const rd,
- uint8_t* const yuv_out, int mode) {
+static int ReconstructUV(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT const rd,
+ uint8_t* WEBP_RESTRICT const yuv_out, int mode) {
const VP8Encoder* const enc = it->enc_;
const uint8_t* const ref = it->yuv_p_ + VP8UVModeOffsets[mode];
const uint8_t* const src = it->yuv_in_ + U_OFF_ENC;
@@ -994,7 +999,8 @@ static void SwapOut(VP8EncIterator* const it) {
SwapPtr(&it->yuv_out_, &it->yuv_out2_);
}
-static void PickBestIntra16(VP8EncIterator* const it, VP8ModeScore* rd) {
+static void PickBestIntra16(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT rd) {
const int kNumBlocks = 16;
VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];
const int lambda = dqm->lambda_i16_;
@@ -1054,7 +1060,7 @@ static void PickBestIntra16(VP8EncIterator* const it, VP8ModeScore* rd) {
//------------------------------------------------------------------------------
// return the cost array corresponding to the surrounding prediction modes.
-static const uint16_t* GetCostModeI4(VP8EncIterator* const it,
+static const uint16_t* GetCostModeI4(VP8EncIterator* WEBP_RESTRICT const it,
const uint8_t modes[16]) {
const int preds_w = it->enc_->preds_w_;
const int x = (it->i4_ & 3), y = it->i4_ >> 2;
@@ -1063,7 +1069,8 @@ static const uint16_t* GetCostModeI4(VP8EncIterator* const it,
return VP8FixedCostsI4[top][left];
}
-static int PickBestIntra4(VP8EncIterator* const it, VP8ModeScore* const rd) {
+static int PickBestIntra4(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT const rd) {
const VP8Encoder* const enc = it->enc_;
const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];
const int lambda = dqm->lambda_i4_;
@@ -1159,7 +1166,8 @@ static int PickBestIntra4(VP8EncIterator* const it, VP8ModeScore* const rd) {
//------------------------------------------------------------------------------
-static void PickBestUV(VP8EncIterator* const it, VP8ModeScore* const rd) {
+static void PickBestUV(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT const rd) {
const int kNumBlocks = 8;
const VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];
const int lambda = dqm->lambda_uv_;
@@ -1211,7 +1219,8 @@ static void PickBestUV(VP8EncIterator* const it, VP8ModeScore* const rd) {
//------------------------------------------------------------------------------
// Final reconstruction and quantization.
-static void SimpleQuantize(VP8EncIterator* const it, VP8ModeScore* const rd) {
+static void SimpleQuantize(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT const rd) {
const VP8Encoder* const enc = it->enc_;
const int is_i16 = (it->mb_->type_ == 1);
int nz = 0;
@@ -1236,9 +1245,9 @@ static void SimpleQuantize(VP8EncIterator* const it, VP8ModeScore* const rd) {
}
// Refine intra16/intra4 sub-modes based on distortion only (not rate).
-static void RefineUsingDistortion(VP8EncIterator* const it,
+static void RefineUsingDistortion(VP8EncIterator* WEBP_RESTRICT const it,
int try_both_modes, int refine_uv_mode,
- VP8ModeScore* const rd) {
+ VP8ModeScore* WEBP_RESTRICT const rd) {
score_t best_score = MAX_COST;
int nz = 0;
int mode;
@@ -1352,7 +1361,8 @@ static void RefineUsingDistortion(VP8EncIterator* const it,
//------------------------------------------------------------------------------
// Entry point
-int VP8Decimate(VP8EncIterator* const it, VP8ModeScore* const rd,
+int VP8Decimate(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT const rd,
VP8RDLevel rd_opt) {
int is_skipped;
const int method = it->enc_->method_;
diff --git a/thirdparty/libwebp/src/enc/vp8i_enc.h b/thirdparty/libwebp/src/enc/vp8i_enc.h
index b4bba08f27..71f76702ae 100644
--- a/thirdparty/libwebp/src/enc/vp8i_enc.h
+++ b/thirdparty/libwebp/src/enc/vp8i_enc.h
@@ -32,7 +32,7 @@ extern "C" {
// version numbers
#define ENC_MAJ_VERSION 1
#define ENC_MIN_VERSION 2
-#define ENC_REV_VERSION 2
+#define ENC_REV_VERSION 4
enum { MAX_LF_LEVELS = 64, // Maximum loop filter level
MAX_VARIABLE_LEVEL = 67, // last (inclusive) level with variable cost
@@ -470,7 +470,8 @@ int VP8EncAnalyze(VP8Encoder* const enc);
// Sets up segment's quantization values, base_quant_ and filter strengths.
void VP8SetSegmentParams(VP8Encoder* const enc, float quality);
// Pick best modes and fills the levels. Returns true if skipped.
-int VP8Decimate(VP8EncIterator* const it, VP8ModeScore* const rd,
+int VP8Decimate(VP8EncIterator* WEBP_RESTRICT const it,
+ VP8ModeScore* WEBP_RESTRICT const rd,
VP8RDLevel rd_opt);
// in alpha.c
@@ -490,19 +491,24 @@ int VP8FilterStrengthFromDelta(int sharpness, int delta);
// misc utils for picture_*.c:
+// Returns true if 'picture' is non-NULL and dimensions/colorspace are within
+// their valid ranges. If returning false, the 'error_code' in 'picture' is
+// updated.
+int WebPValidatePicture(const WebPPicture* const picture);
+
// Remove reference to the ARGB/YUVA buffer (doesn't free anything).
void WebPPictureResetBuffers(WebPPicture* const picture);
-// Allocates ARGB buffer of given dimension (previous one is always free'd).
-// Preserves the YUV(A) buffer. Returns false in case of error (invalid param,
-// out-of-memory).
-int WebPPictureAllocARGB(WebPPicture* const picture, int width, int height);
+// Allocates ARGB buffer according to set width/height (previous one is
+// always free'd). Preserves the YUV(A) buffer. Returns false in case of error
+// (invalid param, out-of-memory).
+int WebPPictureAllocARGB(WebPPicture* const picture);
-// Allocates YUVA buffer of given dimension (previous one is always free'd).
-// Uses picture->csp to determine whether an alpha buffer is needed.
+// Allocates YUVA buffer according to set width/height (previous one is always
+// free'd). Uses picture->csp to determine whether an alpha buffer is needed.
// Preserves the ARGB buffer.
// Returns false in case of error (invalid param, out-of-memory).
-int WebPPictureAllocYUVA(WebPPicture* const picture, int width, int height);
+int WebPPictureAllocYUVA(WebPPicture* const picture);
// Replace samples that are fully transparent by 'color' to help compressibility
// (no guarantee, though). Assumes pic->use_argb is true.
diff --git a/thirdparty/libwebp/src/enc/vp8l_enc.c b/thirdparty/libwebp/src/enc/vp8l_enc.c
index e330e716f1..2b345df610 100644
--- a/thirdparty/libwebp/src/enc/vp8l_enc.c
+++ b/thirdparty/libwebp/src/enc/vp8l_enc.c
@@ -15,15 +15,16 @@
#include <assert.h>
#include <stdlib.h>
+#include "src/dsp/lossless.h"
+#include "src/dsp/lossless_common.h"
#include "src/enc/backward_references_enc.h"
#include "src/enc/histogram_enc.h"
#include "src/enc/vp8i_enc.h"
#include "src/enc/vp8li_enc.h"
-#include "src/dsp/lossless.h"
-#include "src/dsp/lossless_common.h"
#include "src/utils/bit_writer_utils.h"
#include "src/utils/huffman_encode_utils.h"
#include "src/utils/utils.h"
+#include "src/webp/encode.h"
#include "src/webp/format_constants.h"
// Maximum number of histogram images (sub-blocks).
@@ -183,10 +184,9 @@ static void CoOccurrenceFindMax(const uint32_t* const cooccurrence,
}
// Builds the cooccurrence matrix
-static WebPEncodingError CoOccurrenceBuild(const WebPPicture* const pic,
- const uint32_t* const palette,
- uint32_t num_colors,
- uint32_t* cooccurrence) {
+static int CoOccurrenceBuild(const WebPPicture* const pic,
+ const uint32_t* const palette, uint32_t num_colors,
+ uint32_t* cooccurrence) {
uint32_t *lines, *line_top, *line_current, *line_tmp;
int x, y;
const uint32_t* src = pic->argb;
@@ -195,7 +195,10 @@ static WebPEncodingError CoOccurrenceBuild(const WebPPicture* const pic,
uint32_t idx_map[MAX_PALETTE_SIZE] = {0};
uint32_t palette_sorted[MAX_PALETTE_SIZE];
lines = (uint32_t*)WebPSafeMalloc(2 * pic->width, sizeof(*lines));
- if (lines == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
+ if (lines == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
+ }
line_top = &lines[0];
line_current = &lines[pic->width];
PrepareMapToPalette(palette, num_colors, palette_sorted, idx_map);
@@ -226,7 +229,7 @@ static WebPEncodingError CoOccurrenceBuild(const WebPPicture* const pic,
src += pic->argb_stride;
}
WebPSafeFree(lines);
- return VP8_ENC_OK;
+ return 1;
}
struct Sum {
@@ -237,7 +240,7 @@ struct Sum {
// Implements the modified Zeng method from "A Survey on Palette Reordering
// Methods for Improving the Compression of Color-Indexed Images" by Armando J.
// Pinho and Antonio J. R. Neves.
-static WebPEncodingError PaletteSortModifiedZeng(
+static int PaletteSortModifiedZeng(
const WebPPicture* const pic, const uint32_t* const palette_sorted,
uint32_t num_colors, uint32_t* const palette) {
uint32_t i, j, ind;
@@ -247,15 +250,16 @@ static WebPEncodingError PaletteSortModifiedZeng(
uint32_t first, last;
uint32_t num_sums;
// TODO(vrabaud) check whether one color images should use palette or not.
- if (num_colors <= 1) return VP8_ENC_OK;
+ if (num_colors <= 1) return 1;
// Build the co-occurrence matrix.
cooccurrence =
(uint32_t*)WebPSafeCalloc(num_colors * num_colors, sizeof(*cooccurrence));
- if (cooccurrence == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
- if (CoOccurrenceBuild(pic, palette_sorted, num_colors, cooccurrence) !=
- VP8_ENC_OK) {
- WebPSafeFree(cooccurrence);
- return VP8_ENC_ERROR_OUT_OF_MEMORY;
+ if (cooccurrence == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
+ }
+ if (!CoOccurrenceBuild(pic, palette_sorted, num_colors, cooccurrence)) {
+ return 0;
}
// Initialize the mapping list with the two best indices.
@@ -316,7 +320,7 @@ static WebPEncodingError PaletteSortModifiedZeng(
for (i = 0; i < num_colors; ++i) {
palette[i] = palette_sorted[remapping[(first + i) % num_colors]];
}
- return VP8_ENC_OK;
+ return 1;
}
// -----------------------------------------------------------------------------
@@ -434,8 +438,8 @@ static int AnalyzeEntropy(const uint32_t* argb,
curr_row += argb_stride;
}
{
- double entropy_comp[kHistoTotal];
- double entropy[kNumEntropyIx];
+ float entropy_comp[kHistoTotal];
+ float entropy[kNumEntropyIx];
int k;
int last_mode_to_analyze = use_palette ? kPalette : kSpatialSubGreen;
int j;
@@ -949,11 +953,11 @@ static WEBP_INLINE void WriteHuffmanCodeWithExtraBits(
VP8LPutBits(bw, (bits << depth) | symbol, depth + n_bits);
}
-static WebPEncodingError StoreImageToBitMask(
+static int StoreImageToBitMask(
VP8LBitWriter* const bw, int width, int histo_bits,
const VP8LBackwardRefs* const refs,
const uint16_t* histogram_symbols,
- const HuffmanTreeCode* const huffman_codes) {
+ const HuffmanTreeCode* const huffman_codes, const WebPPicture* const pic) {
const int histo_xsize = histo_bits ? VP8LSubSampleSize(width, histo_bits) : 1;
const int tile_mask = (histo_bits == 0) ? 0 : -(1 << histo_bits);
// x and y trace the position in the image.
@@ -1006,44 +1010,53 @@ static WebPEncodingError StoreImageToBitMask(
}
VP8LRefsCursorNext(&c);
}
- return bw->error_ ? VP8_ENC_ERROR_OUT_OF_MEMORY : VP8_ENC_OK;
+ if (bw->error_) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
+ }
+ return 1;
}
-// Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31
-static WebPEncodingError EncodeImageNoHuffman(
- VP8LBitWriter* const bw, const uint32_t* const argb,
- VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs_array,
- int width, int height, int quality, int low_effort) {
+// Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31.
+// pic and percent are for progress.
+static int EncodeImageNoHuffman(VP8LBitWriter* const bw,
+ const uint32_t* const argb,
+ VP8LHashChain* const hash_chain,
+ VP8LBackwardRefs* const refs_array, int width,
+ int height, int quality, int low_effort,
+ const WebPPicture* const pic, int percent_range,
+ int* const percent) {
int i;
int max_tokens = 0;
- WebPEncodingError err = VP8_ENC_OK;
VP8LBackwardRefs* refs;
HuffmanTreeToken* tokens = NULL;
- HuffmanTreeCode huffman_codes[5] = { { 0, NULL, NULL } };
- const uint16_t histogram_symbols[1] = { 0 }; // only one tree, one symbol
+ HuffmanTreeCode huffman_codes[5] = {{0, NULL, NULL}};
+ const uint16_t histogram_symbols[1] = {0}; // only one tree, one symbol
int cache_bits = 0;
VP8LHistogramSet* histogram_image = NULL;
HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
- 3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
+ 3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
if (huff_tree == NULL) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
// Calculate backward references from ARGB image.
- if (!VP8LHashChainFill(hash_chain, quality, argb, width, height,
- low_effort)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ if (!VP8LHashChainFill(hash_chain, quality, argb, width, height, low_effort,
+ pic, percent_range / 2, percent)) {
+ goto Error;
+ }
+ if (!VP8LGetBackwardReferences(width, height, argb, quality, /*low_effort=*/0,
+ kLZ77Standard | kLZ77RLE, cache_bits,
+ /*do_no_cache=*/0, hash_chain, refs_array,
+ &cache_bits, pic,
+ percent_range - percent_range / 2, percent)) {
goto Error;
}
- err = VP8LGetBackwardReferences(
- width, height, argb, quality, /*low_effort=*/0, kLZ77Standard | kLZ77RLE,
- cache_bits, /*do_no_cache=*/0, hash_chain, refs_array, &cache_bits);
- if (err != VP8_ENC_OK) goto Error;
refs = &refs_array[0];
histogram_image = VP8LAllocateHistogramSet(1, cache_bits);
if (histogram_image == NULL) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
VP8LHistogramSetClear(histogram_image);
@@ -1054,7 +1067,7 @@ static WebPEncodingError EncodeImageNoHuffman(
// Create Huffman bit lengths and codes for each histogram image.
assert(histogram_image->size == 1);
if (!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
@@ -1071,7 +1084,7 @@ static WebPEncodingError EncodeImageNoHuffman(
tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
if (tokens == NULL) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
@@ -1083,27 +1096,32 @@ static WebPEncodingError EncodeImageNoHuffman(
}
// Store actual literals.
- err = StoreImageToBitMask(bw, width, 0, refs, histogram_symbols,
- huffman_codes);
+ if (!StoreImageToBitMask(bw, width, 0, refs, histogram_symbols, huffman_codes,
+ pic)) {
+ goto Error;
+ }
Error:
WebPSafeFree(tokens);
WebPSafeFree(huff_tree);
VP8LFreeHistogramSet(histogram_image);
WebPSafeFree(huffman_codes[0].codes);
- return err;
+ return (pic->error_code == VP8_ENC_OK);
}
-static WebPEncodingError EncodeImageInternal(
+// pic and percent are for progress.
+static int EncodeImageInternal(
VP8LBitWriter* const bw, const uint32_t* const argb,
VP8LHashChain* const hash_chain, VP8LBackwardRefs refs_array[4], int width,
int height, int quality, int low_effort, int use_cache,
const CrunchConfig* const config, int* cache_bits, int histogram_bits,
- size_t init_byte_position, int* const hdr_size, int* const data_size) {
- WebPEncodingError err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ size_t init_byte_position, int* const hdr_size, int* const data_size,
+ const WebPPicture* const pic, int percent_range, int* const percent) {
const uint32_t histogram_image_xysize =
VP8LSubSampleSize(width, histogram_bits) *
VP8LSubSampleSize(height, histogram_bits);
+ int remaining_percent = percent_range;
+ int percent_start = *percent;
VP8LHistogramSet* histogram_image = NULL;
VP8LHistogram* tmp_histo = NULL;
int histogram_image_size = 0;
@@ -1112,9 +1130,8 @@ static WebPEncodingError EncodeImageInternal(
3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
HuffmanTreeToken* tokens = NULL;
HuffmanTreeCode* huffman_codes = NULL;
- uint16_t* const histogram_symbols =
- (uint16_t*)WebPSafeMalloc(histogram_image_xysize,
- sizeof(*histogram_symbols));
+ uint16_t* const histogram_symbols = (uint16_t*)WebPSafeMalloc(
+ histogram_image_xysize, sizeof(*histogram_symbols));
int sub_configs_idx;
int cache_bits_init, write_histogram_image;
VP8LBitWriter bw_init = *bw, bw_best;
@@ -1126,14 +1143,27 @@ static WebPEncodingError EncodeImageInternal(
assert(hdr_size != NULL);
assert(data_size != NULL);
- // Make sure we can allocate the different objects.
memset(&hash_chain_histogram, 0, sizeof(hash_chain_histogram));
+ if (!VP8LBitWriterInit(&bw_best, 0)) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ goto Error;
+ }
+
+ // Make sure we can allocate the different objects.
if (huff_tree == NULL || histogram_symbols == NULL ||
- !VP8LHashChainInit(&hash_chain_histogram, histogram_image_xysize) ||
- !VP8LHashChainFill(hash_chain, quality, argb, width, height,
- low_effort)) {
+ !VP8LHashChainInit(&hash_chain_histogram, histogram_image_xysize)) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ goto Error;
+ }
+
+ percent_range = remaining_percent / 5;
+ if (!VP8LHashChainFill(hash_chain, quality, argb, width, height,
+ low_effort, pic, percent_range, percent)) {
goto Error;
}
+ percent_start += percent_range;
+ remaining_percent -= percent_range;
+
if (use_cache) {
// If the value is different from zero, it has been set during the
// palette analysis.
@@ -1142,22 +1172,27 @@ static WebPEncodingError EncodeImageInternal(
cache_bits_init = 0;
}
// If several iterations will happen, clone into bw_best.
- if (!VP8LBitWriterInit(&bw_best, 0) ||
- ((config->sub_configs_size_ > 1 ||
- config->sub_configs_[0].do_no_cache_) &&
- !VP8LBitWriterClone(bw, &bw_best))) {
+ if ((config->sub_configs_size_ > 1 || config->sub_configs_[0].do_no_cache_) &&
+ !VP8LBitWriterClone(bw, &bw_best)) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
+
for (sub_configs_idx = 0; sub_configs_idx < config->sub_configs_size_;
++sub_configs_idx) {
const CrunchSubConfig* const sub_config =
&config->sub_configs_[sub_configs_idx];
int cache_bits_best, i_cache;
- err = VP8LGetBackwardReferences(width, height, argb, quality, low_effort,
- sub_config->lz77_, cache_bits_init,
- sub_config->do_no_cache_, hash_chain,
- &refs_array[0], &cache_bits_best);
- if (err != VP8_ENC_OK) goto Error;
+ int i_remaining_percent = remaining_percent / config->sub_configs_size_;
+ int i_percent_range = i_remaining_percent / 4;
+ i_remaining_percent -= i_percent_range;
+
+ if (!VP8LGetBackwardReferences(
+ width, height, argb, quality, low_effort, sub_config->lz77_,
+ cache_bits_init, sub_config->do_no_cache_, hash_chain,
+ &refs_array[0], &cache_bits_best, pic, i_percent_range, percent)) {
+ goto Error;
+ }
for (i_cache = 0; i_cache < (sub_config->do_no_cache_ ? 2 : 1); ++i_cache) {
const int cache_bits_tmp = (i_cache == 0) ? cache_bits_best : 0;
@@ -1172,11 +1207,17 @@ static WebPEncodingError EncodeImageInternal(
histogram_image =
VP8LAllocateHistogramSet(histogram_image_xysize, cache_bits_tmp);
tmp_histo = VP8LAllocateHistogram(cache_bits_tmp);
- if (histogram_image == NULL || tmp_histo == NULL ||
- !VP8LGetHistoImageSymbols(width, height, &refs_array[i_cache],
- quality, low_effort, histogram_bits,
- cache_bits_tmp, histogram_image, tmp_histo,
- histogram_symbols)) {
+ if (histogram_image == NULL || tmp_histo == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ goto Error;
+ }
+
+ i_percent_range = i_remaining_percent / 3;
+ i_remaining_percent -= i_percent_range;
+ if (!VP8LGetHistoImageSymbols(
+ width, height, &refs_array[i_cache], quality, low_effort,
+ histogram_bits, cache_bits_tmp, histogram_image, tmp_histo,
+ histogram_symbols, pic, i_percent_range, percent)) {
goto Error;
}
// Create Huffman bit lengths and codes for each histogram image.
@@ -1189,6 +1230,7 @@ static WebPEncodingError EncodeImageInternal(
// GetHuffBitLengthsAndCodes().
if (huffman_codes == NULL ||
!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
// Free combined histograms.
@@ -1211,12 +1253,14 @@ static WebPEncodingError EncodeImageInternal(
write_histogram_image = (histogram_image_size > 1);
VP8LPutBits(bw, write_histogram_image, 1);
if (write_histogram_image) {
- uint32_t* const histogram_argb =
- (uint32_t*)WebPSafeMalloc(histogram_image_xysize,
- sizeof(*histogram_argb));
+ uint32_t* const histogram_argb = (uint32_t*)WebPSafeMalloc(
+ histogram_image_xysize, sizeof(*histogram_argb));
int max_index = 0;
uint32_t i;
- if (histogram_argb == NULL) goto Error;
+ if (histogram_argb == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ goto Error;
+ }
for (i = 0; i < histogram_image_xysize; ++i) {
const int symbol_index = histogram_symbols[i] & 0xffff;
histogram_argb[i] = (symbol_index << 8);
@@ -1227,12 +1271,17 @@ static WebPEncodingError EncodeImageInternal(
histogram_image_size = max_index;
VP8LPutBits(bw, histogram_bits - 2, 3);
- err = EncodeImageNoHuffman(
- bw, histogram_argb, &hash_chain_histogram, &refs_array[2],
- VP8LSubSampleSize(width, histogram_bits),
- VP8LSubSampleSize(height, histogram_bits), quality, low_effort);
+ i_percent_range = i_remaining_percent / 2;
+ i_remaining_percent -= i_percent_range;
+ if (!EncodeImageNoHuffman(
+ bw, histogram_argb, &hash_chain_histogram, &refs_array[2],
+ VP8LSubSampleSize(width, histogram_bits),
+ VP8LSubSampleSize(height, histogram_bits), quality, low_effort,
+ pic, i_percent_range, percent)) {
+ WebPSafeFree(histogram_argb);
+ goto Error;
+ }
WebPSafeFree(histogram_argb);
- if (err != VP8_ENC_OK) goto Error;
}
// Store Huffman codes.
@@ -1256,9 +1305,10 @@ static WebPEncodingError EncodeImageInternal(
}
// Store actual literals.
hdr_size_tmp = (int)(VP8LBitWriterNumBytes(bw) - init_byte_position);
- err = StoreImageToBitMask(bw, width, histogram_bits, &refs_array[i_cache],
- histogram_symbols, huffman_codes);
- if (err != VP8_ENC_OK) goto Error;
+ if (!StoreImageToBitMask(bw, width, histogram_bits, &refs_array[i_cache],
+ histogram_symbols, huffman_codes, pic)) {
+ goto Error;
+ }
// Keep track of the smallest image so far.
if (VP8LBitWriterNumBytes(bw) < bw_size_best) {
bw_size_best = VP8LBitWriterNumBytes(bw);
@@ -1278,7 +1328,10 @@ static WebPEncodingError EncodeImageInternal(
}
}
VP8LBitWriterSwap(bw, &bw_best);
- err = VP8_ENC_OK;
+
+ if (!WebPReportProgress(pic, percent_start + remaining_percent, percent)) {
+ goto Error;
+ }
Error:
WebPSafeFree(tokens);
@@ -1292,7 +1345,7 @@ static WebPEncodingError EncodeImageInternal(
}
WebPSafeFree(histogram_symbols);
VP8LBitWriterWipeOut(&bw_best);
- return err;
+ return (pic->error_code == VP8_ENC_OK);
}
// -----------------------------------------------------------------------------
@@ -1305,22 +1358,23 @@ static void ApplySubtractGreen(VP8LEncoder* const enc, int width, int height,
VP8LSubtractGreenFromBlueAndRed(enc->argb_, width * height);
}
-static WebPEncodingError ApplyPredictFilter(const VP8LEncoder* const enc,
- int width, int height,
- int quality, int low_effort,
- int used_subtract_green,
- VP8LBitWriter* const bw) {
+static int ApplyPredictFilter(const VP8LEncoder* const enc, int width,
+ int height, int quality, int low_effort,
+ int used_subtract_green, VP8LBitWriter* const bw,
+ int percent_range, int* const percent) {
const int pred_bits = enc->transform_bits_;
const int transform_width = VP8LSubSampleSize(width, pred_bits);
const int transform_height = VP8LSubSampleSize(height, pred_bits);
// we disable near-lossless quantization if palette is used.
- const int near_lossless_strength = enc->use_palette_ ? 100
- : enc->config_->near_lossless;
+ const int near_lossless_strength =
+ enc->use_palette_ ? 100 : enc->config_->near_lossless;
- VP8LResidualImage(width, height, pred_bits, low_effort, enc->argb_,
- enc->argb_scratch_, enc->transform_data_,
- near_lossless_strength, enc->config_->exact,
- used_subtract_green);
+ if (!VP8LResidualImage(
+ width, height, pred_bits, low_effort, enc->argb_, enc->argb_scratch_,
+ enc->transform_data_, near_lossless_strength, enc->config_->exact,
+ used_subtract_green, enc->pic_, percent_range / 2, percent)) {
+ return 0;
+ }
VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
VP8LPutBits(bw, PREDICTOR_TRANSFORM, 2);
assert(pred_bits >= 2);
@@ -1328,19 +1382,23 @@ static WebPEncodingError ApplyPredictFilter(const VP8LEncoder* const enc,
return EncodeImageNoHuffman(
bw, enc->transform_data_, (VP8LHashChain*)&enc->hash_chain_,
(VP8LBackwardRefs*)&enc->refs_[0], transform_width, transform_height,
- quality, low_effort);
+ quality, low_effort, enc->pic_, percent_range - percent_range / 2,
+ percent);
}
-static WebPEncodingError ApplyCrossColorFilter(const VP8LEncoder* const enc,
- int width, int height,
- int quality, int low_effort,
- VP8LBitWriter* const bw) {
+static int ApplyCrossColorFilter(const VP8LEncoder* const enc, int width,
+ int height, int quality, int low_effort,
+ VP8LBitWriter* const bw, int percent_range,
+ int* const percent) {
const int ccolor_transform_bits = enc->transform_bits_;
const int transform_width = VP8LSubSampleSize(width, ccolor_transform_bits);
const int transform_height = VP8LSubSampleSize(height, ccolor_transform_bits);
- VP8LColorSpaceTransform(width, height, ccolor_transform_bits, quality,
- enc->argb_, enc->transform_data_);
+ if (!VP8LColorSpaceTransform(width, height, ccolor_transform_bits, quality,
+ enc->argb_, enc->transform_data_, enc->pic_,
+ percent_range / 2, percent)) {
+ return 0;
+ }
VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
VP8LPutBits(bw, CROSS_COLOR_TRANSFORM, 2);
assert(ccolor_transform_bits >= 2);
@@ -1348,23 +1406,21 @@ static WebPEncodingError ApplyCrossColorFilter(const VP8LEncoder* const enc,
return EncodeImageNoHuffman(
bw, enc->transform_data_, (VP8LHashChain*)&enc->hash_chain_,
(VP8LBackwardRefs*)&enc->refs_[0], transform_width, transform_height,
- quality, low_effort);
+ quality, low_effort, enc->pic_, percent_range - percent_range / 2,
+ percent);
}
// -----------------------------------------------------------------------------
-static WebPEncodingError WriteRiffHeader(const WebPPicture* const pic,
- size_t riff_size, size_t vp8l_size) {
+static int WriteRiffHeader(const WebPPicture* const pic, size_t riff_size,
+ size_t vp8l_size) {
uint8_t riff[RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8L_SIGNATURE_SIZE] = {
'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P',
'V', 'P', '8', 'L', 0, 0, 0, 0, VP8L_MAGIC_BYTE,
};
PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);
PutLE32(riff + RIFF_HEADER_SIZE + TAG_SIZE, (uint32_t)vp8l_size);
- if (!pic->writer(riff, sizeof(riff), pic)) {
- return VP8_ENC_ERROR_BAD_WRITE;
- }
- return VP8_ENC_OK;
+ return pic->writer(riff, sizeof(riff), pic);
}
static int WriteImageSize(const WebPPicture* const pic,
@@ -1384,36 +1440,29 @@ static int WriteRealAlphaAndVersion(VP8LBitWriter* const bw, int has_alpha) {
return !bw->error_;
}
-static WebPEncodingError WriteImage(const WebPPicture* const pic,
- VP8LBitWriter* const bw,
- size_t* const coded_size) {
- WebPEncodingError err = VP8_ENC_OK;
+static int WriteImage(const WebPPicture* const pic, VP8LBitWriter* const bw,
+ size_t* const coded_size) {
const uint8_t* const webpll_data = VP8LBitWriterFinish(bw);
const size_t webpll_size = VP8LBitWriterNumBytes(bw);
const size_t vp8l_size = VP8L_SIGNATURE_SIZE + webpll_size;
const size_t pad = vp8l_size & 1;
const size_t riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8l_size + pad;
- err = WriteRiffHeader(pic, riff_size, vp8l_size);
- if (err != VP8_ENC_OK) goto Error;
-
- if (!pic->writer(webpll_data, webpll_size, pic)) {
- err = VP8_ENC_ERROR_BAD_WRITE;
- goto Error;
+ if (!WriteRiffHeader(pic, riff_size, vp8l_size) ||
+ !pic->writer(webpll_data, webpll_size, pic)) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_WRITE);
+ return 0;
}
if (pad) {
const uint8_t pad_byte[1] = { 0 };
if (!pic->writer(pad_byte, 1, pic)) {
- err = VP8_ENC_ERROR_BAD_WRITE;
- goto Error;
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_WRITE);
+ return 0;
}
}
*coded_size = CHUNK_HEADER_SIZE + riff_size;
- return VP8_ENC_OK;
-
- Error:
- return err;
+ return 1;
}
// -----------------------------------------------------------------------------
@@ -1429,18 +1478,16 @@ static void ClearTransformBuffer(VP8LEncoder* const enc) {
// Flags influencing the memory allocated:
// enc->transform_bits_
// enc->use_predict_, enc->use_cross_color_
-static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,
- int width, int height) {
- WebPEncodingError err = VP8_ENC_OK;
+static int AllocateTransformBuffer(VP8LEncoder* const enc, int width,
+ int height) {
const uint64_t image_size = width * height;
// VP8LResidualImage needs room for 2 scanlines of uint32 pixels with an extra
// pixel in each, plus 2 regular scanlines of bytes.
// TODO(skal): Clean up by using arithmetic in bytes instead of words.
const uint64_t argb_scratch_size =
- enc->use_predict_
- ? (width + 1) * 2 +
- (width * 2 + sizeof(uint32_t) - 1) / sizeof(uint32_t)
- : 0;
+ enc->use_predict_ ? (width + 1) * 2 + (width * 2 + sizeof(uint32_t) - 1) /
+ sizeof(uint32_t)
+ : 0;
const uint64_t transform_data_size =
(enc->use_predict_ || enc->use_cross_color_)
? VP8LSubSampleSize(width, enc->transform_bits_) *
@@ -1448,17 +1495,16 @@ static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,
: 0;
const uint64_t max_alignment_in_words =
(WEBP_ALIGN_CST + sizeof(uint32_t) - 1) / sizeof(uint32_t);
- const uint64_t mem_size =
- image_size + max_alignment_in_words +
- argb_scratch_size + max_alignment_in_words +
- transform_data_size;
+ const uint64_t mem_size = image_size + max_alignment_in_words +
+ argb_scratch_size + max_alignment_in_words +
+ transform_data_size;
uint32_t* mem = enc->transform_mem_;
if (mem == NULL || mem_size > enc->transform_mem_size_) {
ClearTransformBuffer(enc);
mem = (uint32_t*)WebPSafeMalloc(mem_size, sizeof(*mem));
if (mem == NULL) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
- goto Error;
+ WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
}
enc->transform_mem_ = mem;
enc->transform_mem_size_ = (size_t)mem_size;
@@ -1471,19 +1517,16 @@ static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,
enc->transform_data_ = mem;
enc->current_width_ = width;
- Error:
- return err;
+ return 1;
}
-static WebPEncodingError MakeInputImageCopy(VP8LEncoder* const enc) {
- WebPEncodingError err = VP8_ENC_OK;
+static int MakeInputImageCopy(VP8LEncoder* const enc) {
const WebPPicture* const picture = enc->pic_;
const int width = picture->width;
const int height = picture->height;
- err = AllocateTransformBuffer(enc, width, height);
- if (err != VP8_ENC_OK) return err;
- if (enc->argb_content_ == kEncoderARGB) return VP8_ENC_OK;
+ if (!AllocateTransformBuffer(enc, width, height)) return 0;
+ if (enc->argb_content_ == kEncoderARGB) return 1;
{
uint32_t* dst = enc->argb_;
@@ -1497,7 +1540,7 @@ static WebPEncodingError MakeInputImageCopy(VP8LEncoder* const enc) {
}
enc->argb_content_ = kEncoderARGB;
assert(enc->current_width_ == width);
- return VP8_ENC_OK;
+ return 1;
}
// -----------------------------------------------------------------------------
@@ -1559,16 +1602,19 @@ static WEBP_INLINE uint32_t ApplyPaletteHash2(uint32_t color) {
// using 'row' as a temporary buffer of size 'width'.
// We assume that all src[] values have a corresponding entry in the palette.
// Note: src[] can be the same as dst[]
-static WebPEncodingError ApplyPalette(const uint32_t* src, uint32_t src_stride,
- uint32_t* dst, uint32_t dst_stride,
- const uint32_t* palette, int palette_size,
- int width, int height, int xbits) {
+static int ApplyPalette(const uint32_t* src, uint32_t src_stride, uint32_t* dst,
+ uint32_t dst_stride, const uint32_t* palette,
+ int palette_size, int width, int height, int xbits,
+ const WebPPicture* const pic) {
// TODO(skal): this tmp buffer is not needed if VP8LBundleColorMap() can be
// made to work in-place.
uint8_t* const tmp_row = (uint8_t*)WebPSafeMalloc(width, sizeof(*tmp_row));
int x, y;
- if (tmp_row == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
+ if (tmp_row == NULL) {
+ WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ return 0;
+ }
if (palette_size < APPLY_PALETTE_GREEDY_MAX) {
APPLY_PALETTE_FOR(SearchColorGreedy(palette, palette_size, pix));
@@ -1613,7 +1659,7 @@ static WebPEncodingError ApplyPalette(const uint32_t* src, uint32_t src_stride,
}
}
WebPSafeFree(tmp_row);
- return VP8_ENC_OK;
+ return 1;
}
#undef APPLY_PALETTE_FOR
#undef PALETTE_INV_SIZE_BITS
@@ -1621,9 +1667,7 @@ static WebPEncodingError ApplyPalette(const uint32_t* src, uint32_t src_stride,
#undef APPLY_PALETTE_GREEDY_MAX
// Note: Expects "enc->palette_" to be set properly.
-static WebPEncodingError MapImageFromPalette(VP8LEncoder* const enc,
- int in_place) {
- WebPEncodingError err = VP8_ENC_OK;
+static int MapImageFromPalette(VP8LEncoder* const enc, int in_place) {
const WebPPicture* const pic = enc->pic_;
const int width = pic->width;
const int height = pic->height;
@@ -1641,19 +1685,22 @@ static WebPEncodingError MapImageFromPalette(VP8LEncoder* const enc,
xbits = (palette_size <= 16) ? 1 : 0;
}
- err = AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height);
- if (err != VP8_ENC_OK) return err;
-
- err = ApplyPalette(src, src_stride,
+ if (!AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height)) {
+ return 0;
+ }
+ if (!ApplyPalette(src, src_stride,
enc->argb_, enc->current_width_,
- palette, palette_size, width, height, xbits);
+ palette, palette_size, width, height, xbits, pic)) {
+ return 0;
+ }
enc->argb_content_ = kEncoderPalette;
- return err;
+ return 1;
}
// Save palette_[] to bitstream.
static WebPEncodingError EncodePalette(VP8LBitWriter* const bw, int low_effort,
- VP8LEncoder* const enc) {
+ VP8LEncoder* const enc,
+ int percent_range, int* const percent) {
int i;
uint32_t tmp_palette[MAX_PALETTE_SIZE];
const int palette_size = enc->palette_size_;
@@ -1668,7 +1715,7 @@ static WebPEncodingError EncodePalette(VP8LBitWriter* const bw, int low_effort,
tmp_palette[0] = palette[0];
return EncodeImageNoHuffman(bw, tmp_palette, &enc->hash_chain_,
&enc->refs_[0], palette_size, 1, /*quality=*/20,
- low_effort);
+ low_effort, enc->pic_, percent_range, percent);
}
// -----------------------------------------------------------------------------
@@ -1712,7 +1759,6 @@ typedef struct {
CrunchConfig crunch_configs_[CRUNCH_CONFIGS_MAX];
int num_crunch_configs_;
int red_and_blue_always_zero_;
- WebPEncodingError err_;
WebPAuxStats* stats_;
} StreamEncodeContext;
@@ -1729,7 +1775,6 @@ static int EncodeStreamHook(void* input, void* data2) {
#if !defined(WEBP_DISABLE_STATS)
WebPAuxStats* const stats = params->stats_;
#endif
- WebPEncodingError err = VP8_ENC_OK;
const int quality = (int)config->quality;
const int low_effort = (config->method == 0);
#if (WEBP_NEAR_LOSSLESS == 1)
@@ -1737,6 +1782,7 @@ static int EncodeStreamHook(void* input, void* data2) {
#endif
const int height = picture->height;
const size_t byte_position = VP8LBitWriterNumBytes(bw);
+ int percent = 2; // for WebPProgressHook
#if (WEBP_NEAR_LOSSLESS == 1)
int use_near_lossless = 0;
#endif
@@ -1750,12 +1796,13 @@ static int EncodeStreamHook(void* input, void* data2) {
if (!VP8LBitWriterInit(&bw_best, 0) ||
(num_crunch_configs > 1 && !VP8LBitWriterClone(bw, &bw_best))) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
for (idx = 0; idx < num_crunch_configs; ++idx) {
const int entropy_idx = crunch_configs[idx].entropy_idx_;
+ int remaining_percent = 97 / num_crunch_configs, percent_range;
enc->use_palette_ =
(entropy_idx == kPalette) || (entropy_idx == kPaletteAndSpatial);
enc->use_subtract_green_ =
@@ -1779,11 +1826,10 @@ static int EncodeStreamHook(void* input, void* data2) {
use_near_lossless = (config->near_lossless < 100) && !enc->use_palette_ &&
!enc->use_predict_;
if (use_near_lossless) {
- err = AllocateTransformBuffer(enc, width, height);
- if (err != VP8_ENC_OK) goto Error;
+ if (!AllocateTransformBuffer(enc, width, height)) goto Error;
if ((enc->argb_content_ != kEncoderNearLossless) &&
!VP8ApplyNearLossless(picture, config->near_lossless, enc->argb_)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
enc->argb_content_ = kEncoderNearLossless;
@@ -1805,14 +1851,17 @@ static int EncodeStreamHook(void* input, void* data2) {
enc->palette_);
} else {
assert(crunch_configs[idx].palette_sorting_type_ == kModifiedZeng);
- err = PaletteSortModifiedZeng(enc->pic_, enc->palette_sorted_,
- enc->palette_size_, enc->palette_);
- if (err != VP8_ENC_OK) goto Error;
+ if (!PaletteSortModifiedZeng(enc->pic_, enc->palette_sorted_,
+ enc->palette_size_, enc->palette_)) {
+ goto Error;
+ }
}
- err = EncodePalette(bw, low_effort, enc);
- if (err != VP8_ENC_OK) goto Error;
- err = MapImageFromPalette(enc, use_delta_palette);
- if (err != VP8_ENC_OK) goto Error;
+ percent_range = remaining_percent / 4;
+ if (!EncodePalette(bw, low_effort, enc, percent_range, &percent)) {
+ goto Error;
+ }
+ remaining_percent -= percent_range;
+ if (!MapImageFromPalette(enc, use_delta_palette)) goto Error;
// If using a color cache, do not have it bigger than the number of
// colors.
if (use_cache && enc->palette_size_ < (1 << MAX_COLOR_CACHE_BITS)) {
@@ -1823,8 +1872,7 @@ static int EncodeStreamHook(void* input, void* data2) {
// In case image is not packed.
if (enc->argb_content_ != kEncoderNearLossless &&
enc->argb_content_ != kEncoderPalette) {
- err = MakeInputImageCopy(enc);
- if (err != VP8_ENC_OK) goto Error;
+ if (!MakeInputImageCopy(enc)) goto Error;
}
// -----------------------------------------------------------------------
@@ -1835,15 +1883,22 @@ static int EncodeStreamHook(void* input, void* data2) {
}
if (enc->use_predict_) {
- err = ApplyPredictFilter(enc, enc->current_width_, height, quality,
- low_effort, enc->use_subtract_green_, bw);
- if (err != VP8_ENC_OK) goto Error;
+ percent_range = remaining_percent / 3;
+ if (!ApplyPredictFilter(enc, enc->current_width_, height, quality,
+ low_effort, enc->use_subtract_green_, bw,
+ percent_range, &percent)) {
+ goto Error;
+ }
+ remaining_percent -= percent_range;
}
if (enc->use_cross_color_) {
- err = ApplyCrossColorFilter(enc, enc->current_width_, height, quality,
- low_effort, bw);
- if (err != VP8_ENC_OK) goto Error;
+ percent_range = remaining_percent / 2;
+ if (!ApplyCrossColorFilter(enc, enc->current_width_, height, quality,
+ low_effort, bw, percent_range, &percent)) {
+ goto Error;
+ }
+ remaining_percent -= percent_range;
}
}
@@ -1851,12 +1906,13 @@ static int EncodeStreamHook(void* input, void* data2) {
// -------------------------------------------------------------------------
// Encode and write the transformed image.
- err = EncodeImageInternal(bw, enc->argb_, &enc->hash_chain_, enc->refs_,
- enc->current_width_, height, quality, low_effort,
- use_cache, &crunch_configs[idx],
- &enc->cache_bits_, enc->histo_bits_,
- byte_position, &hdr_size, &data_size);
- if (err != VP8_ENC_OK) goto Error;
+ if (!EncodeImageInternal(
+ bw, enc->argb_, &enc->hash_chain_, enc->refs_, enc->current_width_,
+ height, quality, low_effort, use_cache, &crunch_configs[idx],
+ &enc->cache_bits_, enc->histo_bits_, byte_position, &hdr_size,
+ &data_size, picture, remaining_percent, &percent)) {
+ goto Error;
+ }
// If we are better than what we already have.
if (VP8LBitWriterNumBytes(bw) < best_size) {
@@ -1886,18 +1942,15 @@ static int EncodeStreamHook(void* input, void* data2) {
}
VP8LBitWriterSwap(&bw_best, bw);
-Error:
+ Error:
VP8LBitWriterWipeOut(&bw_best);
- params->err_ = err;
// The hook should return false in case of error.
- return (err == VP8_ENC_OK);
+ return (params->picture_->error_code == VP8_ENC_OK);
}
-WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
- const WebPPicture* const picture,
- VP8LBitWriter* const bw_main,
- int use_cache) {
- WebPEncodingError err = VP8_ENC_OK;
+int VP8LEncodeStream(const WebPConfig* const config,
+ const WebPPicture* const picture,
+ VP8LBitWriter* const bw_main, int use_cache) {
VP8LEncoder* const enc_main = VP8LEncoderNew(config, picture);
VP8LEncoder* enc_side = NULL;
CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX];
@@ -1909,15 +1962,24 @@ WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
// The main thread uses picture->stats, the side thread uses stats_side.
WebPAuxStats stats_side;
VP8LBitWriter bw_side;
+ WebPPicture picture_side;
const WebPWorkerInterface* const worker_interface = WebPGetWorkerInterface();
int ok_main;
+ if (enc_main == NULL || !VP8LBitWriterInit(&bw_side, 0)) {
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
+ VP8LEncoderDelete(enc_main);
+ return 0;
+ }
+
+ // Avoid "garbage value" error from Clang's static analysis tool.
+ WebPPictureInit(&picture_side);
+
// Analyze image (entropy, num_palettes etc)
- if (enc_main == NULL ||
- !EncoderAnalyze(enc_main, crunch_configs, &num_crunch_configs_main,
+ if (!EncoderAnalyze(enc_main, crunch_configs, &num_crunch_configs_main,
&red_and_blue_always_zero) ||
- !EncoderInit(enc_main) || !VP8LBitWriterInit(&bw_side, 0)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ !EncoderInit(enc_main)) {
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
@@ -1946,25 +2008,32 @@ WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
StreamEncodeContext* const param =
(idx == 0) ? &params_main : &params_side;
param->config_ = config;
- param->picture_ = picture;
param->use_cache_ = use_cache;
param->red_and_blue_always_zero_ = red_and_blue_always_zero;
if (idx == 0) {
+ param->picture_ = picture;
param->stats_ = picture->stats;
param->bw_ = bw_main;
param->enc_ = enc_main;
} else {
+ // Create a side picture (error_code is not thread-safe).
+ if (!WebPPictureView(picture, /*left=*/0, /*top=*/0, picture->width,
+ picture->height, &picture_side)) {
+ assert(0);
+ }
+ picture_side.progress_hook = NULL; // Progress hook is not thread-safe.
+ param->picture_ = &picture_side; // No need to free a view afterwards.
param->stats_ = (picture->stats == NULL) ? NULL : &stats_side;
// Create a side bit writer.
if (!VP8LBitWriterClone(bw_main, &bw_side)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
param->bw_ = &bw_side;
// Create a side encoder.
- enc_side = VP8LEncoderNew(config, picture);
+ enc_side = VP8LEncoderNew(config, &picture_side);
if (enc_side == NULL || !EncoderInit(enc_side)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
// Copy the values that were computed for the main encoder.
@@ -1988,7 +2057,7 @@ WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
// Start the second thread if needed.
if (num_crunch_configs_side != 0) {
if (!worker_interface->Reset(&worker_side)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
#if !defined(WEBP_DISABLE_STATS)
@@ -1998,8 +2067,6 @@ WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
memcpy(&stats_side, picture->stats, sizeof(stats_side));
}
#endif
- // This line is only useful to remove a Clang static analyzer warning.
- params_side.err_ = VP8_ENC_OK;
worker_interface->Launch(&worker_side);
}
// Execute the main thread.
@@ -2011,7 +2078,10 @@ WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
const int ok_side = worker_interface->Sync(&worker_side);
worker_interface->End(&worker_side);
if (!ok_main || !ok_side) {
- err = ok_main ? params_side.err_ : params_main.err_;
+ if (picture->error_code == VP8_ENC_OK) {
+ assert(picture_side.error_code != VP8_ENC_OK);
+ WebPEncodingSetError(picture, picture_side.error_code);
+ }
goto Error;
}
if (VP8LBitWriterNumBytes(&bw_side) < VP8LBitWriterNumBytes(bw_main)) {
@@ -2022,18 +2092,13 @@ WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
}
#endif
}
- } else {
- if (!ok_main) {
- err = params_main.err_;
- goto Error;
- }
}
-Error:
+ Error:
VP8LBitWriterWipeOut(&bw_side);
VP8LEncoderDelete(enc_main);
VP8LEncoderDelete(enc_side);
- return err;
+ return (picture->error_code == VP8_ENC_OK);
}
#undef CRUNCH_CONFIGS_MAX
@@ -2046,14 +2111,12 @@ int VP8LEncodeImage(const WebPConfig* const config,
size_t coded_size;
int percent = 0;
int initial_size;
- WebPEncodingError err = VP8_ENC_OK;
VP8LBitWriter bw;
if (picture == NULL) return 0;
if (config == NULL || picture->argb == NULL) {
- err = VP8_ENC_ERROR_NULL_PARAMETER;
- WebPEncodingSetError(picture, err);
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_NULL_PARAMETER);
return 0;
}
@@ -2064,13 +2127,13 @@ int VP8LEncodeImage(const WebPConfig* const config,
initial_size = (config->image_hint == WEBP_HINT_GRAPH) ?
width * height : width * height * 2;
if (!VP8LBitWriterInit(&bw, initial_size)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
if (!WebPReportProgress(picture, 1, &percent)) {
UserAbort:
- err = VP8_ENC_ERROR_USER_ABORT;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_USER_ABORT);
goto Error;
}
// Reset stats (for pure lossless coding)
@@ -2086,28 +2149,26 @@ int VP8LEncodeImage(const WebPConfig* const config,
// Write image size.
if (!WriteImageSize(picture, &bw)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
has_alpha = WebPPictureHasTransparency(picture);
// Write the non-trivial Alpha flag and lossless version.
if (!WriteRealAlphaAndVersion(&bw, has_alpha)) {
- err = VP8_ENC_ERROR_OUT_OF_MEMORY;
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
goto Error;
}
- if (!WebPReportProgress(picture, 5, &percent)) goto UserAbort;
+ if (!WebPReportProgress(picture, 2, &percent)) goto UserAbort;
// Encode main image stream.
- err = VP8LEncodeStream(config, picture, &bw, 1 /*use_cache*/);
- if (err != VP8_ENC_OK) goto Error;
+ if (!VP8LEncodeStream(config, picture, &bw, 1 /*use_cache*/)) goto Error;
- if (!WebPReportProgress(picture, 90, &percent)) goto UserAbort;
+ if (!WebPReportProgress(picture, 99, &percent)) goto UserAbort;
// Finish the RIFF chunk.
- err = WriteImage(picture, &bw, &coded_size);
- if (err != VP8_ENC_OK) goto Error;
+ if (!WriteImage(picture, &bw, &coded_size)) goto Error;
if (!WebPReportProgress(picture, 100, &percent)) goto UserAbort;
@@ -2126,13 +2187,11 @@ int VP8LEncodeImage(const WebPConfig* const config,
}
Error:
- if (bw.error_) err = VP8_ENC_ERROR_OUT_OF_MEMORY;
- VP8LBitWriterWipeOut(&bw);
- if (err != VP8_ENC_OK) {
- WebPEncodingSetError(picture, err);
- return 0;
+ if (bw.error_) {
+ WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
}
- return 1;
+ VP8LBitWriterWipeOut(&bw);
+ return (picture->error_code == VP8_ENC_OK);
}
//------------------------------------------------------------------------------
diff --git a/thirdparty/libwebp/src/enc/vp8li_enc.h b/thirdparty/libwebp/src/enc/vp8li_enc.h
index 00de48946c..3d35e1612d 100644
--- a/thirdparty/libwebp/src/enc/vp8li_enc.h
+++ b/thirdparty/libwebp/src/enc/vp8li_enc.h
@@ -89,9 +89,10 @@ int VP8LEncodeImage(const WebPConfig* const config,
// Encodes the main image stream using the supplied bit writer.
// If 'use_cache' is false, disables the use of color cache.
-WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
- const WebPPicture* const picture,
- VP8LBitWriter* const bw, int use_cache);
+// Returns false in case of error (stored in picture->error_code).
+int VP8LEncodeStream(const WebPConfig* const config,
+ const WebPPicture* const picture, VP8LBitWriter* const bw,
+ int use_cache);
#if (WEBP_NEAR_LOSSLESS == 1)
// in near_lossless.c
@@ -103,13 +104,18 @@ int VP8ApplyNearLossless(const WebPPicture* const picture, int quality,
//------------------------------------------------------------------------------
// Image transforms in predictor.c.
-void VP8LResidualImage(int width, int height, int bits, int low_effort,
- uint32_t* const argb, uint32_t* const argb_scratch,
- uint32_t* const image, int near_lossless, int exact,
- int used_subtract_green);
-
-void VP8LColorSpaceTransform(int width, int height, int bits, int quality,
- uint32_t* const argb, uint32_t* image);
+// pic and percent are for progress.
+// Returns false in case of error (stored in pic->error_code).
+int VP8LResidualImage(int width, int height, int bits, int low_effort,
+ uint32_t* const argb, uint32_t* const argb_scratch,
+ uint32_t* const image, int near_lossless, int exact,
+ int used_subtract_green, const WebPPicture* const pic,
+ int percent_range, int* const percent);
+
+int VP8LColorSpaceTransform(int width, int height, int bits, int quality,
+ uint32_t* const argb, uint32_t* image,
+ const WebPPicture* const pic, int percent_range,
+ int* const percent);
//------------------------------------------------------------------------------
diff --git a/thirdparty/libwebp/src/enc/webp_enc.c b/thirdparty/libwebp/src/enc/webp_enc.c
index ce2db2e94b..9620e05070 100644
--- a/thirdparty/libwebp/src/enc/webp_enc.c
+++ b/thirdparty/libwebp/src/enc/webp_enc.c
@@ -336,9 +336,7 @@ int WebPEncode(const WebPConfig* config, WebPPicture* pic) {
if (!WebPValidateConfig(config)) {
return WebPEncodingSetError(pic, VP8_ENC_ERROR_INVALID_CONFIGURATION);
}
- if (pic->width <= 0 || pic->height <= 0) {
- return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);
- }
+ if (!WebPValidatePicture(pic)) return 0;
if (pic->width > WEBP_MAX_DIMENSION || pic->height > WEBP_MAX_DIMENSION) {
return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);
}
diff --git a/thirdparty/libwebp/src/mux/muxedit.c b/thirdparty/libwebp/src/mux/muxedit.c
index 02c3edecd7..63e71a0aba 100644
--- a/thirdparty/libwebp/src/mux/muxedit.c
+++ b/thirdparty/libwebp/src/mux/muxedit.c
@@ -70,6 +70,7 @@ void WebPMuxDelete(WebPMux* mux) {
err = ChunkAssignData(&chunk, data, copy_data, tag); \
if (err == WEBP_MUX_OK) { \
err = ChunkSetHead(&chunk, (LIST)); \
+ if (err != WEBP_MUX_OK) ChunkRelease(&chunk); \
} \
return err; \
}
diff --git a/thirdparty/libwebp/src/mux/muxi.h b/thirdparty/libwebp/src/mux/muxi.h
index d9bf9b3770..0f4af1784d 100644
--- a/thirdparty/libwebp/src/mux/muxi.h
+++ b/thirdparty/libwebp/src/mux/muxi.h
@@ -29,7 +29,7 @@ extern "C" {
#define MUX_MAJ_VERSION 1
#define MUX_MIN_VERSION 2
-#define MUX_REV_VERSION 2
+#define MUX_REV_VERSION 4
// Chunk object.
typedef struct WebPChunk WebPChunk;
diff --git a/thirdparty/libwebp/src/mux/muxinternal.c b/thirdparty/libwebp/src/mux/muxinternal.c
index b9ee6717d3..75b6b416b9 100644
--- a/thirdparty/libwebp/src/mux/muxinternal.c
+++ b/thirdparty/libwebp/src/mux/muxinternal.c
@@ -155,17 +155,18 @@ WebPMuxError ChunkSetHead(WebPChunk* const chunk,
WebPMuxError ChunkAppend(WebPChunk* const chunk,
WebPChunk*** const chunk_list) {
+ WebPMuxError err;
assert(chunk_list != NULL && *chunk_list != NULL);
if (**chunk_list == NULL) {
- ChunkSetHead(chunk, *chunk_list);
+ err = ChunkSetHead(chunk, *chunk_list);
} else {
WebPChunk* last_chunk = **chunk_list;
while (last_chunk->next_ != NULL) last_chunk = last_chunk->next_;
- ChunkSetHead(chunk, &last_chunk->next_);
- *chunk_list = &last_chunk->next_;
+ err = ChunkSetHead(chunk, &last_chunk->next_);
+ if (err == WEBP_MUX_OK) *chunk_list = &last_chunk->next_;
}
- return WEBP_MUX_OK;
+ return err;
}
//------------------------------------------------------------------------------
diff --git a/thirdparty/libwebp/src/webp/encode.h b/thirdparty/libwebp/src/webp/encode.h
index b4c599df87..56b68e2f10 100644
--- a/thirdparty/libwebp/src/webp/encode.h
+++ b/thirdparty/libwebp/src/webp/encode.h
@@ -441,7 +441,7 @@ WEBP_EXTERN int WebPPictureCrop(WebPPicture* picture,
// the original dimension will be lost). Picture 'dst' need not be initialized
// with WebPPictureInit() if it is different from 'src', since its content will
// be overwritten.
-// Returns false in case of memory allocation error or invalid parameters.
+// Returns false in case of invalid parameters.
WEBP_EXTERN int WebPPictureView(const WebPPicture* src,
int left, int top, int width, int height,
WebPPicture* dst);
@@ -455,7 +455,7 @@ WEBP_EXTERN int WebPPictureIsView(const WebPPicture* picture);
// dimension will be calculated preserving the aspect ratio.
// No gamma correction is applied.
// Returns false in case of error (invalid parameter or insufficient memory).
-WEBP_EXTERN int WebPPictureRescale(WebPPicture* pic, int width, int height);
+WEBP_EXTERN int WebPPictureRescale(WebPPicture* picture, int width, int height);
// Colorspace conversion function to import RGB samples.
// Previous buffer will be free'd, if any.
@@ -526,7 +526,7 @@ WEBP_EXTERN int WebPPictureHasTransparency(const WebPPicture* picture);
// Remove the transparency information (if present) by blending the color with
// the background color 'background_rgb' (specified as 24bit RGB triplet).
// After this call, all alpha values are reset to 0xff.
-WEBP_EXTERN void WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb);
+WEBP_EXTERN void WebPBlendAlpha(WebPPicture* picture, uint32_t background_rgb);
//------------------------------------------------------------------------------
// Main call
diff --git a/thirdparty/spirv-reflect/patches/zero-calloc.patch b/thirdparty/spirv-reflect/patches/zero-calloc.patch
new file mode 100644
index 0000000000..796fe1266a
--- /dev/null
+++ b/thirdparty/spirv-reflect/patches/zero-calloc.patch
@@ -0,0 +1,28 @@
+diff --git a/thirdparty/spirv-reflect/spirv_reflect.c b/thirdparty/spirv-reflect/spirv_reflect.c
+index c174ae1900..11ccbdee3a 100644
+--- a/thirdparty/spirv-reflect/spirv_reflect.c
++++ b/thirdparty/spirv-reflect/spirv_reflect.c
+@@ -3322,12 +3322,18 @@ static SpvReflectResult ParseExecutionModes(
+ }
+ for (size_t entry_point_idx = 0; entry_point_idx < p_module->entry_point_count; ++entry_point_idx) {
+ SpvReflectEntryPoint* p_entry_point = &p_module->entry_points[entry_point_idx];
+- p_entry_point->execution_modes =
+- (SpvExecutionMode*)calloc(p_entry_point->execution_mode_count, sizeof(*p_entry_point->execution_modes));
+- if (IsNull(p_entry_point->execution_modes)) {
+- SafeFree(indices);
+- return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED;
++// -- GODOT begin --
++ if (p_entry_point->execution_mode_count > 0) {
++// -- GODOT end --
++ p_entry_point->execution_modes =
++ (SpvExecutionMode*)calloc(p_entry_point->execution_mode_count, sizeof(*p_entry_point->execution_modes));
++ if (IsNull(p_entry_point->execution_modes)) {
++ SafeFree(indices);
++ return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED;
++ }
++// -- GODOT begin --
+ }
++// -- GODOT end --
+ }
+
+ for (size_t node_idx = 0; node_idx < p_parser->node_count; ++node_idx) {
diff --git a/thirdparty/spirv-reflect/spirv_reflect.c b/thirdparty/spirv-reflect/spirv_reflect.c
index c174ae1900..11ccbdee3a 100644
--- a/thirdparty/spirv-reflect/spirv_reflect.c
+++ b/thirdparty/spirv-reflect/spirv_reflect.c
@@ -3322,12 +3322,18 @@ static SpvReflectResult ParseExecutionModes(
}
for (size_t entry_point_idx = 0; entry_point_idx < p_module->entry_point_count; ++entry_point_idx) {
SpvReflectEntryPoint* p_entry_point = &p_module->entry_points[entry_point_idx];
- p_entry_point->execution_modes =
- (SpvExecutionMode*)calloc(p_entry_point->execution_mode_count, sizeof(*p_entry_point->execution_modes));
- if (IsNull(p_entry_point->execution_modes)) {
- SafeFree(indices);
- return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED;
+// -- GODOT begin --
+ if (p_entry_point->execution_mode_count > 0) {
+// -- GODOT end --
+ p_entry_point->execution_modes =
+ (SpvExecutionMode*)calloc(p_entry_point->execution_mode_count, sizeof(*p_entry_point->execution_modes));
+ if (IsNull(p_entry_point->execution_modes)) {
+ SafeFree(indices);
+ return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED;
+ }
+// -- GODOT begin --
}
+// -- GODOT end --
}
for (size_t node_idx = 0; node_idx < p_parser->node_count; ++node_idx) {