Skip to main content

delvewright_dsl/
actor.rs

1//! Stage 5 — scripted actors (DSL v0.6, spec-0014): bodies the story moves.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6use crate::serde_fields::{is_false, is_zero3};
7use crate::{
8    ActorId, AnchorId, BodyTraversal, EncounterTier, MobAttributes, MobDrop, MobEquipment, NpcSkin,
9    OnKill, QuestEffect,
10};
11
12#[cfg(doc)]
13use crate::{Mark, Npc, Wave};
14
15/// A scripted stage actor (DSL v0.6, spec-0014): a NoAI/Silent/no-loot puppet,
16/// distinct from a stage-2 [`Npc`] (no dialogue, any mob type). Emitted with tag
17/// `dw_actor_<id>`, `Invulnerable` unless `vulnerable` (a damageable puppet stays
18/// knockback-immune — the tower-defense creep). `skin` re-dresses it as a
19/// `minecraft:mannequin`, exactly as a stage-2 NPC skin. The puppet is summoned by
20/// a `spawn-actor` effect (not at load), moved by `move-actor`, and can be replaced
21/// by a real-AI twin with `unleash-actor`.
22#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
23#[serde(deny_unknown_fields)]
24pub struct Actor {
25    /// Unique actor id (`actor/<kebab>`).
26    pub id: ActorId,
27    /// The vanilla entity to puppet, e.g. `minecraft:warden`. Validated against the
28    /// pinned 1.21.11 entity registry (`DW0173`).
29    pub entity: String,
30    /// Optional custom name shown above the puppet.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub name: Option<String>,
33    /// Optional player-model skin (mannequin), as a stage-2 NPC (`DW0190`).
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub skin: Option<NpcSkin>,
36    /// The anchor the puppet is summoned on (resolved across areas, like an
37    /// `open-gate` / `move-npc` destination).
38    pub anchor: AnchorId,
39    /// Integer `[x, y, z]` block offset from `anchor` (spec-0066, default
40    /// `[0, 0, 0]`): the puppet stands at the [`Mark`] the two fields spell, so
41    /// a rank of bodies is one anchor and an offset apiece.
42    #[serde(default, skip_serializing_if = "is_zero3")]
43    pub offset: [i32; 3],
44    /// Initial facing (default `south`). The puppet spawns yawed this way.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub facing: Option<Facing>,
47    /// If `true`, the puppet is damageable (a tower-defense creep) but stays
48    /// knockback-immune; default `false` (fully `Invulnerable`).
49    #[serde(default, skip_serializing_if = "is_false")]
50    pub vulnerable: bool,
51    /// Gear the actor wears and holds, in the same shape a wave mob uses
52    /// ([`MobEquipment`]). Emitted into BOTH the staged puppet and the
53    /// unleashed twin, so the dormant elite the player has been circling is
54    /// visibly the same armoured thing that stands up. Drop chances are zero —
55    /// wave gear and actor gear are never farmable (no-grind constitution).
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub equipment: Option<MobEquipment>,
58    /// Attribute overrides, in the same shape a wave mob uses ([`MobAttributes`],
59    /// the v0.4 surface — one type, one rule set, so the two surfaces cannot
60    /// drift). Emitted into BOTH the staged puppet and the unleashed twin, so the
61    /// elite the party fights is the elite the author tuned; without it an actor
62    /// was stuck at vanilla base values while every wave mob could be tuned,
63    /// which is what blocked elite authoring. A `vulnerable` actor's
64    /// knockback-immunity is emitted first and is not authorable.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub attributes: Option<MobAttributes>,
67    /// How hard this actor's fight is *meant* to be (DSL v0.8, spec-0023) — the
68    /// same [`EncounterTier`] vocabulary a [`Wave`] declares. Absent =
69    /// [`EncounterTier::Ordinary`], byte-identical to every pre-0.8 campaign.
70    ///
71    /// A wave is not the only shape an elite takes. The set-piece souls fight —
72    /// the armoured thing kneeling among the graves that stands up when you hit
73    /// it — is an **actor**: staged by `spawn-actor`, given AI by
74    /// `unleash-actor`, killed by hand rather than by a `kill` objective. Before
75    /// this field nothing anywhere stated what such a fight was billed as.
76    ///
77    /// Like the wave field this is a **declaration, not a knob**: the compiler
78    /// never scales an actor from it, and emission is unchanged whichever tier is
79    /// declared. Its readers are the health-bar advisory (`DW0912`) and the drop
80    /// rule — only a billed fight leaves anything behind.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub tier: Option<EncounterTier>,
83    /// A health bar over this actor's fight (DSL v0.31, spec-0073) — the same
84    /// [`HealthBar`](crate::healthbar::HealthBar) a [`Wave`] declares. It reads the
85    /// bodies whose health can move: the unleashed twin, or the puppet itself when
86    /// the actor is `vulnerable`. A bar on an actor that is neither is `DW0909`.
87    /// Absent = no bar, byte-identical.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub health_bar: Option<crate::healthbar::HealthBar>,
90    /// What this actor leaves behind when a player kills it. Only an
91    /// `elite`/`boss` actor may
92    /// declare it (`DW0491`). Emitted into BOTH the staged puppet and the
93    /// unleashed twin, exactly as `equipment` is — the drop belongs to the body,
94    /// not to one of its two lifecycles. A `despawn-actor` strips the
95    /// declaration off the body before removing it, so re-caging an elite (a
96    /// souls re-seat) never scatters its axe.
97    #[serde(default, skip_serializing_if = "Vec::is_empty")]
98    pub drops: Vec<MobDrop>,
99    /// What this body can do when it moves (DSL v0.11, spec-0034) — the same
100    /// [`BodyTraversal`] a stage-2 [`Npc`] carries, because traversal belongs to
101    /// the body and not to the stage that declares it. Absent = the class the
102    /// compiler derives from `entity` (or from `minecraft:mannequin` when `skin`
103    /// is set).
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub traversal: Option<BodyTraversal>,
106    /// What happens each time a player is credited with killing this actor's
107    /// body (spec-0074) — effect root R9, the same [`OnKill`] a
108    /// wave declares. Absent = no bundle, and the actor's emission is
109    /// byte-identical.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub on_kill: Option<OnKill>,
112}
113
114/// A cardinal facing keyword (DSL v0.6). Emitted as the puppet's spawn yaw
115/// (MC: yaw 0 = +z/south).
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
117#[serde(rename_all = "kebab-case")]
118pub enum Facing {
119    /// Facing +z (yaw 0) — the default.
120    South,
121    /// Facing -z (yaw 180).
122    North,
123    /// Facing -x (yaw 90).
124    West,
125    /// Facing +x (yaw 270).
126    East,
127}
128
129impl Facing {
130    /// The kebab token (`south` / `north` / `west` / `east`).
131    pub fn token(self) -> &'static str {
132        match self {
133            Facing::South => "south",
134            Facing::North => "north",
135            Facing::West => "west",
136            Facing::East => "east",
137        }
138    }
139}
140
141/// How a `despawn-actor` removes its puppet (DSL v0.6).
142#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
143#[serde(rename_all = "kebab-case")]
144pub enum DespawnStyle {
145    /// The body leaves unseen: no death animation, red flash or death particles
146    /// where it stood. It is moved under the world and removed there.
147    Vanish,
148    /// The body dies where it stands, with the vanilla death animation (a death
149    /// the player is meant to watch).
150    Kill,
151}
152
153impl DespawnStyle {
154    /// The kebab token (`vanish` / `kill`).
155    pub fn token(self) -> &'static str {
156        match self {
157            DespawnStyle::Vanish => "vanish",
158            DespawnStyle::Kill => "kill",
159        }
160    }
161}
162
163/// One step of a [`Verb::Sequence`] (DSL v0.6): a group of effects fired at
164/// an exact tick offset from the sequence's start.
165#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
166#[serde(deny_unknown_fields)]
167pub struct SequenceStep {
168    /// Tick offset from the sequence start at which `effects` fire.
169    pub at_ticks: u32,
170    /// The effects fired at `at_ticks`. Any stage-5 effect except a nested
171    /// `sequence` (rejected with `DW0329`).
172    pub effects: Vec<QuestEffect>,
173}
174
175// ---------------------------------------------------------------------------
176// Validation — the checks `dsl::validate` runs over this object (ADR-0031)
177// ---------------------------------------------------------------------------
178
179use crate::Verb;
180use crate::diagnostic::{Diagnostic, codes};
181use crate::envelope::Campaign;
182use crate::ids::is_kebab;
183use crate::quest::check::check_no_nested_sequence;
184use crate::registry::{AnchorRegistry, EntityRegistry, ItemRegistry};
185use crate::validate::{AnchorProviders, station_kind_diag};
186use crate::wave::check_equipment;
187use std::collections::BTreeSet;
188
189/// Recursively visit every effect in `effs`, descending into every nested effect
190/// list ([`QuestEffect::nested_effect_lists`]: `sequence` steps, `set-checkpoint`
191/// `on_respawn`, `begin-stealth` `on_caught`, `move-actor` / `move-npc`
192/// `on_arrive`).
193fn walk_effects_deep(effs: &[QuestEffect], f: &mut dyn FnMut(&QuestEffect)) {
194    for e in effs {
195        e.visit_deep(f);
196    }
197}
198
199/// Actor declarations (spec-0014): a known entity id, a well-formed and distinct
200/// skin, a spawn anchor some area provides — and every actor staging effect's
201/// reference (`DW0112`), every `move-actor` destination anchor (`DW0142`) and the
202/// no-nested-`sequence` rule (`DW0329`) at every depth of a quest's or a
203/// trigger's bundles.
204pub(crate) fn actor_checks(
205    c: &Campaign,
206    anchors: &dyn AnchorRegistry,
207    entities: &dyn EntityRegistry,
208    d: &mut Vec<Diagnostic>,
209) {
210    let quests = &c.quests.content;
211    let declared: BTreeSet<&str> = quests.actors.iter().map(|a| a.id.as_str()).collect();
212
213    // Anchor names provided by single-prefab areas (pool areas resolve anchors in
214    // the compiler, so their presence defers the check — mirroring `DW0142`'s
215    // single-prefab-only scope; never a false positive).
216    let providers = AnchorProviders::build(c, anchors);
217
218    // Actor declarations: entity id, skin, spawn anchor.
219    for (i, a) in quests.actors.iter().enumerate() {
220        if !entities.contains(&a.entity) {
221            d.push(Diagnostic::error(
222                codes::ENTITY_UNKNOWN,
223                "quests",
224                format!("/content/actors/{i}/entity"),
225                format!(
226                    "actor entity `{}` is not a known 1.21.11 entity id — use a valid namespaced \
227                     entity id (e.g. `minecraft:warden`)",
228                    a.entity
229                ),
230            ));
231        }
232        if let Some(skin) = &a.skin
233            && !is_kebab(&skin.texture_id)
234        {
235            d.push(Diagnostic::error(
236                codes::SKIN_INVALID,
237                "quests",
238                format!("/content/actors/{i}/skin/texture_id"),
239                format!(
240                    "actor skin `texture_id` `{}` is malformed — it must be a bare kebab token \
241                     (e.g. `giant-idle`), matching the `skins/<texture_id>.png` filename",
242                    skin.texture_id
243                ),
244            ));
245        }
246        if let Some(f) = station_kind_diag(
247            &providers,
248            a.anchor.as_str(),
249            crate::layout::StationKind::Point,
250            "an actor's station",
251            "quests",
252            format!("/content/actors/{i}/anchor"),
253        ) {
254            d.push(f);
255        }
256        if !providers.resolvable(a.anchor.as_str()) {
257            d.push(Diagnostic::error(
258                codes::ANCHOR_UNRESOLVED,
259                "quests",
260                format!("/content/actors/{i}/anchor"),
261                format!(
262                    "actor anchor `{}` is not provided by any area's prefab — {}",
263                    a.anchor,
264                    providers.anchor_remedy(
265                        "use an anchor a prefab exposes, or bind a prefab/pool that carries it"
266                    ),
267                ),
268            ));
269        }
270    }
271
272    // Effect-level: actor references (DW0112), move-actor destination anchors
273    // (DW0142), and the no-nested-sequence rule (DW0329). Deep-walk so effects
274    // nested in a `sequence` / `move-actor` `on_arrive` are covered.
275    let mut groups: Vec<(String, &[QuestEffect])> = Vec::new();
276    for (i, q) in quests.quests.iter().enumerate() {
277        for (key, effs) in &q.on_objective_complete {
278            groups.push((
279                format!("/content/quests/{i}/on_objective_complete/{key}"),
280                effs.as_slice(),
281            ));
282        }
283        groups.push((
284            format!("/content/quests/{i}/on_complete"),
285            q.on_complete.as_slice(),
286        ));
287    }
288    for (i, t) in quests.triggers.iter().enumerate() {
289        groups.push((
290            format!("/content/triggers/{i}/effects"),
291            t.effects.as_slice(),
292        ));
293    }
294    for (path, effs) in &groups {
295        let mut visit = |e: &QuestEffect| {
296            if let Some(actor) = e.actor_ref()
297                && !declared.contains(actor.as_str())
298            {
299                d.push(Diagnostic::error(
300                    codes::DANGLING_REF,
301                    "quests",
302                    path.clone(),
303                    format!(
304                        "actor staging effect references unknown actor `{actor}` — declare it in \
305                         the stage-5 `actors` list, or fix the reference"
306                    ),
307                ));
308            }
309            if let Verb::MoveActor { to, .. } = &e.verb
310                && let Some(f) = station_kind_diag(
311                    &providers,
312                    to.anchor.as_str(),
313                    crate::layout::StationKind::Point,
314                    "a `move-actor` destination",
315                    "quests",
316                    path.clone(),
317                )
318            {
319                d.push(f);
320            } else if let Verb::MoveActor { to, .. } = &e.verb
321                && !providers.resolvable(to.anchor.as_str())
322            {
323                d.push(Diagnostic::error(
324                    codes::ANCHOR_UNRESOLVED,
325                    "quests",
326                    path.clone(),
327                    format!(
328                        "move-actor destination anchor `{}` is not provided by any \
329                         area's prefab — {}",
330                        to.anchor,
331                        providers.anchor_remedy("use an anchor a prefab exposes"),
332                    ),
333                ));
334            }
335        };
336        walk_effects_deep(effs, &mut visit);
337        check_no_nested_sequence(effs, path, d);
338    }
339}
340
341/// Actor `equipment` (spec-0021): item ids and enchantments, by the wave mob's
342/// rule ([`crate::wave::check_equipment`]).
343pub(crate) fn actor_equipment_checks(
344    c: &Campaign,
345    items: &dyn ItemRegistry,
346    d: &mut Vec<Diagnostic>,
347) {
348    let quests = &c.quests.content;
349    // Actor `equipment` (spec-0021): the same shape, the same registries, the
350    // same diagnostics as a wave mob's — one surface, one rule set.
351    for (i, a) in quests.actors.iter().enumerate() {
352        let Some(eq) = &a.equipment else { continue };
353        check_equipment(
354            eq,
355            "actor",
356            &format!("/content/actors/{i}/equipment"),
357            items,
358            d,
359        );
360    }
361}
362
363/// `DW0110` over the scripted-actor ids.
364pub(crate) fn actor_id_syntax(c: &Campaign, d: &mut Vec<Diagnostic>) {
365    for (i, a) in c.quests.content.actors.iter().enumerate() {
366        crate::ids::id_syntax!(d, a.id, "quests", format!("/content/actors/{i}/id"));
367    }
368}
369
370/// `DW0111` over the scripted-actor ids: unique within the stage-5 actors
371/// namespace (DSL v0.6).
372pub(crate) fn actor_id_uniqueness(c: &Campaign, d: &mut Vec<Diagnostic>) {
373    crate::ids::dup_check(
374        c.quests
375            .content
376            .actors
377            .iter()
378            .enumerate()
379            .map(|(i, a)| (a.id.as_str(), format!("/content/actors/{i}/id"))),
380        "quests",
381        "actor",
382        d,
383    );
384}