use serde::{Deserialize, Serialize};
use uuid::Uuid;
use super::field_ast::{ScalarField, VectorField};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FieldId(pub Uuid);
impl FieldId {
#[cfg(not(target_arch = "wasm32"))]
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(id: Uuid) -> Self {
Self(id)
}
pub fn as_uuid(self) -> Uuid {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CouplingId(pub Uuid);
impl CouplingId {
#[cfg(not(target_arch = "wasm32"))]
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(id: Uuid) -> Self {
Self(id)
}
pub fn as_uuid(self) -> Uuid {
self.0
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FieldDefinition {
Scalar(ScalarField),
Vector(VectorField),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FieldExtent {
Global,
Region {
min_x: f32,
min_y: f32,
max_x: f32,
max_y: f32,
},
AttachedToNode(Uuid),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FieldLifecycle {
Active,
Retired,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Field {
pub id: FieldId,
pub name: Option<String>,
pub definition: FieldDefinition,
pub extent: FieldExtent,
pub lifecycle: FieldLifecycle,
}
impl Field {
pub fn new(id: FieldId, definition: FieldDefinition) -> Self {
Self {
id,
name: None,
definition,
extent: FieldExtent::Global,
lifecycle: FieldLifecycle::Active,
}
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn with_extent(mut self, extent: FieldExtent) -> Self {
self.extent = extent;
self
}
pub fn is_active(&self) -> bool {
self.lifecycle == FieldLifecycle::Active
}
}
#[cfg(test)]
mod tests {
use super::super::field_ast::Falloff;
use super::*;
fn sample_uuid(n: u8) -> Uuid {
Uuid::from_bytes([n; 16])
}
#[test]
fn field_serde_roundtrip() {
let field = Field::new(
FieldId::from_uuid(sample_uuid(1)),
FieldDefinition::Scalar(ScalarField::disk_at(0.0, 0.0, 50.0, Falloff::Smoothstep)),
)
.with_name("focus")
.with_extent(FieldExtent::AttachedToNode(sample_uuid(2)));
let s = serde_json::to_string(&field).unwrap();
let back: Field = serde_json::from_str(&s).unwrap();
assert_eq!(field, back);
}
#[test]
fn defaults_are_global_active() {
let f = Field::new(
FieldId::from_uuid(sample_uuid(3)),
FieldDefinition::Vector(VectorField::Coord),
);
assert_eq!(f.extent, FieldExtent::Global);
assert!(f.is_active());
assert!(f.name.is_none());
}
#[test]
fn ids_are_distinct_types_but_uuid_backed() {
let fid = FieldId::from_uuid(sample_uuid(4));
let cid = CouplingId::from_uuid(sample_uuid(4));
assert_eq!(fid.as_uuid(), cid.as_uuid());
}
}