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
use std::{io::Read, time::Duration};

use ambient_shared_types::{procedural_storage_handle_definitions, ComponentIndex};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use glam::{IVec2, IVec3, IVec4, Mat4, Quat, UVec2, UVec3, UVec4, Vec2, Vec3, Vec4};
use paste::paste;
use thiserror::Error;

#[derive(Error, Debug)]
/// Error that can occur during message ser/de.
pub enum MessageSerdeError {
    /// Arbitrary I/O error during ser/de.
    #[error("arbitrary I/O error")]
    IO(#[from] std::io::Error),
    /// An invalid value was encountered during ser/de.
    #[error("invalid value")]
    InvalidValue,
    /// An invalid component definition was encountered during ser/de.
    #[error("invalid component definition")]
    InvalidComponentDefinition { index: ComponentIndex },
    /// The length of an array exceeded 2^32-1 bytes.
    #[error("array too long")]
    ArrayTooLong(#[from] std::num::TryFromIntError),
    /// This type is not supported for message serde on this side.
    #[error("unsupported type")]
    UnsupportedType,
}

/// Implemented for all types that can be serialized in a message.
pub trait MessageSerde: Default + Clone
where
    Self: Sized,
{
    /// Serialize this to a `Vec<u8>`.
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError>;
    /// Deserialize this if possible.
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError>;
}
impl MessageSerde for () {
    fn serialize_message_part(&self, _output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(())
    }
    fn deserialize_message_part(_input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(())
    }
}
impl MessageSerde for bool {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_u8(if *self { 1 } else { 0 })?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        match input.read_u8()? {
            0 => Ok(false),
            1 => Ok(true),
            _ => Err(MessageSerdeError::InvalidValue),
        }
    }
}
impl MessageSerde for f32 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_f32::<BigEndian>(*self)?)
    }

    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_f32::<BigEndian>()?)
    }
}
impl MessageSerde for f64 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_f64::<BigEndian>(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_f64::<BigEndian>()?)
    }
}
impl MessageSerde for Mat4 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_cols_array() {
            output.write_f32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0f32; 16];
        for value in &mut values {
            *value = input.read_f32::<BigEndian>()?;
        }
        Ok(Self::from_cols_array(&values))
    }
}
impl MessageSerde for Quat {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_f32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0f32; 4];
        for value in &mut values {
            *value = input.read_f32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for u8 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_u8(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_u8()?)
    }
}
impl MessageSerde for u16 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_u16::<BigEndian>(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_u16::<BigEndian>()?)
    }
}
impl MessageSerde for u32 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_u32::<BigEndian>(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_u32::<BigEndian>()?)
    }
}
impl MessageSerde for u64 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_u64::<BigEndian>(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_u64::<BigEndian>()?)
    }
}
impl MessageSerde for i8 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_i8(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_i8()?)
    }
}
impl MessageSerde for i16 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_i16::<BigEndian>(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_i16::<BigEndian>()?)
    }
}
impl MessageSerde for i32 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_i32::<BigEndian>(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_i32::<BigEndian>()?)
    }
}
impl MessageSerde for i64 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        Ok(output.write_i64::<BigEndian>(*self)?)
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(input.read_i64::<BigEndian>()?)
    }
}
impl MessageSerde for Vec2 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_f32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0f32; 2];
        for value in &mut values {
            *value = input.read_f32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for Vec3 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_f32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0f32; 3];
        for value in &mut values {
            *value = input.read_f32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for Vec4 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_f32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0f32; 4];
        for value in &mut values {
            *value = input.read_f32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for UVec2 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_u32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0u32; 2];
        for value in &mut values {
            *value = input.read_u32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for UVec3 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_u32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0u32; 3];
        for value in &mut values {
            *value = input.read_u32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for UVec4 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_u32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0u32; 4];
        for value in &mut values {
            *value = input.read_u32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for IVec2 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_i32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0i32; 2];
        for value in &mut values {
            *value = input.read_i32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for IVec3 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_i32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0i32; 3];
        for value in &mut values {
            *value = input.read_i32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for IVec4 {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        for value in self.to_array() {
            output.write_i32::<BigEndian>(value)?;
        }
        Ok(())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let mut values = [0i32; 4];
        for value in &mut values {
            *value = input.read_i32::<BigEndian>()?;
        }
        Ok(Self::from_array(values))
    }
}
impl MessageSerde for String {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        serialize_array(output, self.as_bytes())
    }
    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        String::from_utf8(deserialize_array(input)?).map_err(|_| MessageSerdeError::InvalidValue)
    }
}
impl<T: MessageSerde> MessageSerde for Vec<T> {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        serialize_array(output, self.as_slice())
    }

    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        deserialize_array(input)
    }
}
impl<T: MessageSerde> MessageSerde for Option<T> {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        if let Some(value) = self {
            true.serialize_message_part(output)?;
            value.serialize_message_part(output)?;
        } else {
            false.serialize_message_part(output)?;
        }
        Ok(())
    }

    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        let present = bool::deserialize_message_part(input)?;
        Ok(if present {
            Some(T::deserialize_message_part(input)?)
        } else {
            None
        })
    }
}
impl MessageSerde for Duration {
    fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
        output.write_u64::<BigEndian>(self.as_nanos().try_into().unwrap())?;
        Ok(())
    }

    fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
        Ok(Self::from_nanos(input.read_u64::<BigEndian>()?))
    }
}

macro_rules! make_procedural_storage_handle_serde {
    ($($name:ident),*) => { paste!{$(
        impl MessageSerde for ambient_shared_types::[<Procedural $name:camel Handle>] {
            fn serialize_message_part(&self, output: &mut Vec<u8>) -> Result<(), MessageSerdeError> {
                output.write_u128::<BigEndian>(ulid::Ulid::from(*self).0)?;
                Ok(())
            }

            fn deserialize_message_part(input: &mut dyn Read) -> Result<Self, MessageSerdeError> {
                Ok(Self::from(ulid::Ulid(input.read_u128::<BigEndian>()?)))
            }
        }
    )*}};
}

procedural_storage_handle_definitions!(make_procedural_storage_handle_serde);

fn serialize_array<T: MessageSerde>(
    output: &mut Vec<u8>,
    data: &[T],
) -> Result<(), MessageSerdeError> {
    output.write_u32::<BigEndian>(data.len().try_into()?)?;
    for value in data {
        value.serialize_message_part(output)?;
    }
    Ok(())
}

fn deserialize_array<T: MessageSerde>(input: &mut dyn Read) -> Result<Vec<T>, MessageSerdeError> {
    let length = usize::try_from(input.read_u32::<BigEndian>()?).unwrap();
    let mut data = vec![Default::default(); length];
    for value in &mut data {
        *value = T::deserialize_message_part(input)?;
    }
    Ok(data)
}

/// Implemented on all types that can be de/serialized from/to a `Vec<u8>`.
pub trait Message: Sized {
    /// The identifier of this message.
    #[doc(hidden)]
    fn id() -> &'static str;

    /// Serialize this to a `Vec<u8>`.
    #[doc(hidden)]
    fn serialize_message(&self) -> Result<Vec<u8>, MessageSerdeError>;
    /// Deserialize this from a `u8` slice.
    #[doc(hidden)]
    fn deserialize_message(input: &[u8]) -> Result<Self, MessageSerdeError>;
}

/// Implemented on all messages that come from the runtime.
pub trait RuntimeMessage: Message {}

/// Implemented on all messages that can be sent between packages.
pub trait ModuleMessage: Message {}