Add shared item references and native container transfer behavior

This commit is contained in:
Ludovic Marie
2026-10-07 07:41:29 +02:00
parent cda5895cab
commit 202dad8192
8 changed files with 944 additions and 0 deletions
@@ -0,0 +1,253 @@
use horizon_world::{
component_patch::{Patch, Prototype},
item_stack_refs::{ItemStacks, StackRef},
simple_container::{ContainerHooks, SimpleContainer},
};
use serde_json::Value;
use std::{
fs,
io::{self, Write},
path::Path,
};
type Stack = StackRef<u8, usize, i32>;
type Container = SimpleContainer<u8, usize, i32>;
fn integer(v: &Value, k: &str) -> i32 {
v[k].as_i64().unwrap() as i32
}
fn opt(v: Option<i32>) -> String {
v.map_or("none".into(), |v| v.to_string())
}
fn max(s: &Stack) -> i32 {
s.read().component(&0).copied().unwrap_or(1)
}
struct World {
out: io::BufWriter<fs::File>,
refs: Vec<Stack>,
ids: Vec<Stack>,
empty: Stack,
op: Value,
calls: i32,
}
impl World {
fn snapshot(&mut self, s: &Stack) -> String {
let id = self
.ids
.iter()
.position(|v| v.same_reference(s))
.unwrap_or_else(|| {
self.ids.push(s.clone());
self.ids.len() - 1
});
let s = s.read();
let patch = s.components.as_patch();
format!(
"{} {} {} {} {} {} {} | {} | {}",
id,
s.item(),
s.count,
s.count(),
s.pop_time,
s.is_empty(),
s.component(&0).copied().unwrap_or(1),
(0..3)
.map(|k| opt(s.component(&k).copied()))
.collect::<Vec<_>>()
.join(","),
patch
.entries()
.iter()
.map(|(k, v)| format!("{k}={}", opt(*v)))
.collect::<Vec<_>>()
.join(",")
)
}
fn all(&mut self, c: &Container) {
for i in 0..self.refs.len() {
let s = self.snapshot(&self.refs[i].clone());
writeln!(self.out, "ref {i} {s}").unwrap();
}
for (i, s) in c.items().iter().enumerate() {
let s = self.snapshot(s);
writeln!(self.out, "slot {i} {s}").unwrap();
}
let s = self.snapshot(&self.empty.clone());
writeln!(self.out, "empty {s}").unwrap();
writeln!(
self.out,
"container {} {} {} {} {}",
c.size(),
c.is_empty(),
c.count_item(0),
c.count_item(1),
c.count_item(2)
)
.unwrap();
}
fn event(&mut self, c: &mut Container, name: &str) -> Result<(), ()> {
self.calls += 1;
writeln!(self.out, "event {name} {}", self.calls).unwrap();
self.all(c);
if self.calls == integer(&self.op, "fail_at") {
return Err(());
}
if self.calls == integer(&self.op, "mutate_at") {
let i = integer(&self.op, "mutate_ref") as usize;
let mut s = self.refs[i].write();
s.count = integer(&self.op, "after_count");
s.components
.set(0, Some(integer(&self.op, "after_max")))
.map_err(|_| ())?;
drop(s);
let slot = integer(&self.op, "mutate_slot");
if slot >= 0 && (slot as usize) < c.size() {
c.items_mut()[slot as usize] =
self.refs[integer(&self.op, "replace_ref") as usize].clone();
}
}
Ok(())
}
}
impl ContainerHooks<u8, usize, i32> for World {
type Error = ();
fn max_stack_size(&mut self, c: &mut Container) -> Result<i32, ()> {
self.event(c, "max")?;
Ok(integer(&self.op, "max"))
}
fn item_max_stack_size(&self, s: &Stack) -> i32 {
max(s)
}
fn changed(&mut self, c: &mut Container) -> Result<(), ()> {
self.event(c, "changed")
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args().nth(1).unwrap();
let dir = Path::new(&arg);
let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?);
for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() {
let f: Value = serde_json::from_str(line)?;
let prototypes: Vec<_> = f["prototypes"]
.as_array()
.unwrap()
.iter()
.map(|p| {
Prototype::new(p.as_array().unwrap().iter().map(|v| {
(
v[0].as_u64().unwrap() as usize,
v[1].as_i64().unwrap() as i32,
)
}))
})
.collect();
let stacks = ItemStacks::new(0);
let empty = stacks.empty();
let refs: Vec<_> = f["stacks"]
.as_array()
.unwrap()
.iter()
.map(|v| {
let item = integer(v, "item");
if item < 0 {
empty.clone()
} else {
let s = stacks.create(
item as u8,
integer(v, "count"),
prototypes[item as usize].clone(),
);
s.write().pop_time = integer(v, "pop");
s.write().components.restore_patch(&Patch::new(
v["patch"].as_array().unwrap().iter().map(|v| {
(
v[0].as_u64().unwrap() as usize,
v[1].as_i64().map(|n| n as i32),
)
}),
));
s
}
})
.collect();
let mut c = Container::from_items(
f["slots"]
.as_array()
.unwrap()
.iter()
.map(|i| refs[i.as_u64().unwrap() as usize].clone())
.collect(),
stacks.clone(),
);
let mut w = World {
out,
refs,
ids: vec![empty.clone()],
empty,
op: Value::Null,
calls: 0,
};
w.all(&c);
for op in f["ops"].as_array().unwrap() {
w.op = op.clone();
w.calls = 0;
let a = integer(op, "a") as usize;
let b = integer(op, "b") as usize;
let slot = integer(op, "slot");
let amount = integer(op, "amount");
let result = (|| -> Result<(), ()> {
match op["kind"].as_str().unwrap() {
"set" => c.set(slot, w.refs[a].clone(), &mut w).map_err(|_| ())?,
"add" => {
let input = w.refs[a].clone();
w.refs[b] = c.add(&input, &mut w).map_err(|_| ())?;
}
"remove" => w.refs[b] = c.remove(slot, amount, &mut w).map_err(|_| ())?,
"remove-type" => {
let i = integer(op, "item") as usize;
w.refs[b] = c
.remove_type(i as u8, prototypes[i].clone(), amount, &mut w)
.map_err(|_| ())?;
}
"no-update" => w.refs[b] = c.remove_no_update::<()>(slot).map_err(|_| ())?,
"clear" => c.clear(&mut w).map_err(|_| ())?,
"all" => {
let result = c.remove_all(&mut w).map_err(|_| ())?;
writeln!(w.out, "all-size {}", result.len()).unwrap();
for s in result {
let s = w.snapshot(&s);
writeln!(w.out, "removed {s}").unwrap();
}
}
"can-add" => {
let v = c.can_add(&w.refs[a], &w);
writeln!(w.out, "can-add {v}").unwrap();
}
"get" => w.refs[b] = c.get(slot),
"alias" => w.refs[b] = w.refs[a].clone(),
"copy" => w.refs[b] = stacks.copy(&w.refs[a]),
"count" => w.refs[a].write().count = amount,
"component" => {
w.refs[a]
.write()
.components
.set(
integer(op, "key") as usize,
op["value"].as_i64().map(|n| n as i32),
)
.map_err(|_| ())?;
}
_ => panic!("operation"),
}
Ok(())
})();
writeln!(
w.out,
"result {} {}",
if result.is_ok() { "ok" } else { "error" },
w.calls
)?;
w.all(&c);
}
out = w.out;
}
Ok(())
}
@@ -0,0 +1,64 @@
//! Shared stack identity for inventories. Cloning a reference retains the same
//! stack; `ItemStacks::copy` copies its value with copy-on-write components.
//! These references belong to the simulation thread and release unreachable
//! stacks automatically. No borrow is held across a container callback.
use crate::{
component_patch::Prototype,
item_stack_storage::{CopyResult, ItemStackData},
};
use std::{
cell::{Ref, RefCell, RefMut},
rc::Rc,
};
#[derive(Debug)]
pub struct StackRef<I, K, V>(Rc<RefCell<ItemStackData<I, K, V>>>);
impl<I, K, V> Clone for StackRef<I, K, V> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<I, K, V> StackRef<I, K, V> {
pub fn new(data: ItemStackData<I, K, V>) -> Self {
Self(Rc::new(RefCell::new(data)))
}
pub fn read(&self) -> Ref<'_, ItemStackData<I, K, V>> {
self.0.borrow()
}
pub fn write(&self) -> RefMut<'_, ItemStackData<I, K, V>> {
self.0.borrow_mut()
}
pub fn same_reference(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Clone, Debug)]
pub struct ItemStacks<I, K, V> {
air: I,
empty: StackRef<I, K, V>,
}
impl<I: Copy + Eq, K: Clone + Eq, V: Clone + PartialEq> ItemStacks<I, K, V> {
pub fn new(air: I) -> Self {
Self {
air,
empty: StackRef::new(ItemStackData::new(air, air, 0, Prototype::new([]))),
}
}
pub fn empty(&self) -> StackRef<I, K, V> {
self.empty.clone()
}
pub fn create(&self, item: I, count: i32, prototype: Prototype<K, V>) -> StackRef<I, K, V> {
StackRef::new(ItemStackData::new(item, self.air, count, prototype))
}
pub fn resolve(&self, copy: CopyResult<ItemStackData<I, K, V>>) -> StackRef<I, K, V> {
match copy {
CopyResult::Empty => self.empty(),
CopyResult::Stack(data) => StackRef::new(data),
}
}
pub fn copy(&self, stack: &StackRef<I, K, V>) -> StackRef<I, K, V> {
self.resolve(stack.read().copy())
}
pub fn split(&self, stack: &StackRef<I, K, V>, amount: i32) -> StackRef<I, K, V> {
self.resolve(stack.write().split(amount))
}
}
+3
View File
@@ -93,3 +93,6 @@ pub mod world_ray;
pub mod worldgen;
pub const DATA_VERSION: i32 = 5023;
pub mod item_stack_refs;
pub mod simple_container;
@@ -0,0 +1,220 @@
//! SimpleContainer storage and transfers using shared stack references.
//! Item component semantics and the virtual size/change hooks are supplied by
//! the caller. Menu transactions, persistence and recipe accounting are separate.
use crate::{
component_patch::Prototype,
item_stack_refs::{ItemStacks, StackRef},
};
#[derive(Debug)]
pub enum ContainerError<E> {
Index,
Callback(E),
}
pub type ContainerResult<T, E> = Result<T, ContainerError<E>>;
#[derive(Debug)]
pub struct SimpleContainer<I, K, V> {
items: Vec<StackRef<I, K, V>>,
stacks: ItemStacks<I, K, V>,
}
pub trait ContainerHooks<I, K, V> {
type Error;
/// Native getMaxStackSize(), normally 99; called before the item's limit.
fn max_stack_size(
&mut self,
container: &mut SimpleContainer<I, K, V>,
) -> Result<i32, Self::Error>;
fn item_max_stack_size(&self, stack: &StackRef<I, K, V>) -> i32;
fn changed(&mut self, container: &mut SimpleContainer<I, K, V>) -> Result<(), Self::Error>;
}
impl<I: Copy + Eq, K: Clone + Eq, V: Clone + PartialEq> SimpleContainer<I, K, V> {
pub fn new(size: usize, stacks: ItemStacks<I, K, V>) -> Self {
Self {
items: vec![stacks.empty(); size],
stacks,
}
}
/// Like the native varargs constructor, this retains aliases without limits.
pub fn from_items(items: Vec<StackRef<I, K, V>>, stacks: ItemStacks<I, K, V>) -> Self {
Self { items, stacks }
}
pub fn items(&self) -> &[StackRef<I, K, V>] {
&self.items
}
pub fn items_mut(&mut self) -> &mut [StackRef<I, K, V>] {
&mut self.items
}
pub fn size(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.iter().all(|s| s.read().is_empty())
}
pub fn get(&self, index: i32) -> StackRef<I, K, V> {
usize::try_from(index)
.ok()
.and_then(|i| self.items.get(i))
.cloned()
.unwrap_or_else(|| self.stacks.empty())
}
pub fn count_item(&self, item: I) -> i32 {
self.items.iter().fold(0_i32, |total, s| {
let s = s.read();
if s.item() == item {
total.wrapping_add(s.count())
} else {
total
}
})
}
pub fn can_add<H: ContainerHooks<I, K, V>>(
&self,
stack: &StackRef<I, K, V>,
hooks: &H,
) -> bool {
self.items.iter().any(|s| {
s.read().is_empty()
|| (s.read().same_item_components(&stack.read())
&& s.read().count() < hooks.item_max_stack_size(s))
})
}
fn limit<H: ContainerHooks<I, K, V>>(
&mut self,
stack: &StackRef<I, K, V>,
hooks: &mut H,
) -> Result<i32, ContainerError<H::Error>> {
let container = hooks
.max_stack_size(self)
.map_err(ContainerError::Callback)?;
Ok(container.min(hooks.item_max_stack_size(stack)))
}
pub fn set<H: ContainerHooks<I, K, V>>(
&mut self,
index: i32,
stack: StackRef<I, K, V>,
hooks: &mut H,
) -> Result<(), ContainerError<H::Error>> {
let slot = usize::try_from(index)
.ok()
.and_then(|i| self.items.get_mut(i))
.ok_or(ContainerError::Index)?;
*slot = stack.clone();
let limit = self.limit(&stack, hooks)?;
stack.write().limit_size(limit);
hooks.changed(self).map_err(ContainerError::Callback)
}
pub fn remove<H: ContainerHooks<I, K, V>>(
&mut self,
index: i32,
amount: i32,
hooks: &mut H,
) -> Result<StackRef<I, K, V>, ContainerError<H::Error>> {
let s = self.get(index);
let result = if amount > 0 && !s.read().is_empty() {
self.stacks.split(&s, amount)
} else {
self.stacks.empty()
};
if !result.read().is_empty() {
hooks.changed(self).map_err(ContainerError::Callback)?;
}
Ok(result)
}
pub fn remove_no_update<E>(
&mut self,
index: i32,
) -> Result<StackRef<I, K, V>, ContainerError<E>> {
let slot = usize::try_from(index)
.ok()
.and_then(|i| self.items.get_mut(i))
.ok_or(ContainerError::Index)?;
if slot.read().is_empty() {
Ok(self.stacks.empty())
} else {
Ok(std::mem::replace(slot, self.stacks.empty()))
}
}
pub fn remove_type<H: ContainerHooks<I, K, V>>(
&mut self,
item: I,
prototype: Prototype<K, V>,
amount: i32,
hooks: &mut H,
) -> Result<StackRef<I, K, V>, ContainerError<H::Error>> {
let result = self.stacks.create(item, 0, prototype);
for index in (0..self.size()).rev() {
let s = self.items[index].clone();
if s.read().item() == item {
let wanted = amount.wrapping_sub(result.read().count());
let removed = self.stacks.split(&s, wanted);
result.write().grow(removed.read().count());
if result.read().count() == amount {
break;
}
}
}
if !result.read().is_empty() {
hooks.changed(self).map_err(ContainerError::Callback)?;
}
Ok(result)
}
pub fn clear<H: ContainerHooks<I, K, V>>(
&mut self,
hooks: &mut H,
) -> Result<(), ContainerError<H::Error>> {
self.items.fill(self.stacks.empty());
hooks.changed(self).map_err(ContainerError::Callback)
}
pub fn remove_all<H: ContainerHooks<I, K, V>>(
&mut self,
hooks: &mut H,
) -> ContainerResult<Vec<StackRef<I, K, V>>, H::Error> {
let result = self
.items
.iter()
.filter(|s| !s.read().is_empty())
.cloned()
.collect();
self.clear(hooks)?;
Ok(result)
}
pub fn add<H: ContainerHooks<I, K, V>>(
&mut self,
stack: &StackRef<I, K, V>,
hooks: &mut H,
) -> Result<StackRef<I, K, V>, ContainerError<H::Error>> {
if stack.read().is_empty() {
return Ok(self.stacks.empty());
}
let remainder = self.stacks.copy(stack);
for index in 0..self.size() {
let target = self.items[index].clone();
if target.read().same_item_components(&remainder.read()) {
let limit = self.limit(&target, hooks)?;
let amount = remainder
.read()
.count()
.min(limit.wrapping_sub(target.read().count()));
if amount > 0 {
target.write().grow(amount);
remainder.write().shrink(amount);
hooks.changed(self).map_err(ContainerError::Callback)?;
}
if remainder.read().is_empty() {
return Ok(self.stacks.empty());
}
}
}
for index in 0..self.size() {
if self.items[index].read().is_empty() {
let moved = self.stacks.resolve(remainder.write().copy_and_clear());
self.set(index as i32, moved, hooks)?;
break;
}
}
if remainder.read().is_empty() {
Ok(self.stacks.empty())
} else {
Ok(remainder)
}
}
}