id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
119078
class_name Player extends CharacterBody2D signal coin_collected() const WALK_SPEED = 300.0 const ACCELERATION_SPEED = WALK_SPEED * 6.0 const JUMP_VELOCITY = -725.0 ## Maximum speed at which the player can fall. const TERMINAL_VELOCITY = 700 ## The player listens for input actions appended with this suffix.[br] ## Used to separate controls for multiple players in splitscreen. @export var action_suffix := "" var gravity: int = ProjectSettings.get("physics/2d/default_gravity") @onready var platform_detector := $PlatformDetector as RayCast2D @onready var animation_player := $AnimationPlayer as AnimationPlayer @onready var shoot_timer := $ShootAnimation as Timer @onready var sprite := $Sprite2D as Sprite2D @onready var jump_sound := $Jump as AudioStreamPlayer2D @onready var gun: Gun = sprite.get_node(^"Gun") @onready var camera := $Camera as Camera2D var _double_jump_charged := false func _physics_process(delta: float) -> void: if is_on_floor(): _double_jump_charged = true if Input.is_action_just_pressed("jump" + action_suffix): try_jump() elif Input.is_action_just_released("jump" + action_suffix) and velocity.y < 0.0: # The player let go of jump early, reduce vertical momentum. velocity.y *= 0.6 # Fall. velocity.y = minf(TERMINAL_VELOCITY, velocity.y + gravity * delta) var direction := Input.get_axis("move_left" + action_suffix, "move_right" + action_suffix) * WALK_SPEED velocity.x = move_toward(velocity.x, direction, ACCELERATION_SPEED * delta) if not is_zero_approx(velocity.x): if velocity.x > 0.0: sprite.scale.x = 1.0 else: sprite.scale.x = -1.0 floor_stop_on_slope = not platform_detector.is_colliding() move_and_slide() var is_shooting := false if Input.is_action_just_pressed("shoot" + action_suffix): is_shooting = gun.shoot(sprite.scale.x) var animation := get_new_animation(is_shooting) if animation != animation_player.current_animation and shoot_timer.is_stopped(): if is_shooting: shoot_timer.start() animation_player.play(animation) func get_new_animation(is_shooting := false) -> String: var animation_new: String if is_on_floor(): if absf(velocity.x) > 0.1: animation_new = "run" else: animation_new = "idle" else: if velocity.y > 0.0: animation_new = "falling" else: animation_new = "jumping" if is_shooting: animation_new += "_weapon" return animation_new func try_jump() -> void: if is_on_floor(): jump_sound.pitch_scale = 1.0 elif _double_jump_charged: _double_jump_charged = false velocity.x *= 2.5 jump_sound.pitch_scale = 1.5 else: return velocity.y = JUMP_VELOCITY jump_sound.play()
119087
extends Node var tween: Tween var sub_tween: Tween @onready var icon: Sprite2D = %Icon @onready var icon_start_position := icon.position @onready var countdown_label: Label = %CountdownLabel @onready var path: Path2D = $Path2D @onready var progress: TextureProgressBar = %Progress func _process(_delta: float) -> void: if not tween or not tween.is_running(): return progress.value = tween.get_total_elapsed_time() func start_animation() -> void: # Reset the icon to original state. reset() # Create the Tween. Also sets the initial animation speed. # All methods that modify Tween will return the Tween, so you can chain them. tween = create_tween().set_speed_scale(%SpeedSlider.value) # Sets the amount of loops. 1 loop = 1 animation cycle, so e.g. 2 loops will play animation twice. if %Infinite.button_pressed: tween.set_loops() # Called without arguments, the Tween will loop infinitely. else: tween.set_loops(%Loops.value) # Step 1 if is_step_enabled("MoveTo", 1.0): # tween_*() methods return a Tweener object. Its methods can also be chained, but # it's stored in a variable here for readability (chained lines tend to be long). # Note the usage of ^"NodePath". A regular "String" is accepted too, but it's very slightly slower. var tweener := tween.tween_property(icon, ^"position", Vector2(400, 250), 1.0) tweener.set_ease(%Ease1.selected) tweener.set_trans(%Trans1.selected) # Step 2 if is_step_enabled("ColorRed", 1.0): tween.tween_property(icon, ^"self_modulate", Color.RED, 1.0) # Step 3 if is_step_enabled("MoveRight", 1.0): # as_relative() makes the value relative, so in this case it moves the icon # 200 pixels from the previous position. var tweener := tween.tween_property(icon, ^"position:x", 200.0, 1.0).as_relative() tweener.set_ease(%Ease3.selected) tweener.set_trans(%Trans3.selected) if is_step_enabled("Roll", 0.0): # parallel() makes the Tweener run in parallel to the previous one. var tweener := tween.parallel().tween_property(icon, ^"rotation", TAU, 1.0) tweener.set_ease(%Ease3.selected) tweener.set_trans(%Trans3.selected) # Step 4 if is_step_enabled("MoveLeft", 1.0): tween.tween_property(icon, ^"position", Vector2.LEFT * 200, 1.0).as_relative() if is_step_enabled("Jump", 0.0): # Jump has 2 substeps, so to make it properly parallel, it can be done in a sub-Tween. # Here we are calling a lambda method that creates a sub-Tween. # Any number of Tweens can animate a single object in the same time. tween.parallel().tween_callback(func(): # Note that transition is set on Tween, but ease is set on Tweener. # Values set on Tween will affect all Tweeners (as defaults) and values # on Tweeners can override them. sub_tween = create_tween().set_speed_scale(%SpeedSlider.value).set_trans(Tween.TRANS_SINE) sub_tween.tween_property(icon, ^"position:y", -150.0, 0.5).as_relative().set_ease(Tween.EASE_OUT) sub_tween.tween_property(icon, ^"position:y", 150.0, 0.5).as_relative().set_ease(Tween.EASE_IN) ) # Step 5 if is_step_enabled("Blink", 2.0): # Loops are handy when creating some animations. for i in 10: tween.tween_callback(icon.hide).set_delay(0.1) tween.tween_callback(icon.show).set_delay(0.1) # Step 6 if is_step_enabled("Teleport", 0.5): # Tweening a value with 0 duration makes it change instantly. tween.tween_property(icon, ^"position", Vector2(325, 325), 0) tween.tween_interval(0.5) # Binds can be used for advanced callbacks. tween.tween_callback(icon.set_position.bind(Vector2(680, 215))) # Step 7 if is_step_enabled("Curve", 3.5): # Method tweening is useful for animating values that can't be directly interpolated. # It can be used for remapping and some very advanced animations. # Here it's used for moving sprite along a path, using inline lambda function. var tweener := tween.tween_method( func(v: float) -> void: icon.position = path.position + path.curve.sample_baked(v), 0.0, path.curve.get_baked_length(), 3.0 ).set_delay(0.5) tweener.set_ease(%Ease7.selected) tweener.set_trans(%Trans7.selected) # Step 8 if is_step_enabled("Wait", 2.0): # ... tween.tween_interval(2) # Step 9 if is_step_enabled("Countdown", 3.0): tween.tween_callback(countdown_label.show) tween.tween_method(do_countdown, 4, 1, 3) tween.tween_callback(countdown_label.hide) # Step 10 if is_step_enabled("Enlarge", 0.0): tween.tween_property(icon, ^"scale", Vector2.ONE * 5, 0.5).set_trans(Tween.TRANS_ELASTIC).set_ease(Tween.EASE_OUT) if is_step_enabled("Vanish", 1.0): tween.parallel().tween_property(icon, ^"self_modulate:a", 0.0, 1.0) if %Loops.value > 1 or %Infinite.button_pressed: tween.tween_callback(icon.show) tween.tween_callback(icon.set_self_modulate.bind(Color.WHITE)) # RESET step if %Reset.button_pressed: tween.tween_callback(reset.bind(true)) func do_countdown(number: int) -> void: countdown_label.text = str(number) func reset(soft: bool = false) -> void: icon.position = icon_start_position icon.self_modulate = Color.WHITE icon.rotation = 0 icon.scale = Vector2.ONE icon.show() countdown_label.hide() if soft: # Only reset properties. return if tween: tween.kill() tween = null if sub_tween: sub_tween.kill() sub_tween = null progress.max_value = 0 func is_step_enabled(step: String, expected_time: float) -> bool: var enabled: bool = get_node("%" + step).button_pressed if enabled: progress.max_value += expected_time return enabled func pause_resume() -> void: if tween and tween.is_valid(): if tween.is_running(): tween.pause() else: tween.play() if sub_tween and sub_tween.is_valid(): if sub_tween.is_running(): sub_tween.pause() else: sub_tween.play() func kill_tween() -> void: if tween: tween.kill() if sub_tween: sub_tween.kill() func speed_changed(value: float) -> void: if tween: tween.set_speed_scale(value) if sub_tween: sub_tween.set_speed_scale(value) %SpeedLabel.text = str("x", value) func infinite_toggled(button_pressed: bool) -> void: %Loops.editable = not button_pressed
119106
[node name="Camera2D" type="Camera2D" parent="."] offset = Vector2(265, 247) [node name="Player" parent="." instance=ExtResource("3")] position = Vector2(120, 456) [node name="SecretDetector" type="Area2D" parent="."] position = Vector2(280, 440) [node name="CollisionShape2D" type="CollisionShape2D" parent="SecretDetector"] shape = SubResource("RectangleShape2D_a2gec") [connection signal="body_entered" from="SecretDetector" to="TileMap" method="_on_secret_detector_body_entered"] [connection signal="body_exited" from="SecretDetector" to="TileMap" method="_on_secret_detector_body_exited"]
119111
[gd_scene load_steps=4 format=2] [ext_resource path="res://player/player.gd" type="Script" id=1] [ext_resource path="res://player/player.png" type="Texture2D" id=2] [sub_resource type="RectangleShape2D" id=1] extents = Vector2(7, 7) [node name="Player" type="CharacterBody2D"] script = ExtResource( 1 ) [node name="Sprite2D" type="Sprite2D" parent="."] texture = ExtResource( 2 ) [node name="CollisionShape2D" type="CollisionShape2D" parent="."] position = Vector2(-0.315559, 0.157784) shape = SubResource( 1 )
119113
extends CharacterBody2D const WALK_FORCE = 600 const WALK_MAX_SPEED = 200 const STOP_FORCE = 1300 const JUMP_SPEED = 200 @onready var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity") func _physics_process(delta: float) -> void: # Horizontal movement code. First, get the player's input. var walk := WALK_FORCE * (Input.get_axis(&"move_left", &"move_right")) # Slow down the player if they're not trying to move. if abs(walk) < WALK_FORCE * 0.2: # The velocity, slowed down a bit, and then reassigned. velocity.x = move_toward(velocity.x, 0, STOP_FORCE * delta) else: velocity.x += walk * delta # Clamp to the maximum horizontal movement speed. velocity.x = clamp(velocity.x, -WALK_MAX_SPEED, WALK_MAX_SPEED) # Vertical movement code. Apply gravity. velocity.y += gravity * delta # Move based on the velocity and snap to the ground. # TODO: This information should be set to the CharacterBody properties instead of arguments: snap, Vector2.DOWN, Vector2.UP # TODO: Rename velocity to linear_velocity in the rest of the script. move_and_slide() # Check for jumping. is_on_floor() must be called after movement code. if is_on_floor() and Input.is_action_just_pressed(&"jump"): velocity.y = -JUMP_SPEED
119199
[gd_scene format=3 uid="uid://dv7rxhg55y3t6"] [node name="StaticScene" type="Node2D"] [node name="StaticBodyPolygon" type="StaticBody2D" parent="."] position = Vector2(-7.85718, 399.596) [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="StaticBodyPolygon"] build_mode = 1 polygon = PackedVector2Array(16.3331, -129.432, 154.006, -20.0078, 292.354, 30.3943, 447.054, 33.9161, 584.899, -14.7955, 751.156, -15.5179, 894.098, -65.4518, 1000.73, -209.127, 1037.77, -398.823, 1029.92, 253.327, 6.2309, 261.185, 7.35339, -398.823)
119201
[gd_scene load_steps=2 format=3 uid="uid://cx2q80okt25o1"] [sub_resource type="RectangleShape2D" id="1"] size = Vector2(1600, 100) [node name="StaticSceneFlat" type="Node2D"] [node name="StaticBodyPolygon" type="StaticBody2D" parent="."] position = Vector2(512, 550) [node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBodyPolygon"] shape = SubResource( "1" )
119202
[gd_scene load_steps=2 format=3 uid="uid://gk0nqu0jrwm"] [sub_resource type="RectangleShape2D" id="1"] size = Vector2(40, 40) [node name="StackBox" type="RigidDynamicBody2D"] position = Vector2(-180, -20) [node name="CollisionShape2D" type="CollisionShape2D" parent="."] shape = SubResource( "1" )
119203
extends Test const BOX_SIZE = Vector2(40, 40) const BOX_SPACE = Vector2(50, 50) @export_range(1, 1000) var row_size := 100 @export_range(1, 1000) var column_size := 100 var _objects: Array[Node2D] = [] var _log_physics := false var _log_physics_time := 0 var _log_physics_time_start := 0 func _ready() -> void: await start_timer(1.0).timeout if is_timer_canceled(): return _log_physics_start() _create_objects() await wait_for_physics_ticks(5).wait_done _log_physics_stop() await start_timer(1.0).timeout if is_timer_canceled(): return _log_physics_start() _add_objects() await wait_for_physics_ticks(5).wait_done _log_physics_stop() await start_timer(1.0).timeout if is_timer_canceled(): return _log_physics_start() _move_objects() await wait_for_physics_ticks(5).wait_done _log_physics_stop() await start_timer(1.0).timeout if is_timer_canceled(): return _log_physics_start() _remove_objects() await wait_for_physics_ticks(5).wait_done _log_physics_stop() await start_timer(1.0).timeout if is_timer_canceled(): return Log.print_log("* Done.") func _exit_tree() -> void: for object in _objects: object.free() func _physics_process(delta: float) -> void: super._physics_process(delta) if _log_physics: var time := Time.get_ticks_usec() var time_delta := time - _log_physics_time var time_total := time - _log_physics_time_start _log_physics_time = time Log.print_log(" Physics Tick: %.3f ms (total = %.3f ms)" % [0.001 * time_delta, 0.001 * time_total]) func _log_physics_start() -> void: _log_physics = true _log_physics_time_start = Time.get_ticks_usec() _log_physics_time = _log_physics_time_start func _log_physics_stop() -> void: _log_physics = false func _create_objects() -> void: _objects.clear() Log.print_log("* Creating objects...") var timer := Time.get_ticks_usec() var pos_x := -0.5 * (row_size - 1) * BOX_SPACE.x for row in row_size: var pos_y := -0.5 * (column_size - 1) * BOX_SPACE.y for column in column_size: # Create a new object and shape every time to avoid the overhead of connecting many bodies to the same shape. var box := create_rigidbody_box(BOX_SIZE) box.gravity_scale = 0.0 box.position = Vector2(pos_x, pos_y) _objects.push_back(box) pos_y += BOX_SPACE.y pos_x += BOX_SPACE.x timer = Time.get_ticks_usec() - timer Log.print_log(" Create Time: %.3f ms" % (0.001 * timer)) func _add_objects() -> void: var root_node: Node2D = $Objects Log.print_log("* Adding objects...") var timer := Time.get_ticks_usec() for object in _objects: root_node.add_child(object) timer = Time.get_ticks_usec() - timer Log.print_log(" Add Time: %.3f ms" % (0.001 * timer)) func _move_objects() -> void: Log.print_log("* Moving objects...") var timer := Time.get_ticks_usec() for object in _objects: object.position += BOX_SPACE timer = Time.get_ticks_usec() - timer Log.print_log(" Move Time: %.3f ms" % (0.001 * timer)) func _remove_objects() -> void: var root_node: Node2D = $Objects Log.print_log("* Removing objects...") var timer := Time.get_ticks_usec() # Remove objects in reversed order to avoid the overhead of changing children index in parent. var object_count := _objects.size() for object_index in object_count: root_node.remove_child(_objects[object_count - object_index - 1]) timer = Time.get_ticks_usec() - timer Log.print_log(" Remove Time: %.3f ms" % (0.001 * timer))
119215
[gd_scene load_steps=7 format=3 uid="uid://dwka2imbe5gcs"] [ext_resource type="Texture2D" uid="uid://c5duuyhbmd0m4" path="res://assets/texture/godot-head.png" id="1"] [ext_resource type="Script" path="res://tests/functional/test_raycasting.gd" id="2"] [ext_resource type="PackedScene" uid="uid://blh3twy74kbkv" path="res://tests/test_options.tscn" id="2_q8u1v"] [sub_resource type="RectangleShape2D" id="1"] size = Vector2(80, 120) [sub_resource type="CircleShape2D" id="2"] radius = 60.0 [sub_resource type="CapsuleShape2D" id="3"] radius = 30.0 height = 110.0 [node name="Test" type="Node2D"] script = ExtResource( "2" ) [node name="Options" parent="." instance=ExtResource( "2_q8u1v" )] offset_right = 134.0 offset_bottom = 135.719 theme_override_font_sizes/font_size = 16 [node name="Shapes" type="Node2D" parent="."] z_index = -1 z_as_relative = false [node name="RigidBodyRectangle" type="RigidDynamicBody2D" parent="Shapes"] position = Vector2(114.877, 248.76) freeze = true [node name="CollisionShape2D" type="CollisionShape2D" parent="Shapes/RigidBodyRectangle"] rotation = -1.19206 scale = Vector2(1.2, 1.2) shape = SubResource( "1" ) [node name="RigidBodySphere" type="RigidDynamicBody2D" parent="Shapes"] position = Vector2(314.894, 257.658) freeze = true [node name="CollisionShape2D" type="CollisionShape2D" parent="Shapes/RigidBodySphere"] shape = SubResource( "2" ) [node name="RigidBodyCapsule" type="RigidDynamicBody2D" parent="Shapes"] position = Vector2(465.629, 261.204) freeze = true [node name="CollisionShape2D" type="CollisionShape2D" parent="Shapes/RigidBodyCapsule"] rotation = -0.202458 scale = Vector2(1.2, 1.2) shape = SubResource( "3" ) [node name="RigidBodyConvexPolygon" type="RigidDynamicBody2D" parent="Shapes"] position = Vector2(613.385, 252.771) freeze = true [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="Shapes/RigidBodyConvexPolygon"] polygon = PackedVector2Array(10.7, -54.5, 28.3596, -49.4067, 47.6282, -34.3806, 57.9717, -20.9447, 50.9869, 35.2694, 38.8, 47.5, 15.9852, 54.3613, -14.9507, 54.1845, -36.5, 48.1, -50.4828, 36.33, -58.0115, -20.515, -46.9473, -34.7342, -26.0876, -50.1138, -11.4152, -54.5332) [node name="GodotIcon" type="Sprite2D" parent="Shapes/RigidBodyConvexPolygon"] modulate = Color(1, 1, 1, 0.392157) texture = ExtResource( "1" ) [node name="RigidBodyConcavePolygon" type="RigidDynamicBody2D" parent="Shapes"] position = Vector2(771.159, 252.771) freeze = true [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="Shapes/RigidBodyConcavePolygon"] polygon = PackedVector2Array(-5.93512, -43.2195, 6.44476, -42.9695, 11.127, -54.3941, 26.9528, -49.4309, 26.2037, -36.508, 37.5346, -28.1737, 47.6282, -34.3806, 58.0427, -20.9631, 51.113, -10.2876, 50.9869, 35.2694, 38.8, 47.5, 15.9852, 54.3613, -14.9507, 54.1845, -36.5, 48.1, -50.4828, 36.33, -51.3668, -9.98545, -57.8889, -20.5885, -46.9473, -34.7342, -37.4014, -28.547, -26.0876, -37.0323, -26.9862, -49.15, -11.4152, -54.5332) [node name="GodotIcon" type="Sprite2D" parent="Shapes/RigidBodyConcavePolygon"] modulate = Color(1, 1, 1, 0.392157) texture = ExtResource( "1" ) [node name="RigidBodyConcaveSegments" type="RigidDynamicBody2D" parent="Shapes"] position = Vector2(930.097, 252.771) freeze = true [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="Shapes/RigidBodyConcaveSegments"] build_mode = 1 polygon = PackedVector2Array(-5.93512, -43.2195, 6.44476, -42.9695, 11.127, -54.3941, 26.9528, -49.4309, 26.2037, -36.508, 37.5346, -28.1737, 47.6282, -34.3806, 58.0427, -20.9631, 51.113, -10.2876, 50.9869, 35.2694, 38.8, 47.5, 15.9852, 54.3613, -14.9507, 54.1845, -36.5, 48.1, -50.4828, 36.33, -51.3668, -9.98545, -57.8889, -20.5885, -46.9473, -34.7342, -37.4014, -28.547, -26.0876, -37.0323, -26.9862, -49.15, -11.4152, -54.5332) [node name="GodotIcon" type="Sprite2D" parent="Shapes/RigidBodyConcaveSegments"] modulate = Color(1, 1, 1, 0.392157) texture = ExtResource( "1" )
119220
[gd_scene load_steps=12 format=3 uid="uid://bxx2ftwccdlft"] [ext_resource type="Script" path="res://tests/functional/test_character_pixels.gd" id="1"] [ext_resource type="Script" path="res://utils/rigidbody_controller.gd" id="2"] [ext_resource type="PackedScene" uid="uid://blh3twy74kbkv" path="res://tests/test_options.tscn" id="3"] [ext_resource type="PackedScene" uid="uid://cx2q80okt25o1" path="res://tests/static_scene_flat.tscn" id="4"] [ext_resource type="Script" path="res://utils/characterbody_controller.gd" id="7"] [sub_resource type="RectangleShape2D" id="3"] size = Vector2(6, 9.8) [sub_resource type="RectangleShape2D" id="RectangleShape2D_scs3g"] size = Vector2(6, 4.8) [sub_resource type="SeparationRayShape2D" id="SeparationRayShape2D_vby12"] length = 7.0 [sub_resource type="PhysicsMaterial" id="1"] friction = 0.0 [sub_resource type="RectangleShape2D" id="2"] size = Vector2(6, 10) [sub_resource type="RectangleShape2D" id="6"] size = Vector2(20, 4) [node name="Test" type="Node2D"] script = ExtResource( "1" ) _motion_speed = 30.0 _gravity_force = 2.0 _jump_force = 50.0 _snap_distance = 1.0 [node name="ViewportContainer" type="SubViewportContainer" parent="."] anchor_right = 1.0 anchor_bottom = 1.0 offset_right = 1024.0 offset_bottom = 600.0 size_flags_horizontal = 3 size_flags_vertical = 3 stretch = true __meta__ = { "_edit_use_anchors_": false } [node name="Viewport" type="SubViewport" parent="ViewportContainer"] handle_input_locally = false size = Vector2i(1024, 600) size_2d_override = Vector2i(128, 75) size_2d_override_stretch = true render_target_update_mode = 4 [node name="StaticSceneFlat" parent="ViewportContainer/Viewport" instance=ExtResource( "4" )] position = Vector2(0, -450) [node name="CharacterBody2D" type="CharacterBody2D" parent="ViewportContainer/Viewport"] position = Vector2(30, 40) collision_mask = 2147483649 script = ExtResource( "7" ) [node name="CollisionShape2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/CharacterBody2D"] shape = SubResource( "3" ) [node name="CharacterBodyRay2D" type="CharacterBody2D" parent="ViewportContainer/Viewport"] position = Vector2(30, 40) collision_mask = 2147483649 script = ExtResource( "7" ) [node name="CollisionShape2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/CharacterBodyRay2D"] position = Vector2(0, -2.5) shape = SubResource( "RectangleShape2D_scs3g" ) [node name="CollisionShapeRay2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/CharacterBodyRay2D"] position = Vector2(0, -2) shape = SubResource( "SeparationRayShape2D_vby12" ) [node name="RigidDynamicBody2D" type="RigidDynamicBody2D" parent="ViewportContainer/Viewport"] position = Vector2(30, 40) collision_mask = 2147483649 physics_material_override = SubResource( "1" ) contacts_reported = 4 contact_monitor = true lock_rotation = true script = ExtResource( "2" ) [node name="CollisionShape2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/RigidDynamicBody2D"] shape = SubResource( "2" ) [node name="RigidBodyRay2D" type="RigidDynamicBody2D" parent="ViewportContainer/Viewport"] position = Vector2(30, 40) collision_mask = 2147483649 physics_material_override = SubResource( "1" ) contacts_reported = 4 contact_monitor = true lock_rotation = true script = ExtResource( "2" ) [node name="CollisionShape2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/RigidBodyRay2D"] position = Vector2(0, -2.5) shape = SubResource( "RectangleShape2D_scs3g" ) [node name="CollisionShapeRay2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/RigidBodyRay2D"] position = Vector2(0, -2) shape = SubResource( "SeparationRayShape2D_vby12" ) [node name="Wall1" type="StaticBody2D" parent="ViewportContainer/Viewport"] position = Vector2(20, 40) [node name="CollisionShape2D" type="CollisionShape2D" parent="SubViewportContainer/SubViewport/Wall1"] rotation = 1.5708 shape = SubResource( "6" ) [node name="Wall2" type="StaticBody2D" parent="ViewportContainer/Viewport"] position = Vector2(122, 40) [node name="CollisionShape2D" type="CollisionShape2D" parent="SubViewportContainer/SubViewport/Wall2"] rotation = 1.5708 shape = SubResource( "6" ) [node name="Platform1" type="StaticBody2D" parent="ViewportContainer/Viewport"] position = Vector2(50, 44) [node name="CollisionShape2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/Platform1"] shape = SubResource( "6" ) one_way_collision = true [node name="Platform2" type="StaticBody2D" parent="ViewportContainer/Viewport"] position = Vector2(80, 38) [node name="CollisionShape2D" type="CollisionShape2D" parent="ViewportContainer/Viewport/Platform2"] shape = SubResource( "6" ) [node name="Slope" type="StaticBody2D" parent="ViewportContainer/Viewport"] position = Vector2(85, 36) [node name="CollisionShape2D" type="CollisionPolygon2D" parent="ViewportContainer/Viewport/Slope"] polygon = PackedVector2Array(0, 0, 6, 0, 22, 16, 16, 16) [node name="LabelTestType" type="Label" parent="."] offset_left = 14.0 offset_top = 79.0 offset_right = 145.0 offset_bottom = 93.0 text = "Testing: " __meta__ = { "_edit_use_anchors_": false } [node name="Options" parent="." instance=ExtResource( "3" )] [node name="LabelFloor" type="Label" parent="."] offset_left = 14.0 offset_top = 237.929 offset_right = 145.0 offset_bottom = 251.929 text = "ON FLOOR" __meta__ = { "_edit_use_anchors_": false } [node name="LabelControls" type="Label" parent="."] offset_left = 14.0 offset_top = 263.291 offset_right = 145.0 offset_bottom = 294.291 text = "LEFT/RIGHT - MOVE UP - JUMP" __meta__ = { "_edit_use_anchors_": false }
119224
extends TestCharacter const OPTION_TEST_CASE_ALL = "Test Cases/TEST ALL (0)" const OPTION_TEST_CASE_JUMP_ONE_WAY_RIGID = "Test Cases/Jump through one-way tiles (Rigid Body)" const OPTION_TEST_CASE_JUMP_ONE_WAY_CHARACTER = "Test Cases/Jump through one-way tiles (Character Body)" const OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_RIGID = "Test Cases/Jump through one-way corner (Rigid Body)" const OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_CHARACTER = "Test Cases/Jump through one-way corner (Character Body)" const OPTION_TEST_CASE_FALL_ONE_WAY_CHARACTER = "Test Cases/Fall and pushed on one-way tiles (Character Body)" var _test_jump_one_way := false var _test_jump_one_way_corner := false var _test_fall_one_way := false var _extra_body: PhysicsBody2D = null var _failed_reason := "" func _ready() -> void: super._ready() options.add_menu_item(OPTION_TEST_CASE_ALL) options.add_menu_item(OPTION_TEST_CASE_JUMP_ONE_WAY_RIGID) options.add_menu_item(OPTION_TEST_CASE_JUMP_ONE_WAY_CHARACTER) options.add_menu_item(OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_RIGID) options.add_menu_item(OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_CHARACTER) options.add_menu_item(OPTION_TEST_CASE_FALL_ONE_WAY_CHARACTER) func _input(event: InputEvent) -> void: super._input(event) if event is InputEventKey and not event.pressed: if event.keycode == KEY_0: await _on_option_selected(OPTION_TEST_CASE_ALL) func _on_option_selected(option: String) -> void: match option: OPTION_TEST_CASE_ALL: await _test_all() OPTION_TEST_CASE_JUMP_ONE_WAY_RIGID: await _start_test_case(option) return OPTION_TEST_CASE_JUMP_ONE_WAY_CHARACTER: await _start_test_case(option) return OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_RIGID: await _start_test_case(option) return OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_CHARACTER: await _start_test_case(option) return OPTION_TEST_CASE_FALL_ONE_WAY_CHARACTER: await _start_test_case(option) return super._on_option_selected(option) func _start_test_case(option: String) -> void: Log.print_log("* Starting " + option) match option: OPTION_TEST_CASE_JUMP_ONE_WAY_RIGID: _body_type = BodyType.RIGID_BODY _test_jump_one_way_corner = false await _start_jump_one_way() OPTION_TEST_CASE_JUMP_ONE_WAY_CHARACTER: _body_type = BodyType.CHARACTER_BODY _test_jump_one_way_corner = false await _start_jump_one_way() OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_RIGID: _body_type = BodyType.RIGID_BODY _test_jump_one_way_corner = true await _start_jump_one_way() OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_CHARACTER: _body_type = BodyType.CHARACTER_BODY _test_jump_one_way_corner = true await _start_jump_one_way() OPTION_TEST_CASE_FALL_ONE_WAY_CHARACTER: _body_type = BodyType.CHARACTER_BODY await _start_fall_one_way() _: Log.print_error("Invalid test case.") func _test_all() -> void: Log.print_log("* TESTING ALL...") # RigidBody tests. await _start_test_case(OPTION_TEST_CASE_JUMP_ONE_WAY_RIGID) if is_timer_canceled(): return await _start_test_case(OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_RIGID) if is_timer_canceled(): return # CharacterBody tests. await _start_test_case(OPTION_TEST_CASE_JUMP_ONE_WAY_CHARACTER) if is_timer_canceled(): return await _start_test_case(OPTION_TEST_CASE_JUMP_ONE_WAY_CORNER_CHARACTER) if is_timer_canceled(): return await _start_test_case(OPTION_TEST_CASE_FALL_ONE_WAY_CHARACTER) if is_timer_canceled(): return Log.print_log("* Done.") func _set_result(test_passed: bool) -> void: var result := "" if test_passed: result = "PASSED" else: result = "FAILED" if not test_passed and not _failed_reason.is_empty(): result += _failed_reason else: result += "." Log.print_log("Test %s" % result) func _start_test() -> void: if _extra_body: _body_parent.remove_child(_extra_body) _extra_body.queue_free() _extra_body = null super._start_test() if _test_jump_one_way: _test_jump_one_way = false _moving_body._initial_velocity = Vector2(600, -1000) if _test_jump_one_way_corner: _moving_body.position.x = 147.0 $JumpTargetArea2D.visible = true $JumpTargetArea2D/CollisionShape2D.disabled = false if _test_fall_one_way: _test_fall_one_way = false _moving_body.position.y = 350.0 _moving_body._gravity_force = 100.0 _moving_body._motion_speed = 0.0 _moving_body._jump_force = 0.0 _extra_body = _moving_body.duplicate() _extra_body._gravity_force = 100.0 _extra_body._motion_speed = 0.0 _extra_body._jump_force = 0.0 _extra_body.position -= Vector2(0.0, 200.0) _body_parent.add_child(_extra_body) $FallTargetArea2D.visible = true $FallTargetArea2D/CollisionShape2D.disabled = false func _start_jump_one_way() -> void: _test_jump_one_way = true _start_test() await start_timer(1.5).timeout if is_timer_canceled(): return _finalize_jump_one_way() func _start_fall_one_way() -> void: _test_fall_one_way = true _start_test() await start_timer(1.0).timeout if is_timer_canceled(): return _finalize_fall_one_way() func _finalize_jump_one_way() -> void: var passed := true if not $JumpTargetArea2D.overlaps_body(_moving_body): passed = false _failed_reason = ": the body wasn't able to jump all the way through." _set_result(passed) $JumpTargetArea2D.visible = false $JumpTargetArea2D/CollisionShape2D.disabled = true func _finalize_fall_one_way() -> void: var passed := true if $FallTargetArea2D.overlaps_body(_moving_body): passed = false _failed_reason = ": the body was pushed through the one-way collision." _set_result(passed) $FallTargetArea2D.visible = false $FallTargetArea2D/CollisionShape2D.disabled = true
119227
extends TestCharacter const OPTION_TEST_CASE_ALL = "Test Cases/TEST ALL (0)" const OPTION_TEST_CASE_DETECT_FLOOR_NO_SNAP = "Test Cases/Floor detection (Character Body)" const OPTION_TEST_CASE_DETECT_FLOOR_MOTION_CHANGES = "Test Cases/Floor detection with motion changes (Character Body)" const MOTION_CHANGES_DIR = Vector2(1.0, 1.0) const MOTION_CHANGES_SPEEDS: Array[float] = [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0] var _test_floor_detection := false var _test_motion_changes := false var _floor_detected := false var _floor_lost := false var _failed_reason := "" func _ready() -> void: super._ready() options.add_menu_item(OPTION_TEST_CASE_ALL) options.add_menu_item(OPTION_TEST_CASE_DETECT_FLOOR_NO_SNAP) options.add_menu_item(OPTION_TEST_CASE_DETECT_FLOOR_MOTION_CHANGES) func _physics_process(delta: float) -> void: super._physics_process(delta) if _moving_body: if _moving_body.is_on_floor(): _floor_detected = true elif _floor_detected: _floor_lost = true if _test_motion_changes: Log.print_log("Floor lost.") if _test_motion_changes: var speed_count := MOTION_CHANGES_SPEEDS.size() var speed_index := randi() % speed_count var speed := MOTION_CHANGES_SPEEDS[speed_index] var velocity := speed * MOTION_CHANGES_DIR _moving_body._constant_velocity = velocity #Log.print_log("Velocity: %s" % velocity) func _input(event: InputEvent) -> void: super._input(event) if event is InputEventKey and not event.pressed: if event.keycode == KEY_0: await _on_option_selected(OPTION_TEST_CASE_ALL) func _on_option_selected(option: String) -> void: match option: OPTION_TEST_CASE_ALL: await _test_all() OPTION_TEST_CASE_DETECT_FLOOR_NO_SNAP: await _start_test_case(option) return OPTION_TEST_CASE_DETECT_FLOOR_MOTION_CHANGES: await _start_test_case(option) return super._on_option_selected(option) func _start_test_case(option: String) -> void: Log.print_log("* Starting " + option) match option: OPTION_TEST_CASE_DETECT_FLOOR_NO_SNAP: _test_floor_detection = true _test_motion_changes = false _use_snap = false _body_type = BodyType.CHARACTER_BODY _start_test() await start_timer(1.0).timeout if is_timer_canceled(): return _set_result(not _floor_lost) OPTION_TEST_CASE_DETECT_FLOOR_MOTION_CHANGES: _test_floor_detection = true _test_motion_changes = true _use_snap = false _body_type = BodyType.CHARACTER_BODY _start_test() await start_timer(4.0).timeout if is_timer_canceled(): _test_motion_changes = false return _test_motion_changes = false _moving_body._constant_velocity = Vector2.ZERO _set_result(not _floor_lost) _: Log.print_error("Invalid test case.") func _test_all() -> void: Log.print_log("* TESTING ALL...") # Test floor detection with no snapping. await _start_test_case(OPTION_TEST_CASE_DETECT_FLOOR_NO_SNAP) if is_timer_canceled(): return # Test floor detection with no snapping. # In this test case, motion alternates different speeds. await _start_test_case(OPTION_TEST_CASE_DETECT_FLOOR_MOTION_CHANGES) if is_timer_canceled(): return Log.print_log("* Done.") func _set_result(test_passed: bool) -> void: var result := "" if test_passed: result = "PASSED" else: result = "FAILED" if not test_passed and not _failed_reason.is_empty(): result += _failed_reason else: result += "." Log.print_log("Test %s" % result) func _start_test() -> void: super._start_test() _failed_reason = "" _floor_detected = false _floor_lost = false if _test_floor_detection: _failed_reason = ": floor was not detected consistently." if _test_motion_changes: # Always use the same seed for reproducible results. seed(123456789) _moving_body._gravity_force = 0.0 _moving_body._motion_speed = 0.0 _moving_body._jump_force = 0.0 else: _moving_body._initial_velocity = Vector2(30, 0) _test_floor_detection = false else: _test_motion_changes = false
119229
[gd_scene load_steps=15 format=3 uid="uid://bqmku5ewlo6j5"] [ext_resource type="Script" path="res://tests/functional/test_character.gd" id="1"] [ext_resource type="PackedScene" uid="uid://blh3twy74kbkv" path="res://tests/test_options.tscn" id="3"] [ext_resource type="Script" path="res://utils/slider.gd" id="3_cd5g0"] [ext_resource type="PackedScene" uid="uid://cx2q80okt25o1" path="res://tests/static_scene_flat.tscn" id="4"] [ext_resource type="Script" path="res://utils/label_slider_value.gd" id="4_eoplu"] [ext_resource type="Script" path="res://utils/rigidbody_controller.gd" id="6"] [ext_resource type="Script" path="res://utils/characterbody_controller.gd" id="7"] [sub_resource type="CapsuleShape2D" id="3"] radius = 15.0 height = 96.0 [sub_resource type="CircleShape2D" id="CircleShape2D_llvur"] radius = 32.0 [sub_resource type="SeparationRayShape2D" id="RayShape2D_3lv1w"] length = 64.0 [sub_resource type="PhysicsMaterial" id="1"] friction = 0.0 [sub_resource type="CapsuleShape2D" id="2"] radius = 15.0 height = 96.0 [sub_resource type="CircleShape2D" id="CircleShape2D_dr08f"] radius = 32.0 [sub_resource type="SeparationRayShape2D" id="RayShape2D_w83f0"] length = 64.0 [node name="Test" type="Node2D"] script = ExtResource("1") _snap_distance = 32.0 _floor_max_angle = 60.0 [node name="LabelTestType" type="Label" parent="."] offset_left = 14.0 offset_top = 79.0 offset_right = 145.0 offset_bottom = 93.0 text = "Testing: " [node name="Options" parent="." instance=ExtResource("3")] [node name="LabelFloor" type="Label" parent="."] offset_left = 14.0 offset_top = 237.929 offset_right = 145.0 offset_bottom = 251.929 text = "ON FLOOR" [node name="LabelControls" type="Label" parent="."] offset_left = 14.0 offset_top = 263.291 offset_right = 145.0 offset_bottom = 294.291 text = "LEFT/RIGHT - MOVE UP - JUMP" [node name="FloorMaxAngle" type="HBoxContainer" parent="."] offset_left = 14.0 offset_top = 160.0 offset_right = 476.0 offset_bottom = 186.0 theme_override_constants/separation = 20 alignment = 2 [node name="Label" type="Label" parent="FloorMaxAngle"] layout_mode = 2 offset_right = 123.0 offset_bottom = 26.0 text = "Floor Max angle" [node name="HSlider" type="HSlider" parent="FloorMaxAngle"] layout_mode = 2 offset_left = 143.0 offset_right = 419.0 offset_bottom = 16.0 size_flags_horizontal = 3 max_value = 180.0 script = ExtResource("3_cd5g0") snap_step = 5.0 [node name="LabelValue" type="Label" parent="FloorMaxAngle"] layout_mode = 2 offset_left = 439.0 offset_right = 462.0 offset_bottom = 26.0 text = "0.0" script = ExtResource("4_eoplu") [node name="CharacterBody2D" type="CharacterBody2D" parent="."] position = Vector2(100, 450) collision_mask = 2147483649 script = ExtResource("7") [node name="CollisionShape2D" type="CollisionShape2D" parent="CharacterBody2D"] shape = SubResource("3") [node name="CharacterBodyRay2D" type="CharacterBody2D" parent="."] position = Vector2(100, 450) collision_mask = 2147483649 script = ExtResource("7") [node name="CollisionShape2D" type="CollisionShape2D" parent="CharacterBodyRay2D"] position = Vector2(0, -16) shape = SubResource("CircleShape2D_llvur") [node name="CollisionShapeRay2D" type="CollisionShape2D" parent="CharacterBodyRay2D"] position = Vector2(0, -16) shape = SubResource("RayShape2D_3lv1w") [node name="RigidDynamicBody2D" type="RigidBody2D" parent="."] position = Vector2(100, 450) collision_mask = 2147483649 physics_material_override = SubResource("1") contact_monitor = true lock_rotation = true script = ExtResource("6") [node name="CollisionShape2D" type="CollisionShape2D" parent="RigidDynamicBody2D"] shape = SubResource("2") [node name="RigidBodyRay2D" type="RigidBody2D" parent="."] position = Vector2(100, 450) collision_mask = 2147483649 physics_material_override = SubResource("1") contact_monitor = true lock_rotation = true script = ExtResource("6") [node name="CollisionShape2D" type="CollisionShape2D" parent="RigidBodyRay2D"] position = Vector2(-7.62939e-06, -16) shape = SubResource("CircleShape2D_dr08f") [node name="CollisionShapeRay2D" type="CollisionShape2D" parent="RigidBodyRay2D"] position = Vector2(-7.62939e-06, -16) shape = SubResource("RayShape2D_w83f0") [node name="StaticSceneFlat" parent="." instance=ExtResource("4")] position = Vector2(0, 12) [node name="StaticBody2D" type="StaticBody2D" parent="."] [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="StaticBody2D"] polygon = PackedVector2Array(171.04, 529.248, 379.275, 294.316, 506.084, 429.135, 648.26, 322.058, 868.746, 322.058, 985.282, 36.6919, 1242.91, 531.917) [connection signal="value_changed" from="FloorMaxAngle/HSlider" to="." method="_update_floor_max_angle"]
119241
extends RigidBody2D var _initial_velocity := Vector2.ZERO var _constant_velocity := Vector2.ZERO var _motion_speed := 400.0 var _gravity_force := 50.0 var _jump_force := 1000.0 var _velocity := Vector2.ZERO var _floor_max_angle := 45.0 var _on_floor := false var _jumping := false var _keep_velocity := false func _ready() -> void: gravity_scale = 0.0 func _physics_process(_delta: float) -> void: if _initial_velocity != Vector2.ZERO: _velocity = _initial_velocity _initial_velocity = Vector2.ZERO _keep_velocity = true elif _constant_velocity != Vector2.ZERO: _velocity = _constant_velocity elif not _keep_velocity: _velocity.x = 0.0 # Handle horizontal controls. if Input.is_action_pressed(&"character_left"): if position.x > 0.0: _velocity.x = -_motion_speed _keep_velocity = false _constant_velocity = Vector2.ZERO elif Input.is_action_pressed(&"character_right"): if position.x < 1024.0: _velocity.x = _motion_speed _keep_velocity = false _constant_velocity = Vector2.ZERO # Handle jump controls and gravity. if is_on_floor(): if not _jumping and Input.is_action_just_pressed(&"character_jump"): # Start jumping. _jumping = true _velocity.y = -_jump_force elif not _jumping: # Reset gravity. _velocity.y = 0.0 else: _velocity.y += _gravity_force _jumping = false linear_velocity = _velocity func _integrate_forces(state: PhysicsDirectBodyState2D) -> void: _on_floor = false var contacts := state.get_contact_count() for i in contacts: var normal := state.get_contact_local_normal(i) # Detect floor. if acos(normal.dot(Vector2.UP)) <= deg_to_rad(_floor_max_angle) + 0.01: _on_floor = true # Detect ceiling. if acos(normal.dot(-Vector2.UP)) <= deg_to_rad(_floor_max_angle) + 0.01: _jumping = false _velocity.y = 0.0 func is_on_floor() -> bool: return _on_floor
119242
extends Node enum PhysicsEngine { GODOT_PHYSICS, OTHER, } var _engine: PhysicsEngine = PhysicsEngine.OTHER func _enter_tree() -> void: process_mode = Node.PROCESS_MODE_ALWAYS # Always enable visible collision shapes on startup # (same as the Debug > Visible Collision Shapes option). get_tree().debug_collisions_hint = true var engine_string:= String(ProjectSettings.get_setting("physics/2d/physics_engine")) match engine_string: "DEFAULT": _engine = PhysicsEngine.GODOT_PHYSICS "GodotPhysics2D": _engine = PhysicsEngine.GODOT_PHYSICS _: _engine = PhysicsEngine.OTHER func _process(_delta: float) -> void: if Input.is_action_just_pressed(&"toggle_full_screen"): if DisplayServer.window_get_mode() == DisplayServer.WINDOW_MODE_FULLSCREEN: DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED) else: DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN) if Input.is_action_just_pressed(&"toggle_debug_collision"): var debug_collision_enabled := not _is_debug_collision_enabled() _set_debug_collision_enabled(debug_collision_enabled) if debug_collision_enabled: Log.print_log("Debug Collision ON") else: Log.print_log("Debug Collision OFF") if Input.is_action_just_pressed(&"toggle_pause"): get_tree().paused = not get_tree().paused if Input.is_action_just_pressed(&"exit"): get_tree().quit() func get_physics_engine() -> PhysicsEngine: return _engine func _set_debug_collision_enabled(enabled: bool) -> void: get_tree().debug_collisions_hint = enabled func _is_debug_collision_enabled() -> bool: return get_tree().debug_collisions_hint
119299
class_name Player extends CharacterBody2D # Keep this in sync with the AnimationTree's state names. const States = { IDLE = "idle", WALK = "walk", RUN = "run", FLY = "fly", FALL = "fall", } const WALK_SPEED = 200.0 const ACCELERATION_SPEED = WALK_SPEED * 6.0 const JUMP_VELOCITY = -400.0 ## Maximum speed at which the player can fall. const TERMINAL_VELOCITY = 400 var falling_slow := false var falling_fast := false var no_move_horizontal_time := 0.0 @onready var gravity := float(ProjectSettings.get_setting("physics/2d/default_gravity")) @onready var sprite: Node2D = $Sprite2D @onready var sprite_scale := sprite.scale.x func _ready() -> void: $AnimationTree.active = true func _physics_process(delta: float) -> void: var is_jumping := false if Input.is_action_just_pressed("jump"): is_jumping = try_jump() elif Input.is_action_just_released("jump") and velocity.y < 0.0: # The player let go of jump early, reduce vertical momentum. velocity.y *= 0.6 # Fall. velocity.y = minf(TERMINAL_VELOCITY, velocity.y + gravity * delta) var direction := Input.get_axis("move_left", "move_right") * WALK_SPEED velocity.x = move_toward(velocity.x, direction, ACCELERATION_SPEED * delta) if no_move_horizontal_time > 0.0: # After doing a hard fall, don't move for a short time. velocity.x = 0.0 no_move_horizontal_time -= delta if not is_zero_approx(velocity.x): if velocity.x > 0.0: sprite.scale.x = 1.0 * sprite_scale else: sprite.scale.x = -1.0 * sprite_scale move_and_slide() # After applying our motion, update our animation to match. # Calculate falling speed for animation purposes. if velocity.y >= TERMINAL_VELOCITY: falling_fast = true falling_slow = false elif velocity.y > 300: falling_slow = true if is_jumping: $AnimationTree["parameters/jump/request"] = AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE if is_on_floor(): # Most animations change when we run, land, or take off. if falling_fast: $AnimationTree["parameters/land_hard/request"] = AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE no_move_horizontal_time = 0.4 elif falling_slow: $AnimationTree["parameters/land/request"] = AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE if abs(velocity.x) > 50: $AnimationTree["parameters/state/transition_request"] = States.RUN $AnimationTree["parameters/run_timescale/scale"] = abs(velocity.x) / 60 elif velocity.x: $AnimationTree["parameters/state/transition_request"] = States.WALK $AnimationTree["parameters/walk_timescale/scale"] = abs(velocity.x) / 12 else: $AnimationTree["parameters/state/transition_request"] = States.IDLE falling_fast = false falling_slow = false else: if velocity.y > 0: $AnimationTree["parameters/state/transition_request"] = States.FALL else: $AnimationTree["parameters/state/transition_request"] = States.FLY func try_jump() -> bool: if is_on_floor(): velocity.y = JUMP_VELOCITY return true return false
119328
[gd_resource type="ShaderMaterial" load_steps=2 format=3 uid="uid://blst65bnoqyam"] [sub_resource type="Shader" id="1"] code = "// original wind shader from https://github.com/Maujoe/godot-simple-wind-shader-2d/tree/master/assets/maujoe.simple_wind_shader_2d // original script modified by HungryProton so that the assets are moving differently : https://pastebin.com/VL3AfV8D // // speed - The speed of the wind movement. // minStrength - The minimal strength of the wind movement. // maxStrength - The maximal strength of the wind movement. // strengthScale - Scalefactor for the wind strength. // interval - The time between minimal and maximal strength changes. // detail - The detail (number of waves) of the wind movement. // distortion - The strength of geometry distortion. // heightOffset - The height where the wind begins to move. By default 0.0. shader_type canvas_item; render_mode blend_mix; // Wind settings. uniform float speed = 1.0; uniform float minStrength : hint_range(0.0, 1.0) = 0.05; uniform float maxStrength : hint_range(0.0, 1.0) = 0.01; uniform float strengthScale = 100.0; uniform float interval = 3.5; uniform float detail = 1.0; uniform float distortion : hint_range(0.0, 1.0); uniform float heightOffset : hint_range(0.0, 1.0); // With the offset value, you can if you want different moves for each asset. Just put a random value (1, 2, 3) in the editor. Don't forget to mark the material as unique if you use this uniform float offset = 0; float getWind(vec2 vertex, vec2 uv, float time){ float diff = pow(maxStrength - minStrength, 2.0); float strength = clamp(minStrength + diff + sin(time / interval) * diff, minStrength, maxStrength) * strengthScale; float wind = (sin(time) + cos(time * detail)) * strength * max(0.0, (1.0-uv.y) - heightOffset); return wind; } void vertex() { vec4 pos = MODEL_MATRIX * vec4(0.0, 0.0, 0.0, 1.0); float time = TIME * speed + offset; //float time = TIME * speed + pos.x * pos.y ; not working when moving... VERTEX.x += getWind(VERTEX.xy, UV, time); }" [resource] shader = SubResource("1") shader_parameter/speed = 1.0 shader_parameter/minStrength = 0.05 shader_parameter/maxStrength = 0.01 shader_parameter/strengthScale = 100.0 shader_parameter/interval = 3.5 shader_parameter/detail = 1.0 shader_parameter/distortion = null shader_parameter/heightOffset = null shader_parameter/offset = 0.0
119362
extends Control var dialogue_node: Node = null func _ready() -> void: visible = false func show_dialogue(player: Pawn, dialogue: Node) -> void: visible = true $Button.grab_focus() dialogue_node = dialogue for c in dialogue.get_signal_connection_list("dialogue_started"): if player == c.callable.get_object(): dialogue_node.start_dialogue() $Name.text = "[center]" + dialogue_node.dialogue_name + "[/center]" $Text.text = dialogue_node.dialogue_text return dialogue_node.dialogue_started.connect(player.set_active.bind(false)) dialogue_node.dialogue_finished.connect(player.set_active.bind(true)) dialogue_node.dialogue_finished.connect(hide) dialogue_node.dialogue_finished.connect(_on_dialogue_finished.bind(player)) dialogue_node.start_dialogue() $Name.text = "[center]" + dialogue_node.dialogue_name + "[/center]" $Text.text = dialogue_node.dialogue_text func _on_Button_button_up() -> void: dialogue_node.next_dialogue() $Name.text = "[center]" + dialogue_node.dialogue_name + "[/center]" $Text.text = dialogue_node.dialogue_text func _on_dialogue_finished(player: Pawn) -> void: dialogue_node.dialogue_started.disconnect(player.set_active) dialogue_node.dialogue_finished.disconnect(player.set_active) dialogue_node.dialogue_finished.disconnect(hide) dialogue_node.dialogue_finished.disconnect(_on_dialogue_finished)
119437
extends CharacterBody2D var movement_speed := 200.0 @onready var navigation_agent: NavigationAgent2D = $NavigationAgent2D func _ready() -> void: # These values need to be adjusted for the actor's speed # and the navigation layout. navigation_agent.path_desired_distance = 2.0 navigation_agent.target_desired_distance = 2.0 navigation_agent.debug_enabled = true # The "click" event is a custom input action defined in # Project > Project Settings > Input Map tab. func _unhandled_input(event: InputEvent) -> void: if not event.is_action_pressed("click"): return set_movement_target(get_global_mouse_position()) func set_movement_target(movement_target: Vector2) -> void: navigation_agent.target_position = movement_target func _physics_process(_delta: float) -> void: if navigation_agent.is_navigation_finished(): return var current_agent_position: Vector2 = global_position var next_path_position: Vector2 = navigation_agent.get_next_path_position() velocity = current_agent_position.direction_to(next_path_position) * movement_speed move_and_slide()
119522
[gd_scene load_steps=12 format=3 uid="uid://jlfslyfbhid5"] [ext_resource type="Script" path="res://logic/paddle.gd" id="1"] [ext_resource type="Texture2D" uid="uid://dvrb8efddt0aa" path="res://paddle.png" id="2"] [ext_resource type="Script" path="res://logic/ball.gd" id="4"] [ext_resource type="Texture2D" uid="uid://clowikjgl4yq1" path="res://ball.png" id="5"] [ext_resource type="Texture2D" uid="uid://drgpdyyomyqpl" path="res://separator.png" id="6"] [ext_resource type="Script" path="res://logic/wall.gd" id="7"] [ext_resource type="Script" path="res://logic/ceiling_floor.gd" id="8"] [sub_resource type="RectangleShape2D" id="1"] size = Vector2(8, 32) [sub_resource type="RectangleShape2D" id="2"] size = Vector2(8, 8) [sub_resource type="RectangleShape2D" id="3"] size = Vector2(20, 400) [sub_resource type="RectangleShape2D" id="4"] size = Vector2(640, 20) [node name="Pong" type="Node2D"] [node name="Background" type="ColorRect" parent="."] offset_right = 640.0 offset_bottom = 400.0 color = Color(0.141176, 0.152941, 0.164706, 1) [node name="Left" type="Area2D" parent="."] modulate = Color(0, 1, 1, 1) position = Vector2(67.6285, 192.594) script = ExtResource("1") [node name="Sprite2D" type="Sprite2D" parent="Left"] texture = ExtResource("2") [node name="Collision" type="CollisionShape2D" parent="Left"] shape = SubResource("1") [node name="Right" type="Area2D" parent="."] modulate = Color(1, 0, 1, 1) position = Vector2(563.815, 188.919) script = ExtResource("1") [node name="Sprite2D" type="Sprite2D" parent="Right"] texture = ExtResource("2") [node name="Collision" type="CollisionShape2D" parent="Right"] shape = SubResource("1") [node name="Ball" type="Area2D" parent="."] position = Vector2(320.5, 191.124) script = ExtResource("4") [node name="Sprite2D" type="Sprite2D" parent="Ball"] texture = ExtResource("5") [node name="Collision" type="CollisionShape2D" parent="Ball"] shape = SubResource("2") [node name="Separator" type="Sprite2D" parent="."] position = Vector2(320, 200) texture = ExtResource("6") [node name="LeftWall" type="Area2D" parent="."] position = Vector2(-10, 200) script = ExtResource("7") [node name="Collision" type="CollisionShape2D" parent="LeftWall"] shape = SubResource("3") [node name="RightWall" type="Area2D" parent="."] position = Vector2(650, 200) script = ExtResource("7") [node name="Collision" type="CollisionShape2D" parent="RightWall"] shape = SubResource("3") [node name="Ceiling" type="Area2D" parent="."] position = Vector2(320, -10) script = ExtResource("8") [node name="Collision" type="CollisionShape2D" parent="Ceiling"] shape = SubResource("4") [node name="Floor" type="Area2D" parent="."] position = Vector2(320, 410) script = ExtResource("8") _bounce_direction = -1 [node name="Collision" type="CollisionShape2D" parent="Floor"] shape = SubResource("4") [node name="Camera2D" type="Camera2D" parent="."] offset = Vector2(320, 200) [connection signal="area_entered" from="Left" to="Left" method="_on_area_entered"] [connection signal="area_entered" from="Right" to="Right" method="_on_area_entered"] [connection signal="area_entered" from="LeftWall" to="LeftWall" method="_on_wall_area_entered"] [connection signal="area_entered" from="RightWall" to="RightWall" method="_on_wall_area_entered"] [connection signal="area_entered" from="Ceiling" to="Ceiling" method="_on_area_entered"] [connection signal="area_entered" from="Floor" to="Floor" method="_on_area_entered"]
119534
[gd_scene format=3 uid="uid://bywptem1jb35a"] [node name="Explanations" type="RichTextLabel"] anchors_preset = 15 anchor_right = 1.0 anchor_bottom = 1.0 offset_left = 10.0 offset_top = -370.0 offset_right = -10.0 offset_bottom = -730.0 size_flags_vertical = 4 mouse_filter = 2 bbcode_enabled = true text = "This example shows how to apply the State programming pattern in GDscript, including Hierarchical States, and a pushdown automaton. States are common in games. You can use the pattern to: 1. Separate each behavior and transitions between behaviors, thus make scripts shorter and easier to manage 2. Respect the Single Responsibility Principle. Each State object represents one action 3. Improve your code's structure. Look at the scene tree and FileSystem tab: without looking at the code, you'll know what the Player can or cannot do. You can read more about States in the excellent Game Programming Patterns ebook."
119550
extends Node2D var bullet := preload("Bullet.tscn") func _unhandled_input(event: InputEvent) -> void: if event.is_action_pressed("fire"): fire() func fire() -> void: if not $CooldownTimer.is_stopped(): return $CooldownTimer.start() var new_bullet := bullet.instantiate() add_child(new_bullet) new_bullet.position = global_position new_bullet.direction = owner.look_direction
119559
extends Label var start_position := Vector2() func _ready() -> void: start_position = position func _physics_process(_delta: float) -> void: position = $"../BodyPivot".position + start_position func _on_StateMachine_state_changed(current_state: Node) -> void: text = String(current_state.name)
119590
shader_type canvas_item; uniform sampler2D screen_texture : hint_screen_texture, filter_linear_mipmap; uniform float amount: hint_range(0.0, 5.0); void fragment() { COLOR.rgb = textureLod(screen_texture, SCREEN_UV, amount).rgb; }
119603
[node name="MovingPlatform1" type="CharacterBody2D" parent="."] position = Vector2(268.651, 152) [node name="Collision" type="CollisionShape2D" parent="MovingPlatform1"] shape = SubResource("3") [node name="Sprite2D" type="Sprite2D" parent="MovingPlatform1"] modulate = Color(0.4, 2, 0.8, 1) texture = ExtResource("2") [node name="AnimationPlayer" type="AnimationPlayer" parent="MovingPlatform1"] callback_mode_process = 0 libraries = { "": SubResource("AnimationLibrary_2v3oa") } autoplay = "leftright" [node name="MovingPlatform2" type="CharacterBody2D" parent="."] position = Vector2(88.3493, 152) [node name="Collision" type="CollisionShape2D" parent="MovingPlatform2"] shape = SubResource("3") [node name="Sprite2D" type="Sprite2D" parent="MovingPlatform2"] modulate = Color(0.4, 2, 0.8, 1) texture = ExtResource("2") [node name="AnimationPlayer" type="AnimationPlayer" parent="MovingPlatform2"] callback_mode_process = 0 libraries = { "": SubResource("AnimationLibrary_j555p") } autoplay = "updown" [node name="Princess" type="Area2D" parent="."] position = Vector2(97, 72) script = ExtResource("7") [node name="Collision" type="CollisionShape2D" parent="Princess"] shape = SubResource("7") [node name="Sprite2D" type="Sprite2D" parent="Princess"] texture = ExtResource("4") [node name="WinText" type="Label" parent="."] visible = false offset_left = 114.0 offset_top = 30.0 offset_right = 299.0 offset_bottom = 82.0 size_flags_horizontal = 2 size_flags_vertical = 0 text = "Thank You Cubio! You Saved The Princess!" [node name="OneWay1" type="CharacterBody2D" parent="."] position = Vector2(440, 308) [node name="Sprite2D" type="Sprite2D" parent="OneWay1"] scale = Vector2(1, 0.3) texture = ExtResource("2") [node name="CollisionShape2D" type="CollisionShape2D" parent="OneWay1"] shape = SubResource("8") one_way_collision = true [node name="OneWay2" type="CharacterBody2D" parent="."] position = Vector2(456, 308) [node name="Sprite2D" type="Sprite2D" parent="OneWay2"] scale = Vector2(1, 0.3) texture = ExtResource("2") [node name="CollisionShape2D" type="CollisionShape2D" parent="OneWay2"] shape = SubResource("8") one_way_collision = true [node name="OneWay3" type="CharacterBody2D" parent="."] position = Vector2(472, 308) [node name="Sprite2D" type="Sprite2D" parent="OneWay3"] scale = Vector2(1, 0.3) texture = ExtResource("2") [node name="CollisionShape2D" type="CollisionShape2D" parent="OneWay3"] shape = SubResource("8") one_way_collision = true [node name="OneWay4" type="CharacterBody2D" parent="."] position = Vector2(487, 308) [node name="Sprite2D" type="Sprite2D" parent="OneWay4"] scale = Vector2(1, 0.3) texture = ExtResource("2") [node name="CollisionShape2D" type="CollisionShape2D" parent="OneWay4"] shape = SubResource("8") one_way_collision = true [node name="Circle" type="CharacterBody2D" parent="."] position = Vector2(241.169, 304.126) rotation = -0.0790058 [node name="Sprite2D" type="Sprite2D" parent="Circle"] modulate = Color(0.4, 2, 0.8, 1) texture = ExtResource("5") [node name="CollisionShape2D" type="CollisionShape2D" parent="Circle"] shape = SubResource("9") [node name="AnimationPlayer" type="AnimationPlayer" parent="Circle"] libraries = { "": SubResource("AnimationLibrary_gijtf") } autoplay = "turn" [node name="BoxSprite" type="Sprite2D" parent="Circle"] modulate = Color(0.4, 2, 0.8, 1) position = Vector2(-3.05176e-05, -37.4108) texture = ExtResource("2") [node name="Box" type="CollisionShape2D" parent="Circle"] position = Vector2(-0.440125, -37.0904) shape = SubResource("11") [node name="Platform" type="StaticBody2D" parent="."] position = Vector2(257, 393) rotation = -0.428054 metadata/_edit_group_ = true [node name="Sprite2D" type="Sprite2D" parent="Platform"] texture = ExtResource("6") [node name="CollisionShape2D" type="CollisionShape2D" parent="Platform"] shape = SubResource("12") [node name="Platform1" type="StaticBody2D" parent="."] position = Vector2(369, 393) rotation = 0.471239 metadata/_edit_group_ = true [node name="Sprite2D" type="Sprite2D" parent="Platform1"] texture = ExtResource("6") [node name="CollisionShape2D" type="CollisionShape2D" parent="Platform1"] shape = SubResource("12") [node name="Camera2D" type="Camera2D" parent="."] offset = Vector2(265, 247) [node name="Player" parent="." instance=ExtResource("3")] position = Vector2(233.06, 223.436) [connection signal="body_entered" from="Princess" to="Princess" method="_on_body_entered"]
119610
extends Node func _on_body_entered(body: Node2D) -> void: if body.name == "Player": $"../WinText".show()
119611
[gd_scene load_steps=4 format=2] [ext_resource path="res://player/player.gd" type="Script" id=1] [ext_resource path="res://player/player.png" type="Texture2D" id=2] [sub_resource type="RectangleShape2D" id=1] extents = Vector2(7, 7) [node name="Player" type="CharacterBody2D"] script = ExtResource( 1 ) [node name="Sprite2D" type="Sprite2D" parent="."] texture = ExtResource( 2 ) [node name="CollisionShape2D" type="CollisionShape2D" parent="."] position = Vector2(-0.315559, 0.157784) shape = SubResource( 1 )
119613
extends CharacterBody2D const WALK_FORCE = 600 const WALK_MAX_SPEED = 200 const STOP_FORCE = 1300 const JUMP_SPEED = 200 @onready var gravity := float(ProjectSettings.get_setting("physics/2d/default_gravity")) func _physics_process(delta: float) -> void: # Horizontal movement code. First, get the player's input. var walk := WALK_FORCE * (Input.get_axis(&"move_left", &"move_right")) # Slow down the player if they're not trying to move. if abs(walk) < WALK_FORCE * 0.2: # The velocity, slowed down a bit, and then reassigned. velocity.x = move_toward(velocity.x, 0, STOP_FORCE * delta) else: velocity.x += walk * delta # Clamp to the maximum horizontal movement speed. velocity.x = clamp(velocity.x, -WALK_MAX_SPEED, WALK_MAX_SPEED) # Vertical movement code. Apply gravity. velocity.y += gravity * delta # Move based on the velocity and snap to the ground. # TODO: This information should be set to the CharacterBody properties instead of arguments: snap, Vector2.DOWN, Vector2.UP # TODO: Rename velocity to linear_velocity in the rest of the script. move_and_slide() # Check for jumping. is_on_floor() must be called after movement code. if is_on_floor() and Input.is_action_just_pressed(&"jump"): velocity.y = -JUMP_SPEED
119627
extends Area2D signal hit @export var speed = 400 # How fast the player will move (pixels/sec). var screen_size # Size of the game window. func _ready(): screen_size = get_viewport_rect().size hide() func _process(delta): var velocity = Vector2.ZERO # The player's movement vector. if Input.is_action_pressed(&"move_right"): velocity.x += 1 if Input.is_action_pressed(&"move_left"): velocity.x -= 1 if Input.is_action_pressed(&"move_down"): velocity.y += 1 if Input.is_action_pressed(&"move_up"): velocity.y -= 1 if velocity.length() > 0: velocity = velocity.normalized() * speed $AnimatedSprite2D.play() else: $AnimatedSprite2D.stop() position += velocity * delta position = position.clamp(Vector2.ZERO, screen_size) if velocity.x != 0: $AnimatedSprite2D.animation = &"right" $AnimatedSprite2D.flip_v = false $Trail.rotation = 0 $AnimatedSprite2D.flip_h = velocity.x < 0 elif velocity.y != 0: $AnimatedSprite2D.animation = &"up" rotation = PI if velocity.y > 0 else 0 func start(pos): position = pos rotation = 0 show() $CollisionShape2D.disabled = false func _on_body_entered(_body): hide() # Player disappears after being hit. hit.emit() # Must be deferred as we can't change physics properties on a physics callback. $CollisionShape2D.set_deferred(&"disabled", true)
119667
[node name="TopLight12" type="Polygon2D" parent="Ambient"] light_mask = 512 material = SubResource("22") position = Vector2(1042, -63) scale = Vector2(0.296875, 1) color = Color(1, 0.584314, 0, 0.341176) texture = ExtResource("13") polygon = PackedVector2Array(414.316, 138, -124.632, 59, 154.947, 16, 683.79, 92) uv = PackedVector2Array(-30.3157, -2, 272.842, -2, 273, 299, -37.0526, 297) [node name="CanvasModulate" type="CanvasModulate" parent="."] show_behind_parent = true light_mask = 0 color = Color(0.466667, 0.635294, 0.92549, 1) [node name="Crows" type="Node2D" parent="."] [node name="CrowSleep" type="AnimatedSprite2D" parent="Crows"] material = SubResource("41") position = Vector2(445, -129) sprite_frames = SubResource("40") animation = &"sleep" autoplay = "sleep" frame = 1 [node name="CrowSleep2" type="AnimatedSprite2D" parent="Crows"] material = SubResource("42") position = Vector2(108, 481) sprite_frames = SubResource("40") animation = &"sleep" autoplay = "sleep" frame = 1 flip_h = true [node name="CrowLook" type="AnimatedSprite2D" parent="Crows"] position = Vector2(-168, -145) sprite_frames = SubResource("91") animation = &"looking" autoplay = "looking" frame = 7 flip_h = true [node name="CrowLook2" type="AnimatedSprite2D" parent="Crows"] position = Vector2(1782, 35) sprite_frames = SubResource("91") animation = &"looking" autoplay = "looking" frame = 7 flip_h = true [node name="CrowLook3" type="AnimatedSprite2D" parent="Crows"] position = Vector2(1024, 78) sprite_frames = SubResource("91") animation = &"looking" autoplay = "looking" frame = 7
119695
[gd_scene load_steps=3 format=2] [ext_resource path="res://tileset/isotiles.png" type="Texture2D" id=1] [sub_resource type="OccluderPolygon2D" id=2] polygon = PackedVector2Array( 0, -100, -67, -68, -66, 0, -1, 33, 66, -2, 64, -67 ) [node name="TilesetEdit" type="Node2D"] [node name="Base" type="Sprite2D" parent="."] texture = ExtResource( 1 ) region_enabled = true region_rect = Rect2( 28, 75, 135, 105 ) [node name="Base2" type="Sprite2D" parent="."] position = Vector2( 200, 0 ) texture = ExtResource( 1 ) region_enabled = true region_rect = Rect2( 221, 75, 135, 105 ) [node name="Wall" type="Sprite2D" parent="."] position = Vector2( 400, 0 ) texture = ExtResource( 1 ) offset = Vector2( 0, -32 ) region_enabled = true region_rect = Rect2( 28, 220, 140, 140 ) [node name="StaticBody2D" type="StaticBody2D" parent="Wall"] [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="Wall/StaticBody2D"] polygon = PackedVector2Array( -64, 0, 0, 32, 64, 0, 0, -32 ) [node name="LightOccluder2D" type="LightOccluder2D" parent="Wall"] visible = false occluder = SubResource( 2 ) [node name="Column" type="Sprite2D" parent="."] position = Vector2( 600, 0 ) texture = ExtResource( 1 ) offset = Vector2( 0, -32 ) region_enabled = true region_rect = Rect2( 259, 241, 55, 95 ) [node name="StaticBody2D" type="StaticBody2D" parent="Column"] [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="Column/StaticBody2D"] position = Vector2( 2, 0 ) polygon = PackedVector2Array( -27, 7, -14, 20, 16, 20, 28, 4, 24, -12, 10, -22, -10, -22, -24, -12 ) [node name="Door1" type="Sprite2D" parent="."] position = Vector2( 800, 0 ) texture = ExtResource( 1 ) offset = Vector2( 0, -25 ) region_enabled = true region_rect = Rect2( 54, 426, 85, 110 ) [node name="StaticBody2D" type="StaticBody2D" parent="Door1"] [node name="CollisionPolygon2D" type="CollisionPolygon2D" parent="Door1/StaticBody2D"] polygon = PackedVector2Array( -24, 24, 40, -8, 24, -16, -40, 16 )
119700
extends CharacterBody2D const MOTION_SPEED = 160 # Pixels/second. var last_direction = Vector2(1, 0) var anim_directions = { "idle": [ # list of [animation name, horizontal flip] ["side_right_idle", false], ["45front_right_idle", false], ["front_idle", false], ["45front_left_idle", false], ["side_left_idle", false], ["45back_left_idle", false], ["back_idle", false], ["45back_right_idle", false], ], "walk": [ ["side_right_walk", false], ["45front_right_walk", false], ["front_walk", false], ["45front_left_walk", false], ["side_left_walk", false], ["45back_left_walk", false], ["back_walk", false], ["45back_right_walk", false], ], } func _physics_process(_delta): var motion = Vector2() motion.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left") motion.y = Input.get_action_strength("move_down") - Input.get_action_strength("move_up") motion.y /= 2 motion = motion.normalized() * MOTION_SPEED #warning-ignore:return_value_discarded set_velocity(motion) move_and_slide() var dir = velocity if dir.length() > 0: last_direction = dir update_animation("walk") else: update_animation("idle") func update_animation(anim_set): var angle = rad_to_deg(last_direction.angle()) + 22.5 var slice_dir = floor(angle / 45) $Sprite2D.play(anim_directions[anim_set][slice_dir][0]) $Sprite2D.flip_h = anim_directions[anim_set][slice_dir][1]
119726
extends CharacterBody2D const MOTION_SPEED = 30 const FRICTION_FACTOR = 0.89 const TAN30DEG = tan(deg_to_rad(30)) func _physics_process(_delta: float) -> void: var motion := Vector2() motion.x = Input.get_axis(&"move_left", &"move_right") motion.y = Input.get_axis(&"move_up", &"move_down") # Make diagonal movement fit for hexagonal tiles. motion.y *= TAN30DEG velocity += motion.normalized() * MOTION_SPEED # Apply friction. velocity *= FRICTION_FACTOR move_and_slide()
119778
#!/usr/bin/env bash # vi:syntax=sh APP_NAME="learn_to_code" # This is used while developing to supply the `GODOT_VERSION` variable that is # normally provided by the CI local_godot_version=${GODOT_VERSION:-"3.4.4"} ######################################## HELP help(){ if [ "$1" == "help" ]; then echo "Shows a short and helpful help text" exit 0 fi echo "" echo "Builder Script for Learn To Code With Godot" echo "please use one of the following commands:" for i in ${!funcs[@]}; do command=${funcs[i]} echo " - ${command//_/:}" done echo "you can get more info about commands by writing ./run <command> help" echo "you dry run most (but not all) commands by setting the \$dry env variable" echo "" } ######################################## CLEAN clean_web(){ if [ "$1" == "help" ]; then echo "Removes web build" exit 0 fi echo "rm -rf \"${dirs[web]}\"" test "$dry" || rm -rf "${dirs[web]}" echo "✓ Removed web files" } clean_all(){ if [ "$1" == "help" ]; then echo "Removes all build directories" exit 0 fi echo "rm -rf build" test "$dry" || rm -rf build echo "mkdir -p build" test "$dry" || mkdir -p build echo "touch build/.gdignore" test "$dry" || touch build/.gdignore echo "✓ Removed all builds" } clean(){ if [ "$1" == "help" ]; then echo "Removes one or all build directories" exit 0 fi echo "choose what to clean" exit 1 } ######################################## WEB DEV HELPERS web_server(){ if [ "$1" == "help" ]; then echo "Runs a python webserver in build/web" exit 0 fi if ! command -v python3 &> /dev/null; then echo "" echo "ERROR: Python 3 isn't available. It is required to run the server" echo " - in Debian/Ubuntu: sudo apt-get -y install inotify-tools" echo " - in Arch/Manjaro: sudo pacman --needed --noconfirm -S python" echo " - in Fedora: sudo dnf install python3" echo "" exit 1 fi echo "python3 -m http.server 8000 --directory \"${dirs[web]}\"" test "$dry" || python3 -m http.server 8000 --directory "${dirs[web]}" } web_watch(){ if [ "$1" == "help" ]; then echo "Watches a directory for changes. Recompiles Godot when a \.gd file changes;" echo "Overwrites JS and CSS files in the static directory when they change" exit 0 fi if ! command -v inotifywait &> /dev/null; then echo "" echo "ERROR: inotifywait isn't available. It is required to run the server" echo "this command is usually part of the package inotify-tools" echo " - in Debian/Ubuntu: sudo apt-get -y install inotify-tools" echo " - in Arch/Manjaro: sudo pacman --needed --noconfirm -S inotify-tools" echo " - in Fedora: sudo dnf install inotify-tools" echo "" exit 1 fi last_time_compiled=0 throttle_compile=10 last_time_copied=0 throttle_copy=1 source_dir=${1:-.} full_path=$(readlink -f $source_dir) _update_file(){ if [ "$base_dir" = "html_export" ]; then if (($now - $last_time_copied >= $throttle_copy)); then if [[ "$filename" == "index_template.html" ]]; then prepare_htmltemplate changed_file="./html_export/index.html" filename="index.html" fi echo "cp \"$changed_file\" \"${dirs[web]}/$filename\"" cp "$changed_file" "${dirs[web]}/$filename" fi last_time_copied=$(date +%s) else echo "Changes detected in $changed_file, will recompile" if (($now - $last_time_compiled >= $throttle_compile)); then export_custom "${presets[web]}" "${dirs[web]}/index.html" fi last_time_compiled=$(date +%s) fi } echo "will watch $full_path" inotifywait --monitor --recursive --quiet --event modify,move,create,delete --format '%w%f' "$source_dir" | while read changed_file do changed_dir=$(dirname "$changed_file") base_dir=$(echo "$changed_dir" | cut -d "/" -f2) ext=${changed_file##*.} now=$(date +%s) filename=$(basename "$changed_file") ext=$(echo "$ext" | tr '[:upper:]' '[:lower:]') exclude=0 include=0 if [[ -d "$$changed_file" ]] || [[ "$filename" =~ ^\. ]] || [[ "$base_dir" == "build" ]]; then exclude=1 fi if [[ "$exclude" -eq 0 ]] && [[ $ext =~ gd|tscn|tres|js|css|html ]]; then include=1 fi if [[ "$exclude" -eq 0 ]] && [[ "$include" -eq 1 ]]; then _update_file fi done } web_debug(){ if [ "$1" == "help" ]; then echo "Exports the web build, starts a python webserver, and watches" echo "the directory for changes. Require Python 3 and inotifywait to" echo "be in your \$PATH" exit 0 fi echo "You need the custom templates. Please make sure to run prepare:local at least once!" debug=true clean_web export_web web_server & web_watch } ######################################## EXPORTS export_custom(){ if [ "$1" == "help" ]; then echo "Exports a Godot build" echo "Usage:" echo "./run export:any <name> <output_path>" echo "" echo "for example: ./run export:any \"HTML5\" \"build/web/index.html\"" echo "" echo "<name> needs to be a valid export specified in \`export_presets.cfg\`" echo "set the environment variable \$debug to export a debug build" exit 0 fi export_name=$1 output=$2 dir=$(dirname "$output") mkdir -p "$dir" prepare_versionfile # THERE IS NO DIFFERENCE BETWEEN A DEBUG AND A RELEASE BUILD # we export a debug build in all cases, due to https://github.com/GDQuest/learn-gdscript/issues/618 # we could remove the `debug` keyword, but it is kept both for backwards # compatibility, and in case we solve this differently in the future # in which case, all that needs to be done is replce `export-debug` with `export` if [ -z "$debug" ]; then echo "godot --quiet --no-window --export-debug \"$export_name\" \"$output\"" test "$dry" || godot --quiet --no-window --export-debug "$export_name" "$output" else echo "godot --quiet --no-window --export-debug \"$export_name\" \"$output\"" test "$dry" || godot --quiet --no-window --export-debug "$export_name" "$output" fi echo "✓ Exported \`$export_name\` build to \`$dir\`" } export_web(){ if [ "$1" == "help" ]; then echo "Exports the Web build and copies over static files" echo "You can specify the following environment variables:" echo " - \`\$url\` for the html template" echo " - \`\$git_branch\` for deploying to a subfolder (the" echo " \`release\` branch will be blanked, and deployed to" echo " the root subfolder)" exit 0 fi prepare_htmltemplate export_custom "${presets[web]}" "${dirs[web]}/index.html" echo "cp -r html_export/static/* \"${dirs[web]}\"" test "$dry" || cp -r html_export/static/* "${dirs[web]}" echo "✓ Copied web files to ${dirs[web]}" } export_osx(){ if [ "$1" == "help" ]; then echo "Exports the OSX build" exit 0 fi export_custom "${presets[osx]}" "${dirs[osx]}/$APP_NAME.zip" }
119891
extends PanelContainer signal toggled(is_pressed) const OPTION_FONT := preload("res://ui/theme/fonts/font_text.tres") const OPTION_SELECTED_FONT := preload("res://ui/theme/fonts/font_text_bold.tres") var _button_text := "" onready var _margin_container := $MarginContainer as MarginContainer onready var _label := $MarginContainer/Label as Label onready var _group: ButtonGroup = preload("QuizAnswerButtonGroup.tres") onready var _button := $CheckBox as CheckBox func _notification(what: int) -> void: if what == NOTIFICATION_TRANSLATION_CHANGED: _label.text = tr(_button_text) func setup(text: String, is_multiple_choice: bool) -> void: _button_text = text if not is_inside_tree(): yield(self, "ready") _label.text = tr(_button_text) _label.add_font_override("font", OPTION_FONT) _button.toggle_mode = true _button.connect("toggled", self, "_on_toggled") if not is_multiple_choice: _button.group = _group func get_answer() -> String: return _button_text if _button.pressed else "" func _on_toggled(is_pressed: bool) -> void: _label.add_font_override("font", OPTION_SELECTED_FONT if is_pressed else OPTION_FONT)
119934
extends Button const EDITOR_EXPAND_ICON := preload("res://ui/icons/fullscreen_on.png") const EDITOR_COLLAPSE_ICON := preload("res://ui/icons/fullscreen_off.png") func _ready() -> void: if OS.has_feature("JavaScript"): modulate.a = 0.0 return connect("pressed", self, "_toggle_fullscreen") Events.connect("fullscreen_toggled", self, "_toggle_fullscreen") _update_icon() func _toggle_fullscreen() -> void: OS.window_fullscreen = not OS.window_fullscreen _update_icon() func _update_icon(): icon = EDITOR_COLLAPSE_ICON if OS.window_fullscreen else EDITOR_EXPAND_ICON
119955
extends Panel const TEXTURE_PROCESSING := preload("robot_tutor_running_code.svg") onready var _texture_rect := $Layout/TextureRect as TextureRect func _ready() -> void: _texture_rect.texture = TEXTURE_PROCESSING
119962
extends Button func _ready() -> void: connect("pressed", get_tree(), "quit") if OS.has_feature("JavaScript"): queue_free()
119974
# Displays a scene inside a frame. class_name GameView extends Control var paused := false setget set_paused var _viewport := Viewport.new() onready var _viewport_container = $ViewportContainer as ViewportContainer onready var _pause_rect := $PauseRect as ColorRect onready var _scene_tree := get_tree() func _ready() -> void: _pause_rect.visible = false _viewport.name = "Viewport" _viewport_container.add_child(_viewport) _scene_tree.connect("screen_resized", self, "_on_screen_resized") call_deferred("_on_screen_resized") func toggle_paused() -> void: set_paused(not paused) func set_paused(value: bool) -> void: paused = value _scene_tree.paused = paused _pause_rect.visible = paused func use_scene(node: Node, viewport_size: Vector2) -> void: _viewport.add_child(node) _pause_rect.raise() _viewport.size = viewport_size func get_viewport() -> Viewport: return _viewport func _on_screen_resized() -> void: _viewport.size = rect_size
119981
tool class_name Revealer, "./Revealer.svg" extends Container const ANIMATION_ICON_DURATION := 0.1 const ANIMATION_REVEAL_DURATION := 0.24 const TOGGLE_OPACITY := 0.65 const TOGGLE_OPACITY_HOVER := 1.0 signal expanded export var title := "Expand" setget set_title export var is_expanded := false setget set_is_expanded export var title_font_color: Color = Color.white setget set_title_font_color export var title_icon_color: Color = Color.white setget set_title_icon_color export var title_font: Font setget set_title_font export var title_panel: StyleBox setget set_title_panel export var title_panel_expanded: StyleBox setget set_title_panel_expanded export var content_panel: StyleBox setget set_content_panel export var content_separation: int = 2 setget set_content_separation onready var _tweener := $Tween as Tween onready var _toggle_bar := $ToggleBar as PanelContainer onready var _toggle_button := $ToggleBar/ToggleCapturer as Button onready var _toggle_label := $ToggleBar/BarLayout/Label as Label onready var _toggle_icon_anchor := $ToggleBar/BarLayout/ToggleIcon as Control onready var _toggle_icon := $ToggleBar/BarLayout/ToggleIcon/Texture as TextureRect var _content_children := [] var _percent_revealed := 0.0 var _title_style: StyleBox func _ready() -> void: _toggle_label.text = title _toggle_button.pressed = is_expanded _index_content() _update_icon_anchor() _update_theme() _toggle_bar.modulate.a = TOGGLE_OPACITY _toggle_button.connect("mouse_entered", self, "_on_toggle_entered") _toggle_button.connect("mouse_exited", self, "_on_toggle_exited") _toggle_button.connect("toggled", self, "_on_toggle_pressed") _tweener.connect("tween_step", self, "_on_tweener_step") _tweener.connect("tween_all_completed", self, "_on_tweener_completed") _toggle_content(is_expanded, true) _title_style = get_title_panel_style() func _draw() -> void: var title_size := _toggle_bar.rect_size if _title_style: var title_rect := Rect2() title_rect.position = Vector2(0, 0) title_rect.size = _toggle_bar.rect_size + _title_style.get_minimum_size() draw_style_box(_title_style, title_rect) title_size += _title_style.get_minimum_size() if content_panel: var content_rect := Rect2() content_rect.position = Vector2(0, title_size.y) content_rect.size = Vector2(rect_size.x, rect_size.y - title_size.y) draw_style_box(content_panel, content_rect) func _notification(what: int) -> void: if what == NOTIFICATION_SORT_CHILDREN: _resort() func _index_content() -> void: _content_children = [] for child_node in get_children(): var control_node := child_node as Control if not control_node or control_node == _toggle_bar: continue _content_children.append(control_node) func _update_icon_anchor() -> void: if not is_inside_tree(): return _toggle_icon_anchor.rect_min_size = _toggle_icon.rect_size _toggle_icon.rect_pivot_offset = _toggle_icon.rect_size / 2 func _update_theme() -> void: if not is_inside_tree(): return _toggle_label.add_font_override("font", title_font) _toggle_label.add_color_override("font_color", title_font_color) _toggle_icon.modulate = title_icon_color func add_child(child_node: Node, legible_unique_name: bool = false) -> void: .add_child(child_node, legible_unique_name) var control_node := child_node as Control if not control_node or control_node == _toggle_bar: return _content_children.append(control_node) func remove_child(child_node: Node) -> void: if _content_children.has(child_node): _content_children.erase(child_node) .remove_child(child_node) func _get_minimum_size() -> Vector2: # Title/toggle bar always contributes to the minimal size in full. var title_size := Vector2.ZERO if is_instance_valid(_toggle_bar): title_size = _toggle_bar.get_combined_minimum_size() if _title_style: title_size += _title_style.get_minimum_size() # Content can be partially visible, so we calculate full size, then slice it. var content_size := Vector2.ZERO var first := true for child_node in get_children(): var control_node := child_node as Control if not control_node or not control_node.is_visible_in_tree(): continue if control_node == _toggle_bar: continue var control_size := control_node.get_combined_minimum_size() if content_size.x < control_size.x: content_size.x = control_size.x content_size.y += control_size.y if first: first = false else: content_size.y += content_separation if content_panel: content_size += content_panel.get_minimum_size() content_size.y *= _percent_revealed # Combine the two. var final_size := title_size if final_size.x < content_size.x: final_size.x = content_size.x final_size.y += content_size.y return final_size func _resort() -> void: var content_offset := 0 var base_width := rect_size.x if is_instance_valid(_toggle_bar): var bar_position := Vector2.ZERO var bar_size := _toggle_bar.rect_min_size bar_size.x = base_width if _title_style: bar_position.x += _title_style.get_margin(MARGIN_LEFT) bar_position.y += _title_style.get_margin(MARGIN_TOP) bar_size.x -= _title_style.get_margin(MARGIN_LEFT) + _title_style.get_margin(MARGIN_RIGHT) fit_child_in_rect(_toggle_bar, Rect2(bar_position, bar_size)) _update_icon_anchor() content_offset = int(_toggle_bar.rect_size.y) if _title_style: content_offset += int(_title_style.get_margin(MARGIN_TOP) + _title_style.get_margin(MARGIN_BOTTOM)) var first := true for child_node in get_children(): var control_node := child_node as Control if not control_node or not control_node.is_visible_in_tree(): continue if control_node == _toggle_bar: continue var position := Vector2.ZERO var size := control_node.rect_min_size size.x = base_width if content_panel: position.x += content_panel.get_margin(MARGIN_LEFT) size.x -= content_panel.get_margin(MARGIN_LEFT) + content_panel.get_margin(MARGIN_RIGHT) if first: first = false if content_panel: content_offset += int(content_panel.get_margin(MARGIN_TOP)) else: content_offset += content_separation position.y = content_offset fit_child_in_rect(control_node, Rect2(position, size)) content_offset += int(control_node.rect_size.y) func set_title(value: String) -> void: title = value if is_inside_tree(): _toggle_label.text = title func set_is_expanded(value: bool) -> void: if is_expanded == value: return is_expanded = value if is_expanded: emit_signal("expanded") if is_inside_tree(): _toggle_button.pressed = is_expanded _toggle_content(is_expanded) func set_title_font_color(value: Color) -> void: title_font_color = value _update_theme() func set_title_icon_color(value: Color) -> void: title_icon_color = value _update_theme() func set_title_font(value: Font) -> void: title_font = value _update_theme() minimum_size_changed() notification(NOTIFICATION_THEME_CHANGED) func set_title_panel(value: StyleBox) -> void: if title_panel == value: return if title_panel: title_panel.disconnect("changed", self, "minimum_size_changed") title_panel.disconnect("changed", self, "queue_sort") title_panel.disconnect("changed", self, "update") title_panel = value if title_panel and not title_panel.is_connected("changed", self, "minimum_size_changed"): title_panel.connect("changed", self, "minimum_size_changed") title_panel.connect("changed", self, "queue_sort") title_panel.connect("changed", self, "update") minimum_size_changed() notification(NOTIFICATION_THEME_CHANGED)
120342
[gd_scene load_steps=3 format=2] [ext_resource path="res://course/lesson-10-the-game-loop/rotating-and-moving/RotateAndMoveSprite.gd" type="Script" id=1] [ext_resource path="res://course/common/Robot.tscn" type="PackedScene" id=2] [node name="RotateAndMoveSprite" type="Node2D"] [node name="Robot" parent="." instance=ExtResource( 2 )] script = ExtResource( 1 ) [node name="Camera2D" type="Camera2D" parent="."] current = true
120419
[gd_scene load_steps=4 format=2] [ext_resource path="res://ui/theme/fonts/font_title.tres" type="DynamicFont" id=1] [ext_resource path="res://ui/theme/panel_normal.tres" type="StyleBox" id=2] [sub_resource type="Theme" id=1] default_font = ExtResource( 1 ) [node name="VisualFunctionDefinition" type="PanelContainer"] margin_right = 580.0 margin_bottom = 45.0 rect_min_size = Vector2( 0, 80 ) size_flags_horizontal = 3 custom_styles/panel = ExtResource( 2 ) __meta__ = { "_edit_use_anchors_": false } [node name="Row" type="HBoxContainer" parent="."] margin_left = 8.0 margin_top = 24.0 margin_right = 610.0 margin_bottom = 55.0 size_flags_vertical = 4 theme = SubResource( 1 ) custom_constants/separation = 4 alignment = 1 __meta__ = { "_edit_use_anchors_": false } [node name="Label6" type="Label" parent="Row"] margin_right = 602.0 margin_bottom = 31.0 custom_colors/font_color = Color( 0.14902, 0.776471, 0.968627, 1 ) text = "Invalid operands 'String' and 'int' in operator '+'."
120440
extends Panel signal used signal restored const SWORD := preload("res://course/common/inventory/sword.png") const SHIELD := preload("res://course/common/inventory/shield.png") const HEALTH := preload("res://course/common/inventory/healing_heart.png") const GEMS := preload("res://course/common/inventory/gems.png") const textures = [ SWORD, SHIELD, HEALTH, GEMS ] export var texture: Texture setget set_texture, get_texture export var hide_after_animation := false onready var anim_player := $AnimationPlayer as AnimationPlayer onready var texture_rect := $TextureRect as TextureRect onready var label := $Label as Label var _animation_backwards := false func _ready() -> void: set_label_index(get_index()) if texture == null: randomize() set_random_texture() anim_player.connect("animation_finished", self, "_on_animation_finished") func set_random_texture(): if get_index() > 0 and get_index() < textures.size(): # ensure textures appear at least once each in the first loop var previous_crate = get_parent().get_child(get_index() - 1) if previous_crate and previous_crate.texture: var previous_texture_index := textures.find(previous_crate.texture) if previous_texture_index > -1: var next_index := (previous_texture_index + 1) % textures.size() set_texture(textures[next_index]) return randomize_texture() func randomize_texture(): set_texture(textures[randi() % textures.size()]) func use() -> void: anim_player.play("use") func reset(speed := 2.0) -> void: show() if speed == 0: anim_player.play("RESET") return _animation_backwards = true anim_player.play("use", -1, -1 * speed, true) func _on_animation_finished(animation_name: String) -> void: if animation_name != "use": return if _animation_backwards: _animation_backwards = false emit_signal("restored") return if hide_after_animation: hide() emit_signal("used") func set_texture(new_texture: Texture) -> void: texture = new_texture if not is_inside_tree(): yield(self, "ready") texture_rect.texture = new_texture func get_texture() -> Texture: return texture func get_texture_name(): var path := texture.resource_path var filename := path.get_file().get_basename().split("_") return PoolStringArray(filename).join(" ") func set_label_index(index: int) -> void: label.text = str(index)
120538
[gd_resource type="Resource" load_steps=3 format=2] [ext_resource path="res://addons/gdscript-slice-exporter/collections/SceneProperties.gd" type="Script" id=1] [ext_resource path="res://course/lesson-12-using-variables/fixing_error/FixingError.tscn" type="PackedScene" id=2] [resource] script = ExtResource( 1 ) scene = ExtResource( 2 ) viewport_size = Vector2( 1920, 1080 )
120621
When programs stop responding on your computer, it's often due to an infinite loop!" answer_options = [ "It would draw squares infinitely until the program is terminated", "It would draw 10 squares", "It would draw 20 squares" ] valid_answers = [ "It would draw squares infinitely until the program is terminated" ] is_multiple_choice = false do_shuffle_answers = true [sub_resource type="Resource" id=21] script = ExtResource( 2 ) content_id = "res://course/lesson-17-while-loops/content-izKUdOCQ.tres" title = "When to use while loops" type = 0 text = "At first, you will not need [code]while[/code] loops often. Even the code we show here has more efficient alternatives. Also, there's a safer kind of loop, [code]for[/code] loops, which we'll look at in the next lesson. Yet, [code]while[/code] loops have important intermediate to advanced-level uses, so you at least need to know they exist and how to use them. We use [code]while[/code] loops every time we need to loop an unknown number of times. For example, games run in a loop that typically generates sixty images per second until the user closes the game. This is possible thanks to [code]while[/code] loops. There are other good uses for [code]while[/code] loops: - Reading and processing a file, like a text document, line by line. - Processing a constant stream of data, like someone recording audio with a microphone. - Reading code and converting it into instructions the computer understands. - Various intermediate to advanced-level algorithms, like finding paths around a map for AI." visual_element_path = "" reverse_blocks = false has_separator = true [sub_resource type="Resource" id=11] script = ExtResource( 2 ) content_id = "res://course/lesson-17-while-loops/content-Ib5BnVHA.tres" title = "" type = 0 text = "Let's practice some [code]while[/code] loops, as they're useful to know. It's also an excellent opportunity to practice 2D vectors. Then, we'll move on to the safer [code]for[/code] loops in the following lesson." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=12] script = ExtResource( 5 ) practice_id = "res://course/lesson-17-while-loops/practice-lkGx0c7D.tres" title = "Moving to the end of a board" goal = "Our robot has decided to stand at the top of the board. Complete the [code]move_to_bottom()[/code] function so the robot moves to the bottom of the board. The board size is determined by the [code]Vector2[/code] [code]board_size[/code]. The robot's current cell is [code]Vector2(2, 0)[/code]. Make sure to use a [code]while[/code] loop so the function works for any board size." starting_code = "func move_to_bottom(): pass" cursor_line = 0 cursor_column = 0 hints = PoolStringArray( "You\'ll have to alter the [code]y[/code] sub-variable of [code]cell[/code] to move the robot downwards", "To move the robot down, [code]cell.y[/code] needs to increase", "Use [code]while cell.y < board_size.y - 1:[/code]" ) validator_script_path = "while_move/TestPracticeBoardWhile.gd" script_slice_path = "while_move/PracticeBoardWhile.live-editor/slices/PracticeBoardWhile.move_to_end.slice.tres" documentation_references = PoolStringArray( "board_size", "cell" ) documentation_resource = ExtResource( 4 ) description = "Use a while loop to have our robot move from the top of the board to the bottom." [resource] script = ExtResource( 1 ) title = "Introduction to While Loops" content_blocks = [ SubResource( 1 ), SubResource( 4 ), SubResource( 22 ), SubResource( 23 ), SubResource( 7 ), SubResource( 20 ), SubResource( 13 ), SubResource( 14 ), SubResource( 15 ), SubResource( 17 ), SubResource( 19 ), SubResource( 18 ), SubResource( 8 ), SubResource( 9 ), SubResource( 10 ), SubResource( 21 ), SubResource( 11 ) ] practices = [ SubResource( 12 ) ]
120692
[gd_scene load_steps=2 format=2] [ext_resource path="res://course/lesson-22-functions-return-values/convert-grid-coordinates/ConvertGridCoordinates.gd" type="Script" id=1] [node name="ConvertGridCoordinates" type="Node2D"] script = ExtResource( 1 ) [node name="Camera2D" type="Camera2D" parent="."] current = true
120727
[gd_resource type="Resource" load_steps=25 format=2] [ext_resource path="res://resources/Lesson.gd" type="Script" id=1] [ext_resource path="res://resources/ContentBlock.gd" type="Script" id=2] [ext_resource path="res://resources/QuizChoice.gd" type="Script" id=3] [ext_resource path="res://course/Documentation.tres" type="Resource" id=4] [ext_resource path="res://resources/Practice.gd" type="Script" id=5] [sub_resource type="Resource" id=1] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-jB7tKRHJ.tres" title = "" type = 0 text = "We used the [code]range()[/code] function in combination with [code]for[/code] loops." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=2] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-MQ2XNwQM.tres" title = "" type = 0 text = "" visual_element_path = "res://course/lesson-19-creating-arrays/visuals/ExamplePrint.tscn" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=3] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-qAYVjotx.tres" title = "" type = 0 text = "The [code]range()[/code] function produced an array that the [code]for[/code] keyword could loop over. We can give [code]for[/code] loops [i]any[/i] array, and they will loop over them just the same. Instead of using the [code]range()[/code] function, we could manually write the numbers and get the same result." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=4] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-F5HUxZPx.tres" title = "" type = 0 text = "" visual_element_path = "visuals/ExamplePrintArray.tscn" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=5] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-Y8VUDpPw.tres" title = "" type = 0 text = "For each element inside the array, the [code]for[/code] loop extracts it, stores it in the temporary variable named [code]number[/code], and executes the loop's code once. Inside the loop, you can access the [code]number[/code] variable, which changes on each [i]iteration[/i]. The code works regardless of the array or where you store it. Often, you will store arrays in variables for easy access." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=6] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-QDwfyqdY.tres" title = "" type = 0 text = "" visual_element_path = "visuals/CodeStoreArrayInVar.tscn" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=7] script = ExtResource( 3 ) quiz_id = "res://course/lesson-20-looping-over-arrays/quiz-n1TxlTtc.tres" question = "What will this code print?" content_bbcode = "[code]var numbers = [0, 1, 2] for number in numbers: print(number) [/code]" hint = "" explanation_bbcode = "Compared to previous examples, we store the array in the [code]numbers[/code] variable. Using the [code]numbers[/code] variable in our [code]for[/code] loop allows the computer to access the array of numbers like before. We have three numbers in the array: [code]0[/code], [code]1[/code], and [code]2[/code]. The loop extracts each of them sequentially and assigns it to the [code]number[/code] temporary variable. As the loop processes each number, the output will print [code]0[/code], then [code]1[/code], then [code]2[/code], each on a separate line." answer_options = [ "0, 1, and 2", "1, 2, and 3", "0, 0, and 0" ] valid_answers = [ "0, 1, and 2" ] is_multiple_choice = false do_shuffle_answers = true [sub_resource type="Resource" id=8] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-OexRjTRh.tres" title = "Making the turtle walk, with a loop" type = 0 text = "In the previous lesson, you made a turtle walk along a path by writing [code]Vector2[/code] coordinates in an array." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=9] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-ZN4rS5AJ.tres" title = "" type = 0 text = "" visual_element_path = "res://course/lesson-19-creating-arrays/visuals/ExampleTurtleRobotPath.tscn" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=13] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-DGt6fUqb.tres" title = "" type = 0 text = "It's a [code]for[/code] loop that makes the turtle walk along the path. The loop works like this: for each coordinate in the array, it moves the turtle once to that cell." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=14] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-TxYej47M.tres" title = "" type = 0 text = "" visual_element_path = "visuals/CodeTurtleMove.tscn" reverse_blocks = false has_separator = true [sub_resource type="Resource" id=10] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-TESv5tT6.tres" title = "" type = 0 text = "It's the same principle with unit selection." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=15] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-vGm22rtQ.tres" title = "" type = 0 text = "" visual_element_path = "visuals/ExampleSelectUnits.tscn" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=16] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-qE82V6jG.tres" title = "" type = 0 text = "For each coordinate in an array named [code]selected_units[/code], we check if there is a unit in that cell. If so, we select it. In that case, we use an array, a loop, and a condition together." visual_element_path = "" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=11] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-hcIb5BnV.tres" title = "" type = 0 text = "" visual_element_path = "visuals/CodeSelectUnits.tscn" reverse_blocks = false has_separator = false [sub_resource type="Resource" id=17] script = ExtResource( 2 ) content_id = "res://course/lesson-20-looping-over-arrays/content-En91c9ll.tres" title = "" type = 0 text = "The code above uses several features you haven't learned yet: - In a condition, the [code]in[/code] keyword allows you to check if a value exists [i]in[/i] an array. - The array's [code]append()[/code] function appends a new value at the end of the array. Notice the use of a period after the [code]selected_units[/code] variable, to call the [code]append()[/code] function. It's because this function exists only on arrays.
120765
[gd_resource type="Resource" load_steps=3 format=2] [ext_resource path="res://addons/gdscript-slice-exporter/collections/SceneProperties.gd" type="Script" id=1] [ext_resource path="res://course/lesson-8-defining-variables/define-health-variable/DefineHealthVar.tscn" type="PackedScene" id=2] [resource] script = ExtResource( 1 ) scene = ExtResource( 2 ) viewport_size = Vector2( 1920, 1080 )
120803
[gd_resource type="Resource" load_steps=3 format=2] [ext_resource path="res://course/lesson-14-multiplying/reducing_damage/ReducingDamage.tscn" type="PackedScene" id=1] [ext_resource path="res://addons/gdscript-slice-exporter/collections/SceneProperties.gd" type="Script" id=2] [resource] script = ExtResource( 2 ) scene = ExtResource( 1 ) viewport_size = Vector2( 1920, 1080 )
120819
tool extends Path2D const COLOR_GREY := Color("928fb8") export var graph_size := Vector2.ONE * 250 export var text_x := "x-axis" export var text_y := "y-axis" export var axis_increments := 50 export var show_speed := 400 var _line var _points := [] var _last_point := Vector2.ZERO # Need a draw offset as the scene is centered in lessons var _draw_offset := Vector2(-graph_size.x / 2, graph_size.y/2) onready var _label_x := $LabelX as Label onready var _label_y := $LabelY as Label func _ready() -> void: update() if Engine.editor_hint: return _label_x.rect_position += _draw_offset _label_x.rect_size.x = graph_size.x _label_x.text = text_x _label_y.rect_position += _draw_offset _label_y.rect_size.x = graph_size.y _label_y.text = text_y _points = curve.tessellate(5, 4) _line = Polygon.new(show_speed) _line.position = _draw_offset _line.line_2d.width = 3 _line.line_2d.default_color = Color.white _line.connect("line_end_moved", self, "_change_sprite_position") add_child(_line) _last_point = _points[0] + _draw_offset func run() -> void: if _line.is_drawing(): return _line.reset() _line.points = _points _line.start_draw_animation() func reset() -> void: _line.reset() _last_point = Vector2(0, 0) func _process(_delta: float) -> void: if Engine.editor_hint: return update() func _change_sprite_position(new_position: Vector2) -> void: _last_point = new_position func _draw() -> void: # Don't offset the graph in the editor as drawing curves won't line up var draw_offset = Vector2.ZERO if Engine.editor_hint else _draw_offset draw_line(Vector2.ZERO + draw_offset, Vector2(graph_size.x, 0) + draw_offset, COLOR_GREY, 4, true) draw_line(Vector2.ZERO + draw_offset, Vector2(0, -graph_size.y) + draw_offset, COLOR_GREY, 4, true) for i in range(graph_size.x / axis_increments): draw_circle(Vector2(axis_increments + i * axis_increments, 0) + draw_offset, 4, Color.white) for i in range(graph_size.y / axis_increments): draw_circle(-Vector2(0, axis_increments + i * axis_increments) + draw_offset, 4, Color.white) if _last_point != Vector2(0, 0): draw_circle(_last_point, 4, Color.white) class Polygon: extends Node2D var points := PoolVector2Array() setget , get_points var draw_speed := 400.0 var line_2d := Line2D.new() var _tween := Tween.new() var _current_points := PoolVector2Array() var _current_point_index := 0 var _total_distance := 0.0 signal animation_finished signal line_end_moved(new_coordinates) func _init(line_draw_speed := 400.0) -> void: add_child(_tween) add_child(line_2d) _tween.connect("tween_all_completed", self, "next") draw_speed = line_draw_speed func reset() -> void: stop_animation() line_2d.clear_points() _current_point_index = 0 _total_distance = 0 _current_points.resize(0) func start_draw_animation() -> void: var previous_point := points[0] as Vector2 for index in range(1, points.size()): var p := points[index] as Vector2 var distance = previous_point.distance_to(p) previous_point = p _total_distance += distance _tween.stop_all() next() func next() -> void: if points.size() - _current_point_index < 2: emit_signal("animation_finished") return var starting_point: Vector2 = points[_current_point_index] var destination: Vector2 = points[_current_point_index + 1] _current_point_index += 1 var distance := starting_point.distance_to(destination) var animation_duration := distance / draw_speed _current_points.append(starting_point) line_2d.points = _current_points _tween.interpolate_method( self, "_animate_point_position", starting_point, destination, animation_duration ) _tween.start() func stop_animation() -> void: _tween.remove_all() func is_drawing() -> bool: return _tween.is_active() func _animate_point_position(point: Vector2) -> void: var new_points := _current_points new_points.push_back(point) line_2d.points = new_points emit_signal("line_end_moved", point + position) # Returns the local bounds of the polygon. That is to say, it only takes the # point into account in local space, but not the polygon's `position`. func get_rect() -> Rect2: var top_left := Vector2.ZERO var bottom_right := Vector2.ZERO for p in points: if p.x > bottom_right.x: bottom_right.x = p.x elif p.x < top_left.x: top_left.x = p.x if p.y > bottom_right.y: bottom_right.y = p.y elif p.y < top_left.y: top_left.y = p.y return Rect2(top_left, bottom_right - top_left) func get_center() -> Vector2: var rect := get_rect() return (rect.position + rect.end) / 2.0 + position func get_points() -> PoolVector2Array: return points
120852
{ "patterns": [ ["Expected", "type for"], ["Expected type after"], ], "raw": [ "Expected a type for the class variable.", "Expected a type for the class constant.", "Expected a type for the variable.", "Expected a type for an argument.", "Expected a return type for the function.", "Expected type for export.", "Expected type after 'as'.", ], "code": ErrorCode.MISPLACED_TYPE_IDENTIFIER, }, { "patterns": [ ["Unknown class"], ["Couldn't find the subclass"], ["Couldn't resolve the constant"], ["Constant isn't a class"], ["Invalid inheritance (unknown class + subclasses)."], ["Parser bug: undecidable inheritance."], ["Couldn't determine inheritance."], ["Parser bug: unresolved constant."], ["isn't a valid type (not a script or class), or couldn't be found on base"], ["isn't declared on base"], ["isn't declared in the current class"], ["isn't declared in the current scope"], ["etter function isn't defined"], # Yes, etter! [ 'Invalid "is" test: the right operand isn\'t a type (neither a native type nor a script).' ], ["not present in built-in type"], ["invalid index", "in constant expression"], ], "raw": [ 'Unknown class: "%CLASS_NAME%"', "Couldn't find the subclass: %SUBCLASS_NAME%", 'Couldn\'t resolve the constant "%CONSTANT_NAME%".', "Constant isn't a class: %IDENTIFIER%", "Invalid inheritance (unknown class + subclasses).", "Parser bug: undecidable inheritance.", "Couldn't determine inheritance.", "Parser bug: unresolved constant.", 'The identifier "%IDENTIFIER%" isn\'t a valid type (not a script or class), or couldn\'t be found on base "%CLASS_NAME%".', 'The method "%CALLEE_NAME%" isn\'t declared on base "%TYPE_NAME%".', 'The method "%CALLEE_NAME%" isn\'t declared in the current class.', 'The identifier "%IDENTIFIER%" isn\'t declared in the current scope.', "The setter function isn't defined.", "The getter function isn't defined.", 'Invalid "is" test: the right operand isn\'t a type (neither a native type nor a script).', "Static constant '%CONSTANT_NAME%' not present in built-in type %BUILTIN_TYPE%.", "invalid index in constant expression", "invalid index '%INDEX_NAME%' in constant expression", ], "code": ErrorCode.NONEXISTENT_IDENTIFIER, }, { "patterns": [ ['"yield()" can only be used inside function blocks.'], ['"self" isn\'t allowed in a static function or constant expression.'], [ 'Expected "var", "onready", "remote", "master", "puppet", "sync", "remotesync", "mastersync", "puppetsync".' ], ['Expected "var".'], ['Expected "var" or "func".'], ['Expected "func".'], ['Unexpected keyword "continue" outside a loop.'], ['Unexpected keyword "break" outside a loop.'], ['"extends" can only be present once per script.'], ['"extends" must be used before anything else.'], ['"class_name" is only valid for the main class namespace.'], ['"class_name" isn\'t allowed in built-in scripts.'], ['"class_name" can only be present once per script.'], ['The "tool" keyword can only be present once per script.'], ], "raw": [ '"yield()" can only be used inside function blocks.', '"self" isn\'t allowed in a static function or constant expression.', 'Expected "var", "onready", "remote", "master", "puppet", "sync", "remotesync", "mastersync", "puppetsync".', 'Expected "var".', 'Expected "var" or "func".', 'Expected "func".', 'Unexpected keyword "continue" outside a loop.', 'Unexpected keyword "break" outside a loop.', '"extends" can only be present once per script.', '"extends" must be used before anything else.', '"class_name" is only valid for the main class namespace.', '"class_name" isn\'t allowed in built-in scripts.', '"class_name" can only be present once per script.', 'The "tool" keyword can only be present once per script.', ], "code": ErrorCode.MISPLACED_KEYWORD, }, { "patterns": [ ["Expected a constant expression"], ["constant expression", "or variables", "in a pattern"], ["Not a constant expression as key"], ], "raw": [ "Expected a constant expression.", "Expect constant expression or variables in a pattern", "Only constant expression or variables allowed in a pattern", "Only constant expressions or variables allowed in a pattern", "Not a constant expression as key", ], "code": ErrorCode.EXPECTED_CONSTANT_EXPRESSION, }, { "patterns": [ [ '"extends" constant must be a string.', ], [ 'Invalid "extends" syntax, expected string constant (path) and/or identifier (parent class).', ], [ '"class_name" syntax: "class_name <UniqueName>"', ], [ "The class icon must be separated by a comma.", ], [ '"class" syntax: "class <Name>:" or "class <Name> extends <BaseClass>:"', ], ], "raw": [ '"extends" constant must be a string.', 'Invalid "extends" syntax, expected string constant (path) and/or identifier (parent class).', '"class_name" syntax: "class_name <UniqueName>"', "The class icon must be separated by a comma.", '"class" syntax: "class <Name>:" or "class <Name> extends <BaseClass>:"', ], "code": ErrorCode.INVALID_CLASS_DECLARATION, },
120929
func assert_file_exists(file_path): var disp = 'expected [' + file_path + '] to exist.' var f = File.new() if(f.file_exists(file_path)): _pass(disp) else: _fail(disp) # ------------------------------------------------------------------------------ # Asserts that a file should not exist # ------------------------------------------------------------------------------ func assert_file_does_not_exist(file_path): var disp = 'expected [' + file_path + '] to NOT exist' var f = File.new() if(!f.file_exists(file_path)): _pass(disp) else: _fail(disp) # ------------------------------------------------------------------------------ # Asserts the specified file is empty # ------------------------------------------------------------------------------ func assert_file_empty(file_path): var disp = 'expected [' + file_path + '] to be empty' var f = File.new() if(f.file_exists(file_path) and gut.is_file_empty(file_path)): _pass(disp) else: _fail(disp) # ------------------------------------------------------------------------------ # Asserts the specified file is not empty # ------------------------------------------------------------------------------ func assert_file_not_empty(file_path): var disp = 'expected [' + file_path + '] to contain data' if(!gut.is_file_empty(file_path)): _pass(disp) else: _fail(disp) # ------------------------------------------------------------------------------ # Asserts the object has the specified method # ------------------------------------------------------------------------------ func assert_has_method(obj, method, text=''): var disp = _str(obj) + ' should have method: ' + method if(text != ''): disp = _str(obj) + ' ' + text assert_true(obj.has_method(method), disp) # Old deprecated method name func assert_get_set_methods(obj, property, default, set_to): _lgr.deprecated('assert_get_set_methods', 'assert_accessors') assert_accessors(obj, property, default, set_to) # ------------------------------------------------------------------------------ # Verifies the object has get and set methods for the property passed in. The # property isn't tied to anything, just a name to be appended to the end of # get_ and set_. Asserts the get_ and set_ methods exist, if not, it stops there. # If they exist then it asserts get_ returns the expected default then calls # set_ and asserts get_ has the value it was set to. # ------------------------------------------------------------------------------ func assert_accessors(obj, property, default, set_to): var fail_count = _summary.failed var get_func = 'get_' + property var set_func = 'set_' + property if(obj.has_method('is_' + property)): get_func = 'is_' + property assert_has_method(obj, get_func, 'should have getter starting with get_ or is_') assert_has_method(obj, set_func) # SHORT CIRCUIT if(_summary.failed > fail_count): return assert_eq(obj.call(get_func), default, 'It should have the expected default value.') obj.call(set_func, set_to) assert_eq(obj.call(get_func), set_to, 'The set value should have been returned.') # --------------------------------------------------------------------------- # Property search helper. Used to retrieve Dictionary of specified property # from passed object. Returns null if not found. # If provided, property_usage constrains the type of property returned by # passing either: # EDITOR_PROPERTY for properties defined as: export(int) var some_value # VARIABLE_PROPERTY for properties defined as: var another_value # --------------------------------------------------------------------------- func _find_object_property(obj, property_name, property_usage=null): var result = null var found = false var properties = obj.get_property_list() while !found and !properties.empty(): var property = properties.pop_back() if property['name'] == property_name: if property_usage == null or property['usage'] == property_usage: result = property found = true return result # ------------------------------------------------------------------------------ # Asserts a class exports a variable. # ------------------------------------------------------------------------------ func assert_exports(obj, property_name, type): var disp = 'expected %s to have editor property [%s]' % [_str(obj), property_name] var property = _find_object_property(obj, property_name, EDITOR_PROPERTY) if property != null: disp += ' of type [%s]. Got type [%s].' % [_strutils.types[type], _strutils.types[property['type']]] if property['type'] == type: _pass(disp) else: _fail(disp) else: _fail(disp) # ------------------------------------------------------------------------------ # Signal assertion helper. # # Verifies that the object and signal are valid for making signal assertions. # This will fail with specific messages that indicate why they are not valid. # This returns true/false to indicate if the object and signal are valid. # ------------------------------------------------------------------------------ func _can_make_signal_assertions(object, signal_name): return !(_fail_if_not_watching(object) or _fail_if_does_not_have_signal(object, signal_name)) # ------------------------------------------------------------------------------ # Check if an object is connected to a signal on another object. Returns True # if it is and false otherwise # ------------------------------------------------------------------------------ func _is_connected(signaler_obj, connect_to_obj, signal_name, method_name=""): if(method_name != ""): return signaler_obj.is_connected(signal_name, connect_to_obj, method_name) else: var connections = signaler_obj.get_signal_connection_list(signal_name) for conn in connections: if((conn.source == signaler_obj) and (conn.target == connect_to_obj)): return true return false # ------------------------------------------------------------------------------ # Watch the signals for an object. This must be called before you can make # any assertions about the signals themselves. # ------------------------------------------------------------------------------ func watch_signals(object): _signal_watcher.watch_signals(object) # ------------------------------------------------------------------------------ # Asserts that an object is connected to a signal on another object # # This will fail with specific messages if the target object is not connected # to the specified signal on the source object. # ------------------------------------------------------------------------------ func assert_connected(signaler_obj, connect_to_obj, signal_name, method_name=""): pass var method_disp = '' if (method_name != ""): method_disp = str(' using method: [', method_name, '] ') var disp = str('Expected object ', _str(signaler_obj),\ ' to be connected to signal: [', signal_name, '] on ',\ _str(connect_to_obj), method_disp) if(_is_connected(signaler_obj, connect_to_obj, signal_name, method_name)): _pass(disp) else: _fail(disp) # ------------------------------------------------------------------------------ # Asserts that an object is not connected to a signal on another object # # This will fail with specific messages if the target object is connected # to the specified signal on the source object. # ------------------------------------------------------------------------------ func assert_not_connected(signaler_obj, connect_to_obj, signal_name, method_name=""): var method_disp = '' if (method_name != ""): method_disp = str(' using method: [', method_name, '] ') var disp = str('Expected object ', _str(signaler_obj),\ ' to not be connected to signal: [', signal_name, '] on ',\ _str(connect_to_obj), method_disp) if(_is_connected(signaler_obj, connect_to_obj, signal_name, method_name)): _fail(disp) else: _pass(disp) # ------------------------------------------------------------------------------ # Asserts that a signal has been emitted at least once. # # This will fail with specific messages if the object is not being watched or # the object does not have the specified signal # ------------------------------------------------------------------------------ func assert_signal_emitted(object, signal_name, text=""): var disp = str('Expected object ', _str(object), ' to have emitted signal [', signal_name, ']: ', text) if(_can_make_signal_assertions(object, signal_name)): if(_signal_watcher.did_emit(object, signal_name)): _pass(disp) else: _fail(_get_fail_msg_including_emitted_signals(disp, object)) # ------------------------------------------------------------------------------ # Asserts that a signal has not been emitted. # # This will fail with specific messages if the object is not being watched or # the object does not have the specified signal # ------------------------------------------------------------------------------ func assert_signal_not_emitted(object, signal_name, text=""): var disp = str('Expected object ', _str(object), ' to NOT emit signal [', signal_name, ']: ', text) if(_can_make_signal_assertions(object, signal_name)): if(_signal_watcher.did_emit(object, signal_name)): _fail(disp) else: _pass(disp) # ------------------------------------------------------------------------------ # Asserts that a signal was fired with the specified parameters. The expected # parameters should be passed in as an array. An optional index can be passed # when a signal has fired more than once. The default is to retrieve the most # recent emission of the signal. # # This will fail with specific messages if the object is not being watched or # the object does not have the specified signal # ------------------------------------------------------------------------------
121043
extends Object # ResourceLoader is unreliable when it comes to cache. # Sub-resources get cached regardless of the argument passed to load function. # This is a workaround that generates a new file on a fly, # while making sure that there is no cache record for it. # This file is then used to load the resource, after which # the resource takes over the original path. static func load_fresh(resource_path: String) -> Resource: var resource = File.new() var error = resource.open(resource_path, File.READ) if error != OK: printerr("Failed to load resource '" + resource_path + "': Error code " + str(error)) return null var resource_ext = resource_path.get_extension() var random_index = randi() var intermediate_path = resource_path + "_temp_" + str(random_index) + "." + resource_ext while ResourceLoader.has_cached(intermediate_path): random_index = randi() intermediate_path = resource_path + "_temp_" + str(random_index) + "." + resource_ext var intermediate_resource = File.new() error = intermediate_resource.open(intermediate_path, File.WRITE) if error != OK: printerr("Failed to load resource '" + resource_path + "': Error code " + str(error)) return null var resource_content = resource.get_as_text() intermediate_resource.store_string(resource_content) intermediate_resource.close() resource.close() var actual_resource = ResourceLoader.load(intermediate_path, "", true) actual_resource.take_over_path(resource_path) var directory = Directory.new() directory.remove(intermediate_path) return actual_resource
121046
"Using own name in class file is not allowed (creates a cyclic reference)" "Can't load global class %IDENTIFIER%, cyclic reference?" "Identifier not found: %IDENTIFIER%" "'self' not present in static function!" "Invalid native class type '%NATIVE_TYPE%'." "Parser bug: unresolved data type." "Attempt to call a non-identifier." "Must use '%IDENTIFIER%' instead of 'self.%IDENTIFIER%' in getter." "Must use '%IDENTIFIER%' instead of 'self.%IDENTIFIER%' in setter." "'break'' not within loop" "'continue' not within loop" "Cyclic class reference for '%CLASS_NAME%'." "Parser bug: invalid inheritance." "Signal '%SIGNAL_NAME%' redefined (in current or parent class)" "Signal '%SIGNAL_NAME%' redefined (original in native class '%CLASS_NAME%')" "Expected end of statement (\"%STATEMENT_NAME%\"), got %TOKEN_NAME% (\"%IDENTIFIER%\") instead." "Expected end of statement (\"%STATEMENT_NAME%\"), got %TOKEN_NAME% instead." "':' expected at end of line." "Mixed tabs and spaces in indentation." "Expression expected" "Expected ',' or ')'" "Expected ')' in expression" "Expected string constant or identifier after '$' or '/'." "Path expected after $." "Expected '(' after 'preload'" "expected string constant as 'preload' argument." "Can't preload itself (use 'get_script()')." "Can't preload resource at path: %PATH%" "Expected ')' after 'preload' path" "Couldn't fully preload the script, possible cyclic reference or compilation error. Use \"load()\" instead if a cyclic reference is intended." "\"yield()\" can only be used inside function blocks." "Expected \"(\" after \"yield\"." "Expected \",\" after the first argument of \"yield\"." "Expected \")\" after the second argument of \"yield\"." "\"self\" isn't allowed in a static function or constant expression." "Built-in type constant or static function expected after \".\"." "Static constant '%CONSTANT_NAME%' not present in built-in type %BUILTIN_TYPE%." "Using assignment with operation on a variable that was never assigned." "Misplaced 'not'." "Expected identifier before 'is' operator" "Unterminated array" "expression or ']' expected" "',' or ']' expected" "Unterminated dictionary" "':' expected" "value expected" "key or '}' expected" "',' or '}' expected" "Duplicate key found in Dictionary literal" "Expected '(' for parent function call." "Error parsing expression, misplaced: %TOKEN_NAME%" "Expected identifier as member" "Expected ']'" "Unexpected 'as'." "Expected type after 'as'." "Unexpected assign." "GDScriptParser bug, invalid operator in expression: %EXPRESSION%" "Unexpected operator" "Yet another parser bug...." "Unexpected end of expression..." "Parser bug..." "Expected else after ternary if." "Expected value after ternary else." "Unexpected two consecutive operators after ternary if." "Unexpected two consecutive operators after ternary else." "Unexpected two consecutive operators." "Invalid argument (#%ARGUMENT_NUMBER%) for '%TYPE_NAME%' constructor." "Too many arguments for '%TYPE_NAME%' constructor." "Too few arguments for '%TYPE_NAME%' constructor." "Invalid arguments for '%TYPE_NAME%' constructor." "Invalid argument (#%ARGUMENT_NUMBER%) for '%TYPE_NAME%' intrinsic function." "Too many arguments for '%TYPE_NAME%' intrinsic function." "Too few arguments for '%TYPE_NAME%' intrinsic function." "Invalid arguments for '%TYPE_NAME%' intrinsic function." "invalid index in constant expression" "invalid index '%INDEX_NAME%' in constant expression" "Can't assign to constant" "Can't assign to self." "Can't assign to an expression" "Invalid operand for unary operator" "Invalid operands for operator" "Invalid export type. Only built-in and native resource types can be exported." "'..' pattern only allowed at the end of an array pattern" "Not a valid pattern" "Expected identifier for binding variable name." "Binding name of '%BINDING_NAME%' is already declared in this scope." "'..' pattern only allowed at the end of a dictionary pattern" "Not a valid key in pattern" "Not a constant expression as key" "Expected pattern in dictionary value" "Not a valid pattern" "Expect constant expression or variables in a pattern" "Invalid operator in pattern. Only index (`A.B`) is allowed" "Only constant expression or variables allowed in a pattern" "Only constant expressions or variables allowed in a pattern" "Cannot use bindings with multipattern." "Expected block in pattern branch" "The pattern type (%PATTERN_TYPE%) isn't compatible with the type of the value to match (%MATCH_TYPE%)." "Cannot match an array pattern with a non-array expression." "Cannot match an dictionary pattern with a non-dictionary expression." "Multipatterns can't contain bindings" "Parser bug: missing pattern bind variable." "Mixed tabs and spaces in indentation." "Expected \";\" or a line break." "Expected an identifier for the local variable name." "Variable \"%VARIABLE_NAME%\" already defined in the scope (at line %LINE_NUMBER%)." "Expected a type for the variable." "Expected an indented block after \"if\"." "Invalid indentation." "Expected an indented block after \"elif\"." "Invalid indentation." "Expected an indented block after \"else\"." "Expected an indented block after \"while\"." "Identifier expected after \"for\"." "\"in\" expected after identifier." "Expected indented block after \"for\"." "Unexpected keyword \"continue\" outside a loop." "Unexpected keyword \"break\" outside a loop." "Expected indented pattern matching block after \"match\"." "Expected '(' after assert" "Wrong number of arguments, expected 1 or 2" "Unexpected ':=', use '=' instead. Expected end of statement after expression." "Expected end of statement after expression, got %TOKEN_NAME% instead." "Mixed tabs and spaces in indentation." "Unexpected indentation." "Invalid indentation. Bug?" "Unindent does not match any outer indentation level." "Mixed tabs and spaces in indentation." "\"extends\" can only be present once per script." "\"extends\" must be used before anything else." "\"extends\" constant must be a string." "Invalid \"extends\" syntax, expected string constant (path) and/or identifier (parent class)." "\"class_name\" is only valid for the main class namespace." "\"class_name\" isn't allowed in built-in scripts." "\"class_name\" syntax: \"class_name <UniqueName>\"" "\"class_name\" can only be present once per script." "Unique global class \"%CLASS_NAME%\" already exists at path: %PATH%" "The class \"%CLASS_NAME%\" shadows a native class." "The class \"%CLASS_NAME%\" conflicts with the AutoLoad singleton of the same name, and is therefore redundant. Remove the class_name declaration to fix this error." "No class icon found at: %PATH%" "The optional parameter after \"class_name\" must be a string constant file path to an icon." "The class icon must be separated by a comma." "The \"tool\" keyword can only be present once per script." "\"class\" syntax: \"class <Name>:\" or \"class <Name> extends <BaseClass>:\"" "The class \"%CLASS_NAME%\" shadows a native class." "Can't override name of the unique global class \"%CLASS_NAME%\". It already exists at: %PATH%" "Another class named \"%CLASS_NAME%\" already exists in this scope (at line %LINE_NUMBER%)." "A constant named \"%CONSTANT_NAME%\" already exists in the outer class scope (at line%LINE_NUMBER%)." "A variable named \"%VARIABLE_NAME%\" already exists in the outer class scope (at line %LINE_NUMBER%)." "Indented block expected." "Expected \"func\"." "Expected an identifier after \"func\" (syntax: \"func <identifier>([arguments]):\")." "The function \"%FUNCTION_NAME%\" already exists in this class (at line %LINE_NUMBER%)." "The function \"%FUNCTION_NAME%\" already exists in this class (at line %LINE_NUMBER%)." "Expected \"(\" after the identifier (syntax: \"func <identifier>([arguments]):\" )." "Expected an identifier for an argument." "The argument name \"%ARGUMENT_NAME%\" is defined multiple times." "Expected a type for an argument." "Default parameter expected." "default argument must be constant" "Expected \",\" or \")\"." "The constructor cannot be static." "Expected \"(\" for parent constructor arguments." "Expected \",\" or \")\"." "Parent constructor call found for a class without inheritance." "Expected a return type for the function." "Indented block expected after declaration of \"%FUNCTION_NAME%\" function." "Expected an identifier after \"signal\"." "The signal \"%SIGNAL_NAME%\" already exists in this class (at line: %LINE_NUMBER%)." "Expected an identifier in a \"signal\" argument." "Expected \",\" or \")\" after a \"signal\" parameter identifier." "Can't export null type." "Can't export raw object type." "Expected \",\" in the bit flags hint." "Expected a string constant in the named bit flags hint." "Expected \")\" or \",\" in the named bit flags hint." "Expected \")\" in the layers 2D render hint." "Expected \")\" in the layers 2D physics hint." "Expected \")\" in the layers 3D render hint." "Expected \")\" in the layers 3D physics hint."
121053
# Compiling for web Because I need this often, here's a one-liner to compile for web: ```sh rm -rf build/web && \ mkdir -p build/web && \ godot -v --export "HTML5" build/web/index.html && \ cp -r html_export/static/* build/web && \ cd build/web && \ python -m http.server 8000 && \ cd - ``` (This assumes `python` and `godot` are available on `$PATH`)
121069
# Global signal bus registered as an auto-loaded node. Allows us to emit events # different nodes listen to without having to bubble signals through long chains # of UI nodes. extends Node signal lesson_started(lesson) signal lesson_completed(lesson) signal lesson_reading_block(block, previous_blocks) signal quiz_completed(quiz) signal practice_started(practice) signal practice_run_completed() signal practice_completed(practice) signal practice_next_requested(practice) signal practice_previous_requested(practice) signal practice_requested(practice) signal course_completed(course) signal settings_requested signal report_form_requested signal fullscreen_toggled signal font_size_scale_changed(new_font_size)
121094
extends KinematicBody2D export var jump_speed := 200 export var jump_max_height := 100.0 export var gravity := 4000 var is_walking := false onready var animated_sprite := $AnimatedSprite as AnimatedSprite var _velocity_y = 0.0 var _jump_starting_point := 0.0 func _ready() -> void: add_to_group("Player") func _physics_process(delta: float) -> void: if Input.is_action_pressed("jump"): # EXPORT jump if is_on_floor(): _jump_starting_point = position.y _velocity_y -= jump_speed else: var jump_height := _jump_starting_point - position.y var is_going_up: bool = _velocity_y < 0 var is_under_apex: bool = jump_height < jump_max_height if is_going_up and is_under_apex: _velocity_y -= jump_speed # /EXPORT jump if Input.is_action_just_pressed("jump"): animated_sprite.play("jump") elif is_on_floor() and is_walking: animated_sprite.play("walk") _velocity_y += gravity * delta var velocity := Vector2(0, _velocity_y) _velocity_y = move_and_slide(velocity, Vector2.UP).y
121098
[gd_scene load_steps=2 format=2] [ext_resource path="res://game_demos/run_and_jump/Obstacle.gd" type="Script" id=1] [node name="Area2D" type="Area2D"] script = ExtResource( 1 ) [node name="CollisionShape2D" type="CollisionShape2D" parent="."] position = Vector2( 0, -0.203634 ) [node name="Sprite" type="Sprite" parent="."]
121105
[gd_resource type="Resource" load_steps=3 format=2] [ext_resource path="res://addons/gdscript-slice-exporter/collections/ScriptProperties.gd" type="Script" id=1] [ext_resource path="res://game_demos/run_and_jump/Player.gd" type="Script" id=2] [resource] script = ExtResource( 1 ) nodes_paths = [ NodePath("Level/Player") ] script_file = ExtResource( 2 ) original_script = "extends KinematicBody2D export var jump_speed := 200 export var jump_max_height := 100.0 export var gravity := 4000 var is_walking := false onready var animated_sprite := $AnimatedSprite as AnimatedSprite var _velocity_y = 0.0 var _jump_starting_point := 0.0 func _ready() -> void: add_to_group(\"Player\") func _physics_process(delta: float) -> void: if Input.is_action_pressed(\"jump\"): # EXPORT jump if is_on_floor(): _jump_starting_point = position.y _velocity_y -= jump_speed else: var jump_height := _jump_starting_point - position.y var is_going_up: bool = _velocity_y < 0 var is_under_apex: bool = jump_height < jump_max_height if is_going_up and is_under_apex: _velocity_y -= jump_speed # /EXPORT jump if Input.is_action_just_pressed(\"jump\"): animated_sprite.play(\"jump\") elif is_on_floor() and is_walking: animated_sprite.play(\"walk\") _velocity_y += gravity * delta var velocity := Vector2(0, _velocity_y) _velocity_y = move_and_slide(velocity, Vector2.UP).y "
121151
- Fix editor crash when unsupported `Resource` is dropped in scene ([GH-89126](https://github.com/godotengine/godot/pull/89126)). - Update lock and group button state when selection changed in CanvasItemEditor ([GH-89132](https://github.com/godotengine/godot/pull/89132)). - Expose TileMapLayer ([GH-89179](https://github.com/godotengine/godot/pull/89179)). - Make CanvasItem's "drawing outside of NOTIFICATION_DRAW" error a macro ([GH-89298](https://github.com/godotengine/godot/pull/89298)). - Fix center view button appears outside the GenericTilePolygonEditor ([GH-89434](https://github.com/godotengine/godot/pull/89434)). - Fix call queue problems when loading TileSet ([GH-89493](https://github.com/godotengine/godot/pull/89493)). - Avoid passing zoom scale for ParallaxLayer mirror ([GH-89572](https://github.com/godotengine/godot/pull/89572)). - Account for scale in scroll logic for `Parallax2D` ([GH-89627](https://github.com/godotengine/godot/pull/89627)). - Fix Path2D's add new point's UndoRedo bug ([GH-89874](https://github.com/godotengine/godot/pull/89874)). - TileSet: Expose `TileData.is_valid_terrain_peering_bit` ([GH-89911](https://github.com/godotengine/godot/pull/89911)). - Replace Clipper1 library by Clipper2 library ([GH-90153](https://github.com/godotengine/godot/pull/90153)). - Ensure `Camera2D.position_smoothing_speed` is non-negative ([GH-90167](https://github.com/godotengine/godot/pull/90167)). - Correctly update TileMapLayer highlighting when disabling it ([GH-90204](https://github.com/godotengine/godot/pull/90204)). - Fix "no cached rect" errors in TileMapLayer editor ([GH-90207](https://github.com/godotengine/godot/pull/90207)). - Fix strange visual bug with camera and external change ([GH-90317](https://github.com/godotengine/godot/pull/90317)). - TileSet: Don't save angular and linear physics velocities if they have their default values ([GH-90384](https://github.com/godotengine/godot/pull/90384)). - Fix selection rect drawing in `TileSet` editor when create/remove tiles with separation ([GH-90709](https://github.com/godotengine/godot/pull/90709)). - Fix rendering transform of Y-sorted branch-root ([GH-90749](https://github.com/godotengine/godot/pull/90749)). - Fix TileMap enabling Y-sort on child nodes ([GH-90752](https://github.com/godotengine/godot/pull/90752)). - Reuse single erase pattern in tile editor ([GH-90817](https://github.com/godotengine/godot/pull/90817)). - Editor: Fix crash when editing TileMap ([GH-90849](https://github.com/godotengine/godot/pull/90849)). - Don't store TileMapLayer data if empty ([GH-90907](https://github.com/godotengine/godot/pull/90907)). - Fix typo in Camera2D node's anchor mode ([GH-91076](https://github.com/godotengine/godot/pull/91076)). - Fix Parallax2D physics interpolation ([GH-91706](https://github.com/godotengine/godot/pull/91706)). - Add support for AtlasTexture in `draw_polygon()` ([GH-91724](https://github.com/godotengine/godot/pull/91724)). - Fix 2d editor selection persisting after application loses focus ([GH-91732](https://github.com/godotengine/godot/pull/91732)). - Fix TileMap selection pattern being needlessly reorganized ([GH-91905](https://github.com/godotengine/godot/pull/91905)). - Allow selecting TileMapLayers by clicking them ([GH-92016](https://github.com/godotengine/godot/pull/92016)). - Fix tile polygon grid not covering whole tile ([GH-92171](https://github.com/godotengine/godot/pull/92171)). - Remove some TileMap dependencies from TileMapLayer ([GH-92194](https://github.com/godotengine/godot/pull/92194)). - Display custom data name instead of indices in TileData inspector ([GH-92322](https://github.com/godotengine/godot/pull/92322)). - Fix TileSet caching wrong collision layer shapes for shapes comprising several polygons ([GH-92373](https://github.com/godotengine/godot/pull/92373)). - Optimize usage of position icon in 2D editor ([GH-92392](https://github.com/godotengine/godot/pull/92392)). - Fix incorrect cull boundary for scaled and repeated Parallax2D children ([GH-92763](https://github.com/godotengine/godot/pull/92763)). - Implement X-draw-order switch in TileMapLayer ([GH-92787](https://github.com/godotengine/godot/pull/92787)). - Make texture filtering in TileAtlasView consistent ([GH-92926](https://github.com/godotengine/godot/pull/92926)). - Update Camera2D gizmos when screen size changes ([GH-92992](https://github.com/godotengine/godot/pull/92992)). - Fix tile polygon editor grid and missing update ([GH-93047](https://github.com/godotengine/godot/pull/93047)). - Allow canceling actions in Path2D editor ([GH-93087](https://github.com/godotengine/godot/pull/93087)). - Store TileMapLayer selection in scene's history ([GH-93475](https://github.com/godotengine/godot/pull/93475)). - Fix snapping lines don't disappearing after drag anchors ([GH-93527](https://github.com/godotengine/godot/pull/93527)). - Fix TileSet property painter popup showing clear color ([GH-93609](https://github.com/godotengine/godot/pull/93609)). - Prevent selecting when a CanvasItem is selected ([GH-93671](https://github.com/godotengine/godot/pull/93671)). - Fix some TileMapLayer editing problems ([GH-93747](https://github.com/godotengine/godot/pull/93747)). - Fix RMB erasing of tiles ([GH-93850](https://github.com/godotengine/godot/pull/93850)). - Fix crash in tile physics editor ([GH-93971](https://github.com/godotengine/godot/pull/93971)). - Fix crash in the TileMapLayer editor when using editable children ([GH-93974](https://github.com/godotengine/godot/pull/93974)). - Add pixel snap for `Parallax2D` ([GH-94014](https://github.com/godotengine/godot/pull/94014)). - Remove unused assignment in Parallax2D ([GH-94035](https://github.com/godotengine/godot/pull/94035)). - Fixes/node configuration warning dialog text ([GH-94147](https://github.com/godotengine/godot/pull/94147)). - Make sure that selected tile source is remembered ([GH-94356](https://github.com/godotengine/godot/pull/94356)).
121153
- Fix `Path3D` tilt gizmo raycasting against local plane ([GH-91109](https://github.com/godotengine/godot/pull/91109)). - Simplify the GPUParticles3D editor gizmo to improve readability ([GH-91226](https://github.com/godotengine/godot/pull/91226)). - Add MultiNodeEdit support to MeshInstance3D editor ([GH-91620](https://github.com/godotengine/godot/pull/91620)). - Disallow selection of ownerless nodes ([GH-92188](https://github.com/godotengine/godot/pull/92188)). - Fix bounding box glitch ([GH-92275](https://github.com/godotengine/godot/pull/92275)). - Fix null `debug_shape` being updated when `CollisionObject3D`'s transform changed ([GH-92302](https://github.com/godotengine/godot/pull/92302)). - Make CSG shape dirty after changing Snap ([GH-93242](https://github.com/godotengine/godot/pull/93242)). - Improve `SurfaceTool::generate_tangents` UV error message ([GH-93326](https://github.com/godotengine/godot/pull/93326)). - Fix invalid inheritance of `OccluderInstance3D` ([GH-93354](https://github.com/godotengine/godot/pull/93354)). - Fix Subviewport keeps using removed Camera3D child ([GH-93377](https://github.com/godotengine/godot/pull/93377)). - Fix crash in Node3DEditorViewport selecting on empty scene ([GH-93404](https://github.com/godotengine/godot/pull/93404)). - Improve viewport rotation gizmo drawing ([GH-93639](https://github.com/godotengine/godot/pull/93639)). - Add alternative shortcut for Align Transform to View in the 3D editor ([GH-93675](https://github.com/godotengine/godot/pull/93675)). - Fix "selectable nodes at position clicked" feature in 3D editor ([GH-94387](https://github.com/godotengine/godot/pull/94387)).
121177
revent race condition on initial breakpoints from DAP ([GH-84895](https://github.com/godotengine/godot/pull/84895)). - Do not bother with line colors if `line_number_gutter` is not yet calculated ([GH-84907](https://github.com/godotengine/godot/pull/84907)). - Improve search/replace bar behavior ([GH-84932](https://github.com/godotengine/godot/pull/84932)). - Add an option to center children around the new parent when reparenting ([GH-84995](https://github.com/godotengine/godot/pull/84995)). - Fix issue with 3D scene drag and drop preview node ([GH-85087](https://github.com/godotengine/godot/pull/85087)). - Don't abort loading when `ext_resource` is missing ([GH-85159](https://github.com/godotengine/godot/pull/85159)). - Add further details on properties returning `Packed*Array` ([GH-85207](https://github.com/godotengine/godot/pull/85207)). - Don't insert newline while saving ([GH-85228](https://github.com/godotengine/godot/pull/85228)). - Use the flat button style on switches in scene and node docks ([GH-85236](https://github.com/godotengine/godot/pull/85236)). - Use `SafeNumeric` to protect `max_index` in ImportThreadData ([GH-85295](https://github.com/godotengine/godot/pull/85295)). - Make copy & paste params skip `resource_path` ([GH-85362](https://github.com/godotengine/godot/pull/85362)). - Improve SceneTreeEditor usability ([GH-85386](https://github.com/godotengine/godot/pull/85386)). - Make it possible to show code hint and code completion at the same time ([GH-85436](https://github.com/godotengine/godot/pull/85436)). - Improve Control hiding in PluginConfigDialog ([GH-85470](https://github.com/godotengine/godot/pull/85470)). - Update NodePaths only in built-in resources ([GH-85502](https://github.com/godotengine/godot/pull/85502)). - Expose `Node.is_part_of_edited_scene()` ([GH-85515](https://github.com/godotengine/godot/pull/85515)). - Fix for Cmd-B shortcut conflict on macOS ([GH-85527](https://github.com/godotengine/godot/pull/85527)). - Fix SnapGrid is almost invisible in light theme ([GH-85585](https://github.com/godotengine/godot/pull/85585)). - Defer creating new editor process in "Quit to Project List" just like in "Reload Current Project" ([GH-85654](https://github.com/godotengine/godot/pull/85654)). - Mark `gui/theme/custom` and `gui/theme/custom_font` as basic properties ([GH-85660](https://github.com/godotengine/godot/pull/85660)). - Add separate feature tags for editor runtime ([GH-85678](https://github.com/godotengine/godot/pull/85678)). - Hide Node dock successfully on undo/redo and deletion ([GH-85686](https://github.com/godotengine/godot/pull/85686)). - Fix theme application in various editor dialogs ([GH-85745](https://github.com/godotengine/godot/pull/85745)). - Improve engine startup/shutdown benchmarks ([GH-85885](https://github.com/godotengine/godot/pull/85885)). - Add a editor FileSystem dock action to open a terminal in selected folder ([GH-85923](https://github.com/godotengine/godot/pull/85923)). - Stop the searching of `find in files` in folders that have `.gdignore` ([GH-85943](https://github.com/godotengine/godot/pull/85943)). - Tweak Help menu icons for better visibility of commonly used items ([GH-85978](https://github.com/godotengine/godot/pull/85978)). - Disable Add button when theme item name is empty ([GH-86044](https://github.com/godotengine/godot/pull/86044)). - Fix "Class name cannot be empty" error when sorting no import files sort by type ([GH-86064](https://github.com/godotengine/godot/pull/86064)). - Stop using `RTR()` inside the "editor" folder ([GH-86143](https://github.com/godotengine/godot/pull/86143)). - Properly select the newly duplicated file ([GH-86164](https://github.com/godotengine/godot/pull/86164)). - Fix file disappearing when renaming dependencies ([GH-86177](https://github.com/godotengine/godot/pull/86177)). - Fix duplicating multiple nodes at different depths in `SceneTreeDock` ([GH-86211](https://github.com/godotengine/godot/pull/86211)). - Add option to add built-in strings in the POT generation ([GH-86222](https://github.com/godotengine/godot/pull/86222)). - Use `set_value_no_signal` in editor property code ([GH-86266](https://github.com/godotengine/godot/pull/86266)). - Allow node visibility to work with custom user-provided node types ([GH-86268](https://github.com/godotengine/godot/pull/86268)). - Optimize scanning routines in the project manager ([GH-86271](https://github.com/godotengine/godot/pull/86271)). - Fix scene dock search losing its default tooltip after typing an invalid filter ([GH-86278](https://github.com/godotengine/godot/pull/86278)). - Add input action name to window title in input map editor ([GH-86280](https://github.com/godotengine/godot/pull/86280)). - Add hover highlight to main editor buttons ([GH-86378](https://github.com/godotengine/godot/pull/86378)). - Strip edges of editor layout names ([GH-86386](https://github.com/godotengine/godot/pull/86386)). - Clear sub-resources list when no sub-resource exists ([GH-86388](https://github.com/godotengine/godot/pull/86388)). - Fix internal profiling button being visible when disabled in settings ([GH-86398](https://github.com/godotengine/godot/pull/86398)). - Improve action name for ungroup button in Scene dock ([GH-86431](https://github.com/godotengine/godot/pull/86431)). - Improve performance of the 'Create New Node' dialog ([GH-86447](https://github.com/godotengine/godot/pull/86447)). - Use ObjectID's instead of node pointers to track scene groups to prevent crash ([GH-86462](https://github.com/godotengine/godot/pull/86462)). - Store horizontal and vertical split offsets separately in FileSystem dock ([GH-86476](https://github.com/godotengine/godot/pull/86476)). - Fix scene parser reading non-built-in scripts for POT generation ([GH-86479](https://github.com/godotengine/godot/pull/86479)). - Improve `EditorDirDialog` ([GH-86486](https://github.com/godotengine/godot/pull/86486)). - Improve Path2D editing ([GH-86542](https://github.com/godotengine/godot/pull/86542)). - Project upgrade tool: Better space handling in "export" ([GH-86598](https://github.com/godotengine/godot/pull/86598)). - Don't update tree on deselect ([GH-86605](https://github.com/godotengine/godot/pull/86605)). - Add option for editor to follow system theme and accent colors ([GH-86610](https://github.com/godotengine/godot/pull/86610)). - Fix possible crash (use after free) in ScriptTextEditor ([GH-86633](https://github.com/godotengine/godot/pull/86633)). - Improved synchronization of Transforms during live debug sessions ([GH-86659](https://github.com/godotengine/godot/pull/86659)). - Automatically add path to built-in shaders ([GH-86668](https://github.com/godotengine/godot/pull/86668)). - Stop escaping `'` on POT generation ([GH-86669](https://github.com/godotengine/godot/pull/86669)). - I
121179
ix data race against `EditorFileSystem.scanning_changes_done` ([GH-88124](https://github.com/godotengine/godot/pull/88124)). - Use `SafeFlag` for `EditorHTTPServer.server_quit` ([GH-88155](https://github.com/godotengine/godot/pull/88155)). - Use highlighted version of the tab icon in the bottom file system dock ([GH-88191](https://github.com/godotengine/godot/pull/88191)). - Asset Library author link, description popup size and UX details ([GH-88229](https://github.com/godotengine/godot/pull/88229)). - Fix update property for dictionaries so that it updates only what is necessary ([GH-88231](https://github.com/godotengine/godot/pull/88231)). - Fix an edge case bug in drag-and-drop Node3D spawning ([GH-88269](https://github.com/godotengine/godot/pull/88269)). - Rework how script is edited when clicking icon ([GH-88288](https://github.com/godotengine/godot/pull/88288)). - Add support for search shortcut to signal connection dialog ([GH-88317](https://github.com/godotengine/godot/pull/88317)). - Fix skipping normal category followed by custom one ([GH-88318](https://github.com/godotengine/godot/pull/88318)). - Focus value editor on type change in Dictionary and Array editors ([GH-88322](https://github.com/godotengine/godot/pull/88322)). - Add const lvalue ref to `editor/*` container parameters ([GH-88368](https://github.com/godotengine/godot/pull/88368)). - Improve look of Donors list in Editor's About ([GH-88370](https://github.com/godotengine/godot/pull/88370)). - Move EditorNode setting registration so they are in class reference ([GH-88380](https://github.com/godotengine/godot/pull/88380)). - Fix Skeleton3D insert key tooltips ([GH-88386](https://github.com/godotengine/godot/pull/88386)). - Fix resource previews not created in compatibility rendering ([GH-88391](https://github.com/godotengine/godot/pull/88391)). - Show keywords in `EditorHelpSearch` ([GH-88450](https://github.com/godotengine/godot/pull/88450)). - Hide Search Results by default and show it on first search ([GH-88465](https://github.com/godotengine/godot/pull/88465)). - Improve merging of docs on generation ([GH-88514](https://github.com/godotengine/godot/pull/88514)). - Add separate program case for Godot Resources ([GH-88523](https://github.com/godotengine/godot/pull/88523)). - Fix crash on documentation generation on macOS ([GH-88545](https://github.com/godotengine/godot/pull/88545)). - Fix crash on changing resource type of dictionary new key/value while editing the resource ([GH-88572](https://github.com/godotengine/godot/pull/88572)). - Add `android` to auto-generated `.gitignore` ([GH-88591](https://github.com/godotengine/godot/pull/88591)). - Remove error when property is outside inspector ([GH-88597](https://github.com/godotengine/godot/pull/88597)). - Improve user experience for VCS metadata generator menu button to mitigate accidentally overriding ([GH-88609](https://github.com/godotengine/godot/pull/88609)). - Add a `h_separation` between icons in `CheckButton`/`CheckBox` ([GH-88615](https://github.com/godotengine/godot/pull/88615)). - Dictionary Editor: Keep the type of the last added item ([GH-88636](https://github.com/godotengine/godot/pull/88636)). - Fix editor hover style margins when Draw Extra Borders is enabled ([GH-88652](https://github.com/godotengine/godot/pull/88652)). - Add tokenized search support to Quick Open dialog and FileSystem filter ([GH-88660](https://github.com/godotengine/godot/pull/88660)). - Remove some redundant method calls from ScriptEditor ([GH-88675](https://github.com/godotengine/godot/pull/88675)). - Improve Run Instances Dialog ([GH-88685](https://github.com/godotengine/godot/pull/88685)). - Fix undo/redo behavior of ColorPicker and add ability to cancel/confirm color selection ([GH-88690](https://github.com/godotengine/godot/pull/88690)). - Fix leak of scene used for customization during export ([GH-88726](https://github.com/godotengine/godot/pull/88726)). - Fix removing element in array inspector not changing page when emptying page ([GH-88731](https://github.com/godotengine/godot/pull/88731)). - Fix the text editor theme not being applied on editor start ([GH-88742](https://github.com/godotengine/godot/pull/88742)). - Inspector `(N changes)` indicator propagates upwards ([GH-88814](https://github.com/godotengine/godot/pull/88814)). - Fix toggling a plugin makes its name black ([GH-88817](https://github.com/godotengine/godot/pull/88817)). - Add create folder icon ([GH-88825](https://github.com/godotengine/godot/pull/88825)). - Add browse folder and browse file icons ([GH-88827](https://github.com/godotengine/godot/pull/88827)). - Save scene and global checkbox options of History window ([GH-88833](https://github.com/godotengine/godot/pull/88833)). - Fix paste Value can empty a dictionary depending on right-click location ([GH-88849](https://github.com/godotengine/godot/pull/88849)). - Remove redundant space after enum/flags word in editor docs ([GH-88911](https://github.com/godotengine/godot/pull/88911)). - Modify shortcut for closing scene on macOS only ([GH-88913](https://github.com/godotengine/godot/pull/88913)). - Allow docks to be closed and opened ([GH-89017](https://github.com/godotengine/godot/pull/89017)). - Add autocompletion for EditorSettings' methods ([GH-89043](https://github.com/godotengine/godot/pull/89043)). - Use `META_UNDERLINE_ON_HOVER` in built-in class reference ([GH-89049](https://github.com/godotengine/godot/pull/89049)). - Display deprecated/experimental messages in tooltips ([GH-89058](https://github.com/godotengine/godot/pull/89058)). - Remember search text in Find/Replace in Files dialog ([GH-89085](https://github.com/godotengine/godot/pull/89085)). - Improve how Project & Editor Settings look in built-in docs ([GH-89086](https://github.com/godotengine/godot/pull/89086)). - Do not attempt to set cursor shape in headless mode ([GH-89099](https://github.com/godotengine/godot/pull/89099)). - Add missing `variablesReference` field to DAP `evaluate` request ([GH-89110](https://github.com/godotengine/godot/pull/89110)). - Fix undo action names for node replacement ([GH-89121](https://github.com/godotengine/godot/pull/89121)). - Fix documentation of localization related editor settings ([GH-89135](https://github.com/godotengine/godot/pull/89135)). - Change Editable Children menu action to be keyboard shortcuttable ([GH-89142](https://github.com/godotengine/godot/pull/89142)). - Add Enter shortcut to add a shader global in the editor ([GH-89184](https://github.com/godotengine/godot/pull/89184)). - Fix AssetLibrary not going online when clicking button ([GH-89200](https://github.com/godotengine/godot/pull/89200)). - Fix wrong undo-redo action when dropping files containing circular dependencies ([GH-89204](https://github.com/godotengine/godot/pull/89204)). - Don't refresh mirrors for development builds in editor export template manager ([GH-89236](https://github.com/godotengine/godot/pull/89236)). - A
121199
iversal: Fix texture decompression ([GH-88676](https://github.com/godotengine/godot/pull/88676)). - Properly calculate binormal when creating SurfaceTool from arrays ([GH-88725](https://github.com/godotengine/godot/pull/88725)). - Multiple fixes for compressed meshes ([GH-88738](https://github.com/godotengine/godot/pull/88738)). - Allow preserving the initial bone pose in rest fixer ([GH-88821](https://github.com/godotengine/godot/pull/88821)). - EditorFileSystem: Add verbose print for file being (re)imported ([GH-88904](https://github.com/godotengine/godot/pull/88904)). - Fix wrong indexing when generating dummy tangents in GLTF import ([GH-88931](https://github.com/godotengine/godot/pull/88931)). - Only store vertices referenced by the indices per surface in the glTF importer ([GH-89418](https://github.com/godotengine/godot/pull/89418)). - BasisUniversal: Fix artifacts on images with resolutions not divisible by 4 ([GH-89426](https://github.com/godotengine/godot/pull/89426)). - Default to trimesh for generated collision shapes in Advanced Import Settings ([GH-89461](https://github.com/godotengine/godot/pull/89461)). - Fix method bindings in FBXDocument by making them virtual in GLTFDocument ([GH-89532](https://github.com/godotengine/godot/pull/89532)). - GLTF: Extract converting hull points to mesh to a helper function ([GH-89542](https://github.com/godotengine/godot/pull/89542)). - Fix crash when columns are skipped in CSV translation ([GH-89573](https://github.com/godotengine/godot/pull/89573)). - Fix import and saving related crashes ([GH-89780](https://github.com/godotengine/godot/pull/89780)). - Fix 2 bugs with scale of position tracks in rest fixer ([GH-90065](https://github.com/godotengine/godot/pull/90065)). - GLTF export: Propagate `property_list_changed` from extensions ([GH-90225](https://github.com/godotengine/godot/pull/90225)). - Separate Shape3D resource logic in GLTFPhysicsShape ([GH-90230](https://github.com/godotengine/godot/pull/90230)). - Fix `GLTFDocument.append_from_scene` crash on null node ([GH-90505](https://github.com/godotengine/godot/pull/90505)). - Fix errors when re-importing 3D asset files ([GH-90531](https://github.com/godotengine/godot/pull/90531)). - FBX: Fix material colors ([GH-90554](https://github.com/godotengine/godot/pull/90554)). - Rename accessor GLTFType to GLTFAccessorType, fix verbose prints, document GLTFAccessor ([GH-90560](https://github.com/godotengine/godot/pull/90560)). - Fix error when loading SVG imported as Image ([GH-90573](https://github.com/godotengine/godot/pull/90573)). - Fix FBX texture path resolving ([GH-90635](https://github.com/godotengine/godot/pull/90635)). - Remove unused Make Streamable option from scene import dialog ([GH-90722](https://github.com/godotengine/godot/pull/90722)). - Fix FBX and glTF when root nodes are skeleton bones ([GH-90789](https://github.com/godotengine/godot/pull/90789)). - Resolve bind poses from FBX clusters instead of FBX poses ([GH-91036](https://github.com/godotengine/godot/pull/91036)). - fbx: Avoid name conflict with humanoid "Root" bone ([GH-91045](https://github.com/godotengine/godot/pull/91045)). - Fix errors/crashes related to skipped imports ([GH-91078](https://github.com/godotengine/godot/pull/91078)). - Enable tangents in blend shape format when using normals ([GH-91372](https://github.com/godotengine/godot/pull/91372)). - FBX: Fix handling missing skins using ufbx importer ([GH-91526](https://github.com/godotengine/godot/pull/91526)). - FBX: Print ufbx load warnings on import ([GH-91529](https://github.com/godotengine/godot/pull/91529)). - GLTF export improvements ([GH-91783](https://github.com/godotengine/godot/pull/91783)). - Editor: Ensure font image rows/columns are positive ([GH-91829](https://github.com/godotengine/godot/pull/91829)). - Improve memory usage for image import and `PortableCompressedTexture2D` ([GH-92179](https://github.com/godotengine/godot/pull/92179)). - FBX: Change trimming default and use FBX2glTF for compatibility ([GH-92197](https://github.com/godotengine/godot/pull/92197)). - Fix script properties being lost and prevent node reference corruption upon scene reimport ([GH-92279](https://github.com/godotengine/godot/pull/92279)). - Fix reimporting assets with csv in the project ([GH-92320](https://github.com/godotengine/godot/pull/92320)). - Fix GLTFDocument so it can export CSG Meshes correctly ([GH-92368](https://github.com/godotengine/godot/pull/92368)). - Avoid crash when importing .glsl in headless ([GH-92539](https://github.com/godotengine/godot/pull/92539)). - Rename FBX2glTF binary path setting back to 4.2 name ([GH-92571](https://github.com/godotengine/godot/pull/92571)). - Fix same importer will be added multiple times in `get_importers_for_extension` ([GH-92718](https://github.com/godotengine/godot/pull/92718)). - Fix Keep/Skip File import selection crash ([GH-92815](https://github.com/godotengine/godot/pull/92815)). - Fix incorrect camera transform of animation view in the import window ([GH-92974](https://github.com/godotengine/godot/pull/92974)). - [Image Font Importer] Fix reading advance after hex/dec range ([GH-93074](https://github.com/godotengine/godot/pull/93074)). - Unset the owner of `ImporterMeshInstance3D` before adding it to skeleton's child ([GH-93117](https://github.com/godotengine/godot/pull/93117)). - [Image Font Importer] Adds support for `\uXXXX` in the kerning config strings ([GH-93119](https://github.com/godotengine/godot/pull/93119)). - Fix ProgressDialog crash when importing TTF font ([GH-93161](https://github.com/godotengine/godot/pull/93161)). - Avoid crashing when scene import settings are empty ([GH-93284](https://github.com/godotengine/godot/pull/93284)). - Remove `monospace/fixed-width` from the `ResourceImporterImageFont` name and description ([GH-93337](https://github.com/godotengine/godot/pull/93337)). - Fix `browse_dialog` in Blender scene importer to accept files ([GH-93411](https://github.com/godotengine/godot/pull/93411)). - Make Basis Universal import quiet unless engine is in verbose mode ([GH-93442](https://github.com/godotengine/godot/pull/93442)). - Fix default collision shape on imported rigidbody ([GH-93506](https://github.com/godotengine/godot/pull/93506)). - Editor: Fix importers add-ons after 93238 ([GH-93518](https://github.com/godotengine/godot/pull/93518)). - Use Hermite instead of Bezier for glTF spline interpolation ([GH-93597](https://github.com/godotengine/godot/pull/93597)). - Fix reimport by scan parsing dependency paths incorrectly ([GH-93765](https://github.com/godotengine/godot/pull/93765)). - Fix adding a translation CSV results in errors on initial import for many types of resources ([GH-93919](https://github.com/godotengine/godot/pull/93919)). - Move GL
121295
// This service worker is required to expose an exported Godot project as a // Progressive Web App. It provides an offline fallback page telling the user // that they need an Internet connection to run the project if desired. // Incrementing CACHE_VERSION will kick off the install event and force // previously cached resources to be updated from the network. /** @type {string} */ const CACHE_VERSION = '___GODOT_VERSION___'; /** @type {string} */ const CACHE_PREFIX = '___GODOT_NAME___-sw-cache-'; const CACHE_NAME = CACHE_PREFIX + CACHE_VERSION; /** @type {string} */ const OFFLINE_URL = '___GODOT_OFFLINE_PAGE___'; /** @type {boolean} */ const ENSURE_CROSSORIGIN_ISOLATION_HEADERS = ___GODOT_ENSURE_CROSSORIGIN_ISOLATION_HEADERS___; // Files that will be cached on load. /** @type {string[]} */ const CACHED_FILES = ___GODOT_CACHE___; // Files that we might not want the user to preload, and will only be cached on first load. /** @type {string[]} */ const CACHABLE_FILES = ___GODOT_OPT_CACHE___; const FULL_CACHE = CACHED_FILES.concat(CACHABLE_FILES); self.addEventListener('install', (event) => { event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(CACHED_FILES))); }); self.addEventListener('activate', (event) => { event.waitUntil(caches.keys().then( function (keys) { // Remove old caches. return Promise.all(keys.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME).map((key) => caches.delete(key))); } ).then(function () { // Enable navigation preload if available. return ('navigationPreload' in self.registration) ? self.registration.navigationPreload.enable() : Promise.resolve(); })); }); /** * Ensures that the response has the correct COEP/COOP headers * @param {Response} response * @returns {Response} */ function ensureCrossOriginIsolationHeaders(response) { if (response.headers.get('Cross-Origin-Embedder-Policy') === 'require-corp' && response.headers.get('Cross-Origin-Opener-Policy') === 'same-origin') { return response; } const crossOriginIsolatedHeaders = new Headers(response.headers); crossOriginIsolatedHeaders.set('Cross-Origin-Embedder-Policy', 'require-corp'); crossOriginIsolatedHeaders.set('Cross-Origin-Opener-Policy', 'same-origin'); const newResponse = new Response(response.body, { status: response.status, statusText: response.statusText, headers: crossOriginIsolatedHeaders, }); return newResponse; } /** * Calls fetch and cache the result if it is cacheable * @param {FetchEvent} event * @param {Cache} cache * @param {boolean} isCacheable * @returns {Response} */ async function fetchAndCache(event, cache, isCacheable) { // Use the preloaded response, if it's there /** @type { Response } */ let response = await event.preloadResponse; if (response == null) { // Or, go over network. response = await self.fetch(event.request); } if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) { response = ensureCrossOriginIsolationHeaders(response); } if (isCacheable) { // And update the cache cache.put(event.request, response.clone()); } return response; } self.addEventListener( 'fetch', /** * Triggered on fetch * @param {FetchEvent} event */ (event) => { const isNavigate = event.request.mode === 'navigate'; const url = event.request.url || ''; const referrer = event.request.referrer || ''; const base = referrer.slice(0, referrer.lastIndexOf('/') + 1); const local = url.startsWith(base) ? url.replace(base, '') : ''; const isCachable = FULL_CACHE.some((v) => v === local) || (base === referrer && base.endsWith(CACHED_FILES[0])); if (isNavigate || isCachable) { event.respondWith((async () => { // Try to use cache first const cache = await caches.open(CACHE_NAME); if (isNavigate) { // Check if we have full cache during HTML page request. /** @type {Response[]} */ const fullCache = await Promise.all(FULL_CACHE.map((name) => cache.match(name))); const missing = fullCache.some((v) => v === undefined); if (missing) { try { // Try network if some cached file is missing (so we can display offline page in case). const response = await fetchAndCache(event, cache, isCachable); return response; } catch (e) { // And return the hopefully always cached offline page in case of network failure. console.error('Network error: ', e); // eslint-disable-line no-console return caches.match(OFFLINE_URL); } } } let cached = await cache.match(event.request); if (cached != null) { if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) { cached = ensureCrossOriginIsolationHeaders(cached); } return cached; } // Try network if don't have it in cache. const response = await fetchAndCache(event, cache, isCachable); return response; })()); } else if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) { event.respondWith((async () => { let response = await fetch(event.request); response = ensureCrossOriginIsolationHeaders(response); return response; })()); } } ); self.addEventListener('message', (event) => { // No cross origin if (event.origin !== self.origin) { return; } const id = event.source.id || ''; const msg = event.data || ''; // Ensure it's one of our clients. self.clients.get(id).then(function (client) { if (!client) { return; // Not a valid client. } if (msg === 'claim') { self.skipWaiting().then(() => self.clients.claim()); } else if (msg === 'clear') { caches.delete(CACHE_NAME); } else if (msg === 'update') { self.skipWaiting().then(() => self.clients.claim()).then(() => self.clients.matchAll()).then((all) => all.forEach((c) => c.navigate(c.url))); } }); });
121412
#ifndef DISABLE_LIGHT_SPOT for (uint i = 0u; i < MAX_FORWARD_LIGHTS; i++) { if (i >= spot_light_count) { break; } #if defined(USE_LIGHTMAP) && !defined(DISABLE_LIGHTMAP) if (spot_lights[spot_light_indices[i]].bake_mode == LIGHT_BAKE_STATIC) { continue; } #endif light_process_spot(spot_light_indices[i], vertex, view, normal, f0, roughness, metallic, 1.0, albedo, alpha, #ifdef LIGHT_BACKLIGHT_USED backlight, #endif #ifdef LIGHT_RIM_USED rim, rim_tint, #endif #ifdef LIGHT_CLEARCOAT_USED clearcoat, clearcoat_roughness, normalize(normal_interp), #endif #ifdef LIGHT_ANISOTROPY_USED tangent, binormal, anisotropy, #endif diffuse_light, specular_light); } #endif // !DISABLE_LIGHT_SPOT #endif // !USE_VERTEX_LIGHTING #endif // BASE_PASS #endif // !MODE_UNSHADED #endif // !MODE_RENDER_DEPTH #if defined(USE_SHADOW_TO_OPACITY) #ifndef MODE_RENDER_DEPTH alpha = min(alpha, clamp(length(ambient_light), 0.0, 1.0)); #if defined(ALPHA_SCISSOR_USED) if (alpha < alpha_scissor_threshold) { discard; } #endif // !ALPHA_SCISSOR_USED #endif // !MODE_RENDER_DEPTH #endif // USE_SHADOW_TO_OPACITY #ifdef MODE_RENDER_DEPTH #ifdef RENDER_SHADOWS_LINEAR // Linearize the depth buffer if rendering cubemap shadows. gl_FragDepth = (scene_data.z_far - (length(vertex) + scene_data.shadow_bias)) / scene_data.z_far; #endif // Nothing happens, so a tree-ssa optimizer will result in no fragment shader :) #else // !MODE_RENDER_DEPTH #ifdef RENDER_MATERIAL albedo_output_buffer.rgb = albedo; albedo_output_buffer.a = alpha; normal_output_buffer.rgb = normal * 0.5 + 0.5; normal_output_buffer.a = 0.0; orm_output_buffer.r = ao; orm_output_buffer.g = roughness; orm_output_buffer.b = metallic; orm_output_buffer.a = 1.0; emission_output_buffer.rgb = emission; emission_output_buffer.a = 0.0; #else // !RENDER_MATERIAL #ifdef BASE_PASS #ifdef MODE_UNSHADED frag_color = vec4(albedo, alpha); #else diffuse_light *= albedo; diffuse_light *= 1.0 - metallic; ambient_light *= 1.0 - metallic; frag_color = vec4(diffuse_light + specular_light, alpha); frag_color.rgb += emission + ambient_light; #endif //!MODE_UNSHADED #ifndef FOG_DISABLED fog.xy = unpackHalf2x16(fog_rg); fog.zw = unpackHalf2x16(fog_ba); frag_color.rgb = mix(frag_color.rgb, fog.rgb, fog.a); #endif // !FOG_DISABLED // Tonemap before writing as we are writing to an sRGB framebuffer frag_color.rgb *= exposure; #ifdef APPLY_TONEMAPPING frag_color.rgb = apply_tonemapping(frag_color.rgb, white); #endif frag_color.rgb = linear_to_srgb(frag_color.rgb); #else // !BASE_PASS frag_color = vec4(0.0, 0.0, 0.0, alpha); #endif // !BASE_PASS /* ADDITIVE LIGHTING PASS */ #ifdef USE_ADDITIVE_LIGHTING diffuse_light = vec3(0.0); specular_light = vec3(0.0); #ifdef USE_VERTEX_LIGHTING diffuse_light = additive_diffuse_light_interp; specular_light = additive_specular_light_interp * f0; #endif // USE_VERTEX_LIGHTING #if !defined(ADDITIVE_OMNI) && !defined(ADDITIVE_SPOT) #ifndef SHADOWS_DISABLED // Orthogonal shadows #if !defined(LIGHT_USE_PSSM2) && !defined(LIGHT_USE_PSSM4) float directional_shadow = sample_shadow(directional_shadow_atlas, directional_shadows[directional_shadow_index].shadow_atlas_pixel_size, shadow_coord); #endif // !defined(LIGHT_USE_PSSM2) && !defined(LIGHT_USE_PSSM4) // PSSM2 shadows #ifdef LIGHT_USE_PSSM2 float depth_z = -vertex.z; vec4 light_split_offsets = directional_shadows[directional_shadow_index].shadow_split_offsets; //take advantage of prefetch float shadow1 = sample_shadow(directional_shadow_atlas, directional_shadows[directional_shadow_index].shadow_atlas_pixel_size, shadow_coord); float shadow2 = sample_shadow(directional_shadow_atlas, directional_shadows[directional_shadow_index].shadow_atlas_pixel_size, shadow_coord2); float directional_shadow = 1.0; if (depth_z < light_split_offsets.y) { #ifdef LIGHT_USE_PSSM_BLEND float directional_shadow2 = 1.0; float pssm_blend = 0.0; bool use_blend = true; #endif if (depth_z < light_split_offsets.x) { directional_shadow = shadow1; #ifdef LIGHT_USE_PSSM_BLEND directional_shadow2 = shadow2; pssm_blend = smoothstep(0.0, light_split_offsets.x, depth_z); #endif } else { directional_shadow = shadow2; #ifdef LIGHT_USE_PSSM_BLEND use_blend = false; #endif } #ifdef LIGHT_USE_PSSM_BLEND if (use_blend) { directional_shadow = mix(directional_shadow, directional_shadow2, pssm_blend); } #endif } #endif //LIGHT_USE_PSSM2 // PSSM4 shadows #ifdef LIGHT_USE_PSSM4 float depth_z = -vertex.z; vec4 light_split_offsets = directional_shadows[directional_shadow_index].shadow_split_offsets; float shadow1 = sample_shadow(directional_shadow_atlas, directional_shadows[directional_shadow_index].shadow_atlas_pixel_size, shadow_coord); float shadow2 = sample_shadow(directional_shadow_atlas, directional_shadows[directional_shadow_index].shadow_atlas_pixel_size, shadow_coord2); float shadow3 = sample_shadow(directional_shadow_atlas, directional_shadows[directional_shadow_index].shadow_atlas_pixel_size, shadow_coord3); float shadow4 = sample_shadow(directional_shadow_atlas, directional_shadows[directional_shadow_index].shadow_atlas_pixel_size, shadow_coord4); float directional_shadow = 1.0; if (depth_z < light_split_offsets.w) { #ifdef LIGHT_USE_PSSM_BLEND float directional_shadow2 = 1.0; float pssm_blend = 0.0; bool use_blend = true; #endif if (depth_z < light_split_offsets.y) { if (depth_z < light_split_offsets.x) { directional_shadow = shadow1; #ifdef LIGHT_USE_PSSM_BLEND directional_shadow2 = shadow2; pssm_blend = smoothstep(0.0, light_split_offsets.x, depth_z); #endif } else { directional_shadow = shadow2; #ifdef LIGHT_USE_PSSM_BLEND directional_shadow2 = shadow3; pssm_blend = smoothstep(light_split_offsets.x, light_split_offsets.y, depth_z); #endif } } else { if (depth_z < light_split_offsets.z) { directional_shadow = shadow3; #if defined(LIGHT_USE_PSSM_BLEND) directional_shadow2 = shadow4; pssm_blend = smoothstep(light_split_offsets.y, light_split_offsets.z, depth_z); #endif } else { directional_shadow = shadow4; #if defined(LIGHT_USE_PSSM_BLEND) use_blend = false; #endif } } #if defined(LIGHT_USE_PSSM_BLEND) if (use_blend) { directional_shadow = mix(directional_shadow, directional_shadow2, pssm_blend); } #endif } #endif //LIGHT_USE_PSSM4 directional_shadow = mix(directional_shadow, 1.0, smoothstep(directional_shadows[directional_shadow_index].fade_from, directional_shadows[directional_shadow_index].fade_to, vertex.z)); directional_shadow = mix(1.0, directional_shadow, directional_lights[directional_shadow_index].shadow_opacity); #else float directional_shadow = 1.0f; #endif // SHADOWS_DISABLED
121413
#ifndef USE_VERTEX_LIGHTING light_compute(normal, normalize(directional_lights[directional_shadow_index].direction), normalize(view), directional_lights[directional_shadow_index].size, directional_lights[directional_shadow_index].color * directional_lights[directional_shadow_index].energy, true, directional_shadow, f0, roughness, metallic, 1.0, albedo, alpha, #ifdef LIGHT_BACKLIGHT_USED backlight, #endif #ifdef LIGHT_RIM_USED rim, rim_tint, #endif #ifdef LIGHT_CLEARCOAT_USED clearcoat, clearcoat_roughness, normalize(normal_interp), #endif #ifdef LIGHT_ANISOTROPY_USED binormal, tangent, anisotropy, #endif diffuse_light, specular_light); #else // Just apply shadows to vertex lighting. diffuse_light *= directional_shadow; specular_light *= directional_shadow; #endif // !USE_VERTEX_LIGHTING #endif // !defined(ADDITIVE_OMNI) && !defined(ADDITIVE_SPOT) #ifdef ADDITIVE_OMNI float omni_shadow = 1.0f; #ifndef SHADOWS_DISABLED vec3 light_ray = ((positional_shadows[positional_shadow_index].shadow_matrix * vec4(shadow_coord.xyz, 1.0))).xyz; omni_shadow = texture(omni_shadow_texture, vec4(light_ray, 1.0 - length(light_ray) * omni_lights[omni_light_index].inv_radius)); omni_shadow = mix(1.0, omni_shadow, omni_lights[omni_light_index].shadow_opacity); #endif // SHADOWS_DISABLED #ifndef USE_VERTEX_LIGHTING light_process_omni(omni_light_index, vertex, view, normal, f0, roughness, metallic, omni_shadow, albedo, alpha, #ifdef LIGHT_BACKLIGHT_USED backlight, #endif #ifdef LIGHT_RIM_USED rim, rim_tint, #endif #ifdef LIGHT_CLEARCOAT_USED clearcoat, clearcoat_roughness, normalize(normal_interp), #endif #ifdef LIGHT_ANISOTROPY_USED binormal, tangent, anisotropy, #endif diffuse_light, specular_light); #else // Just apply shadows to vertex lighting. diffuse_light *= omni_shadow; specular_light *= omni_shadow; #endif // !USE_VERTEX_LIGHTING #endif // ADDITIVE_OMNI #ifdef ADDITIVE_SPOT float spot_shadow = 1.0f; #ifndef SHADOWS_DISABLED spot_shadow = sample_shadow(spot_shadow_texture, positional_shadows[positional_shadow_index].shadow_atlas_pixel_size, shadow_coord); spot_shadow = mix(1.0, spot_shadow, spot_lights[spot_light_index].shadow_opacity); #endif // SHADOWS_DISABLED #ifndef USE_VERTEX_LIGHTING light_process_spot(spot_light_index, vertex, view, normal, f0, roughness, metallic, spot_shadow, albedo, alpha, #ifdef LIGHT_BACKLIGHT_USED backlight, #endif #ifdef LIGHT_RIM_USED rim, rim_tint, #endif #ifdef LIGHT_CLEARCOAT_USED clearcoat, clearcoat_roughness, normalize(normal_interp), #endif #ifdef LIGHT_ANISOTROPY_USED tangent, binormal, anisotropy, #endif diffuse_light, specular_light); #else // Just apply shadows to vertex lighting. diffuse_light *= spot_shadow; specular_light *= spot_shadow; #endif // !USE_VERTEX_LIGHTING #endif // ADDITIVE_SPOT diffuse_light *= albedo; diffuse_light *= 1.0 - metallic; vec3 additive_light_color = diffuse_light + specular_light; #ifndef FOG_DISABLED fog.xy = unpackHalf2x16(fog_rg); fog.zw = unpackHalf2x16(fog_ba); additive_light_color *= (1.0 - fog.a); #endif // !FOG_DISABLED // Tonemap before writing as we are writing to an sRGB framebuffer additive_light_color *= exposure; #ifdef APPLY_TONEMAPPING additive_light_color = apply_tonemapping(additive_light_color, white); #endif additive_light_color = linear_to_srgb(additive_light_color); frag_color.rgb += additive_light_color; #endif // USE_ADDITIVE_LIGHTING frag_color.rgb *= scene_data.luminance_multiplier; #endif // !RENDER_MATERIAL #endif // !MODE_RENDER_DEPTH #ifdef PREMUL_ALPHA_USED frag_color.rgb *= premul_alpha; #endif // PREMUL_ALPHA_USED }
121754
/**************************************************************************/ /* http_client_tcp.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 HTTP_CLIENT_TCP_H #define HTTP_CLIENT_TCP_H #include "http_client.h" #include "core/crypto/crypto.h" class HTTPClientTCP : public HTTPClient { private: Status status = STATUS_DISCONNECTED; IP::ResolverID resolving = IP::RESOLVER_INVALID_ID; Array ip_candidates; int conn_port = -1; // Server to make requests to. String conn_host; int server_port = -1; // Server to connect to (might be a proxy server). String server_host; int http_proxy_port = -1; // Proxy server for http requests. String http_proxy_host; int https_proxy_port = -1; // Proxy server for https requests. String https_proxy_host; bool blocking = false; bool handshaking = false; bool head_request = false; Ref<TLSOptions> tls_options; Vector<uint8_t> response_str; bool chunked = false; Vector<uint8_t> chunk; int chunk_left = 0; bool chunk_trailer_part = false; int64_t body_size = -1; int64_t body_left = 0; bool read_until_eof = false; Ref<StreamPeerBuffer> request_buffer; Ref<StreamPeerTCP> tcp_connection; Ref<StreamPeer> connection; Ref<HTTPClientTCP> proxy_client; // Negotiate with proxy server. int response_num = 0; Vector<String> response_headers; // 64 KiB by default (favors fast download speeds at the cost of memory usage). int read_chunk_size = 65536; Error _get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received); public: static HTTPClient *_create_func(bool p_notify_postinitialize); Error request(Method p_method, const String &p_url, const Vector<String> &p_headers, const uint8_t *p_body, int p_body_size) override; Error connect_to_host(const String &p_host, int p_port = -1, Ref<TLSOptions> p_tls_options = Ref<TLSOptions>()) override; void set_connection(const Ref<StreamPeer> &p_connection) override; Ref<StreamPeer> get_connection() const override; void close() override; Status get_status() const override; bool has_response() const override; bool is_response_chunked() const override; int get_response_code() const override; Error get_response_headers(List<String> *r_response) override; int64_t get_response_body_length() const override; PackedByteArray read_response_body_chunk() override; void set_blocking_mode(bool p_enable) override; bool is_blocking_mode_enabled() const override; void set_read_chunk_size(int p_size) override; int get_read_chunk_size() const override; Error poll() override; void set_http_proxy(const String &p_host, int p_port) override; void set_https_proxy(const String &p_host, int p_port) override; HTTPClientTCP(); }; #endif // HTTP_CLIENT_TCP_H
121767
public: enum ThreadLoadStatus { THREAD_LOAD_INVALID_RESOURCE, THREAD_LOAD_IN_PROGRESS, THREAD_LOAD_FAILED, THREAD_LOAD_LOADED }; enum LoadThreadMode { LOAD_THREAD_FROM_CURRENT, LOAD_THREAD_SPAWN_SINGLE, LOAD_THREAD_DISTRIBUTE, }; struct LoadToken : public RefCounted { String local_path; String user_path; uint32_t user_rc = 0; // Having user RC implies regular RC incremented in one, until the user RC reaches zero. ThreadLoadTask *task_if_unregistered = nullptr; void clear(); virtual ~LoadToken(); }; static const int BINARY_MUTEX_TAG = 1; static Ref<LoadToken> _load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode, bool p_for_user = false); static Ref<Resource> _load_complete(LoadToken &p_load_token, Error *r_error); private: static LoadToken *_load_threaded_request_reuse_user_token(const String &p_path); static void _load_threaded_request_setup_user_token(LoadToken *p_token, const String &p_path); static Ref<Resource> _load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock); static Ref<ResourceFormatLoader> loader[MAX_LOADERS]; static int loader_count; static bool timestamp_on_load; static void *err_notify_ud; static ResourceLoadErrorNotify err_notify; static void *dep_err_notify_ud; static DependencyErrorNotify dep_err_notify; static bool abort_on_missing_resource; static bool create_missing_resources_if_class_unavailable; static HashMap<String, Vector<String>> translation_remaps; static HashMap<String, String> path_remaps; static String _path_remap(const String &p_path, bool *r_translation_remapped = nullptr); friend class Resource; static SelfList<Resource>::List remapped_list; friend class ResourceFormatImporter; static Ref<Resource> _load(const String &p_path, const String &p_original_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error, bool p_use_sub_threads, float *r_progress); static ResourceLoadedCallback _loaded_callback; static Ref<ResourceFormatLoader> _find_custom_resource_format_loader(const String &path); struct ThreadLoadTask { WorkerThreadPool::TaskID task_id = 0; // Used if run on a worker thread from the pool. Thread::ID thread_id = 0; // Used if running on an user thread (e.g., simple non-threaded load). bool awaited = false; // If it's in the pool, this helps not awaiting from more than one dependent thread. ConditionVariable *cond_var = nullptr; // In not in the worker pool or already awaiting, this is used as a secondary awaiting mechanism. uint32_t awaiters_count = 0; bool need_wait = true; LoadToken *load_token = nullptr; String local_path; String type_hint; float progress = 0.0f; float max_reported_progress = 0.0f; uint64_t last_progress_check_main_thread_frame = UINT64_MAX; ThreadLoadStatus status = THREAD_LOAD_IN_PROGRESS; ResourceFormatLoader::CacheMode cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE; Error error = OK; Ref<Resource> resource; bool use_sub_threads = false; HashSet<String> sub_tasks; struct ResourceChangedConnection { Resource *source = nullptr; Callable callable; uint32_t flags = 0; }; LocalVector<ResourceChangedConnection> resource_changed_connections; }; static void _run_load_task(void *p_userdata); static thread_local int load_nesting; static thread_local HashMap<int, HashMap<String, Ref<Resource>>> res_ref_overrides; // Outermost key is nesting level. static thread_local Vector<String> load_paths_stack; static thread_local ThreadLoadTask *curr_load_task; static SafeBinaryMutex<BINARY_MUTEX_TAG> thread_load_mutex; friend SafeBinaryMutex<BINARY_MUTEX_TAG> &_get_res_loader_mutex(); static HashMap<String, ThreadLoadTask> thread_load_tasks; static bool cleaning_tasks; static HashMap<String, LoadToken *> user_load_tokens; static float _dependency_get_progress(const String &p_path); static bool _ensure_load_progress(); public: static Error load_threaded_request(const String &p_path, const String &p_type_hint = "", bool p_use_sub_threads = false, ResourceFormatLoader::CacheMode p_cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE); static ThreadLoadStatus load_threaded_get_status(const String &p_path, float *r_progress = nullptr); static Ref<Resource> load_threaded_get(const String &p_path, Error *r_error = nullptr); static bool is_within_load() { return load_nesting > 0; }; static void resource_changed_connect(Resource *p_source, const Callable &p_callable, uint32_t p_flags); static void resource_changed_disconnect(Resource *p_source, const Callable &p_callable); static void resource_changed_emit(Resource *p_source); static Ref<Resource> load(const String &p_path, const String &p_type_hint = "", ResourceFormatLoader::CacheMode p_cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE, Error *r_error = nullptr); static bool exists(const String &p_path, const String &p_type_hint = ""); static void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions); static void add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front = false); static void remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader); static void get_classes_used(const String &p_path, HashSet<StringName> *r_classes); static String get_resource_type(const String &p_path); static String get_resource_script_class(const String &p_path); static ResourceUID::ID get_resource_uid(const String &p_path); static void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); static Error rename_dependencies(const String &p_path, const HashMap<String, String> &p_map); static bool is_import_valid(const String &p_path); static String get_import_group_file(const String &p_path); static bool is_imported(const String &p_path); static int get_import_order(const String &p_path); static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load = p_timestamp; } static bool get_timestamp_on_load() { return timestamp_on_load; } // Loaders can safely use this regardless which thread they are running on. static void notify_load_error(const String &p_err) { if (err_notify) { MessageQueue::get_main_singleton()->push_callable(callable_mp_static(err_notify).bind(p_err)); } } static void set_error_notify_func(ResourceLoadErrorNotify p_err_notify) { err_notify = p_err_notify; } // Loaders can safely use this regardless which thread they are running on. static void notify_dependency_error(const String &p_path, const String &p_dependency, const String &p_type) { if (dep_err_notify) { if (Thread::get_caller_id() == Thread::get_main_id()) { dep_err_notify(p_path, p_dependency, p_type); } else { MessageQueue::get_main_singleton()->push_callable(callable_mp_static(dep_err_notify).bind(p_path, p_dependency, p_type)); } } } static void set_dependency_error_notify_func(DependencyErrorNotify p_err_notify) { dep_err_notify = p_err_notify; } static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource = p_abort; } static bool get_abort_on_missing_resources() { return abort_on_missing_resource; } static String path_remap(const String &p_path); static String import_remap(const String &p_path); static void load_path_remaps(); static void clear_path_remaps(); static void reload_translation_remaps(); static void load_translation_remaps(); static void clear_translation_remaps(); static void clear_thread_load_tasks(); static void set_load_callback(ResourceLoadedCallback p_callback); static ResourceLoaderImport import; static bool add_custom_resource_format_loader(const String &script_path); static void add_custom_loaders(); static void remove_custom_loaders(); static void set_create_missing_resources_if_class_unavailable(bool p_enable); _FORCE_INLINE_ static bool is_creating_missing_resources_if_class_unavailable_enabled() { return create_missing_resources_if_class_unavailable; } static Ref<Resource> ensure_resource_ref_override_for_outer_load(const String &p_path, const String &p_res_type); static Ref<Resource> get_resource_ref_override(const String &p_path); static bool is_cleaning_tasks(); static void initialize(); static void finalize(); }; #endif // RESOURCE_LOADER_H
121769
/**************************************************************************/ /* stream_peer_tcp.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 STREAM_PEER_TCP_H #define STREAM_PEER_TCP_H #include "core/io/ip.h" #include "core/io/ip_address.h" #include "core/io/net_socket.h" #include "core/io/stream_peer.h" class StreamPeerTCP : public StreamPeer { GDCLASS(StreamPeerTCP, StreamPeer); public: enum Status { STATUS_NONE, STATUS_CONNECTING, STATUS_CONNECTED, STATUS_ERROR, }; protected: Ref<NetSocket> _sock; uint64_t timeout = 0; Status status = STATUS_NONE; IPAddress peer_host; uint16_t peer_port = 0; Error _connect(const String &p_address, int p_port); Error write(const uint8_t *p_data, int p_bytes, int &r_sent, bool p_block); Error read(uint8_t *p_buffer, int p_bytes, int &r_received, bool p_block); static void _bind_methods(); public: void accept_socket(Ref<NetSocket> p_sock, IPAddress p_host, uint16_t p_port); Error bind(int p_port, const IPAddress &p_host); Error connect_to_host(const IPAddress &p_host, int p_port); IPAddress get_connected_host() const; int get_connected_port() const; int get_local_port() const; void disconnect_from_host(); int get_available_bytes() const override; Status get_status() const; void set_no_delay(bool p_enabled); // Poll socket updating its state. Error poll(); // Wait or check for writable, readable. Error wait(NetSocket::PollType p_type, int p_timeout = 0); // Read/Write from StreamPeer Error put_data(const uint8_t *p_data, int p_bytes) override; Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) override; Error get_data(uint8_t *p_buffer, int p_bytes) override; Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) override; StreamPeerTCP(); ~StreamPeerTCP(); }; VARIANT_ENUM_CAST(StreamPeerTCP::Status); #endif // STREAM_PEER_TCP_H
121784
/**************************************************************************/ /* json.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 JSON_H #define JSON_H #include "core/io/resource.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/variant/variant.h" class JSON : public Resource { GDCLASS(JSON, Resource); enum TokenType { TK_CURLY_BRACKET_OPEN, TK_CURLY_BRACKET_CLOSE, TK_BRACKET_OPEN, TK_BRACKET_CLOSE, TK_IDENTIFIER, TK_STRING, TK_NUMBER, TK_COLON, TK_COMMA, TK_EOF, TK_MAX }; enum Expecting { EXPECT_OBJECT, EXPECT_OBJECT_KEY, EXPECT_COLON, EXPECT_OBJECT_VALUE, }; struct Token { TokenType type; Variant value; }; String text; Variant data; String err_str; int err_line = 0; static const char *tk_name[]; static String _make_indent(const String &p_indent, int p_size); static String _stringify(const Variant &p_var, const String &p_indent, int p_cur_indent, bool p_sort_keys, HashSet<const void *> &p_markers, bool p_full_precision = false); static Error _get_token(const char32_t *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str); static Error _parse_value(Variant &value, Token &token, const char32_t *p_str, int &index, int p_len, int &line, int p_depth, String &r_err_str); static Error _parse_array(Array &array, const char32_t *p_str, int &index, int p_len, int &line, int p_depth, String &r_err_str); static Error _parse_object(Dictionary &object, const char32_t *p_str, int &index, int p_len, int &line, int p_depth, String &r_err_str); static Error _parse_string(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line); protected: static void _bind_methods(); public: Error parse(const String &p_json_string, bool p_keep_text = false); String get_parsed_text() const; 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; } void set_data(const Variant &p_data); inline int get_error_line() const { return err_line; } inline String get_error_message() const { return err_str; } static Variant from_native(const Variant &p_variant, bool p_allow_classes = false, bool p_allow_scripts = false); static Variant to_native(const Variant &p_json, bool p_allow_classes = false, bool p_allow_scripts = false); }; class ResourceFormatLoaderJSON : public ResourceFormatLoader { public: virtual Ref<Resource> load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE) override; virtual void get_recognized_extensions(List<String> *p_extensions) const override; virtual bool handles_type(const String &p_type) const override; virtual String get_resource_type(const String &p_path) const override; }; class ResourceFormatSaverJSON : public ResourceFormatSaver { public: virtual Error save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags = 0) override; virtual void get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const override; virtual bool recognize(const Ref<Resource> &p_resource) const override; }; #endif // JSON_H
121836
/**************************************************************************/ /* transform_interpolator.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 TRANSFORM_INTERPOLATOR_H #define TRANSFORM_INTERPOLATOR_H #include "core/math/math_defs.h" #include "core/math/vector3.h" // Keep all the functions for fixed timestep interpolation together. // There are two stages involved: // Finding a method, for determining the interpolation method between two // keyframes (which are physics ticks). // And applying that pre-determined method. // Pre-determining the method makes sense because it is expensive and often // several frames may occur between each physics tick, which will make it cheaper // than performing every frame. struct Transform2D; struct Transform3D; struct Basis; struct Quaternion; class TransformInterpolator { public: enum Method { INTERP_LERP, INTERP_SLERP, INTERP_SCALED_SLERP, }; private: _FORCE_INLINE_ static bool _sign(real_t p_val) { return p_val >= 0; } static real_t _vec3_sum(const Vector3 &p_pt) { return p_pt.x + p_pt.y + p_pt.z; } static real_t _vec3_normalize(Vector3 &p_vec); _FORCE_INLINE_ static bool _vec3_is_equal_approx(const Vector3 &p_a, const Vector3 &p_b, real_t p_tolerance) { return Math::is_equal_approx(p_a.x, p_b.x, p_tolerance) && Math::is_equal_approx(p_a.y, p_b.y, p_tolerance) && Math::is_equal_approx(p_a.z, p_b.z, p_tolerance); } static Vector3 _basis_orthonormalize(Basis &r_basis); static Method _test_basis(Basis p_basis, bool r_needed_normalize, Quaternion &r_quat); static Basis _basis_slerp_unchecked(Basis p_from, Basis p_to, real_t p_fraction); static Quaternion _quat_slerp_unchecked(const Quaternion &p_from, const Quaternion &p_to, real_t p_fraction); static Quaternion _basis_to_quat_unchecked(const Basis &p_basis); static bool _basis_is_orthogonal(const Basis &p_basis, real_t p_epsilon = 0.01f); static bool _basis_is_orthogonal_any_scale(const Basis &p_basis); static void interpolate_basis_linear(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction); static void interpolate_basis_scaled_slerp(Basis p_prev, Basis p_curr, Basis &r_result, real_t p_fraction); public: static void interpolate_transform_2d(const Transform2D &p_prev, const Transform2D &p_curr, Transform2D &r_result, real_t p_fraction); // Generic functions, use when you don't know what method should be used, e.g. from GDScript. // These will be slower. static void interpolate_transform_3d(const Transform3D &p_prev, const Transform3D &p_curr, Transform3D &r_result, real_t p_fraction); static void interpolate_basis(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction); // Optimized function when you know ahead of time the method. static void interpolate_transform_3d_via_method(const Transform3D &p_prev, const Transform3D &p_curr, Transform3D &r_result, real_t p_fraction, Method p_method); static void interpolate_basis_via_method(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction, Method p_method); static real_t checksum_transform_3d(const Transform3D &p_transform); static Method find_method(const Basis &p_a, const Basis &p_b); }; #endif // TRANSFORM_INTERPOLATOR_H
121838
/**************************************************************************/ /* quaternion.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 QUATERNION_H #define QUATERNION_H #include "core/math/math_funcs.h" #include "core/math/vector3.h" #include "core/string/ustring.h" struct [[nodiscard]] Quaternion { union { struct { real_t x; real_t y; real_t z; real_t w; }; real_t components[4] = { 0, 0, 0, 1.0 }; }; _FORCE_INLINE_ real_t &operator[](int p_idx) { return components[p_idx]; } _FORCE_INLINE_ const real_t &operator[](int p_idx) const { return components[p_idx]; } _FORCE_INLINE_ real_t length_squared() const; bool is_equal_approx(const Quaternion &p_quaternion) const; bool is_finite() const; real_t length() const; void normalize(); Quaternion normalized() const; bool is_normalized() const; Quaternion inverse() const; Quaternion log() const; Quaternion exp() const; _FORCE_INLINE_ real_t dot(const Quaternion &p_q) const; real_t angle_to(const Quaternion &p_to) const; Vector3 get_euler(EulerOrder p_order = EulerOrder::YXZ) const; static Quaternion from_euler(const Vector3 &p_euler); Quaternion slerp(const Quaternion &p_to, real_t p_weight) const; Quaternion slerpni(const Quaternion &p_to, real_t p_weight) const; Quaternion spherical_cubic_interpolate(const Quaternion &p_b, const Quaternion &p_pre_a, const Quaternion &p_post_b, 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, real_t p_weight, real_t p_b_t, real_t p_pre_a_t, real_t p_post_b_t) const; Vector3 get_axis() const; real_t get_angle() const; _FORCE_INLINE_ void get_axis_angle(Vector3 &r_axis, real_t &r_angle) const { r_angle = 2 * Math::acos(w); real_t r = ((real_t)1) / Math::sqrt(1 - w * w); r_axis.x = x * r; r_axis.y = y * r; r_axis.z = z * r; } void operator*=(const Quaternion &p_q); Quaternion operator*(const Quaternion &p_q) const; _FORCE_INLINE_ Vector3 xform(const Vector3 &p_v) const { #ifdef MATH_CHECKS ERR_FAIL_COND_V_MSG(!is_normalized(), p_v, "The quaternion " + operator String() + " must be normalized."); #endif Vector3 u(x, y, z); Vector3 uv = u.cross(p_v); return p_v + ((uv * w) + u.cross(uv)) * ((real_t)2); } _FORCE_INLINE_ Vector3 xform_inv(const Vector3 &p_v) const { return inverse().xform(p_v); } _FORCE_INLINE_ void operator+=(const Quaternion &p_q); _FORCE_INLINE_ void operator-=(const Quaternion &p_q); _FORCE_INLINE_ void operator*=(real_t p_s); _FORCE_INLINE_ void operator/=(real_t p_s); _FORCE_INLINE_ Quaternion operator+(const Quaternion &p_q2) const; _FORCE_INLINE_ Quaternion operator-(const Quaternion &p_q2) const; _FORCE_INLINE_ Quaternion operator-() const; _FORCE_INLINE_ Quaternion operator*(real_t p_s) const; _FORCE_INLINE_ Quaternion operator/(real_t p_s) const; _FORCE_INLINE_ bool operator==(const Quaternion &p_quaternion) const; _FORCE_INLINE_ bool operator!=(const Quaternion &p_quaternion) const; operator String() const; _FORCE_INLINE_ Quaternion() {} _FORCE_INLINE_ Quaternion(real_t p_x, real_t p_y, real_t p_z, real_t p_w) : x(p_x), y(p_y), z(p_z), w(p_w) { } Quaternion(const Vector3 &p_axis, real_t p_angle); Quaternion(const Quaternion &p_q) : x(p_q.x), y(p_q.y), z(p_q.z), w(p_q.w) { } void operator=(const Quaternion &p_q) { x = p_q.x; y = p_q.y; z = p_q.z; w = p_q.w; } Quaternion(const Vector3 &p_v0, const Vector3 &p_v1) { // Shortest arc. Vector3 c = p_v0.cross(p_v1); real_t d = p_v0.dot(p_v1); if (d < -1.0f + (real_t)CMP_EPSILON) { x = 0; y = 1; z = 0; w = 0; } else { real_t s = Math::sqrt((1.0f + d) * 2.0f); real_t rs = 1.0f / s; x = c.x * rs; y = c.y * rs; z = c.z * rs; w = s * 0.5f; } } }; real_t Quaternion::dot(const Quaternion &p_q) const { return x * p_q.x + y * p_q.y + z * p_q.z + w * p_q.w; } real_t Quaternion::length_squared() const { return dot(*this); } void Quaternion::operator+=(const Quaternion &p_q) { x += p_q.x; y += p_q.y; z += p_q.z; w += p_q.w; } void Quaternion::operator-=(const Quaternion &p_q) { x -= p_q.x; y -= p_q.y; z -= p_q.z; w -= p_q.w; } void Quaternion::operator*=(real_t p_s) { x *= p_s; y *= p_s; z *= p_s; w *= p_s; } void Quaternion::operator/=(real_t p_s) { *this *= 1.0f / p_s; } Quaternion Quaternion::operator+(const Quaternion &p_q2) const { const Quaternion &q1 = *this; return Quaternion(q1.x + p_q2.x, q1.y + p_q2.y, q1.z + p_q2.z, q1.w + p_q2.w); } Quaternion Quaternion::operator-(const Quaternion &p_q2) const { const Quaternion &q1 = *this; return Quaternion(q1.x - p_q2.x, q1.y - p_q2.y, q1.z - p_q2.z, q1.w - p_q2.w); } Quaternion Quaternion::operator-() const { const Quaternion &q2 = *this; return Quaternion(-q2.x, -q2.y, -q2.z, -q2.w); } Quaternion Quaternion::operator*(real_t p_s) const { return Quaternion(x * p_s, y * p_s, z * p_s, w * p_s); } Quaternion Quaternion::operator/(real_t p_s) const { return *this * (1.0f / p_s); } bool Quaternion::operator==(const Quaternion &p_quaternion) const { return x == p_quaternion.x && y == p_quaternion.y && z == p_quaternion.z && w == p_quaternion.w; } bool Quaternion::operator!=(const Quaternion &p_quaternion) const { return x != p_quaternion.x || y != p_quaternion.y || z != p_quaternion.z || w != p_quaternion.w; } _FORCE_INLINE_ Quaternion operator*(real_t p_real, const Quaternion &p_quaternion) { return p_quaternion * p_real; } #endif // QUATERNION_H
121894
struct [[nodiscard]] Vector3 { static const int AXIS_COUNT = 3; enum Axis { AXIS_X, AXIS_Y, AXIS_Z, }; union { struct { real_t x; real_t y; real_t z; }; real_t coord[3] = { 0 }; }; _FORCE_INLINE_ const real_t &operator[](int p_axis) const { DEV_ASSERT((unsigned int)p_axis < 3); return coord[p_axis]; } _FORCE_INLINE_ real_t &operator[](int p_axis) { DEV_ASSERT((unsigned int)p_axis < 3); return coord[p_axis]; } _FORCE_INLINE_ Vector3::Axis min_axis_index() const { return x < y ? (x < z ? Vector3::AXIS_X : Vector3::AXIS_Z) : (y < z ? Vector3::AXIS_Y : Vector3::AXIS_Z); } _FORCE_INLINE_ Vector3::Axis max_axis_index() const { return x < y ? (y < z ? Vector3::AXIS_Z : Vector3::AXIS_Y) : (x < z ? Vector3::AXIS_Z : Vector3::AXIS_X); } Vector3 min(const Vector3 &p_vector3) const { return Vector3(MIN(x, p_vector3.x), MIN(y, p_vector3.y), MIN(z, p_vector3.z)); } Vector3 minf(real_t p_scalar) const { return Vector3(MIN(x, p_scalar), MIN(y, p_scalar), MIN(z, p_scalar)); } Vector3 max(const Vector3 &p_vector3) const { return Vector3(MAX(x, p_vector3.x), MAX(y, p_vector3.y), MAX(z, p_vector3.z)); } Vector3 maxf(real_t p_scalar) const { return Vector3(MAX(x, p_scalar), MAX(y, p_scalar), MAX(z, p_scalar)); } _FORCE_INLINE_ real_t length() const; _FORCE_INLINE_ real_t length_squared() const; _FORCE_INLINE_ void normalize(); _FORCE_INLINE_ Vector3 normalized() const; _FORCE_INLINE_ bool is_normalized() const; _FORCE_INLINE_ Vector3 inverse() const; Vector3 limit_length(real_t p_len = 1.0) const; _FORCE_INLINE_ void zero(); void snap(const Vector3 &p_step); void snapf(real_t p_step); Vector3 snapped(const Vector3 &p_step) const; Vector3 snappedf(real_t p_step) const; void rotate(const Vector3 &p_axis, real_t p_angle); Vector3 rotated(const Vector3 &p_axis, real_t p_angle) const; /* Static Methods between 2 vector3s */ _FORCE_INLINE_ Vector3 lerp(const Vector3 &p_to, real_t p_weight) const; _FORCE_INLINE_ Vector3 slerp(const Vector3 &p_to, real_t p_weight) const; _FORCE_INLINE_ Vector3 cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, 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, real_t p_weight, real_t p_b_t, real_t p_pre_a_t, 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, real_t p_t) const; _FORCE_INLINE_ Vector3 bezier_derivative(const Vector3 &p_control_1, const Vector3 &p_control_2, const Vector3 &p_end, real_t p_t) const; Vector3 move_toward(const Vector3 &p_to, real_t p_delta) const; Vector2 octahedron_encode() const; static Vector3 octahedron_decode(const Vector2 &p_oct); Vector2 octahedron_tangent_encode(float p_sign) const; static Vector3 octahedron_tangent_decode(const Vector2 &p_oct, float *r_sign); _FORCE_INLINE_ Vector3 cross(const Vector3 &p_with) const; _FORCE_INLINE_ real_t dot(const Vector3 &p_with) const; Basis outer(const Vector3 &p_with) const; _FORCE_INLINE_ Vector3 abs() const; _FORCE_INLINE_ Vector3 floor() const; _FORCE_INLINE_ Vector3 sign() const; _FORCE_INLINE_ Vector3 ceil() const; _FORCE_INLINE_ Vector3 round() const; Vector3 clamp(const Vector3 &p_min, const Vector3 &p_max) const; Vector3 clampf(real_t p_min, real_t p_max) const; _FORCE_INLINE_ real_t distance_to(const Vector3 &p_to) const; _FORCE_INLINE_ real_t distance_squared_to(const Vector3 &p_to) const; _FORCE_INLINE_ Vector3 posmod(real_t p_mod) const; _FORCE_INLINE_ Vector3 posmodv(const Vector3 &p_modv) const; _FORCE_INLINE_ Vector3 project(const Vector3 &p_to) const; _FORCE_INLINE_ real_t angle_to(const Vector3 &p_to) const; _FORCE_INLINE_ real_t signed_angle_to(const Vector3 &p_to, const Vector3 &p_axis) const; _FORCE_INLINE_ Vector3 direction_to(const Vector3 &p_to) const; _FORCE_INLINE_ Vector3 slide(const Vector3 &p_normal) const; _FORCE_INLINE_ Vector3 bounce(const Vector3 &p_normal) const; _FORCE_INLINE_ Vector3 reflect(const Vector3 &p_normal) const; bool is_equal_approx(const Vector3 &p_v) const; bool is_zero_approx() const; bool is_finite() const; /* Operators */ _FORCE_INLINE_ Vector3 &operator+=(const Vector3 &p_v); _FORCE_INLINE_ Vector3 operator+(const Vector3 &p_v) const; _FORCE_INLINE_ Vector3 &operator-=(const Vector3 &p_v); _FORCE_INLINE_ Vector3 operator-(const Vector3 &p_v) const; _FORCE_INLINE_ Vector3 &operator*=(const Vector3 &p_v); _FORCE_INLINE_ Vector3 operator*(const Vector3 &p_v) const; _FORCE_INLINE_ Vector3 &operator/=(const Vector3 &p_v); _FORCE_INLINE_ Vector3 operator/(const Vector3 &p_v) const; _FORCE_INLINE_ Vector3 &operator*=(real_t p_scalar); _FORCE_INLINE_ Vector3 operator*(real_t p_scalar) const; _FORCE_INLINE_ Vector3 &operator/=(real_t p_scalar); _FORCE_INLINE_ Vector3 operator/(real_t p_scalar) const; _FORCE_INLINE_ Vector3 operator-() const; _FORCE_INLINE_ bool operator==(const Vector3 &p_v) const; _FORCE_INLINE_ bool operator!=(const Vector3 &p_v) const; _FORCE_INLINE_ bool operator<(const Vector3 &p_v) const; _FORCE_INLINE_ bool operator<=(const Vector3 &p_v) const; _FORCE_INLINE_ bool operator>(const Vector3 &p_v) const; _FORCE_INLINE_ bool operator>=(const Vector3 &p_v) const; operator String() const; operator Vector3i() const; _FORCE_INLINE_ Vector3() {} _FORCE_INLINE_ Vector3(real_t p_x, real_t p_y, real_t p_z) { x = p_x; y = p_y; z = p_z; } }; Vector3 Vector3::cross(const Vector3 &p_with) const { Vector3 ret( (y * p_with.z) - (z * p_with.y), (z * p_with.x) - (x * p_with.z), (x * p_with.y) - (y * p_with.x)); return ret; } real_t Vector3::dot(const Vector3 &p_with) const { return x * p_with.x + y * p_with.y + z * p_with.z; } Vector3 Vector3::abs() const { return Vector3(Math::abs(x), Math::abs(y), Math::abs(z)); } Vector3 Vector3::sign() const { return Vector3(SIGN(x), SIGN(y), SIGN(z)); } Vector3 Vector3::floor() const { return Vector3(Math::floor(x), Math::floor(y), Math::floor(z)); } Vector3 Vector3::ceil() const { return Vector3(Math::ceil(x), Math::ceil(y), Math::ceil(z)); } Vector3 Vector3::round() const { return Vector3(Math::round(x), Math::round(y), Math::round(z)); } Vector3 Vector3::lerp(const Vector3 &p_to, real_t p_weight) const { Vector3 res = *this; res.x = Math::lerp(res.x, p_to.x, p_weight); res.y = Math::lerp(res.y, p_to.y, p_weight); res.z = Math::lerp(res.z, p_to.z, p_weight); return res; }
121895
Vector3 Vector3::slerp(const Vector3 &p_to, real_t p_weight) const { // This method seems more complicated than it really is, since we write out // the internals of some methods for efficiency (mainly, checking length). real_t start_length_sq = length_squared(); real_t end_length_sq = p_to.length_squared(); if (unlikely(start_length_sq == 0.0f || end_length_sq == 0.0f)) { // Zero length vectors have no angle, so the best we can do is either lerp or throw an error. return lerp(p_to, p_weight); } Vector3 axis = cross(p_to); real_t axis_length_sq = axis.length_squared(); if (unlikely(axis_length_sq == 0.0f)) { // Colinear vectors have no rotation axis or angle between them, so the best we can do is lerp. return lerp(p_to, p_weight); } axis /= Math::sqrt(axis_length_sq); real_t start_length = Math::sqrt(start_length_sq); real_t result_length = Math::lerp(start_length, Math::sqrt(end_length_sq), p_weight); real_t angle = angle_to(p_to); return rotated(axis, angle * p_weight) * (result_length / start_length); } Vector3 Vector3::cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_weight) const { Vector3 res = *this; res.x = Math::cubic_interpolate(res.x, p_b.x, p_pre_a.x, p_post_b.x, p_weight); res.y = Math::cubic_interpolate(res.y, p_b.y, p_pre_a.y, p_post_b.y, p_weight); res.z = Math::cubic_interpolate(res.z, p_b.z, p_pre_a.z, p_post_b.z, p_weight); return res; } Vector3 Vector3::cubic_interpolate_in_time(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_weight, real_t p_b_t, real_t p_pre_a_t, 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, real_t p_t) const { Vector3 res = *this; res.x = Math::bezier_interpolate(res.x, p_control_1.x, p_control_2.x, p_end.x, p_t); res.y = Math::bezier_interpolate(res.y, p_control_1.y, p_control_2.y, p_end.y, p_t); res.z = Math::bezier_interpolate(res.z, p_control_1.z, p_control_2.z, p_end.z, p_t); return res; } Vector3 Vector3::bezier_derivative(const Vector3 &p_control_1, const Vector3 &p_control_2, const Vector3 &p_end, real_t p_t) const { Vector3 res = *this; res.x = Math::bezier_derivative(res.x, p_control_1.x, p_control_2.x, p_end.x, p_t); res.y = Math::bezier_derivative(res.y, p_control_1.y, p_control_2.y, p_end.y, p_t); res.z = Math::bezier_derivative(res.z, p_control_1.z, p_control_2.z, p_end.z, p_t); return res; } real_t Vector3::distance_to(const Vector3 &p_to) const { return (p_to - *this).length(); } real_t Vector3::distance_squared_to(const Vector3 &p_to) const { return (p_to - *this).length_squared(); } Vector3 Vector3::posmod(real_t p_mod) const { return Vector3(Math::fposmod(x, p_mod), Math::fposmod(y, p_mod), Math::fposmod(z, p_mod)); } Vector3 Vector3::posmodv(const Vector3 &p_modv) const { return Vector3(Math::fposmod(x, p_modv.x), Math::fposmod(y, p_modv.y), Math::fposmod(z, p_modv.z)); } Vector3 Vector3::project(const Vector3 &p_to) const { return p_to * (dot(p_to) / p_to.length_squared()); } real_t Vector3::angle_to(const Vector3 &p_to) const { return Math::atan2(cross(p_to).length(), dot(p_to)); } real_t Vector3::signed_angle_to(const Vector3 &p_to, const Vector3 &p_axis) const { Vector3 cross_to = cross(p_to); real_t unsigned_angle = Math::atan2(cross_to.length(), dot(p_to)); real_t sign = cross_to.dot(p_axis); return (sign < 0) ? -unsigned_angle : unsigned_angle; } Vector3 Vector3::direction_to(const Vector3 &p_to) const { Vector3 ret(p_to.x - x, p_to.y - y, p_to.z - z); ret.normalize(); return ret; } /* Operators */ Vector3 &Vector3::operator+=(const Vector3 &p_v) { x += p_v.x; y += p_v.y; z += p_v.z; return *this; } Vector3 Vector3::operator+(const Vector3 &p_v) const { return Vector3(x + p_v.x, y + p_v.y, z + p_v.z); } Vector3 &Vector3::operator-=(const Vector3 &p_v) { x -= p_v.x; y -= p_v.y; z -= p_v.z; return *this; } Vector3 Vector3::operator-(const Vector3 &p_v) const { return Vector3(x - p_v.x, y - p_v.y, z - p_v.z); } Vector3 &Vector3::operator*=(const Vector3 &p_v) { x *= p_v.x; y *= p_v.y; z *= p_v.z; return *this; } Vector3 Vector3::operator*(const Vector3 &p_v) const { return Vector3(x * p_v.x, y * p_v.y, z * p_v.z); } Vector3 &Vector3::operator/=(const Vector3 &p_v) { x /= p_v.x; y /= p_v.y; z /= p_v.z; return *this; } Vector3 Vector3::operator/(const Vector3 &p_v) const { return Vector3(x / p_v.x, y / p_v.y, z / p_v.z); } Vector3 &Vector3::operator*=(real_t p_scalar) { x *= p_scalar; y *= p_scalar; z *= p_scalar; return *this; } // Multiplication operators required to workaround issues with LLVM using implicit conversion // to Vector3i instead for integers where it should not. _FORCE_INLINE_ Vector3 operator*(float p_scalar, const Vector3 &p_vec) { return p_vec * p_scalar; } _FORCE_INLINE_ Vector3 operator*(double p_scalar, const Vector3 &p_vec) { return p_vec * p_scalar; } _FORCE_INLINE_ Vector3 operator*(int32_t p_scalar, const Vector3 &p_vec) { return p_vec * p_scalar; } _FORCE_INLINE_ Vector3 operator*(int64_t p_scalar, const Vector3 &p_vec) { return p_vec * p_scalar; } Vector3 Vector3::operator*(real_t p_scalar) const { return Vector3(x * p_scalar, y * p_scalar, z * p_scalar); } Vector3 &Vector3::operator/=(real_t p_scalar) { x /= p_scalar; y /= p_scalar; z /= p_scalar; return *this; } Vector3 Vector3::operator/(real_t p_scalar) const { return Vector3(x / p_scalar, y / p_scalar, z / p_scalar); } Vector3 Vector3::operator-() const { return Vector3(-x, -y, -z); } bool Vector3::operator==(const Vector3 &p_v) const { return x == p_v.x && y == p_v.y && z == p_v.z; } bool Vector3::operator!=(const Vector3 &p_v) const { return x != p_v.x || y != p_v.y || z != p_v.z; }
121896
bool Vector3::operator<(const Vector3 &p_v) const { if (x == p_v.x) { if (y == p_v.y) { return z < p_v.z; } return y < p_v.y; } return x < p_v.x; } bool Vector3::operator>(const Vector3 &p_v) const { if (x == p_v.x) { if (y == p_v.y) { return z > p_v.z; } return y > p_v.y; } return x > p_v.x; } bool Vector3::operator<=(const Vector3 &p_v) const { if (x == p_v.x) { if (y == p_v.y) { return z <= p_v.z; } return y < p_v.y; } return x < p_v.x; } bool Vector3::operator>=(const Vector3 &p_v) const { if (x == p_v.x) { if (y == p_v.y) { return z >= p_v.z; } return y > p_v.y; } return x > p_v.x; } _FORCE_INLINE_ Vector3 vec3_cross(const Vector3 &p_a, const Vector3 &p_b) { return p_a.cross(p_b); } _FORCE_INLINE_ real_t vec3_dot(const Vector3 &p_a, const Vector3 &p_b) { return p_a.dot(p_b); } real_t Vector3::length() const { real_t x2 = x * x; real_t y2 = y * y; real_t z2 = z * z; return Math::sqrt(x2 + y2 + z2); } real_t Vector3::length_squared() const { real_t x2 = x * x; real_t y2 = y * y; real_t z2 = z * z; return x2 + y2 + z2; } void Vector3::normalize() { real_t lengthsq = length_squared(); if (lengthsq == 0) { x = y = z = 0; } else { real_t length = Math::sqrt(lengthsq); x /= length; y /= length; z /= length; } } Vector3 Vector3::normalized() const { Vector3 v = *this; v.normalize(); return v; } bool Vector3::is_normalized() const { // use length_squared() instead of length() to avoid sqrt(), makes it more stringent. return Math::is_equal_approx(length_squared(), 1, (real_t)UNIT_EPSILON); } Vector3 Vector3::inverse() const { return Vector3(1.0f / x, 1.0f / y, 1.0f / z); } void Vector3::zero() { x = y = z = 0; } // slide returns the component of the vector along the given plane, specified by its normal vector. Vector3 Vector3::slide(const Vector3 &p_normal) const { #ifdef MATH_CHECKS ERR_FAIL_COND_V_MSG(!p_normal.is_normalized(), Vector3(), "The normal Vector3 " + p_normal.operator String() + " must be normalized."); #endif return *this - p_normal * dot(p_normal); } Vector3 Vector3::bounce(const Vector3 &p_normal) const { return -reflect(p_normal); } Vector3 Vector3::reflect(const Vector3 &p_normal) const { #ifdef MATH_CHECKS ERR_FAIL_COND_V_MSG(!p_normal.is_normalized(), Vector3(), "The normal Vector3 " + p_normal.operator String() + " must be normalized."); #endif return 2.0f * p_normal * dot(p_normal) - *this; } #endif // VECTOR3_H
121925
#ifndef OBJECT_H #define OBJECT_H #include "core/extension/gdextension_interface.h" #include "core/object/message_queue.h" #include "core/object/object_id.h" #include "core/os/rw_lock.h" #include "core/os/spin_lock.h" #include "core/templates/hash_map.h" #include "core/templates/hash_set.h" #include "core/templates/list.h" #include "core/templates/rb_map.h" #include "core/templates/safe_refcount.h" #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_less][,hide_slider][,radians_as_degrees][,degrees][,exp][,suffix:<keyword>] range. PROPERTY_HINT_ENUM, ///< hint_text= "val1,val2,val3,etc" PROPERTY_HINT_ENUM_SUGGESTION, ///< hint_text= "val1,val2,val3,etc" PROPERTY_HINT_EXP_EASING, /// exponential easing function (Math::ease) use "attenuation" hint string to revert (flip h), "positive_only" to exclude in-out and out-in. (ie: "attenuation,positive_only") PROPERTY_HINT_LINK, PROPERTY_HINT_FLAGS, ///< hint_text= "flag1,flag2,etc" (as bit flags) PROPERTY_HINT_LAYERS_2D_RENDER, PROPERTY_HINT_LAYERS_2D_PHYSICS, PROPERTY_HINT_LAYERS_2D_NAVIGATION, PROPERTY_HINT_LAYERS_3D_RENDER, PROPERTY_HINT_LAYERS_3D_PHYSICS, PROPERTY_HINT_LAYERS_3D_NAVIGATION, PROPERTY_HINT_FILE, ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," PROPERTY_HINT_DIR, ///< a directory path must be passed PROPERTY_HINT_GLOBAL_FILE, ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," PROPERTY_HINT_GLOBAL_DIR, ///< a directory path must be passed PROPERTY_HINT_RESOURCE_TYPE, ///< a resource object type PROPERTY_HINT_MULTILINE_TEXT, ///< used for string properties that can contain multiple lines PROPERTY_HINT_EXPRESSION, ///< used for string properties that can contain multiple lines PROPERTY_HINT_PLACEHOLDER_TEXT, ///< used to set a placeholder text for string properties PROPERTY_HINT_COLOR_NO_ALPHA, ///< used for ignoring alpha component when editing a color PROPERTY_HINT_OBJECT_ID, PROPERTY_HINT_TYPE_STRING, ///< a type string, the hint is the base type to choose PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE, // Deprecated. PROPERTY_HINT_OBJECT_TOO_BIG, ///< object is too big to send PROPERTY_HINT_NODE_PATH_VALID_TYPES, PROPERTY_HINT_SAVE_FILE, ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc,". This opens a save dialog PROPERTY_HINT_GLOBAL_SAVE_FILE, ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc,". This opens a save dialog PROPERTY_HINT_INT_IS_OBJECTID, // Deprecated. PROPERTY_HINT_INT_IS_POINTER, PROPERTY_HINT_ARRAY_TYPE, 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_PASSWORD, PROPERTY_HINT_LAYERS_AVOIDANCE, PROPERTY_HINT_DICTIONARY_TYPE, PROPERTY_HINT_TOOL_BUTTON, PROPERTY_HINT_MAX, }; enum PropertyUsageFlags { PROPERTY_USAGE_NONE = 0, PROPERTY_USAGE_STORAGE = 1 << 1, PROPERTY_USAGE_EDITOR = 1 << 2, PROPERTY_USAGE_INTERNAL = 1 << 3, PROPERTY_USAGE_CHECKABLE = 1 << 4, // Used for editing global variables. PROPERTY_USAGE_CHECKED = 1 << 5, // Used for editing global variables. PROPERTY_USAGE_GROUP = 1 << 6, // Used for grouping props in the editor. PROPERTY_USAGE_CATEGORY = 1 << 7, PROPERTY_USAGE_SUBGROUP = 1 << 8, PROPERTY_USAGE_CLASS_IS_BITFIELD = 1 << 9, PROPERTY_USAGE_NO_INSTANCE_STATE = 1 << 10, PROPERTY_USAGE_RESTART_IF_CHANGED = 1 << 11, PROPERTY_USAGE_SCRIPT_VARIABLE = 1 << 12, PROPERTY_USAGE_STORE_IF_NULL = 1 << 13, PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED = 1 << 14, PROPERTY_USAGE_SCRIPT_DEFAULT_VALUE = 1 << 15, // Deprecated. PROPERTY_USAGE_CLASS_IS_ENUM = 1 << 16, PROPERTY_USAGE_NIL_IS_VARIANT = 1 << 17, PROPERTY_USAGE_ARRAY = 1 << 18, // Used in the inspector to group properties as elements of an array. PROPERTY_USAGE_ALWAYS_DUPLICATE = 1 << 19, // When duplicating a resource, always duplicate, even with subresource duplication disabled. PROPERTY_USAGE_NEVER_DUPLICATE = 1 << 20, // When duplicating a resource, never duplicate, even with subresource duplication enabled. PROPERTY_USAGE_HIGH_END_GFX = 1 << 21, PROPERTY_USAGE_NODE_PATH_FROM_SCENE_ROOT = 1 << 22, PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT = 1 << 23, PROPERTY_USAGE_KEYING_INCREMENTS = 1 << 24, // Used in inspector to increment property when keyed in animation player. PROPERTY_USAGE_DEFERRED_SET_RESOURCE = 1 << 25, // Deprecated. PROPERTY_USAGE_EDITOR_INSTANTIATE_OBJECT = 1 << 26, // For Object properties, instantiate them when creating in editor. PROPERTY_USAGE_EDITOR_BASIC_SETTING = 1 << 27, //for project or editor settings, show when basic settings are selected. PROPERTY_USAGE_READ_ONLY = 1 << 28, // Mark a property as read-only in the inspector. PROPERTY_USAGE_SECRET = 1 << 29, // Export preset credentials that should be stored separately from the rest of the export config. PROPERTY_USAGE_DEFAULT = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR, PROPERTY_USAGE_NO_EDITOR = PROPERTY_USAGE_STORAGE, }; #define ADD_SIGNAL(m_signal) ::ClassDB::add_signal(get_class_static(), m_signal) #define ADD_PROPERTY(m_property, m_setter, m_getter) ::ClassDB::add_property(get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter)) #define ADD_PROPERTYI(m_property, m_setter, m_getter, m_index) ::ClassDB::add_property(get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter), m_index) #define ADD_PROPERTY_DEFAULT(m_property, m_default) ::ClassDB::set_property_default_value(get_class_static(), m_property, m_default) #define ADD_GROUP(m_name, m_prefix) ::ClassDB::add_property_group(get_class_static(), m_name, m_prefix) #define ADD_GROUP_INDENT(m_name, m_prefix, m_depth) ::ClassDB::add_property_group(get_class_static(), m_name, m_prefix, m_depth) #define ADD_SUBGROUP(m_name, m_prefix) ::ClassDB::add_property_subgroup(get_class_static(), m_name, m_prefix) #define ADD_SUBGROUP_INDENT(m_name, m_prefix, m_depth) ::ClassDB::add_property_subgroup(get_class_static(), m_name, m_prefix, m_depth) #define ADD_LINKED_PROPERTY(m_property, m_linked_property) ::ClassDB::add_linked_property(get_class_static(), m_property, m_linked_property) #define ADD_ARRAY_COUNT(m_label, m_count_property, m_count_property_setter, m_count_property_getter, m_prefix) ClassDB::add_property_array_count(get_class_static(), m_label, m_count_property, _scs_create(m_count_property_setter), _scs_create(m_count_property_getter), m_prefix) #define ADD_ARRAY_COUNT_WITH_USAGE_FLAGS(m_label, m_count_property, m_count_property_setter, m_count_property_getter, m_prefix, m_property_usage_flags) ClassDB::add_property_array_count(get_class_static(), m_label, m_count_property, _scs_create(m_count_property_setter), _scs_create(m_count_property_getter), m_prefix, m_property_usage_flags) #define ADD_ARRAY(m_array_path, m_prefix) ClassDB::add_property_array(get_class_static(), m_array_path, m_prefix) // Helper macro to use with PROPERTY_HINT_ARRAY_TYPE for arrays of specific resources: // PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("Font") #define MAKE_RESOURCE_TYPE_HINT(m_type) vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, m_type)
121926
struct PropertyInfo { Variant::Type type = Variant::NIL; String name; StringName class_name; // For classes PropertyHint hint = PROPERTY_HINT_NONE; String hint_string; uint32_t usage = PROPERTY_USAGE_DEFAULT; // If you are thinking about adding another member to this class, ask the maintainer (Juan) first. _FORCE_INLINE_ PropertyInfo added_usage(uint32_t p_fl) const { PropertyInfo pi = *this; pi.usage |= p_fl; return pi; } operator Dictionary() const; static PropertyInfo from_dict(const Dictionary &p_dict); PropertyInfo() {} PropertyInfo(const Variant::Type p_type, const String &p_name, const PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_string = "", const uint32_t p_usage = PROPERTY_USAGE_DEFAULT, const StringName &p_class_name = StringName()) : type(p_type), name(p_name), hint(p_hint), hint_string(p_hint_string), usage(p_usage) { if (hint == PROPERTY_HINT_RESOURCE_TYPE) { class_name = hint_string; } else { class_name = p_class_name; } } PropertyInfo(const StringName &p_class_name) : type(Variant::OBJECT), class_name(p_class_name) {} explicit PropertyInfo(const GDExtensionPropertyInfo &pinfo) : type((Variant::Type)pinfo.type), name(*reinterpret_cast<StringName *>(pinfo.name)), class_name(*reinterpret_cast<StringName *>(pinfo.class_name)), hint((PropertyHint)pinfo.hint), hint_string(*reinterpret_cast<String *>(pinfo.hint_string)), usage(pinfo.usage) {} bool operator==(const PropertyInfo &p_info) const { return ((type == p_info.type) && (name == p_info.name) && (class_name == p_info.class_name) && (hint == p_info.hint) && (hint_string == p_info.hint_string) && (usage == p_info.usage)); } bool operator<(const PropertyInfo &p_info) const { return name < p_info.name; } }; TypedArray<Dictionary> convert_property_list(const List<PropertyInfo> *p_list); enum MethodFlags { METHOD_FLAG_NORMAL = 1, METHOD_FLAG_EDITOR = 2, METHOD_FLAG_CONST = 4, METHOD_FLAG_VIRTUAL = 8, METHOD_FLAG_VARARG = 16, METHOD_FLAG_STATIC = 32, METHOD_FLAG_OBJECT_CORE = 64, METHOD_FLAG_VIRTUAL_REQUIRED = 128, METHOD_FLAGS_DEFAULT = METHOD_FLAG_NORMAL, }; struct MethodInfo { String name; PropertyInfo return_val; uint32_t flags = METHOD_FLAGS_DEFAULT; int id = 0; List<PropertyInfo> arguments; Vector<Variant> default_arguments; int return_val_metadata = 0; Vector<int> arguments_metadata; int get_argument_meta(int p_arg) const { ERR_FAIL_COND_V(p_arg < -1 || p_arg > arguments.size(), 0); if (p_arg == -1) { return return_val_metadata; } return arguments_metadata.size() > p_arg ? arguments_metadata[p_arg] : 0; } inline bool operator==(const MethodInfo &p_method) const { return id == p_method.id && name == p_method.name; } inline bool operator<(const MethodInfo &p_method) const { return id == p_method.id ? (name < p_method.name) : (id < p_method.id); } operator Dictionary() const; static MethodInfo from_dict(const Dictionary &p_dict); MethodInfo() {} explicit MethodInfo(const GDExtensionMethodInfo &pinfo) : name(*reinterpret_cast<StringName *>(pinfo.name)), return_val(PropertyInfo(pinfo.return_value)), flags(pinfo.flags), id(pinfo.id) { for (uint32_t j = 0; j < pinfo.argument_count; j++) { arguments.push_back(PropertyInfo(pinfo.arguments[j])); } const Variant *def_values = (const Variant *)pinfo.default_arguments; for (uint32_t j = 0; j < pinfo.default_argument_count; j++) { default_arguments.push_back(def_values[j]); } } void _push_params(const PropertyInfo &p_param) { arguments.push_back(p_param); } template <typename... VarArgs> void _push_params(const PropertyInfo &p_param, VarArgs... p_params) { arguments.push_back(p_param); _push_params(p_params...); } MethodInfo(const String &p_name) { name = p_name; } template <typename... VarArgs> MethodInfo(const String &p_name, VarArgs... p_params) { name = p_name; _push_params(p_params...); } MethodInfo(Variant::Type ret) { return_val.type = ret; } MethodInfo(Variant::Type ret, const String &p_name) { return_val.type = ret; name = p_name; } template <typename... VarArgs> MethodInfo(Variant::Type ret, const String &p_name, VarArgs... p_params) { name = p_name; return_val.type = ret; _push_params(p_params...); } MethodInfo(const PropertyInfo &p_ret, const String &p_name) { return_val = p_ret; name = p_name; } template <typename... VarArgs> MethodInfo(const PropertyInfo &p_ret, const String &p_name, VarArgs... p_params) { return_val = p_ret; name = p_name; _push_params(p_params...); } }; // API used to extend in GDExtension and other C compatible compiled languages. class MethodBind; class GDExtension; struct ObjectGDExtension { GDExtension *library = nullptr; ObjectGDExtension *parent = nullptr; List<ObjectGDExtension *> children; StringName parent_class_name; StringName class_name; bool editor_class = false; bool reloadable = false; bool is_virtual = false; bool is_abstract = false; bool is_exposed = true; #ifdef TOOLS_ENABLED bool is_runtime = false; bool is_placeholder = false; #endif GDExtensionClassSet set; GDExtensionClassGet get; GDExtensionClassGetPropertyList get_property_list; GDExtensionClassFreePropertyList2 free_property_list2; GDExtensionClassPropertyCanRevert property_can_revert; GDExtensionClassPropertyGetRevert property_get_revert; GDExtensionClassValidateProperty validate_property; #ifndef DISABLE_DEPRECATED GDExtensionClassNotification notification; GDExtensionClassFreePropertyList free_property_list; #endif // DISABLE_DEPRECATED GDExtensionClassNotification2 notification2; GDExtensionClassToString to_string; GDExtensionClassReference reference; GDExtensionClassReference unreference; GDExtensionClassGetRID get_rid; _FORCE_INLINE_ bool is_class(const String &p_class) const { const ObjectGDExtension *e = this; while (e) { if (p_class == e->class_name.operator String()) { return true; } e = e->parent; } return false; } void *class_userdata = nullptr; #ifndef DISABLE_DEPRECATED GDExtensionClassCreateInstance create_instance; #endif // DISABLE_DEPRECATED GDExtensionClassCreateInstance2 create_instance2; GDExtensionClassFreeInstance free_instance; GDExtensionClassGetVirtual get_virtual; GDExtensionClassGetVirtualCallData get_virtual_call_data; GDExtensionClassCallVirtualWithData call_virtual_with_data; GDExtensionClassRecreateInstance recreate_instance; #ifdef TOOLS_ENABLED void *tracking_userdata = nullptr; void (*track_instance)(void *p_userdata, void *p_instance) = nullptr; void (*untrack_instance)(void *p_userdata, void *p_instance) = nullptr; #endif }; #define GDVIRTUAL_CALL(m_name, ...) _gdvirtual_##m_name##_call(__VA_ARGS__) #define GDVIRTUAL_CALL_PTR(m_obj, m_name, ...) m_obj->_gdvirtual_##m_name##_call(__VA_ARGS__) #ifdef DEBUG_METHODS_ENABLED #define GDVIRTUAL_BIND(m_name, ...) ::ClassDB::add_virtual_method(get_class_static(), _gdvirtual_##m_name##_get_method_info(), true, sarray(__VA_ARGS__)); #else #define GDVIRTUAL_BIND(m_name, ...) #endif #define GDVIRTUAL_IS_OVERRIDDEN(m_name) _gdvirtual_##m_name##_overridden() #define GDVIRTUAL_IS_OVERRIDDEN_PTR(m_obj, m_name) m_obj->_gdvirtual_##m_name##_overridden() /* * The following is an incomprehensible blob of hacks and workarounds to * compensate for many of the fallacies in C++. As a plus, this macro pretty * much alone defines the object model. */ #define GDCLASS(m_class, m_inherits)
122003
#ifndef TYPED_ARRAY_H #define TYPED_ARRAY_H #include "core/object/object.h" #include "core/variant/array.h" #include "core/variant/binder_common.h" #include "core/variant/method_ptrcall.h" #include "core/variant/type_info.h" #include "core/variant/variant.h" template <typename T> class TypedArray : public Array { public: _FORCE_INLINE_ void operator=(const Array &p_array) { ERR_FAIL_COND_MSG(!is_same_typed(p_array), "Cannot assign an array with a different element type."); _ref(p_array); } _FORCE_INLINE_ TypedArray(const Variant &p_variant) : TypedArray(Array(p_variant)) { } _FORCE_INLINE_ TypedArray(const Array &p_array) { set_typed(Variant::OBJECT, T::get_class_static(), Variant()); if (is_same_typed(p_array)) { _ref(p_array); } else { assign(p_array); } } _FORCE_INLINE_ TypedArray() { set_typed(Variant::OBJECT, T::get_class_static(), Variant()); } }; template <typename T> struct VariantInternalAccessor<TypedArray<T>> { static _FORCE_INLINE_ TypedArray<T> get(const Variant *v) { return *VariantInternal::get_array(v); } static _FORCE_INLINE_ void set(Variant *v, const TypedArray<T> &p_array) { *VariantInternal::get_array(v) = p_array; } }; template <typename T> struct VariantInternalAccessor<const TypedArray<T> &> { static _FORCE_INLINE_ TypedArray<T> get(const Variant *v) { return *VariantInternal::get_array(v); } static _FORCE_INLINE_ void set(Variant *v, const TypedArray<T> &p_array) { *VariantInternal::get_array(v) = p_array; } }; //specialization for the rest of variant types #define MAKE_TYPED_ARRAY(m_type, m_variant_type) \ template <> \ class TypedArray<m_type> : public Array { \ public: \ _FORCE_INLINE_ void operator=(const Array &p_array) { \ ERR_FAIL_COND_MSG(!is_same_typed(p_array), "Cannot assign an array with a different element type."); \ _ref(p_array); \ } \ _FORCE_INLINE_ TypedArray(const Variant &p_variant) : \ TypedArray(Array(p_variant)) { \ } \ _FORCE_INLINE_ TypedArray(const Array &p_array) { \ set_typed(m_variant_type, StringName(), Variant()); \ if (is_same_typed(p_array)) { \ _ref(p_array); \ } else { \ assign(p_array); \ } \ } \ _FORCE_INLINE_ TypedArray() { \ set_typed(m_variant_type, StringName(), Variant()); \ } \ }; // All Variant::OBJECT types are intentionally omitted from this list because they are handled by // the unspecialized TypedArray definition. MAKE_TYPED_ARRAY(bool, Variant::BOOL) MAKE_TYPED_ARRAY(uint8_t, Variant::INT) MAKE_TYPED_ARRAY(int8_t, Variant::INT) MAKE_TYPED_ARRAY(uint16_t, Variant::INT) MAKE_TYPED_ARRAY(int16_t, Variant::INT) MAKE_TYPED_ARRAY(uint32_t, Variant::INT) MAKE_TYPED_ARRAY(int32_t, Variant::INT) MAKE_TYPED_ARRAY(uint64_t, Variant::INT) MAKE_TYPED_ARRAY(int64_t, Variant::INT) MAKE_TYPED_ARRAY(float, Variant::FLOAT) MAKE_TYPED_ARRAY(double, Variant::FLOAT) MAKE_TYPED_ARRAY(String, Variant::STRING) MAKE_TYPED_ARRAY(Vector2, Variant::VECTOR2) MAKE_TYPED_ARRAY(Vector2i, Variant::VECTOR2I) MAKE_TYPED_ARRAY(Rect2, Variant::RECT2) MAKE_TYPED_ARRAY(Rect2i, Variant::RECT2I) MAKE_TYPED_ARRAY(Vector3, Variant::VECTOR3) MAKE_TYPED_ARRAY(Vector3i, Variant::VECTOR3I) MAKE_TYPED_ARRAY(Transform2D, Variant::TRANSFORM2D) MAKE_TYPED_ARRAY(Vector4, Variant::VECTOR4) MAKE_TYPED_ARRAY(Vector4i, Variant::VECTOR4I) MAKE_TYPED_ARRAY(Plane, Variant::PLANE) MAKE_TYPED_ARRAY(Quaternion, Variant::QUATERNION) MAKE_TYPED_ARRAY(AABB, Variant::AABB) MAKE_TYPED_ARRAY(Basis, Variant::BASIS) MAKE_TYPED_ARRAY(Transform3D, Variant::TRANSFORM3D) MAKE_TYPED_ARRAY(Projection, Variant::PROJECTION) MAKE_TYPED_ARRAY(Color, Variant::COLOR) MAKE_TYPED_ARRAY(StringName, Variant::STRING_NAME) MAKE_TYPED_ARRAY(NodePath, Variant::NODE_PATH) MAKE_TYPED_ARRAY(RID, Variant::RID) MAKE_TYPED_ARRAY(Callable, Variant::CALLABLE) MAKE_TYPED_ARRAY(Signal, Variant::SIGNAL) MAKE_TYPED_ARRAY(Dictionary, Variant::DICTIONARY) MAKE_TYPED_ARRAY(Array, Variant::ARRAY) MAKE_TYPED_ARRAY(PackedByteArray, Variant::PACKED_BYTE_ARRAY) MAKE_TYPED_ARRAY(PackedInt32Array, Variant::PACKED_INT32_ARRAY) MAKE_TYPED_ARRAY(PackedInt64Array, Variant::PACKED_INT64_ARRAY) MAKE_TYPED_ARRAY(PackedFloat32Array, Variant::PACKED_FLOAT32_ARRAY) MAKE_TYPED_ARRAY(PackedFloat64Array, Variant::PACKED_FLOAT64_ARRAY) MAKE_TYPED_ARRAY(PackedStringArray, Variant::PACKED_STRING_ARRAY) MAKE_TYPED_ARRAY(PackedVector2Array, Variant::PACKED_VECTOR2_ARRAY) MAKE_TYPED_ARRAY(PackedVector3Array, Variant::PACKED_VECTOR3_ARRAY) MAKE_TYPED_ARRAY(PackedColorArray, Variant::PACKED_COLOR_ARRAY) MAKE_TYPED_ARRAY(PackedVector4Array, Variant::PACKED_VECTOR4_ARRAY) MAKE_TYPED_ARRAY(IPAddress, Variant::STRING) template <typename T> struct PtrToArg<TypedArray<T>> { _FORCE_INLINE_ static TypedArray<T> convert(const void *p_ptr) { return TypedArray<T>(*reinterpret_cast<const Array *>(p_ptr)); } typedef Array EncodeT; _FORCE_INLINE_ static void encode(TypedArray<T> p_val, void *p_ptr) { *(Array *)p_ptr = p_val; } }; template <typename T> struct PtrToArg<const TypedArray<T> &> { typedef Array EncodeT; _FORCE_INLINE_ static TypedArray<T> convert(const void *p_ptr) { return TypedArray<T>(*reinterpret_cast<const Array *>(p_ptr)); } }; template <typename T> struct GetTypeInfo<TypedArray<T>> { static const Variant::Type VARIANT_TYPE = Variant::ARRAY; static const GodotTypeInfo::Metadata METADATA = GodotTypeInfo::METADATA_NONE; static inline PropertyInfo get_class_info() { return PropertyInfo(Variant::ARRAY, String(), PROPERTY_HINT_ARRAY_TYPE, T::get_class_static()); } }; template <typename T> struct GetTypeInfo<const TypedArray<T> &> { static const Variant::Type VARIANT_TYPE = Variant::ARRAY; static const GodotTypeInfo::Metadata METADATA = GodotTypeInfo::METADATA_NONE; static inline PropertyInfo get_class_info() { return PropertyInfo(Variant::ARRAY, String(), PROPERTY_HINT_ARRAY_TYPE, T::get_class_static()); } }; #define MAKE_TYPED_ARRAY_INFO(m_type, m_variant_type) \ template <> \ struct GetTypeInfo<TypedArray<m_type>> { \ static const Variant::Type VARIANT_TYPE = Variant::ARRAY; \ static const GodotTypeInfo::Metadata METADATA = GodotTypeInfo::METADATA_NONE; \ static inline PropertyInfo get_class_info() { \ return PropertyInfo(Variant::ARRAY, String(), PROPERTY_HINT_ARRAY_TYPE, Variant::get_type_name(m_variant_type)); \ } \ }; \ template <> \ struct GetTypeInfo<const TypedArray<m_type> &> { \ static const Variant::Type VARIANT_TYPE = Variant::ARRAY; \ static const GodotTypeInfo::Metadata METADATA = GodotTypeInfo::METADATA_NONE; \ static inline PropertyInfo get_class_info() { \ return PropertyInfo(Variant::ARRAY, String(), PROPERTY_HINT_ARRAY_TYPE, Variant::get_type_name(m_variant_type)); \ } \ }; MAKE_TYPED_ARRAY_INFO(bool, Variant::BOOL) MAKE_TYPED_ARRAY_INFO(uint8_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(int8_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(uint16_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(int16_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(uint32_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(int32_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(uint64_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(int64_t, Variant::INT) MAKE_TYPED_ARRAY_INFO(float, Variant::FLOAT) MAKE_TYPED_ARRAY_INFO(double, Variant::FLOAT) MAKE_TYPED_ARRAY_INFO(String, Variant::STRING) MAKE_TYPED_ARRAY_INFO(Vector2, Variant::VECTOR2) MAKE_TYPED_ARRAY_INFO(Vector2i, Variant::VECTOR2I) MAKE_TYPED_ARRAY_INFO(Rect2, Variant::RECT2) MAKE_TYPED_ARRAY_INFO(Rect2i, Variant::RECT2I) MAKE_TYPED_ARRAY_INFO(Vector3, Variant::VECTOR3) MAKE_TYPED_ARRAY_INFO(Vector3i, Variant::VECTOR3I)
122012
uint64_t get_indexed_size() const; /* Keying */ static bool is_keyed(Variant::Type p_type); typedef void (*ValidatedKeyedSetter)(Variant *base, const Variant *key, const Variant *value, bool *valid); typedef void (*ValidatedKeyedGetter)(const Variant *base, const Variant *key, Variant *value, bool *valid); typedef bool (*ValidatedKeyedChecker)(const Variant *base, const Variant *key, bool *valid); static ValidatedKeyedSetter get_member_validated_keyed_setter(Variant::Type p_type); static ValidatedKeyedGetter get_member_validated_keyed_getter(Variant::Type p_type); static ValidatedKeyedChecker get_member_validated_keyed_checker(Variant::Type p_type); typedef void (*PTRKeyedSetter)(void *base, const void *key, const void *value); typedef void (*PTRKeyedGetter)(const void *base, const void *key, void *value); typedef uint32_t (*PTRKeyedChecker)(const void *base, const void *key); static PTRKeyedSetter get_member_ptr_keyed_setter(Variant::Type p_type); static PTRKeyedGetter get_member_ptr_keyed_getter(Variant::Type p_type); static PTRKeyedChecker get_member_ptr_keyed_checker(Variant::Type p_type); void set_keyed(const Variant &p_key, const Variant &p_value, bool &r_valid); Variant get_keyed(const Variant &p_key, bool &r_valid) const; bool has_key(const Variant &p_key, bool &r_valid) const; /* Generic */ enum VariantSetError { SET_OK, SET_KEYED_ERR, SET_NAMED_ERR, SET_INDEXED_ERR }; enum VariantGetError { GET_OK, GET_KEYED_ERR, GET_NAMED_ERR, GET_INDEXED_ERR }; void set(const Variant &p_index, const Variant &p_value, bool *r_valid = nullptr, VariantSetError *err_code = nullptr); Variant get(const Variant &p_index, bool *r_valid = nullptr, VariantGetError *err_code = nullptr) const; bool in(const Variant &p_index, bool *r_valid = nullptr) const; bool iter_init(Variant &r_iter, bool &r_valid) const; bool iter_next(Variant &r_iter, bool &r_valid) const; Variant iter_get(const Variant &r_iter, bool &r_valid) const; void get_property_list(List<PropertyInfo> *p_list) const; static void call_utility_function(const StringName &p_name, Variant *r_ret, const Variant **p_args, int p_argcount, Callable::CallError &r_error); static bool has_utility_function(const StringName &p_name); typedef void (*ValidatedUtilityFunction)(Variant *r_ret, const Variant **p_args, int p_argcount); typedef void (*PTRUtilityFunction)(void *r_ret, const void **p_args, int p_argcount); static ValidatedUtilityFunction get_validated_utility_function(const StringName &p_name); static PTRUtilityFunction get_ptr_utility_function(const StringName &p_name); enum UtilityFunctionType { UTILITY_FUNC_TYPE_MATH, UTILITY_FUNC_TYPE_RANDOM, UTILITY_FUNC_TYPE_GENERAL, }; static UtilityFunctionType get_utility_function_type(const StringName &p_name); static MethodInfo get_utility_function_info(const StringName &p_name); static int get_utility_function_argument_count(const StringName &p_name); static Variant::Type get_utility_function_argument_type(const StringName &p_name, int p_arg); static String get_utility_function_argument_name(const StringName &p_name, int p_arg); static bool has_utility_function_return_value(const StringName &p_name); static Variant::Type get_utility_function_return_type(const StringName &p_name); static bool is_utility_function_vararg(const StringName &p_name); static uint32_t get_utility_function_hash(const StringName &p_name); static void get_utility_function_list(List<StringName> *r_functions); static int get_utility_function_count(); //argsVariant call() bool operator==(const Variant &p_variant) const; bool operator!=(const Variant &p_variant) const; bool operator<(const Variant &p_variant) const; uint32_t hash() const; uint32_t recursive_hash(int recursion_count) const; // By default, performs a semantic comparison. Otherwise, numeric/binary comparison (if appropriate). bool hash_compare(const Variant &p_variant, int recursion_count = 0, bool semantic_comparison = true) const; bool identity_compare(const Variant &p_variant) const; bool booleanize() const; String stringify(int recursion_count = 0) const; String to_json_string() const; void static_assign(const Variant &p_variant); static void get_constants_for_type(Variant::Type p_type, List<StringName> *p_constants); static int get_constants_count_for_type(Variant::Type p_type); static bool has_constant(Variant::Type p_type, const StringName &p_value); static Variant get_constant_value(Variant::Type p_type, const StringName &p_value, bool *r_valid = nullptr); static void get_enums_for_type(Variant::Type p_type, List<StringName> *p_enums); static void get_enumerations_for_enum(Variant::Type p_type, const StringName &p_enum_name, List<StringName> *p_enumerations); static int get_enum_value(Variant::Type p_type, const StringName &p_enum_name, const StringName &p_enumeration, bool *r_valid = nullptr); typedef String (*ObjectDeConstruct)(const Variant &p_object, void *ud); typedef void (*ObjectConstruct)(const String &p_text, void *ud, Variant &r_value); String get_construct_string() const; static void construct_from_string(const String &p_string, Variant &r_value, ObjectConstruct p_obj_construct = nullptr, void *p_construct_ud = nullptr); void operator=(const Variant &p_variant); // only this is enough for all the other types static void register_types(); static void unregister_types(); Variant(const Variant &p_variant); _FORCE_INLINE_ Variant() : type(NIL) {} _FORCE_INLINE_ ~Variant() { clear(); } }; //typedef Dictionary Dictionary; no //typedef Array Array; template <typename... VarArgs> Vector<Variant> varray(VarArgs... p_args) { Vector<Variant> v; Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported. uint32_t argc = sizeof...(p_args); if (argc > 0) { v.resize(argc); Variant *vw = v.ptrw(); for (uint32_t i = 0; i < argc; i++) { vw[i] = args[i]; } } return v; } struct VariantHasher { static _FORCE_INLINE_ uint32_t hash(const Variant &p_variant) { return p_variant.hash(); } }; struct VariantComparator { static _FORCE_INLINE_ bool compare(const Variant &p_lhs, const Variant &p_rhs) { return p_lhs.hash_compare(p_rhs); } }; struct StringLikeVariantComparator { static bool compare(const Variant &p_lhs, const Variant &p_rhs); }; struct StringLikeVariantOrder { static _ALWAYS_INLINE_ bool compare(const Variant &p_lhs, const Variant &p_rhs) { if (p_lhs.is_string() && p_rhs.is_string()) { return p_lhs.operator String() < p_rhs.operator String(); } return p_lhs < p_rhs; } _ALWAYS_INLINE_ bool operator()(const Variant &p_lhs, const Variant &p_rhs) const { return compare(p_lhs, p_rhs); } }; Variant::ObjData &Variant::_get_obj() { return *reinterpret_cast<ObjData *>(&_data._mem[0]); } const Variant::ObjData &Variant::_get_obj() const { return *reinterpret_cast<const ObjData *>(&_data._mem[0]); } template <typename... VarArgs> String vformat(const String &p_text, const VarArgs... p_args) { Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported. Array args_array; args_array.resize(sizeof...(p_args)); for (uint32_t i = 0; i < sizeof...(p_args); i++) { args_array[i] = args[i]; } bool error = false; String fmt = p_text.sprintf(args_array, &error); ERR_FAIL_COND_V_MSG(error, String(), String("Formatting error in string \"") + p_text + "\": " + fmt + "."); return fmt; } template <typename... VarArgs> Variant
122202
#!/usr/bin/env python3 import argparse import contextlib import os import socket import subprocess import sys from http.server import HTTPServer, SimpleHTTPRequestHandler from pathlib import Path # See cpython GH-17851 and GH-17864. class DualStackServer(HTTPServer): def server_bind(self): # Suppress exception when protocol is IPv4. with contextlib.suppress(Exception): self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) return super().server_bind() class CORSRequestHandler(SimpleHTTPRequestHandler): def end_headers(self): self.send_header("Cross-Origin-Opener-Policy", "same-origin") self.send_header("Cross-Origin-Embedder-Policy", "require-corp") self.send_header("Access-Control-Allow-Origin", "*") super().end_headers() def shell_open(url): if sys.platform == "win32": os.startfile(url) else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, url]) def serve(root, port, run_browser): os.chdir(root) address = ("", port) httpd = DualStackServer(address, CORSRequestHandler) url = f"http://127.0.0.1:{port}" if run_browser: # Open the served page in the user's default browser. print(f"Opening the served URL in the default browser (use `--no-browser` or `-n` to disable this): {url}") shell_open(url) else: print(f"Serving at: {url}") try: httpd.serve_forever() except KeyboardInterrupt: print("\nKeyboard interrupt received, stopping server.") finally: # Clean-up server httpd.server_close() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", help="port to listen on", default=8060, type=int) parser.add_argument( "-r", "--root", help="path to serve as root (relative to `platform/web/`)", default="../../bin", type=Path ) browser_parser = parser.add_mutually_exclusive_group(required=False) browser_parser.add_argument( "-n", "--no-browser", help="don't open default web browser automatically", dest="browser", action="store_false" ) parser.set_defaults(browser=True) args = parser.parse_args() # Change to the directory where the script is located, # so that the script can be run from any location. os.chdir(Path(__file__).resolve().parent) serve(args.root, args.port, args.browser)
122217
/**************************************************************************/ /* http_client_web.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 HTTP_CLIENT_WEB_H #define HTTP_CLIENT_WEB_H #include "core/io/http_client.h" #ifdef __cplusplus extern "C" { #endif #include <stddef.h> typedef enum { GODOT_JS_FETCH_STATE_REQUESTING = 0, GODOT_JS_FETCH_STATE_BODY = 1, GODOT_JS_FETCH_STATE_DONE = 2, GODOT_JS_FETCH_STATE_ERROR = -1, } godot_js_fetch_state_t; extern int godot_js_fetch_create(const char *p_method, const char *p_url, const char **p_headers, int p_headers_len, const uint8_t *p_body, int p_body_len); extern int godot_js_fetch_read_headers(int p_id, void (*parse_callback)(int p_size, const char **p_headers, void *p_ref), void *p_ref); extern int godot_js_fetch_read_chunk(int p_id, uint8_t *p_buf, int p_buf_size); extern void godot_js_fetch_free(int p_id); extern godot_js_fetch_state_t godot_js_fetch_state_get(int p_id); extern int godot_js_fetch_http_status_get(int p_id); extern int godot_js_fetch_is_chunked(int p_id); #ifdef __cplusplus } #endif class HTTPClientWeb : public HTTPClient { private: int js_id = 0; Status status = STATUS_DISCONNECTED; // 64 KiB by default (favors fast download speeds at the cost of memory usage). int read_limit = 65536; String host; int port = -1; bool use_tls = false; int polled_response_code = 0; Vector<String> response_headers; Vector<uint8_t> response_buffer; #ifdef DEBUG_ENABLED uint64_t last_polling_frame = 0; #endif static void _parse_headers(int p_len, const char **p_headers, void *p_ref); public: static HTTPClient *_create_func(bool p_notify_postinitialize); Error request(Method p_method, const String &p_url, const Vector<String> &p_headers, const uint8_t *p_body, int p_body_size) override; Error connect_to_host(const String &p_host, int p_port = -1, Ref<TLSOptions> p_tls_options = Ref<TLSOptions>()) override; void set_connection(const Ref<StreamPeer> &p_connection) override; Ref<StreamPeer> get_connection() const override; void close() override; Status get_status() const override; bool has_response() const override; bool is_response_chunked() const override; int get_response_code() const override; Error get_response_headers(List<String> *r_response) override; int64_t get_response_body_length() const override; PackedByteArray read_response_body_chunk() override; void set_blocking_mode(bool p_enable) override; bool is_blocking_mode_enabled() const override; void set_read_chunk_size(int p_size) override; int get_read_chunk_size() const override; Error poll() override; HTTPClientWeb(); ~HTTPClientWeb(); }; #endif // HTTP_CLIENT_WEB_H
122257
const Features = { /** * Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for. * * @param {number=} [majorVersion=1] The major WebGL version to check for. * @returns {boolean} If the given major version of WebGL is available. * @function Engine.isWebGLAvailable */ isWebGLAvailable: function (majorVersion = 1) { try { return !!document.createElement('canvas').getContext(['webgl', 'webgl2'][majorVersion - 1]); } catch (e) { /* Not available */ } return false; }, /** * Check whether the Fetch API available and supports streaming responses. * * @returns {boolean} If the Fetch API is available and supports streaming responses. * @function Engine.isFetchAvailable */ isFetchAvailable: function () { return 'fetch' in window && 'Response' in window && 'body' in window.Response.prototype; }, /** * Check whether the engine is running in a Secure Context. * * @returns {boolean} If the engine is running in a Secure Context. * @function Engine.isSecureContext */ isSecureContext: function () { return window['isSecureContext'] === true; }, /** * Check whether the engine is cross origin isolated. * This value is dependent on Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers sent by the server. * * @returns {boolean} If the engine is running in a Secure Context. * @function Engine.isSecureContext */ isCrossOriginIsolated: function () { return window['crossOriginIsolated'] === true; }, /** * Check whether SharedBufferArray is available. * * Most browsers require the page to be running in a secure context, and the * the server to provide specific CORS headers for SharedArrayBuffer to be available. * * @returns {boolean} If SharedArrayBuffer is available. * @function Engine.isSharedArrayBufferAvailable */ isSharedArrayBufferAvailable: function () { return 'SharedArrayBuffer' in window; }, /** * Check whether the AudioContext supports AudioWorkletNodes. * * @returns {boolean} If AudioWorkletNode is available. * @function Engine.isAudioWorkletAvailable */ isAudioWorkletAvailable: function () { return 'AudioContext' in window && 'audioWorklet' in AudioContext.prototype; }, /** * Return an array of missing required features (as string). * * @returns {Array<string>} A list of human-readable missing features. * @function Engine.getMissingFeatures * @param {{threads: (boolean|undefined)}} supportedFeatures */ getMissingFeatures: function (supportedFeatures = {}) { const { // Quotes are needed for the Closure compiler. 'threads': supportsThreads = true, } = supportedFeatures; const missing = []; if (!Features.isWebGLAvailable(2)) { missing.push('WebGL2 - Check web browser configuration and hardware support'); } if (!Features.isFetchAvailable()) { missing.push('Fetch - Check web browser version'); } if (!Features.isSecureContext()) { missing.push('Secure Context - Check web server configuration (use HTTPS)'); } if (supportsThreads) { if (!Features.isCrossOriginIsolated()) { missing.push('Cross-Origin Isolation - Check that the web server configuration sends the correct headers.'); } if (!Features.isSharedArrayBufferAvailable()) { missing.push('SharedArrayBuffer - Check that the web server configuration sends the correct headers.'); } } // Audio is normally optional since we have a dummy fallback. return missing; }, };
122264
<?xml version="1.0" encoding="UTF-8" ?> <class name="EditorExportPlatformWeb" inherits="EditorExportPlatform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> Exporter for the Web. </brief_description> <description> The Web exporter customizes how a web build is handled. In the editor's "Export" window, it is created when adding a new "Web" preset. [b]Note:[/b] Godot on Web is rendered inside a [code]&lt;canvas&gt;[/code] tag. Normally, the canvas cannot be positioned or resized manually, but otherwise acts as the main [Window] of the application. </description> <tutorials> <link title="Exporting for the Web">$DOCS_URL/tutorials/export/exporting_for_web.html</link> <link title="Web documentation index">$DOCS_URL/tutorials/platform/web/index.html</link> </tutorials> <members> <member name="custom_template/debug" type="String" setter="" getter=""> File path to the custom export template used for debug builds. If left empty, the default template is used. </member> <member name="custom_template/release" type="String" setter="" getter=""> File path to the custom export template used for release builds. If left empty, the default template is used. </member> <member name="html/canvas_resize_policy" type="int" setter="" getter=""> Determines how the canvas should be resized by Godot. - [b]None:[/b] The canvas is not automatically resized. - [b]Project:[/b] The size of the canvas is dependent on the [ProjectSettings]. - [b]Adaptive:[/b] The canvas is automatically resized to fit as much of the web page as possible. </member> <member name="html/custom_html_shell" type="String" setter="" getter=""> The custom HTML page that wraps the exported web build. If left empty, the default HTML shell is used. For more information, see the [url=$DOCS_URL/tutorials/platform/web/customizing_html5_shell.html]Customizing HTML5 Shell[/url] tutorial. </member> <member name="html/experimental_virtual_keyboard" type="bool" setter="" getter="" experimental=""> If [code]true[/code], embeds support for a virtual keyboard into the web page, which is shown when necessary on touchscreen devices. </member> <member name="html/export_icon" type="bool" setter="" getter=""> If [code]true[/code], the project icon will be used as the favicon for this application's web page. </member> <member name="html/focus_canvas_on_start" type="bool" setter="" getter=""> If [code]true[/code], the canvas will be focused as soon as the application is loaded, if the browser window is already in focus. </member> <member name="html/head_include" type="String" setter="" getter=""> Additional HTML tags to include inside the [code]&lt;head&gt;[/code], such as [code]&lt;meta&gt;[/code] tags. [b]Note:[/b] You do not need to add a [code]&lt;title&gt;[/code] tag, as it is automatically included based on the project's name. </member> <member name="progressive_web_app/background_color" type="Color" setter="" getter=""> The background color used behind the web application. </member> <member name="progressive_web_app/display" type="int" setter="" getter=""> The [url=https://developer.mozilla.org/en-US/docs/Web/Manifest/display/]display mode[/url] to use for this progressive web application. Different browsers and platforms may not behave the same. - [b]Fullscreen:[/b] Displays the app in fullscreen and hides all of the browser's UI elements. - [b]Standalone:[/b] Displays the app in a separate window and hides all of the browser's UI elements. - [b]Minimal UI:[/b] Displays the app in a separate window and only shows the browser's UI elements for navigation. - [b]Browser:[/b] Displays the app as a normal web page. </member> <member name="progressive_web_app/enabled" type="bool" setter="" getter=""> If [code]true[/code], turns this web build into a [url=https://en.wikipedia.org/wiki/Progressive_web_app]progressive web application[/url] (PWA). </member> <member name="progressive_web_app/ensure_cross_origin_isolation_headers" type="bool" setter="" getter=""> When enabled, the progressive web app will make sure that each request has cross-origin isolation headers (COEP/COOP). This can simplify the setup to serve the exported game. </member> <member name="progressive_web_app/icon_144x144" type="String" setter="" getter=""> File path to the smallest icon for this web application. If not defined, defaults to the project icon. [b]Note:[/b] If the icon is not 144x144, it will be automatically resized for the final build. </member> <member name="progressive_web_app/icon_180x180" type="String" setter="" getter=""> File path to the small icon for this web application. If not defined, defaults to the project icon. [b]Note:[/b] If the icon is not 180x180, it will be automatically resized for the final build. </member> <member name="progressive_web_app/icon_512x512" type="String" setter="" getter=""> File path to the smallest icon for this web application. If not defined, defaults to the project icon. [b]Note:[/b] If the icon is not 512x512, it will be automatically resized for the final build. </member> <member name="progressive_web_app/offline_page" type="String" setter="" getter=""> The page to display, should the server hosting the page not be available. This page is saved in the client's machine. </member> <member name="progressive_web_app/orientation" type="int" setter="" getter=""> The orientation to use when the web application is run through a mobile device. - [b]Any:[/b] No orientation is forced. - [b]Landscape:[/b] Forces a horizontal layout (wider than it is taller). - [b]Portrait:[/b] Forces a vertical layout (taller than it is wider). </member> <member name="variant/extensions_support" type="bool" setter="" getter=""> If [code]true[/code] enables [GDExtension] support for this web build. </member> <member name="variant/thread_support" type="bool" setter="" getter=""> If [code]true[/code], the exported game will support threads. It requires [url=https://web.dev/articles/coop-coep]a "cross-origin isolated" website[/url], which may be difficult to set up and is limited for security reasons (such as not being able to communicate with third-party websites). If [code]false[/code], the exported game will not support threads. As a result, it is more prone to performance and audio issues, but will only require to be run on an HTTPS website. </member> <member name="vram_texture_compression/for_desktop" type="bool" setter="" getter=""> If [code]true[/code], allows textures to be optimized for desktop through the S3TC algorithm. </member> <member name="vram_texture_compression/for_mobile" type="bool" setter="" getter=""> If [code]true[/code] allows textures to be optimized for mobile through the ETC2 algorithm. </member> </members> </class>
122450
boolean handleMouseEvent(final MotionEvent event, int eventActionOverride, boolean doubleTap) { return handleMouseEvent(event, eventActionOverride, event.getButtonState(), doubleTap); } boolean handleMouseEvent(final MotionEvent event, int eventActionOverride, int buttonMaskOverride, boolean doubleTap) { final float x = event.getX(); final float y = event.getY(); final float pressure = event.getPressure(); float verticalFactor = 0; float horizontalFactor = 0; // If event came from RotaryEncoder (Bezel or Crown rotate event on Wear OS smart watches), // convert it to mouse wheel event. if (event.isFromSource(InputDevice.SOURCE_ROTARY_ENCODER)) { if (rotaryInputAxis == ROTARY_INPUT_HORIZONTAL_AXIS) { horizontalFactor = -event.getAxisValue(MotionEvent.AXIS_SCROLL); } else { // If rotaryInputAxis is not ROTARY_INPUT_HORIZONTAL_AXIS then use default ROTARY_INPUT_VERTICAL_AXIS axis. verticalFactor = -event.getAxisValue(MotionEvent.AXIS_SCROLL); } } else { verticalFactor = event.getAxisValue(MotionEvent.AXIS_VSCROLL); horizontalFactor = event.getAxisValue(MotionEvent.AXIS_HSCROLL); } boolean sourceMouseRelative = false; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { sourceMouseRelative = event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE); } return handleMouseEvent(eventActionOverride, buttonMaskOverride, x, y, horizontalFactor, verticalFactor, doubleTap, sourceMouseRelative, pressure, getEventTiltX(event), getEventTiltY(event)); } boolean handleMouseEvent(int eventAction, boolean sourceMouseRelative) { return handleMouseEvent(eventAction, 0, 0f, 0f, 0f, 0f, false, sourceMouseRelative, 1f, 0f, 0f); } boolean handleMouseEvent(int eventAction, int buttonsMask, float x, float y, float deltaX, float deltaY, boolean doubleClick, boolean sourceMouseRelative, float pressure, float tiltX, float tiltY) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return false; } // Fix the buttonsMask switch (eventAction) { case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // Zero-up the button state buttonsMask = 0; break; case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: if (buttonsMask == 0) { buttonsMask = MotionEvent.BUTTON_PRIMARY; } break; } // We don't handle ACTION_BUTTON_PRESS and ACTION_BUTTON_RELEASE events as they typically // follow ACTION_DOWN and ACTION_UP events. As such, handling them would result in duplicate // stream of events to the engine. switch (eventAction) { case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_HOVER_ENTER: case MotionEvent.ACTION_HOVER_EXIT: case MotionEvent.ACTION_HOVER_MOVE: case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_SCROLL: { runnable.setMouseEvent(eventAction, buttonsMask, x, y, deltaX, deltaY, doubleClick, sourceMouseRelative, pressure, tiltX, tiltY); dispatchInputEventRunnable(runnable); return true; } } return false; } boolean handleTouchEvent(final MotionEvent event) { return handleTouchEvent(event, event.getActionMasked()); } boolean handleTouchEvent(final MotionEvent event, int eventActionOverride) { return handleTouchEvent(event, eventActionOverride, false); } boolean handleTouchEvent(final MotionEvent event, int eventActionOverride, boolean doubleTap) { if (event.getPointerCount() == 0) { return true; } InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return false; } switch (eventActionOverride) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_DOWN: { runnable.setTouchEvent(event, eventActionOverride, doubleTap); dispatchInputEventRunnable(runnable); return true; } } return false; } void handleMagnifyEvent(float x, float y, float factor) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } runnable.setMagnifyEvent(x, y, factor); dispatchInputEventRunnable(runnable); } void handlePanEvent(float x, float y, float deltaX, float deltaY) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } runnable.setPanEvent(x, y, deltaX, deltaY); dispatchInputEventRunnable(runnable); } private void handleJoystickButtonEvent(int device, int button, boolean pressed) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } runnable.setJoystickButtonEvent(device, button, pressed); dispatchInputEventRunnable(runnable); } private void handleJoystickAxisEvent(int device, int axis, float value) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } runnable.setJoystickAxisEvent(device, axis, value); dispatchInputEventRunnable(runnable); } private void handleJoystickHatEvent(int device, int hatX, int hatY) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } runnable.setJoystickHatEvent(device, hatX, hatY); dispatchInputEventRunnable(runnable); } private void handleJoystickConnectionChangedEvent(int device, boolean connected, String name) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } runnable.setJoystickConnectionChangedEvent(device, connected, name); dispatchInputEventRunnable(runnable); } void handleKeyEvent(int physicalKeycode, int unicode, int keyLabel, boolean pressed, boolean echo) { InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } runnable.setKeyEvent(physicalKeycode, unicode, keyLabel, pressed, echo); dispatchInputEventRunnable(runnable); } private void dispatchInputEventRunnable(@NonNull InputEventRunnable runnable) { if (shouldDispatchInputToRenderThread()) { godot.runOnRenderThread(runnable); } else { runnable.run(); } } @Override public void onSensorChanged(SensorEvent event) { final float[] values = event.values; if (values == null || values.length != 3) { return; } InputEventRunnable runnable = InputEventRunnable.obtain(); if (runnable == null) { return; } float rotatedValue0 = 0f; float rotatedValue1 = 0f; float rotatedValue2 = 0f; switch (windowManager.getDefaultDisplay().getRotation()) { case Surface.ROTATION_0: rotatedValue0 = values[0]; rotatedValue1 = values[1]; rotatedValue2 = values[2]; break; case Surface.ROTATION_90: rotatedValue0 = -values[1]; rotatedValue1 = values[0]; rotatedValue2 = values[2]; break; case Surface.ROTATION_180: rotatedValue0 = -values[0]; rotatedValue1 = -values[1]; rotatedValue2 = values[2]; break; case Surface.ROTATION_270: rotatedValue0 = values[1]; rotatedValue1 = -values[0]; rotatedValue2 = values[2]; break; } runnable.setSensorEvent(event.sensor.getType(), rotatedValue0, rotatedValue1, rotatedValue2); godot.runOnRenderThread(runnable); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} }
123212
{ const Vector3 vector_x = Vector3(1, 0, 0); const Vector3 vector_y = Vector3(0, 1, 0); const Vector3 vector_z = Vector3(0, 0, 1); const Vector3 a = Vector3(3.5, 8.5, 2.3); const Vector3 b = Vector3(5.2, 4.6, 7.8); CHECK_MESSAGE( vector_x.cross(vector_y) == vector_z, "Vector3 cross product of X and Y should give Z."); CHECK_MESSAGE( vector_y.cross(vector_x) == -vector_z, "Vector3 cross product of Y and X should give negative Z."); CHECK_MESSAGE( vector_y.cross(vector_z) == vector_x, "Vector3 cross product of Y and Z should give X."); CHECK_MESSAGE( vector_z.cross(vector_x) == vector_y, "Vector3 cross product of Z and X should give Y."); CHECK_MESSAGE( a.cross(b).is_equal_approx(Vector3(55.72, -15.34, -28.1)), "Vector3 cross should return expected value."); CHECK_MESSAGE( Vector3(-a.x, a.y, -a.z).cross(Vector3(b.x, -b.y, b.z)).is_equal_approx(Vector3(55.72, 15.34, -28.1)), "Vector2 cross should return expected value."); CHECK_MESSAGE( vector_x.dot(vector_y) == 0.0, "Vector3 dot product of perpendicular vectors should be zero."); CHECK_MESSAGE( vector_x.dot(vector_x) == 1.0, "Vector3 dot product of identical unit vectors should be one."); CHECK_MESSAGE( (vector_x * 10).dot(vector_x * 10) == 100.0, "Vector3 dot product of same direction vectors should behave as expected."); CHECK_MESSAGE( a.dot(b) == doctest::Approx((real_t)75.24), "Vector3 dot should return expected value."); CHECK_MESSAGE( Vector3(-a.x, a.y, -a.z).dot(Vector3(b.x, -b.y, b.z)) == doctest::Approx((real_t)-75.24), "Vector3 dot should return expected value."); } TEST_CASE("[Vector3] Finite number checks") { const double infinite[] = { NAN, INFINITY, -INFINITY }; CHECK_MESSAGE( Vector3(0, 1, 2).is_finite(), "Vector3(0, 1, 2) should be finite"); for (double x : infinite) { CHECK_FALSE_MESSAGE( Vector3(x, 1, 2).is_finite(), "Vector3 with one component infinite should not be finite."); CHECK_FALSE_MESSAGE( Vector3(0, x, 2).is_finite(), "Vector3 with one component infinite should not be finite."); CHECK_FALSE_MESSAGE( Vector3(0, 1, x).is_finite(), "Vector3 with one component infinite should not be finite."); } for (double x : infinite) { for (double y : infinite) { CHECK_FALSE_MESSAGE( Vector3(x, y, 2).is_finite(), "Vector3 with two components infinite should not be finite."); CHECK_FALSE_MESSAGE( Vector3(x, 1, y).is_finite(), "Vector3 with two components infinite should not be finite."); CHECK_FALSE_MESSAGE( Vector3(0, x, y).is_finite(), "Vector3 with two components infinite should not be finite."); } } for (double x : infinite) { for (double y : infinite) { for (double z : infinite) { CHECK_FALSE_MESSAGE( Vector3(x, y, z).is_finite(), "Vector3 with three components infinite should not be finite."); } } } } } // namespace TestVector3 #endif // TEST_VECTOR3_H
123239
{ // Arbitrary Euler angles. Vector3 euler_yxz(Math::deg_to_rad(31.41), Math::deg_to_rad(-49.16), Math::deg_to_rad(12.34)); // Basis vectors from online calculation of rotation matrix. Vector3 i_unit(0.5545787, 0.1823950, 0.8118957); Vector3 j_unit(-0.5249245, 0.8337420, 0.1712555); Vector3 k_unit(-0.6456754, -0.5211586, 0.5581192); // Quaternion from online calculation. Quaternion q_calc(0.2016913, -0.4245716, 0.206033, 0.8582598); // Quaternion from local calculation. Quaternion q_local = quat_euler_yxz_deg(Vector3(31.41, -49.16, 12.34)); // Quaternion from Euler angles constructor. Quaternion q_euler = Quaternion::from_euler(euler_yxz); CHECK(q_calc.is_equal_approx(q_local)); CHECK(q_local.is_equal_approx(q_euler)); // Calculate Basis and construct Quaternion. // When this is written, C++ Basis class does not construct from basis vectors. // This is by design, but may be subject to change. // Workaround by constructing Basis from Euler angles. // basis_axes = Basis(i_unit, j_unit, k_unit); Basis basis_axes = Basis::from_euler(euler_yxz); Quaternion q(basis_axes); CHECK(basis_axes.get_column(0).is_equal_approx(i_unit)); CHECK(basis_axes.get_column(1).is_equal_approx(j_unit)); CHECK(basis_axes.get_column(2).is_equal_approx(k_unit)); CHECK(q.is_equal_approx(q_calc)); CHECK_FALSE(q.inverse().is_equal_approx(q_calc)); CHECK(q.is_equal_approx(q_local)); CHECK(q.is_equal_approx(q_euler)); CHECK(q[0] == doctest::Approx(0.2016913)); CHECK(q[1] == doctest::Approx(-0.4245716)); CHECK(q[2] == doctest::Approx(0.206033)); CHECK(q[3] == doctest::Approx(0.8582598)); } TEST_CASE("[Quaternion] Get Euler Orders") { double x = Math::deg_to_rad(30.0); double y = Math::deg_to_rad(45.0); double z = Math::deg_to_rad(10.0); Vector3 euler(x, y, z); for (int i = 0; i < 6; i++) { EulerOrder order = (EulerOrder)i; Basis basis = Basis::from_euler(euler, order); Quaternion q = Quaternion(basis); Vector3 check = q.get_euler(order); CHECK_MESSAGE(check.is_equal_approx(euler), "Quaternion get_euler method should return the original angles."); CHECK_MESSAGE(check.is_equal_approx(basis.get_euler(order)), "Quaternion get_euler method should behave the same as Basis get_euler."); } } TEST_CASE("[Quaternion] Product (book)") { // Example from "Quaternions and Rotation Sequences" by Jack Kuipers, p. 108. Quaternion p(1.0, -2.0, 1.0, 3.0); Quaternion q(-1.0, 2.0, 3.0, 2.0); Quaternion pq = p * q; CHECK(pq[0] == doctest::Approx(-9.0)); CHECK(pq[1] == doctest::Approx(-2.0)); CHECK(pq[2] == doctest::Approx(11.0)); CHECK(pq[3] == doctest::Approx(8.0)); } TEST_CASE("[Quaternion] Product") { double yaw = Math::deg_to_rad(45.0); double pitch = Math::deg_to_rad(30.0); double roll = Math::deg_to_rad(10.0); Vector3 euler_y(0.0, yaw, 0.0); Quaternion q_y = Quaternion::from_euler(euler_y); CHECK(q_y[0] == doctest::Approx(0.0)); CHECK(q_y[1] == doctest::Approx(0.382684)); CHECK(q_y[2] == doctest::Approx(0.0)); CHECK(q_y[3] == doctest::Approx(0.923879)); Vector3 euler_p(pitch, 0.0, 0.0); Quaternion q_p = Quaternion::from_euler(euler_p); CHECK(q_p[0] == doctest::Approx(0.258819)); CHECK(q_p[1] == doctest::Approx(0.0)); CHECK(q_p[2] == doctest::Approx(0.0)); CHECK(q_p[3] == doctest::Approx(0.965926)); Vector3 euler_r(0.0, 0.0, roll); Quaternion q_r = Quaternion::from_euler(euler_r); CHECK(q_r[0] == doctest::Approx(0.0)); CHECK(q_r[1] == doctest::Approx(0.0)); CHECK(q_r[2] == doctest::Approx(0.0871558)); CHECK(q_r[3] == doctest::Approx(0.996195)); // Test ZYX dynamic-axes since test data is available online. // Rotate first about X axis, then new Y axis, then new Z axis. // (Godot uses YXZ Yaw-Pitch-Roll order). Quaternion q_yp = q_y * q_p; CHECK(q_yp[0] == doctest::Approx(0.239118)); CHECK(q_yp[1] == doctest::Approx(0.369644)); CHECK(q_yp[2] == doctest::Approx(-0.099046)); CHECK(q_yp[3] == doctest::Approx(0.892399)); Quaternion q_ryp = q_r * q_yp; CHECK(q_ryp[0] == doctest::Approx(0.205991)); CHECK(q_ryp[1] == doctest::Approx(0.389078)); CHECK(q_ryp[2] == doctest::Approx(-0.0208912)); CHECK(q_ryp[3] == doctest::Approx(0.897636)); } TEST_CASE("[Quaternion] xform unit vectors")
123381
/**************************************************************************/ /* test_button.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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_BUTTON_H #define TEST_BUTTON_H #include "scene/gui/button.h" #include "scene/main/window.h" #include "tests/test_macros.h" namespace TestButton { TEST_CASE("[SceneTree][Button] is_hovered()") { // Create new button instance. Button *button = memnew(Button); CHECK(button != nullptr); Window *root = SceneTree::get_singleton()->get_root(); root->add_child(button); // Set up button's size and position. button->set_size(Size2i(50, 50)); button->set_position(Size2i(10, 10)); // Button should initially be not hovered. CHECK(button->is_hovered() == false); // Simulate mouse entering the button. SEND_GUI_MOUSE_MOTION_EVENT(Point2i(25, 25), MouseButtonMask::NONE, Key::NONE); CHECK(button->is_hovered() == true); // Simulate mouse exiting the button. SEND_GUI_MOUSE_MOTION_EVENT(Point2i(150, 150), MouseButtonMask::NONE, Key::NONE); CHECK(button->is_hovered() == false); memdelete(button); } } //namespace TestButton #endif // TEST_BUTTON_H
123389
{ List<Node *> nodes; SceneTree::get_singleton()->get_nodes_in_group("nodes", &nodes); CHECK(nodes.is_empty()); SceneTree::get_singleton()->get_nodes_in_group("other_nodes", &nodes); CHECK(nodes.is_empty()); node1->add_to_group("nodes"); node2->add_to_group("other_nodes"); node1_1->add_to_group("nodes"); node1_1->add_to_group("other_nodes"); SceneTree::get_singleton()->get_nodes_in_group("nodes", &nodes); CHECK_EQ(nodes.size(), 2); List<Node *>::Element *E = nodes.front(); CHECK_EQ(E->get(), node1); E = E->next(); CHECK_EQ(E->get(), node1_1); // Clear and try again with the other group. nodes.clear(); SceneTree::get_singleton()->get_nodes_in_group("other_nodes", &nodes); CHECK_EQ(nodes.size(), 2); E = nodes.front(); CHECK_EQ(E->get(), node1_1); E = E->next(); CHECK_EQ(E->get(), node2); // Clear and try again with the other group and one node removed. nodes.clear(); node1->remove_from_group("nodes"); SceneTree::get_singleton()->get_nodes_in_group("nodes", &nodes); CHECK_EQ(nodes.size(), 1); E = nodes.front(); CHECK_EQ(E->get(), node1_1); } SUBCASE("Nodes added as siblings of another node should be right next to it") { node1->remove_child(node1_1); node1->add_sibling(node1_1); CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child_count(), 3); CHECK_EQ(SceneTree::get_singleton()->get_node_count(), 4); CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child(0), node1); CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child(1), node1_1); CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child(2), node2); } SUBCASE("Replaced nodes should be be removed and the replacing node added") { SceneTree::get_singleton()->get_root()->remove_child(node2); node1->replace_by(node2); CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child_count(), 1); CHECK_EQ(SceneTree::get_singleton()->get_node_count(), 3); CHECK_FALSE(node1->is_inside_tree()); CHECK(node2->is_inside_tree()); CHECK_EQ(node1->get_parent(), nullptr); CHECK_EQ(node2->get_parent(), SceneTree::get_singleton()->get_root()); CHECK_EQ(node2->get_child_count(), 1); CHECK_EQ(node2->get_child(0), node1_1); } SUBCASE("Replacing nodes should keep the groups of the replaced nodes") { SceneTree::get_singleton()->get_root()->remove_child(node2); node1->add_to_group("nodes"); node1->replace_by(node2, true); List<Node *> nodes; SceneTree::get_singleton()->get_nodes_in_group("nodes", &nodes); CHECK_EQ(nodes.size(), 1); List<Node *>::Element *E = nodes.front(); CHECK_EQ(E->get(), node2); } SUBCASE("Duplicating a node should also duplicate the children") { node1->set_name("MyName1"); node1_1->set_name("MyName1_1"); Node *duplicate1 = node1->duplicate(); CHECK_EQ(duplicate1->get_child_count(), node1->get_child_count()); Node *duplicate1_1 = duplicate1->get_child(0); CHECK_EQ(duplicate1_1->get_child_count(), node1_1->get_child_count()); CHECK_EQ(duplicate1->get_name(), node1->get_name()); CHECK_EQ(duplicate1_1->get_name(), node1_1->get_name()); CHECK_FALSE(duplicate1->is_inside_tree()); CHECK_FALSE(duplicate1_1->is_inside_tree()); memdelete(duplicate1_1); memdelete(duplicate1); } memdelete(node1_1); memdelete(node1); memdelete(node2); } TEST_CASE("[SceneTree][Node]Exported node checks") { TestNode *node = memnew(TestNode); SceneTree::get_singleton()->get_root()->add_child(node); Node *child = memnew(Node); child->set_name("Child"); node->add_child(child); child->set_owner(node); Node *child2 = memnew(Node); child2->set_name("Child2"); node->add_child(child2); child2->set_owner(node); Array children; children.append(child); node->set("exported_node", child); node->set("exported_nodes", children); SUBCASE("Property of duplicated node should point to duplicated child") { GDREGISTER_CLASS(TestNode); TestNode *dup = Object::cast_to<TestNode>(node->duplicate()); Node *new_exported = Object::cast_to<Node>(dup->get("exported_node")); CHECK(new_exported == dup->get_child(0)); memdelete(dup); } #ifdef TOOLS_ENABLED SUBCASE("Saving instance with exported nodes should not store the unchanged property") { Ref<PackedScene> ps; ps.instantiate(); ps->pack(node); String scene_path = TestUtils::get_temp_path("test_scene.tscn"); ps->set_path(scene_path); Node *root = memnew(Node); Node *sub_child = ps->instantiate(PackedScene::GEN_EDIT_STATE_MAIN); root->add_child(sub_child); sub_child->set_owner(root); Ref<PackedScene> ps2; ps2.instantiate(); ps2->pack(root); scene_path = TestUtils::get_temp_path("new_test_scene.tscn"); ResourceSaver::save(ps2, scene_path); memdelete(root); bool is_wrong = false; Ref<FileAccess> fa = FileAccess::open(scene_path, FileAccess::READ); while (!fa->eof_reached()) { const String line = fa->get_line(); if (line.begins_with("exported_node")) { // The property was saved, while it shouldn't. is_wrong = true; break; } } CHECK_FALSE(is_wrong); } SUBCASE("Saving instance with exported nodes should store property if changed") { Ref<PackedScene> ps; ps.instantiate(); ps->pack(node); String scene_path = TestUtils::get_temp_path("test_scene.tscn"); ps->set_path(scene_path); Node *root = memnew(Node); Node *sub_child = ps->instantiate(PackedScene::GEN_EDIT_STATE_MAIN); root->add_child(sub_child); sub_child->set_owner(root); sub_child->set("exported_node", sub_child->get_child(1)); children = Array(); children.append(sub_child->get_child(1)); sub_child->set("exported_nodes", children); Ref<PackedScene> ps2; ps2.instantiate(); ps2->pack(root); scene_path = TestUtils::get_temp_path("new_test_scene2.tscn"); ResourceSaver::save(ps2, scene_path); memdelete(root); int stored_properties = 0; Ref<FileAccess> fa = FileAccess::open(scene_path, FileAccess::READ); while (!fa->eof_reached()) { const String line = fa->get_line(); if (line.begins_with("exported_node")) { stored_properties++; } } CHECK_EQ(stored_properties, 2); } #endif // TOOLS_ENABLED memdelete(node); } TEST_CASE("[Node] Processing checks")
123398
{ // Cameras need a viewport to know how to compute their frustums, so we make a fake one here. Camera3D *test_camera = memnew(Camera3D); SubViewport *mock_viewport = memnew(SubViewport); // 4:2. mock_viewport->set_size(Vector2(400, 200)); SceneTree::get_singleton()->get_root()->add_child(mock_viewport); mock_viewport->add_child(test_camera); test_camera->set_global_position(Vector3(0, 0, 0)); test_camera->set_global_rotation(Vector3(0, 0, 0)); test_camera->set_keep_aspect_mode(Camera3D::KeepAspect::KEEP_HEIGHT); SUBCASE("project_position") { SUBCASE("Orthogonal projection") { test_camera->set_orthogonal(5.0f, 0.5f, 1000.0f); // Center. CHECK(test_camera->project_position(Vector2(200, 100), 0.5f).is_equal_approx(Vector3(0, 0, -0.5f))); // Top left. CHECK(test_camera->project_position(Vector2(0, 0), 1.5f).is_equal_approx(Vector3(-5.0f, 2.5f, -1.5f))); // Bottom right. CHECK(test_camera->project_position(Vector2(400, 200), 5.0f).is_equal_approx(Vector3(5.0f, -2.5f, -5.0f))); } SUBCASE("Perspective projection") { test_camera->set_perspective(120.0f, 0.5f, 1000.0f); // Center. CHECK(test_camera->project_position(Vector2(200, 100), 0.5f).is_equal_approx(Vector3(0, 0, -0.5f))); CHECK(test_camera->project_position(Vector2(200, 100), 100.0f).is_equal_approx(Vector3(0, 0, -100.0f))); // 3/4th way to Top left. CHECK(test_camera->project_position(Vector2(100, 50), 0.5f).is_equal_approx(Vector3(-SQRT3 * 0.5f, SQRT3 * 0.25f, -0.5f))); CHECK(test_camera->project_position(Vector2(100, 50), 1.0f).is_equal_approx(Vector3(-SQRT3, SQRT3 * 0.5f, -1.0f))); // 3/4th way to Bottom right. CHECK(test_camera->project_position(Vector2(300, 150), 0.5f).is_equal_approx(Vector3(SQRT3 * 0.5f, -SQRT3 * 0.25f, -0.5f))); CHECK(test_camera->project_position(Vector2(300, 150), 1.0f).is_equal_approx(Vector3(SQRT3, -SQRT3 * 0.5f, -1.0f))); } } // Uses cases that are the inverse of the above sub-case. SUBCASE("unproject_position") { SUBCASE("Orthogonal projection") { test_camera->set_orthogonal(5.0f, 0.5f, 1000.0f); // Center CHECK(test_camera->unproject_position(Vector3(0, 0, -0.5f)).is_equal_approx(Vector2(200, 100))); // Top left CHECK(test_camera->unproject_position(Vector3(-5.0f, 2.5f, -1.5f)).is_equal_approx(Vector2(0, 0))); // Bottom right CHECK(test_camera->unproject_position(Vector3(5.0f, -2.5f, -5.0f)).is_equal_approx(Vector2(400, 200))); } SUBCASE("Perspective projection") { test_camera->set_perspective(120.0f, 0.5f, 1000.0f); // Center. CHECK(test_camera->unproject_position(Vector3(0, 0, -0.5f)).is_equal_approx(Vector2(200, 100))); CHECK(test_camera->unproject_position(Vector3(0, 0, -100.0f)).is_equal_approx(Vector2(200, 100))); // 3/4th way to Top left. WARN(test_camera->unproject_position(Vector3(-SQRT3 * 0.5f, SQRT3 * 0.25f, -0.5f)).is_equal_approx(Vector2(100, 50))); WARN(test_camera->unproject_position(Vector3(-SQRT3, SQRT3 * 0.5f, -1.0f)).is_equal_approx(Vector2(100, 50))); // 3/4th way to Bottom right. CHECK(test_camera->unproject_position(Vector3(SQRT3 * 0.5f, -SQRT3 * 0.25f, -0.5f)).is_equal_approx(Vector2(300, 150))); CHECK(test_camera->unproject_position(Vector3(SQRT3, -SQRT3 * 0.5f, -1.0f)).is_equal_approx(Vector2(300, 150))); } } memdelete(test_camera); memdelete(mock_viewport); } TEST_CASE("[SceneTree][Camera3D] Project ray")
123406
{ SubViewport *mock_viewport = memnew(SubViewport); Camera2D *test_camera = memnew(Camera2D); mock_viewport->set_size(Vector2(400, 200)); SceneTree::get_singleton()->get_root()->add_child(mock_viewport); mock_viewport->add_child(test_camera); SUBCASE("Anchor mode") { test_camera->set_anchor_mode(Camera2D::ANCHOR_MODE_DRAG_CENTER); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(0, 0))); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); test_camera->set_anchor_mode(Camera2D::ANCHOR_MODE_FIXED_TOP_LEFT); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(200, 100))); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); } SUBCASE("Offset") { test_camera->set_offset(Vector2(100, 100)); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(100, 100))); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); test_camera->set_offset(Vector2(-100, 300)); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(-100, 300))); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); test_camera->set_offset(Vector2(0, 0)); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(0, 0))); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); } SUBCASE("Limits") { test_camera->set_limit(SIDE_LEFT, 100); test_camera->set_limit(SIDE_TOP, 50); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(300, 150))); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); test_camera->set_limit(SIDE_LEFT, 0); test_camera->set_limit(SIDE_TOP, 0); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(200, 100))); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); } SUBCASE("Drag") { CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(0, 0))); // horizontal test_camera->set_drag_horizontal_enabled(true); test_camera->set_drag_margin(SIDE_RIGHT, 0.5); test_camera->set_position(Vector2(100, 100)); test_camera->force_update_scroll(); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 100))); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(0, 100))); test_camera->set_position(Vector2(101, 101)); test_camera->force_update_scroll(); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(1, 101))); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(1, 101))); // test align test_camera->set_position(Vector2(0, 0)); test_camera->align(); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(0, 0))); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(0, 0))); // vertical test_camera->set_drag_vertical_enabled(true); test_camera->set_drag_horizontal_enabled(false); test_camera->set_drag_margin(SIDE_TOP, 0.3); test_camera->set_position(Vector2(200, -20)); test_camera->force_update_scroll(); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(200, 0))); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(200, 0))); test_camera->set_position(Vector2(250, -55)); test_camera->force_update_scroll(); CHECK(test_camera->get_camera_position().is_equal_approx(Vector2(250, -25))); CHECK(test_camera->get_camera_screen_center().is_equal_approx(Vector2(250, -25))); } memdelete(test_camera); memdelete(mock_viewport); } TEST_CASE("[SceneTree][Camera2D] Transforms") { SubViewport *mock_viewport = memnew(SubViewport); Camera2D *test_camera = memnew(Camera2D); mock_viewport->set_size(Vector2(400, 200)); SceneTree::get_singleton()->get_root()->add_child(mock_viewport); mock_viewport->add_child(test_camera); SUBCASE("Default camera") { Transform2D xform = mock_viewport->get_canvas_transform(); // x,y are basis vectors, origin = screen center Transform2D test_xform = Transform2D(Vector2(1, 0), Vector2(0, 1), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); } SUBCASE("Zoom") { test_camera->set_zoom(Vector2(0.5, 2)); Transform2D xform = mock_viewport->get_canvas_transform(); Transform2D test_xform = Transform2D(Vector2(0.5, 0), Vector2(0, 2), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); test_camera->set_zoom(Vector2(10, 10)); xform = mock_viewport->get_canvas_transform(); test_xform = Transform2D(Vector2(10, 0), Vector2(0, 10), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); test_camera->set_zoom(Vector2(1, 1)); xform = mock_viewport->get_canvas_transform(); test_xform = Transform2D(Vector2(1, 0), Vector2(0, 1), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); } SUBCASE("Rotation") { test_camera->set_rotation(Math_PI / 2); Transform2D xform = mock_viewport->get_canvas_transform(); Transform2D test_xform = Transform2D(Vector2(1, 0), Vector2(0, 1), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); test_camera->set_ignore_rotation(false); xform = mock_viewport->get_canvas_transform(); test_xform = Transform2D(Vector2(0, -1), Vector2(1, 0), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); test_camera->set_rotation(-1 * Math_PI); test_camera->force_update_scroll(); xform = mock_viewport->get_canvas_transform(); test_xform = Transform2D(Vector2(-1, 0), Vector2(0, -1), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); test_camera->set_rotation(0); test_camera->force_update_scroll(); xform = mock_viewport->get_canvas_transform(); test_xform = Transform2D(Vector2(1, 0), Vector2(0, 1), Vector2(200, 100)); CHECK(xform.is_equal_approx(test_xform)); } memdelete(test_camera); memdelete(mock_viewport); } } // namespace TestCamera2D #endif // TEST_CAMERA_2D_H
123424
{ SIGNAL_WATCH(node_i, SceneStringName(mouse_entered)); SIGNAL_WATCH(node_i, SceneStringName(mouse_exited)); Array signal_args; signal_args.push_back(Array()); node_i->set_mouse_filter(Control::MOUSE_FILTER_PASS); node_j->set_mouse_filter(Control::MOUSE_FILTER_PASS); // Move to Control node_j. SEND_GUI_MOUSE_MOTION_EVENT(on_j, MouseButtonMask::NONE, Key::NONE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK(SceneStringName(mouse_entered), signal_args); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); // Change node_i to MOUSE_FILTER_IGNORE. node_i should receive Mouse Exit. node_i->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK_FALSE(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK_FALSE(SceneStringName(mouse_entered)); SIGNAL_CHECK(SceneStringName(mouse_exited), signal_args); // Change node_i to MOUSE_FILTER_PASS. node_i should receive Mouse Enter. node_i->set_mouse_filter(Control::MOUSE_FILTER_PASS); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK(SceneStringName(mouse_entered), signal_args); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); // Change node_j to MOUSE_FILTER_IGNORE. After updating the mouse motion, node_i should now have mouse_over_self. node_j->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); SEND_GUI_MOUSE_MOTION_EVENT(on_j, MouseButtonMask::NONE, Key::NONE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK(node_i->mouse_over_self); CHECK_FALSE(node_j->mouse_over); CHECK_FALSE(node_j->mouse_over_self); SIGNAL_CHECK_FALSE(SceneStringName(mouse_entered)); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); // Change node_j to MOUSE_FILTER_PASS. After updating the mouse motion, node_j should now have mouse_over_self. node_j->set_mouse_filter(Control::MOUSE_FILTER_PASS); SEND_GUI_MOUSE_MOTION_EVENT(on_j, MouseButtonMask::NONE, Key::NONE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK_FALSE(SceneStringName(mouse_entered)); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); CHECK_FALSE(node_h->invalid_order); CHECK_FALSE(node_i->invalid_order); CHECK_FALSE(node_j->invalid_order); node_i->set_mouse_filter(Control::MOUSE_FILTER_STOP); node_j->set_mouse_filter(Control::MOUSE_FILTER_STOP); SIGNAL_UNWATCH(node_i, SceneStringName(mouse_entered)); SIGNAL_UNWATCH(node_i, SceneStringName(mouse_exited)); } SUBCASE("[Viewport][GuiInputEvent] Mouse Enter/Exit notification when removing the hovered Control.") { SIGNAL_WATCH(node_h, SceneStringName(mouse_entered)); SIGNAL_WATCH(node_h, SceneStringName(mouse_exited)); Array signal_args; signal_args.push_back(Array()); node_i->set_mouse_filter(Control::MOUSE_FILTER_PASS); node_j->set_mouse_filter(Control::MOUSE_FILTER_PASS); // Move to Control node_j. SEND_GUI_MOUSE_MOTION_EVENT(on_j, MouseButtonMask::NONE, Key::NONE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK(SceneStringName(mouse_entered), signal_args); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); // Remove node_i from the tree. node_i and node_j should receive Mouse Exit. node_h should not receive any new signals. node_h->remove_child(node_i); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK_FALSE(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK_FALSE(node_j->mouse_over); CHECK_FALSE(node_j->mouse_over_self); SIGNAL_CHECK_FALSE(SceneStringName(mouse_entered)); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); // Add node_i to the tree and update the mouse. node_i and node_j should receive Mouse Enter. node_h should not receive any new signals. node_h->add_child(node_i); SEND_GUI_MOUSE_MOTION_EVENT(on_j, MouseButtonMask::NONE, Key::NONE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK_FALSE(SceneStringName(mouse_entered)); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); CHECK_FALSE(node_h->invalid_order); CHECK_FALSE(node_i->invalid_order); CHECK_FALSE(node_j->invalid_order); node_i->set_mouse_filter(Control::MOUSE_FILTER_STOP); node_j->set_mouse_filter(Control::MOUSE_FILTER_STOP); SIGNAL_UNWATCH(node_h, SceneStringName(mouse_entered)); SIGNAL_UNWATCH(node_h, SceneStringName(mouse_exited)); } SUBCASE("[Viewport][GuiInputEvent] Mouse Enter/Exit notification when hiding the hovered Control.") { SIGNAL_WATCH(node_h, SceneStringName(mouse_entered)); SIGNAL_WATCH(node_h, SceneStringName(mouse_exited)); Array signal_args; signal_args.push_back(Array()); node_i->set_mouse_filter(Control::MOUSE_FILTER_PASS); node_j->set_mouse_filter(Control::MOUSE_FILTER_PASS); // Move to Control node_j. SEND_GUI_MOUSE_MOTION_EVENT(on_j, MouseButtonMask::NONE, Key::NONE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK(SceneStringName(mouse_entered), signal_args); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); // Hide node_i. node_i and node_j should receive Mouse Exit. node_h should not receive any new signals. node_i->hide(); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK_FALSE(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK_FALSE(node_j->mouse_over); CHECK_FALSE(node_j->mouse_over_self); SIGNAL_CHECK_FALSE(SceneStringName(mouse_entered)); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); // Show node_i and update the mouse. node_i and node_j should receive Mouse Enter. node_h should not receive any new signals. node_i->show(); SEND_GUI_MOUSE_MOTION_EVENT(on_j, MouseButtonMask::NONE, Key::NONE); CHECK(node_h->mouse_over); CHECK_FALSE(node_h->mouse_over_self); CHECK(node_i->mouse_over); CHECK_FALSE(node_i->mouse_over_self); CHECK(node_j->mouse_over); CHECK(node_j->mouse_over_self); SIGNAL_CHECK_FALSE(SceneStringName(mouse_entered)); SIGNAL_CHECK_FALSE(SceneStringName(mouse_exited)); CHECK_FALSE(node_h->invalid_order); CHECK_FALSE(node_i->invalid_order); CHECK_FALSE(node_j->invalid_order); node_i->set_mouse_filter(Control::MOUSE_FILTER_STOP); node_j->set_mouse_filter(Control::MOUSE_FILTER_STOP); SIGNAL_UNWATCH(node_h, SceneStringName(mouse_entered)); SIGNAL_UNWATCH(node_h, SceneStringName(mouse_exited)); } SUBCASE("[Viewport][GuiInputEvent] Window Mouse Enter/Exit signals.")
123609
<?xml version="1.0" encoding="UTF-8" ?> <class name="PhysicsBody3D" inherits="CollisionObject3D" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> Abstract base class for 3D game objects affected by physics. </brief_description> <description> [PhysicsBody3D] is an abstract base class for 3D game objects affected by physics. All 3D physics bodies inherit from it. [b]Warning:[/b] With a non-uniform scale, this node will likely not behave as expected. It is advised to keep its scale the same on all axes and adjust its collision shape(s) instead. </description> <tutorials> <link title="Physics introduction">$DOCS_URL/tutorials/physics/physics_introduction.html</link> </tutorials> <methods> <method name="add_collision_exception_with"> <return type="void" /> <param index="0" name="body" type="Node" /> <description> Adds a body to the list of bodies that this body can't collide with. </description> </method> <method name="get_axis_lock" qualifiers="const"> <return type="bool" /> <param index="0" name="axis" type="int" enum="PhysicsServer3D.BodyAxis" /> <description> Returns [code]true[/code] if the specified linear or rotational [param axis] is locked. </description> </method> <method name="get_collision_exceptions"> <return type="PhysicsBody3D[]" /> <description> Returns an array of nodes that were added as collision exceptions for this body. </description> </method> <method name="get_gravity" qualifiers="const"> <return type="Vector3" /> <description> Returns the gravity vector computed from all sources that can affect the body, including all gravity overrides from [Area3D] nodes and the global world gravity. </description> </method> <method name="move_and_collide"> <return type="KinematicCollision3D" /> <param index="0" name="motion" type="Vector3" /> <param index="1" name="test_only" type="bool" default="false" /> <param index="2" name="safe_margin" type="float" default="0.001" /> <param index="3" name="recovery_as_collision" type="bool" default="false" /> <param index="4" name="max_collisions" type="int" default="1" /> <description> Moves the body along the vector [param motion]. In order to be frame rate independent in [method Node._physics_process] or [method Node._process], [param motion] 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.safe_margin] for more details). If [param recovery_as_collision] is [code]true[/code], any depenetration from the recovery phase is also reported as a collision; this is used e.g. by [CharacterBody3D] for improving floor detection during floor snapping. [param max_collisions] allows to retrieve more than one collision result. </description> </method> <method name="remove_collision_exception_with"> <return type="void" /> <param index="0" name="body" type="Node" /> <description> Removes a body from the list of bodies that this body can't collide with. </description> </method> <method name="set_axis_lock"> <return type="void" /> <param index="0" name="axis" type="int" enum="PhysicsServer3D.BodyAxis" /> <param index="1" name="lock" type="bool" /> <description> Locks or unlocks the specified linear or rotational [param axis] depending on the value of [param lock]. </description> </method> <method name="test_move" keywords="check, collision, sweep"> <return type="bool" /> <param index="0" name="from" type="Transform3D" /> <param index="1" name="motion" type="Vector3" /> <param index="2" name="collision" type="KinematicCollision3D" default="null" /> <param index="3" name="safe_margin" type="float" default="0.001" /> <param index="4" name="recovery_as_collision" type="bool" default="false" /> <param index="5" name="max_collisions" type="int" default="1" /> <description> Checks for collisions without moving the body. In order to be frame rate independent in [method Node._physics_process] or [method Node._process], [param motion] 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 motion]. 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.safe_margin] for more details). If [param recovery_as_collision] is [code]true[/code], any depenetration from the recovery phase is also reported as a collision; this is useful for checking whether the body would [i]touch[/i] any other bodies. [param max_collisions] allows to retrieve more than one collision result. </description> </method> </methods> <members> <member name="axis_lock_angular_x" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false"> Lock the body's rotation in the X axis. </member> <member name="axis_lock_angular_y" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false"> Lock the body's rotation in the Y axis. </member> <member name="axis_lock_angular_z" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false"> Lock the body's rotation in the Z axis. </member> <member name="axis_lock_linear_x" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false"> Lock the body's linear movement in the X axis. </member> <member name="axis_lock_linear_y" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false"> Lock the body's linear movement in the Y axis. </member> <member name="axis_lock_linear_z" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false"> Lock the body's linear movement in the Z axis. </member> </members> </class>
123616
<?xml version="1.0" encoding="UTF-8" ?> <class name="BaseButton" inherits="Control" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> Abstract base class for GUI buttons. </brief_description> <description> [BaseButton] is an abstract base class for GUI buttons. It doesn't display anything by itself. </description> <tutorials> </tutorials> <methods> <method name="_pressed" qualifiers="virtual"> <return type="void" /> <description> Called when the button is pressed. If you need to know the button's pressed state (and [member toggle_mode] is active), use [method _toggled] instead. </description> </method> <method name="_toggled" qualifiers="virtual"> <return type="void" /> <param index="0" name="toggled_on" type="bool" /> <description> Called when the button is toggled (only if [member toggle_mode] is active). </description> </method> <method name="get_draw_mode" qualifiers="const"> <return type="int" enum="BaseButton.DrawMode" /> <description> Returns the visual state used to draw the button. This is useful mainly when implementing your own draw code by either overriding _draw() or connecting to "draw" signal. The visual state of the button is defined by the [enum DrawMode] enum. </description> </method> <method name="is_hovered" qualifiers="const"> <return type="bool" /> <description> Returns [code]true[/code] if the mouse has entered the button and has not left it yet. </description> </method> <method name="set_pressed_no_signal"> <return type="void" /> <param index="0" name="pressed" type="bool" /> <description> Changes the [member button_pressed] state of the button, without emitting [signal toggled]. Use when you just want to change the state of the button without sending the pressed event (e.g. when initializing scene). Only works if [member toggle_mode] is [code]true[/code]. [b]Note:[/b] This method doesn't unpress other buttons in [member button_group]. </description> </method> </methods> <members> <member name="action_mode" type="int" setter="set_action_mode" getter="get_action_mode" enum="BaseButton.ActionMode" default="1"> Determines when the button is considered clicked, one of the [enum ActionMode] constants. </member> <member name="button_group" type="ButtonGroup" setter="set_button_group" getter="get_button_group"> The [ButtonGroup] associated with the button. Not to be confused with node groups. [b]Note:[/b] The button will be configured as a radio button if a [ButtonGroup] is assigned to it. </member> <member name="button_mask" type="int" setter="set_button_mask" getter="get_button_mask" enum="MouseButtonMask" is_bitfield="true" default="1"> Binary mask to choose which mouse buttons this button will respond to. To allow both left-click and right-click, use [code]MOUSE_BUTTON_MASK_LEFT | MOUSE_BUTTON_MASK_RIGHT[/code]. </member> <member name="button_pressed" type="bool" setter="set_pressed" getter="is_pressed" default="false"> If [code]true[/code], the button's state is pressed. Means the button is pressed down or toggled (if [member toggle_mode] is active). Only works if [member toggle_mode] is [code]true[/code]. [b]Note:[/b] Changing the value of [member button_pressed] will result in [signal toggled] to be emitted. If you want to change the pressed state without emitting that signal, use [method set_pressed_no_signal]. </member> <member name="disabled" type="bool" setter="set_disabled" getter="is_disabled" default="false" keywords="enabled"> If [code]true[/code], the button is in disabled state and can't be clicked or toggled. </member> <member name="focus_mode" type="int" setter="set_focus_mode" getter="get_focus_mode" overrides="Control" enum="Control.FocusMode" default="2" /> <member name="keep_pressed_outside" type="bool" setter="set_keep_pressed_outside" getter="is_keep_pressed_outside" default="false"> If [code]true[/code], the button stays pressed when moving the cursor outside the button while pressing it. [b]Note:[/b] This property only affects the button's visual appearance. Signals will be emitted at the same moment regardless of this property's value. </member> <member name="shortcut" type="Shortcut" setter="set_shortcut" getter="get_shortcut"> [Shortcut] associated to the button. </member> <member name="shortcut_feedback" type="bool" setter="set_shortcut_feedback" getter="is_shortcut_feedback" default="true"> If [code]true[/code], the button will highlight for a short amount of time when its shortcut is activated. If [code]false[/code] and [member toggle_mode] is [code]false[/code], the shortcut will activate without any visual feedback. </member> <member name="shortcut_in_tooltip" type="bool" setter="set_shortcut_in_tooltip" getter="is_shortcut_in_tooltip_enabled" default="true"> If [code]true[/code], the button will add information about its shortcut in the tooltip. [b]Note:[/b] This property does nothing when the tooltip control is customized using [method Control._make_custom_tooltip]. </member> <member name="toggle_mode" type="bool" setter="set_toggle_mode" getter="is_toggle_mode" default="false"> If [code]true[/code], the button is in toggle mode. Makes the button flip state between pressed and unpressed each time its area is clicked. </member> </members> <signals> <signal name="button_down"> <description> Emitted when the button starts being held down. </description> </signal> <signal name="button_up"> <description> Emitted when the button stops being held down. </description> </signal> <signal name="pressed"> <description> Emitted when the button is toggled or pressed. This is on [signal button_down] if [member action_mode] is [constant ACTION_MODE_BUTTON_PRESS] and on [signal button_up] otherwise. If you need to know the button's pressed state (and [member toggle_mode] is active), use [signal toggled] instead. </description> </signal> <signal name="toggled"> <param index="0" name="toggled_on" type="bool" /> <description> Emitted when the button was just toggled between pressed and normal states (only if [member toggle_mode] is active). The new state is contained in the [param toggled_on] argument. </description> </signal> </signals> <constants> <constant name="DRAW_NORMAL" value="0" enum="DrawMode"> The normal state (i.e. not pressed, not hovered, not toggled and enabled) of buttons. </constant> <constant name="DRAW_PRESSED" value="1" enum="DrawMode"> The state of buttons are pressed. </constant> <constant name="DRAW_HOVER" value="2" enum="DrawMode"> The state of buttons are hovered. </constant> <constant name="DRAW_DISABLED" value="3" enum="DrawMode"> The state of buttons are disabled. </constant> <constant name="DRAW_HOVER_PRESSED" value="4" enum="DrawMode"> The state of buttons are both hovered and pressed. </constant> <constant name="ACTION_MODE_BUTTON_PRESS" value="0" enum="ActionMode"> Require just a press to consider the button clicked. </constant> <constant name="ACTION_MODE_BUTTON_RELEASE" value="1" enum="ActionMode"> Require a press and a subsequent release before considering the button clicked. </constant> </constants> </class>
123617
<?xml version="1.0" encoding="UTF-8" ?> <class name="MeshInstance3D" inherits="GeometryInstance3D" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> Node that instances meshes into a scenario. </brief_description> <description> MeshInstance3D is a node that takes a [Mesh] resource and adds it to the current scenario by creating an instance of it. This is the class most often used render 3D geometry and can be used to instance a single [Mesh] in many places. This allows reusing geometry, which can save on resources. When a [Mesh] has to be instantiated more than thousands of times at close proximity, consider using a [MultiMesh] in a [MultiMeshInstance3D] instead. </description> <tutorials> <link title="3D Material Testers Demo">https://godotengine.org/asset-library/asset/2742</link> <link title="3D Kinematic Character Demo">https://godotengine.org/asset-library/asset/2739</link> <link title="3D Platformer Demo">https://godotengine.org/asset-library/asset/2748</link> <link title="Third Person Shooter (TPS) Demo">https://godotengine.org/asset-library/asset/2710</link> </tutorials>
123618
<methods> <method name="bake_mesh_from_current_blend_shape_mix"> <return type="ArrayMesh" /> <param index="0" name="existing" type="ArrayMesh" default="null" /> <description> Takes a snapshot from the current [ArrayMesh] with all blend shapes applied according to their current weights and bakes it to the provided [param existing] mesh. If no [param existing] mesh is provided a new [ArrayMesh] is created, baked and returned. Mesh surface materials are not copied. [b]Performance:[/b] [Mesh] data needs to be received from the GPU, stalling the [RenderingServer] in the process. </description> </method> <method name="bake_mesh_from_current_skeleton_pose"> <return type="ArrayMesh" /> <param index="0" name="existing" type="ArrayMesh" default="null" /> <description> Takes a snapshot of the current animated skeleton pose of the skinned mesh and bakes it to the provided [param existing] mesh. If no [param existing] mesh is provided a new [ArrayMesh] is created, baked, and returned. Requires a skeleton with a registered skin to work. Blendshapes are ignored. Mesh surface materials are not copied. [b]Performance:[/b] [Mesh] data needs to be retrieved from the GPU, stalling the [RenderingServer] in the process. </description> </method> <method name="create_convex_collision"> <return type="void" /> <param index="0" name="clean" type="bool" default="true" /> <param index="1" name="simplify" type="bool" default="false" /> <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 number of vertices. Disabled by default. </description> </method> <method name="create_debug_tangents"> <return type="void" /> <description> This helper creates a [MeshInstance3D] child node with gizmos at every vertex calculated from the mesh geometry. It's mainly used for testing. </description> </method> <method name="create_multiple_convex_collisions"> <return type="void" /> <param index="0" name="settings" type="MeshConvexDecompositionSettings" default="null" /> <description> This helper creates a [StaticBody3D] child node with multiple [ConvexPolygonShape3D] collision shapes calculated from the mesh geometry via convex decomposition. The convex decomposition operation can be controlled with parameters from the optional [param settings]. </description> </method> <method name="create_trimesh_collision"> <return type="void" /> <description> This helper creates a [StaticBody3D] child node with a [ConcavePolygonShape3D] collision shape calculated from the mesh geometry. It's mainly used for testing. </description> </method> <method name="find_blend_shape_by_name"> <return type="int" /> <param index="0" name="name" type="StringName" /> <description> Returns the index of the blend shape with the given [param name]. Returns [code]-1[/code] if no blend shape with this name exists, including when [member mesh] is [code]null[/code]. </description> </method> <method name="get_active_material" qualifiers="const"> <return type="Material" /> <param index="0" name="surface" type="int" /> <description> Returns the [Material] that will be used by the [Mesh] when drawing. This can return the [member GeometryInstance3D.material_override], the surface override [Material] defined in this [MeshInstance3D], or the surface [Material] defined in the [member mesh]. For example, if [member GeometryInstance3D.material_override] is used, all surfaces will return the override material. Returns [code]null[/code] if no material is active, including when [member mesh] is [code]null[/code]. </description> </method> <method name="get_blend_shape_count" qualifiers="const"> <return type="int" /> <description> Returns the number of blend shapes available. Produces an error if [member mesh] is [code]null[/code]. </description> </method> <method name="get_blend_shape_value" qualifiers="const"> <return type="float" /> <param index="0" name="blend_shape_idx" type="int" /> <description> Returns the value of the blend shape at the given [param blend_shape_idx]. Returns [code]0.0[/code] and produces an error if [member mesh] is [code]null[/code] or doesn't have a blend shape at that index. </description> </method> <method name="get_skin_reference" qualifiers="const"> <return type="SkinReference" /> <description> Returns the internal [SkinReference] containing the skeleton's [RID] attached to this RID. See also [method Resource.get_rid], [method SkinReference.get_skeleton], and [method RenderingServer.instance_attach_skeleton]. </description> </method> <method name="get_surface_override_material" qualifiers="const"> <return type="Material" /> <param index="0" name="surface" type="int" /> <description> Returns the override [Material] for the specified [param surface] of the [Mesh] resource. See also [method get_surface_override_material_count]. [b]Note:[/b] This returns the [Material] associated to the [MeshInstance3D]'s Surface Material Override properties, not the material within the [Mesh] resource. To get the material within the [Mesh] resource, use [method Mesh.surface_get_material] instead. </description> </method> <method name="get_surface_override_material_count" qualifiers="const"> <return type="int" /> <description> Returns the number of surface override materials. This is equivalent to [method Mesh.get_surface_count]. See also [method get_surface_override_material]. </description> </method> <method name="set_blend_shape_value"> <return type="void" /> <param index="0" name="blend_shape_idx" type="int" /> <param index="1" name="value" type="float" /> <description> Sets the value of the blend shape at [param blend_shape_idx] to [param value]. Produces an error if [member mesh] is [code]null[/code] or doesn't have a blend shape at that index. </description> </method> <method name="set_surface_override_material"> <return type="void" /> <param index="0" name="surface" type="int" /> <param index="1" name="material" type="Material" /> <description> Sets the override [param material] for the specified [param surface] of the [Mesh] resource. This material is associated with this [MeshInstance3D] rather than with [member mesh]. [b]Note:[/b] This assigns the [Material] associated to the [MeshInstance3D]'s Surface Material Override properties, not the material within the [Mesh] resource. To set the material within the [Mesh] resource, use [method Mesh.surface_get_material] instead. </description> </method> </methods>
123627
<?xml version="1.0" encoding="UTF-8" ?> <class name="Viewport" inherits="Node" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> Abstract base class for viewports. Encapsulates drawing and interaction with a game world. </brief_description> <description> A [Viewport] creates a different view into the screen, or a sub-view inside another viewport. Child 2D nodes will display on it, and child Camera3D 3D nodes will render on it too. Optionally, a viewport can have its own 2D or 3D world, so it doesn't share what it draws with other viewports. Viewports can also choose to be audio listeners, so they generate positional audio depending on a 2D or 3D camera child of it. Also, viewports can be assigned to different screens in case the devices have multiple screens. Finally, viewports can also behave as render targets, in which case they will not be visible unless the associated texture is used to draw. </description> <tutorials> <link title="Using Viewports">$DOCS_URL/tutorials/rendering/viewports.html</link> <link title="Viewport and canvas transforms">$DOCS_URL/tutorials/2d/2d_transforms.html</link> <link title="GUI in 3D Viewport Demo">https://godotengine.org/asset-library/asset/2807</link> <link title="3D in 2D Viewport Demo">https://godotengine.org/asset-library/asset/2804</link> <link title="2D in 3D Viewport Demo">https://godotengine.org/asset-library/asset/2803</link> <link title="Screen Capture Demo">https://godotengine.org/asset-library/asset/2808</link> <link title="Dynamic Split Screen Demo">https://godotengine.org/asset-library/asset/2806</link> <link title="3D Resolution Scaling Demo">https://godotengine.org/asset-library/asset/2805</link> </tutorials>
123628
<methods> <method name="find_world_2d" qualifiers="const"> <return type="World2D" /> <description> Returns the first valid [World2D] for this viewport, searching the [member world_2d] property of itself and any Viewport ancestor. </description> </method> <method name="find_world_3d" qualifiers="const"> <return type="World3D" /> <description> Returns the first valid [World3D] for this viewport, searching the [member world_3d] property of itself and any Viewport ancestor. </description> </method> <method name="get_audio_listener_2d" qualifiers="const"> <return type="AudioListener2D" /> <description> Returns the currently active 2D audio listener. Returns [code]null[/code] if there are no active 2D audio listeners, in which case the active 2D camera will be treated as listener. </description> </method> <method name="get_audio_listener_3d" qualifiers="const"> <return type="AudioListener3D" /> <description> Returns the currently active 3D audio listener. Returns [code]null[/code] if there are no active 3D audio listeners, in which case the active 3D camera will be treated as listener. </description> </method> <method name="get_camera_2d" qualifiers="const"> <return type="Camera2D" /> <description> Returns the currently active 2D camera. Returns null if there are no active cameras. </description> </method> <method name="get_camera_3d" qualifiers="const"> <return type="Camera3D" /> <description> Returns the currently active 3D camera. </description> </method> <method name="get_canvas_cull_mask_bit" qualifiers="const"> <return type="bool" /> <param index="0" name="layer" type="int" /> <description> Returns an individual bit on the rendering layer mask. </description> </method> <method name="get_embedded_subwindows" qualifiers="const"> <return type="Window[]" /> <description> Returns a list of the visible embedded [Window]s inside the viewport. [b]Note:[/b] [Window]s inside other viewports will not be listed. </description> </method> <method name="get_final_transform" qualifiers="const"> <return type="Transform2D" /> <description> Returns the transform from the viewport's coordinate system to the embedder's coordinate system. </description> </method> <method name="get_mouse_position" qualifiers="const"> <return type="Vector2" /> <description> Returns the mouse's position in this [Viewport] using the coordinate system of this [Viewport]. </description> </method> <method name="get_positional_shadow_atlas_quadrant_subdiv" qualifiers="const"> <return type="int" enum="Viewport.PositionalShadowAtlasQuadrantSubdiv" /> <param index="0" name="quadrant" type="int" /> <description> Returns the positional shadow atlas quadrant subdivision of the specified quadrant. </description> </method> <method name="get_render_info"> <return type="int" /> <param index="0" name="type" type="int" enum="Viewport.RenderInfoType" /> <param index="1" name="info" type="int" enum="Viewport.RenderInfo" /> <description> Returns rendering statistics of the given type. See [enum RenderInfoType] and [enum RenderInfo] for options. </description> </method> <method name="get_screen_transform" qualifiers="const"> <return type="Transform2D" /> <description> Returns the transform from the Viewport's coordinates to the screen coordinates of the containing window manager window. </description> </method> <method name="get_texture" qualifiers="const"> <return type="ViewportTexture" /> <description> Returns the viewport's texture. [b]Note:[/b] When trying to store the current texture (e.g. in a file), it might be completely black or outdated if used too early, especially when used in e.g. [method Node._ready]. To make sure the texture you get is correct, you can await [signal RenderingServer.frame_post_draw] signal. [codeblock] func _ready(): await RenderingServer.frame_post_draw $Viewport.get_texture().get_image().save_png("user://Screenshot.png") [/codeblock] [b]Note:[/b] When [member use_hdr_2d] is [code]true[/code] the returned texture will be an HDR image encoded in linear space. </description> </method> <method name="get_viewport_rid" qualifiers="const"> <return type="RID" /> <description> Returns the viewport's RID from the [RenderingServer]. </description> </method> <method name="get_visible_rect" qualifiers="const"> <return type="Rect2" /> <description> Returns the visible rectangle in global screen coordinates. </description> </method> <method name="gui_cancel_drag"> <return type="void" /> <description> Cancels the drag operation that was previously started through [method Control._get_drag_data] or forced with [method Control.force_drag]. </description> </method> <method name="gui_get_drag_data" qualifiers="const"> <return type="Variant" /> <description> Returns the drag data from the GUI, that was previously returned by [method Control._get_drag_data]. </description> </method> <method name="gui_get_focus_owner" qualifiers="const"> <return type="Control" /> <description> Returns the [Control] having the focus within this viewport. If no [Control] has the focus, returns null. </description> </method> <method name="gui_get_hovered_control" qualifiers="const"> <return type="Control" /> <description> Returns the [Control] that the mouse is currently hovering over in this viewport. If no [Control] has the cursor, returns null. Typically the leaf [Control] node or deepest level of the subtree which claims hover. This is very useful when used together with [method Node.is_ancestor_of] to find if the mouse is within a control tree. </description> </method> <method name="gui_is_drag_successful" qualifiers="const"> <return type="bool" /> <description> Returns [code]true[/code] if the drag operation is successful. </description> </method> <method name="gui_is_dragging" qualifiers="const"> <return type="bool" /> <description> Returns [code]true[/code] if a drag operation is currently ongoing and where the drop action could happen in this viewport. Alternative to [constant Node.NOTIFICATION_DRAG_BEGIN] and [constant Node.NOTIFICATION_DRAG_END] when you prefer polling the value. </description> </method> <method name="gui_release_focus"> <return type="void" /> <description> Removes the focus from the currently focused [Control] within this viewport. If no [Control] has the focus, does nothing. </description> </method> <method name="is_input_handled" qualifiers="const"> <return type="bool" /> <description> Returns whether the current [InputEvent] has been handled. Input events are not handled until [method set_input_as_handled] has been called during the lifetime of an [InputEvent]. This is usually done as part of input handling methods like [method Node._input], [method Control._gui_input] or others, as well as in corresponding signal handlers. If [member handle_input_locally] is set to [code]false[/code], this method will try finding the first parent viewport that is set to handle input locally, and return its value for [method is_input_handled] instead. </description> </method>
123664
<?xml version="1.0" encoding="UTF-8" ?> <class name="ProjectSettings" inherits="Object" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> Stores globally-accessible variables. </brief_description> <description> Stores variables that can be accessed from everywhere. Use [method get_setting], [method set_setting] or [method has_setting] to access them. Variables stored in [code]project.godot[/code] are also loaded into [ProjectSettings], making this object very useful for reading custom game configuration options. When naming a Project Settings property, use the full path to the setting including the category. For example, [code]"application/config/name"[/code] for the project name. Category and property names can be viewed in the Project Settings dialog. [b]Feature tags:[/b] Project settings can be overridden for specific platforms and configurations (debug, release, ...) using [url=$DOCS_URL/tutorials/export/feature_tags.html]feature tags[/url]. [b]Overriding:[/b] Any project setting can be overridden by creating a file named [code]override.cfg[/code] in the project's root directory. This can also be used in exported projects by placing this file in the same directory as the project binary. Overriding will still take the base project settings' [url=$DOCS_URL/tutorials/export/feature_tags.html]feature tags[/url] in account. Therefore, make sure to [i]also[/i] override the setting with the desired feature tags if you want them to override base project settings on all platforms and configurations. </description> <tutorials> <link title="Project Settings">$DOCS_URL/tutorials/editor/project_settings.html</link> <link title="3D Physics Tests Demo">https://godotengine.org/asset-library/asset/2747</link> <link title="3D Platformer Demo">https://godotengine.org/asset-library/asset/2748</link> <link title="Operating System Testing Demo">https://godotengine.org/asset-library/asset/2789</link> </tutorials>