- 加入 Godot 基础试玩、画风展示和通孔验证场景 - 支持自由放球、多层叠放、墙壁、锥口球洞及固定 +5 m/s 定向加速方块 - 保存 Blender 源资产、模型导出、资源制作脚本和关卡编辑存档逻辑 - 按七类目录归档工程,集中 zsh 启动入口并补充 AGENTS.md 文件索引 - 同步设计规则、依赖锁定、验证报告和目录迁移记录 验证:目录迁移后的资源导入与四个场景加载通过;本次提交前检查暂存内容,未重复运行整套物理测试。
908 lines
42 KiB
GDScript
908 lines
42 KiB
GDScript
extends Node3D
|
||
|
||
const Library = preload("res://runtime/asset_library.gd")
|
||
const LevelData = preload("res://designer/scripts/level_data.gd")
|
||
const Placement = preload("res://designer/scripts/placement.gd")
|
||
const Booster = preload("res://assets/blocks/directional_boost/behavior.gd")
|
||
const IDS = ["straight", "turn_cw", "turn_ccw", "gentle", "steep", "y_merge"]
|
||
const TITLES = ["直行", "右转", "左转", "缓坡 ½", "陡坡 1", "Y 汇流"]
|
||
const INK = Color("343143")
|
||
const PAPER = Color("fff4d9")
|
||
const ACCENT = Color("bf6050")
|
||
const SAVE_DIR = "res://designer/drafts"
|
||
const EXAMPLE_LEVELS = ["res://playtest/showcase/data/meadowexample.json", "res://playtest/underpass/data/underpass_validation.json"]
|
||
var editor_mode := false
|
||
var lib = Library.new()
|
||
var codec = LevelData.new(lib,IDS)
|
||
var placement = Placement.new(lib)
|
||
var entity_registry: Dictionary=JSON.parse_string(FileAccess.get_file_as_string("res://assets/collections/storybook/entities.json"))
|
||
var records: Array = []
|
||
var spawn_specs: Array = []
|
||
var goal_position := Vector3.ZERO # Compatibility: first goal position.
|
||
var goals: Array=[]
|
||
var pieces: Array = []
|
||
var balls: Array = []
|
||
var tags: Array = []
|
||
var previous: Array = []
|
||
var entered := {}
|
||
var lost := {}
|
||
var events: Array = []
|
||
var samples: Array = []
|
||
var release_ticks: Array = []
|
||
var pause_states: Array = []
|
||
var visited := {}
|
||
var contact_visited := {}
|
||
var elapsed := 0.0
|
||
var started := false
|
||
var paused := false
|
||
var status := "准备好,让两颗铁球一起出发。"
|
||
var world := Node3D.new()
|
||
var actors := Node3D.new()
|
||
var camera := Camera3D.new()
|
||
var grid := Node3D.new()
|
||
var selection := Node3D.new()
|
||
var cursor := Vector3.ZERO # Bottom-face placement coordinates, ground Y = 0.
|
||
var block_mode := "place"
|
||
var last_placed_id := ""
|
||
var mode_buttons: Dictionary={}
|
||
var place_button: Button
|
||
var apply_button: Button
|
||
var delete_button: Button
|
||
var boost_controls: VBoxContainer
|
||
var ground_view := MeshInstance3D.new()
|
||
var ground_holes: Array=[]
|
||
var quarter := 0
|
||
var kind := "straight"
|
||
var selected_id := ""
|
||
var serial := 0
|
||
var undo_stack: Array = []
|
||
var redo_stack: Array = []
|
||
var yaw := .72
|
||
var pitch := .78
|
||
var target := Vector3(1.5,1,0)
|
||
var orbiting := false
|
||
var panning := false
|
||
var camera_size := 12.0
|
||
var name_field: LineEdit
|
||
var file_list: OptionButton
|
||
var status_label: Label
|
||
var count_label: Label
|
||
var detail_label: Label
|
||
var notice_label: Label
|
||
var run_button: Button
|
||
var position_fields: Array = []
|
||
var ball_list: OptionButton
|
||
var palette_box: GridContainer
|
||
var block_controls: VBoxContainer
|
||
var ball_controls: VBoxContainer
|
||
var add_ball_button: Button
|
||
var sidebar_scroll: ScrollContainer
|
||
var category_buttons: Dictionary={}
|
||
var category := "chutes"
|
||
var ball_position_fields: Array=[]
|
||
var ball_cursor := Vector3(0,2,0)
|
||
var selected_ball_id := ""
|
||
var ball_marker := Node3D.new()
|
||
var ball_pick_mode: OptionButton
|
||
var ball_pick_hint: Label
|
||
var move_ball_button: Button
|
||
var editable: Array = []
|
||
var font := SystemFont.new()
|
||
var capture_path := ""
|
||
var capture_count := -1
|
||
var autorun := false
|
||
var syncing := false
|
||
|
||
func _ready() -> void:
|
||
get_window().title="IntoHole · 关卡工坊" if editor_mode else "IntoHole · 林间汇流"
|
||
font.font_names=PackedStringArray(["PingFang SC","Noto Sans CJK SC","Arial"])
|
||
add_child(world);add_child(actors);add_child(grid);add_child(selection);add_child(ball_marker)
|
||
setup_environment()
|
||
setup_ui()
|
||
initialize_level()
|
||
for arg in OS.get_cmdline_user_args():
|
||
if arg.begins_with("--capture="):capture_path=arg.trim_prefix("--capture=");capture_count=15
|
||
if arg=="--autorun":autorun=true
|
||
if autorun:toggle_run()
|
||
|
||
func initialize_level() -> void:
|
||
pass # Each standalone scene owns its startup layout.
|
||
|
||
func material(color: Color) -> StandardMaterial3D:
|
||
var m:=StandardMaterial3D.new();m.albedo_color=color;m.roughness=.92
|
||
return m
|
||
|
||
func box(size: Vector3, at: Vector3, color: Color, parent: Node3D) -> Node3D:
|
||
var object: Node3D=lib.create_box(size,at,color,false)
|
||
parent.add_child(object)
|
||
return object
|
||
|
||
func setup_environment() -> void:
|
||
var env:=Environment.new()
|
||
env.background_mode=Environment.BG_COLOR;env.background_color=Color("e8e1bd")
|
||
env.ambient_light_source=Environment.AMBIENT_SOURCE_COLOR
|
||
env.ambient_light_color=Color.WHITE;env.ambient_light_energy=.3
|
||
env.tonemap_mode=Environment.TONE_MAPPER_ACES;env.tonemap_exposure=.85
|
||
var we:=WorldEnvironment.new();we.environment=env;add_child(we)
|
||
var light:=DirectionalLight3D.new();light.rotation_degrees=Vector3(-58,-28,0)
|
||
light.light_color=Color.WHITE;light.light_energy=.35;light.shadow_enabled=true
|
||
light.directional_shadow_max_distance=65;add_child(light)
|
||
add_child(camera);camera.projection=Camera3D.PROJECTION_ORTHOGONAL
|
||
camera.near=.05;camera.far=250;camera.current=true;camera.h_offset=-1.9
|
||
update_camera()
|
||
ground_view.name="GroundY0";add_child(ground_view);refresh_ground()
|
||
# Authored low-poly scenery stays outside the working track. No invisible collisions.
|
||
for p in [Vector3(-5,0,-4),Vector3(-3,0,-4.5),Vector3(2,0,-4.5),Vector3(7,0,-3),Vector3(9,0,3.5),Vector3(-5,0,4.2)]:
|
||
make_tree(p)
|
||
for p in [Vector3(-4,.18,-3),Vector3(4,.18,-3.5),Vector3(8,.18,3)]:
|
||
var rock:=MeshInstance3D.new();var mesh:=SphereMesh.new()
|
||
mesh.radial_segments=7;mesh.rings=3;mesh.radius=.35;mesh.height=.45
|
||
rock.mesh=mesh;rock.material_override=material(Color("93937a"));rock.position=p;add_child(rock)
|
||
# Small ground marks make the large quiet color area feel drawn.
|
||
var rng:=RandomNumberGenerator.new();rng.seed=42
|
||
for i in range(150):
|
||
var at:=Vector3(rng.randf_range(-7,11),.002,rng.randf_range(-6,6))
|
||
box(Vector3(.035,.003,.09),at,Color("a3ad7c"),self)
|
||
|
||
func make_tree(at: Vector3) -> void:
|
||
var trunk:=box(Vector3(.18,.65,.18),at+Vector3.UP*.32,Color("73553f"),self)
|
||
for i in range(3):
|
||
var cone:=CylinderMesh.new();cone.top_radius=0;cone.bottom_radius=.65-i*.13
|
||
cone.height=.95;cone.radial_segments=7
|
||
var view:=MeshInstance3D.new();view.mesh=cone
|
||
view.material_override=material(Color("748657") if i%2==0 else Color("8c9b64"))
|
||
view.position=at+Vector3.UP*(.9+i*.46);add_child(view)
|
||
var rim:=CylinderMesh.new();rim.top_radius=0;rim.bottom_radius=cone.bottom_radius+.012
|
||
rim.height=.035;rim.radial_segments=7
|
||
var outline:=MeshInstance3D.new();outline.mesh=rim;outline.material_override=material(INK)
|
||
outline.position=view.position-Vector3.UP*.47;add_child(outline)
|
||
trunk.name="DecorativeTree"
|
||
|
||
func style(color: Color, border:=INK, radius:=12) -> StyleBoxFlat:
|
||
var s:=StyleBoxFlat.new();s.bg_color=color;s.border_color=border
|
||
s.set_border_width_all(2);s.set_corner_radius_all(radius)
|
||
s.content_margin_left=12;s.content_margin_right=12;s.content_margin_top=9;s.content_margin_bottom=9
|
||
return s
|
||
|
||
func label(text: String, size:=16, color:=INK) -> Label:
|
||
var l:=Label.new();l.text=text;l.add_theme_font_override("font",font)
|
||
l.add_theme_font_size_override("font_size",size);l.add_theme_color_override("font_color",color)
|
||
return l
|
||
|
||
func button(text: String, action: Callable, primary:=false, lock:=false) -> Button:
|
||
var b:=Button.new();b.text=text;b.custom_minimum_size.y=36
|
||
b.add_theme_font_override("font",font);b.add_theme_font_size_override("font_size",15)
|
||
b.add_theme_stylebox_override("normal",style(ACCENT if primary else PAPER))
|
||
b.add_theme_stylebox_override("hover",style(Color("f0d7a6")))
|
||
b.add_theme_stylebox_override("pressed",style(Color("c3cd98")))
|
||
b.add_theme_color_override("font_color",Color.WHITE if primary else INK)
|
||
b.add_theme_color_override("font_hover_color",INK);b.add_theme_color_override("font_pressed_color",INK)
|
||
b.pressed.connect(action)
|
||
if lock:editable.append(b)
|
||
return b
|
||
|
||
func row(parent: Node) -> HBoxContainer:
|
||
var r:=HBoxContainer.new();r.add_theme_constant_override("separation",6);parent.add_child(r);return r
|
||
|
||
func setup_ui() -> void:
|
||
var layer:=CanvasLayer.new();add_child(layer)
|
||
var panel:=PanelContainer.new();panel.position=Vector2(20,20);panel.size=Vector2(294,860)
|
||
panel.add_theme_stylebox_override("panel",style(PAPER));layer.add_child(panel)
|
||
var scroll:=ScrollContainer.new();sidebar_scroll=scroll;scroll.custom_minimum_size=Vector2(266,830);panel.add_child(scroll)
|
||
scroll.horizontal_scroll_mode=ScrollContainer.SCROLL_MODE_DISABLED
|
||
var col:=VBoxContainer.new();col.size_flags_horizontal=Control.SIZE_EXPAND_FILL
|
||
col.add_theme_constant_override("separation",10);scroll.add_child(col)
|
||
col.add_child(label("INTO / HOLE",28))
|
||
col.add_child(label("关卡工坊" if editor_mode else "01 林间汇流",20))
|
||
col.add_child(label("无限积木 · 自由编排" if editor_mode else "六种滑槽 · 两颗铁球 · 一个洞",14,Color("7a7366")))
|
||
count_label=label("",18);col.add_child(count_label)
|
||
run_button=button("▶ 同时释放",toggle_run,true);col.add_child(run_button)
|
||
col.add_child(button("↺ 重试 / 返回编辑" if editor_mode else "↺ 重新开始",reset_simulation))
|
||
if editor_mode:build_editor_ui(col)
|
||
else:
|
||
col.add_child(label("沿途积木",17))
|
||
for i in range(IDS.size()):col.add_child(label("%02d %s" % [i+1,TITLES[i]],16))
|
||
col.add_child(label("空格 释放 / 暂停\nT 重试\n右键拖动 旋转视角\n中键拖动 平移\n滚轮 缩放\nF 回到全景",14,Color("7a7366")))
|
||
status_label=label("",15);status_label.autowrap_mode=TextServer.AUTOWRAP_WORD_SMART
|
||
status_label.custom_minimum_size.x=255;col.add_child(status_label)
|
||
var footer:=PanelContainer.new();footer.position=Vector2(340,824);footer.size=Vector2(660,52)
|
||
footer.add_theme_stylebox_override("panel",style(PAPER));layer.add_child(footer)
|
||
notice_label=label("林间实验场 / 滑槽积木 × 手绘色彩",16)
|
||
notice_label.autowrap_mode=TextServer.AUTOWRAP_WORD_SMART;footer.add_child(notice_label)
|
||
|
||
func build_editor_ui(col: VBoxContainer) -> void:
|
||
var categories:=GridContainer.new();categories.columns=2;categories.add_theme_constant_override("h_separation",6);categories.add_theme_constant_override("v_separation",6);col.add_child(categories)
|
||
var group:=ButtonGroup.new()
|
||
for entry in [["chutes","滑槽"],["balls","小球"],["interactive","交互方块"],["nonInteractive","非交互方块"]]:
|
||
var id: String=entry[0]
|
||
var tab:=button(entry[1],func():select_category(id),false,true)
|
||
tab.toggle_mode=true;tab.button_group=group;tab.button_pressed=id==category
|
||
tab.add_theme_font_size_override("font_size",14);tab.custom_minimum_size.x=126
|
||
categories.add_child(tab);category_buttons[id]=tab
|
||
palette_box=GridContainer.new();palette_box.columns=2;col.add_child(palette_box)
|
||
block_controls=VBoxContainer.new();block_controls.add_theme_constant_override("separation",10);col.add_child(block_controls)
|
||
detail_label=label("",14);block_controls.add_child(detail_label)
|
||
boost_controls=VBoxContainer.new();block_controls.add_child(boost_controls)
|
||
boost_controls.add_child(label("固定增速:+%.0f m/s" % Booster.SPEED_GAIN,14))
|
||
var boost_hint:=label("顶面接触一次:先转向,再增速。\n离开后再次接触可重新触发。",13,Color("7a7366"))
|
||
boost_controls.add_child(boost_hint)
|
||
var modes:=row(block_controls)
|
||
var mode_group:=ButtonGroup.new()
|
||
for entry in [["place","放置模式"],["edit","选择 / 移动"]]:
|
||
var mode: String=entry[0]
|
||
var b:=button(entry[1],func():set_block_mode(mode),false,true)
|
||
b.toggle_mode=true;b.button_group=mode_group;b.button_pressed=mode==block_mode
|
||
mode_buttons[mode]=b;modes.add_child(b)
|
||
block_controls.add_child(label("方块底面坐标 · 地面 Y = 0",13,Color("7a7366")))
|
||
var coords:=row(block_controls)
|
||
for i in range(3):
|
||
var field:=SpinBox.new();field.min_value=-10000;field.max_value=10000
|
||
field.step=.5 if i==1 else 1;field.prefix=["X ","Y ","Z "][i]
|
||
field.custom_minimum_size.x=83;field.add_theme_font_size_override("font_size",13)
|
||
var axis:=i
|
||
field.value_changed.connect(func(v):
|
||
if syncing:return
|
||
cursor[axis]=v;refresh_selection())
|
||
coords.add_child(field);position_fields.append(field);editable.append(field)
|
||
var actions:=row(block_controls)
|
||
place_button=button("放置新方块",place_current,false,true);actions.add_child(place_button)
|
||
actions.add_child(button("旋转 R",rotate_current,false,true))
|
||
apply_button=button("应用修改到选中方块",apply_selected,false,true);block_controls.add_child(apply_button)
|
||
actions=row(block_controls);delete_button=button("删除 Del",remove_current,false,true);actions.add_child(delete_button)
|
||
ball_controls=VBoxContainer.new();ball_controls.add_theme_constant_override("separation",10);col.add_child(ball_controls)
|
||
ball_pick_mode=OptionButton.new()
|
||
ball_pick_mode.add_item("贴表面点选")
|
||
ball_pick_mode.add_item("按 Y 高度点选(悬空)")
|
||
ball_controls.add_child(ball_pick_mode);editable.append(ball_pick_mode)
|
||
ball_pick_mode.item_selected.connect(func(_index):refresh_ball_pick_hint())
|
||
ball_pick_hint=label("",13,Color("7a7366"))
|
||
ball_pick_hint.autowrap_mode=TextServer.AUTOWRAP_WORD_SMART;ball_pick_hint.custom_minimum_size.x=255
|
||
ball_controls.add_child(ball_pick_hint);refresh_ball_pick_hint()
|
||
ball_controls.add_child(label("铁球 · 球心坐标",17))
|
||
var ball_coords:=row(ball_controls)
|
||
for i in range(3):
|
||
var field:=SpinBox.new();field.min_value=-10000;field.max_value=10000
|
||
field.step=.01;field.allow_greater=true;field.allow_lesser=true
|
||
field.prefix=["X ","Y ","Z "][i];field.value=ball_cursor[i]
|
||
field.custom_minimum_size.x=83;field.add_theme_font_size_override("font_size",12)
|
||
var axis:=i
|
||
field.value_changed.connect(func(v):
|
||
if syncing:return
|
||
ball_cursor[axis]=v;refresh_ball_marker())
|
||
ball_coords.add_child(field);ball_position_fields.append(field);editable.append(field)
|
||
add_ball_button=button("+ 放置铁球",add_spawn,true,true);ball_controls.add_child(add_ball_button)
|
||
ball_list=OptionButton.new();ball_controls.add_child(ball_list);editable.append(ball_list)
|
||
ball_list.item_selected.connect(select_ball)
|
||
actions=row(ball_controls);move_ball_button=button("移动选中铁球",move_spawn,false,true);actions.add_child(move_ball_button)
|
||
actions.add_child(button("移除铁球",remove_spawn,false,true))
|
||
ball_controls.add_child(label("可悬空;启动后受重力影响。",13,Color("7a7366")))
|
||
actions=row(col);actions.add_child(button("撤销",undo,false,true));actions.add_child(button("重做",redo,false,true))
|
||
col.add_child(label("关卡文件",17))
|
||
name_field=LineEdit.new();name_field.text="my_level";name_field.placeholder_text="关卡名称"
|
||
col.add_child(name_field);editable.append(name_field)
|
||
actions=row(col);actions.add_child(button("保存",save_named,false,true));actions.add_child(button("载入",load_named,false,true))
|
||
file_list=OptionButton.new();col.add_child(file_list);refresh_files();editable.append(file_list)
|
||
file_list.item_selected.connect(func(i):name_field.text=file_list.get_item_text(i))
|
||
col.add_child(button("新建空白",clear_level,false,true))
|
||
col.add_child(label("放置模式:点顶面向上叠放,点侧面拼接
|
||
选择模式:点方块后修改坐标并应用
|
||
铁球 Y 为球心高度
|
||
R 旋转 · Del 删除 · F 全景
|
||
空格试跑,T 回到原布局
|
||
右键旋转 / 中键平移 / 滚轮缩放",13,Color("7a7366")))
|
||
refresh_palette()
|
||
|
||
func kind_name(id: String) -> String:
|
||
if id=="iron_ball":return "铁球"
|
||
if id in IDS:return TITLES[IDS.find(id)]
|
||
for group in entity_registry.values():
|
||
for item in group:
|
||
if item.id==id:return item.name
|
||
return "未选择方块"
|
||
|
||
func kinds_in_category(id: String) -> Array:
|
||
if id=="balls":return ["iron_ball"]
|
||
if id=="chutes":return IDS.duplicate()
|
||
return entity_registry[id].map(func(item):return item.id)
|
||
|
||
func select_category(id: String) -> void:
|
||
if started:return
|
||
category=id
|
||
if id=="balls":
|
||
selected_id=""
|
||
else:
|
||
selected_ball_id=""
|
||
var options:=kinds_in_category(id)
|
||
if kind not in options:kind="" if options.is_empty() else options[0]
|
||
if sidebar_scroll!=null:sidebar_scroll.scroll_vertical=0
|
||
refresh_palette();refresh_selection();refresh_ball_marker()
|
||
|
||
func refresh_palette() -> void:
|
||
clear_children(palette_box)
|
||
var options:=kinds_in_category(category)
|
||
if options.is_empty():palette_box.add_child(label("暂无交互方块 · 待添加",14,Color("7a7366")))
|
||
for id in options:
|
||
var chosen: String=id
|
||
palette_box.add_child(button(kind_name(id)+" ∞",func():
|
||
if started:return
|
||
if category=="balls":refresh_ball_marker()
|
||
else:kind=chosen;refresh_selection(),false,true))
|
||
for id in category_buttons:category_buttons[id].button_pressed=id==category
|
||
if block_controls!=null:block_controls.visible=category!="balls"
|
||
if ball_controls!=null:ball_controls.visible=category=="balls"
|
||
ball_marker.visible=category=="balls"
|
||
|
||
func category_for(id: String) -> String:
|
||
if id in IDS:return "chutes"
|
||
for group in entity_registry:
|
||
if entity_registry[group].any(func(item):return item.id==id):return group
|
||
return "chutes"
|
||
|
||
func encode() -> Dictionary:
|
||
return codec.encode(records,spawn_specs,name_field.text if editor_mode else "林间汇流")
|
||
|
||
func validate_level(data: Variant) -> String:
|
||
return codec.validate(data)
|
||
|
||
func valid_vector(value: Variant) -> bool:
|
||
return codec.valid_vector(value)
|
||
|
||
func apply_data(data: Dictionary) -> void:
|
||
var normalized: Dictionary=codec.normalize(data)
|
||
records=normalized.records;spawn_specs=normalized.balls
|
||
selected_id="";selected_ball_id="";block_mode="place"
|
||
rebuild();reset_simulation();frame_level()
|
||
|
||
func clear_level() -> void:
|
||
if started:return
|
||
remember();records.clear();spawn_specs.clear()
|
||
selected_id="";selected_ball_id="";block_mode="place";cursor=Vector3.ZERO;ball_cursor=Vector3(0,2,0)
|
||
rebuild();reset_simulation();frame_level()
|
||
status="空白关卡:选择方块分类或添加悬空铁球。";refresh_ui()
|
||
|
||
func remember() -> void:
|
||
undo_stack.append(encode());redo_stack.clear()
|
||
if undo_stack.size()>100:undo_stack.pop_front()
|
||
|
||
func undo() -> void:
|
||
if started or undo_stack.is_empty():return
|
||
redo_stack.append(encode());apply_data(undo_stack.pop_back());status="已撤销";refresh_ui()
|
||
|
||
func redo() -> void:
|
||
if started or redo_stack.is_empty():return
|
||
undo_stack.append(encode());apply_data(redo_stack.pop_back());status="已重做";refresh_ui()
|
||
|
||
func index_for(id: String) -> int:
|
||
for i in range(records.size()):
|
||
if records[i].id==id:return i
|
||
return -1
|
||
|
||
func unique_id(prefix: String) -> String:
|
||
serial+=1
|
||
return prefix+"_"+str(Time.get_ticks_usec())+"_"+str(serial)
|
||
|
||
func overlaps(a: Dictionary,b: Dictionary) -> bool:
|
||
return codec.overlaps(a,b)
|
||
|
||
func placement_error(candidate: Dictionary, ignore: String="") -> String:
|
||
# A level author may create disconnected route seeds; occupancy still applies.
|
||
for r in records:
|
||
if r.id!=ignore and overlaps(candidate,r):return "这个位置与已有积木重叠。"
|
||
return ""
|
||
|
||
func place_current() -> void:
|
||
if started or not editor_mode or category=="balls":return
|
||
if kind.is_empty():status="此分类暂无可用方块。";refresh_ui();return
|
||
# Adding never overwrites or moves an existing record, even if it was selected.
|
||
var record: Dictionary=placement.record_at(kind,cursor,quarter,unique_id("piece"))
|
||
var issue:=placement_error(record)
|
||
if not issue.is_empty():status=issue;refresh_ui();return
|
||
remember();records.append(record);last_placed_id=record.id
|
||
cursor=placement.bottom_of(record);selected_id="";selected_ball_id="";block_mode="place"
|
||
rebuild();reset_simulation()
|
||
status="已新增 %s · 底面 Y %.2f;点顶面可继续叠放" % [kind_name(kind),cursor.y];refresh_ui()
|
||
|
||
func set_block_mode(mode: String) -> void:
|
||
if started or not editor_mode:return
|
||
block_mode=mode;selected_id="";selected_ball_id=""
|
||
status="点方块顶面或侧面选择新位置,再放置。" if mode=="place" else "点击要修改的方块,再调整坐标并应用修改。"
|
||
refresh_selection()
|
||
|
||
func select_record(id: String) -> void:
|
||
if started:return
|
||
var index:=index_for(id)
|
||
if index<0:return
|
||
block_mode="edit";selected_ball_id="";selected_id=id
|
||
var record: Dictionary=records[index]
|
||
cursor=placement.bottom_of(record);kind=record.kind;quarter=record.quarter
|
||
category=category_for(kind);refresh_palette();refresh_selection()
|
||
|
||
func apply_selected() -> void:
|
||
if started or not editor_mode:return
|
||
var index:=index_for(selected_id)
|
||
if block_mode!="edit" or index<0:status="先用选择模式选中要修改的方块。";refresh_ui();return
|
||
if kind.is_empty():return
|
||
var candidate: Dictionary=placement.record_at(kind,cursor,quarter,selected_id)
|
||
var issue:=placement_error(candidate,selected_id)
|
||
if not issue.is_empty():status=issue;refresh_ui();return
|
||
remember();records[index]=candidate;cursor=placement.bottom_of(candidate)
|
||
rebuild();reset_simulation();status="已修改选中方块;其他方块保持原位。";refresh_ui()
|
||
|
||
func rotate_current() -> void:
|
||
if started or not editor_mode or category=="balls":return
|
||
var old:=quarter;quarter=(quarter+1)%4
|
||
var idx:=index_for(selected_id) if block_mode=="edit" else -1
|
||
if idx>=0:
|
||
var candidate: Dictionary=records[idx].duplicate();candidate.quarter=quarter
|
||
var issue:=placement_error(candidate,selected_id)
|
||
if not issue.is_empty():quarter=old;status=issue;refresh_ui();return
|
||
remember();records[idx]=candidate;rebuild();reset_simulation()
|
||
refresh_selection()
|
||
|
||
func remove_current() -> void:
|
||
if started or not editor_mode:return
|
||
if not selected_ball_id.is_empty():remove_spawn();return
|
||
var idx:=index_for(selected_id)
|
||
if idx<0:return
|
||
remember();records.remove_at(idx)
|
||
selected_id="";rebuild();reset_simulation();status="方块已移除,铁球坐标保持不变。";refresh_ui()
|
||
|
||
func add_spawn() -> void:
|
||
if started or not editor_mode:return
|
||
remember();selected_ball_id=unique_id("iron");selected_id=""
|
||
spawn_specs.append({"id":selected_ball_id,"ballTypeId":"iron_ball","position":codec.array_from(ball_cursor),"launchDirection":codec.array_from(Vector3.RIGHT)})
|
||
reset_simulation();status="已按球心坐标放置铁球,可悬空。";refresh_ui()
|
||
|
||
func refresh_ball_pick_hint() -> void:
|
||
if ball_pick_hint==null:return
|
||
ball_pick_hint.text="点击场景选位置,再点“放置铁球”。\n滑槽会自动对准槽内。" if ball_pick_mode.selected==0 else "先设置球心 Y,再点击场景选 X/Z,\n最后点“放置铁球”。"
|
||
|
||
func ball_position_is_clear(at: Vector3) -> bool:
|
||
var shape:=SphereShape3D.new();shape.radius=float(lib.catalog.iron_ball.radius)
|
||
var query:=PhysicsShapeQueryParameters3D.new();query.shape=shape
|
||
query.transform=Transform3D(Basis.IDENTITY,at);query.collision_mask=1;query.margin=0
|
||
return get_world_3d().direct_space_state.intersect_shape(query).is_empty()
|
||
|
||
func ball_position_on_chute(hit: Dictionary) -> Variant:
|
||
var node: Node=hit.collider
|
||
while node!=null and not node.has_meta("record_id"):node=node.get_parent()
|
||
if node==null:return null
|
||
var record: Dictionary=records[index_for(node.get_meta("record_id"))]
|
||
if record.kind not in IDS:return null
|
||
var transform:=Transform3D(Basis(Vector3.UP,-int(record.quarter)*PI/2),lib.record_center(record))
|
||
var local: Vector3=transform.affine_inverse()*Vector3(hit.position)
|
||
var point:=Vector2(local.x,local.z)
|
||
var paths: Array=lib.catalog[record.kind].upperPaths
|
||
var distance:=INF;var best_t:=0.0;var best_branch:=0
|
||
for branch in range(paths.size()):
|
||
var path: Array=paths[branch]
|
||
for i in range(path.size()-1):
|
||
var a:=Vector2(path[i][0],path[i][2]);var b:=Vector2(path[i+1][0],path[i+1][2])
|
||
var segment:=b-a
|
||
var ratio:=clampf((point-a).dot(segment)/maxf(segment.length_squared(),.000001),0,1)
|
||
var d:=point.distance_squared_to(a+segment*ratio)
|
||
if d<distance:distance=d;best_t=(i+ratio)/(path.size()-1);best_branch=branch
|
||
var candidate: Vector3=(transform*lib.ball_on_surface(record.kind,best_t,best_branch)).snapped(Vector3.ONE*.01)
|
||
if ball_position_is_clear(candidate):return candidate
|
||
# At a seam a nearby wall can obstruct the ideal groove point. Find the
|
||
# closest clear point on this same asset without moving or altering any block.
|
||
var best_distance:=INF
|
||
for branch in range(paths.size()):
|
||
for i in range(paths[branch].size()):
|
||
var t: float=float(i)/(paths[branch].size()-1)
|
||
var alternative: Vector3=(transform*lib.ball_on_surface(record.kind,t,branch)).snapped(Vector3.ONE*.01)
|
||
var d: float=alternative.distance_squared_to(Vector3(hit.position))
|
||
if d<best_distance and ball_position_is_clear(alternative):candidate=alternative;best_distance=d
|
||
return candidate
|
||
|
||
func pick_ball_position(origin: Vector3,direction: Vector3,hit: Dictionary) -> void:
|
||
var candidate: Variant=null
|
||
var radius: float=lib.catalog.iron_ball.radius
|
||
if ball_pick_mode.selected==1:
|
||
candidate=Plane(Vector3.UP,ball_cursor.y).intersects_ray(origin,direction)
|
||
elif not hit.is_empty():
|
||
candidate=ball_position_on_chute(hit)
|
||
if candidate==null:
|
||
var normal: Vector3=hit.normal
|
||
if normal.length_squared()<.001:return
|
||
candidate=hit.position+normal.normalized()*(radius+.018)
|
||
else:
|
||
var ground=Plane(Vector3.UP,0).intersects_ray(origin,direction)
|
||
if ground!=null:candidate=ground+Vector3.UP*(radius+.018)
|
||
if candidate==null:return
|
||
var rounded: Vector3=Vector3(candidate).snapped(Vector3.ONE*.01)
|
||
if not ball_position_is_clear(rounded):
|
||
status="这里容不下铁球;请换个位置或提高球心 Y。";refresh_ui();return
|
||
ball_cursor=rounded
|
||
refresh_ball_marker()
|
||
status="已选球心 (%.2f, %.2f, %.2f) · 点放置新增,或移动选中铁球" % [ball_cursor.x,ball_cursor.y,ball_cursor.z]
|
||
refresh_ui()
|
||
|
||
func select_ball(index: int) -> void:
|
||
if started or index<0 or index>=spawn_specs.size():return
|
||
selected_ball_id=spawn_specs[index].id;selected_id=""
|
||
category="balls";refresh_palette()
|
||
if sidebar_scroll!=null:sidebar_scroll.scroll_vertical=0
|
||
ball_cursor=lib.vector(spawn_specs[index].position)
|
||
syncing=true
|
||
for i in range(ball_position_fields.size()):ball_position_fields[i].value=ball_cursor[i]
|
||
syncing=false
|
||
refresh_selection();refresh_ball_marker()
|
||
|
||
func ball_index() -> int:
|
||
for i in range(spawn_specs.size()):
|
||
if spawn_specs[i].id==selected_ball_id:return i
|
||
return -1
|
||
|
||
func move_spawn() -> void:
|
||
if started:return
|
||
var index:=ball_index()
|
||
if index<0:status="先选择一颗铁球。";refresh_ui();return
|
||
remember();spawn_specs[index].position=codec.array_from(ball_cursor)
|
||
reset_simulation();status="已移动铁球球心。";refresh_ui()
|
||
|
||
func refresh_ball_marker() -> void:
|
||
clear_children(ball_marker)
|
||
if not editor_mode or started or category!="balls":return
|
||
syncing=true
|
||
for i in range(ball_position_fields.size()):ball_position_fields[i].value=ball_cursor[i]
|
||
syncing=false
|
||
var index:=ball_index()
|
||
if index>=0 and lib.vector(spawn_specs[index].position).is_equal_approx(ball_cursor):return
|
||
var preview: Node3D=load(lib.catalog.iron_ball.path).instantiate()
|
||
preview.position=ball_cursor;ball_marker.add_child(preview);ghost(preview)
|
||
if absf(ball_cursor.y)>.02:
|
||
box(Vector3(.012,absf(ball_cursor.y),.012),Vector3(ball_cursor.x,ball_cursor.y*.5,ball_cursor.z),Color("649e82"),ball_marker)
|
||
box(Vector3(.15,.008,.15),Vector3(ball_cursor.x,.008,ball_cursor.z),Color("649e82"),ball_marker)
|
||
|
||
func remove_spawn() -> void:
|
||
if started:return
|
||
var index:=ball_index()
|
||
if index<0:return
|
||
remember();spawn_specs.remove_at(index);selected_ball_id="";reset_simulation()
|
||
|
||
func place_goal() -> void:
|
||
if started or not editor_mode:return
|
||
kind="goal_hole";category="nonInteractive";refresh_palette();place_current()
|
||
|
||
func clear_children(node: Node) -> void:
|
||
for child in node.get_children():node.remove_child(child);child.queue_free()
|
||
|
||
func rebuild() -> void:
|
||
clear_children(world);pieces.clear();goals.clear()
|
||
for r in records:
|
||
var object: Node3D=lib.create_piece(r.kind,lib.record_center(r),r.quarter)
|
||
object.set_meta("record_id",r.id);world.add_child(object);pieces.append(object)
|
||
if r.kind=="goal_hole":goals.append(r)
|
||
goal_position=Vector3.ZERO if goals.is_empty() else goals[0].position
|
||
refresh_ground();refresh_selection()
|
||
|
||
func reset_simulation() -> void:
|
||
clear_children(actors);balls.clear();tags.clear();previous.clear()
|
||
entered.clear();lost.clear();events.clear();samples.clear();visited.clear();contact_visited.clear();release_ticks.clear();pause_states.clear()
|
||
elapsed=0;started=false;paused=false
|
||
for spec in spawn_specs:
|
||
var ball=lib.create_ball();ball.freeze=true;ball.name=spec.id;ball.set_meta("ball_id",spec.id)
|
||
actors.add_child(ball);ball.position=lib.vector(spec.position)
|
||
balls.append(ball);previous.append(ball.position)
|
||
var tag:=Label3D.new();tag.text=str(balls.size());tag.font=font;tag.font_size=42
|
||
tag.pixel_size=.006;tag.modulate=ACCENT;tag.outline_size=3;tag.outline_modulate=PAPER
|
||
tag.billboard=BaseMaterial3D.BILLBOARD_ENABLED;actors.add_child(tag);tags.append(tag)
|
||
refresh_ball_marker()
|
||
status="准备释放 %d 颗铁球。" % balls.size();refresh_ui()
|
||
|
||
func initial_velocity(_index: int) -> Vector3:
|
||
return Vector3.ZERO
|
||
|
||
func toggle_run() -> void:
|
||
if balls.is_empty():status="请先添加至少一个铁球起点。";refresh_ui();return
|
||
if not started:
|
||
started=true;paused=false;clear_children(ball_marker)
|
||
for i in range(balls.size()):
|
||
balls[i].freeze=false
|
||
balls[i].linear_velocity=initial_velocity(i)
|
||
balls[i].angular_velocity=Vector3.ZERO
|
||
release_ticks.append(Engine.get_physics_frames())
|
||
elif not paused:
|
||
pause_states.clear()
|
||
for b in balls:pause_states.append([b.linear_velocity,b.angular_velocity]);b.freeze=true
|
||
paused=true
|
||
else:
|
||
for i in range(balls.size()):
|
||
if entered.has(i) or lost.has(i):continue
|
||
balls[i].freeze=false;balls[i].linear_velocity=pause_states[i][0];balls[i].angular_velocity=pause_states[i][1]
|
||
paused=false
|
||
refresh_ui()
|
||
|
||
func _physics_process(delta: float) -> void:
|
||
for i in range(tags.size()):tags[i].position=balls[i].position+Vector3.UP*.6
|
||
if not started or paused:return
|
||
if entered.size()+lost.size()==balls.size():return
|
||
elapsed+=delta
|
||
for i in range(balls.size()):
|
||
if entered.has(i) or lost.has(i):continue
|
||
var b=balls[i]
|
||
for collider in b.get_colliding_bodies():
|
||
if collider.has_meta("piece_type"):contact_visited[str(collider.get_meta("piece_type"))]=true
|
||
for r in records:
|
||
var bounds: AABB=lib.record_bounds(r)
|
||
if bounds.grow(.08).has_point(b.position-Vector3.UP*b.radius):visited[r.kind]=true
|
||
var reached: String=crossed_goal_id(previous[i],b.position,b.radius)
|
||
if not reached.is_empty():
|
||
entered[i]=true;events.append({"ballId":str(b.name),"goalId":reached,"time":elapsed,"position":[b.position.x,b.position.y,b.position.z]})
|
||
b.freeze=true;b.hide();b.collision_layer=0;b.collision_mask=0;tags[i].hide()
|
||
elif b.position.y<minimum_y()-3:
|
||
lost[i]=true;b.freeze=true
|
||
previous[i]=b.position
|
||
if Engine.get_physics_frames()%6==0:
|
||
var positions: Array=[]
|
||
for b in balls:positions.append([b.position.x,b.position.y,b.position.z])
|
||
samples.append({"time":elapsed,"positions":positions,"entered":entered.size()})
|
||
if entered.size()==balls.size():status="全部入洞! %.2f 秒" % elapsed
|
||
elif not lost.is_empty():status="有铁球离轨。按 T 回到编辑。"
|
||
else:status="运行中 · %.1f 秒" % elapsed
|
||
refresh_ui()
|
||
|
||
func crossed_goal_id(before: Vector3,after: Vector3,radius: float) -> String:
|
||
for goal in goals:
|
||
if lib.crossed_goal(before,after,goal.position,radius):return goal.id
|
||
return ""
|
||
|
||
func minimum_y() -> float:
|
||
var result:=0.0
|
||
for r in records:result=minf(result,lib.record_bounds(r).position.y)
|
||
for spawn in spawn_specs:result=minf(result,float(spawn.position[1]))
|
||
return result
|
||
|
||
func refresh_ui() -> void:
|
||
if status_label==null:return
|
||
status_label.text=status
|
||
if notice_label!=null:notice_label.text=status
|
||
count_label.text="%d / %d 已入洞" % [entered.size(),balls.size()]
|
||
run_button.text="继续" if paused else ("暂停" if started else "▶ 同时释放")
|
||
editable=editable.filter(func(control):return is_instance_valid(control))
|
||
for control in editable:
|
||
if control is BaseButton:control.disabled=started
|
||
elif control is SpinBox or control is LineEdit:control.editable=not started
|
||
elif control is Range:control.editable=not started
|
||
if editor_mode:
|
||
boost_controls.visible=category!="balls" and kind==Booster.KIND
|
||
for mode in mode_buttons:mode_buttons[mode].button_pressed=mode==block_mode
|
||
if apply_button!=null:apply_button.disabled=started or block_mode!="edit" or index_for(selected_id)<0
|
||
if delete_button!=null:delete_button.disabled=started or (index_for(selected_id)<0 and ball_index()<0)
|
||
if place_button!=null:place_button.disabled=started or kind.is_empty()
|
||
if move_ball_button!=null:move_ball_button.disabled=started or ball_index()<0
|
||
ball_list.clear()
|
||
for i in range(spawn_specs.size()):
|
||
var p: Array=spawn_specs[i].position
|
||
ball_list.add_item("铁球 %d · (%.2f, %.2f, %.2f)" % [i+1,p[0],p[1],p[2]])
|
||
ball_list.select(ball_index())
|
||
if detail_label!=null:detail_label.text="%s · %d° · %d 块" % [kind_name(kind),quarter*90,records.size()]
|
||
|
||
func refresh_selection() -> void:
|
||
clear_children(selection)
|
||
if not editor_mode:return
|
||
if category=="balls":refresh_grid();refresh_ui();return
|
||
if kind.is_empty():refresh_grid();refresh_ui();return
|
||
var candidate: Dictionary=placement.record_at(kind,cursor,quarter,"preview")
|
||
var bounds: AABB=lib.record_bounds(candidate)
|
||
var center: Vector3=bounds.get_center();center.y=bounds.position.y
|
||
var footprint: Vector2i=lib.footprint(kind,quarter)
|
||
var issue:=placement_error(candidate,selected_id if block_mode=="edit" else "")
|
||
var tint:=Color("4d8c70") if issue.is_empty() else ACCENT
|
||
for axis in range(2):
|
||
for side in [-1,1]:
|
||
var size:=Vector3(.03,.03,footprint.y) if axis==0 else Vector3(footprint.x,.03,.03)
|
||
var p:=center+(Vector3(side*footprint.x*.5,.025,0) if axis==0 else Vector3(0,.025,side*footprint.y*.5))
|
||
box(size,p,tint,selection)
|
||
var editing_unchanged:=false
|
||
var index:=index_for(selected_id)
|
||
if block_mode=="edit" and index>=0:
|
||
editing_unchanged=records[index].position.is_equal_approx(candidate.position) and records[index].kind==kind and records[index].quarter==quarter
|
||
if issue.is_empty() and not editing_unchanged:
|
||
var preview: Node3D=load(lib.catalog[kind].path).instantiate()
|
||
preview.position=lib.record_center(candidate);preview.rotation.y=-quarter*PI/2
|
||
selection.add_child(preview);ghost(preview)
|
||
if absf(center.y)>.01:
|
||
box(Vector3(.012,absf(center.y),.012),Vector3(center.x,center.y*.5,center.z),tint,selection)
|
||
syncing=true
|
||
for i in range(position_fields.size()):
|
||
position_fields[i].step=.01 if kind=="goal_hole" else (.5 if i==1 else 1)
|
||
position_fields[i].value=cursor[i]
|
||
syncing=false
|
||
refresh_grid();refresh_ui()
|
||
|
||
func ghost(node: Node) -> void:
|
||
if node is MeshInstance3D:
|
||
var m:=StandardMaterial3D.new();m.albedo_color=Color(.7,.85,.7,.35)
|
||
m.transparency=BaseMaterial3D.TRANSPARENCY_ALPHA;node.material_override=m
|
||
node.cast_shadow=GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||
for child in node.get_children():ghost(child)
|
||
|
||
func refresh_ground() -> void:
|
||
# Y=0 is a visual construction datum. Cut out goal footprints so the plane
|
||
# does not cover mouths/outlets that cross it. Physics remains geometry driven.
|
||
ground_holes.clear()
|
||
for goal in goals:
|
||
var bounds: AABB=lib.record_bounds(goal)
|
||
if bounds.position.y<=.001 and bounds.end.y>=-.001:
|
||
ground_holes.append(Rect2(bounds.position.x,bounds.position.z,bounds.size.x,bounds.size.z))
|
||
var regions: Array=[Rect2(-100,-100,200,200)]
|
||
for hole: Rect2 in ground_holes:
|
||
var split: Array=[]
|
||
for region: Rect2 in regions:
|
||
if not region.intersects(hole):split.append(region);continue
|
||
var cut:=region.intersection(hole)
|
||
var candidates=[Rect2(region.position,Vector2(cut.position.x-region.position.x,region.size.y)),
|
||
Rect2(Vector2(cut.end.x,region.position.y),Vector2(region.end.x-cut.end.x,region.size.y)),
|
||
Rect2(Vector2(cut.position.x,region.position.y),Vector2(cut.size.x,cut.position.y-region.position.y)),
|
||
Rect2(Vector2(cut.position.x,cut.end.y),Vector2(cut.size.x,region.end.y-cut.end.y))]
|
||
for rect: Rect2 in candidates:
|
||
if rect.size.x>.00001 and rect.size.y>.00001:split.append(rect)
|
||
regions=split
|
||
var mesh:=ImmediateMesh.new();mesh.surface_begin(Mesh.PRIMITIVE_TRIANGLES)
|
||
mesh.surface_set_normal(Vector3.UP)
|
||
for region: Rect2 in regions:
|
||
var a:=Vector3(region.position.x,0,region.position.y)
|
||
var b:=Vector3(region.position.x,0,region.end.y)
|
||
var c:=Vector3(region.end.x,0,region.end.y)
|
||
var d:=Vector3(region.end.x,0,region.position.y)
|
||
for vertex in [a,c,b,a,d,c]:mesh.surface_add_vertex(vertex)
|
||
mesh.surface_end();ground_view.mesh=mesh
|
||
ground_view.cast_shadow=GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||
var mat:=material(Color("8b9a64"));mat.cull_mode=BaseMaterial3D.CULL_DISABLED
|
||
ground_view.material_override=mat
|
||
|
||
func refresh_grid() -> void:
|
||
clear_children(grid)
|
||
if not editor_mode:return
|
||
# Grid stays on the datum, independent of the selected height.
|
||
for axis in range(2):
|
||
for i in range(-12,13):
|
||
var fixed: float=(cursor.x if axis==0 else cursor.z)+i-.5
|
||
var along: float=cursor.z if axis==0 else cursor.x
|
||
var intervals: Array=[Vector2(along-12,along+12)]
|
||
for hole: Rect2 in ground_holes:
|
||
var across_min: float=hole.position.x if axis==0 else hole.position.y
|
||
var across_max: float=hole.end.x if axis==0 else hole.end.y
|
||
if fixed<across_min or fixed>across_max:continue
|
||
var start: float=hole.position.y if axis==0 else hole.position.x
|
||
var end: float=hole.end.y if axis==0 else hole.end.x
|
||
var next: Array=[]
|
||
for interval: Vector2 in intervals:
|
||
if interval.y<=start or interval.x>=end:next.append(interval)
|
||
else:
|
||
if interval.x<start:next.append(Vector2(interval.x,start))
|
||
if interval.y>end:next.append(Vector2(end,interval.y))
|
||
intervals=next
|
||
for interval: Vector2 in intervals:
|
||
var length: float=interval.y-interval.x;var middle: float=(interval.x+interval.y)*.5
|
||
var size:=Vector3(.008,.004,length) if axis==0 else Vector3(length,.004,.008)
|
||
var at:=Vector3(fixed,.004,middle) if axis==0 else Vector3(middle,.004,fixed)
|
||
box(size,at,Color("a2aa7c"),grid)
|
||
|
||
func frame_level() -> void:
|
||
if records.is_empty() and spawn_specs.is_empty():target=Vector3.ZERO;camera_size=12;update_camera();return
|
||
var low:=Vector3(INF,INF,INF);var high:=-low
|
||
for r in records:
|
||
var bounds: AABB=lib.record_bounds(r);low=low.min(bounds.position);high=high.max(bounds.end)
|
||
for spawn in spawn_specs:
|
||
var p: Vector3=lib.vector(spawn.position);low=low.min(p);high=high.max(p)
|
||
target=(low+high)*.5;camera_size=maxf(9.0,(high-low).length()*.93+2)
|
||
update_camera()
|
||
|
||
func update_camera() -> void:
|
||
camera.size=camera_size
|
||
camera.position=target+Vector3(cos(yaw)*cos(pitch),sin(pitch),sin(yaw)*cos(pitch))*40
|
||
camera.look_at(target)
|
||
|
||
func select_at(screen: Vector2) -> void:
|
||
if started or not editor_mode:return
|
||
var origin:=camera.project_ray_origin(screen);var dir:=camera.project_ray_normal(screen)
|
||
var query:=PhysicsRayQueryParameters3D.create(origin,origin+dir*300,3)
|
||
var hit:=get_world_3d().direct_space_state.intersect_ray(query)
|
||
if not hit.is_empty():
|
||
var node: Node=hit.collider
|
||
if node.has_meta("ball_id"):
|
||
for i in range(spawn_specs.size()):
|
||
if spawn_specs[i].id==str(node.get_meta("ball_id")):select_ball(i);refresh_ui();return
|
||
if category=="balls":pick_ball_position(origin,dir,hit);return
|
||
while node!=null and not node.has_meta("record_id"):node=node.get_parent()
|
||
if node!=null:
|
||
var id: String=node.get_meta("record_id")
|
||
if block_mode=="edit":select_record(id);return
|
||
if kind.is_empty():status="先选择要放置的方块。";refresh_ui();return
|
||
cursor=placement.on_face(records[index_for(id)],hit.position,hit.normal,kind,quarter)
|
||
selected_id="";selected_ball_id=""
|
||
status="新方块底面 Y %.2f · 原方块保持不动" % cursor.y
|
||
refresh_selection();return
|
||
if category=="balls":pick_ball_position(origin,dir,{});return
|
||
var p=Plane(Vector3.UP,0).intersects_ray(origin,dir)
|
||
if p!=null:
|
||
cursor=Vector3(round(p.x),0,round(p.z));selected_id="";selected_ball_id=""
|
||
refresh_selection()
|
||
|
||
func _unhandled_input(event: InputEvent) -> void:
|
||
if event is InputEventKey and event.pressed and not event.echo:
|
||
match event.keycode:
|
||
KEY_SPACE:toggle_run()
|
||
KEY_T:reset_simulation()
|
||
KEY_R:rotate_current()
|
||
KEY_DELETE,KEY_BACKSPACE:remove_current()
|
||
KEY_F:frame_level()
|
||
KEY_Z:
|
||
if event.ctrl_pressed or event.meta_pressed:undo()
|
||
if event is InputEventMouseButton:
|
||
if event.button_index==MOUSE_BUTTON_RIGHT:orbiting=event.pressed
|
||
if event.button_index==MOUSE_BUTTON_MIDDLE:panning=event.pressed
|
||
if event.pressed:
|
||
if event.button_index==MOUSE_BUTTON_WHEEL_UP:camera_size=maxf(3,camera_size-.7);update_camera()
|
||
if event.button_index==MOUSE_BUTTON_WHEEL_DOWN:camera_size=minf(150,camera_size+.7);update_camera()
|
||
if event.button_index==MOUSE_BUTTON_LEFT:select_at(event.position)
|
||
if event is InputEventMouseMotion:
|
||
if orbiting:yaw-=event.relative.x*.006;pitch=clampf(pitch+event.relative.y*.004,.18,1.4);update_camera()
|
||
if panning:
|
||
target-=camera.global_basis.x*event.relative.x*camera_size/900
|
||
target+=Vector3(camera.global_basis.y.x,0,camera.global_basis.y.z)*event.relative.y*camera_size/900
|
||
update_camera()
|
||
|
||
func save_level(path: String) -> Error:
|
||
var f:=FileAccess.open(path,FileAccess.WRITE)
|
||
if f==null:return FileAccess.get_open_error()
|
||
f.store_string(JSON.stringify(encode()," "));f.close();return OK
|
||
|
||
func load_level(path: String) -> String:
|
||
if started:return "请先返回编辑。"
|
||
if not FileAccess.file_exists(path):return "未找到关卡文件。"
|
||
var parsed:=JSON.new()
|
||
if parsed.parse(FileAccess.get_file_as_string(path))!=OK:return "JSON 格式有误。"
|
||
var issue:=validate_level(parsed.data)
|
||
if not issue.is_empty():return issue
|
||
remember();apply_data(parsed.data);return ""
|
||
|
||
func safe_name() -> String:
|
||
return name_field.text.strip_edges().validate_filename().replace(".","_")
|
||
|
||
func save_named() -> void:
|
||
if started:return
|
||
var title:=safe_name()
|
||
if title.is_empty():status="请输入关卡名称。";refresh_ui();return
|
||
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(SAVE_DIR))
|
||
var path:=SAVE_DIR+"/"+title+".json"
|
||
# Keep one local backup on replacement.
|
||
if FileAccess.file_exists(path):DirAccess.copy_absolute(ProjectSettings.globalize_path(path),ProjectSettings.globalize_path(path+".bak"))
|
||
var err:=save_level(path)
|
||
status="已保存:designer/drafts/"+title+".json" if err==OK else "保存失败:"+error_string(err)
|
||
refresh_files();refresh_ui()
|
||
|
||
func load_named() -> void:
|
||
var path:=SAVE_DIR+"/"+safe_name()+".json"
|
||
if not FileAccess.file_exists(path):
|
||
for i in range(file_list.item_count):
|
||
if file_list.get_item_text(i)==safe_name():path=str(file_list.get_item_metadata(i));break
|
||
var issue:=load_level(path)
|
||
status="关卡已载入。" if issue.is_empty() else issue;refresh_ui()
|
||
|
||
func refresh_files() -> void:
|
||
if file_list==null:return
|
||
file_list.clear()
|
||
var dir:=DirAccess.open(SAVE_DIR)
|
||
var listed: Array=[]
|
||
if dir!=null:
|
||
for file in dir.get_files():
|
||
if file.ends_with(".json"):
|
||
var title:=file.trim_suffix(".json");listed.append(title);file_list.add_item(title)
|
||
file_list.set_item_metadata(file_list.item_count-1,SAVE_DIR+"/"+file)
|
||
for path in EXAMPLE_LEVELS:
|
||
var title: String=path.get_file().trim_suffix(".json")
|
||
if title not in listed and FileAccess.file_exists(path):
|
||
file_list.add_item(title);file_list.set_item_metadata(file_list.item_count-1,path)
|
||
|
||
func _process(_delta: float) -> void:
|
||
if capture_count<0:return
|
||
capture_count-=1
|
||
if capture_count==0:
|
||
await RenderingServer.frame_post_draw
|
||
get_viewport().get_texture().get_image().save_png(capture_path)
|
||
get_tree().quit()
|