extends RefCounted
## HY3D treasure chests (Boss 2026-10-21: "แบบฟรีก่อน ลดขนาดลง 20%"): AI-made (Tencent HY 3D) 3D models of the copper /
## silver / gold chests drawn by treasure_view.gd in place of the painted billboards. VIEW ONLY: the spots, the open /
## start ranges (server/treasure.gd OPEN_R / START_R) and everything the server decides stay exactly as they were.
## Config (data/config.json):
##   "hy3d_chests": true/false - off = the painted billboards exactly (nothing below runs);
##   "hy3d_chests_map": {<kind>: <file id>} - res://assets/hy3d/chests/<file>.glb (+ .glb.import importer "skip"),
##       a kind left out keeps its billboard;
##   "hy3d_chests_size": 0.8 - on-screen size against the painted chest (Boss: 20 % smaller).
## The model files come from tools/hy3d/chests/ (texture shrink -> decimate ~6k tris -> chest_split.gd): one GLB =
## Chest > Body (+ the dark cap of the cut) and LidPivot (at the back hinge) > Lid, base on y = 0, front = +Z.
## Size: the painted chest's visible box (SPRITE_VIS, measured from assets/ui/treasure/chest_<k>.png at its old
## HEIGHT) seen by the default game camera (pitch 28 deg) has an on-screen area; the model is scaled so its own
## on-screen box (yaw 22.5 deg, the same pitch) is hy3d_chests_size^2 of that area (= 0.8 of the length).
## Facing: the front turns to the most open side (rays against the map's static colliders, 16 directions, the
## default camera side preferred); the base sits on the ground under the spot (a ray down, +-0.6 m, flat ground = 0).

const EnvAssets = preload("res://scripts/env_assets.gd")
const DIR := "res://assets/hy3d/chests/"
## visible painted chest [width, height] in metres (alpha box of the billboard png x its old pixel size)
const SPRITE_VIS := {"copper": Vector2(3.484, 3.103), "silver": Vector2(4.147, 3.305), "gold": Vector2(3.922, 3.852)}
const CAM_PITCH := 28.0
const LID_OPEN_DEG := 100.0
const DIM := 0.68

## file id -> [Node3D proto (toon, never in the tree) or null, AABB]
static var _protos := {}
static var _dim := {}
static var made := 0


static func on(k: String = "") -> bool:
	if not bool(GameData.config.get("hy3d_chests", false)):
		return false
	return k == "" or file_of(k) != ""


static func file_of(k: String) -> String:
	var m = GameData.config.get("hy3d_chests_map", {})
	var f := str((m as Dictionary).get(k, "")) if m is Dictionary else ""
	return f if f != "" and FileAccess.file_exists(DIR + f + ".glb") else ""


static func size_k() -> float:
	return clampf(float(GameData.config.get("hy3d_chests_size", 0.8)), 0.2, 2.0)


## HITCH (2026-10-27, docs/CHECKPOINT_2026-10-22.md §2.23): proto() parsed a chest GLB (~0.4 s) in the frame the
## first chest of a kind showed (the first login, the first silver / gold of a session). preload_async() (BootPrewarm,
## on the title) parses every mapped model on a worker thread, one after the other (one task); proto() takes the
## result (waits if still parsing).
static var _pre := {}


static func preload_async() -> void:
	if not on():
		return
	var m = GameData.config.get("hy3d_chests_map", {})
	if not (m is Dictionary):
		return
	var files: Array = []
	for k in m:
		var f := file_of(str(k))
		if f != "" and not _protos.has(f) and not _pre.has(f) and not files.has(f):
			files.append(f)
	if files.is_empty():
		return
	var box: Array = []
	box.resize(files.size())
	var task := WorkerThreadPool.add_task(func() -> void:
		for i in files.size():
			box[i] = _parse(files[i]), false, "hy3d_chests preload")
	for i in files.size():
		_pre[files[i]] = [task, box, i]


## Waits for a preload still parsing and frees the models never used (main.gd _exit_tree).
static func preload_clear() -> void:
	var waited := {}
	for f in _pre:
		var e: Array = _pre[f]
		if e.size() < 4 and not waited.has(int(e[0])):
			waited[int(e[0])] = true
			WorkerThreadPool.wait_for_task_completion(int(e[0]))
	for f in _pre:
		var r = _pre[f][1][int(_pre[f][2])]
		if r is Node and is_instance_valid(r):
			(r as Node).free()
	_pre.clear()


## The chest GLB as a scene (any thread), null when unreadable.
static func _parse(f: String) -> Node3D:
	var doc := GLTFDocument.new()
	var st := GLTFState.new()
	if doc.append_from_file(DIR + f + ".glb", st) != OK:
		return null
	return doc.generate_scene(st) as Node3D


static func proto(f: String) -> Array:
	if _protos.has(f):
		return _protos[f]
	var out: Array = [null, AABB()]
	var root: Node3D = null
	if _pre.has(f):
		var pe: Array = _pre[f]
		var task := int(pe[0])
		# (one task for all the files: waited for once, the others then just read their slot)
		_pre.erase(f)
		if pe.size() < 4:
			WorkerThreadPool.wait_for_task_completion(task)
			for v in _pre.values():
				if int(v[0]) == task:
					v.append(true)
		root = pe[1][int(pe[2])]
	else:
		root = _parse(f)
	if root != null:
		if root.get_node_or_null("LidPivot") != null:
			EnvAssets._toonify(root, false)
			root.name = "HY3DChest_" + f
			out = [root, EnvAssets._bounds(root)]
		elif root != null:
			root.free()
	if out[0] == null:
		push_warning("hy3d_chests: cannot read " + DIR + f + ".glb")
	_protos[f] = out
	return out


## Uniform scale of a kind's model (see the header).
static func scale_of(k: String) -> float:
	var f := file_of(k)
	if f == "":
		return 1.0
	var bb: AABB = proto(f)[1]
	var vis: Vector2 = SPRITE_VIS.get(k, Vector2(3.5, 3.2))
	var p := deg_to_rad(CAM_PITCH)
	var y := deg_to_rad(22.5)
	var sprite_a := vis.x * vis.y * cos(p)
	var mw := bb.size.x * cos(y) + bb.size.z * sin(y)
	var mh := bb.size.y * cos(p) + bb.size.z * sin(p)
	return size_k() * sqrt(sprite_a / maxf(0.0001, mw * mh))


## Model height in metres after the fit (the aura / sparkles / name tag are placed by it).
static func height(k: String) -> float:
	var f := file_of(k)
	return (proto(f)[1] as AABB).size.y * scale_of(k) if f != "" else 0.0


## Model footprint (x width, z depth) in metres after the fit.
static func foot(k: String) -> Vector2:
	var f := file_of(k)
	if f == "":
		return Vector2.ZERO
	var bb: AABB = proto(f)[1]
	return Vector2(bb.size.x, bb.size.z) * scale_of(k)


## A new model node "Model" for a kind (null when not mapped); lid closed, dimmed when `opened`.
static func make(k: String, opened: bool) -> Node3D:
	var f := file_of(k)
	if f == "":
		return null
	var pr: Array = proto(f)
	if pr[0] == null:
		return null
	var n := (pr[0] as Node3D).duplicate() as Node3D
	n.name = "Model"
	n.scale = Vector3.ONE * scale_of(k)
	n.set_meta("hy3d_chest", f)
	if opened:
		dim(n, f)
	made += 1
	return n


## Opened chests: every surface on a darker copy of its material (shared per model).
static func dim(n: Node3D, f: String) -> void:
	for mi in n.find_children("*", "MeshInstance3D", true, false):
		var m := mi as MeshInstance3D
		for s in m.mesh.get_surface_count():
			var src := m.get_active_material(s)
			var key := "%s|%s|%d" % [f, m.name, s]
			if not _dim.has(key):
				var d = src.duplicate() if src != null else null
				if d is ShaderMaterial:
					var a = (d as ShaderMaterial).get_shader_parameter("albedo")
					var c: Color = a if a is Color else Color.WHITE
					(d as ShaderMaterial).set_shader_parameter("albedo", Color(c.r * DIM, c.g * DIM, c.b * DIM * 1.04, c.a))
				elif d is BaseMaterial3D:
					(d as BaseMaterial3D).albedo_color = (d as BaseMaterial3D).albedo_color * Color(DIM, DIM, DIM * 1.04, 1)
				_dim[key] = d
			m.set_surface_override_material(s, _dim[key])


## Lid angle 0 (closed) .. 1 (open).
static func set_lid(n: Node3D, f: float) -> void:
	var p := n.get_node_or_null("LidPivot") as Node3D if n != null else null
	if p != null:
		p.rotation = Vector3(-deg_to_rad(LID_OPEN_DEG) * clampf(f, 0.0, 1.2), 0, 0)


static func lid(n: Node3D) -> float:
	var p := n.get_node_or_null("LidPivot") as Node3D if n != null else null
	return -p.rotation.x / deg_to_rad(LID_OPEN_DEG) if p != null else 0.0


## The lid swings open (a small overshoot, then settles) - played when this player opens the chest.
static func open_anim(n: Node3D) -> Tween:
	set_lid(n, 0.0)
	var tw := n.create_tween()
	tw.tween_interval(0.12)
	tw.tween_method(func(v: float): set_lid(n, v), 0.0, 1.08, 0.42).set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT)
	tw.tween_method(func(v: float): set_lid(n, v), 1.08, 1.0, 0.22).set_trans(Tween.TRANS_SINE)
	return tw


## Fade (camera-side occlusion of the hero): 1 = solid.
static func set_alpha(n: Node3D, a: float) -> void:
	for mi in n.find_children("*", "MeshInstance3D", true, false):
		(mi as GeometryInstance3D).transparency = clampf(1.0 - a, 0.0, 1.0)

# ---------------------------------------------------------------- placing

## Hits of a ray against static map geometry only (players / monsters / areas skipped). {} = none.
static func _ray(space: PhysicsDirectSpaceState3D, a: Vector3, b: Vector3) -> Dictionary:
	if space == null:
		return {}
	var q := PhysicsRayQueryParameters3D.create(a, b)
	q.collide_with_areas = false
	var ex: Array[RID] = []
	for i in 6:
		q.exclude = ex
		var h := space.intersect_ray(q)
		if h.is_empty():
			return {}
		if h.get("collider") is StaticBody3D:
			return h
		ex.append(h["rid"])
	return {}


## Ground height under a spot: the static floor within +-0.6 m of y = 0 (flat maps have no floor collider -> 0).
static func ground_y(space: PhysicsDirectSpaceState3D, at: Vector3) -> float:
	var h := _ray(space, Vector3(at.x, 0.6, at.z), Vector3(at.x, -0.6, at.z))
	if not h.is_empty() and (h["normal"] as Vector3).y > 0.7:
		return (h["position"] as Vector3).y
	return 0.0


## Free distance (max `far`) from the chest along the yaw (model front = +Z turned by yaw), at knee and chest height.
static func free_dist(space: PhysicsDirectSpaceState3D, at: Vector3, yaw: float, far: float = 6.0) -> float:
	var d := Vector3(sin(yaw), 0, cos(yaw))
	var best := far
	for hy in [0.5, 1.2]:
		var o := Vector3(at.x, at.y + hy, at.z)
		var h := _ray(space, o, o + d * far)
		if not h.is_empty():
			best = minf(best, o.distance_to(h["position"]))
	return best


## The facing (yaw, radians) of a chest at `at`: the most open of 16 directions, the default camera side (+Z) and
## its neighbours first on a tie (scores within 0.5 m).
static func face_yaw(space: PhysicsDirectSpaceState3D, at: Vector3) -> float:
	var best := 0.0
	var bs := -INF
	for i in 16:
		var yaw := TAU * float(i) / 16.0
		var s := free_dist(space, at, yaw) + 0.5 * cos(yaw)
		if s > bs + 0.001:
			bs = s
			best = yaw
	return best


## World AABBs of the visible props of the loaded world (trees, rocks, houses, fences...; not ground / grass / heroes /
## the chests themselves): [AABB, name]. `skip` = a node whose subtree is left out.
static func props(tree_root: Node, skip: Node = null) -> Array:
	var out: Array = []
	for n in tree_root.find_children("*", "GeometryInstance3D", true, false):
		var g := n as GeometryInstance3D
		if not g.is_visible_in_tree() or (skip != null and skip.is_ancestor_of(g)):
			continue
		if str(g.name).ends_with("Shadow"):
			continue
		var bad := false
		var p: Node = g
		while p != null:
			if p is CharacterBody3D or p is Camera3D or p is CanvasLayer or p.is_in_group("monsters") or p.is_in_group("mobs") \
					or p.is_in_group("npcs") or p.is_in_group("player_entities"):
				bad = true
				break
			p = p.get_parent()
		if bad:
			continue
		if g is MeshInstance3D and str(g.name).begins_with("FieldDress") and (g as MeshInstance3D).mesh != null:
			# a merged dressing chunk (many rocks / bushes in one mesh): its own vertices, not the chunk box
			var pts := PackedVector3Array()
			var xf := g.global_transform
			for v in (g as MeshInstance3D).mesh.get_faces():
				var w := xf * v
				if w.y > 0.4:
					pts.append(w)
			if not pts.is_empty():
				out.append([g.global_transform * (g as MeshInstance3D).mesh.get_aabb(), str(g.name), pts])
			continue
		if g is MultiMeshInstance3D:
			var mm := (g as MultiMeshInstance3D).multimesh
			if mm == null or mm.mesh == null or mm.mesh.get_aabb().size.y < 0.5:
				continue
			var lb := mm.mesh.get_aabb()
			for i in mm.instance_count:
				var b: AABB = (g.global_transform * mm.get_instance_transform(i)) * lb
				if b.size.y >= 0.5 and maxf(b.size.x, b.size.z) < 14.0:
					out.append([b, str(g.name)])
		elif g is MeshInstance3D and (g as MeshInstance3D).mesh != null:
			var b2: AABB = g.global_transform * (g as MeshInstance3D).mesh.get_aabb()
			if b2.size.y >= 0.5 and maxf(b2.size.x, b2.size.z) < 14.0 and b2.position.y < 3.0:
				out.append([b2, str(g.name)])
	return out


## Map colliders (StaticBody3D) inside the chest's box (`shrink` of the footprint, lifted 0.15 m): their names.
static func walls_at(space: PhysicsDirectSpaceState3D, k: String, pos: Vector3, yaw: float, shrink: float = 0.85) -> PackedStringArray:
	var out := PackedStringArray()
	if space == null:
		return out
	var fp := foot(k)
	var h := height(k)
	var box := BoxShape3D.new()
	box.size = Vector3(fp.x * shrink, h * 0.8, fp.y * shrink)
	var q := PhysicsShapeQueryParameters3D.new()
	q.shape = box
	q.collide_with_areas = false
	q.transform = Transform3D(Basis(Vector3.UP, yaw), pos + Vector3(0, 0.15 + h * 0.4, 0))
	for hh in space.intersect_shape(q, 8):
		if hh.get("collider") is StaticBody3D:
			out.append(str((hh["collider"] as Node).name))
	return out


## Visible props overlapping the chest's box (`shrink` of the footprint, more than 15 cm each way): their names.
static func props_at(prop_list: Array, k: String, pos: Vector3, shrink: float = 0.7) -> PackedStringArray:
	var out := PackedStringArray()
	var fp := foot(k)
	var h := height(k)
	var cb := AABB(pos + Vector3(-fp.x * shrink * 0.5, 0.2, -fp.y * shrink * 0.5), Vector3(fp.x * shrink, h * 0.7, fp.y * shrink))
	for pr in prop_list:
		if (pr as Array).size() > 2:
			if (pr[0] as AABB).intersects(cb):
				var n := 0
				for w in (pr[2] as PackedVector3Array):
					if cb.has_point(w):
						n += 1
						if n >= 3:
							out.append(str(pr[1]))
							break
			continue
		if (pr[0] as AABB).intersects(cb):
			var ib := (pr[0] as AABB).intersection(cb)
			if ib.size.x > 0.15 and ib.size.z > 0.15:
				out.append(str(pr[1]))
	return out


static var _props_key := ""
static var _props_list: Array = []
## settled spots of the current props key: "<kind>|<x>|<z>" -> [pos, yaw]
static var _spots := {}


## HITCH 2026-10-27: the props of `prop_list` that can touch a `k` chest nudged up to NUDGE_MAX m off `at` (props_at
## tests a prop's AABB against the chest box first, so props_at(props_near(..)) = props_at(prop_list) for those spots).
static func props_near(prop_list: Array, k: String, at: Vector3) -> Array:
	var fp := foot(k)
	var reach := NUDGE_MAX + maxf(fp.x, fp.y) + 1.0
	var near := AABB(Vector3(at.x - reach, -1.0e6, at.z - reach), Vector3(reach * 2.0, 2.0e6, reach * 2.0))
	return prop_list.filter(func(pr) -> bool: return (pr[0] as AABB).intersects(near))


## Places / turns a chest root (treasure_view.gd node) on its spot: ground height + facing; when the model there
## would stand inside a map collider or a visible prop (a cave wall, a tree), it is drawn up to NUDGE_MAX m off the
## spot, at the nearest clear place (VIEW ONLY: the server spot / open range stay). Returns [yaw, y, offset].
const NUDGE_MAX := 2.25
static func settle(root: Node3D, at: Vector3, k: String = "", map_id: String = "", fresh: bool = false) -> Array:
	var space: PhysicsDirectSpaceState3D = root.get_world_3d().direct_space_state if root.is_inside_tree() else null
	var pos := Vector3(at.x, ground_y(space, at), at.z)
	var yaw := face_yaw(space, pos)
	var off := Vector3.ZERO
	var c_skip := false
	if k != "" and space != null and file_of(k) != "":
		var key := "%s|%d" % [map_id, root.get_tree().root.get_instance_id()]
		if key != _props_key or map_id == "":
			_props_key = key
			_props_list = props(root.get_tree().root, root.get_parent())
			_spots.clear()
		var sk := "%s|%.2f|%.2f" % [k, at.x, at.z]
		if not fresh and _spots.has(sk):
			pos = _spots[sk][0]
			yaw = _spots[sk][1]
			off = Vector3(pos.x - at.x, 0, pos.z - at.z)
			c_skip = true
		# HITCH 2026-10-27: only the props within reach of this spot (a nudged chest scanned all ~4,000 of the map's props
		# for each of up to 144 tries: 45-210 ms a chest, twice; the same answer - props_at tests the AABB first)
		var local: Array = props_near(_props_list, k, at)
		# 0 = clear; walls weigh more than props
		var cost := func(p: Vector3, y: float) -> int:
			return walls_at(space, k, p, y, 0.95).size() * 3 + props_at(local, k, p, 0.8).size()
		var c0: int = 0 if c_skip else cost.call(pos, yaw)
		if c0 > 0:
			var best := [c0, pos, yaw]
			var r := 0.25
			while r <= NUDGE_MAX + 0.001 and int(best[0]) > 0:
				for i in 16:
					var a := TAU * float(i) / 16.0
					var q := Vector3(at.x + sin(a) * r, 0, at.z + cos(a) * r)
					q.y = ground_y(space, q)
					var y2 := face_yaw(space, q)
					var cq: int = cost.call(q, y2)
					if cq < int(best[0]):
						best = [cq, q, y2]
						if cq == 0:
							break
				r += 0.25
			pos = best[1]
			yaw = best[2]
			off = Vector3(pos.x - at.x, 0, pos.z - at.z)
		_spots[sk] = [pos, yaw]
	root.position = pos
	var m := root.get_node_or_null("Model") as Node3D
	if m != null:
		m.rotation = Vector3(0, yaw, 0)
	root.set_meta("yaw", yaw)
	root.set_meta("nudge", off)
	return [yaw, pos.y, off]


## Drops the cached prop boxes (the map scenery changed).
static func forget_props() -> void:
	_props_key = ""
	_props_list = []
	_spots.clear()
