Feature: model config (facing/scale/tint) + animation loop fix

SERVER
- CardAsset gains ModelFacingDirection (string?), ModelScale (float?),
  ModelTintColor (string?), ModelTintMaskUrl (string?) columns.
- CardAssetDto and ContentDtoMapper updated to expose them.
- EF migration AddModelConfig applied to pg-forge-01 / SOR DB.

CLIENT (game_screen.gd)
Animation loop:
- GLB standard: first 5 frames (ANIM_TRANSITION_SECS = 5/30s) are
  entry frames that blend from idle into the action.  Looping
  animations now skip those frames on every iteration after the
  first, eliminating the bind-pose flash at the loop seam.
- Manual loop management via animation_finished + CONNECT_ONE_SHOT
  replaces LOOP_LINEAR so the seek-past-transition trick works.
- _idle_callbacks tracks active loop callables so they can be
  disconnected when a one-shot animation interrupts idle.
- _idle_entry_done reset when a one-shot starts so the transition
  frames play correctly when returning to idle after the action.

Model config:
- _find_model3d_asset() replaces _find_model3d_url() — returns the
  full asset dict including the new fields.
- ModelFacingDirection → _facing_to_base_angle() → rotation.y applied
  at load; stored in _model_base_angles for movement / idle reset.
- ModelScale applied uniformly to model_node.scale on load.
- ModelTintColor applied as multiplicative albedo_color tint to all
  StandardMaterial3D surfaces (materials duplicated per-instance).
- ModelTintMaskUrl stored in DB/DTO; per-texel shader not yet wired.

Movement facing:
- _animate_unit_move pre-computes a facing angle per BFS step and
  snaps model_node.rotation.y at the start of each step so units
  face the direction they walk.
- On movement end, rotation resets to the idle/team direction.

Cleanup:
- _rebuild_units removal loop erases _idle_entry_done, _idle_callbacks,
  _model_base_angles, _needs_face_rot for freed units.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-15 22:01:58 -04:00
co-authored by Claude Happy
parent 48a12ed14b
commit 8e8b61cbb7
7 changed files with 731 additions and 28 deletions
+153 -26
View File
@@ -168,6 +168,17 @@ var _rebuild_tween : Tween = null
const MOVE_STEP_SECS : float = 0.28
## How long to hold after one-shot animations (attack / damaged / dying) before rebuilding.
const POST_ANIM_SECS : float = 1.2
## Seconds to skip at the start of looping animations on subsequent loop iterations.
## GLB animations use the first N frames as a transition-in from idle; on repeat loops
## we jump past them to avoid the bind-pose flash.
const ANIM_TRANSITION_SECS : float = 5.0 / 30.0 # 5 frames at 30 fps
# Per-unit animation loop tracking.
var _idle_entry_done : Dictionary = {} # iid → true once the first idle entry has played
var _idle_callbacks : Dictionary = {} # iid → Callable (active loop reconnect, to cancel on interrupt)
# Per-unit model config.
var _model_base_angles : Dictionary = {} # iid → float (base facing angle, radians)
var _needs_face_rot : Dictionary = {} # iid → bool (team-based 180° flip flag)
## Animation name aliases: maps the canonical lower-case action to fallback track names.
## The AnimationPlayer track list is matched case-insensitively against each entry.
@@ -580,6 +591,10 @@ func _rebuild_units(state: Dictionary) -> void:
_unit_meshes.erase(iid)
_anim_players.erase(iid)
_unit_def_ids.erase(iid)
_idle_entry_done.erase(iid)
_idle_callbacks.erase(iid) # callback already fired or animation stopping
_model_base_angles.erase(iid)
_needs_face_rot.erase(iid)
# 3. Add units not yet present (newly played, or first render after connect).
for iid : String in desired:
@@ -653,16 +668,26 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false)
_unit_def_ids[iid] = def_id
if def_id.is_empty():
return
var def := ContentCache.get_definition(def_id)
var model_url := _find_model3d_url(def)
var def := ContentCache.get_definition(def_id)
var model_asset := _find_model3d_asset(def)
var model_url := str(model_asset.get("cdnUrl", ""))
if model_url.is_empty():
return
var body_ref : Variant = weakref(body)
# Capture facing flag: P1 units face +Z (rotate 180° Y); P2 units face -Z (default).
# Convention: GLB models exported facing -Z. P1 is at -Z side of the board.
# Read per-model config from the asset.
var facing_dir : String = str(model_asset.get("modelFacingDirection", "north"))
var model_scale : float = float(model_asset.get("modelScale", 1.0))
var tint_str : String = str(model_asset.get("modelTintColor", ""))
var model_tint : Color = Color.WHITE
if not tint_str.is_empty() and tint_str != "null":
model_tint = Color(tint_str)
# Team-based facing: P1 units face +Z (toward P2), P2 units face -Z (toward P1).
# Rotate if: (local is P1 AND friendly) OR (local is P2 AND enemy).
var needs_face_rotation : bool = _local_is_p1 != is_enemy
var base_angle : float = _facing_to_base_angle(facing_dir)
var body_ref : Variant = weakref(body)
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
# Guard: body may have been freed by a state rebuild before load finished.
var b := body_ref.get_ref() as StaticBody3D
@@ -678,9 +703,19 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false)
if child is MeshInstance3D:
child.queue_free()
# Apply facing rotation so units face their opponent across the board.
if needs_face_rotation:
model_node.rotation_degrees = Vector3(0, 180, 0)
# Apply uniform scale if configured.
if not is_equal_approx(model_scale, 1.0):
model_node.scale = Vector3.ONE * model_scale
# Store per-unit model config for movement facing and idle rotation.
_model_base_angles[iid] = base_angle
_needs_face_rot[iid] = needs_face_rotation
# Apply idle/team rotation (facing toward opponent).
model_node.rotation.y = _idle_rotation(iid)
# Apply multiplicative tint to all StandardMaterial3D surfaces.
_apply_model_tint(model_node, model_tint)
# Position model so its local origin sits at the body's position.
# Skip reset if a move tween is driving this body — it controls position.
@@ -697,13 +732,36 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false)
)
func _find_model3d_url(def: Dictionary) -> String:
## Returns the first Model3D asset dict for a card definition, or {} if none.
func _find_model3d_asset(def: Dictionary) -> Dictionary:
for asset: Variant in def.get("assets", []):
var d := asset as Dictionary
if d == null: continue
if str(d.get("assetType", "")) == "Model3D":
return str(d.get("cdnUrl", ""))
return ""
return d
return {}
## Apply a multiplicative colour tint to all StandardMaterial3D surfaces in a
## model subtree. Materials are duplicated per-instance to avoid cross-unit
## bleed. White (default) is a no-op.
func _apply_model_tint(model: Node3D, tint: Color) -> void:
if tint.is_equal_approx(Color.WHITE):
return
var stack : Array = [model]
while not stack.is_empty():
var n = stack.pop_back()
if n is MeshInstance3D:
var mi := n as MeshInstance3D
if mi.mesh != null:
for i in mi.mesh.get_surface_count():
var mat := mi.get_active_material(i)
if mat is StandardMaterial3D:
var dup := mat.duplicate() as StandardMaterial3D
dup.albedo_color = dup.albedo_color * tint
mi.set_surface_override_material(i, dup)
for child in n.get_children():
stack.append(child)
## Recursively find the first AnimationPlayer in a model subtree.
@@ -749,9 +807,32 @@ func _resolve_anim_track(ap: AnimationPlayer, action_lower: String) -> String:
return ""
## Convert a model's exported facing direction string to a base angle in radians.
## The angle represents atan2(dir.x, -dir.z) for the direction the model faces
## when rotation.y == 0. All animations and movement share this offset.
func _facing_to_base_angle(facing: String) -> float:
match facing.to_lower():
"south": return PI
"east": return PI / 2.0
"west": return -PI / 2.0
_: return 0.0 # "north" / default: model faces -Z
## Returns the rotation.y (radians) that makes a unit's model face its opponent
## across the board, given its stored base angle and team-flip flag.
func _idle_rotation(iid: String) -> float:
var base : float = float(_model_base_angles.get(iid, 0.0))
var flip : bool = bool(_needs_face_rot.get(iid, false))
# flip=true → unit should face +Z (south, toward P2) atan2(0,-1)=π
# flip=false → unit should face -Z (north, toward P1) atan2(0, 1)=0
var dir := Vector3(0, 0, 1) if flip else Vector3(0, 0, -1)
return atan2(dir.x, -dir.z) - base
## Play an animation on a unit by action name. Uses card's AnimationTrackName
## override when set, then falls back to case-insensitive convention matching.
## Pass loop=true for looping animations (e.g. Idle).
## Pass loop=true for looping animations (e.g. idle, moving).
## GLB convention: the first ANIM_TRANSITION_SECS of any animation are
## "entry frames" that blend from idle into the action. For looping animations
## those frames are played once on entry, then skipped on every subsequent loop.
func _play_unit_anim(iid: String, action: String, loop: bool = false) -> void:
var ap : AnimationPlayer = _anim_players.get(iid, null)
if ap == null or not is_instance_valid(ap):
@@ -769,23 +850,48 @@ func _play_unit_anim(iid: String, action: String, loop: bool = false) -> void:
var anim := ap.get_animation(track)
if anim == null:
return
anim.loop_mode = Animation.LOOP_LINEAR if loop else Animation.LOOP_NONE
# All animations are managed with LOOP_NONE; looping is handled manually
# so we can seek past the transition frames on subsequent iterations.
anim.loop_mode = Animation.LOOP_NONE
# Disconnect any stale idle loop callback that would restart idle unexpectedly.
if _idle_callbacks.has(iid):
var old_cb := _idle_callbacks[iid] as Callable
if ap.animation_finished.is_connected(old_cb):
ap.animation_finished.disconnect(old_cb)
_idle_callbacks.erase(iid)
# Don't restart the same animation while it's already playing correctly.
if ap.current_animation == track and ap.is_playing():
return
ap.play(track)
# For one-shot animations (not dying), queue idle immediately so the
# AnimationPlayer transitions with no bind-pose gap between them.
# Starting a non-loop animation: reset entry-done so the NEXT idle play
# uses the transition frames to blend back from the action pose.
if not loop:
_idle_entry_done.erase(iid)
ap.play(track)
if loop:
# On subsequent loop iterations skip the GLB entry frames.
if _idle_entry_done.get(iid, false):
ap.seek(ANIM_TRANSITION_SECS, true)
else:
_idle_entry_done[iid] = true
# Schedule the next loop iteration via animation_finished.
var cb := func(_n: String) -> void: _play_unit_anim(iid, action, true)
ap.animation_finished.connect(cb, CONNECT_ONE_SHOT)
_idle_callbacks[iid] = cb
else:
# For one-shot non-death animations: return to idle via animation_finished
# (fires synchronously inside AnimationPlayer._process, so no gap frame).
var action_l := action.to_lower()
var is_death := action_l == "dying" or action_l == "death" or action_l == "die"
if not is_death:
var idle_track := _resolve_anim_track(ap, "idle")
if not idle_track.is_empty():
var idle_anim := ap.get_animation(idle_track)
if idle_anim != null:
idle_anim.loop_mode = Animation.LOOP_LINEAR
ap.queue(idle_track)
ap.animation_finished.connect(
func(_n: String) -> void: _play_unit_anim(iid, "idle", true),
CONNECT_ONE_SHOT)
## Detect HP decreases and unit deaths vs previous state, and fire animations.
@@ -886,17 +992,38 @@ func _animate_unit_move(iid: String, from_coord: Vector2i, to_coord: Vector2i,
(_move_anims[iid] as Tween).kill()
# Play the looping move animation.
_play_unit_anim(iid, "moving", true)
# Tween the body through each grid step, preserving its current Y.
# Pre-compute per-step facing angles so the closures capture the correct values.
var base_angle := float(_model_base_angles.get(iid, 0.0))
var prev_coord := from_coord
var step_angles : Array[float] = []
for step : Vector2i in path:
var step_wp := _coord_to_world(step.x, step.y)
var prev_wp := _coord_to_world(prev_coord.x, prev_coord.y)
var dir := step_wp - prev_wp # XZ direction in world space
step_angles.append(atan2(dir.x, -dir.z) - base_angle)
prev_coord = step
# Tween the body through each grid step, rotating the model to face each direction.
var body_y := body.position.y
var tween := create_tween()
tween.set_ease(Tween.EASE_IN_OUT)
tween.set_trans(Tween.TRANS_SINE)
for step : Vector2i in path:
var wp := _coord_to_world(step.x, step.y)
for i in path.size():
var step : Vector2i = path[i]
var wp := _coord_to_world(step.x, step.y)
# Snap model rotation to face the movement direction before each step.
tween.tween_callback(
(func(angle: float) -> void:
var m := _unit_meshes.get(iid) as Node3D
if is_instance_valid(m):
m.rotation.y = angle
).bind(step_angles[i]))
tween.tween_property(body, "position", Vector3(wp.x, body_y, wp.z), MOVE_STEP_SECS)
# Return to Idle once movement finishes.
# Return to idle rotation and idle animation once movement finishes.
tween.tween_callback(func() -> void:
_move_anims.erase(iid)
var m := _unit_meshes.get(iid) as Node3D
if is_instance_valid(m):
m.rotation.y = _idle_rotation(iid)
_play_unit_anim(iid, "idle", true))
_move_anims[iid] = tween
return duration