yog-formats 0.2.0

The schemas of Yog's source formats — .yblock/.yitem, .yrecipe, .ydef, .yres, yog.toml — for the build and the editors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! The `.yitem` and `.yblock` formats in Yog Data: an item or a block, its
//! model (a template or elements) and properties. `yog build` turns them
//! into the game's models, block states, loot tables and the Rust glue.

use yog_data::kinds::Item;
use yog_data::with::{Opt, RefTo};
use yog_data::{Ordered, Reader, Res, Schema, Shape, Text, Value};

use crate::def::{LevelKind, SoundGroupKind, TOOL_LEVELS};

/// Registered by `yog_api::content!()` (`auto`), or by the mod's code.
#[derive(Schema, Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Register {
    #[default]
    Auto,
    Manual,
}

/// What eating it gives.
#[derive(Schema, Debug, Clone)]
pub struct Food {
    #[data(range = "0..=1000")]
    pub nutrition: u32,
    #[data(default, range = "0..=100")]
    pub saturation: f64,
    /// Eaten even when not hungry.
    #[data(default)]
    pub always_edible: bool,
}

/// An item's properties.
#[derive(Schema, Debug, Clone, Default)]
pub struct ItemProps {
    /// How many stack (1–99; 1 with durability).
    #[data(range = "1..=99")]
    pub stack_size: Option<u8>,
    /// Uses before it breaks (0: none).
    #[data(range = "0..=1000000000")]
    pub durability: Option<u32>,
    /// Survives fire and lava.
    #[data(default)]
    pub fire_resistant: bool,
    /// Ticks it burns in a furnace.
    #[data(range = "0..=1000000000")]
    pub fuel_ticks: Option<u32>,
    pub food: Option<Food>,
}

/// A block tag a block joins, as its full id. Tools and tool tiers are
/// tags in Minecraft, so a mod's own are written like any other tag; the
/// game's have short names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockTag(pub String);

/// `pickaxe` → `minecraft:mineable/pickaxe`, or any `@tag:block:mymod:mineable/hammer`.
pub struct ToolTag;

/// A sound group: the game's by short name (`stone`, `amethyst` =
/// `@sound_group:minecraft:amethyst`) or any `@sound_group:…` (a `.ydef`).
pub struct SoundRef;

/// A tool level: the game's by short name (`iron` = `@level:minecraft:iron`)
/// or any `@level:…`.
pub struct LevelRef;

/// The game's tools and tiers, by short name.
pub const TOOLS: [&str; 4] = ["pickaxe", "axe", "shovel", "hoe"];

fn block_tag(
    v: &Value,
    cx: &mut Reader,
    short: &[&str],
    full: fn(&str) -> String,
    what: &str,
) -> Option<BlockTag> {
    match v {
        Value::Str(s) if short.contains(&s.as_str()) => Some(BlockTag(full(s))),
        Value::Str(s) if !s.starts_with('@') => {
            cx.problem(format!(
                "`{s}`: one of {} — or a tag of the mod's own {what}s, `@tag:block:mymod:…`",
                short.join(", ")
            ));
            None
        }
        _ => yog_data::TagId::<yog_data::kinds::Block>::read(v, cx).map(|t| BlockTag(t.id)),
    }
}

impl yog_data::with::With<BlockTag> for ToolTag {
    fn shape() -> Shape {
        Shape::Tag(&["block"])
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<BlockTag> {
        block_tag(v, cx, &TOOLS, |s| format!("minecraft:mineable/{s}"), "tool")
    }
    fn write(f: &BlockTag) -> Value {
        match f.0.strip_prefix("minecraft:mineable/") {
            Some(s) if TOOLS.contains(&s) => Value::from(s),
            _ => Value::Tag(yog_data::Ref::new("block", f.0.clone())),
        }
    }
}

impl yog_data::with::With<String> for LevelRef {
    fn shape() -> Shape {
        Shape::Ref(&["level"])
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<String> {
        match v {
            Value::Str(s) if TOOL_LEVELS.contains(&s.as_str()) => Some(format!("minecraft:{s}")),
            Value::Str(s) if !s.starts_with('@') => {
                cx.problem(format!(
                    "`{s}`: one of {} — or a level of the tool ladder, `@level:mymod:…` (a .ydef)",
                    TOOL_LEVELS.join(", ")
                ));
                None
            }
            _ => yog_data::with::RefTo::<LevelKind>::read(v, cx),
        }
    }
    fn write(f: &String) -> Value {
        match f.strip_prefix("minecraft:") {
            Some(s) if TOOL_LEVELS.contains(&s) => Value::from(s),
            _ => Value::Ref(yog_data::Ref::new("level", f.clone())),
        }
    }
}

impl yog_data::with::With<String> for SoundRef {
    fn shape() -> Shape {
        Shape::Ref(&["sound_group"])
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<String> {
        match v {
            Value::Str(s) if !s.starts_with('@') => match yog_registry::SoundGroup::built_in(s) {
                Some(g) => Some(g.id.clone()),
                None => {
                    cx.problem(format!("`{s}`: not one of the game's sound groups (stone, wood, metal, amethyst…) — a mod's is `@sound_group:mymod:…` (a .ydef)"));
                    None
                }
            },
            _ => yog_data::with::RefTo::<SoundGroupKind>::read(v, cx),
        }
    }
    fn write(f: &String) -> Value {
        match f.strip_prefix("minecraft:") {
            Some(s) if yog_registry::SoundGroup::built_in(s).is_some() => Value::from(s),
            _ => Value::Ref(yog_data::Ref::new("sound_group", f.clone())),
        }
    }
}

/// One value or a list of them, each through `W`.
pub struct OneOrMany<W>(std::marker::PhantomData<W>);

impl<F, W: yog_data::with::With<F>> yog_data::with::With<Vec<F>> for OneOrMany<W> {
    fn shape() -> Shape {
        Shape::List(W::shape)
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<Vec<F>> {
        match v {
            Value::List(_) => yog_data::with::List::<W>::read(v, cx),
            _ => W::read(v, cx).map(|x| vec![x]),
        }
    }
    fn write(f: &Vec<F>) -> Value {
        match f.as_slice() {
            [one] => W::write(one),
            many => Value::List(many.iter().map(W::write).collect()),
        }
    }
    fn absent() -> Option<Vec<F>> {
        Some(Vec::new())
    }
    fn skip(f: &Vec<F>) -> bool {
        f.is_empty()
    }
}

#[derive(Schema, Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderLayer {
    Solid,
    Cutout,
    CutoutMipped,
    Translucent,
}

/// A schema enum's name as written.
pub fn word<T: Schema>(v: &T) -> String {
    v.write().as_str().unwrap_or_default().to_string()
}

/// The collision box: the model's bounds (`auto`), a full cube, or
/// `[x1, y1, z1, x2, y2, z2]` in pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BlockShape {
    Auto,
    Full,
    Box([f64; 6]),
}

impl Schema for BlockShape {
    fn shape() -> Shape {
        Shape::Any
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<Self> {
        match v {
            Value::Str(s) if s == "auto" => Some(BlockShape::Auto),
            Value::Str(s) if s == "full" => Some(BlockShape::Full),
            Value::List(_) => {
                let b = <[f64; 6]>::read(v, cx)?;
                if b.iter().any(|n| !(0.0..=16.0).contains(n)) {
                    cx.problem("a box is [x1, y1, z1, x2, y2, z2] in pixels, 0–16");
                    return None;
                }
                Some(BlockShape::Box(b))
            }
            other => {
                cx.expected(
                    "\"auto\" (the model's bounds), \"full\" or [x1, y1, z1, x2, y2, z2] in pixels",
                    other,
                );
                None
            }
        }
    }
    fn write(&self) -> Value {
        match self {
            BlockShape::Auto => Value::from("auto"),
            BlockShape::Full => Value::from("full"),
            BlockShape::Box(b) => b.write(),
        }
    }
}

/// How many drop: a number, or `[min, max]`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DropCount {
    Exactly(f64),
    Between(f64, f64),
}

impl Schema for DropCount {
    fn shape() -> Shape {
        Shape::Any
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<Self> {
        let n = match v {
            Value::List(_) => {
                let [lo, hi] = <[f64; 2]>::read(v, cx)?;
                (lo, hi, DropCount::Between(lo, hi))
            }
            _ => {
                let n = f64::read(v, cx)?;
                (n, n, DropCount::Exactly(n))
            }
        };
        if !(0.0..=64.0).contains(&n.0) || !(0.0..=64.0).contains(&n.1) || n.0 > n.1 {
            cx.problem("a count is 1–64, or [min, max] within 0–64");
            return None;
        }
        Some(n.2)
    }
    fn write(&self) -> Value {
        match *self {
            DropCount::Exactly(n) => Value::Float(n),
            DropCount::Between(a, b) => Value::List(vec![Value::Float(a), Value::Float(b)]),
        }
    }
}

/// A drop of an item: by default the block's own.
#[derive(Schema, Debug, Clone)]
pub struct DropItem {
    #[data(with = "Opt<RefTo<Item>>")]
    pub item: Option<String>,
    pub count: Option<DropCount>,
}

/// What breaking the block drops: itself, nothing, or an item.
#[derive(Debug, Clone)]
pub enum Drops {
    Itself,
    Nothing,
    Item(DropItem),
}

impl Schema for Drops {
    fn shape() -> Shape {
        Shape::Any
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<Self> {
        match v {
            Value::Str(s) if s == "self" => Some(Drops::Itself),
            Value::Str(s) if s == "none" => Some(Drops::Nothing),
            Value::Map(_) => DropItem::read(v, cx).map(Drops::Item),
            other => {
                cx.expected(
                    "\"self\", \"none\" or { item: \"@item:ns:item\", count: [1, 3] }",
                    other,
                );
                None
            }
        }
    }
    fn write(&self) -> Value {
        match self {
            Drops::Itself => Value::from("self"),
            Drops::Nothing => Value::from("none"),
            Drops::Item(d) => d.write(),
        }
    }
}

/// A block's properties.
#[derive(Schema, Debug, Clone, Default)]
pub struct BlockProps {
    /// Seconds-ish to mine it (-1: unbreakable).
    #[data(range = "-1..=1000000")]
    pub hardness: Option<f64>,
    /// Against explosions.
    #[data(range = "0..=10000000")]
    pub resistance: Option<f64>,
    /// How it sounds: one of the game's sound groups (`stone`, `wood`,
    /// `metal`, `amethyst`, `copper`…) or a mod's (`@sound_group:mymod:crystal`, a `.ydef`).
    #[data(with = "Opt<SoundRef>")]
    pub sound: Option<String>,
    /// Light it gives off, 0–15.
    #[data(range = "0..=15")]
    pub light: Option<u8>,
    /// The tools that mine it fast: `pickaxe`, `axe`, `shovel`, `hoe`, or
    /// a mod's tool tag (`@tag:block:mymod:mineable/hammer`); one or a list.
    #[data(with = "OneOrMany<ToolTag>")]
    pub tool: Vec<BlockTag>,
    /// The tool level it needs: `stone`, `iron`, `diamond`, `netherite`, or
    /// any level of the tool ladder (`@level:mymod:mythril`, a `.ydef`).
    #[data(with = "Opt<LevelRef>")]
    pub tool_level: Option<String>,
    /// Drops nothing without the tool.
    #[data(default)]
    pub requires_tool: bool,
    /// Entities bump into it (`false`: walk through).
    pub collision: Option<bool>,
    #[data(range = "0..=1")]
    pub slipperiness: Option<f64>,
    pub shape: Option<BlockShape>,
    pub render_layer: Option<RenderLayer>,
    pub drops: Option<Drops>,
    /// Blocks it connects to (`states.connect`): these groups' members.
    #[data(default)]
    pub connect_groups: Vec<String>,
    /// The inventory screen it opens: a `.yui` `<Screen id>` with `<Slot>`s.
    pub inventory: Option<String>,
    /// Gives off redstone power, set by the mod per position.
    #[data(default)]
    pub redstone: bool,
}

/// A texture: `#slot`, `@Set.image` (a `.yres` image), a `.png` path in
/// `resources/`, or a texture id (`minecraft:block/stone`).
#[derive(Debug, Clone, PartialEq)]
pub enum Texture {
    Slot(String),
    Res(Res),
    /// A `.png` path or a texture id, as written.
    Plain(String),
}

impl Schema for Texture {
    fn shape() -> Shape {
        Shape::Image
    }
    fn read(v: &Value, cx: &mut Reader) -> Option<Self> {
        match v {
            Value::Res(r) => Some(Texture::Res(r.clone())),
            Value::Str(s) if s.starts_with('#') => {
                if s.len() == 1 {
                    cx.problem("`#` needs a slot name");
                    return None;
                }
                Some(Texture::Slot(s[1..].to_string()))
            }
            Value::Str(s) if s.starts_with('@') => Res::read(v, cx).map(Texture::Res),
            Value::Str(s) => Some(Texture::Plain(s.clone())),
            other => {
                cx.expected("a texture", other);
                None
            }
        }
    }
    fn write(&self) -> Value {
        match self {
            Texture::Slot(s) => Value::Str(format!("#{s}")),
            Texture::Res(r) => Value::Res(r.clone()),
            Texture::Plain(s) => Value::Str(s.clone()),
        }
    }
}

#[derive(Schema, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Axis {
    X,
    Y,
    Z,
}

#[derive(Schema, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    Down,
    Up,
    North,
    South,
    West,
    East,
}

#[derive(Schema, Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuiLight {
    Front,
    Side,
}

/// An element's rotation about one axis.
#[derive(Schema, Debug, Clone)]
pub struct ElementRotation {
    /// The point it turns about; the block's middle by default.
    #[data(range = "-16..=32")]
    pub origin: Option<[f64; 3]>,
    pub axis: Axis,
    /// -45, -22.5, 0, 22.5 or 45 degrees.
    #[data(range = "-45..=45")]
    pub angle: f64,
    #[data(default)]
    pub rescale: bool,
}

/// One face of an element.
#[derive(Schema, Debug, Clone)]
pub struct Face {
    /// `#slot` — a slot of the model's textures.
    pub texture: String,
    #[data(range = "0..=16")]
    pub uv: Option<[f64; 4]>,
    /// 0, 90, 180 or 270.
    pub rotation: Option<u32>,
    /// Not drawn when this side touches a full block.
    pub cullface: Option<Direction>,
    /// The tint index (-1: none).
    #[data(range = "-1..=255")]
    pub tint: Option<i64>,
}

#[derive(Schema, Debug, Clone, Default)]
pub struct Faces {
    pub down: Option<Face>,
    pub up: Option<Face>,
    pub north: Option<Face>,
    pub south: Option<Face>,
    pub west: Option<Face>,
    pub east: Option<Face>,
}

impl Faces {
    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &Face)> {
        [
            ("down", &self.down),
            ("up", &self.up),
            ("north", &self.north),
            ("south", &self.south),
            ("west", &self.west),
            ("east", &self.east),
        ]
        .into_iter()
        .filter_map(|(d, f)| f.as_ref().map(|f| (d, f)))
    }
}

/// A box of a model.
#[derive(Schema, Debug, Clone)]
pub struct Element {
    pub name: Option<String>,
    #[data(range = "-16..=32")]
    pub from: [f64; 3],
    #[data(range = "-16..=32")]
    pub to: [f64; 3],
    pub rotation: Option<ElementRotation>,
    pub shade: Option<bool>,
    pub faces: Option<Faces>,
}

/// How an item model sits in one place.
#[derive(Schema, Debug, Clone)]
pub struct Transform {
    #[data(range = "-360..=360")]
    pub rotation: Option<[f64; 3]>,
    #[data(range = "-80..=80")]
    pub translation: Option<[f64; 3]>,
    #[data(range = "-4..=4")]
    pub scale: Option<[f64; 3]>,
}

#[derive(Schema, Debug, Clone, Default)]
pub struct Display {
    pub thirdperson_righthand: Option<Transform>,
    pub thirdperson_lefthand: Option<Transform>,
    pub firstperson_righthand: Option<Transform>,
    pub firstperson_lefthand: Option<Transform>,
    pub gui: Option<Transform>,
    pub head: Option<Transform>,
    pub ground: Option<Transform>,
    pub fixed: Option<Transform>,
}

impl Display {
    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &Transform)> {
        [
            ("thirdperson_righthand", &self.thirdperson_righthand),
            ("thirdperson_lefthand", &self.thirdperson_lefthand),
            ("firstperson_righthand", &self.firstperson_righthand),
            ("firstperson_lefthand", &self.firstperson_lefthand),
            ("gui", &self.gui),
            ("head", &self.head),
            ("ground", &self.ground),
            ("fixed", &self.fixed),
        ]
        .into_iter()
        .filter_map(|(d, t)| t.as_ref().map(|t| (d, t)))
    }
}

/// A model: a template (`cube_all`, `generated`, …) or a model id as
/// `parent`, its textures, or its own elements.
#[derive(Schema, Debug, Clone)]
pub struct Model {
    pub parent: Option<String>,
    /// Slot → texture.
    #[data(default)]
    pub textures: Ordered<Texture>,
    pub elements: Option<Vec<Element>>,
    pub display: Option<Display>,
    pub ambient_occlusion: Option<bool>,
    pub gui_light: Option<GuiLight>,
}

/// One way the block stands.
#[derive(Schema, Debug, Clone)]
pub struct Rotation {
    /// 0, 90, 180 or 270.
    pub x: Option<u32>,
    /// 0, 90, 180 or 270.
    pub y: Option<u32>,
    #[data(range = "1..=1000000")]
    pub weight: Option<f64>,
    #[data(default)]
    pub uvlock: bool,
}

/// Arms towards neighbours that connect (see `block.connect_groups`).
#[derive(Schema, Debug, Clone)]
pub struct Connect {
    /// The model of the arm towards north.
    pub arm: Model,
    #[data(default)]
    pub uvlock: bool,
}

#[derive(Schema, Debug, Clone)]
pub struct States {
    pub rotations: Option<Vec<Rotation>>,
    pub connect: Option<Connect>,
}

/// A `.yitem`.
#[derive(Schema, Debug, Clone)]
pub struct ItemFile {
    /// The file format; 1.
    pub format: Option<u32>,
    /// Its id; the file's name in the mod's namespace by default.
    pub id: Option<String>,
    pub name: Option<Text>,
    pub tooltip: Option<Text>,
    pub register: Option<Register>,
    pub model: Model,
    pub item: Option<ItemProps>,
}

/// A `.yblock` — the block and its item form.
#[derive(Schema, Debug, Clone)]
pub struct BlockFile {
    pub format: Option<u32>,
    pub id: Option<String>,
    pub name: Option<Text>,
    pub tooltip: Option<Text>,
    pub register: Option<Register>,
    pub model: Model,
    /// The item form's model; the block's by default.
    pub item_model: Option<Model>,
    pub block: Option<BlockProps>,
    pub states: Option<States>,
}