Multirious / bevy_tween

Flexible tweening plugin library for Bevy.
Apache License 2.0
87 stars 2 forks source link

Implement `Serialize` and `Deserialize` #27

Closed janhohenheim closed 2 months ago

janhohenheim commented 2 months ago

I'd like EaseFunction (and maybe other types?) to implement Serialize and Deserialize so that I can configure my easings in an external config file. Currently, I have to use remote derives to work around the fact that bevy_tween does not export serde derives.

Multirious commented 2 months ago

Yeah, we can have serde impls.

bevy_tween does not export serde derives.

I'm not sure what this means though. The crate doesn't even have a dependency on serde yet.

Edit: I just realized bevy_reflect derive should've automatically derive Serialize and Deserialize?

Multirious commented 2 months ago

I just realized bevy_reflect derive should've automatically derive Serialize and Deserialize?

That's can only be used with ReflectSerializer, TypedReflectDeserializer, and UntypedReflectDeserializer seems like. All types in the crate implements Reflect so we can deserialize and serialize them this way. Would this work?

I've experimentally created these function and they does deserialize and serialize with a bit of extra metadata. ```rust fn json_to_string_pretty_reflect( value: &dyn Reflect, registry: &TypeRegistry, ) -> serde_json::Result { use serde::Serialize; let serializer = ReflectSerializer::new(value, registry); let mut buf = Vec::new(); serializer.serialize(&mut serde_json::Serializer::pretty(&mut buf))?; // SAFETY: "We do not emit invalid UTF-8." - serde_json let s = unsafe { String::from_utf8_unchecked(buf) }; Ok(s) } fn json_from_str_pretty_reflect( str: &str, registry: &TypeRegistry, ) -> serde_json::Result> { use serde::de::DeserializeSeed; let type_registration = registry .get(std::any::TypeId::of::()) .expect("Unregistered type"); let deserializer = TypedReflectDeserializer::new(type_registration, registry); let v = deserializer.deserialize(&mut serde_json::Deserializer::from_str(str))?; Ok(v.downcast::().unwrap()) } ```
janhohenheim commented 2 months ago

I'm not sure what this means though. The crate doesn't even have a dependency on serde yet.

Yeah, that's what I meant. Sorry for not being clear 😅

All types in the crate implements Reflect so we can deserialize and serialize them this way. Would this work?

In theory, but what I'm trying to do is to just register a GameConfig struct in bevy_common_assets, which expects the whole struct to be at least Deserialize.

Multirious commented 2 months ago

Alright, 7ae79621e296d2074d9bb6fe8863880b1030543e is merged. I've tried to implement Serialize and Deserialize on other types but seems like only EaseFunction is the only one that make sense 🤔. I guess I'll be implementing serde on a request basis.

janhohenheim commented 2 months ago

Thanks a bunch :D