1use nadir_assets::{Asset, AssetPath, Handle};
42use nadir_codec::json::Value;
43use nadir_core::{Color, IVec2, Rect, Vec2};
44
45use crate::{
46 FieldInfo, FromValue, Reflect, ReflectContext, ReflectError, ReflectErrorKind, ReflectKind,
47};
48
49macro_rules! primitive {
52 ($name:expr) => {
53 fn type_name(&self) -> &'static str {
54 $name
55 }
56
57 fn kind(&self) -> ReflectKind {
58 ReflectKind::Primitive
59 }
60
61 fn fields(&self) -> &'static [FieldInfo] {
62 &[]
63 }
64
65 fn field(&self, _index: usize) -> Option<&dyn Reflect> {
66 None
67 }
68
69 fn field_mut(&mut self, _index: usize) -> Option<&mut dyn Reflect> {
70 None
71 }
72
73 fn apply_value(
74 &mut self,
75 value: &Value,
76 cx: &mut ReflectContext<'_>,
77 ) -> Result<(), ReflectError> {
78 *self = Self::from_value(value, cx)?;
79 Ok(())
80 }
81 };
82}
83
84macro_rules! integers {
85 ($($int:ty),*) => {$(
86 impl Reflect for $int {
87 primitive!(stringify!($int));
88
89 fn to_value(&self, _cx: &mut ReflectContext<'_>) -> Value {
90 match i64::try_from(*self) {
91 Ok(value) => Value::Int(value),
92 Err(_) => Value::String(self.to_string()),
93 }
94 }
95 }
96
97 impl FromValue for $int {
98 const TYPE_NAME: &'static str = stringify!($int);
99
100 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
101 let out_of_range = |cx: &ReflectContext<'_>, text: String| {
102 cx.error(ReflectErrorKind::OutOfRange {
103 type_name: Self::TYPE_NAME,
104 value: text,
105 })
106 };
107 match value {
108 Value::Int(int) => <$int>::try_from(*int).map_err(|_| out_of_range(cx, int.to_string())),
109 Value::String(digits) => match digits.parse::<$int>() {
111 Ok(int) if i64::try_from(int).is_err() => Ok(int),
112 Err(_) if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) => {
113 Err(out_of_range(cx, digits.clone()))
114 }
115 _ => Err(cx.expected("an integer", value)),
116 },
117 _ => Err(cx.expected("an integer", value)),
118 }
119 }
120 }
121 )*};
122}
123
124integers!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
125
126impl Reflect for f64 {
127 primitive!("f64");
128
129 fn to_value(&self, _cx: &mut ReflectContext<'_>) -> Value {
130 Value::Float(*self)
131 }
132}
133
134impl FromValue for f64 {
135 const TYPE_NAME: &'static str = "f64";
136
137 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
138 match *value {
139 Value::Float(float) => Ok(float),
140 Value::Int(int) => Ok(int as f64),
141 _ => Err(cx.expected("a number", value)),
142 }
143 }
144}
145
146impl Reflect for f32 {
147 primitive!("f32");
148
149 fn to_value(&self, _cx: &mut ReflectContext<'_>) -> Value {
150 Value::Float(f64::from(*self))
151 }
152}
153
154impl FromValue for f32 {
155 const TYPE_NAME: &'static str = "f32";
156
157 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
158 let wide = f64::from_value(value, cx)?;
159 let narrow = wide as f32;
160 if wide.is_finite() && narrow.is_infinite() {
162 return Err(cx.error(ReflectErrorKind::OutOfRange {
163 type_name: Self::TYPE_NAME,
164 value: wide.to_string(),
165 }));
166 }
167 Ok(narrow)
168 }
169}
170
171impl Reflect for bool {
172 primitive!("bool");
173
174 fn to_value(&self, _cx: &mut ReflectContext<'_>) -> Value {
175 Value::Bool(*self)
176 }
177}
178
179impl FromValue for bool {
180 const TYPE_NAME: &'static str = "bool";
181
182 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
183 value
184 .as_bool()
185 .ok_or_else(|| cx.expected("a boolean", value))
186 }
187}
188
189impl Reflect for String {
190 primitive!("String");
191
192 fn to_value(&self, _cx: &mut ReflectContext<'_>) -> Value {
193 Value::String(self.clone())
194 }
195}
196
197impl FromValue for String {
198 const TYPE_NAME: &'static str = "String";
199
200 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
201 value
202 .as_str()
203 .map(str::to_string)
204 .ok_or_else(|| cx.expected("a string", value))
205 }
206}
207
208fn pair<'v>(
210 value: &'v Value,
211 cx: &ReflectContext<'_>,
212) -> Result<(&'v Value, &'v Value), ReflectError> {
213 match value.as_array() {
214 Some([x, y]) => Ok((x, y)),
215 Some(other) => Err(cx.error(ReflectErrorKind::WrongLength {
216 expected: 2,
217 found: other.len(),
218 })),
219 None => Err(cx.expected("an array `[x, y]`", value)),
220 }
221}
222
223impl Reflect for Vec2 {
224 primitive!("Vec2");
225
226 fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
227 Value::Array(vec![self.x.to_value(cx), self.y.to_value(cx)])
228 }
229}
230
231impl FromValue for Vec2 {
232 const TYPE_NAME: &'static str = "Vec2";
233
234 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
235 let (x, y) = pair(value, cx)?;
236 let x = cx.index(0, |cx| f32::from_value(x, cx))?;
237 let y = cx.index(1, |cx| f32::from_value(y, cx))?;
238 Ok(Vec2::new(x, y))
239 }
240}
241
242impl Reflect for IVec2 {
243 primitive!("IVec2");
244
245 fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
246 Value::Array(vec![self.x.to_value(cx), self.y.to_value(cx)])
247 }
248}
249
250impl FromValue for IVec2 {
251 const TYPE_NAME: &'static str = "IVec2";
252
253 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
254 let (x, y) = pair(value, cx)?;
255 let x = cx.index(0, |cx| i32::from_value(x, cx))?;
256 let y = cx.index(1, |cx| i32::from_value(y, cx))?;
257 Ok(IVec2::new(x, y))
258 }
259}
260
261impl Reflect for Color {
262 primitive!("Color");
263
264 fn to_value(&self, _cx: &mut ReflectContext<'_>) -> Value {
265 let Color { r, g, b, a } = *self;
266 Value::String(if a == u8::MAX {
267 format!("#{r:02x}{g:02x}{b:02x}")
268 } else {
269 format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
270 })
271 }
272}
273
274impl FromValue for Color {
275 const TYPE_NAME: &'static str = "Color";
276
277 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
278 let text = value
279 .as_str()
280 .ok_or_else(|| cx.expected("a color `#rrggbb` or `#rrggbbaa`", value))?;
281 text.strip_prefix('#')
283 .filter(|digits| !digits.starts_with('#'))
284 .and_then(|digits| Color::from_hex(digits).ok())
285 .ok_or_else(|| cx.error(ReflectErrorKind::BadColor(text.to_string())))
286 }
287}
288
289impl Reflect for Rect {
290 fn type_name(&self) -> &'static str {
291 "Rect"
292 }
293
294 fn kind(&self) -> ReflectKind {
295 ReflectKind::Primitive
296 }
297
298 fn fields(&self) -> &'static [FieldInfo] {
299 &[]
300 }
301
302 fn field(&self, _index: usize) -> Option<&dyn Reflect> {
303 None
304 }
305
306 fn field_mut(&mut self, _index: usize) -> Option<&mut dyn Reflect> {
307 None
308 }
309
310 fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
311 Value::Object(vec![
312 ("min".to_string(), self.min.to_value(cx)),
313 ("max".to_string(), self.max.to_value(cx)),
314 ])
315 }
316
317 fn apply_value(
320 &mut self,
321 value: &Value,
322 cx: &mut ReflectContext<'_>,
323 ) -> Result<(), ReflectError> {
324 let members = value
325 .as_object()
326 .ok_or_else(|| cx.expected("an object `{\"min\": [x, y], \"max\": [x, y]}`", value))?;
327 for (key, member) in members {
328 match key.as_str() {
329 "min" => self.min = cx.field("min", |cx| Vec2::from_value(member, cx))?,
330 "max" => self.max = cx.field("max", |cx| Vec2::from_value(member, cx))?,
331 _ => cx.unknown_field(<Self as FromValue>::TYPE_NAME, key),
332 }
333 }
334 Ok(())
335 }
336}
337
338impl FromValue for Rect {
339 const TYPE_NAME: &'static str = "Rect";
340
341 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
342 let mut rect = Rect::default();
343 rect.apply_value(value, cx)?;
344 Ok(rect)
345 }
346}
347
348impl<T: FromValue> Reflect for Option<T> {
349 fn type_name(&self) -> &'static str {
350 "Option"
351 }
352
353 fn kind(&self) -> ReflectKind {
354 ReflectKind::Option
355 }
356
357 fn fields(&self) -> &'static [FieldInfo] {
358 &[]
359 }
360
361 fn field(&self, index: usize) -> Option<&dyn Reflect> {
362 match self {
363 Some(inner) if index == 0 => Some(inner),
364 _ => None,
365 }
366 }
367
368 fn field_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
369 match self {
370 Some(inner) if index == 0 => Some(inner),
371 _ => None,
372 }
373 }
374
375 fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
376 match self {
377 Some(inner) => inner.to_value(cx),
378 None => Value::Null,
379 }
380 }
381
382 fn apply_value(
385 &mut self,
386 value: &Value,
387 cx: &mut ReflectContext<'_>,
388 ) -> Result<(), ReflectError> {
389 match (self.as_mut(), value) {
390 (_, Value::Null) => *self = None,
391 (Some(inner), _) => inner.apply_value(value, cx)?,
392 (None, _) => *self = Some(T::from_value(value, cx)?),
393 }
394 Ok(())
395 }
396}
397
398impl<T: FromValue> FromValue for Option<T> {
399 const TYPE_NAME: &'static str = "Option";
400
401 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
402 match value {
403 Value::Null => Ok(None),
404 _ => T::from_value(value, cx).map(Some),
405 }
406 }
407}
408
409impl<T: FromValue> Reflect for Vec<T> {
410 fn type_name(&self) -> &'static str {
411 "Vec"
412 }
413
414 fn kind(&self) -> ReflectKind {
415 ReflectKind::List
416 }
417
418 fn fields(&self) -> &'static [FieldInfo] {
419 &[]
420 }
421
422 fn field(&self, index: usize) -> Option<&dyn Reflect> {
423 self.get(index).map(|element| element as &dyn Reflect)
424 }
425
426 fn field_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
427 self.get_mut(index)
428 .map(|element| element as &mut dyn Reflect)
429 }
430
431 fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
432 Value::Array(self.iter().map(|element| element.to_value(cx)).collect())
433 }
434
435 fn apply_value(
436 &mut self,
437 value: &Value,
438 cx: &mut ReflectContext<'_>,
439 ) -> Result<(), ReflectError> {
440 *self = Self::from_value(value, cx)?;
441 Ok(())
442 }
443}
444
445impl<T: FromValue> FromValue for Vec<T> {
446 const TYPE_NAME: &'static str = "Vec";
447
448 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
449 let elements = value
450 .as_array()
451 .ok_or_else(|| cx.expected("an array", value))?;
452 elements
453 .iter()
454 .enumerate()
455 .map(|(index, element)| cx.index(index, |cx| T::from_value(element, cx)))
456 .collect()
457 }
458}
459
460impl<T: Asset> Reflect for Handle<T> {
461 fn type_name(&self) -> &'static str {
462 "Handle"
463 }
464
465 fn kind(&self) -> ReflectKind {
466 ReflectKind::Handle
467 }
468
469 fn fields(&self) -> &'static [FieldInfo] {
470 &[]
471 }
472
473 fn field(&self, _index: usize) -> Option<&dyn Reflect> {
474 None
475 }
476
477 fn field_mut(&mut self, _index: usize) -> Option<&mut dyn Reflect> {
478 None
479 }
480
481 fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
482 match cx.assets().and_then(|server| server.path(*self)) {
483 Some(path) => Value::String(path.to_string()),
484 None => {
485 cx.warn("an asset handle the asset server does not know is written as null");
486 Value::Null
487 }
488 }
489 }
490
491 fn apply_value(
492 &mut self,
493 value: &Value,
494 cx: &mut ReflectContext<'_>,
495 ) -> Result<(), ReflectError> {
496 *self = Self::from_value(value, cx)?;
497 Ok(())
498 }
499}
500
501impl<T: Asset> FromValue for Handle<T> {
502 const TYPE_NAME: &'static str = "Handle";
503
504 fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
505 let text = value
506 .as_str()
507 .ok_or_else(|| cx.expected("an asset path, a string", value))?;
508 let bad = |cx: &ReflectContext<'_>, reason: String| {
509 cx.error(ReflectErrorKind::BadAssetPath {
510 path: text.to_string(),
511 reason,
512 })
513 };
514 let path = AssetPath::new(text).map_err(|error| bad(cx, error.to_string()))?;
515 if !path
516 .extension()
517 .is_some_and(|extension| T::EXTENSIONS.contains(&extension))
518 {
519 let reason = format!("its file ends in one of {}", T::EXTENSIONS.join(", "));
520 return Err(bad(cx, reason));
521 }
522 if cx.assets_mut().is_none() {
523 return Err(cx.error(ReflectErrorKind::NoContext {
524 needs: "the asset server, to load an asset",
525 }));
526 }
527 let (server, scope) = cx.assets_mut().expect("checked above");
528 Ok(server.load_in(path.as_str(), scope))
529 }
530}