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
use super::*;

/// A type data that can be used to specify a custom metatable to use for the type when it is
/// used in an [`EcsRef`] in the lua API.
#[derive(HasSchema)]
#[schema(no_clone, no_default)]
pub struct SchemaLuaEcsRefMetatable(pub fn(piccolo::Context) -> piccolo::Table);

/// A reference to an ECS-compatible value.
#[derive(Clone)]
pub struct EcsRef {
    /// The kind of reference.
    pub data: EcsRefData,
    /// The path to the desired field.
    pub path: Ustr,
}
impl Default for EcsRef {
    fn default() -> Self {
        #[derive(HasSchema, Clone, Default)]
        struct Void;
        Self {
            data: EcsRefData::Free(Rc::new(AtomicCell::new(SchemaBox::new(Void)))),
            path: default(),
        }
    }
}
impl<'gc> FromValue<'gc> for &'gc EcsRef {
    fn from_value(_ctx: Context<'gc>, value: Value<'gc>) -> Result<Self, piccolo::TypeError> {
        value.as_static_user_data::<EcsRef>()
    }
}

impl EcsRef {
    /// Borrow the value pointed to by the [`EcsRef`]
    pub fn borrow(&self) -> EcsRefBorrow {
        EcsRefBorrow {
            borrow: self.data.borrow(),
            path: self.path,
        }
    }

    /// Mutably borrow the value pointed to by the [`EcsRef`]
    pub fn borrow_mut(&self) -> EcsRefBorrowMut {
        EcsRefBorrowMut {
            borrow: self.data.borrow_mut(),
            path: self.path,
        }
    }

    /// Convert into a lua value.
    pub fn into_value(self, ctx: Context) -> Value {
        let metatable = ctx.singletons().get(ctx, self.metatable_fn());
        let ecsref = UserData::new_static(&ctx, self);
        ecsref.set_metatable(&ctx, Some(metatable));
        ecsref.into()
    }
}

/// A borrow of an [`EcsRef`].
pub struct EcsRefBorrow<'a> {
    borrow: EcsRefBorrowKind<'a>,
    path: Ustr,
}

impl EcsRefBorrow<'_> {
    /// Get the [`SchemaRef`].
    pub fn schema_ref(&self) -> Result<SchemaRef, EcsRefBorrowError> {
        let b = self.borrow.schema_ref()?;
        let b = b
            .field_path(FieldPath(self.path))
            .ok_or(EcsRefBorrowError::FieldNotFound(self.path))?;
        Ok(b)
    }
}

/// A mutable borrow of an [`EcsRef`].
pub struct EcsRefBorrowMut<'a> {
    borrow: EcsRefBorrowMutKind<'a>,
    path: Ustr,
}

impl EcsRefBorrowMut<'_> {
    /// Get the [`SchemaRef`].
    pub fn schema_ref_mut(&mut self) -> Result<SchemaRefMut, EcsRefBorrowError> {
        let b = self.borrow.schema_ref_mut()?;
        let b = b
            .into_field_path(FieldPath(self.path))
            .ok_or(EcsRefBorrowError::FieldNotFound(self.path))?;
        Ok(b)
    }
}

/// The kind of value reference for [`EcsRef`].
#[derive(Clone)]
pub enum EcsRefData {
    /// A resource ref.
    Resource(AtomicUntypedResource),
    /// A component ref.
    Component(ComponentRef),
    /// An asset ref.
    Asset(AssetRef),
    /// A free-standing ref, not stored in the ECS.
    // TODO: use a `Gc` pointer instead of an Rc maybe.
    Free(Rc<AtomicCell<SchemaBox>>),
}

/// A kind of borrow into an [`EcsRef`].
pub enum EcsRefBorrowKind<'a> {
    Resource(Ref<'a, Option<SchemaBox>>),
    Component(ComponentBorrow<'a>),
    Free(Ref<'a, SchemaBox>),
    Asset(Option<MappedRef<'a, Cid, LoadedAsset, SchemaBox>>),
}

/// An error that occurs when borrowing an [`EcsRef`].
#[derive(Debug)]
pub enum EcsRefBorrowError {
    MissingResource,
    MissingComponent {
        entity: Entity,
        component_name: &'static str,
    },
    AssetNotLoaded,
    FieldNotFound(Ustr),
}
impl std::error::Error for EcsRefBorrowError {}
impl std::fmt::Display for EcsRefBorrowError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EcsRefBorrowError::MissingComponent {
                entity,
                component_name,
            } => write!(
                f,
                "Cannot access variable because entity {entity:?} no longer has the \
                component `{component_name}`. This may happen if you remove the cmponent \
                while you still have a variable referencing the component data, and you \
                then try to access the component data through the variable."
            ),
            EcsRefBorrowError::AssetNotLoaded => write!(f, "Asset not loaded"),
            EcsRefBorrowError::FieldNotFound(field) => write!(f, "Field not found: {field}"),
            EcsRefBorrowError::MissingResource => {
                write!(f, "Resource not in world.")
            }
        }
    }
}

impl EcsRefBorrowKind<'_> {
    /// Get the borrow as a [`SchemaRef`].
    ///
    /// Will return none if the value does not exist, such as an unloaded asset or a component
    /// that is not set for a given entity.
    pub fn schema_ref(&self) -> Result<SchemaRef, EcsRefBorrowError> {
        match self {
            EcsRefBorrowKind::Resource(r) => Ok(r
                .as_ref()
                .ok_or(EcsRefBorrowError::MissingResource)?
                .as_ref()),
            EcsRefBorrowKind::Component(c) => {
                c.borrow
                    .get_ref(c.entity)
                    .ok_or(EcsRefBorrowError::MissingComponent {
                        entity: c.entity,
                        component_name: &c.borrow.schema().full_name,
                    })
            }
            EcsRefBorrowKind::Free(f) => Ok(f.as_ref()),
            EcsRefBorrowKind::Asset(a) => a
                .as_ref()
                .map(|x| x.as_ref())
                .ok_or(EcsRefBorrowError::AssetNotLoaded),
        }
    }
}

/// A component borrow into an [`EcsRef`].
pub struct ComponentBorrow<'a> {
    pub borrow: Ref<'a, UntypedComponentStore>,
    pub entity: Entity,
}

/// A mutable component borrow into an [`EcsRef`].
pub struct ComponentBorrowMut<'a> {
    pub borrow: RefMut<'a, UntypedComponentStore>,
    pub entity: Entity,
}

/// A kind of mutable borrow of an [`EcsRef`].
pub enum EcsRefBorrowMutKind<'a> {
    Resource(RefMut<'a, Option<SchemaBox>>),
    Component(ComponentBorrowMut<'a>),
    Free(RefMut<'a, SchemaBox>),
    Asset(Option<MappedRefMut<'a, Cid, LoadedAsset, SchemaBox>>),
}

impl EcsRefBorrowMutKind<'_> {
    /// Get the borrow as a [`SchemaRefMut`].
    ///
    /// Will return none if the value does not exist, such as an unloaded asset or a component
    /// that is not set for a given entity.
    pub fn schema_ref_mut(&mut self) -> Result<SchemaRefMut, EcsRefBorrowError> {
        match self {
            EcsRefBorrowMutKind::Resource(r) => Ok(r
                .as_mut()
                .ok_or(EcsRefBorrowError::MissingResource)?
                .as_mut()),
            EcsRefBorrowMutKind::Component(c) => {
                c.borrow
                    .get_ref_mut(c.entity)
                    .ok_or(EcsRefBorrowError::MissingComponent {
                        entity: c.entity,
                        component_name: &c.borrow.schema().full_name,
                    })
            }
            EcsRefBorrowMutKind::Free(f) => Ok(f.as_mut()),
            EcsRefBorrowMutKind::Asset(a) => a
                .as_mut()
                .map(|x| x.as_mut())
                .ok_or(EcsRefBorrowError::AssetNotLoaded),
        }
    }
}

impl EcsRefData {
    /// Immutably borrow the data.
    pub fn borrow(&self) -> EcsRefBorrowKind {
        match self {
            EcsRefData::Resource(resource) => {
                let b = resource.as_ref().borrow();
                EcsRefBorrowKind::Resource(b)
            }
            EcsRefData::Component(componentref) => {
                let b = componentref.store.as_ref();
                EcsRefBorrowKind::Component(ComponentBorrow {
                    borrow: b.borrow(),
                    entity: componentref.entity,
                })
            }
            EcsRefData::Asset(assetref) => {
                let b = assetref.server.try_get_untyped(assetref.handle);
                EcsRefBorrowKind::Asset(b)
            }
            EcsRefData::Free(rc) => {
                let b = rc.as_ref();
                EcsRefBorrowKind::Free(b.borrow())
            }
        }
    }

    /// Mutably borrow the data.
    pub fn borrow_mut(&self) -> EcsRefBorrowMutKind {
        match self {
            EcsRefData::Resource(resource) => {
                let b = resource.borrow_mut();
                EcsRefBorrowMutKind::Resource(b)
            }
            EcsRefData::Component(componentref) => {
                let b = componentref.store.borrow_mut();
                EcsRefBorrowMutKind::Component(ComponentBorrowMut {
                    borrow: b,
                    entity: componentref.entity,
                })
            }
            EcsRefData::Asset(assetref) => {
                let b = assetref.server.try_get_untyped_mut(assetref.handle);
                EcsRefBorrowMutKind::Asset(b)
            }
            EcsRefData::Free(rc) => {
                let b = rc.borrow_mut();
                EcsRefBorrowMutKind::Free(b)
            }
        }
    }
}

/// A reference to component in an [`EcsRef`].
#[derive(Clone)]
pub struct ComponentRef {
    /// The component store.
    pub store: UntypedAtomicComponentStore,
    /// The entity to get the component data for.
    pub entity: Entity,
}

/// A reference to an asset in an [`EcsRef`]
#[derive(Clone)]
pub struct AssetRef {
    /// The asset server handle.
    pub server: AssetServer,
    /// The kind of asset we are referencing.
    pub handle: UntypedHandle,
}

pub fn metatable(ctx: Context) -> Table {
    let metatable = Table::new(&ctx);

    metatable
        .set(
            ctx,
            "__tostring",
            Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
                let this: &EcsRef = stack.consume(ctx)?;

                let b = this.borrow();
                if let Ok(value) = b.schema_ref() {
                    let access = value.access();
                    stack.push_front(Value::String(piccolo::String::from_slice(
                        &ctx,
                        format!("{access:?}"),
                    )));
                }
                Ok(CallbackReturn::Return)
            }),
        )
        .unwrap();
    metatable
        .set(
            ctx,
            "__index",
            Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
                let (this, key): (&EcsRef, lua::Value) = stack.consume(ctx)?;

                let mut newref = this.clone();
                newref.path = ustr(&format!("{}.{key}", this.path));
                let b = newref.borrow();

                match b.schema_ref()?.access() {
                    SchemaRefAccess::Primitive(p) if !matches!(p, PrimitiveRef::Opaque { .. }) => {
                        match p {
                            PrimitiveRef::Bool(b) => stack.push_front(Value::Boolean(*b)),
                            PrimitiveRef::U8(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::U16(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::U32(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::U64(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::U128(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::I8(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::I16(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::I32(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::I64(n) => stack.push_front(Value::Integer(*n)),
                            PrimitiveRef::I128(n) => stack.push_front(Value::Integer(*n as i64)),
                            PrimitiveRef::F32(n) => stack.push_front(Value::Number(*n as f64)),
                            PrimitiveRef::F64(n) => stack.push_front(Value::Number(*n)),
                            PrimitiveRef::String(s) => stack
                                .push_front(Value::String(piccolo::String::from_slice(&ctx, s))),
                            PrimitiveRef::Opaque { .. } => unreachable!(),
                        }
                    }
                    _ => {
                        stack.push_front(newref.clone().into_value(ctx));
                    }
                }

                Ok(CallbackReturn::Return)
            }),
        )
        .unwrap();
    metatable
        .set(
            ctx,
            "__newindex",
            Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
                let (this, key, newvalue): (&EcsRef, lua::Value, lua::Value) =
                    stack.consume(ctx)?;

                let mut this = this.clone();
                this.path = ustr(&format!("{}.{key}", this.path));
                let mut b = this.borrow_mut();
                let mut this_ref = b.schema_ref_mut()?;

                match this_ref.access_mut() {
                    SchemaRefMutAccess::Struct(_)
                    | SchemaRefMutAccess::Vec(_)
                    | SchemaRefMutAccess::Enum(_)
                    | SchemaRefMutAccess::Map(_) => {
                        let newvalue = newvalue.as_static_user_data::<EcsRef>()?;
                        let newvalue_b = newvalue.borrow();
                        let newvalue_ref = newvalue_b.schema_ref()?;

                        // If the current and new ref are asset handles
                        if this_ref
                            .schema()
                            .type_data
                            .get::<SchemaAssetHandle>()
                            .is_some()
                            && newvalue_ref
                                .schema()
                                .type_data
                                .get::<SchemaAssetHandle>()
                                .is_some()
                        {
                            // SOUND: the `SchemaAssetHandle` type data asserts that these types
                            // are represented by `UntypedHandle`. Additionally, `SchemaAssetHandle`
                            // cannot be constructed outside the crate due to private fields, so it
                            // cannot be added to non-conforming types.
                            unsafe {
                                *this_ref.cast_mut_unchecked::<UntypedHandle>() =
                                    *newvalue_ref.cast_unchecked::<UntypedHandle>()
                            }
                        } else {
                            // If we are not dealing with asset handles
                            // Attempt to write the new value
                            this_ref.write(newvalue_ref)?;
                        }
                    }
                    SchemaRefMutAccess::Primitive(p) => match (p, newvalue) {
                        (PrimitiveRefMut::Bool(b), Value::Boolean(newb)) => *b = newb,
                        (PrimitiveRefMut::U8(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::U16(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::U32(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::U64(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::U128(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::I8(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::I16(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::I32(n), Value::Integer(newi)) => {
                            *n = newi.try_into().unwrap()
                        }
                        (PrimitiveRefMut::I64(n), Value::Integer(newi)) => *n = newi,
                        (PrimitiveRefMut::I128(n), Value::Integer(newi)) => *n = newi.into(),
                        (PrimitiveRefMut::F32(n), Value::Number(newf)) => *n = newf as f32,
                        (PrimitiveRefMut::F64(n), Value::Number(newf)) => *n = newf,
                        (PrimitiveRefMut::F32(n), Value::Integer(newi)) => *n = newi as f32,
                        (PrimitiveRefMut::F64(n), Value::Integer(newi)) => *n = newi as f64,
                        (PrimitiveRefMut::String(s), Value::String(news)) => {
                            if let Ok(news) = news.to_str() {
                                s.clear();
                                s.push_str(news);
                            } else {
                                return Err(
                                    anyhow::format_err!("Non UTF-8 string assignment.").into()
                                );
                            }
                        }
                        (PrimitiveRefMut::Opaque { mut schema_ref, .. }, value) => {
                            // Special handling for `Ustr`
                            if let Ok(ustr) = schema_ref.reborrow().try_cast_mut::<Ustr>() {
                                if let Value::String(s) = value {
                                    *ustr = s.to_str()?.into()
                                } else if let Value::UserData(data) = value {
                                    let ecsref = data.downcast_static::<EcsRef>()?;
                                    let b = ecsref.borrow();
                                    let value_ref = b.schema_ref()?;

                                    if let Ok(value) = value_ref.try_cast::<Ustr>() {
                                        *ustr = *value;
                                    } else if let Ok(value) = value_ref.try_cast::<String>() {
                                        *ustr = value.as_str().into();
                                    }
                                }
                            } else {
                                todo!("Opaque type assignment")
                            }
                        }
                        _ => return Err(anyhow::format_err!("Invalid type").into()),
                    },
                }

                Ok(CallbackReturn::Return)
            }),
        )
        .unwrap();

    metatable
}