## A player's figure (A2): the islander that tools/models/figure.py builds in Blender, ## hung on a hierarchy of pivots and animated by an AnimationTree. ## ## The parts are rigid OBJ models, one per limb, each with its origin at the joint it ## turns about (assets/models/figure/, with figure.json giving the joints). Debian's ## Blender can't export a skinned glTF, so the figure is jointed like a carved toy ## rather than skinned, which suits the folk-art look. ## ## Every animation is built here in code from key poses (FigurePoses), and played by ## one AnimationTree: ## ## move Transition: ground (idle, walk, run by speed), crouch (still and ## creeping by speed), air, skydive, glide, swim, aboard ## hold filtered to the arms: how the held item is carried (long, short, carry) ## reload, use filtered to the arms and head, blended in while they last ## act OneShot on the upper body: fire_long, fire_short, swing, throw, build ## hit OneShot flinch ## ## drive() sets the tree's parameters from a SimEntity, which on a network client is ## only what snapshots and FX replicate (position, look, the FLAG_ bits, the held ## item and health), and trigger() plays one-off actions from FX records. Nothing ## here reads input or any other client-only state. advance() steps the tree; the ## tree runs in manual mode so tests and captures can pose a figure exactly. class_name FigureRig extends Node3D const MODEL_DIR: String = "res://assets/models/figure" ## Joints the animations turn (and, for the hips, move). The spine and hands aren't ## animated: the code turns the spine with the player's pitch and points the hand ## along the aim. const ANIMATED: Array[String] = [ "hips", "waist", "neck", "shoulder_r", "elbow_r", "shoulder_l", "elbow_l", "hip_r", "knee_r", "hip_l", "knee_l", ] ## Joint -> its parent pivot. "spine" sits on the waist joint and carries the chest. const PARENT: Dictionary = { "hips": "", "waist": "hips", "spine": "waist", "neck": "spine", "shoulder_r": "spine", "elbow_r": "shoulder_r", "shoulder_l": "spine", "elbow_l": "shoulder_l", "hip_r": "hips", "knee_r": "hip_r", "hip_l": "hips", "knee_l": "hip_l", "kite": "", } ## Part model -> the joint pivot it hangs on. const PART_JOINT: Dictionary = { "pelvis": "hips", "torso": "spine", "head": "neck", "upper_arm_r": "shoulder_r", "forearm_r": "elbow_r", "upper_arm_l": "shoulder_l", "forearm_l": "elbow_l", "thigh_r": "hip_r", "shin_r": "knee_r", "thigh_l": "hip_l", "shin_l": "knee_l", "kite": "kite", } ## Material names in the part models -> Palette colours. COAT and COAT_DARK are the ## player's own oilskin. const COLOURS: Dictionary = { "TAR": Palette.TAR, "TAR_WEATHERED": Palette.TAR_WEATHERED, "SKIN": Palette.SKIN, "INK": Palette.INK, "BARK": Palette.BARK, "CANVAS": Palette.CANVAS, "GILT": Palette.GILT, "PLANK": Palette.PLANK, "OCHRE_RED": Palette.OCHRE_RED, "TANNED_SAIL": Palette.TANNED_SAIL, "SALT": Palette.SALT, } const COAT_SHADE: float = 0.28 ## The states of `move`, in input order. const STATES: Array[String] = ["ground", "crouch", "air", "skydive", "glide", "swim", "aboard", "downed"] const HOLDS: Array[String] = ["long", "short", "carry"] const ACTIONS: Array[String] = ["fire_long", "fire_short", "swing", "throw", "build"] ## How long a figure must be off the ground before it's drawn in the air, so steps ## down a slope don't flicker into a leap. const AIR_DELAY: float = 0.12 ## How quickly the drawn speed follows the real one, per second. const SPEED_FOLLOW: float = 10.0 ## How much of the look's pitch the chest takes; the held item takes all of it. const SPINE_PITCH: float = 0.35 ## A part's surfaces, by how they're lit (see _merged()). const FINISH_COAT: String = "FINISH_COAT" const FINISH_GILT: String = "FINISH_GILT" const FINISH_PLAIN: String = "FINISH_PLAIN" const FINISHES: Array[String] = [FINISH_COAT, FINISH_GILT, FINISH_PLAIN] static var _layout: Dictionary = {} static var _meshes: Dictionary = {} static var _finishes: Dictionary = {} static var _library: AnimationLibrary = null var coat: Color = Palette.OILSKIN var tree: AnimationTree ## Joint name -> its pivot node. var joints: Dictionary = {} ## The state, hold and speed last driven, for tests and captures. var state: String = "ground" var hold: String = "long" var speed: float = 0.0 var _hand: Node3D var _held: MeshInstance3D var _kite: Node3D var _pitch: float = 0.0 var _holding: bool = true var _airborne: float = 0.0 var _last_position: Vector3 = Vector3.INF var _last_health: int = -1 var _reload: float = 0.0 var _use: float = 0.0 var _reloading: bool = false var _using: bool = false ## Builds the figure in `coat_colour`. func _init(coat_colour: Color = Palette.OILSKIN) -> void: coat = coat_colour var layout: Dictionary = FigureRig.layout() var at: Dictionary = layout.get("joints", {}) for joint: String in PARENT: var pivot: Node3D = Node3D.new() pivot.name = joint var parent_name: String = PARENT[joint] var place: Vector3 = _vector(at.get("waist" if joint == "spine" else joint, [0, 0, 0])) if parent_name != "": var parent_joint: String = "waist" if parent_name == "spine" else parent_name place -= _vector(at.get(parent_joint, [0, 0, 0])) pivot.position = place joints[joint] = pivot (self if parent_name == "" else joints[parent_name] as Node3D).add_child(pivot) for part: String in PART_JOINT: var mesh: ArrayMesh = FigureRig.part_mesh(part, coat) if mesh == null: continue var instance: MeshInstance3D = MeshInstance3D.new() instance.name = part instance.mesh = mesh (joints[PART_JOINT[part]] as Node3D).add_child(instance) _kite = joints["kite"] _kite.visible = false _hand = Node3D.new() _hand.name = "hand_r" _hand.position = _vector(layout.get("hand_r", [-0.24, 0.86, 0.03])) - _vector(at.get("elbow_r", [0, 0, 0])) (joints["elbow_r"] as Node3D).add_child(_hand) _held = MeshInstance3D.new() _held.name = "Held" _hand.add_child(_held) tree = _build_tree() add_child(tree) ## figure.json: joints, parts and hands. static func layout() -> Dictionary: if _layout.is_empty(): var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(MODEL_DIR + "/figure.json")) _layout = parsed if parsed is Dictionary else {"joints": {}} return _layout ## A part's model painted for a coat colour; shared, so don't change it. static func part_mesh(part: String, coat_colour: Color) -> ArrayMesh: var key: String = "%s@%s" % [part, coat_colour.to_html(false)] if _meshes.has(key): return _meshes[key] var path: String = "%s/%s.obj" % [MODEL_DIR, part] var made: ArrayMesh = null if ResourceLoader.exists(path): var source: Mesh = load(path) as Mesh if source != null: made = _merged(source, coat_colour) made.resource_name = key _meshes[key] = made return made ## H1: one surface per finish instead of one per colour, with each Palette colour ## carried as a vertex colour. The model's surfaces are separate draw calls in every ## pass, and 24 figures crowded on the ship passed the draw-call budget; merged, a ## figure costs a third of the draws and looks the same. Each surface is named after ## its finish: FINISH_COAT, FINISH_GILT or FINISH_PLAIN. static func _merged(source: Mesh, coat_colour: Color) -> ArrayMesh: var tools: Dictionary = {} for surface: int in source.get_surface_count(): var material: Material = source.surface_get_material(surface) var name: String = material.resource_name if material != null else "" var finish: String = finish_of(name) if not tools.has(finish): var tool: SurfaceTool = SurfaceTool.new() tool.begin(Mesh.PRIMITIVE_TRIANGLES) tools[finish] = tool var arrays: Array = source.surface_get_arrays(surface) var count: int = (arrays[Mesh.ARRAY_VERTEX] as PackedVector3Array).size() var colours: PackedColorArray = PackedColorArray() colours.resize(count) colours.fill(colour_of(name, coat_colour)) arrays[Mesh.ARRAY_COLOR] = colours (tools[finish] as SurfaceTool).append_from(_array_mesh(arrays), 0, Transform3D.IDENTITY) var made: ArrayMesh = ArrayMesh.new() for finish: String in FINISHES: if not tools.has(finish): continue (tools[finish] as SurfaceTool).commit(made) made.surface_set_material(made.get_surface_count() - 1, finish_material(finish)) made.surface_set_name(made.get_surface_count() - 1, finish) return made static func _array_mesh(arrays: Array) -> ArrayMesh: var mesh: ArrayMesh = ArrayMesh.new() mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays) return mesh ## How a model material is lit: oilskin coat, gilt, or everything else. static func finish_of(material_name: String) -> String: if material_name.begins_with("COAT"): return FINISH_COAT if material_name == "GILT": return FINISH_GILT return FINISH_PLAIN ## The shared material for a finish; the colour comes from the vertices. static func finish_material(finish: String) -> StandardMaterial3D: if not _finishes.has(finish): var paint: StandardMaterial3D = StandardMaterial3D.new() paint.vertex_color_use_as_albedo = true paint.vertex_color_is_srgb = true paint.roughness = 0.6 if finish == FINISH_COAT else 0.88 if finish == FINISH_GILT: paint.metallic = 0.35 paint.resource_name = finish _finishes[finish] = paint return _finishes[finish] ## The Palette colour of a part's material, with COAT the player's own. static func colour_of(material_name: String, coat_colour: Color) -> Color: if material_name == "COAT": return coat_colour if material_name == "COAT_DARK": return coat_colour.darkened(COAT_SHADE) return COLOURS.get(material_name, Palette.HOLD_SHADOW) ## Every animation the figure has, built once from FigurePoses. static func library() -> AnimationLibrary: if _library == null: _library = AnimationLibrary.new() var rest: Dictionary = layout().get("joints", {}) for name: String in FigurePoses.clips(): _library.add_animation(name, FigurePoses.animation(name, rest)) return _library static func clear() -> void: _meshes.clear() _finishes.clear() _layout.clear() _library = null func hand() -> Node3D: return _hand func held() -> MeshInstance3D: return _held func kite() -> Node3D: return _kite ## Sets the tree from an entity's replicated state. `delta` is the time since the last ## drive, for the speed it derives from movement and for the delay before the air. func drive(entity: SimEntity, delta: float) -> void: var flat: Vector3 = Vector3(entity.velocity.x, 0.0, entity.velocity.z) var moved: float = flat.length() if moved == 0.0 and _last_position != Vector3.INF and delta > 0.0: var step: Vector3 = entity.position - _last_position moved = Vector2(step.x, step.z).length() / delta # A jump in place (a correction, a respawn) isn't running. if moved > Tuning.SLIDE_MAX_SPEED * 2.0: moved = 0.0 _last_position = entity.position speed = moved if delta <= 0.0 else lerpf(speed, moved, clampf(delta * SPEED_FOLLOW, 0.0, 1.0)) _airborne = 0.0 if entity.on_ground or entity.swimming else _airborne + delta state = state_of(entity, _airborne >= AIR_DELAY) _holding = state in ["ground", "crouch", "air"] hold = hold_of(EntityView.held_code(entity)) _reloading = entity.reload_ticks > 0 and _holding _using = entity.use_ticks > 0 and _holding if _last_health >= 0 and entity.health < _last_health and not entity.eliminated: flinch() _last_health = entity.health _pitch = float(entity.pitch) / PlayerCommand.PITCH_MAX * (PI * 0.5) _kite.visible = state == "glide" _hand.visible = _holding tree.set("parameters/move/transition_request", state) tree.set("parameters/ground/blend_position", speed) tree.set("parameters/crouch/blend_position", speed) tree.set("parameters/ground_pace/scale", clampf(speed / Tuning.WALK_SPEED, 0.75, 1.3) if speed > 0.3 else 1.0) tree.set("parameters/hold/transition_request", hold) tree.set("parameters/holding/blend_amount", 1.0 if _holding else 0.0) ## Which of STATES an entity is drawn in. static func state_of(entity: SimEntity, airborne: bool) -> String: match entity.drop_state: Drop.ABOARD: return "aboard" Drop.FREEFALL: return "skydive" Drop.GLIDING: return "glide" if entity.swimming: return "swim" if entity.downed: # Duos (M7): down on hands and knees, crawling. return "downed" if airborne: return "air" return "crouch" if entity.crouching else "ground" ## How an item is carried: long things in both hands, small weapons in one, and ## everything else (tonics, bandages, kegs) held up in front. static func hold_of(code: int) -> String: var id: String = ItemModels.id_of(code) if ItemModels.info(id).get("support") != null: return "long" var def: ItemDef = ItemCatalog.get_def(code) if def != null and def.is_weapon() and id != "powder_keg": return "short" return "carry" ## Plays the one-off action an FX record shows: a shot, a swing or throw, a harvest ## hit (a swing) or a piece placed. func hear(record: Dictionary) -> void: match int(record.get("kind", 0)): NetFx.SHOT: var id: String = ItemModels.id_of(int(record.get("item", -1))) if id == ItemCatalog.BOATHOOK: act("swing") elif id == "powder_keg": act("throw") else: act("fire_long" if hold_of(int(record["item"])) == "long" else "fire_short") NetFx.PLACE: act("build") ## Plays one of ACTIONS on the upper body, from its start. func act(action: String) -> void: if not ACTIONS.has(action) or not _holding: return tree.set("parameters/action/transition_request", action) tree.set("parameters/act/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE) func flinch() -> void: tree.set("parameters/hit/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE) ## Steps the animation by `delta` and points the chest and held item along the look. func advance(delta: float) -> void: _reload = move_toward(_reload, 1.0 if _reloading else 0.0, delta * 6.0) _use = move_toward(_use, 1.0 if _using else 0.0, delta * 6.0) tree.set("parameters/reload/blend_amount", _reload) tree.set("parameters/use/blend_amount", _use) tree.advance(delta) _aim() ## Whether an action or flinch is playing. func acting() -> bool: return bool(tree.get("parameters/act/active")) or bool(tree.get("parameters/hit/active")) ## The hand's orientation relative to the figure. func hand_basis() -> Basis: return relative(_hand).basis ## A node's transform relative to this figure, without needing the scene tree. func relative(node: Node3D) -> Transform3D: var out: Transform3D = Transform3D.IDENTITY var at: Node = node while at != null and at != self: out = (at as Node3D).transform * out at = at.get_parent() return out func _aim() -> void: var spine: Node3D = joints["spine"] spine.rotation = Vector3(-_pitch * SPINE_PITCH if _holding else 0.0, 0.0, 0.0) # The item points along the look whatever the arm is doing; the arm only places it. var parent: Transform3D = relative(_hand.get_parent() as Node3D) _hand.basis = parent.basis.orthonormalized().inverse() * Basis(Vector3.RIGHT, -_pitch) func _build_tree() -> AnimationTree: var made: AnimationTree = AnimationTree.new() made.name = "Animation" made.add_animation_library("", FigureRig.library()) made.callback_mode_process = AnimationMixer.ANIMATION_CALLBACK_MODE_PROCESS_MANUAL made.deterministic = true var root: AnimationNodeBlendTree = AnimationNodeBlendTree.new() var ground: AnimationNodeBlendSpace1D = AnimationNodeBlendSpace1D.new() ground.add_blend_point(_clip("idle"), 0.0, -1, &"idle") ground.add_blend_point(_clip("walk"), Tuning.WALK_SPEED, -1, &"walk") ground.add_blend_point(_clip("run"), Tuning.SPRINT_SPEED, -1, &"run") ground.min_space = 0.0 ground.max_space = Tuning.SPRINT_SPEED ground.sync = true root.add_node("ground", ground) root.add_node("ground_pace", AnimationNodeTimeScale.new()) root.connect_node("ground_pace", 0, "ground") var crouch: AnimationNodeBlendSpace1D = AnimationNodeBlendSpace1D.new() crouch.add_blend_point(_clip("crouch_idle"), 0.0, -1, &"crouch_idle") crouch.add_blend_point(_clip("crouch_walk"), Tuning.CROUCH_SPEED, -1, &"crouch_walk") crouch.min_space = 0.0 crouch.max_space = Tuning.CROUCH_SPEED crouch.sync = true root.add_node("crouch", crouch) var move: AnimationNodeTransition = AnimationNodeTransition.new() move.xfade_time = 0.18 move.input_count = STATES.size() for index: int in STATES.size(): move.set_input_name(index, STATES[index]) root.add_node("move", move) root.connect_node("move", 0, "ground_pace") root.connect_node("move", 1, "crouch") for index: int in range(2, STATES.size()): root.add_node("clip_" + STATES[index], _clip(STATES[index])) root.connect_node("move", index, "clip_" + STATES[index]) var holds: AnimationNodeTransition = AnimationNodeTransition.new() holds.xfade_time = 0.15 holds.input_count = HOLDS.size() for index: int in HOLDS.size(): holds.set_input_name(index, HOLDS[index]) root.add_node("hold_" + HOLDS[index], _clip("hold_" + HOLDS[index])) root.add_node("hold", holds) for index: int in HOLDS.size(): root.connect_node("hold", index, "hold_" + HOLDS[index]) var holding: AnimationNodeBlend2 = _filtered(AnimationNodeBlend2.new(), FigurePoses.ARMS) as AnimationNodeBlend2 root.add_node("holding", holding) root.connect_node("holding", 0, "move") root.connect_node("holding", 1, "hold") var last: String = "holding" for layer: String in ["reload", "use"]: root.add_node("clip_" + layer, _clip(layer)) root.add_node(layer, _filtered(AnimationNodeBlend2.new(), FigurePoses.ARMS_AND_HEAD)) root.connect_node(layer, 0, last) root.connect_node(layer, 1, "clip_" + layer) last = layer var actions: AnimationNodeTransition = AnimationNodeTransition.new() actions.xfade_time = 0.0 actions.input_count = ACTIONS.size() for index: int in ACTIONS.size(): actions.set_input_name(index, ACTIONS[index]) root.add_node("clip_" + ACTIONS[index], _clip(ACTIONS[index])) root.add_node("action", actions) for index: int in ACTIONS.size(): root.connect_node("action", index, "clip_" + ACTIONS[index]) var act_shot: AnimationNodeOneShot = _filtered(AnimationNodeOneShot.new(), FigurePoses.UPPER) as AnimationNodeOneShot act_shot.fadein_time = 0.04 act_shot.fadeout_time = 0.12 root.add_node("act", act_shot) root.connect_node("act", 0, last) root.connect_node("act", 1, "action") root.add_node("clip_flinch", _clip("flinch")) var hit: AnimationNodeOneShot = _filtered(AnimationNodeOneShot.new(), FigurePoses.TORSO) as AnimationNodeOneShot hit.fadein_time = 0.03 hit.fadeout_time = 0.1 root.add_node("hit", hit) root.connect_node("hit", 0, "act") root.connect_node("hit", 1, "clip_flinch") root.connect_node("output", 0, "hit") made.tree_root = root made.root_node = NodePath("..") made.active = true return made func _clip(name: String) -> AnimationNodeAnimation: var node: AnimationNodeAnimation = AnimationNodeAnimation.new() node.animation = name return node func _filtered(node: AnimationNode, filtered: Array[String]) -> AnimationNode: node.filter_enabled = true for joint: String in filtered: node.set_filter_path(NodePath(FigurePoses.path_of(joint)), true) return node static func _vector(values: Variant) -> Vector3: var list: Array = values if values is Array else [0, 0, 0] return Vector3(float(list[0]), float(list[1]), float(list[2]))