Fix SummonToken tile-filter validation: reject bad picks before costs are paid

Three bugs fixed for abilities like Demonate Leviathan (SummonToken + TileFilter):

1. Server: AbilityUsesThisTurn was incremented (and costs paid) before effect-level
   TileFilter validation ran. Added PreValidateClientTileTargets() called before the
   use-count increment so an invalid tile pick wastes no uses and no sacrificed tokens.

2. Server: SummonToken silently break'd when TileFilter or token-affinity check failed,
   giving the client no error. Changed both to throw GameException("INVALID_TILE").

3. Client: tile_passes_filters() only checked the target selector's filters, not the
   effect-level TileFilter (e.g. SummonToken.tileFilter). Added _collect_effect_tile_filters()
   and TileAffinityMatches handling so invalid tiles are never highlighted or accepted.

Also includes: Art2dUrl/ModelUrl deltas in GameStateDiffer/GameMessages/GameEngine,
unit_mesh_builder token-model URL fallback + shader/tint helpers, ModelCache v3 bump,
Game.gd unit delta merging for art2dUrl/modelUrl.

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-05-12 07:06:54 -04:00
co-authored by Claude Happy
parent 3bbf419836
commit f3e5363c13
10 changed files with 210 additions and 37 deletions
+2
View File
@@ -692,6 +692,8 @@ func _merge_unit_delta(unit: Dictionary, ud: Dictionary) -> void:
if ud.has("effectsJson") and ud["effectsJson"] != null: unit["effectsJson"] = ud["effectsJson"]
if ud.has("abilitiesJson") and ud["abilitiesJson"] != null: unit["abilitiesJson"] = ud["abilitiesJson"]
if ud.has("abilityUsesJson") and ud["abilityUsesJson"] != null: unit["abilityUsesJson"] = ud["abilityUsesJson"]
if ud.has("art2dUrl") and ud["art2dUrl"] != null: unit["art2dUrl"] = ud["art2dUrl"]
if ud.has("modelUrl") and ud["modelUrl"] != null: unit["modelUrl"] = ud["modelUrl"]
func _on_server_push(type: String, payload: Variant) -> void:
+1 -1
View File
@@ -17,7 +17,7 @@ extends Node
## stale .bin files from the old scheme are purged on first launch.
const _CACHE_DIR := "user://remote_model_cache"
const _CACHE_VER := "v2" # bump this when the disk-key scheme changes
const _CACHE_VER := "v3" # bump this when cached GLBs need to be re-fetched
# On web exports, direct CDN fetches are blocked by CORS (Ceph RadosGW doesn't send
# Access-Control-Allow-Origin). Route through the game server proxy instead.
@@ -0,0 +1 @@
uid://d4bnvq4ulqph8
@@ -0,0 +1 @@
uid://caefv6gdfthxp
@@ -297,6 +297,9 @@ func highlight_ability_targets(action: Dictionary) -> void:
# Tile target.
if type_ == "Tile":
# Gather effect-level tile filters (e.g. SummonToken.tileFilter) in addition to
# the target selector's filters so invalid tiles are never highlighted.
var effect_tile_filters: Array = _collect_effect_tile_filters(action)
var bw: int = Game.board_width()
var bh: int = Game.board_height()
for tx: int in range(bw):
@@ -308,8 +311,11 @@ func highlight_ability_targets(action: Dictionary) -> void:
continue
if requires_los and pathfinder != null and not pathfinder.client_has_los(sx, sy, tx, ty):
continue
if tile_passes_filters(tx, ty, filters):
emit_signal("highlight_add_requested", tx, ty, "ability")
if not tile_passes_filters(tx, ty, filters):
continue
if not tile_passes_filters(tx, ty, effect_tile_filters):
continue
emit_signal("highlight_add_requested", tx, ty, "ability")
return
# Unit-type target.
@@ -370,7 +376,10 @@ func is_valid_board_target(coord: Vector2i, unit_id: String) -> bool:
var filters: Array = filters_v as Array if filters_v is Array else []
if type_ == "Tile":
return coord.x >= 0 and tile_passes_filters(coord.x, coord.y, filters) \
var effect_tile_filters: Array = _collect_effect_tile_filters(action)
return coord.x >= 0 \
and tile_passes_filters(coord.x, coord.y, filters) \
and tile_passes_filters(coord.x, coord.y, effect_tile_filters) \
and _target_coord_passes_range(coord)
if unit_id.is_empty():
@@ -471,6 +480,19 @@ func unit_passes_filters(unit: Dictionary, filters: Array) -> bool:
return true
## Collects all effect-level tile filters from a single action's effects array.
## Currently supports SummonToken.tileFilter.
func _collect_effect_tile_filters(action: Dictionary) -> Array:
var result: Array = []
var effects_v: Variant = action.get("effects", [])
var effects: Array = effects_v as Array if effects_v is Array else []
for fx: Dictionary in effects:
var tile_filter_v: Variant = fx.get("tilefilter", [])
var tile_filter: Array = tile_filter_v as Array if tile_filter_v is Array else []
result.append_array(tile_filter)
return result
func tile_passes_filters(tx: int, ty: int, filters: Array) -> bool:
if filters.is_empty():
return true
@@ -486,6 +508,10 @@ func tile_passes_filters(tx: int, ty: int, filters: Array) -> bool:
int(src_pos.get("x", 0)), int(src_pos.get("y", 0)))
if dist < int(f.get("min", 0)) or dist > int(f.get("max", 999)):
return false
"tileaffinitymatches":
var tile: Dictionary = Game.get_tile(tx, ty)
if tile.get("affinity", "") != f.get("affinity", ""):
return false
return true
@@ -321,24 +321,23 @@ func add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false,
var def_id: String = str(unit.get("cardDefinitionId", ""))
if not def_id.is_empty():
unit_registry.unit_def_ids[iid] = def_id
if def_id.is_empty():
return
var def: Dictionary = ContentCache.get_definition(def_id)
_prime_unit_sfx(def)
var def: Dictionary = ContentCache.get_definition(def_id) if not def_id.is_empty() else {}
if not def.is_empty():
_prime_unit_sfx(def)
var model_asset: Dictionary = find_model3d_asset(def)
var model_url: String = str(model_asset.get("cdnUrl", ""))
var model_etag: String = str(model_asset.get("contentETag", ""))
var model_url: String = str(unit.get("modelUrl", "")).strip_edges()
var model_etag: String = ""
if model_url.is_empty():
model_url = str(model_asset.get("cdnUrl", "")).strip_edges()
model_etag = str(model_asset.get("contentETag", ""))
if model_url.is_empty():
return
# Asset-level config (model-file specific).
var facing_dir: String = str(model_asset.get("modelFacingDirection", "south"))
# Card-level config (visual identity of this card, not the shared mesh file).
var model_scale: float = float(def.get("modelScale", 1.0))
var tint_str: String = str(def.get("modelTintColor", ""))
var model_tint: Color = Color.WHITE
if not tint_str.is_empty() and tint_str != "null":
model_tint = Color(tint_str)
var model_scale: float = _parse_model_scale(def.get("modelScale", 1.0))
var model_tint: Color = _parse_model_tint(def.get("modelTintColor", ""))
# 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).
@@ -694,7 +693,8 @@ func _play_materialize_shader_timed(visual: Node3D, team_color: Color, duration:
mat.shader = _materialize_shader()
mat.set_shader_parameter("reveal", 0.0)
mat.set_shader_parameter("team_color", Color(team_color.r, team_color.g, team_color.b, 1.0))
mi.material_override = mat
_configure_materialize_source(mat, entry.get("active_material", null))
_apply_materialize_override(mi, entry, mat)
reveal_mats.append(mat)
var target_scale: Vector3 = visual.scale
@@ -715,7 +715,7 @@ func _play_materialize_shader_timed(visual: Node3D, team_color: Color, duration:
var mesh_ref: WeakRef = entry["mesh_ref"] as WeakRef
var mi: MeshInstance3D = mesh_ref.get_ref() as MeshInstance3D if mesh_ref != null else null
if is_instance_valid(mi):
mi.material_override = entry["override"]
_restore_materialize_override(mi, entry)
)
@@ -741,7 +741,8 @@ func _play_dissolve_shader_timed(visual: Node3D, team_color: Color, duration: fl
mat.shader = _materialize_shader()
mat.set_shader_parameter("reveal", 1.0)
mat.set_shader_parameter("team_color", Color(team_color.r, team_color.g, team_color.b, 1.0))
mi.material_override = mat
_configure_materialize_source(mat, entry.get("active_material", null))
_apply_materialize_override(mi, entry, mat)
dissolve_mats.append(mat)
var tween: Tween = create_tween()
@@ -769,14 +770,62 @@ func _exit_tree() -> void:
func _collect_materialize_surfaces(node: Node, surfaces: Array[Dictionary]) -> void:
if node is MeshInstance3D:
var mi: MeshInstance3D = node as MeshInstance3D
surfaces.append({
"mesh_ref": weakref(mi),
"override": mi.material_override
})
if mi.material_override != null or mi.mesh == null or mi.mesh.get_surface_count() <= 0:
var active_material: Material = null
if mi.mesh != null and mi.mesh.get_surface_count() > 0:
active_material = mi.get_active_material(0)
surfaces.append({
"mesh_ref": weakref(mi),
"surface_idx": -1,
"override": mi.material_override,
"active_material": active_material
})
else:
for i: int in mi.mesh.get_surface_count():
surfaces.append({
"mesh_ref": weakref(mi),
"surface_idx": i,
"override": mi.get_surface_override_material(i),
"active_material": mi.get_active_material(i)
})
for child: Node in node.get_children():
_collect_materialize_surfaces(child, surfaces)
func _apply_materialize_override(mi: MeshInstance3D, entry: Dictionary, mat: ShaderMaterial) -> void:
var surface_idx: int = int(entry.get("surface_idx", -1))
if surface_idx >= 0:
mi.set_surface_override_material(surface_idx, mat)
else:
mi.material_override = mat
func _restore_materialize_override(mi: MeshInstance3D, entry: Dictionary) -> void:
var surface_idx: int = int(entry.get("surface_idx", -1))
if surface_idx >= 0:
mi.set_surface_override_material(surface_idx, entry.get("override", null) as Material)
else:
mi.material_override = entry.get("override", null) as Material
func _configure_materialize_source(shader_mat: ShaderMaterial, source: Material) -> void:
var base_color: Color = Color.WHITE
var base_texture: Texture2D = null
var roughness: float = 0.35
var metallic: float = 0.0
if source is StandardMaterial3D:
var standard: StandardMaterial3D = source as StandardMaterial3D
base_color = standard.albedo_color
base_texture = standard.albedo_texture
roughness = standard.roughness
metallic = standard.metallic
shader_mat.set_shader_parameter("base_color", base_color)
shader_mat.set_shader_parameter("base_texture", base_texture)
shader_mat.set_shader_parameter("has_base_texture", base_texture != null)
shader_mat.set_shader_parameter("base_roughness", roughness)
shader_mat.set_shader_parameter("base_metallic", metallic)
func _materialize_shader() -> Shader:
if has_meta("_materialize_shader"):
return get_meta("_materialize_shader") as Shader
@@ -787,6 +836,11 @@ render_mode blend_mix, cull_disabled, depth_draw_opaque;
uniform float reveal : hint_range(0.0, 1.0) = 0.0;
uniform vec4 team_color : source_color = vec4(0.35, 0.5, 1.0, 1.0);
uniform vec4 base_color : source_color = vec4(1.0);
uniform sampler2D base_texture : source_color;
uniform bool has_base_texture = false;
uniform float base_roughness : hint_range(0.0, 1.0) = 0.35;
uniform float base_metallic : hint_range(0.0, 1.0) = 0.0;
varying vec3 local_pos;
@@ -812,15 +866,20 @@ void fragment() {
float edge = 1.0 - smoothstep(0.0, 0.16, abs(bubble_noise - threshold));
float shimmer = smoothstep(0.72, 1.0, fine_noise) * (1.0 - reveal * 0.45);
vec4 source = base_color;
if (has_base_texture) {
source *= texture(base_texture, UV);
}
vec3 black_bubble = vec3(0.012, 0.010, 0.018);
vec3 final_tint = mix(team_color.rgb * 0.35, team_color.rgb, reveal);
vec3 final_tint = mix(team_color.rgb * 0.35, source.rgb, reveal);
vec3 color = mix(black_bubble, final_tint, smoothstep(0.25, 1.0, reveal));
color += team_color.rgb * (edge * 1.8 + shimmer * 0.9);
ALBEDO = color;
EMISSION = team_color.rgb * (edge * 1.5 + shimmer);
ROUGHNESS = 0.35;
ALPHA = 1.0;
ROUGHNESS = base_roughness;
METALLIC = base_metallic;
ALPHA = source.a;
}
"""
set_meta("_materialize_shader", shader)
@@ -1064,11 +1123,8 @@ func do_model_retry(iid: String, model_url: String, attempt: int, etag: String =
# Re-read card config in case ContentCache was refreshed since placement.
var def_id: String = unit_registry.unit_def_ids.get(iid, "")
var def: Dictionary = ContentCache.get_definition(def_id)
var model_scale: float = float(def.get("modelScale", 1.0))
var tint_str: String = str(def.get("modelTintColor", ""))
var model_tint: Color = Color.WHITE
if not tint_str.is_empty() and tint_str != "null":
model_tint = Color(tint_str)
var model_scale: float = _parse_model_scale(def.get("modelScale", 1.0))
var model_tint: Color = _parse_model_tint(def.get("modelTintColor", ""))
var target_scale: Vector3 = Vector3.ONE * model_scale
if not is_equal_approx(model_scale, 1.0):
model_node.scale = target_scale
@@ -1089,6 +1145,38 @@ func do_model_retry(iid: String, model_url: String, attempt: int, etag: String =
# ── Model helpers ─────────────────────────────────────────────────────────────
func _parse_model_scale(value: Variant) -> float:
var parsed: float = 1.0
match typeof(value):
TYPE_FLOAT, TYPE_INT:
parsed = value
TYPE_STRING, TYPE_STRING_NAME:
var text: String = str(value).strip_edges()
if text.is_valid_float():
parsed = text.to_float()
_:
parsed = 1.0
if parsed <= 0.0:
return 1.0
return parsed
func _parse_model_tint(value: Variant) -> Color:
var text: String = str(value).strip_edges()
if text.is_empty() or text.to_lower() == "null":
return Color.WHITE
if text.to_lower() == "white":
return Color.WHITE
if not Color.html_is_valid(text):
push_warning("[UnitMeshBuilder] Ignoring invalid modelTintColor '%s'" % text)
return Color.WHITE
var parsed: Color = Color.html(text)
if maxf(parsed.r, maxf(parsed.g, parsed.b)) <= 0.02:
push_warning("[UnitMeshBuilder] Ignoring near-black modelTintColor '%s'; multiplicative tint hides GLB textures" % text)
return Color.WHITE
return Color(parsed.r, parsed.g, parsed.b, 1.0)
## 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", []):
+48 -3
View File
@@ -126,6 +126,10 @@ public static class AbilitySystem
if (!ValidateSourceActivationConditions(def, ctx, source))
throw new GameException("ABILITY_CONDITION_NOT_MET");
// Pre-validate client tile targets against effect-level TileFilters BEFORE
// incrementing the use count or paying any costs, so a bad pick wastes nothing.
PreValidateClientTileTargets(def, clientTargets, ctx);
source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1;
var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex, def.Range, def.Duration);
@@ -191,6 +195,42 @@ public static class AbilitySystem
return true;
}
/// <summary>
/// Checks client-supplied tile targets against any effect-level <c>TileFilter</c> constraints
/// (e.g. <see cref="SummonTokenEffect.TileFilter"/>). Called before the use-count is
/// incremented and before costs are paid, so a rejected pick costs the player nothing.
/// </summary>
private static void PreValidateClientTileTargets(
AbilityDefinition def,
IReadOnlyList<AbilityTarget>? clientTargets,
AbilityContext ctx)
{
if (clientTargets is null || ctx.State.Board is null) return;
// Iterate the flat action list in the top-level AND group (the common case).
// OR/XOR groups with pending interactive picks are handled after the pick resolves
// and never reach this path with client-provided tile coords.
var actions = def.ActionGroup?.Actions ?? def.Actions ?? [];
for (int ai = 0; ai < actions.Length; ai++)
{
var action = actions[ai];
if (action.Target.Type != TargetType.Tile) continue;
foreach (var effect in action.Effects)
{
if (effect is not SummonTokenEffect ste || ste.TileFilter is not { Length: > 0 }) continue;
var ct = clientTargets.FirstOrDefault(t => t.ActionIndex == ai && t.Coord is not null);
if (ct is null) continue;
var coord = new Coord(ct.Coord!.X, ct.Coord!.Y);
var tile = ctx.State.Board.GetTile(coord);
if (tile is null || !TileMatchesFilters(ste.TileFilter, tile, ctx))
throw new GameException("INVALID_TILE");
}
}
}
/// <summary>
/// Scans every battlefield unit (and, when SourceZoneGate is set, hand/discard/deck cards)
/// for Triggered abilities matching the occurrence and fires each matching one.
@@ -2837,12 +2877,17 @@ public static class AbilitySystem
var proto = JsonSerializer.Deserialize<CardInstance>(ste.TokenDefJson, _jsonOpts);
if (proto is null) break;
// Enforce tile affinity: a token with a non-Void affinity may only be
// placed on a tile whose resolved affinity is compatible with the token.
// Enforce explicit TileFilter (e.g. TileAffinityMatches) — throw so the client
// receives an error rather than silently swallowing a bad pick.
if (ste.TileFilter is { Length: > 0 } && !TileMatchesFilters(ste.TileFilter, tile, ctx))
throw new GameException("INVALID_TILE");
// Enforce tile affinity derived from the token's own Affinity field: a token
// with a non-Void affinity may only be placed on a compatible tile.
if (!string.IsNullOrEmpty(proto.Affinity) && proto.Affinity != "Void"
&& Enum.TryParse<Affinity>(proto.Affinity, out var tokenAffinity)
&& !AffinitySystem.IsAffinityValid(tile, tokenAffinity))
break;
throw new GameException("INVALID_TILE");
proto.InstanceId = Guid.NewGuid().ToString("N")[..8];
proto.CardType = "SpiritToken";
+3 -1
View File
@@ -1701,7 +1701,9 @@ public static class GameEngine
AttackRequiresLos : c.RequiresLos,
ExtraAttacksRemaining : c.ExtraAttacksRemaining,
CanBeAttacked : c.CanBeAttacked,
AbilitiesJson : c.AbilitiesJson);
AbilitiesJson : c.AbilitiesJson,
Art2dUrl : c.Art2dUrl,
ModelUrl : c.ModelUrl);
}
private static BoardDto ToBoardDto(Board board)
+6 -2
View File
@@ -556,7 +556,9 @@ public sealed record UnitDelta(
int? ExtraAttacksRemaining,
CoordDto? Position,
string? AbilitiesJson,
string? AbilityUsesJson);
string? AbilityUsesJson,
string? Art2dUrl,
string? ModelUrl);
public sealed record PublicCountsDelta(
int? DeckCount,
@@ -725,7 +727,9 @@ public sealed record CardInstanceDto(
bool AttackRequiresLos,
int ExtraAttacksRemaining,
bool CanBeAttacked,
string? AbilitiesJson);
string? AbilitiesJson,
string? Art2dUrl,
string? ModelUrl);
public sealed record BoardDto(
int Width,
+5 -1
View File
@@ -251,6 +251,8 @@ internal static class GameStateDiffer
prevC.ExtraAttacksRemaining != nextC.ExtraAttacksRemaining ||
prevFc?.Position != nextFc?.Position ||
prevC.AbilitiesJson != nextC.AbilitiesJson ||
prevC.Art2dUrl != nextC.Art2dUrl ||
prevC.ModelUrl != nextC.ModelUrl ||
abilityUsesChanged;
if (!anyChange) return null;
@@ -280,7 +282,9 @@ internal static class GameStateDiffer
ExtraAttacksRemaining : prevC.ExtraAttacksRemaining != nextC.ExtraAttacksRemaining ? nextC.ExtraAttacksRemaining : null,
Position : positionDelta,
AbilitiesJson : prevC.AbilitiesJson != nextC.AbilitiesJson ? nextC.AbilitiesJson : null,
AbilityUsesJson : abilityUsesJson);
AbilityUsesJson : abilityUsesJson,
Art2dUrl : prevC.Art2dUrl != nextC.Art2dUrl ? nextC.Art2dUrl : null,
ModelUrl : prevC.ModelUrl != nextC.ModelUrl ? nextC.ModelUrl : null);
}
private static PlayerStatsDelta? DiffPlayerStats(PlayerState prev, PlayerState next)