defmodule Manganese.SerializationKit.Structs.UnityVector2Int do @moduledoc """ A Unity vector2 value with integer `:x` and `:y` 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 vector2 int. """ @type t :: %Structs.UnityVector2Int{ x: integer, y: integer } defstruct [ :x, :y ] # Helpers @doc """ A vector2 int with zero values for all components. """ @spec zero :: t def zero, do: %Structs.UnityVector2Int{ x: 0, y: 0 } # Deserialization @doc """ Deserialize a vector2 int from a map. """ @spec from_map(t_external) :: t def from_map(%{ "x" => x, "y" => y }) do %Structs.UnityVector2Int{ x: x, y: y } end @doc """ Deserialize a vector2 from a tuple. """ @spec from_tuple(t_internal) :: t def from_tuple({ x, y }) do %Structs.UnityVector2{ x: x, y: y } end # Serialization @type t_internal :: { integer, integer } @type t_external :: map @doc """ Serialize a vector2 int to a map. """ @spec to_map(t) :: t_external def to_map(%Structs.UnityVector2Int{ x: x, y: y }) do %{ "x" => x, "y" => y } end @doc """ Serialize a vector2 int to a tuple. """ @spec to_tuple(t) :: t_internal def to_tuple(%Structs.UnityVector2Int{ x: x, y: y }) do { x, y } end # Ecto type use Ecto.Type @doc """ The PostgreSQL composite type used to represent a vector2 int. """ def type, do: :unity_vector2_int def cast(%Structs.UnityVector2Int{} = unity_vector2), do: { :ok, unity_vector2 } def cast({ _x, _y } = tuple), do: { :ok, from_tuple tuple } def cast(nil), do: { :ok, nil } def cast(_), do: :error def load({ _x, _y } = tuple), do: { :ok, from_tuple tuple } def load(nil), do: { :ok, nil } def load(_), do: :error def dump(%Structs.UnityVector2Int{} = unity_vector2), do: { :ok, to_tuple unity_vector2 } def dump(nil), do: { :ok, nil } def dump(_), do: :error end