1
0
Fork 0

feat(interior): route logistics deposits through the shared placement core

This commit is contained in:
Jason Fraley 2026-10-20 20:08:25 -04:00
parent 0af105e055
commit 54cbf19fdf
2 changed files with 143 additions and 98 deletions

View file

@ -10,6 +10,7 @@ import { EventTypes } from "@/utils/event-log/eventTypes";
import { effectiveMaxMass } from "@/lib/base/modules";
import { checkStorageDeposit, storageViolationMessage } from "@/lib/storageRules";
import { maybeStartConstruction } from "@/lib/map/construction";
import { computeDepositPlacement } from "@/lib/interior/storageBridge";
interface ActionResult {
success: boolean;
@ -160,110 +161,35 @@ export async function addResourceInternal(
};
}
// Auto-place on grid if structure has grid dimensions
const existing = [...(structure.storedResources ?? [])];
// Place via the shared deposit core (top up stacks, first-fit grid, flat otherwise).
const gridW = structureType.xSize ?? 0;
const gridH = structureType.ySize ?? 0;
const hasGrid = gridW > 0 && gridH > 0;
const maxStack = resource.stackable === false ? 1 : (resource.maxStackSize ?? Infinity);
if (hasGrid) {
const resW = resource.gridWidth ?? 1;
const resH = resource.gridHeight ?? 1;
const ew = resW;
const eh = resH;
const maxStack = resource.stackable === false ? 1 : (resource.maxStackSize ?? Infinity);
const placed = computeDepositPlacement({
rows: ((structure.storedResources ?? []) as unknown[]).map((r) => ({ ...(r as object) })) as any[],
resourceId,
amount,
resourceName: resource.name,
maxStack,
item: { w: resource.gridWidth ?? 1, h: resource.gridHeight ?? 1 },
grid: gridW > 0 && gridH > 0 ? { w: gridW, h: gridH } : undefined,
resolveDims: (row: any) => {
const otherRes = row.resource as Resource;
if (!otherRes || typeof otherRes === "number") return null;
const rotated = row.rotated ?? false;
const ow = rotated ? (otherRes.gridHeight ?? 1) : (otherRes.gridWidth ?? 1);
const oh = rotated ? (otherRes.gridWidth ?? 1) : (otherRes.gridHeight ?? 1);
return { w: ow, h: oh };
},
});
// 1. Fill existing stacks of the same resource that have space
let remaining = amount;
const sameType = existing.filter((e) => {
const r = e.resource;
return typeof r === "object" && r !== null && "id" in r
? r.id === resourceId
: r === resourceId;
});
for (const entry of sameType) {
if (remaining <= 0) break;
const space =
maxStack === Infinity ? remaining : Math.min(maxStack - entry.amount, remaining);
if (space <= 0) continue;
const idx = existing.findIndex((e) => e.id === entry.id);
if (idx >= 0) {
existing[idx] = { ...entry, amount: entry.amount + space };
remaining -= space;
}
}
// 2. Create new entries for remaining amount
while (remaining > 0) {
let spot: { x: number; y: number } | null = null;
for (let y = 0; y <= gridH - eh && !spot; y++) {
for (let x = 0; x <= gridW - ew && !spot; x++) {
const cells = new Set<string>();
for (let dx = 0; dx < ew; dx++) {
for (let dy = 0; dy < eh; dy++) {
cells.add(`${x + dx},${y + dy}`);
}
}
let overlaps = false;
for (const other of existing) {
if (other.id == null) continue;
const otherRes = other.resource as Resource;
if (!otherRes || typeof otherRes === "number") continue;
const otherRotated = other.rotated ?? false;
const ow = otherRotated ? (otherRes.gridHeight ?? 1) : (otherRes.gridWidth ?? 1);
const oh = otherRotated ? (otherRes.gridWidth ?? 1) : (otherRes.gridHeight ?? 1);
for (let dx = 0; dx < ow; dx++) {
for (let dy = 0; dy < oh; dy++) {
if (cells.has(`${other.gridX + dx},${other.gridY + dy}`)) {
overlaps = true;
break;
}
}
if (overlaps) break;
}
if (overlaps) break;
}
if (!overlaps) spot = { x, y };
}
}
if (!spot) {
return {
success: false,
error: `No space on grid for ${resource.name}. Need ${ew}×${eh} free cells.`,
};
}
const stackAmount = Math.min(remaining, maxStack === Infinity ? remaining : maxStack);
existing.push({
resource: resourceId,
amount: stackAmount,
gridX: spot.x,
gridY: spot.y,
rotated: false,
});
remaining -= stackAmount;
}
} else {
// No grid — flat-list behavior
const existingIndex = existing.findIndex((e) => {
const res = e.resource;
return typeof res === "object" && res !== null && "id" in res
? res.id === resourceId
: res === resourceId;
});
if (existingIndex >= 0) {
existing[existingIndex] = {
...existing[existingIndex],
amount: existing[existingIndex].amount + amount,
};
} else {
existing.push({ resource: resourceId, amount, gridX: 0, gridY: 0, rotated: false });
}
if (!placed.ok) {
return { success: false, error: placed.error };
}
const existing = placed.rows as unknown as NonNullable<GameStructure["storedResources"]>;
const updated = await payload.update({
collection: "game-structures",
id: structureId,

View file

@ -150,6 +150,125 @@ export function applyStoragePlacement(
return rows;
}
export type DepositPlacementInput = {
/** Existing stored-resource rows (unmutated; a working copy is returned). */
rows: StoredResource[];
resourceId: number;
amount: number;
/** Display name used in the "no space" rejection message. */
resourceName: string;
/** Max units per row; `Infinity` for unbounded stackables. */
maxStack: number;
/** Footprint of the incoming item in cells. */
item: { w: number; h: number };
/** Structure grid; omit (or zero dims) for flat-list behavior. */
grid?: { w: number; h: number };
/**
* Resolve an existing row's occupied footprint (rotation applied), or null
* when the row's resource reference carries no dimensions (treated as not
* blocking). Callers with populated resource refs provide this.
*/
resolveDims?: (row: StoredResource) => { w: number; h: number } | null;
};
export type DepositPlacementResult =
| { ok: true; rows: StoredResource[] }
| { ok: false; error: string };
/**
* The single deposit placement engine, extracted from `addResourceInternal`
* (logistics/structures/actions.ts) so logistics and interior deposits share
* one implementation. Fills existing stacks of the same resource first, then
* creates new rows: on a gridded structure it first-fits each row into free
* cells (rejecting with a readable message when none are left); on a flat
* structure it merges into (or appends to) the first same-resource row.
*/
export function computeDepositPlacement(input: DepositPlacementInput): DepositPlacementResult {
const existing = input.rows.map((r) => ({ ...r }));
const sameResource = (row: StoredResource) => refId(row.resource) === input.resourceId;
if (input.grid && input.grid.w > 0 && input.grid.h > 0) {
const ew = input.item.w;
const eh = input.item.h;
let remaining = input.amount;
// 1. Top up existing stacks of the same resource.
for (const entry of [...existing]) {
if (remaining <= 0) break;
if (!sameResource(entry)) continue;
const space =
input.maxStack === Infinity ? remaining : Math.min(input.maxStack - entry.amount, remaining);
if (space <= 0) continue;
const idx = existing.indexOf(entry);
if (idx >= 0) {
existing[idx] = { ...entry, amount: entry.amount + space };
remaining -= space;
}
}
// 2. First-fit new rows around occupied cells.
while (remaining > 0) {
let spot: { x: number; y: number } | null = null;
for (let y = 0; y <= input.grid.h - eh && !spot; y++) {
for (let x = 0; x <= input.grid.w - ew && !spot; x++) {
const cells = new Set<string>();
for (let dx = 0; dx < ew; dx++) {
for (let dy = 0; dy < eh; dy++) {
cells.add(`${x + dx},${y + dy}`);
}
}
let overlaps = false;
for (const other of existing) {
const dims = input.resolveDims?.(other) ?? null;
if (!dims || other.gridX == null || other.gridY == null) continue;
outer: for (let dx = 0; dx < dims.w; dx++) {
for (let dy = 0; dy < dims.h; dy++) {
if (cells.has(`${other.gridX + dx},${other.gridY + dy}`)) {
overlaps = true;
break outer;
}
}
}
if (overlaps) break;
}
if (!overlaps) spot = { x, y };
}
}
if (!spot) {
return {
ok: false,
error: `No space on grid for ${input.resourceName}. Need ${ew}×${eh} free cells.`,
};
}
const stackAmount = Math.min(remaining, input.maxStack === Infinity ? remaining : input.maxStack);
existing.push({
resource: input.resourceId,
amount: stackAmount,
gridX: spot.x,
gridY: spot.y,
rotated: false,
});
remaining -= stackAmount;
}
return { ok: true, rows: existing };
}
// No grid — flat-list behavior: merge into the first same-resource row.
const existingIndex = existing.findIndex(sameResource);
if (existingIndex >= 0) {
existing[existingIndex] = {
...existing[existingIndex],
amount: existing[existingIndex].amount + input.amount,
};
} else {
existing.push({ resource: input.resourceId, amount: input.amount, gridX: 0, gridY: 0, rotated: false });
}
return { ok: true, rows: existing };
}
/**
* Mass check helper: would adding `amount` of `resourceId` (at `resourceMass`
* each) exceed the structure's effective capacity mass (blueprint capacity