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
+87
View File
@@ -0,0 +1,87 @@
# 首版 playtest 验证说明
更新日期:2026-11-15(Asia/Shanghai)。
这是资产、接触运动和搭建流程的可运行验证台。正式方块规则继续以 [blocks.md](../../references/design/blocks.md) 为准;试验中发现的尺寸冲突在此记录,不自动修改正式规则。
## 运行环境与生成链路
使用项目现有 uv 环境运行 `scripts/python/baseline.py`。建模由 Blender 自带 Python 执行,项目 Python 负责启动、文件管理和测试编排。
本机可执行文件:
- Godot 4.7.2:`/Applications/Godot.app/Contents/MacOS/Godot`。
- Blender 5.2.0 LTS:`/Applications/Blender.app/Contents/MacOS/Blender`。
`/usr/local/bin/blender` 是符号链接,在本次环境中曾导致 Blender 无法找到捆绑资源;启动器解析为应用程序内的真实路径。基础模型变体现位于 `assets/<资源类型>/<资源名>/baseline/model.glb`;整套源文件与制作代码在 `assets/collections/baseline/source/`。`source/.gdignore` 避免 Godot 自动反复导入 `.blend`。
建模坐标为 Z 向上,导出的 glTF 为 Y 向上;坐标转换为 `(x,y,z) → (x,z,-y)`。Godot 中绕 Y 轴负方向旋转 90°,对应从局部 +Z 看向原点的顺时针操作。模型默认朝向为 0°。
## 资产与几何结果
六种滑槽分别为直行、顺时针拐弯、逆时针拐弯、缓坡、陡坡和 Y 形汇流。球半径现为 0.3 m(直径 0.6 m);上槽半圆截面、底部圆孔和目标洞口均采用 0.32 m 净半径(直径 0.64 m),径向余量为 0.02 m。模型、导出目录与碰撞体使用同一几何来源。
模型与碰撞体均保留实际槽面、底部开孔;碰撞采用最终布尔网格的三角面,不使用填满方块的盒形碰撞。所有生成滑槽的布尔网格通过闭合流形边检查,详细测量见 [geometry_report.json](../artifacts/baseline/geometry_report.json)。
滑槽是独立的方块或楔形底座,通过布尔切削生成上方半圆槽和下方拱孔。默认连续路线由一个缓坡和三个直行滑槽拼接,并非一整条长轨模型。当前木材使用基础颜色与粗糙度表达油漆木表面,尚未制作精细木纹贴图。
滑槽作为固定碰撞对象保持位置,不需要立柱承托。试验场景不再添加装饰立柱;底部通孔试验保留入口、出口及开放底孔所需的承托台,小球由真实孔洞引导,不再生成独立下层导轨。
- 直行、两种拐弯及缓坡的包围尺寸为 1 × 1 × 1 m。Y 形汇流的声明规格及实测尺寸均为 2 × 2 × 1 m。
- 陡坡的包围尺寸为 1 × 1 × 1.5 m。其两端高差保留为 1 m,沿用用户已确认保留的超界试验件外形;此次缩小槽径后仍维持该原型包围尺寸,正式单格规则以后再调整。该资产在目录和界面中均有标记。
- 水平直槽、拐弯和 Y 形的底孔为封闭圆形通孔,孔底与方块底面、孔顶与上槽槽底之间分别约有 0.02 m 实体厚度。缓坡、陡坡的底孔仍部分开放,试验平台提供孔底与进出口承托。
- Y 形在同一侧设置两个相邻、等高的入口,中心相距 1 m,各自连接一个单格直槽;公共出口与其中一路对齐,另一路以连续 S 形曲线并入,不要求对称。单件场景同时展示两个输入直槽和一个输出直槽,验证真实接缝。
- 编辑器按 Y 形四格占用进行选择、替换、旋转及重叠检查;数量配额计为一块。下方孔洞直接按上方路线的对角线镜像制作,通孔自身保留引导表面。
目标洞口现由 Blender 制作并导出为 `goal_hole.glb`:入口与喉部净半径均为 0.32 m,深度 0.55 m,壁厚 0.04 m。碰撞使用同一空心网格,避免只缩小视觉开口。入洞检测记录球心向下跨过洞底平面的交点,再按洞口净空校验水平位置。
独立半径对比实验已完成选择并清理:删除其 Blender 模型、GLB、Godot 场景、脚本和报告,以及旧镜像下层导轨夹具;当前主模型与五个主试玩场景继续保留。
## 物理实现与参数
铁球为 SphereShape3D 刚体,半径读取生成的资产目录;均匀实心球惯量按质量和半径生成。所有轨道为静态三角网格碰撞体,铁球与轨道、铁球与铁球碰撞均开启。固定物理频率为 120 Hz,启用连续碰撞检测。
当前 `physics.json` 中的名义铁密度假设为 7870 kg/m³,半径 0.3 m 对应约 890.08 kg;质量值保存在物理预设中。木材接触试验系数为:静摩擦 0.42、动摩擦 0.32、滚动阻力 0.025、回弹 0.08;空气密度 1.225 kg/m³,球阻力系数 0.47。这些是首轮验证参数,不是实验测得的材质常数。
Godot 原生 PhysicsMaterial 只暴露一个摩擦参数;本轮根据接触点滑速切换静/动摩擦系数,再由原生求解器计算接触冲量。这是用于本轮试验的近似,不等价于完整的逐接触双系数材质求解。滚动阻力另施加受限力矩,空气作用使用相对空气速度计算,不额外修改轨道速度。多材质同时接触和铁球之间的独立材质配对尚未完整标定;目前原生回弹合成会使两个铁球各 0.08 的回弹得到约 0.16 的相对恢复表现。[Godot PhysicsMaterial](https://docs.godotengine.org/en/4.7/classes/class_physicsmaterial.html)
接触数据和力矩在刚体积分回调中读取、施加,轨迹记录只用于显示与测量。[Godot PhysicsDirectBodyState3D](https://docs.godotengine.org/en/4.7/classes/class_physicsdirectbodystate3d.html)
## 验证范围
运行 `./scripts/run.zsh baseline-test` 会刷新 Godot 导入并运行物理、交互流程和双球汇流三组测试。报告记录实际参数、轨迹和结果;退出码非零表示测试失败。
物理测试共 70 项:
- 真空自由落体与球在半圆槽中的静止接触。
- 30° 理想平面上实心球滚动,加速度与解析值比较。
- 水平滚动时关闭/开启滚动阻力的速度差异。
- 两个铁球副本迎面碰撞,检查速度方向与总动量。
- 六种滑槽、四个朝向的上方通过与下方通过;Y 形分别测试两个岔口,共 56 项路径测试。
- Y 形连接两个相邻直槽及一个出口直槽后,分别测试两个入口和四个朝向,共 8 项完整连接测试。连接测试初速度为 1.6 m/s,其余既有路径测试继续使用原有的 1.2 m/s 或坡道静止释放条件。
- 无接触条件下,质量相差十倍时的风响应比较。
交互流程测试共 30 项:默认重力路线穿过真实洞口、释放、暂停、重试、六种资产选择与四次旋转复位、相邻放置、运行后编辑锁定、删除、拒绝悬空放置、场景配额及鼠标射线选取可见方块;另覆盖 Y 形的合法四格尺寸、超界标记区分、重叠拒绝、四格选择、中心旋转和替换后释放多余格子。
较长的完整连接测试采用 1.6 m/s 初速度,场景中仍可用滑块调整;试验只设置初始速度,未添加持续推力、速度锁定或关闭摩擦。低初速度是否足够到达后续路线,继续由实际行程和摩擦耗能决定。
测试调用真实 Godot 场景和物理引擎。界面按钮通过信号触发、选格通过引擎输入事件路径验证;原生渲染已截图检查。没有声称通过操作系统鼠标自动化完成所有按钮测试。
最新结果见 [物理报告](../artifacts/baseline/physics_report.json) 与 [交互报告](../artifacts/baseline/playtest_report.json)。默认路线约 2.90 秒入洞;30° 平面加速度约 3.5033 m/s²,解析值约 3.5036 m/s²。窗口关闭或不同操作路径不会被这两个数值覆盖,需要按实际试玩继续验证。
## 双铁球汇流场景
场景菜单第 5 项为“双铁球 · 汇流入洞”,也可使用 `./scripts/run.zsh merge` 直接打开。布局和出生位置保存在 [scenarios.json](data/scenarios.json) 的 `dual_merge` 项。
路线由一个 Y 形汇流、五个直槽和两个缓坡组成。A、B 两球使用同一个铁球资产与物理预设,从两条支路相同高度的位置同时静止释放。A 路比 B 路多一个直槽,通过真实行程错开汇入时间;两路在 Y 形的相邻同高入口汇合,经公共水平直槽进入同一个洞口。缩小洞口后,将最后一段下坡改为水平直槽,以减少出口加速造成的撞沿和卡边;未调整球材质,也没有额外推力、延迟释放或轨迹牵引。
球间碰撞保持开启;当前演示布局利用路线长度避免两球同时挤入狭窄合流处。画面以 A/B 标识和不同颜色轨迹区分两球,分别显示速度和状态。
入洞按球的唯一编号计数,每球只记录一次。已入洞球隐藏并退出碰撞;部分入洞不成功,任何一球丢失也不能通过减少剩余球数完成通关。重试会重建两球并清空入洞、轨迹及暂停状态。预设演示场景不开放方块编辑,可切回自由搭建场景调整其他布局。
双球专项验证共 16 项,覆盖同高分支、同时释放、球间碰撞开关、两球暂停、分别通过不同入口及共同出口、两球进入同一洞口、部分入洞、事件去重、退出模拟、重试复现、丢球不判胜及切回单球场景。实际完成时间约 5.4 秒,具体轨迹和逐球入洞事件见 [双球汇流报告](../artifacts/baseline/merge_report.json)。
## 后续需验证
陡坡的单格几何仍需做设计取舍;下穿布局需要明确下层承托空间。自由搭建提供格子选择、0.5 m 高度调整、声明占用及包围盒重叠和相邻检查,尚不是完整的表面吸附、精确几何互锁与地图通关验收编辑器。物理系数、多材质同时接触及高速极端组合也需要继续验证。
@@ -0,0 +1,84 @@
extends SceneTree
var results: Array=[]
var failures:=0
func _initialize() -> void:call_deferred("run")
func check(name: String, ok: bool, detail: Dictionary={}) -> void:
results.append({"name":name,"passed":ok,"detail":detail.duplicate(true)})
if not ok:failures+=1
print(("PASS " if ok else "FAIL ")+name+" "+JSON.stringify(detail))
func run() -> void:
var app=load("res://playtest/baseline/scenes/main.tscn").instantiate()
root.add_child(app)
app.build_preset(4)
await physics_frame
check("two_iron_balls_ready",app.merge_balls.size()==2 and app.merge_balls.all(func(b):return b.freeze and is_equal_approx(b.radius,.3) and b.linear_velocity.is_zero_approx()))
check("separate_equal_height_branches",is_equal_approx(app.merge_balls[0].position.y,app.merge_balls[1].position.y) and is_equal_approx(absf(app.merge_balls[0].position.z-app.merge_balls[1].position.z),1.0))
check("ball_collision_enabled",app.merge_balls.all(func(b):return (b.collision_layer&2)!=0 and (b.collision_mask&2)!=0))
app.start_button.pressed.emit()
check("simultaneous_release",app.merge_release_ticks.size()==2 and app.merge_release_ticks[0]==app.merge_release_ticks[1] and app.merge_balls.all(func(b):return not b.freeze and b.linear_velocity.is_zero_approx()))
for i in range(35):await physics_frame
app.toggle_run()
var positions: Array=app.merge_balls.map(func(b):return b.position)
var time: float=app.elapsed
for i in range(20):await physics_frame
check("pause_stops_both_balls",app.paused and app.merge_balls[0].position.is_equal_approx(positions[0]) and app.merge_balls[1].position.is_equal_approx(positions[1]) and is_equal_approx(time,app.elapsed))
app.toggle_run()
var partial_seen:=false
var premature_win:=false
for i in range(2400):
await physics_frame
if app.merge_entered.size()==1:
partial_seen=true
premature_win=premature_win or app.status.begins_with("成功")
if app.merge_entered.size()+app.merge_lost.size()==2:break
check("both_balls_enter_common_hole",app.merge_entered.size()==2 and app.merge_lost.is_empty(),{"status":app.status,"time":app.elapsed,"hole_events":app.merge_hole_events,"ball_collision_frames":app.merge_collision_frames,"a_position":[app.merge_balls[0].position.x,app.merge_balls[0].position.y,app.merge_balls[0].position.z],"b_position":[app.merge_balls[1].position.x,app.merge_balls[1].position.y,app.merge_balls[1].position.z]})
check("one_ball_is_not_a_win",partial_seen and not premature_win)
check("two_unique_hole_events",app.merge_hole_events.size()==2 and app.merge_hole_events[0].ballId!=app.merge_hole_events[1].ballId)
var first_run: Array=app.merge_samples.duplicate(true)
var correct_inlets:=true
var common_outlet:=true
for i in range(2):
var key: String="a" if i==0 else "b"
var inlet_seen:=false
var outlet_seen:=false
for sample in first_run:
var p: Array=sample[key]
if p[0]>-.6 and p[0]<-.1 and absf(p[2]-i)<.2 and p[1]>1.8:inlet_seen=true
if p[0]>1.3 and p[0]<1.7 and absf(p[2]-1)<.2 and p[1]>1.5:outlet_seen=true
correct_inlets=correct_inlets and inlet_seen
common_outlet=common_outlet and outlet_seen
check("both_use_distinct_y_inlets",correct_inlets)
check("both_use_common_y_outlet",common_outlet)
for i in range(60):await physics_frame
check("hole_events_not_repeated",app.merge_hole_events.size()==2)
check("entered_balls_exit_simulation",app.merge_balls.all(func(b):return b.freeze and not b.visible and b.collision_mask==0 and b.collision_layer==0))
app.reset_ball()
await physics_frame
check("retry_restores_two_balls",app.merge_balls.size()==2 and app.merge_balls.all(func(b):return b.freeze and b.visible and b.collision_mask==3) and app.merge_entered.is_empty() and app.merge_hole_events.is_empty() and app.elapsed==0)
app.toggle_run()
for i in range(2400):
await physics_frame
if app.merge_entered.size()+app.merge_lost.size()==2:break
check("repeat_run_completes",app.merge_entered.size()==2 and app.merge_lost.is_empty(),{"time":app.elapsed})
app.reset_ball();app.toggle_run()
app.merge_balls[0].position=Vector3(0,-2,0)
for i in range(1800):
await physics_frame
if app.merge_entered.size()+app.merge_lost.size()==2:break
check("lost_ball_does_not_reduce_target",app.merge_lost.size()==1 and app.merge_entered.size()==1 and not app.status.begins_with("成功"))
app.build_preset(0)
await physics_frame
var dynamic_balls:=0
for child in app.get_children():
if child is RigidBody3D:dynamic_balls+=1
check("switch_back_to_single_ball_scene",app.merge_balls.is_empty() and dynamic_balls==1 and is_instance_valid(app.ball))
var path=ProjectSettings.globalize_path("res://playtest/artifacts/baseline/merge_report.json")
var file=FileAccess.open(path,FileAccess.WRITE)
file.store_string(JSON.stringify({"passed":results.size()-failures,"failed":failures,"results":results,"first_run_trace":first_run}," "))
file.close()
app.queue_free()
await process_frame
quit(1 if failures else 0)
@@ -0,0 +1 @@
uid://mumonx8gdgce
@@ -0,0 +1,188 @@
extends SceneTree
const Library = preload("res://playtest/baseline/scripts/asset_library.gd")
var lib = Library.new()
var arena: Node3D
var results: Array = []
var failures := 0
func _initialize() -> void:
call_deferred("run")
func vec(v: Vector3) -> Array:
return [snappedf(v.x,.000001),snappedf(v.y,.000001),snappedf(v.z,.000001)]
func clear_arena() -> void:
if is_instance_valid(arena):
root.remove_child(arena)
arena.queue_free()
arena=Node3D.new()
root.add_child(arena)
await physics_frame
await physics_frame
func record(name: String, passed: bool, detail: Dictionary) -> void:
results.append({"name":name,"passed":passed,"detail":detail})
if not passed:failures+=1
print(("PASS " if passed else "FAIL ")+name+" "+JSON.stringify(detail))
func run_path(kind: String, rotation_step: int, branch: int, lower: bool, connected := false) -> void:
await clear_arena()
var basis:=Basis(Vector3.UP,-rotation_step*PI/2)
arena.add_child(lib.create_piece(kind,Vector3.ZERO,rotation_step))
var sphere=lib.create_ball()
sphere.freeze=true
var descending: bool=not lower and kind in ["gentle","steep"]
var t:=.80 if descending else .05
var direction: Vector3=lib.path_tangent(kind,0,branch,lower)
var start: Vector3
var target: Vector3
var exit_direction: Vector3
if lower:
var guide: Dictionary=lib.lower_passage_spec(kind)
arena.add_child(lib.create_box(Vector3(4,.1,4),Vector3(0,float(guide.floor_y)-.05,0),Color.GRAY))
start=lib.path_point(kind,0,branch,true)-direction*.35+Vector3.UP*.015
start.y=float(guide.center_height)+.015
target=lib.path_point(kind,1,branch,true)
target.y=float(guide.center_height)
exit_direction=lib.path_tangent(kind,1,branch,true)
else:
start=lib.ball_on_surface(kind,t,branch)
target=lib.ball_on_surface(kind,0 if descending else 1,branch)
exit_direction=-lib.path_tangent(kind,0,branch) if descending else lib.path_tangent(kind,1,branch)
if connected:
for local_center in lib.y_connectors():arena.add_child(lib.create_piece("straight",basis*local_center,rotation_step))
start=lib.path_point(kind,0,branch)+Vector3(-.65,-float(lib.catalog[kind].grooveRadius)+sphere.radius+.018,0)
target=lib.path_point(kind,1,branch)+Vector3(.85,-float(lib.catalog[kind].grooveRadius)+sphere.radius,0)
direction=Vector3.RIGHT
arena.add_child(sphere)
sphere.position=basis*start
await physics_frame
sphere.freeze=false
var initial_speed: float=1.6 if connected else 1.2
sphere.linear_velocity=Vector3.ZERO if descending else basis*direction*initial_speed
sphere.angular_velocity=Vector3.UP.cross(sphere.linear_velocity)/sphere.radius
var closest:=100.0
var reached:=false
var contact_frames:=0
var highest_speed:=0.0
var trace: Array=[]
var time_at_exit:=-1.0
for frame in range(720):
await physics_frame
var p: Vector3=basis.inverse()*sphere.position
var delta_to_goal:=p-target
var axial:=delta_to_goal.dot(exit_direction)
var lateral:=(delta_to_goal-exit_direction*axial).length()
closest=minf(closest,delta_to_goal.length())
highest_speed=maxf(highest_speed,sphere.linear_velocity.length())
if sphere.contact_count>0:contact_frames+=1
if frame%12==0:trace.append({"t":frame/120.0,"p":vec(p),"v":vec(basis.inverse()*sphere.linear_velocity)})
if axial>.04 and lateral<.22:
reached=true
time_at_exit=frame/120.0
break
if p.y < -2:break
var path_name:="connected" if connected else ("lower" if lower else "upper")
record("%s_%s_r%d_b%d" % [path_name,kind,rotation_step*90,branch],reached and contact_frames>0,
{"reached_exit":reached,"time":time_at_exit,"initial_speed":0.0 if descending else initial_speed,"closest_m":closest,"contact_frames":contact_frames,"max_speed":highest_speed,"final":vec(basis.inverse()*sphere.position),"trace":trace})
func run() -> void:
Engine.physics_ticks_per_second=120
await clear_arena()
var falling=lib.create_ball()
falling.drag_enabled=false
falling.rolling_enabled=false
arena.add_child(falling)
falling.position=Vector3(0,10,0)
await physics_frame
var start_y: float=falling.position.y
var start_v: float=falling.linear_velocity.y
for i in range(120):await physics_frame
var expected_drop: float=-start_v+4.905
var observed_drop: float=start_y-falling.position.y
record("vacuum_freefall_1s",absf((falling.linear_velocity.y-start_v)+9.81)<.02 and absf(observed_drop-expected_drop)<.05,
{"initial_velocity":start_v,"velocity_delta":falling.linear_velocity.y-start_v,"distance":observed_drop,"analytic_distance":expected_drop,"position_error":absf(observed_drop-expected_drop)})
await clear_arena()
arena.add_child(lib.create_piece("straight"))
var resting=lib.create_ball()
arena.add_child(resting)
resting.position=Vector3(0,1.8,0)
for i in range(300):await physics_frame
record("sphere_groove_rest",absf(resting.position.y-(1.0-float(lib.catalog["straight"].grooveRadius)+resting.radius))<.035 and resting.linear_velocity.length()<.1,
{"position":vec(resting.position),"speed":resting.linear_velocity.length(),"contacts":resting.contact_count})
# An independent analytic benchmark: sphere rolling on a 30 degree plane.
await clear_arena()
var plane=lib.create_box(Vector3(20,.2,4),Vector3(0,-.1,0),Color.GRAY)
plane.rotation.z=-PI/6
arena.add_child(plane)
var ramp_ball=lib.create_ball()
ramp_ball.drag_enabled=false
ramp_ball.rolling_enabled=false
arena.add_child(ramp_ball)
var normal: Vector3=plane.basis*Vector3.UP
var downhill: Vector3=plane.basis*Vector3.RIGHT
ramp_ball.position=plane.transform*Vector3(0,.1,0)+normal*(ramp_ball.radius+.005)
for i in range(30):await physics_frame
var first_velocity: float=ramp_ball.linear_velocity.dot(downhill)
for i in range(60):await physics_frame
var acceleration: float=(ramp_ball.linear_velocity.dot(downhill)-first_velocity)/.5
var slip: float=absf(ramp_ball.linear_velocity.dot(downhill)-ramp_ball.angular_velocity.length()*ramp_ball.radius)
record("solid_sphere_30_degree_plane",absf(acceleration-3.503571)<.09 and slip<.06,{"acceleration":acceleration,"analytic_acceleration":3.503571,"rolling_slip":slip})
var horizontal_speeds: Array=[]
for enabled in [false,true]:
await clear_arena()
arena.add_child(lib.create_box(Vector3(30,.2,4),Vector3(0,-.1,0),Color.GRAY))
var rolling_ball=lib.create_ball()
rolling_ball.drag_enabled=false
rolling_ball.rolling_enabled=enabled
arena.add_child(rolling_ball)
rolling_ball.position=Vector3(0,rolling_ball.radius+.001,0)
rolling_ball.linear_velocity=Vector3(2,0,0)
rolling_ball.angular_velocity=Vector3(0,0,-2/rolling_ball.radius)
for i in range(240):await physics_frame
horizontal_speeds.append(rolling_ball.linear_velocity.length())
record("rolling_resistance_dissipates",absf(horizontal_speeds[0]-2)<.05 and horizontal_speeds[1]<horizontal_speeds[0]-.15,{"disabled_enabled_speeds":horizontal_speeds})
await clear_arena()
var left=lib.create_ball()
var right=lib.create_ball()
for sphere in [left,right]:
sphere.gravity_scale=0
sphere.drag_enabled=false
sphere.rolling_enabled=false
arena.add_child(sphere)
left.position=Vector3(-1,2,0);right.position=Vector3(1,2,0)
left.linear_velocity=Vector3.RIGHT;right.linear_velocity=Vector3.LEFT
for i in range(150):await physics_frame
var momentum_error: float=(left.linear_velocity+right.linear_velocity).length()
record("ball_to_ball_collision_enabled",left.linear_velocity.x<-.02 and right.linear_velocity.x>.02 and momentum_error<.02,{"left_velocity":vec(left.linear_velocity),"right_velocity":vec(right.linear_velocity),"normalized_momentum_error":momentum_error})
for kind in ["straight","turn_cw","turn_ccw","gentle","steep","y_merge"]:
for q in range(4):
for branch in range(2 if kind=="y_merge" else 1):
await run_path(kind,q,branch,false)
await run_path(kind,q,branch,true)
for q in range(4):
for branch in range(2):await run_path("y_merge",q,branch,false,true)
# Air response independently of contacts; compare actual simulated velocities.
var air_velocities: Array=[]
for mass_factor in [1.0,10.0]:
await clear_arena()
var sphere=lib.create_ball()
sphere.gravity_scale=0
sphere.mass*=mass_factor
sphere.wind_velocity=Vector3(20,0,0)
arena.add_child(sphere)
sphere.position=Vector3(0,5,0)
for i in range(60):await physics_frame
air_velocities.append(sphere.linear_velocity.x)
var ratio: float=air_velocities[0]/maxf(air_velocities[1],.000001)
record("wind_mass_response",absf(ratio-10)<.15,{"speeds":air_velocities,"ratio":ratio})
var output={"engine":Engine.get_version_info().string,"physics_engine":ProjectSettings.get_setting("physics/3d/physics_engine"),"ticks_per_second":120,"passed":results.size()-failures,"failed":failures,"results":results}
var path: String=ProjectSettings.globalize_path("res://playtest/artifacts/baseline/physics_report.json")
var file:=FileAccess.open(path,FileAccess.WRITE)
file.store_string(JSON.stringify(output," "))
file.close()
print("PHYSICS_REPORT "+path+" failures="+str(failures))
if is_instance_valid(arena):arena.queue_free()
await process_frame
quit(1 if failures else 0)
@@ -0,0 +1 @@
uid://byeccpbcfaoj3
@@ -0,0 +1,89 @@
extends SceneTree
var results: Array=[]
var failed:=0
func _initialize() -> void:
call_deferred("run")
func check(name: String, passed: bool, detail: Dictionary={}) -> void:
results.append({"name":name,"passed":passed,"detail":detail})
if not passed:failed+=1
print(("PASS " if passed else "FAIL ")+name+" "+JSON.stringify(detail))
func run() -> void:
var app=load("res://playtest/baseline/scenes/main.tscn").instantiate()
root.add_child(app)
await physics_frame
check("one_iron_ball_ready",is_instance_valid(app.ball) and app.ball.freeze and is_equal_approx(app.ball.radius,.3),{"mass_kg":app.ball.mass,"radius_m":app.ball.radius})
app.start_button.pressed.emit()
check("release_button",app.started and not app.ball.freeze)
for i in range(1800):
await physics_frame
if app.status.begins_with("成功") or app.status.begins_with("已离开"):break
check("default_course_reaches_hole",app.status.begins_with("成功"),{"status":app.status,"time":app.elapsed,"position":[app.ball.position.x,app.ball.position.y,app.ball.position.z],"max_speed":app.max_speed})
app.reset_ball()
await physics_frame
check("retry_clears_state",not app.started and app.ball.freeze and app.trail_points.is_empty() and app.elapsed==0)
check("scenario_specific_quotas",app.quota("steep")==0 and app.quota("straight")==6)
app.choose_kind("steep")
check("reject_unavailable_type",app.selected_kind!="steep")
var click:=InputEventMouseButton.new()
click.button_index=MOUSE_BUTTON_LEFT
click.pressed=true
click.position=app.camera.unproject_position(Vector3(0,1.3,.5))
app._unhandled_input(click)
check("ray_select_visible_tile",app.selected_index==app.find_cell(Vector2i(0,0)) and is_equal_approx(app.placement_height,.5))
app.build_preset(1)
await physics_frame
for kind in app.IDS:
app.choose_kind(kind)
await physics_frame
check("library_"+kind,app.records.size()==1 and app.records[0].kind==kind and app.pieces.size()==1)
for i in range(4):app.rotate_selected()
check("rotation_cycle_"+kind,app.preview_quarter==0 and app.records[0].quarter==0)
check("y_has_declared_four_cell_footprint",app.lib.footprint("y_merge")==Vector2i(2,2) and app.lib.catalog.y_merge.declaredBoundsFits and app.lib.catalog.y_merge.ports.size()==3)
check("y_not_mislabelled_as_steep_exception",not app.warning_label.text.contains("陡坡"))
app.build_preset(3)
await physics_frame
var previous: int=app.records.size()
app.selected_cell=Vector2i(2,0)
app.placement_height=.5
app.choose_kind("turn_cw")
app.place_selected()
check("place_adjacent_tile",app.records.size()==previous+1 and app.find_cell(Vector2i(2,0))>=0)
app.toggle_run()
var locked: int=app.records.size()
app.remove_selected()
check("editing_locked_after_release",app.records.size()==locked)
app.toggle_run()
check("pause_preserves_run_lock",app.paused and app.started and app.ball.freeze)
app.reset_ball()
app.remove_selected()
check("delete_after_retry",app.records.size()==previous)
app.selected_cell=Vector2i(4,4)
app.place_selected()
check("reject_unattached_tile",app.records.size()==previous)
app.selected_cell=Vector2i(0,0)
app.placement_height=.5
app.choose_kind("y_merge")
app.place_selected()
check("reject_y_overlap_with_neighbor",app.records.size()==previous and app.records[app.find_cell(Vector2i(0,0))].kind=="straight" and app.status.contains("重叠"))
app.selected_cell=Vector2i(-1,1)
app.place_selected()
var y_index: int=app.find_cell(Vector2i(-1,1))
var all_cells_match: bool=y_index>=0
for cell in [Vector2i(-1,1),Vector2i(0,1),Vector2i(-1,2),Vector2i(0,2)]:all_cells_match=all_cells_match and app.find_cell(cell)==y_index
check("y_reserves_four_cells",app.records.size()==previous+1 and all_cells_match)
var model_center: Vector3=app.pieces[y_index].position
for i in range(4):app.rotate_selected()
check("y_rotates_about_fixed_center",app.pieces[y_index].position.is_equal_approx(model_center) and app.preview_quarter==0)
app.choose_kind("straight")
app.place_selected()
check("replace_y_releases_extra_cells",app.find_cell(Vector2i(-1,1))==y_index and app.find_cell(Vector2i(0,2))==-1)
var path=ProjectSettings.globalize_path("res://playtest/artifacts/baseline/playtest_report.json")
var out=FileAccess.open(path,FileAccess.WRITE)
out.store_string(JSON.stringify({"passed":results.size()-failed,"failed":failed,"results":results}," "))
out.close()
app.queue_free()
await process_frame
quit(1 if failed else 0)
@@ -0,0 +1 @@
uid://ddf8i08g3bf4k
+154
View File
@@ -0,0 +1,154 @@
[
{
"id": "gravity_course",
"name": "连续轨道",
"quotas": {
"straight": 6,
"turn_cw": 1,
"turn_ccw": 1,
"gentle": 2,
"steep": 0,
"y_merge": 0
}
},
{
"id": "part_test",
"name": "单件试跑",
"quotas": {
"straight": 1,
"turn_cw": 1,
"turn_ccw": 1,
"gentle": 1,
"steep": 1,
"y_merge": 1
}
},
{
"id": "underpass_test",
"name": "底部通孔",
"quotas": {
"straight": 1,
"turn_cw": 1,
"turn_ccw": 1,
"gentle": 1,
"steep": 1,
"y_merge": 1
}
},
{
"id": "construction_lab",
"name": "自由搭建",
"quotas": {
"straight": 12,
"turn_cw": 3,
"turn_ccw": 3,
"gentle": 3,
"steep": 2,
"y_merge": 2
}
},
{
"id": "dual_merge",
"name": "双铁球汇流",
"quotas": {
"straight": 5,
"turn_cw": 0,
"turn_ccw": 0,
"gentle": 2,
"steep": 0,
"y_merge": 1
},
"layout": [
{
"kind": "y_merge",
"position": [
0,
1,
0
],
"quarter": 0
},
{
"kind": "straight",
"position": [
-1,
1,
0
],
"quarter": 0
},
{
"kind": "straight",
"position": [
-1,
1,
1
],
"quarter": 0
},
{
"kind": "straight",
"position": [
-2,
1,
0
],
"quarter": 0
},
{
"kind": "gentle",
"position": [
-3,
1.5,
0
],
"quarter": 2
},
{
"kind": "gentle",
"position": [
-2,
1.5,
1
],
"quarter": 2
},
{
"kind": "straight",
"position": [
2,
1,
1
],
"quarter": 0
},
{
"kind": "straight",
"position": [
3,
1,
1
],
"quarter": 0
}
],
"spawns": [
{
"ballId": "iron_A",
"recordIndex": 4,
"pathT": 0.82
},
{
"ballId": "iron_B",
"recordIndex": 5,
"pathT": 0.82
}
],
"goal": [
4.0,
1.68,
1
],
"notes": "Two equal-height iron balls release simultaneously from rest. Branch A has one extra straight tile. The merged outlet remains level to approach the close-fitting 0.32m-radius hole without the former final downhill acceleration."
}
]
+4
View File
@@ -0,0 +1,4 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://playtest/baseline/scripts/playtest.gd" id="1"]
[node name="IntoHolePlaytest" type="Node3D"]
script = ExtResource("1")
+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