amethyst/apps/amethyst/lib/blockregistry.ex

74 lines
2.3 KiB
Elixir

# Amethyst - An experimental Minecraft server written in Elixir.
# Copyright (C) 2024 KodiCraft
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
defmodule Amethyst.BlockRegistry do
use GenServer
@moduledoc """
GenServer which can be populated with block states and their corresponding IDs.
It can be queried by block identifier and state to get the corresponding ID.
"""
require Logger
def start_link(map) do
GenServer.start_link(__MODULE__, map)
end
def init(map) do
{:ok, map}
end
def handle_cast({:add, id, bs, bsi}, state) do
state = Map.put_new(state, id, %{})
state = Map.put(state, id, Map.put(state[id], bs, bsi))
{:noreply, state}
end
def handle_call({:get, id, bs}, _from, state) do
case Map.get(state, id) do
nil -> {:reply, nil, state}
block_states -> {:reply, Map.get(block_states, bs), state}
end
end
def handle_call(:debug, _from, state) do
Logger.debug("BlockRegistry state: #{inspect(state)}")
{:reply, :ok, state}
end
@doc """
Adds a block state to the registry.
## Parameters
- `id` - The block identifier
- `bs` - The block state
- `bsi` - The block state ID
"""
@spec add(String.t(), map(), integer()) :: :ok
def add(id, bs, bsi) do
GenServer.cast({:via, PartitionSupervisor, {__MODULE__, id}}, {:add, id, bs, bsi})
end
@doc """
Gets the block state ID for a given block identifier and block state.
- `id` - The block identifier
- `bs` - The block state, nil if the block has no states
"""
@spec get(String.t(), map() | nil) :: integer() | nil
def get(id, bs \\ %{}) do
GenServer.call({:via, PartitionSupervisor, {__MODULE__, id}}, {:get, id, bs})
end
end