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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
use std::collections::BTreeSet;
use heck::{ToPascalCase, ToShoutySnakeCase};
use proc_macro2::TokenStream;
use quote::quote;
use serde::Deserialize;
use crate::ident;
#[derive(Deserialize, Clone, Debug)]
struct TopLevel {
blocks: Vec<Block>,
shapes: Vec<Shape>,
}
#[derive(Deserialize, Clone, Debug)]
struct Block {
#[allow(unused)]
id: u16,
translation_key: String,
name: String,
properties: Vec<Property>,
default_state_id: u16,
states: Vec<State>,
}
impl Block {
pub fn min_state_id(&self) -> u16 {
self.states.iter().map(|s| s.id).min().unwrap()
}
pub fn max_state_id(&self) -> u16 {
self.states.iter().map(|s| s.id).max().unwrap()
}
}
#[derive(Deserialize, Clone, Debug)]
struct Property {
name: String,
values: Vec<String>,
}
#[derive(Deserialize, Clone, Debug)]
struct State {
id: u16,
luminance: u8,
opaque: bool,
collision_shapes: Vec<u16>,
}
#[derive(Deserialize, Clone, Debug)]
struct Shape {
min_x: f64,
min_y: f64,
min_z: f64,
max_x: f64,
max_y: f64,
max_z: f64,
}
pub fn build() -> anyhow::Result<TokenStream> {
let TopLevel { blocks, shapes } =
serde_json::from_str(include_str!("../extracted/blocks.json"))?;
let max_state_id = blocks.iter().map(|b| b.max_state_id()).max().unwrap();
let kind_to_translation_key_arms = blocks
.iter()
.map(|b| {
let kind = ident(b.name.to_pascal_case());
let translation_key = &b.translation_key;
quote! {
Self::#kind => #translation_key,
}
})
.collect::<TokenStream>();
let state_to_kind_arms = blocks
.iter()
.map(|b| {
let min = b.min_state_id();
let max = b.max_state_id();
let name = ident(&b.name.to_pascal_case());
quote! {
#min..=#max => BlockKind::#name,
}
})
.collect::<TokenStream>();
let state_to_luminance_arms = blocks
.iter()
.flat_map(|b| {
b.states.iter().filter(|s| s.luminance != 0).map(|s| {
let id = s.id;
let luminance = s.luminance;
quote! {
#id => #luminance,
}
})
})
.collect::<TokenStream>();
let state_to_opaque_arms = blocks
.iter()
.flat_map(|b| {
b.states.iter().filter(|s| !s.opaque).map(|s| {
let id = s.id;
quote! {
#id => false,
}
})
})
.collect::<TokenStream>();
let shapes = shapes.iter().map(|s| {
let min_x = s.min_x;
let min_y = s.min_y;
let min_z = s.min_z;
let max_x = s.max_x;
let max_y = s.max_y;
let max_z = s.max_z;
quote! {
[
#min_x,
#min_y,
#min_z,
#max_x,
#max_y,
#max_z,
]
}
});
let shape_count = shapes.len();
let state_to_collision_shapes_arms = blocks
.iter()
.flat_map(|b| {
b.states.iter().map(|s| {
let id = s.id;
let collision_shapes = &s.collision_shapes;
quote! {
#id => &[#(#collision_shapes),*],
}
})
})
.collect::<TokenStream>();
let get_arms = blocks
.iter()
.filter(|&b| !b.properties.is_empty())
.map(|b| {
let block_kind_name = ident(b.name.to_pascal_case());
let arms = b
.properties
.iter()
.map(|p| {
let prop_name = ident(p.name.to_pascal_case());
let min_state_id = b.min_state_id();
let product: u16 = b
.properties
.iter()
.rev()
.take_while(|&other| p.name != other.name)
.map(|p| p.values.len() as u16)
.product();
let values_count = p.values.len() as u16;
let arms = p.values.iter().enumerate().map(|(i, v)| {
let value_idx = i as u16;
let value_name = ident(v.to_pascal_case());
quote! {
#value_idx => Some(PropValue::#value_name),
}
}).collect::<TokenStream>();
quote! {
PropName::#prop_name => match (self.0 - #min_state_id) / #product % #values_count {
#arms
_ => unreachable!(),
},
}
})
.collect::<TokenStream>();
quote! {
BlockKind::#block_kind_name => match name {
#arms
_ => None,
},
}
})
.collect::<TokenStream>();
let set_arms = blocks
.iter()
.filter(|&b| !b.properties.is_empty())
.map(|b| {
let block_kind_name = ident(b.name.to_pascal_case());
let arms = b
.properties
.iter()
.map(|p| {
let prop_name = ident(p.name.to_pascal_case());
let min_state_id = b.min_state_id();
let product: u16 = b
.properties
.iter()
.rev()
.take_while(|&other| p.name != other.name)
.map(|p| p.values.len() as u16)
.product();
let values_count = p.values.len() as u16;
let arms = p
.values
.iter()
.enumerate()
.map(|(i, v)| {
let val_idx = i as u16;
let val_name = ident(v.to_pascal_case());
quote! {
PropValue::#val_name =>
Self(self.0 - (self.0 - #min_state_id) / #product % #values_count * #product
+ #val_idx * #product),
}
})
.collect::<TokenStream>();
quote! {
PropName::#prop_name => match val {
#arms
_ => self,
},
}
})
.collect::<TokenStream>();
quote! {
BlockKind::#block_kind_name => match name {
#arms
_ => self,
},
}
})
.collect::<TokenStream>();
let default_block_states = blocks
.iter()
.map(|b| {
let name = ident(b.name.to_shouty_snake_case());
let state = b.default_state_id;
let doc = format!("The default block state for `{}`.", b.name);
quote! {
#[doc = #doc]
pub const #name: BlockState = BlockState(#state);
}
})
.collect::<TokenStream>();
let kind_to_state_arms = blocks
.iter()
.map(|b| {
let kind = ident(b.name.to_pascal_case());
let state = ident(b.name.to_shouty_snake_case());
quote! {
BlockKind::#kind => BlockState::#state,
}
})
.collect::<TokenStream>();
let block_kind_variants = blocks
.iter()
.map(|b| ident(b.name.to_pascal_case()))
.collect::<Vec<_>>();
let block_kind_from_str_arms = blocks
.iter()
.map(|b| {
let name = &b.name;
let name_ident = ident(name.to_pascal_case());
quote! {
#name => Some(BlockKind::#name_ident),
}
})
.collect::<TokenStream>();
let block_kind_to_str_arms = blocks
.iter()
.map(|b| {
let name = &b.name;
let name_ident = ident(name.to_pascal_case());
quote! {
BlockKind::#name_ident => #name,
}
})
.collect::<TokenStream>();
let block_kind_props_arms = blocks
.iter()
.filter(|&b| !b.properties.is_empty())
.map(|b| {
let name = ident(b.name.to_pascal_case());
let prop_names = b.properties.iter().map(|p| ident(p.name.to_pascal_case()));
quote! {
Self::#name => &[#(PropName::#prop_names,)*],
}
})
.collect::<TokenStream>();
let block_kind_count = blocks.len();
let prop_names = blocks
.iter()
.flat_map(|b| b.properties.iter().map(|p| p.name.as_str()))
.collect::<BTreeSet<_>>();
let prop_name_variants = prop_names
.iter()
.map(|&name| ident(name.to_pascal_case()))
.collect::<Vec<_>>();
let prop_name_from_str_arms = prop_names
.iter()
.map(|&name| {
let ident = ident(name.to_pascal_case());
quote! {
#name => Some(PropName::#ident),
}
})
.collect::<TokenStream>();
let prop_name_to_str_arms = prop_names
.iter()
.map(|&name| {
let ident = ident(name.to_pascal_case());
quote! {
PropName::#ident => #name,
}
})
.collect::<TokenStream>();
let prop_name_count = prop_names.len();
let prop_values = blocks
.iter()
.flat_map(|b| b.properties.iter().flat_map(|p| &p.values))
.map(|s| s.as_str())
.collect::<BTreeSet<_>>();
let prop_value_variants = prop_values
.iter()
.map(|val| ident(val.to_pascal_case()))
.collect::<Vec<_>>();
let prop_value_from_str_arms = prop_values
.iter()
.map(|val| {
let ident = ident(val.to_pascal_case());
quote! {
#val => Some(PropValue::#ident),
}
})
.collect::<TokenStream>();
let prop_value_to_str_arms = prop_values
.iter()
.map(|val| {
let ident = ident(val.to_pascal_case());
quote! {
PropValue::#ident => #val,
}
})
.collect::<TokenStream>();
let prop_value_from_u16_arms = prop_values
.iter()
.filter_map(|v| v.parse::<u16>().ok())
.map(|n| {
let ident = ident(n.to_string());
quote! {
#n => Some(PropValue::#ident),
}
})
.collect::<TokenStream>();
let prop_value_to_u16_arms = prop_values
.iter()
.filter_map(|v| v.parse::<u16>().ok())
.map(|n| {
let ident = ident(n.to_string());
quote! {
PropValue::#ident => Some(#n),
}
})
.collect::<TokenStream>();
let prop_value_count = prop_values.len();
Ok(quote! {
/// Represents the state of a block. This does not include block entity data such as
/// the text on a sign, the design on a banner, or the content of a spawner.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
pub struct BlockState(u16);
impl BlockState {
/// Returns the default block state for a given block type.
pub const fn from_kind(kind: BlockKind) -> Self {
match kind {
#kind_to_state_arms
}
}
/// Constructs a block state from a raw block state ID.
///
/// If the given ID is invalid, `None` is returned.
pub const fn from_raw(id: u16) -> Option<Self> {
if id <= #max_state_id {
Some(Self(id))
} else {
None
}
}
pub(crate) const fn from_raw_unchecked(id: u16) -> Self {
debug_assert!(Self::from_raw(id).is_some());
Self(id)
}
/// Returns the [`BlockKind`] of this block state.
pub const fn to_kind(self) -> BlockKind {
match self.0 {
#state_to_kind_arms
_ => unreachable!(),
}
}
/// Converts this block state to its underlying raw block state ID.
///
/// The original block state can be recovered with [`BlockState::from_raw`].
pub const fn to_raw(self) -> u16 {
self.0
}
/// Returns the maximum block state ID.
pub const fn max_raw() -> u16 {
#max_state_id
}
/// Gets the value of the property with the given name from this block.
///
/// If this block does not have the property, then `None` is returned.
pub const fn get(self, name: PropName) -> Option<PropValue> {
match self.to_kind() {
#get_arms
_ => None
}
}
/// Sets the value of a property on this block, returning the modified block.
///
/// If this block does not have the given property or the property value is invalid,
/// then the original block is returned unchanged.
#[must_use]
pub const fn set(self, name: PropName, val: PropValue) -> Self {
match self.to_kind() {
#set_arms
_ => self,
}
}
/// If this block is `air`, `cave_air` or `void_air`.
pub const fn is_air(self) -> bool {
matches!(
self.to_kind(),
BlockKind::Air | BlockKind::CaveAir | BlockKind::VoidAir
)
}
// TODO: is_solid
/// If this block is water or lava.
pub const fn is_liquid(self) -> bool {
matches!(self.to_kind(), BlockKind::Water | BlockKind::Lava)
}
pub const fn is_opaque(self) -> bool {
match self.0 {
#state_to_opaque_arms
_ => true,
}
}
const SHAPES: [[f64; 6]; #shape_count] = [
#(#shapes,)*
];
pub fn collision_shapes(self) -> impl ExactSizeIterator<Item = vek::Aabb<f64>> + FusedIterator + Clone {
let shape_idxs: &'static [u16] = match self.0 {
#state_to_collision_shapes_arms
_ => &[],
};
shape_idxs.iter().map(|idx| {
let [min_x, min_y, min_z, max_x, max_y, max_z] = Self::SHAPES[*idx as usize];
vek::Aabb {
min: vek::Vec3::new(min_x, min_y, min_z),
max: vek::Vec3::new(max_x, max_y, max_z),
}
})
}
pub const fn luminance(self) -> u8 {
match self.0 {
#state_to_luminance_arms
_ => 0,
}
}
#default_block_states
}
/// An enumeration of all block kinds.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum BlockKind {
#(#block_kind_variants,)*
}
impl BlockKind {
/// Construct a block kind from its snake_case name.
///
/// Returns `None` if the name is invalid.
pub fn from_str(name: &str) -> Option<BlockKind> {
match name {
#block_kind_from_str_arms
_ => None
}
}
/// Get the snake_case name of this block kind.
pub const fn to_str(self) -> &'static str {
match self {
#block_kind_to_str_arms
}
}
/// Returns the default block state for a given block kind.
pub const fn to_state(self) -> BlockState {
BlockState::from_kind(self)
}
/// Returns a slice of all properties this block kind has.
pub const fn props(self) -> &'static [PropName] {
match self {
#block_kind_props_arms
_ => &[],
}
}
pub const fn translation_key(self) -> &'static str {
match self {
#kind_to_translation_key_arms
}
}
/// An array of all block kinds.
pub const ALL: [Self; #block_kind_count] = [#(Self::#block_kind_variants,)*];
}
/// The default block kind is `air`.
impl Default for BlockKind {
fn default() -> Self {
Self::Air
}
}
/// Contains all possible block state property names.
///
/// For example, `waterlogged`, `facing`, and `half` are all property names.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum PropName {
#(#prop_name_variants,)*
}
impl PropName {
/// Construct a property name from its snake_case name.
///
/// Returns `None` if the given name is not valid.
pub fn from_str(name: &str) -> Option<Self> {
// TODO: match on str in const fn.
match name {
#prop_name_from_str_arms
_ => None,
}
}
/// Get the snake_case name of this property name.
pub const fn to_str(self) -> &'static str {
match self {
#prop_name_to_str_arms
}
}
/// An array of all property names.
pub const ALL: [Self; #prop_name_count] = [#(Self::#prop_name_variants,)*];
}
/// Contains all possible values that a block property might have.
///
/// For example, `upper`, `true`, and `2` are all property values.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum PropValue {
#(#prop_value_variants,)*
}
impl PropValue {
/// Construct a property value from its snake_case name.
///
/// Returns `None` if the given name is not valid.
pub fn from_str(name: &str) -> Option<Self> {
match name {
#prop_value_from_str_arms
_ => None,
}
}
/// Get the snake_case name of this property value.
pub const fn to_str(self) -> &'static str {
match self {
#prop_value_to_str_arms
}
}
/// Converts a `u16` into a numeric property value.
/// Returns `None` if the given number does not have a
/// corresponding property value.
pub const fn from_u16(n: u16) -> Option<Self> {
match n {
#prop_value_from_u16_arms
_ => None,
}
}
/// Converts this property value into a `u16` if it is numeric.
/// Returns `None` otherwise.
pub const fn to_u16(self) -> Option<u16> {
match self {
#prop_value_to_u16_arms
_ => None,
}
}
/// Converts a `bool` to a `True` or `False` property value.
pub const fn from_bool(b: bool) -> Self {
if b {
Self::True
} else {
Self::False
}
}
/// Converts a `True` or `False` property value to a `bool`.
///
/// Returns `None` if this property value is not `True` or `False`
pub const fn to_bool(self) -> Option<bool> {
match self {
Self::True => Some(true),
Self::False => Some(false),
_ => None,
}
}
/// An array of all property values.
pub const ALL: [Self; #prop_value_count] = [#(Self::#prop_value_variants,)*];
}
impl From<bool> for PropValue {
fn from(b: bool) -> Self {
Self::from_bool(b)
}
}
})
}