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
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Represents the physical properties that parts can have.
///
/// Equivalent to Roblox's [`PhysicalProperties`][PhysicalProperties] type, with
/// the difference that `Default` is a variant here, instead of a hidden state
/// that `PhysicalProperties` can have.
///
/// [PhysicalProperties]: https://developer.roblox.com/en-us/api-reference/datatype/PhysicalProperties
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PhysicalProperties {
    Default,
    Custom(CustomPhysicalProperties),
}

impl From<CustomPhysicalProperties> for PhysicalProperties {
    fn from(value: CustomPhysicalProperties) -> Self {
        Self::Custom(value)
    }
}

/// Custom physics properties that can be given to parts.
///
/// Documentation for what these do can be found on the
/// [`PhysicalProperties`][PhysicalProperties] DevHub documentation.
///
/// [PhysicalProperties]: https://developer.roblox.com/en-us/api-reference/datatype/PhysicalProperties
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct CustomPhysicalProperties {
    pub density: f32,
    pub friction: f32,
    pub elasticity: f32,
    pub friction_weight: f32,
    pub elasticity_weight: f32,
}

#[cfg(feature = "serde")]
mod serde_impl {
    use std::fmt;

    use serde::de;

    use super::*;

    #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
    enum TaggedPhysicalProperties {
        Default,
        Custom(CustomPhysicalProperties),
    }

    impl From<PhysicalProperties> for TaggedPhysicalProperties {
        fn from(value: PhysicalProperties) -> Self {
            match value {
                PhysicalProperties::Default => TaggedPhysicalProperties::Default,
                PhysicalProperties::Custom(custom) => TaggedPhysicalProperties::Custom(custom),
            }
        }
    }

    impl From<TaggedPhysicalProperties> for PhysicalProperties {
        fn from(value: TaggedPhysicalProperties) -> Self {
            match value {
                TaggedPhysicalProperties::Default => PhysicalProperties::Default,
                TaggedPhysicalProperties::Custom(custom) => PhysicalProperties::Custom(custom),
            }
        }
    }

    impl Serialize for PhysicalProperties {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            if serializer.is_human_readable() {
                match self {
                    PhysicalProperties::Default => serializer.serialize_str("Default"),
                    PhysicalProperties::Custom(custom) => custom.serialize(serializer),
                }
            } else {
                TaggedPhysicalProperties::from(*self).serialize(serializer)
            }
        }
    }

    impl<'de> Deserialize<'de> for PhysicalProperties {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            struct Visitor;

            impl<'de> de::Visitor<'de> for Visitor {
                type Value = PhysicalProperties;

                fn expecting(&self, out: &mut fmt::Formatter) -> fmt::Result {
                    write!(
                        out,
                        "the string \"Default\" or a CustomPhysicalProperties struct"
                    )
                }

                fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
                    if value == "Default" {
                        Ok(PhysicalProperties::Default)
                    } else {
                        Err(E::invalid_value(de::Unexpected::Str(value), &self))
                    }
                }

                fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
                        .map(PhysicalProperties::Custom)
                }
            }

            if deserializer.is_human_readable() {
                deserializer.deserialize_any(Visitor)
            } else {
                TaggedPhysicalProperties::deserialize(deserializer).map(Into::into)
            }
        }
    }
}

#[cfg(all(test, feature = "serde"))]
mod serde_test {
    use super::*;

    #[test]
    fn json_default() {
        let default = PhysicalProperties::Default;

        let ser = serde_json::to_string(&default).unwrap();
        assert_eq!(ser, "\"Default\"");

        let de: PhysicalProperties = serde_json::from_str("\"Default\"").unwrap();
        assert_eq!(de, default);
    }

    #[test]
    fn json_custom() {
        let custom = PhysicalProperties::Custom(CustomPhysicalProperties {
            density: 1.0,
            friction: 0.5,
            elasticity: 0.0,
            elasticity_weight: 5.0,
            friction_weight: 6.0,
        });

        let ser = serde_json::to_string(&custom).unwrap();
        assert_eq!(ser, "{\"density\":1.0,\"friction\":0.5,\"elasticity\":0.0,\"frictionWeight\":6.0,\"elasticityWeight\":5.0}");

        let de: PhysicalProperties = serde_json::from_str(&ser).unwrap();
        assert_eq!(de, custom);
    }

    #[test]
    fn bincode_default() {
        let default = PhysicalProperties::Default;

        let ser = bincode::serialize(&default).unwrap();
        let de: PhysicalProperties = bincode::deserialize(&ser).unwrap();

        assert_eq!(de, default);
    }

    #[test]
    fn bincode_custom() {
        let custom = PhysicalProperties::Custom(CustomPhysicalProperties {
            density: 1.0,
            friction: 0.5,
            elasticity: 0.0,
            elasticity_weight: 5.0,
            friction_weight: 6.0,
        });

        let ser = bincode::serialize(&custom).unwrap();
        let de: PhysicalProperties = bincode::deserialize(&ser).unwrap();

        assert_eq!(de, custom);
    }
}