268 lines
10 KiB
GDScript
268 lines
10 KiB
GDScript
extends SceneTree
|
|
## Gives the ithappy farm prefabs that farm.tscn places their collision, so every instance (and
|
|
## every later placement of the same prefab) collides. Each processed prefab gets a "Collision"
|
|
## StaticBody3D (layer 1, world) holding one CollisionShape3D fitted to its mesh:
|
|
## * ground/, road/ (terrain folders): trimesh of the mesh, so the player walks on the visible
|
|
## surface instead of the flat floor under it (tile and curb edges are ramps).
|
|
## * plant/, animal/: none. Crops are walk-through; animals become moving entities (Step 8).
|
|
## * prop/fence_018 (the open gate) carries a hand-made thin box along its panel, so it is
|
|
## skipped like any prefab that already has collision.
|
|
## * tree/ trees: cylinder around the trunk, widened to half the reach of foliage hanging below
|
|
## 1.5 m; tree/ bushes: cylinder at 80 % of the bush's mean half-width; barrels: cylinder.
|
|
## * box_*: the pack's unit cube, placed scaled flat as concrete pads, so its top is inset 5 %
|
|
## per side; on a pad that turns the 0.2 m edge into a ramp (a plain box edge blocks the
|
|
## capsule), on a cube-shaped crate the sides stay near vertical.
|
|
## * everything else: box around the geometry in the first 2 m above its base (the footprint,
|
|
## ignoring roof overhangs), spanning the full mesh height.
|
|
## Prefabs that already contain a CollisionShape3D are left alone, so hand-tuned shapes survive;
|
|
## --force regenerates the "Collision" bodies this tool made (other collision is still kept).
|
|
## Re-run after placing new prefab types (editor closed):
|
|
## godot --headless --path . --script res://game/tools/build_prop_collision.gd [-- --force]
|
|
|
|
const SCENE := "res://game/scenes/farm.tscn"
|
|
const PREFAB_DIR := "res://assets/farm/ithappy/farm/prefabs/assets/"
|
|
const BODY_NAME := "Collision"
|
|
## Folders whose prefabs are walked on rather than around.
|
|
const WALKABLE := ["ground", "road", "field", "landscape", "mountain"]
|
|
const NO_COLLISION := ["plant", "animal"]
|
|
## Band above the prefab's base that counts as its footprint (about the player's height).
|
|
const FOOTPRINT_HEIGHT := 2.0
|
|
const TRUNK_HEIGHT := 0.5
|
|
const LOW_FOLIAGE_HEIGHT := 1.5
|
|
const LOW_FOLIAGE_SHARE := 0.5
|
|
const TRUNK_MARGIN := 0.05
|
|
const BUSH_SHARE := 0.8
|
|
const SLAB_TOP_INSET := 0.05
|
|
|
|
|
|
func _initialize() -> void:
|
|
var ok := _build("--force" in OS.get_cmdline_user_args())
|
|
quit(0 if ok else 1)
|
|
|
|
|
|
func _build(force: bool) -> bool:
|
|
var farm := load(SCENE) as PackedScene
|
|
if farm == null:
|
|
push_error("missing " + SCENE)
|
|
return false
|
|
var state := farm.get_state()
|
|
var placed := {}
|
|
for i in state.get_node_count():
|
|
var instance := state.get_node_instance(i)
|
|
if instance != null and instance.resource_path.begins_with(PREFAB_DIR):
|
|
placed[instance.resource_path] = true
|
|
var paths: Array = placed.keys()
|
|
paths.sort()
|
|
var ok := true
|
|
var added := 0
|
|
for path: String in paths:
|
|
var result := _process_prefab(path, force)
|
|
if result.begins_with("error"):
|
|
push_error("%s: %s" % [path, result])
|
|
ok = false
|
|
elif result.begins_with("added"):
|
|
added += 1
|
|
print("%-44s %s" % [path.trim_prefix(PREFAB_DIR), result])
|
|
print("%d placed prefabs, collision added to %d" % [paths.size(), added])
|
|
return ok
|
|
|
|
|
|
func _process_prefab(path: String, force: bool) -> String:
|
|
var scene := load(path) as PackedScene
|
|
if scene == null:
|
|
return "error: not a scene"
|
|
var root := scene.instantiate(PackedScene.GEN_EDIT_STATE_MAIN) as Node3D
|
|
if root == null:
|
|
return "error: root is not a Node3D"
|
|
var previous := root.get_node_or_null(BODY_NAME)
|
|
if force and previous is StaticBody3D:
|
|
root.remove_child(previous)
|
|
previous.free()
|
|
if not root.find_children("*", "CollisionShape3D", true, false).is_empty():
|
|
root.free()
|
|
return "kept existing collision"
|
|
var kind := _kind(path)
|
|
if kind == "none":
|
|
root.free()
|
|
return "no collision (walk-through)"
|
|
var faces := _faces(root)
|
|
if faces.is_empty():
|
|
root.free()
|
|
return "error: no mesh faces"
|
|
var shape := _fit(kind, faces)
|
|
var description := _describe(shape)
|
|
var body := StaticBody3D.new()
|
|
body.name = BODY_NAME
|
|
root.add_child(body)
|
|
body.owner = root
|
|
body.add_child(shape)
|
|
shape.owner = root
|
|
root.scene_file_path = ""
|
|
var uid := ResourceLoader.get_resource_uid(path)
|
|
var packed := PackedScene.new()
|
|
var err := packed.pack(root)
|
|
root.free()
|
|
if err == OK:
|
|
err = ResourceSaver.save(packed, path)
|
|
if err == OK:
|
|
err = _restore_uids(path, uid)
|
|
if err != OK:
|
|
return "error %d while saving" % err
|
|
return "added " + description
|
|
|
|
|
|
func _kind(path: String) -> String:
|
|
var folder := path.get_base_dir().get_file()
|
|
var file := path.get_file().get_basename()
|
|
if folder in NO_COLLISION:
|
|
return "none"
|
|
if folder in WALKABLE:
|
|
return "trimesh"
|
|
if file.begins_with("box_"):
|
|
return "slab"
|
|
if folder == "tree":
|
|
return "bush" if file.begins_with("bush") else "trunk"
|
|
if file.begins_with("barrel"):
|
|
return "cylinder"
|
|
return "box"
|
|
|
|
|
|
func _fit(kind: String, faces: PackedVector3Array) -> CollisionShape3D:
|
|
var node := CollisionShape3D.new()
|
|
node.name = "CollisionShape3D"
|
|
var aabb := AABB(faces[0], Vector3.ZERO)
|
|
for v in faces:
|
|
aabb = aabb.expand(v)
|
|
var base := maxf(aabb.position.y, 0.0)
|
|
var mid_y := aabb.get_center().y
|
|
match kind:
|
|
"trimesh":
|
|
var mesh_shape := ConcavePolygonShape3D.new()
|
|
mesh_shape.set_faces(faces)
|
|
node.shape = mesh_shape
|
|
"slab":
|
|
var hull := ConvexPolygonShape3D.new()
|
|
var inset := aabb.size * SLAB_TOP_INSET
|
|
var lo := aabb.position
|
|
var hi := aabb.end
|
|
hull.points = PackedVector3Array([
|
|
Vector3(lo.x, lo.y, lo.z), Vector3(hi.x, lo.y, lo.z),
|
|
Vector3(hi.x, lo.y, hi.z), Vector3(lo.x, lo.y, hi.z),
|
|
Vector3(lo.x + inset.x, hi.y, lo.z + inset.z), Vector3(hi.x - inset.x, hi.y, lo.z + inset.z),
|
|
Vector3(hi.x - inset.x, hi.y, hi.z - inset.z), Vector3(lo.x + inset.x, hi.y, hi.z - inset.z),
|
|
])
|
|
node.shape = hull
|
|
"trunk":
|
|
var trunk := _band_points(faces, base, base + TRUNK_HEIGHT)
|
|
var center := _rect(trunk).get_center()
|
|
var foliage := _band_points(faces, base, base + LOW_FOLIAGE_HEIGHT)
|
|
var radius := maxf(_reach(trunk, center) + TRUNK_MARGIN, _reach(foliage, center) * LOW_FOLIAGE_SHARE)
|
|
node.shape = _cylinder(radius, aabb.size.y)
|
|
node.position = Vector3(center.x, mid_y, center.y)
|
|
"bush", "cylinder":
|
|
var rect := _rect(_band_points(faces, base, base + FOOTPRINT_HEIGHT))
|
|
var radius := maxf(rect.size.x, rect.size.y) * 0.5
|
|
if kind == "bush":
|
|
radius = (rect.size.x + rect.size.y) * 0.25 * BUSH_SHARE
|
|
node.shape = _cylinder(radius, aabb.size.y)
|
|
node.position = Vector3(rect.get_center().x, mid_y, rect.get_center().y)
|
|
_:
|
|
var rect := _rect(_band_points(faces, base, base + FOOTPRINT_HEIGHT))
|
|
var box := BoxShape3D.new()
|
|
box.size = Vector3(rect.size.x, aabb.size.y, rect.size.y)
|
|
node.shape = box
|
|
node.position = Vector3(rect.get_center().x, mid_y, rect.get_center().y)
|
|
return node
|
|
|
|
|
|
## Every mesh triangle of the prefab, in the prefab root's space.
|
|
func _faces(root: Node3D) -> PackedVector3Array:
|
|
var faces := PackedVector3Array()
|
|
for mesh_instance: MeshInstance3D in root.find_children("*", "MeshInstance3D", true, false):
|
|
if mesh_instance.mesh == null:
|
|
continue
|
|
var to_root := mesh_instance.transform
|
|
var parent := mesh_instance.get_parent()
|
|
while parent != root:
|
|
if parent is Node3D:
|
|
to_root = (parent as Node3D).transform * to_root
|
|
parent = parent.get_parent()
|
|
for v in mesh_instance.mesh.get_faces():
|
|
faces.append(to_root * v)
|
|
return faces
|
|
|
|
|
|
## XZ corners of the faces clipped to heights lo..hi: triangle corners inside the band plus the
|
|
## points where triangle edges cross its two planes.
|
|
func _band_points(faces: PackedVector3Array, lo: float, hi: float) -> PackedVector2Array:
|
|
var points := PackedVector2Array()
|
|
for t in range(0, faces.size(), 3):
|
|
for i in 3:
|
|
var p := faces[t + i]
|
|
var q := faces[t + (i + 1) % 3]
|
|
if p.y >= lo and p.y <= hi:
|
|
points.append(Vector2(p.x, p.z))
|
|
for h: float in [lo, hi]:
|
|
if (p.y - h) * (q.y - h) < 0.0:
|
|
var cross := p.lerp(q, (h - p.y) / (q.y - p.y))
|
|
points.append(Vector2(cross.x, cross.z))
|
|
return points
|
|
|
|
|
|
func _rect(points: PackedVector2Array) -> Rect2:
|
|
var rect := Rect2(points[0], Vector2.ZERO)
|
|
for p in points:
|
|
rect = rect.expand(p)
|
|
return rect
|
|
|
|
|
|
func _reach(points: PackedVector2Array, center: Vector2) -> float:
|
|
var reach := 0.0
|
|
for p in points:
|
|
reach = maxf(reach, p.distance_to(center))
|
|
return reach
|
|
|
|
|
|
func _cylinder(radius: float, height: float) -> CylinderShape3D:
|
|
var cylinder := CylinderShape3D.new()
|
|
cylinder.radius = radius
|
|
cylinder.height = height
|
|
return cylinder
|
|
|
|
|
|
## ResourceSaver only writes UIDs when the editor supplies them, so this headless save drops the
|
|
## scene's own uid and its ext_resource uids. Put them back, or references by uid (farm.tscn's)
|
|
## would fall back to paths and the editor would hand the prefab a new uid.
|
|
func _restore_uids(path: String, uid: int) -> Error:
|
|
var text := FileAccess.get_file_as_string(path)
|
|
if text.is_empty():
|
|
return FileAccess.get_open_error()
|
|
var lines := text.split("\n")
|
|
for i in lines.size():
|
|
var line := lines[i]
|
|
if line.contains(" uid="):
|
|
continue
|
|
if line.begins_with("[gd_scene") and uid != ResourceUID.INVALID_ID:
|
|
lines[i] = line.trim_suffix("]") + ' uid="%s"]' % ResourceUID.id_to_text(uid)
|
|
elif line.begins_with("[ext_resource"):
|
|
var ext_uid := ResourceLoader.get_resource_uid(line.get_slice(' path="', 1).get_slice('"', 0))
|
|
if ext_uid != ResourceUID.INVALID_ID:
|
|
lines[i] = line.replace(' path="', ' uid="%s" path="' % ResourceUID.id_to_text(ext_uid))
|
|
var file := FileAccess.open(path, FileAccess.WRITE)
|
|
if file == null:
|
|
return FileAccess.get_open_error()
|
|
file.store_string("\n".join(lines))
|
|
return OK
|
|
|
|
|
|
func _describe(node: CollisionShape3D) -> String:
|
|
var shape := node.shape
|
|
if shape is BoxShape3D:
|
|
var s := (shape as BoxShape3D).size
|
|
return "box %.2f x %.2f x %.2f" % [s.x, s.y, s.z]
|
|
if shape is CylinderShape3D:
|
|
var c := shape as CylinderShape3D
|
|
return "cylinder r %.2f h %.2f" % [c.radius, c.height]
|
|
if shape is ConvexPolygonShape3D:
|
|
return "ramped slab"
|
|
return "trimesh %d triangles" % ((shape as ConcavePolygonShape3D).get_faces().size() / 3)
|