Files
Yanchen d1141b04c7 feat: 更新 IntoHole 的球体、滑槽和环境资产
- 为铁球、陶瓷球和木球制作风格化材质,归档 CC0 原始参考
- 更新方形球洞和实心滑槽,统一 90° 弯槽并兼容旧存档
- 用顺流泡沫表示水流方向,为冰块制作三种交错的裂纹
- 同步 Blender 源资产、Godot 加载、工坊和试玩预览
2026-11-19 16:18:41 +08:00

496 lines
22 KiB
GDScript

extends "res://designer/scripts/studio.gd"
const Thumbnail = preload("res://playtest/tutorial/scripts/block_thumbnail.gd")
const CELL_OVERLAY_Y := 0.014
const Maps = preload("res://playtest/tutorial/scripts/maps.gd")
const NAMES = {"straight":"直行滑槽","gentle":"缓坡 · 0.5 m","steep":"急坡 · 1 m","turn_90":"90°弯槽","y_merge":"Y 汇流"}
@export_range(0,4) var lesson_index := 0
var lesson: Dictionary = {}
# Legal empty positions for the currently oriented piece, keyed by its bottom.
var build_cells: Dictionary = {}
var hover_candidate: Dictionary = {}
var hover_screen := Vector2.INF
var erase_mode := false
var orientations: Dictionary = {}
var palette_row: HBoxContainer
var toolbar: PanelContainer
var erase_button: Thumbnail
var slots_view := Node3D.new()
var preview_view := Node3D.new()
var palette_buttons: Dictionary = {}
var lesson_buttons: Array = []
var heading: Label
var objective_label: Label
var selection_label: Label
var hint_label: Label
var timer_label: Label
var retry_button: Button
var restart_button: Button
var next_button: Button
var hint_button: Button
var unlocked := 0
var completed: Dictionary = {}
var solved := false
var failed := false
var attempt_done := false
var retries := 0
var challenge_seconds := 0.0
var still_seconds := 0.0
var contact_ids: Dictionary = {}
var hint_open := false
var interface_events: Array = []
func _ready() -> void:
super._ready()
get_window().title = "IntoHole · " + series_title()
func series_title() -> String:
return "等级一 / 滑槽入门"
func read_lesson(index: int) -> Dictionary:
return Maps.read_lesson(index)
func initial_layout(data: Dictionary) -> Dictionary:
return Maps.initial_level(data, lib)
func setup_environment() -> void:
super.setup_environment()
camera.h_offset = 0
camera.v_offset = -.65
yaw = .95; pitch = 1.12
add_child(slots_view); add_child(preview_view)
func button(text: String, action: Callable, primary:=false, lock:=false) -> Button:
var b:Button=super.button(text,action,primary,lock)
b.focus_mode=Control.FOCUS_NONE
return b
func setup_ui() -> void:
var layer:=CanvasLayer.new();add_child(layer)
var info:=PanelContainer.new();info.position=Vector2(18,18);info.custom_minimum_size.x=316
info.add_theme_stylebox_override("panel",style(PAPER));layer.add_child(info)
var col:=VBoxContainer.new();col.add_theme_constant_override("separation",7);info.add_child(col)
col.add_child(label("INTO / HOLE",25))
var steps:=row(col)
for i in range(5):
var b:=button(str(i+1),func():open_lesson(i));b.custom_minimum_size.x=48
steps.add_child(b);lesson_buttons.append(b)
heading=label("",20);col.add_child(heading)
objective_label=label("",14);objective_label.custom_minimum_size.x=290
objective_label.autowrap_mode=TextServer.AUTOWRAP_WORD_SMART;col.add_child(objective_label)
hint_label=label("",14,Color("7a7366"));hint_label.custom_minimum_size.x=290
hint_label.autowrap_mode=TextServer.AUTOWRAP_WORD_SMART;col.add_child(hint_label)
var actions:=PanelContainer.new();layer.add_child(actions)
actions.set_anchors_and_offsets_preset(Control.PRESET_TOP_RIGHT)
actions.offset_left=-368;actions.offset_right=-18;actions.offset_top=18
actions.add_theme_stylebox_override("panel",style(PAPER))
var controls:=VBoxContainer.new();controls.add_theme_constant_override("separation",6);actions.add_child(controls)
timer_label=label("",14,Color("7a7366"));controls.add_child(timer_label)
var line:=row(controls)
run_button=button("▶ 释放小球",toggle_run,true);run_button.custom_minimum_size.x=108;line.add_child(run_button)
retry_button=button("局内重试",retry_attempt);line.add_child(retry_button)
hint_button=button("提示",toggle_hint);line.add_child(hint_button)
status_label=label("",14);status_label.custom_minimum_size.x=320
status_label.autowrap_mode=TextServer.AUTOWRAP_WORD_SMART;controls.add_child(status_label)
next_button=button("下一关 →",next_lesson,true);controls.add_child(next_button)
restart_button=button("重新挑战本关",restart_challenge);controls.add_child(restart_button)
toolbar=PanelContainer.new();layer.add_child(toolbar)
toolbar.set_anchors_and_offsets_preset(Control.PRESET_CENTER_BOTTOM)
toolbar.add_theme_stylebox_override("panel",style(PAPER))
var bottom:=VBoxContainer.new();bottom.add_theme_constant_override("separation",6);toolbar.add_child(bottom)
selection_label=label("",14);selection_label.horizontal_alignment=HORIZONTAL_ALIGNMENT_CENTER
selection_label.autowrap_mode=TextServer.AUTOWRAP_WORD_SMART;bottom.add_child(selection_label)
palette_row=row(bottom);palette_row.alignment=BoxContainer.ALIGNMENT_CENTER;palette_row.add_theme_constant_override("separation",8)
for panel in [info,actions,toolbar]:panel.mouse_entered.connect(clear_hover)
func clear_hover() -> void:
hover_screen=Vector2.INF
if hover_candidate.is_empty():return
hover_candidate={};refresh_preview();refresh_ui()
func initialize_level() -> void:
for arg in OS.get_cmdline_user_args():
if arg.begins_with("--lesson="): lesson_index = clampi(int(arg.trim_prefix("--lesson="))-1,0,4)
unlocked = lesson_index
open_lesson(lesson_index)
func open_lesson(index: int) -> void:
if failed and index!=0:return
if index > unlocked or (started and not solved and not failed): return
var next_data := read_lesson(index)
if next_data.is_empty():
push_error("无法载入%s第 %d 关" % [series_title(), index + 1])
return
lesson_index = index
lesson = next_data
hover_screen=Vector2.INF; hover_candidate = {}; erase_mode = false; quarter = 0; orientations.clear()
solved = false; failed = false; attempt_done = false; retries = 0; challenge_seconds = 0; still_seconds = 0
contact_ids.clear(); hint_open = false; interface_events.clear()
clear_children(palette_row);palette_buttons.clear()
for id in lesson.inventory:
orientations[id]=int(lesson.defaults.get(id,0))
var tile:=Thumbnail.new();palette_row.add_child(tile)
tile.configure(NAMES[id],lib.catalog[id].path,float(lib.catalog[id].boundsBlender.size[2]),font)
tile.pressed.connect(func():choose_kind(id));tile.mouse_entered.connect(clear_hover);palette_buttons[id]=tile
erase_button=Thumbnail.new();palette_row.add_child(erase_button)
erase_button.configure("擦除 / 回收","",1.0,font)
erase_button.pressed.connect(choose_eraser);erase_button.mouse_entered.connect(clear_hover)
var width:float=maxf(640,(palette_buttons.size()+1)*112+palette_buttons.size()*8+24)
toolbar.offset_left=-width*.5;toolbar.offset_right=width*.5
toolbar.offset_top=-196;toolbar.offset_bottom=-14
kind=""
apply_data(initial_layout(lesson))
status = "把路线接好,再释放小球。"
refresh_slots(); refresh_preview(); refresh_ui()
func next_lesson() -> void:
if not solved:return
if lesson_index < 4:
started = false; open_lesson(lesson_index+1)
else:
status = "%s · 五关全部通过。" % series_title(); refresh_ui()
func encode() -> Dictionary:
return codec.encode(records,spawn_specs,str(lesson.get("title","滑槽入门")))
func restart_challenge() -> void:
started = false
if failed:
unlocked = 0; completed.clear(); open_lesson(0)
else: open_lesson(lesson_index)
func retry_attempt() -> void:
if not started or solved or failed:return
retries += 1
if retries >= 5: fail_challenge("局内重试已达 5 次。"); return
reset_simulation(); contact_ids.clear(); still_seconds = 0; attempt_done = false
status = "布局已保留,可以修改后再试。"
refresh_slots(); refresh_preview(); refresh_ui()
func fail_challenge(reason: String) -> void:
failed = true; paused = true
for b in balls:b.freeze = true
status = reason + "请从本组第一关重新挑战。"
refresh_ui()
func used_count(type_id: String, ignore := "") -> int:
var count := 0
for r in records:
if str(r.id).begins_with("built_") and r.id != ignore and r.kind == type_id: count += 1
return count
func choose_kind(id: String) -> void:
if started or solved or failed or not lesson.inventory.has(id):return
if not erase_mode and kind==id:
rotate_current();return
erase_mode=false;kind=id;quarter=int(orientations[id])
interface_events.append({"action":"palette","kind":id})
refresh_slots();refresh_preview();refresh_ui()
func choose_eraser() -> void:
if started or solved or failed:return
erase_mode=true
interface_events.append({"action":"eraser"})
refresh_slots();refresh_preview();refresh_ui()
func placement_issue(candidate: Dictionary) -> String:
if not lesson.inventory.has(candidate.kind):return "本关没有这种滑槽。"
if used_count(candidate.kind,candidate.id) >= int(lesson.inventory[candidate.kind]): return "这种滑槽已用完,先移除或替换一块。"
return geometry_issue(candidate)
func geometry_issue(candidate: Dictionary) -> String:
for r in records:
if r.id != candidate.id and codec.overlaps(candidate,r): return "与其他方块重叠,无法放置。"
# Placement adjacency is a puzzle rule, not a physical support requirement.
var a: AABB = lib.record_bounds(candidate)
for r in records:
if r.id == candidate.id:continue
var b: AABB = lib.record_bounds(r)
var extent := a.end.min(b.end)-a.position.max(b.position)
for axis in range(3):
if absf(extent[axis])<.002 and extent[(axis+1)%3]>.01 and extent[(axis+2)%3]>.01:return ""
return "滑槽至少有一面需要贴住其他方块。"
func place_current() -> void:
if started or solved or failed or erase_mode or kind.is_empty() or hover_candidate.is_empty():return
var candidate := hover_candidate.duplicate()
var issue := placement_issue(candidate)
if not issue.is_empty():
status=issue;refresh_ui();return
if candidate.id == "":
candidate.id=unique_id("built")
records.append(candidate)
else:
var existing:=index_for(candidate.id)
if existing<0 or not str(candidate.id).begins_with("built_"):return
records[existing]=candidate
interface_events.append({"action":"place","id":candidate.id,"position":codec.array_from(candidate.position),"kind":kind,"quarter":quarter})
rebuild();refresh_slots();refresh_preview()
status="已放置,可继续延伸路线。";refresh_ui()
func rotate_current() -> void:
if started or solved or failed or erase_mode or kind.is_empty():return
quarter=(quarter+1)%4;orientations[kind]=quarter
interface_events.append({"action":"rotate","kind":kind,"quarter":quarter})
refresh_slots()
if hover_screen.is_finite():hover_at(hover_screen,Input.is_key_pressed(KEY_SHIFT))
refresh_preview();refresh_ui()
func remove_current() -> void:
if started or solved or failed or not erase_mode or hover_candidate.is_empty():return
var id:=str(hover_candidate.id)
var existing:=index_for(id)
if existing<0 or not id.begins_with("built_"):return
var old_kind:String=records[existing].kind
records.remove_at(existing)
interface_events.append({"action":"remove","id":id,"kind":old_kind})
rebuild();refresh_slots();refresh_preview();status="已回收,可继续擦除其他滑槽。";refresh_ui()
func toggle_hint() -> void:
hint_open=not hint_open;refresh_ui()
func refresh_slots() -> void:
clear_children(slots_view)
slots_view.visible=not started
build_cells.clear()
hover_candidate={}
if lesson.is_empty() or kind.is_empty() or erase_mode or started:return
var size: Vector2i=lib.footprint(kind,quarter)
var height: float=lib.catalog[kind].boundsBlender.size[2]
# Enumerate touching footprints around live records, including both vertical
# faces. Piece geometry decides heights. No authored route is consulted.
for support in records:
var bounds: AABB = lib.record_bounds(support)
# Grid anchors are centres of the first occupied cell. Include the outer
# ring where exactly one horizontal edge can touch the support.
var first_x := ceili(bounds.position.x + 0.5 - size.x - 0.001)
var last_x := floori(bounds.end.x + 0.5 + 0.001)
var first_z := ceili(bounds.position.z + 0.5 - size.y - 0.001)
var last_z := floori(bounds.end.z + 0.5 + 0.001)
for x in range(first_x, last_x + 1):
for z in range(first_z, last_z + 1):
var dx:=minf(x-.5+size.x,bounds.end.x)-maxf(x-.5,bounds.position.x)
var dz:=minf(z-.5+size.y,bounds.end.z)-maxf(z-.5,bounds.position.z)
var base:=Vector3(x,bounds.position.y,z)
if dx>.01 and dz>.01:
for y in [bounds.end.y,bounds.position.y-height]:
add_build_cell(placement.record_at(kind,Vector3(x,y,z),quarter,""))
elif (absf(dx)<.002 and dz>.01) or (absf(dz)<.002 and dx>.01):
var candidate:Dictionary=placement.record_at(kind,base,quarter,"")
add_build_cell(placement.align_surfaces(candidate,records,support.id))
draw_build_cells()
func add_build_cell(candidate: Dictionary) -> void:
var bottom:Vector3=placement.bottom_of(candidate)
var key:=bottom.snapped(Vector3.ONE*.0001)
if not build_cells.has(key) and geometry_issue(candidate).is_empty():
build_cells[key]=candidate
func draw_build_cells() -> void:
if build_cells.is_empty():return
var mesh:=ImmediateMesh.new()
var ink:=StandardMaterial3D.new()
ink.shading_mode=BaseMaterial3D.SHADING_MODE_UNSHADED
ink.albedo_color=Color("426f60")
mesh.surface_begin(Mesh.PRIMITIVE_LINES,ink)
for cell in build_cells.values():
var bounds:AABB=lib.record_bounds(cell)
var p:=bounds.get_center()
p.y=bounds.position.y+CELL_OVERLAY_Y
for axis in [Vector3.RIGHT,Vector3.BACK]:
var across:=Vector3.BACK if axis==Vector3.RIGHT else Vector3.RIGHT
for side in [-1,1]:
for segment in [-.32,0.0,.32]:
var edge:Vector3=p+across*side*(bounds.size.dot(across)*.5-.04)
mesh.surface_add_vertex(edge+axis*(segment-.1)*bounds.size.dot(axis))
mesh.surface_add_vertex(edge+axis*(segment+.1)*bounds.size.dot(axis))
mesh.surface_end()
var visual:=MeshInstance3D.new()
visual.mesh=mesh
visual.cast_shadow=GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
slots_view.add_child(visual)
func refresh_preview() -> void:
clear_children(preview_view)
if hover_candidate.is_empty() or started or solved or failed or erase_mode or kind.is_empty():return
var candidate:=hover_candidate
var position:Vector3=lib.record_center(candidate)
var existing:=index_for(candidate.id)
if existing<0 or records[existing]!=candidate:
var visual:Node3D=load(lib.catalog[kind].path).instantiate()
visual.position=position;visual.rotation.y=-quarter*PI/2;preview_view.add_child(visual)
var tint:=Color(.3,.7,.55,.38) if placement_issue(candidate).is_empty() else Color(.85,.25,.2,.38)
var mat:=material(tint)
mat.transparency=BaseMaterial3D.TRANSPARENCY_ALPHA
for node in visual.find_children("*","MeshInstance3D",true,false):
node.cast_shadow=GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
if str(node.name).begins_with("ink_"):node.hide();continue
node.material_override=mat
if lesson_index>=3:
var basis:=Basis(Vector3.UP,-quarter*PI/2)
for t in [0.0,1.0]:
var endpoint:Vector3=position+basis*(lib.path_point(kind,t)-Vector3.UP*float(lib.catalog[kind].grooveRadius))
var tag:=Label3D.new();tag.text="槽底 %.2f m"%endpoint.y;tag.font=font;tag.font_size=36
tag.pixel_size=.005;tag.billboard=BaseMaterial3D.BILLBOARD_ENABLED;tag.position=endpoint+Vector3.UP*.2
tag.modulate=INK;tag.outline_modulate=PAPER;preview_view.add_child(tag)
func pick_candidate(screen: Vector2, attach: bool=false) -> Dictionary:
var origin:=camera.project_ray_origin(screen)
var direction:=camera.project_ray_normal(screen)
var query:=PhysicsRayQueryParameters3D.create(origin,origin+direction*300,11)
query.collide_with_areas=true
var hit:=get_world_3d().direct_space_state.intersect_ray(query)
var hit_record:Dictionary={}
var nearest:=300.0
if not hit.is_empty():
nearest=origin.distance_to(hit.position)
var node:Node=hit.collider
while node!=null and not node.has_meta("record_id"):node=node.get_parent()
if node!=null:
var index:=index_for(node.get_meta("record_id"))
if index>=0:hit_record=records[index]
var is_built:=str(hit_record.get("id","")).begins_with("built_")
var hit_bounds:AABB=lib.record_bounds(hit_record) if is_built else AABB()
if erase_mode:return hit_record if is_built else {}
if kind.is_empty():return {}
if attach and not hit_record.is_empty():
return face_candidate(hit_record,hit)
var picked:Dictionary={}
for cell in build_cells.values():
var bounds:AABB=lib.record_bounds(cell)
# Use the visible grid outline's plane, clipped by actual scene geometry.
var crossing=Plane(Vector3.UP,bounds.position.y+CELL_OVERLAY_Y).intersects_ray(origin,direction)
if crossing==null:continue
var distance:=origin.distance_to(crossing)
if distance>=nearest:continue
if crossing.x<bounds.position.x or crossing.x>bounds.end.x or crossing.z<bounds.position.z or crossing.z>bounds.end.z:continue
# Keep a player's visible piece clickable for replacement; Shift explicitly stacks.
if is_built and absf(bounds.position.y-hit_bounds.end.y)<.002 and hit_bounds.grow(.02).has_point(crossing):continue
picked=cell;nearest=distance
if not picked.is_empty():return picked
if is_built:
var candidate:Dictionary=placement.record_at(kind,placement.bottom_of(hit_record),quarter,hit_record.id)
return placement.align_surfaces(candidate,records)
if not hit_record.is_empty():return face_candidate(hit_record,hit)
return {}
func face_candidate(support:Dictionary,hit:Dictionary) -> Dictionary:
var bottom:Vector3=placement.on_face(support,hit.position,hit.normal,kind,quarter,records)
return placement.record_at(kind,bottom,quarter,"")
func hover_at(screen:Vector2,attach:bool=false) -> void:
hover_screen=screen
var candidate:=pick_candidate(screen,attach)
if candidate==hover_candidate:return
hover_candidate=candidate
refresh_preview();refresh_ui()
func select_at(screen:Vector2) -> void:
use_pointer(screen,Input.is_key_pressed(KEY_SHIFT))
func use_pointer(screen:Vector2,attach:bool) -> void:
if started or solved or failed:return
hover_at(screen,attach)
if erase_mode:remove_current()
elif kind.is_empty():status="先点击下方缩略图选择滑槽。";refresh_ui()
elif hover_candidate.is_empty():status="请选择贴住已有方块的空位。";refresh_ui()
else:place_current()
func toggle_run() -> void:
if failed or solved or attempt_done:return
if not started:
contact_ids.clear();still_seconds=0
interface_events.append({"action":"release","placed":records.filter(func(r):return str(r.id).begins_with("built_")).size()})
clear_children(preview_view)
slots_view.hide()
super.toggle_run()
refresh_ui()
func _physics_process(delta: float) -> void:
if solved or failed or attempt_done:return
super._physics_process(delta)
if not started or paused:return
var all_remaining_still := true
for i in range(balls.size()):
var body: RigidBody3D = balls[i]
for collider in body.get_colliding_bodies():
var node: Node = collider
while node != null and not node.has_meta("record_id"):
node = node.get_parent()
if node != null:
contact_ids[str(node.get_meta("record_id"))] = true
if not entered.has(i) and not lost.has(i) and body.linear_velocity.length() >= .035:
all_remaining_still = false
if entered.size()==balls.size():
solved=true;completed[lesson_index]=true;unlocked=maxi(unlocked,mini(4,lesson_index+1))
status="通关!全部小球已入洞。"
elif not lost.is_empty():
finish_attempt("小球掉落了。局内重试可保留布局再调整。")
else:
still_seconds=still_seconds+delta if all_remaining_still else 0.0
if still_seconds>2.5 or elapsed>25:
finish_attempt("仍有小球未到达洞口。局内重试可保留布局再调整。")
refresh_ui()
func finish_attempt(message: String) -> void:
attempt_done = true
for body in balls:
body.freeze = true
status = message
func refresh_ui() -> void:
if status_label==null or lesson.is_empty():return
heading.text="%02d %s"%[lesson_index+1,lesson.title]
objective_label.text=lesson.objective
var remaining:=maxi(0,300-int(challenge_seconds))
timer_label.text="%02d:%02d · 局内重试 %d / 5"%[remaining/60,remaining%60,retries]
if balls.size()>1:
timer_label.text+=" · %d/%d 入洞" % [entered.size(), balls.size()]
status_label.text=status
for i in range(5):
lesson_buttons[i].disabled=failed or i>unlocked or (started and not solved)
lesson_buttons[i].text=("✓" if completed.has(i) else str(i+1))
var locked:=started or solved or failed
for id in palette_buttons:
var left:int=int(lesson.inventory[id])-used_count(id)
palette_buttons[id].set_state(left,int(orientations[id]),kind==id and not erase_mode,locked)
erase_button.set_state(0,0,erase_mode,locked,true)
if erase_mode:selection_label.text="擦除中 · 点击滑槽回收 · 点击方块缩略图退出"
elif kind.is_empty():selection_label.text="选缩略图 → 点格放置 · 再点同一缩略图旋转"
else:selection_label.text="%s · %d° | 点邻格放置 · 点已铺槽替换 · Shift+点面叠放"%[NAMES[kind],quarter*90]
if not hover_candidate.is_empty() and lesson_index>=3 and not erase_mode and not kind.is_empty():
var y:float=hover_candidate.position.y-lib.catalog[kind].grooveRadius
selection_label.text+=" | 槽底 %.2f / %.2f m"%[y+lib.path_point(kind,0).y,y+lib.path_point(kind,1).y]
run_button.disabled=solved or failed or attempt_done
run_button.text="继续" if paused else ("暂停" if started else "▶ 释放小球")
retry_button.disabled=not started or solved or failed
next_button.visible=solved;next_button.text="下一关 →" if lesson_index<4 else "本组完成 ✓"
restart_button.text="从第一关重新挑战" if failed else "重新挑战本关(清空搭建)"
hint_label.visible=hint_open;hint_label.text=lesson.hint
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseButton and event.button_index==MOUSE_BUTTON_LEFT and event.pressed:
use_pointer(event.position,event.shift_pressed)
return
if event is InputEventKey and event.keycode==KEY_SHIFT and hover_screen.is_finite() and not started:
hover_at(hover_screen,event.pressed)
if event is InputEventKey and event.pressed and not event.echo:
match event.keycode:
KEY_SPACE:toggle_run()
KEY_T:retry_attempt()
KEY_R:rotate_current()
KEY_E:choose_eraser()
KEY_F:frame_level()
return
if event is InputEventMouseMotion and not orbiting and not panning and not started:
hover_at(event.position,event.shift_pressed)
# Orbit, pan and zoom use the shared camera controls.
super._unhandled_input(event)
func _process(delta: float) -> void:
if not lesson.is_empty() and not solved and not failed:
challenge_seconds+=delta
if challenge_seconds>=300:fail_challenge("本轮挑战已满 5 分钟。")
else:refresh_ui()
super._process(delta)