defmodule Manganese.SerializationKit.Structs.UnityVector4 do @moduledoc """ A Unity vector4 value with `:x`, `:y`, `:z`, and `:w` components. *Note that Unity structs are available in order to process the data in the API server, but most vector calculations occur in the environment simulation service.* This module can be used as an Ecto type for de/serialization when interacting with the database. """ alias Manganese.SerializationKit.Structs @typedoc """ A Unity vector4. """ @type t :: %Structs.UnityVector4{ x: float, y: float, z: float, w: float } defstruct [ :x, :y, :z, :w ] # Helpers @doc """ A vector4 with zero values for all components. """ @spec zero :: t def zero, do: %Structs.UnityVector4{ x: 0, y: 0, z: 0, w: 0 } # Deserialization @doc """ Deserialize a vector4 from a map. """ @spec from_map(t_external) :: t def from_map(%{ "x" => x, "y" => y, "z" => z, "w" => w }) do %Structs.UnityVector4{ x: x, y: y, z: z, w: w } end @doc """ Deserialize a vector4 from a tuple. """ @spec from_tuple(t_internal) :: t def from_tuple({ x, y, z, w }) do %Structs.UnityVector4{ x: x, y: y, z: z, w: w } end # Serialization @type t_internal :: { float, float, float, float } @type t_external :: map @doc """ Serialize a vector4 to a map. """ @spec to_map(t) :: t_external def to_map(%Structs.UnityVector4{ x: x, y: y, z: z, w: w }) do %{ "x" => x, "y" => y, "z" => z, "w" => w } end @doc """ Serialize a vector4 to a tuple. """ @spec to_tuple(t) :: t_internal def to_tuple(%Structs.UnityVector4{ x: x, y: y, z: z, w: w }) do { x, y, z, w } end # Ecto type use Ecto.Type @doc """ The PostgreSQL composite type used to represent a vector4. """ def type, do: :unity_vector4 def cast(%Structs.UnityVector4{} = unity_vector4), do: { :ok, unity_vector4 } def cast({ _x, _y, _z, _w } = tuple), do: { :ok, from_tuple tuple } def cast(nil), do: { :ok, nil } def cast(_), do: :error def load({ _x, _y, _z, _w } = tuple), do: { :ok, from_tuple tuple } def load(nil), do: { :ok, nil } def load(_), do: :error def dump(%Structs.UnityVector4{} = unity_vector4), do: { :ok, to_tuple unity_vector4 } def dump(nil), do: { :ok, nil } def dump(_), do: :error end