Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bevy_reflect: Reflection diffing #13253

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions crates/bevy_reflect/derive/src/impls/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,67 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream
fn clone_dynamic(&self) -> #bevy_reflect_path::DynamicEnum {
#bevy_reflect_path::DynamicEnum::from_ref::<Self>(self)
}

fn apply_enum_diff(&mut self, diff: #bevy_reflect_path::diff::EnumDiff) -> #bevy_reflect_path::diff::DiffApplyResult {
println!("Diffing... {}", #bevy_reflect_path::DynamicTypePath::reflect_type_path(self));
let info = <Self as #bevy_reflect_path::Typed>::type_info();

if info.type_id() != diff.type_info().type_id() {
return #FQResult::Err(#bevy_reflect_path::diff::DiffApplyError::TypeMismatch);
}

match diff {
#bevy_reflect_path::diff::EnumDiff::Swapped(value_diff) => {
#bevy_reflect_path::Reflect::try_apply(
self,
#bevy_reflect_path::Reflect::as_reflect(::core::ops::Deref::deref(&value_diff))
)
.map_err(::core::convert::Into::into)
},
#bevy_reflect_path::diff::EnumDiff::Tuple(diff) => {
let variant_type = #bevy_reflect_path::Enum::variant_type(self);
if !matches!(variant_type, #bevy_reflect_path::VariantType::Tuple) {
return #FQResult::Err(#bevy_reflect_path::diff::DiffApplyError::VariantMismatch {
expected: #bevy_reflect_path::VariantType::Tuple,
received: variant_type,
});
}

let mut diffs = ::core::iter::IntoIterator::into_iter(diff.take_changes());

for index in 0..#bevy_reflect_path::Enum::field_len(self) {
#bevy_reflect_path::Reflect::apply_diff(
#bevy_reflect_path::Enum::field_at_mut(self, index).unwrap(),
diffs.next().ok_or(#bevy_reflect_path::diff::DiffApplyError::MissingField)?
)?;
}

#FQResult::Ok(())
},
#bevy_reflect_path::diff::EnumDiff::Struct(diff) => {
let variant_type = #bevy_reflect_path::Enum::variant_type(self);
if !matches!(variant_type, #bevy_reflect_path::VariantType::Struct) {
return #FQResult::Err(#bevy_reflect_path::diff::DiffApplyError::VariantMismatch {
expected: #bevy_reflect_path::VariantType::Struct,
received: variant_type,
});
}

let mut diffs = diff.take_changes();

for index in 0..#bevy_reflect_path::Enum::field_len(self) {
let name = #bevy_reflect_path::Enum::name_at(self, index).unwrap();
let diff = diffs.remove(name).ok_or(#bevy_reflect_path::diff::DiffApplyError::MissingField)?;
#bevy_reflect_path::Reflect::apply_diff(
#bevy_reflect_path::Enum::field_at_mut(self, index).unwrap(),
diff
)?;
}

#FQResult::Ok(())
},
}
}
}

impl #impl_generics #bevy_reflect_path::Reflect for #enum_path #ty_generics #where_reflect_clause {
Expand Down Expand Up @@ -203,6 +264,11 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream
#FQBox::new(#bevy_reflect_path::Enum::clone_dynamic(self))
}

#[inline]
fn diff<'new>(&self, other: &'new dyn #bevy_reflect_path::Reflect) -> #bevy_reflect_path::diff::DiffResult<'_, 'new> {
#bevy_reflect_path::diff::diff_enum(self, other)
}

#[inline]
fn set(&mut self, #ref_value: #FQBox<dyn #bevy_reflect_path::Reflect>) -> #FQResult<(), #FQBox<dyn #bevy_reflect_path::Reflect>> {
*self = <dyn #bevy_reflect_path::Reflect>::take(#ref_value)?;
Expand Down
24 changes: 24 additions & 0 deletions crates/bevy_reflect/derive/src/impls/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,25 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenS
#(dynamic.insert_boxed(#field_names, #bevy_reflect_path::Reflect::clone_value(&self.#field_idents));)*
dynamic
}

fn apply_struct_diff(&mut self, diff: #bevy_reflect_path::diff::StructDiff) -> #bevy_reflect_path::diff::DiffApplyResult {
let info = <Self as #bevy_reflect_path::Typed>::type_info();

if info.type_id() != diff.type_info().type_id() {
return #FQResult::Err(#bevy_reflect_path::diff::DiffApplyError::TypeMismatch);
}

let mut diffs = diff.take_changes();

#(
#bevy_reflect_path::Reflect::apply_diff(
&mut self.#field_idents,
diffs.remove(#field_names).ok_or(#bevy_reflect_path::diff::DiffApplyError::MissingField)?
)?;
)*

#FQResult::Ok(())
}
}

impl #impl_generics #bevy_reflect_path::Reflect for #struct_path #ty_generics #where_reflect_clause {
Expand Down Expand Up @@ -164,6 +183,11 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenS
#FQBox::new(#bevy_reflect_path::Struct::clone_dynamic(self))
}

#[inline]
fn diff<'new>(&self, other: &'new dyn #bevy_reflect_path::Reflect) -> #bevy_reflect_path::diff::DiffResult<'_, 'new> {
#bevy_reflect_path::diff::diff_struct(self, other)
}

#[inline]
fn set(&mut self, value: #FQBox<dyn #bevy_reflect_path::Reflect>) -> #FQResult<(), #FQBox<dyn #bevy_reflect_path::Reflect>> {
*self = <dyn #bevy_reflect_path::Reflect>::take(value)?;
Expand Down
24 changes: 24 additions & 0 deletions crates/bevy_reflect/derive/src/impls/tuple_structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,25 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> proc_macro2::
#(dynamic.insert_boxed(#bevy_reflect_path::Reflect::clone_value(&self.#field_idents));)*
dynamic
}

fn apply_tuple_struct_diff(&mut self, diff: #bevy_reflect_path::diff::TupleStructDiff) -> #bevy_reflect_path::diff::DiffApplyResult {
let info = <Self as #bevy_reflect_path::Typed>::type_info();

if info.type_id() != diff.type_info().type_id() {
return #FQResult::Err(#bevy_reflect_path::diff::DiffApplyError::TypeMismatch);
}

let mut diffs = diff.take_changes().into_iter();

#(
#bevy_reflect_path::Reflect::apply_diff(
&mut self.#field_idents,
diffs.next().ok_or(#bevy_reflect_path::diff::DiffApplyError::MissingField)?
)?;
)*

#FQResult::Ok(())
}
}

impl #impl_generics #bevy_reflect_path::Reflect for #struct_path #ty_generics #where_reflect_clause {
Expand Down Expand Up @@ -133,6 +152,11 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> proc_macro2::
#FQBox::new(#bevy_reflect_path::TupleStruct::clone_dynamic(self))
}

#[inline]
fn diff<'new>(&self, other: &'new dyn #bevy_reflect_path::Reflect) -> #bevy_reflect_path::diff::DiffResult<'_, 'new> {
#bevy_reflect_path::diff::diff_tuple_struct(self, other)
}

#[inline]
fn set(&mut self, value: #FQBox<dyn #bevy_reflect_path::Reflect>) -> #FQResult<(), #FQBox<dyn #bevy_reflect_path::Reflect>> {
*self = <dyn #bevy_reflect_path::Reflect>::take(value)?;
Expand Down
5 changes: 5 additions & 0 deletions crates/bevy_reflect/derive/src/impls/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ pub(crate) fn impl_value(meta: &ReflectMeta) -> proc_macro2::TokenStream {
#bevy_reflect_path::ReflectOwned::Value(self)
}

#[inline]
fn diff<'new>(&self, other: &'new dyn #bevy_reflect_path::Reflect) -> #bevy_reflect_path::diff::DiffResult<'_, 'new> {
#bevy_reflect_path::diff::diff_value(self, other)
}

#hash_fn

#partial_eq_fn
Expand Down
29 changes: 29 additions & 0 deletions crates/bevy_reflect/src/array.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::diff::{diff_array, ArrayDiff, DiffApplyError, DiffApplyResult, DiffResult};
use crate::{
self as bevy_reflect, utility::reflect_hasher, ApplyError, Reflect, ReflectKind, ReflectMut,
ReflectOwned, ReflectRef, TypeInfo, TypePath, TypePathTable,
Expand Down Expand Up @@ -72,6 +73,9 @@ pub trait Array: Reflect {
values: self.iter().map(|value| value.clone_value()).collect(),
}
}

/// Apply the given [`ArrayDiff`] to this value.
fn apply_array_diff(&mut self, diff: ArrayDiff) -> DiffApplyResult;
}

/// A container for compile-time array info.
Expand Down Expand Up @@ -297,6 +301,11 @@ impl Reflect for DynamicArray {
Box::new(self.clone_dynamic())
}

#[inline]
fn diff<'new>(&self, other: &'new dyn Reflect) -> DiffResult<'_, 'new> {
diff_array(self, other)
}

#[inline]
fn reflect_hash(&self) -> Option<u64> {
array_hash(self)
Expand Down Expand Up @@ -355,6 +364,26 @@ impl Array for DynamicArray {
.collect(),
}
}

fn apply_array_diff(&mut self, diff: ArrayDiff) -> DiffApplyResult {
if self.len() != diff.len() {
return Err(DiffApplyError::TypeMismatch);
}

if let Some(info) = self.get_represented_type_info() {
if info.type_id() != diff.type_info().type_id() {
return Err(DiffApplyError::TypeMismatch);
}
};

for (index, diff) in diff.take_changes().into_iter().enumerate() {
self.get_mut(index)
.ok_or(DiffApplyError::MissingField)?
.apply_diff(diff)?;
}

Ok(())
}
}

impl_type_path!((in bevy_reflect) DynamicArray);
Expand Down
100 changes: 100 additions & 0 deletions crates/bevy_reflect/src/diff/array_diff.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
use crate::diff::{Diff, DiffError, DiffResult, DiffType, ValueDiff};
use crate::{Array, Reflect, ReflectKind, ReflectRef, TypeInfo};
use std::fmt::{Debug, Formatter};
use std::slice::Iter;

/// Diff object for [arrays](Array).
pub struct ArrayDiff<'old, 'new> {
type_info: &'static TypeInfo,
elements: Vec<Diff<'old, 'new>>,
}

impl<'old, 'new> ArrayDiff<'old, 'new> {
/// Returns the [`TypeInfo`] of the reflected value currently being diffed.
pub fn type_info(&self) -> &TypeInfo {
self.type_info
}

/// Returns the [`Diff`] for the field at the given index.
pub fn get(&self, index: usize) -> Option<&Diff<'old, 'new>> {
self.elements.get(index)
}

/// Returns the number of elements in the array.
pub fn len(&self) -> usize {
self.elements.len()
}

/// Returns true if the array contains no elements.
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}

/// Returns an iterator over the [`Diff`] for _every_ element.
pub fn iter(&self) -> Iter<'_, Diff<'old, 'new>> {
self.elements.iter()
}

/// Take the changes contained in this diff.
pub fn take_changes(self) -> Vec<Diff<'old, 'new>> {
self.elements
}

pub fn clone_diff(&self) -> ArrayDiff<'static, 'static> {
ArrayDiff {
type_info: self.type_info,
elements: self.elements.iter().map(Diff::clone_diff).collect(),
}
}
}

impl<'old, 'new> Debug for ArrayDiff<'old, 'new> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArrayDiff")
.field("elements", &self.elements)
.finish()
}
}

/// Utility function for diffing two [`Array`] objects.
pub fn diff_array<'old, 'new, T: Array>(
old: &'old T,
new: &'new dyn Reflect,
) -> DiffResult<'old, 'new> {
let new = match new.reflect_ref() {
ReflectRef::Array(new) => new,
new => {
return Err(DiffError::KindMismatch {
expected: ReflectKind::Array,
received: new.kind(),
})
}
};

let (old_info, new_info) = old
.get_represented_type_info()
.zip(new.get_represented_type_info())
.ok_or(DiffError::MissingInfo)?;

if old.len() != new.len() || old_info.type_id() != new_info.type_id() {
return Ok(Diff::Replaced(ValueDiff::Borrowed(new.as_reflect())));
}

let mut diff = ArrayDiff {
type_info: old_info,
elements: Vec::with_capacity(old.len()),
};

let mut was_modified = false;
for (old_field, new_field) in old.iter().zip(new.iter()) {
let field_diff = old_field.diff(new_field)?;
was_modified |= !matches!(field_diff, Diff::NoChange);
diff.elements.push(field_diff);
}

if was_modified {
Ok(Diff::Modified(DiffType::Array(diff)))
} else {
Ok(Diff::NoChange)
}
}
Loading