feat: 建立关卡工坊并整理项目目录

- 加入 Godot 基础试玩、画风展示和通孔验证场景
- 支持自由放球、多层叠放、墙壁、锥口球洞及固定 +5 m/s 定向加速方块
- 保存 Blender 源资产、模型导出、资源制作脚本和关卡编辑存档逻辑
- 按七类目录归档工程,集中 zsh 启动入口并补充 AGENTS.md 文件索引
- 同步设计规则、依赖锁定、验证报告和目录迁移记录

验证:目录迁移后的资源导入与四个场景加载通过;本次提交前检查暂存内容,未重复运行整套物理测试。
This commit is contained in:
Yanchen
2026-11-16 11:12:21 +08:00
parent 151993e6df
commit 39ff1fd7b4
233 changed files with 147900 additions and 152 deletions
+156
View File
@@ -0,0 +1,156 @@
extends RefCounted
const BallScript = preload("res://playtest/baseline/scripts/iron_ball.gd")
var catalog: Dictionary
var physics: Dictionary
var scene_cache := {}
var collision_cache := {}
func _init() -> void:
catalog = JSON.parse_string(FileAccess.get_file_as_string("res://assets/collections/baseline/catalog.json"))["models"]
physics = JSON.parse_string(FileAccess.get_file_as_string("res://assets/collections/baseline/physics.json"))
func vector(a: Array) -> Vector3:
return Vector3(float(a[0]),float(a[1]),float(a[2]))
func create_piece(kind: String, location := Vector3.ZERO, quarter := 0) -> Node3D:
var root := Node3D.new()
root.name = kind
root.set_meta("piece_type",kind)
root.set_meta("quarter",quarter)
root.position = location
root.rotation.y = -quarter * PI / 2.0
if not scene_cache.has(kind):
scene_cache[kind] = load(catalog[kind]["path"])
var visual: Node3D = scene_cache[kind].instantiate()
root.add_child(visual)
add_colliders(visual,kind)
return root
func add_colliders(node: Node, kind: String) -> void:
if node is MeshInstance3D:
var body := StaticBody3D.new()
body.collision_layer = 1
body.collision_mask = 2
body.set_meta("piece_type",kind)
var material := PhysicsMaterial.new()
material.friction = .25 if kind=="goal_hole" else 1.0 # native pair uses min.
material.bounce = 0.0
body.physics_material_override = material
var collider := CollisionShape3D.new()
var key := kind + ":" + str(node.name)
if not collision_cache.has(key):
var shape: ConcavePolygonShape3D = node.mesh.create_trimesh_shape()
shape.backface_collision = true
collision_cache[key] = shape
collider.shape = collision_cache[key]
body.add_child(collider)
node.add_child(body)
for child in node.get_children():
if not child is StaticBody3D:
add_colliders(child,kind)
func create_ball() -> RigidBody3D:
var body = BallScript.new()
body.name = "IronBall"
var kind: Dictionary = physics["ballTypes"][0]
var profile: Dictionary = physics["physicsProfiles"][kind["physicsProfileId"]]
var data: Dictionary = catalog[kind["assetId"]]
var pair: Dictionary = physics["contactMaterialPairs"][0]
body.radius = float(data["radius"])
body.mass = float(profile["massKg"])
body.inertia = Vector3.ONE * (0.4 * body.mass * body.radius * body.radius)
body.drag_coefficient = float(profile["dragCoefficient"])
body.air_density = float(physics["airDensity"])
body.mu_static = float(pair["staticFriction"])
body.mu_dynamic = float(pair["dynamicFriction"])
body.rolling_resistance = float(pair["rollingResistance"])
body.collision_layer = 2
body.collision_mask = 3
var material := PhysicsMaterial.new()
material.friction = body.mu_static
material.bounce = float(pair["restitution"])
body.physics_material_override = material
var shape := SphereShape3D.new()
shape.radius = body.radius
var collision := CollisionShape3D.new()
collision.shape = shape
body.add_child(collision)
body.add_child(load(data["path"]).instantiate())
return body
func create_box(size: Vector3, location: Vector3, color: Color, solid := true) -> Node3D:
var root: Node3D = StaticBody3D.new() if solid else Node3D.new()
root.position = location
var mesh := BoxMesh.new()
mesh.size = size
var mat := StandardMaterial3D.new()
mat.albedo_color = color
mat.roughness = 0.8
mesh.material = mat
var visual := MeshInstance3D.new()
visual.mesh = mesh
root.add_child(visual)
if solid:
var shape := BoxShape3D.new()
shape.size = size
var collision := CollisionShape3D.new()
collision.shape = shape
root.add_child(collision)
root.collision_layer = 1
root.collision_mask = 2
var pm := PhysicsMaterial.new()
pm.friction = 1.0
root.physics_material_override = pm
return root
func path_point(kind: String, t: float, branch := 0, lower := false) -> Vector3:
var key := "lowerPaths" if lower else "upperPaths"
var path: Array = catalog[kind][key][branch]
var f := clampf(t,0.0,1.0)*(path.size()-1)
var i := mini(int(f),path.size()-2)
return vector(path[i]).lerp(vector(path[i+1]),f-i)
func path_tangent(kind: String, t: float, branch := 0, lower := false) -> Vector3:
return (path_point(kind,minf(t+.02,1.0),branch,lower)-path_point(kind,maxf(t-.02,0.0),branch,lower)).normalized()
func ball_on_surface(kind: String, t: float, branch := 0) -> Vector3:
var p := path_point(kind,t,branch)
var tangent := path_tangent(kind,t,branch)
var horizontal := Vector3(tangent.x,0,tangent.z).normalized()
var slope := tangent.y / maxf(Vector2(tangent.x,tangent.z).length(),0.001)
var normal := (Vector3.UP-horizontal*slope).normalized()
return p-Vector3.UP*float(catalog[kind]["grooveRadius"])+normal*float(catalog["iron_ball"]["radius"])+Vector3.UP*.018
func lower_passage_spec(kind: String) -> Dictionary:
var floor_y: float=catalog[kind].bottomRouteFloor
return {"floor_y":floor_y,"center_height":floor_y+float(catalog["iron_ball"].radius)}
func footprint(kind: String, quarter := 0) -> Vector2i:
var size: Array=catalog[kind].get("cellFootprint",[1,1])
return Vector2i(int(size[0]),int(size[1])) if quarter%2==0 else Vector2i(int(size[1]),int(size[0]))
func record_center(record: Dictionary) -> Vector3:
# Records store a grid anchor, while assets rotate around their own center.
var size:=footprint(record.kind,int(record.quarter))
return record.position+Vector3((size.x-1)*.5,0,(size.y-1)*.5)
func record_bounds(record: Dictionary) -> AABB:
var size:=footprint(record.kind,int(record.quarter))
var bounds: Dictionary=catalog[record.kind].boundsBlender
var corner: Vector3=record.position+Vector3(-.5,float(bounds["min"][2]),-.5)
return AABB(corner,Vector3(size.x,float(bounds["size"][2]),size.y))
func y_connectors() -> Array:
return [Vector3(-1.5,0,.5),Vector3(-1.5,0,-.5),Vector3(1.5,0,.5)]
func create_goal_hole(location: Vector3) -> Node3D:
return create_piece("goal_hole",location)
func crossed_goal(previous: Vector3, current: Vector3, goal: Vector3, radius: float) -> bool:
var height: float=goal.y-float(catalog["goal_hole"].depth)
if previous.y<=height or current.y>height:return false
var ratio: float=(previous.y-height)/maxf(previous.y-current.y,.000001)
var crossing: Vector3=previous.lerp(current,ratio)
var clearance: float=float(catalog["goal_hole"].openingRadius)-radius+.01
return Vector2(crossing.x-goal.x,crossing.z-goal.z).length()<=clearance
@@ -0,0 +1 @@
uid://dy6eglurc1qfn
+67
View File
@@ -0,0 +1,67 @@
extends RigidBody3D
var radius: float = 0.3
var drag_coefficient: float = 0.47
var air_density: float = 1.225
var wind_velocity := Vector3.ZERO
var mu_static: float = 0.42
var mu_dynamic: float = 0.32
var rolling_resistance: float = 0.025
var friction_enabled := true
var rolling_enabled := true
var drag_enabled := true
var contact_count := 0
var ball_contact_count := 0
var contact_slip := 0.0
var air_force := Vector3.ZERO
var rolling_torque := Vector3.ZERO
var travelled := 0.0
var previous_position := Vector3.ZERO
var tracking_started := false
func _ready() -> void:
continuous_cd = true
contact_monitor = true
max_contacts_reported = 12
can_sleep = false
linear_damp_mode = RigidBody3D.DAMP_MODE_REPLACE
angular_damp_mode = RigidBody3D.DAMP_MODE_REPLACE
linear_damp = 0.0
angular_damp = 0.0
func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
if freeze:
return
contact_count = state.get_contact_count()
ball_contact_count = 0
contact_slip = 0.0
var support_normal := Vector3.ZERO
for i in range(contact_count):
if state.get_contact_collider_object(i) is RigidBody3D:ball_contact_count+=1
# Contact positions are global; the sphere's radial direction is unambiguous.
var n := (state.transform.origin - state.get_contact_local_position(i)).normalized()
var relative := state.get_contact_local_velocity_at_position(i) - state.get_contact_collider_velocity_at_position(i)
var slip := relative - n * relative.dot(n)
contact_slip = maxf(contact_slip, slip.length())
if n.dot(Vector3.UP) > 0.15:
support_normal += n
# Godot exposes one native friction coefficient. Select a slip-dependent
# coefficient; native contact solver still owns the friction impulse.
physics_material_override.friction = (mu_static if contact_slip < 0.035 else mu_dynamic) if friction_enabled else 0.0
var relative_air := state.linear_velocity - wind_velocity
air_force = -0.5 * air_density * drag_coefficient * PI * radius * radius * relative_air.length() * relative_air if drag_enabled else Vector3.ZERO
state.apply_central_force(air_force)
rolling_torque = Vector3.ZERO
if rolling_enabled and support_normal.length_squared() > 0.001:
var n := support_normal.normalized()
var roll := state.angular_velocity - n * state.angular_velocity.dot(n)
if roll.length() > 0.0001:
var support := maxf(0.0, -(mass * state.total_gravity + air_force).dot(n))
var moment := 0.4 * mass * radius * radius
var limit := roll.length() * moment / state.step
rolling_torque = -roll.normalized() * minf(rolling_resistance * support * radius, limit)
state.apply_torque(rolling_torque)
if tracking_started:
travelled += state.transform.origin.distance_to(previous_position)
previous_position = state.transform.origin
tracking_started = true
@@ -0,0 +1 @@
uid://b47421ukibf66
+861
View File
@@ -0,0 +1,861 @@
extends Node3D
const Library = preload("res://playtest/baseline/scripts/asset_library.gd")
const IDS = ["straight", "turn_cw", "turn_ccw", "gentle", "steep", "y_merge"]
const NAMES = ["直行", "顺时针拐弯", "逆时针拐弯", "缓坡 · 0.5 m", "陡坡 · 1 m", "Y 汇流 · 2×2"]
const INK = Color("223c37")
const MUTED = Color("647a70")
const ACCENT = Color("347d68")
const PANEL = Color("f6f5ed")
var lib = Library.new()
var scenarios: Array = JSON.parse_string(FileAccess.get_file_as_string("res://playtest/baseline/data/scenarios.json"))
var world := Node3D.new()
var camera := Camera3D.new()
var records: Array = []
var pieces: Array = []
var ball
var previous_ball_position:=Vector3.ZERO
var merge_previous_positions: Array=[]
var merge_balls: Array = []
var merge_tags: Array = []
var merge_entered := {}
var merge_lost := {}
var merge_hole_events: Array = []
var merge_release_ticks: Array = []
var merge_pause_states: Array = []
var merge_collision_frames := 0
var merge_samples: Array = []
var second_trail_points := PackedVector3Array()
var second_trail_mesh := ImmediateMesh.new()
var second_trail_view := MeshInstance3D.new()
var editing_controls: Array = []
var branch_button: Button
var mode := 0
var selected_kind := "straight"
var selected_cell := Vector2i.ZERO
var selected_index := -1
var preview_quarter := 0
var placement_height := 0.0
var selected_branch := 0
var started := false
var paused := false
var elapsed := 0.0
var max_speed := 0.0
var spawn_transform := Transform3D.IDENTITY
var launch_velocity := Vector3.ZERO
var goal_position := Vector3.ZERO
var goal_active := false
var status := "搭建中 · 准备释放"
var launch_speed := 1.2
var saved_linear := Vector3.ZERO
var saved_angular := Vector3.ZERO
var yaw := 0.78
var pitch := 0.68
var camera_distance := 12.0
var camera_target := Vector3(0,0.55,0)
var orbiting := false
var trail_points := PackedVector3Array()
var trail_timer := 0.0
var trail_mesh := ImmediateMesh.new()
var trail_view := MeshInstance3D.new()
var trail_enabled := true
var cell_marker: Node3D
var stat_label: Label
var status_label: Label
var detail_label: Label
var warning_label: Label
var start_button: Button
var quota_label: Label
var mode_selector: OptionButton
var speed_slider: HSlider
var wind_slider: HSlider
var type_buttons: Array = []
var ui_font: SystemFont
var capture_frames := -1
var auto_release := false
var capture_path := ""
func _ready() -> void:
var initial_mode := 0
for arg in OS.get_cmdline_user_args():
if arg.begins_with("--capture="):
capture_path = arg.trim_prefix("--capture=")
capture_frames = 20
if arg == "--auto-release": auto_release = true
if arg.begins_with("--scenario="): initial_mode = clampi(int(arg.trim_prefix("--scenario=")),0,scenarios.size()-1)
if arg.begins_with("--piece=") and arg.trim_prefix("--piece=") in IDS: selected_kind = arg.trim_prefix("--piece=")
if arg.begins_with("--capture-frame="): capture_frames = int(arg.trim_prefix("--capture-frame="))
add_child(world)
setup_environment()
setup_ui()
build_preset(initial_mode)
mode_selector.select(initial_mode)
if auto_release: toggle_run()
func setup_environment() -> void:
var environment := Environment.new()
environment.background_mode = Environment.BG_COLOR
environment.background_color = Color("dce7df")
environment.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR
environment.ambient_light_color = Color("f1f2e9")
environment.ambient_light_energy = 0.35
environment.tonemap_mode = Environment.TONE_MAPPER_ACES
environment.tonemap_exposure = 0.85
environment.reflected_light_source = Environment.REFLECTION_SOURCE_SKY
var sky := Sky.new()
var sky_mat := ProceduralSkyMaterial.new()
sky_mat.sky_top_color = Color("a8c9d1")
sky_mat.sky_horizon_color = Color("e9e9da")
sky_mat.ground_bottom_color = Color("344d45")
sky_mat.ground_horizon_color = Color("b0b6a2")
sky.sky_material = sky_mat
environment.sky = sky
var env := WorldEnvironment.new()
env.environment = environment
add_child(env)
var sun := DirectionalLight3D.new()
sun.rotation_degrees = Vector3(-53,-32,0)
sun.light_color = Color("fff2d3")
sun.light_energy = 0.8
sun.shadow_enabled = true
add_child(sun)
var fill := DirectionalLight3D.new()
fill.rotation_degrees = Vector3(-27,145,0)
fill.light_color = Color("a4d9e8")
fill.light_energy = .25
add_child(fill)
add_child(camera)
camera.projection = Camera3D.PROJECTION_ORTHOGONAL
camera.size = 9.0
camera.near = .05
camera.far = 100
camera.current = true
camera.h_offset = -1.55
update_camera()
add_child(lib.create_box(Vector3(12,.22,10),Vector3(0,-1.2,0),Color("9da991")))
for axis in range(2):
for i in range(-5,6):
var size := Vector3(.008,.003,10) if axis == 0 else Vector3(10,.003,.008)
var pos := Vector3(i-.5,-1.087,0) if axis == 0 else Vector3(0,-1.087,i-.5)
add_child(lib.create_box(size,pos,Color("c1c9b5"),false))
trail_view.mesh = trail_mesh
var line_mat := StandardMaterial3D.new()
line_mat.albedo_color = Color("b85d39")
line_mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
trail_view.material_override = line_mat
add_child(trail_view)
second_trail_view.mesh=second_trail_mesh
var second_mat:=StandardMaterial3D.new()
second_mat.albedo_color=Color("377eae")
second_mat.shading_mode=BaseMaterial3D.SHADING_MODE_UNSHADED
second_trail_view.material_override=second_mat
add_child(second_trail_view)
func panel_style(color: Color, border := Color.TRANSPARENT, radius := 16) -> StyleBoxFlat:
var s := StyleBoxFlat.new()
s.bg_color = color
s.set_corner_radius_all(radius)
s.set_border_width_all(1)
s.border_color = border
s.content_margin_left = 14
s.content_margin_right = 14
s.content_margin_top = 6
s.content_margin_bottom = 6
return s
func label_for(text: String, size := 16, color := INK) -> Label:
var label := Label.new()
label.text = text
label.add_theme_font_size_override("font_size",size)
label.add_theme_color_override("font_color",color)
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
return label
func button_for(text: String, callback: Callable, primary := false) -> Button:
var button := Button.new()
button.text = text
button.custom_minimum_size.y = 34
button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
button.add_theme_stylebox_override("normal",panel_style(ACCENT if primary else Color("e6eade")))
button.add_theme_stylebox_override("hover",panel_style(Color("428e77") if primary else Color("d9e2d1")))
button.add_theme_stylebox_override("pressed",panel_style(Color("286853") if primary else Color("cbdac5")))
button.add_theme_color_override("font_color",Color("ffffff") if primary else INK)
button.add_theme_color_override("font_hover_color",Color("ffffff") if primary else INK)
button.pressed.connect(callback)
return button
func setup_ui() -> void:
var layer := CanvasLayer.new()
add_child(layer)
var theme := Theme.new()
var font := SystemFont.new()
font.font_names = PackedStringArray(["PingFang SC","Hiragino Sans GB","Arial"])
ui_font = font
theme.default_font = font
for type in ["OptionButton","CheckButton","PopupMenu"]:
theme.set_color("font_color",type,INK)
for state in ["font_pressed_color","font_hover_color","font_hover_pressed_color","font_focus_color"]:
theme.set_color(state,type,INK)
theme.default_font_size = 14
var root := Control.new()
root.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
root.mouse_filter = Control.MOUSE_FILTER_IGNORE
root.theme = theme
layer.add_child(root)
var header := VBoxContainer.new()
header.position = Vector2(30,22)
header.size = Vector2(700,95)
root.add_child(header)
header.add_child(label_for("INTOHOLE / PLAYTEST 01",14,ACCENT))
header.add_child(label_for("木轨道 · 铁球实验台",30))
header.add_child(label_for("Blender 资产 / Godot 真实刚体 / 120 Hz",14,MUTED))
var panel := PanelContainer.new()
panel.position = Vector2(26,130)
panel.size = Vector2(310,700)
panel.add_theme_stylebox_override("panel",panel_style(PANEL,Color("c8d1c0"),20))
root.add_child(panel)
var column := VBoxContainer.new()
column.add_theme_constant_override("separation",6)
panel.add_child(column)
column.add_child(label_for("试验场景",14,MUTED))
mode_selector = OptionButton.new()
for title in ["01 连续轨道 · 重力起跑","02 单件试跑 · 轨道检验","03 底部通孔 · 交叉检验","04 自由搭建 · 修改布局","05 双铁球 · 汇流入洞"]:mode_selector.add_item(title)
mode_selector.custom_minimum_size.y = 34
mode_selector.add_theme_stylebox_override("normal",panel_style(Color("e6eade")))
mode_selector.item_selected.connect(build_preset)
column.add_child(mode_selector)
column.add_child(label_for("滑槽库",14,MUTED))
var grid := GridContainer.new()
grid.columns = 2
grid.add_theme_constant_override("h_separation",6)
grid.add_theme_constant_override("v_separation",6)
column.add_child(grid)
for i in range(IDS.size()):
var kind: String = IDS[i]
var button := button_for(NAMES[i],func(): choose_kind(kind))
button.add_theme_font_size_override("font_size",13)
type_buttons.append(button)
grid.add_child(button)
detail_label = label_for("",13,MUTED)
column.add_child(detail_label)
var edit_row := HBoxContainer.new()
edit_row.add_child(button_for("↻ 旋转 90°",rotate_selected))
edit_row.add_child(button_for("放置 / 替换",place_selected))
column.add_child(edit_row)
var height_row := HBoxContainer.new()
height_row.add_child(button_for("降低 0.5",func(): change_height(-.5)))
height_row.add_child(button_for("抬高 0.5",func(): change_height(.5)))
height_row.add_child(button_for("移除",remove_selected))
column.add_child(height_row)
editing_controls=edit_row.get_children()+height_row.get_children()
quota_label = label_for("",12,MUTED)
column.add_child(quota_label)
column.add_child(HSeparator.new())
column.add_child(label_for("单件 / 通孔试验初速度",13,MUTED))
speed_slider = HSlider.new()
speed_slider.min_value = 0
speed_slider.max_value = 4
speed_slider.step = .1
speed_slider.value = launch_speed
speed_slider.value_changed.connect(func(v):
launch_speed=v
if not started: configure_spawn(); reset_ball()
)
column.add_child(speed_slider)
column.add_child(label_for("横风速度(m/s)",13,MUTED))
wind_slider = HSlider.new()
wind_slider.min_value = 0
wind_slider.max_value = 60
wind_slider.step = 5
column.add_child(wind_slider)
var checks := HBoxContainer.new()
var trail_check := CheckButton.new()
trail_check.text = "轨迹"
trail_check.button_pressed = true
trail_check.toggled.connect(func(on): trail_enabled=on; trail_view.visible=on; second_trail_view.visible=on)
checks.add_child(trail_check)
branch_button=button_for("切换岔口",func():
if started or mode==4:return
selected_branch=1-selected_branch
configure_spawn();reset_ball()
)
checks.add_child(branch_button)
column.add_child(checks)
var run_row := HBoxContainer.new()
start_button = button_for("▶ 释放铁球",toggle_run,true)
run_row.add_child(start_button)
run_row.add_child(button_for("重试",reset_ball))
column.add_child(run_row)
column.add_child(button_for("恢复场景",func(): build_preset(mode)))
status_label = label_for("",16,ACCENT)
column.add_child(status_label)
stat_label = label_for("",13,MUTED)
column.add_child(stat_label)
warning_label = label_for("",12,Color("a15c32"))
column.add_child(warning_label)
var help := label_for("左键选择格子 · R 旋转 · 空格释放/暂停 · T 重试\n右键拖动视角 · 滚轮缩放 · Esc 退出",14,INK)
help.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_LEFT)
help.position = Vector2(365,-70)
help.size = Vector2(900,50)
root.add_child(help)
refresh_ui()
func choose_kind(kind: String) -> void:
if started or mode==4 or quota(kind)<=0:return
selected_kind=kind
preview_quarter=0
selected_branch=0
if kind=="y_merge" and mode==1:
launch_speed=1.6
speed_slider.set_value_no_signal(launch_speed)
if mode==1 or mode==2: build_preset(mode)
else:update_marker()
refresh_ui()
func add_record(kind: String, position: Vector3, quarter := 0) -> void:
records.append({"kind":kind,"position":position,"quarter":quarter})
func build_preset(new_mode: int) -> void:
var previous_mode:=mode
mode=new_mode
get_window().title="IntoHole · 双铁球汇流" if mode==4 else "IntoHole · Physics Playtest"
if mode==4:
selected_kind="y_merge"
launch_speed=0
speed_slider.set_value_no_signal(0)
wind_slider.set_value_no_signal(0)
elif previous_mode==4:
launch_speed=1.2
speed_slider.set_value_no_signal(launch_speed)
if quota(selected_kind)<=0:selected_kind="straight"
if mode==1 and selected_kind=="y_merge":
launch_speed=1.6
speed_slider.set_value_no_signal(launch_speed)
started=false
paused=false
preview_quarter=0
placement_height=0
selected_index=-1
selected_cell=Vector2i.ZERO
records.clear()
if mode==0 or mode==3:
add_record("gentle",Vector3(-2,1,0),2)
for x in [-1,0,1]:add_record("straight",Vector3(x,.5,0))
goal_position=Vector3(2.0,.5+float(lib.catalog["straight"].ports[0].surface[1]),0)
goal_active=true
elif mode==1:
add_record(selected_kind,Vector3.ZERO)
goal_active=false
elif mode==2:
add_record(selected_kind,Vector3(0,.8,0))
goal_active=false
else:
for entry in scenarios[mode].layout:add_record(entry.kind,lib.vector(entry.position),int(entry.quarter))
goal_position=lib.vector(scenarios[mode].goal)
goal_active=true
selected_index=0 if mode==1 or mode==2 else find_cell(selected_cell)
if selected_index>=0:
placement_height=records[selected_index].position.y
preview_quarter=records[selected_index].quarter
rebuild_world()
configure_spawn()
reset_ball()
camera_target=Vector3(-.1,.8,0) if mode==0 or mode==3 else lib.record_center(records[0])+Vector3(0,.55,0)
camera.size=8.0 if mode==0 or mode==3 else (6.2 if selected_kind=="y_merge" else 4.2)
if mode==4:
camera_target=Vector3(.5,1.1,.5)
camera.size=9.5
update_camera()
refresh_ui()
func rebuild_world() -> void:
for child in world.get_children():
world.remove_child(child)
child.queue_free()
pieces.clear()
for record in records:
var center: Vector3=lib.record_center(record)
var piece: Node3D = lib.create_piece(record.kind,center,record.quarter)
world.add_child(piece)
pieces.append(piece)
var caption := Label3D.new()
caption.text=NAMES[IDS.find(record.kind)]
caption.font=ui_font
caption.outline_size=0
caption.font_size=28
caption.pixel_size=.005
caption.position=center+Vector3(0,-.08,lib.footprint(record.kind,record.quarter).y*.5+.13)
caption.rotation_degrees.x=-45
caption.modulate=Color("385449")
world.add_child(caption)
if mode==2 and not records.is_empty():
var record: Dictionary = records[0]
var center: Vector3=lib.record_center(record)
var footprint: Vector2i=lib.footprint(record.kind,record.quarter)
var guide: Dictionary=lib.lower_passage_spec(record.kind)
var floor_y: float = float(guide.floor_y)+record.position.y
var floor_node=lib.create_box(Vector3(footprint.x+2.4,.12,footprint.y+2.4),Vector3(center.x,floor_y-.06,center.z),Color("6f9e88"))
world.add_child(floor_node)
var caption := Label3D.new()
caption.text="通过真实孔洞 · 净半径 0.32 m"
caption.font=ui_font
caption.outline_size=0
caption.font_size=28
caption.pixel_size=.005
caption.position=Vector3(center.x,floor_y+.01,center.z+footprint.y*.5+.8)
caption.rotation_degrees.x=-90
world.add_child(caption)
if mode==1 and not records.is_empty() and records[0].kind=="y_merge":
var record: Dictionary=records[0]
var transform:=Transform3D(Basis(Vector3.UP,-int(record.quarter)*PI/2),lib.record_center(record))
for local_center in lib.y_connectors():
world.add_child(lib.create_piece("straight",transform*local_center,record.quarter))
if goal_active:
world.add_child(lib.create_goal_hole(goal_position))
var goal_label := Label3D.new()
goal_label.text="目标洞口"
goal_label.position=goal_position+Vector3(0,0,.7)
goal_label.font=ui_font
goal_label.outline_size=0
goal_label.font_size=30
goal_label.pixel_size=.006
goal_label.rotation_degrees.x=-45
goal_label.modulate=ACCENT
world.add_child(goal_label)
update_marker()
func configure_spawn() -> void:
if mode==4:return
if records.is_empty():return
var record: Dictionary=records[0]
if mode==3 and selected_index>=0 and selected_index<records.size():record=records[selected_index]
var kind: String=record.kind
var basis := Basis(Vector3.UP,-int(record.quarter)*PI/2)
var transform := Transform3D(basis,lib.record_center(record))
if mode==2:
var branch := mini(selected_branch,lib.catalog[kind].lowerPaths.size()-1)
var start: Vector3=lib.path_point(kind,0,branch,true)
start.y=float(lib.lower_passage_spec(kind).center_height)
var direction: Vector3=lib.path_tangent(kind,0,branch,true)
spawn_transform=Transform3D.IDENTITY
spawn_transform.origin=transform*(start-direction*.55+Vector3.UP*.025)
launch_velocity=basis*direction*launch_speed
elif kind=="gentle" or kind=="steep":
spawn_transform=Transform3D.IDENTITY
spawn_transform.origin=transform*lib.ball_on_surface(kind,.82)
launch_velocity=Vector3.ZERO
else:
var branch := mini(selected_branch,lib.catalog[kind].upperPaths.size()-1)
spawn_transform=Transform3D.IDENTITY
if mode==1 and kind=="y_merge":
spawn_transform.origin=transform*(lib.path_point(kind,0,branch)+Vector3(-.65,-float(lib.catalog[kind].grooveRadius)+float(lib.catalog["iron_ball"].radius)+.018,0))
launch_velocity=basis*Vector3.RIGHT*launch_speed
else:
spawn_transform.origin=transform*lib.ball_on_surface(kind,.08,branch)
launch_velocity=basis*lib.path_tangent(kind,.08,branch)*launch_speed
func reset_ball() -> void:
if not merge_balls.is_empty():
for sphere in merge_balls:
if is_instance_valid(sphere):remove_child(sphere);sphere.queue_free()
merge_balls.clear()
ball=null
for tag in merge_tags:
if is_instance_valid(tag):tag.queue_free()
merge_tags.clear()
merge_previous_positions.clear()
merge_entered.clear()
merge_lost.clear()
merge_hole_events.clear()
merge_release_ticks.clear()
merge_pause_states.clear()
merge_collision_frames=0
merge_samples.clear()
second_trail_points.clear()
second_trail_mesh.clear_surfaces()
if is_instance_valid(ball):
remove_child(ball)
ball.queue_free()
started=false
paused=false
elapsed=0
max_speed=0
trail_points.clear()
trail_mesh.clear_surfaces()
trail_timer=0
if mode==4:
create_merge_balls()
status="准备释放 · 两球同时从静止出发"
refresh_ui()
return
configure_spawn()
ball=lib.create_ball()
ball.freeze=true
add_child(ball)
ball.global_transform=spawn_transform
previous_ball_position=ball.position
status="准备释放 · 可调整布局"
refresh_ui()
func toggle_run() -> void:
if mode==4:
toggle_merge_run()
return
if not is_instance_valid(ball):return
if status.begins_with("成功") or status.begins_with("已离开"):
reset_ball()
if not started:
started=true
paused=false
ball.freeze=false
ball.linear_velocity=launch_velocity
ball.angular_velocity=Vector3.UP.cross(launch_velocity)/ball.radius
status="运行中"
elif not paused:
saved_linear=ball.linear_velocity
saved_angular=ball.angular_velocity
paused=true
ball.freeze=true
status="已暂停 · 重试后可编辑"
else:
paused=false
ball.freeze=false
ball.linear_velocity=saved_linear
ball.angular_velocity=saved_angular
status="运行中"
refresh_ui()
func refresh_ui() -> void:
if not is_instance_valid(detail_label):return
var count:=0
for record in records:
if record.kind==selected_kind:count+=1
var footprint: Vector2i=lib.footprint(selected_kind,preview_quarter)
detail_label.text="%s · %d° · 占用 %d×%d\n底座高度 %.1f m" % [NAMES[IDS.find(selected_kind)],preview_quarter*90,footprint.x,footprint.y,placement_height]
quota_label.text="当前类型 %d / %d 件 · 选格 (%d, %d)" % [count,quota(selected_kind),selected_cell.x,selected_cell.y]
for i in range(type_buttons.size()):
type_buttons[i].disabled=quota(IDS[i])<=0 or started or mode==4
type_buttons[i].add_theme_stylebox_override("normal",panel_style(Color("c5dbc8") if IDS[i]==selected_kind else Color("e6eade")))
start_button.text="▶ 释放铁球" if not started else ("▶ 继续" if paused else "Ⅱ 暂停")
for control in editing_controls:control.disabled=mode==4 or started
branch_button.disabled=mode==4 or started
speed_slider.editable=mode!=4 and not started
if mode==4:
start_button.text="▶ 同时释放两球" if not started else ("▶ 继续" if paused else "Ⅱ 暂停")
if merge_entered.size()+merge_lost.size()==2:start_button.text="↻ 再试一次"
quota_label.text="预设路线 · 两条支路汇入同一洞口"
status_label.text=status
var conflict:=false
for record in records:
if not bool(lib.catalog[record.kind].declaredBoundsFits):conflict=true
warning_label.text="陡坡试验件高 1.5 m,超出单格;保留原高差与球尺寸供验证。" if conflict else ("通孔净半径 0.32 m;平台仅提供进出口承托。" if mode==2 else "当前铁球半径 0.3 m · 开口净半径 0.32 m")
if mode==4:warning_label.text="两球同时释放 · 初速度为零 · 球间碰撞开启"
func quota(kind: String) -> int:
return int(scenarios[mode].quotas.get(kind,0))
func find_cell(cell: Vector2i) -> int:
for i in range(records.size()):
var pos: Vector3=records[i].position
var footprint: Vector2i=lib.footprint(records[i].kind,records[i].quarter)
if cell.x>=roundi(pos.x) and cell.x<roundi(pos.x)+footprint.x and cell.y>=roundi(pos.z) and cell.y<roundi(pos.z)+footprint.y:return i
return -1
func placement_error(candidate: Dictionary, ignore_index := -1) -> String:
var box: AABB=lib.record_bounds(candidate)
var attached:=records.is_empty() or (records.size()==1 and ignore_index==0)
for i in range(records.size()):
if i==ignore_index:continue
var other: AABB=lib.record_bounds(records[i])
var overlap:=Vector3(minf(box.end.x,other.end.x)-maxf(box.position.x,other.position.x),minf(box.end.y,other.end.y)-maxf(box.position.y,other.position.y),minf(box.end.z,other.end.z)-maxf(box.position.z,other.position.z))
if overlap.x>.001 and overlap.y>.001 and overlap.z>.001:return "占用空间与其他方块重叠"
for axis in range(3):
if absf(overlap[axis])<.001 and overlap[(axis+1)%3]>.001 and overlap[(axis+2)%3]>.001:attached=true
return "" if attached else "新滑槽至少一侧需依附已有方块"
func place_selected() -> void:
if started or mode==4:return
if mode==1 or mode==2:
records[0]={"kind":selected_kind,"position":Vector3(0,.8 if mode==2 else 0,0),"quarter":preview_quarter}
else:
var count:=0
for record in records:
if record.kind==selected_kind:count+=1
var idx:=find_cell(selected_cell)
if count>=quota(selected_kind) and (idx<0 or records[idx].kind!=selected_kind):
status="该类型数量已达本场配额";refresh_ui();return
var entry={"kind":selected_kind,"position":Vector3(selected_cell.x,placement_height,selected_cell.y),"quarter":preview_quarter}
var issue:=placement_error(entry,idx)
if not issue.is_empty():status=issue;refresh_ui();return
if idx>=0:records[idx]=entry
else:records.append(entry)
selected_index=find_cell(selected_cell)
rebuild_world();reset_ball()
func rotate_selected() -> void:
if started or mode==4:return
var next_quarter: int=(preview_quarter+1)%4
var idx:=0 if mode==1 or mode==2 else find_cell(selected_cell)
if idx>=0:
var candidate: Dictionary=records[idx].duplicate()
candidate.quarter=next_quarter
var issue: String=placement_error(candidate,idx) if mode in [0,3] else ""
if not issue.is_empty():status=issue;refresh_ui();return
records[idx]=candidate
preview_quarter=next_quarter
rebuild_world();reset_ball()
else:
preview_quarter=next_quarter
update_marker()
refresh_ui()
func change_height(amount: float) -> void:
if started or mode==4:return
var new_height: float=clampf(placement_height+amount,-.5,3.0)
var idx:=0 if mode==1 or mode==2 else find_cell(selected_cell)
if idx>=0:
var pos: Vector3=records[idx].position
pos.y=new_height
var candidate: Dictionary=records[idx].duplicate()
candidate.position=pos
var issue: String=placement_error(candidate,idx) if mode in [0,3] else ""
if not issue.is_empty():status=issue;refresh_ui();return
records[idx]=candidate
placement_height=new_height
rebuild_world();reset_ball()
else:
placement_height=new_height
update_marker()
refresh_ui()
func remove_selected() -> void:
if started or mode in [1,2,4]:return
var idx:=find_cell(selected_cell)
if idx>=0:
records.remove_at(idx)
selected_index=-1
rebuild_world();reset_ball()
func update_marker() -> void:
if is_instance_valid(cell_marker):cell_marker.queue_free()
cell_marker=Node3D.new()
add_child(cell_marker)
if mode in [1,2,4]:return
var footprint: Vector2i=lib.footprint(selected_kind,preview_quarter)
var center:=Vector3(selected_cell.x+(footprint.x-1)*.5,placement_height+.01,selected_cell.y+(footprint.y-1)*.5)
for axis in range(2):
for side in [-1,1]:
var size:=Vector3(.025,.025,footprint.y) if axis==0 else Vector3(footprint.x,.025,.025)
var pos:=center+(Vector3(side*footprint.x*.5,0,0) if axis==0 else Vector3(0,0,side*footprint.y*.5))
cell_marker.add_child(lib.create_box(size,pos,Color("c7743d"),false))
func update_camera() -> void:
camera.position=camera_target+Vector3(cos(yaw)*cos(pitch),sin(pitch),sin(yaw)*cos(pitch))*camera_distance
camera.look_at(camera_target)
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventKey and event.pressed and not event.echo:
if event.keycode==KEY_SPACE:toggle_run()
elif event.keycode==KEY_R:rotate_selected()
elif event.keycode==KEY_T:reset_ball()
elif event.keycode==KEY_DELETE:remove_selected()
elif event.keycode==KEY_ESCAPE:get_tree().quit()
if event is InputEventMouseButton:
if event.button_index==MOUSE_BUTTON_RIGHT:orbiting=event.pressed
if event.pressed and event.button_index==MOUSE_BUTTON_WHEEL_UP:camera.size=maxf(2.5,camera.size-.5)
if event.pressed and event.button_index==MOUSE_BUTTON_WHEEL_DOWN:camera.size=minf(16,camera.size+.5)
if event.pressed and event.button_index==MOUSE_BUTTON_LEFT and not started and mode in [0,3]:
var origin:=camera.project_ray_origin(event.position)
var direction:=camera.project_ray_normal(event.position)
var query:=PhysicsRayQueryParameters3D.create(origin,origin+direction*100,1)
var collision:=get_world_3d().direct_space_state.intersect_ray(query)
if not collision.is_empty():
var node: Node=collision.collider
while node!=null and node not in pieces:
node=node.get_parent()
if node!=null:
selected_index=pieces.find(node)
var record: Dictionary=records[selected_index]
selected_cell=Vector2i(roundi(record.position.x),roundi(record.position.z))
selected_kind=record.kind
preview_quarter=record.quarter
placement_height=record.position.y
update_marker();refresh_ui()
return
var hit=Plane(Vector3.UP,placement_height).intersects_ray(origin,direction)
if hit!=null:
selected_cell=Vector2i(clampi(roundi(hit.x),-4,4),clampi(roundi(hit.z),-4,4))
selected_index=find_cell(selected_cell)
if selected_index>=0:
selected_cell=Vector2i(roundi(records[selected_index].position.x),roundi(records[selected_index].position.z))
selected_kind=records[selected_index].kind
preview_quarter=records[selected_index].quarter
placement_height=records[selected_index].position.y
update_marker();refresh_ui()
if event is InputEventMouseMotion and orbiting:
yaw-=event.relative.x*.006
pitch=clampf(pitch+event.relative.y*.004,.18,1.4)
update_camera()
func _physics_process(delta: float) -> void:
if mode==4:
process_merge(delta)
return
if not is_instance_valid(ball):return
ball.wind_velocity=Vector3(0,0,float(wind_slider.value))
if started and not paused and not ball.freeze:
elapsed+=delta
max_speed=maxf(max_speed,ball.linear_velocity.length())
if goal_active and lib.crossed_goal(previous_ball_position,ball.position,goal_position,ball.radius):
status="成功入洞 · %.2f 秒" % elapsed
ball.freeze=true
ball.hide()
ball.collision_layer=0
ball.collision_mask=0
refresh_ui()
elif ball.position.y<-.65 and mode!=2 or ball.position.y<-2.0 or ball.position.length()>30:
status="已离开轨道 · 调整布局后重试"
ball.freeze=true
refresh_ui()
trail_timer+=delta
if trail_timer>.045:
trail_timer=0
trail_points.append(ball.position)
if trail_points.size()>800:trail_points.remove_at(0)
trail_mesh.clear_surfaces()
if trail_points.size()>1:
trail_mesh.surface_begin(Mesh.PRIMITIVE_LINE_STRIP)
for point in trail_points:trail_mesh.surface_add_vertex(point)
trail_mesh.surface_end()
previous_ball_position=ball.position
stat_label.text="速度 %.2f m/s 最高 %.2f m/s\n高度 %.2f m 时间 %.2f s\n转速 %.2f rad/s 接触 %d\n铁球 R %.2f m / %.1f kg" % [ball.linear_velocity.length(),max_speed,ball.position.y,elapsed,ball.angular_velocity.length(),ball.contact_count,ball.radius,ball.mass]
func _process(_delta: float) -> void:
if capture_frames>0:
capture_frames-=1
if capture_frames==0:
await RenderingServer.frame_post_draw
get_viewport().get_texture().get_image().save_png(capture_path)
print("CAPTURE_SAVED "+capture_path)
get_tree().quit()
func create_merge_balls() -> void:
for i in range(scenarios[mode].spawns.size()):
var spec: Dictionary=scenarios[mode].spawns[i]
var record: Dictionary=records[int(spec.recordIndex)]
var transform:=Transform3D(Basis(Vector3.UP,-int(record.quarter)*PI/2),lib.record_center(record))
var sphere=lib.create_ball()
sphere.name=spec.ballId
sphere.set_meta("ball_id",spec.ballId)
sphere.freeze=true
add_child(sphere)
sphere.global_position=transform*lib.ball_on_surface(record.kind,float(spec.pathT))
merge_balls.append(sphere)
merge_previous_positions.append(sphere.position)
var tag:=Label3D.new()
tag.text="A" if i==0 else "B"
tag.font=ui_font
tag.font_size=36
tag.pixel_size=.006
tag.outline_size=0
tag.modulate=Color("a95330") if i==0 else Color("276894")
tag.billboard=BaseMaterial3D.BILLBOARD_ENABLED
tag.position=sphere.position+Vector3.UP*.65
add_child(tag)
merge_tags.append(tag)
ball=merge_balls[0]
func toggle_merge_run() -> void:
if merge_balls.is_empty():return
if merge_entered.size()+merge_lost.size()==merge_balls.size():reset_ball()
if not started:
started=true
paused=false
merge_release_ticks.clear()
for sphere in merge_balls:
sphere.freeze=false
sphere.linear_velocity=Vector3.ZERO
sphere.angular_velocity=Vector3.ZERO
merge_release_ticks.append(Engine.get_physics_frames())
status="运行中 · 已入洞 0/2"
elif not paused:
merge_pause_states.clear()
for i in range(merge_balls.size()):
var sphere=merge_balls[i]
merge_pause_states.append({"linear":sphere.linear_velocity,"angular":sphere.angular_velocity})
if not merge_entered.has(i) and not merge_lost.has(i):sphere.freeze=true
paused=true
status="已暂停 · 已入洞 %d/2" % merge_entered.size()
else:
for i in range(merge_balls.size()):
if merge_entered.has(i) or merge_lost.has(i):continue
merge_balls[i].freeze=false
merge_balls[i].linear_velocity=merge_pause_states[i].linear
merge_balls[i].angular_velocity=merge_pause_states[i].angular
paused=false
status="运行中 · 已入洞 %d/2" % merge_entered.size()
refresh_ui()
func draw_trace(mesh: ImmediateMesh, points: PackedVector3Array) -> void:
mesh.clear_surfaces()
if points.size()<2:return
mesh.surface_begin(Mesh.PRIMITIVE_LINE_STRIP)
for point in points:mesh.surface_add_vertex(point)
mesh.surface_end()
func process_merge(delta: float) -> void:
if merge_balls.size()!=2:return
var active:=merge_balls.size()-merge_entered.size()-merge_lost.size()
if started and not paused and active>0:
var previous_status:=status
elapsed+=delta
var touching_ball:=false
for i in range(merge_balls.size()):
if merge_entered.has(i) or merge_lost.has(i):continue
var sphere=merge_balls[i]
sphere.wind_velocity=Vector3(0,0,float(wind_slider.value))
max_speed=maxf(max_speed,sphere.linear_velocity.length())
if sphere.ball_contact_count>0:touching_ball=true
if lib.crossed_goal(merge_previous_positions[i],sphere.position,goal_position,sphere.radius):
merge_entered[i]=true
merge_hole_events.append({"ballId":str(sphere.get_meta("ball_id")),"time":elapsed,"position":[sphere.position.x,sphere.position.y,sphere.position.z]})
sphere.freeze=true
sphere.hide()
sphere.collision_layer=0
sphere.collision_mask=0
merge_tags[i].hide()
print("MERGE_HOLE "+JSON.stringify(merge_hole_events.back()))
elif sphere.position.y<-.65 or sphere.position.length()>30:
merge_lost[i]=true
sphere.freeze=true
merge_previous_positions[i]=sphere.position
if touching_ball:merge_collision_frames+=1
if merge_entered.size()==2:
status="成功入洞 2/2 · %.2f 秒" % elapsed
elif merge_lost.size()>0:
status="有球离轨 · 已入洞 %d/2" % merge_entered.size()
else:
status="运行中 · 已入洞 %d/2" % merge_entered.size()
trail_timer+=delta
if trail_timer>.045:
trail_timer=0
if not merge_entered.has(0) and not merge_lost.has(0):trail_points.append(merge_balls[0].position)
if not merge_entered.has(1) and not merge_lost.has(1):second_trail_points.append(merge_balls[1].position)
if trail_points.size()>800:trail_points.remove_at(0)
if second_trail_points.size()>800:second_trail_points.remove_at(0)
draw_trace(trail_mesh,trail_points)
draw_trace(second_trail_mesh,second_trail_points)
merge_samples.append({"time":elapsed,"a":[merge_balls[0].position.x,merge_balls[0].position.y,merge_balls[0].position.z],"b":[merge_balls[1].position.x,merge_balls[1].position.y,merge_balls[1].position.z],"entered":merge_entered.size()})
if merge_samples.size()>2400:merge_samples.pop_front()
if status!=previous_status:refresh_ui()
var lines:=PackedStringArray()
for i in range(merge_balls.size()):
var sphere=merge_balls[i]
merge_tags[i].position=sphere.position+Vector3.UP*.65
var label: String="A" if i==0 else "B"
var state: String="已入洞" if merge_entered.has(i) else ("已离轨" if merge_lost.has(i) else ("行进中" if started else "待释放"))
if merge_entered.has(i) or merge_lost.has(i):lines.append("%s %s" % [label,state])
else:lines.append("%s %.2f m/s · %s" % [label,sphere.linear_velocity.length(),state])
lines.append("入洞 %d/2 · 用时 %.2f s" % [merge_entered.size(),elapsed])
lines.append("每球 R %.2f m · %.1f kg" % [merge_balls[0].radius,merge_balls[0].mass])
stat_label.text="\n".join(lines)
@@ -0,0 +1 @@
uid://854wfkeb5fa