载入中...
搜索中...
未找到
Logistics.cpp
浏览该文件的文档.
1// eve-hot-path
3
4#include "common/Assert.h"
5#include "common/Diagnostic.h"
6
7#include <algorithm>
8#include <cmath>
9#include <utility>
10
11namespace eve::logistics {
12namespace {
13
14Result<void> fail(DiagnosticCode code, std::string message, std::string path = {}) {
15 return Result<void>::failure(Diagnostic::error(code, std::move(message), std::move(path)));
16}
17
18template <class T>
19Result<T> failT(DiagnosticCode code, std::string message, std::string path = {}) {
20 return Result<T>::failure(Diagnostic::error(code, std::move(message), std::move(path)));
21}
22
23} // namespace
24
25Logistics::Logistics() = default;
26Logistics::~Logistics() = default;
27
29
30Result<void> Logistics::configure(int width, int height, int layers, float cellSize, float originX, float originY) {
31 if (width <= 0 || height <= 0 || layers <= 0)
32 return fail(DiagnosticCode::InvalidArgument, "grid dimensions must be positive", "configure");
33 if (!(cellSize > 0.f) || !std::isfinite(cellSize))
34 return fail(DiagnosticCode::InvalidArgument, "cellSize must be a positive finite float", "cellSize");
35 if (!std::isfinite(originX) || !std::isfinite(originY))
36 return fail(DiagnosticCode::InvalidArgument, "origin must be finite", "origin");
37 width_ = width;
38 height_ = height;
39 layers_ = layers;
40 cellSize_ = cellSize;
41 originX_ = originX;
42 originY_ = originY;
43 cells_.assign(
44 static_cast<std::size_t>(width_) * static_cast<std::size_t>(height_) * static_cast<std::size_t>(layers_),
45 Cell{});
46 machines_.clear();
47 recipes_.clear();
48 itemType_.clear();
49 itemCellX_.clear();
50 itemCellY_.clear();
51 itemLayer_.clear();
52 itemProgress_.clear();
53 itemDir_.clear();
54 occupancy_.assign(cells_.size(), -1);
55 nextMachineId_ = 1;
56 sunkTotal_ = 0;
57 craftsTotal_ = 0;
58 tick_ = SimulationTick::zero();
59 return Result<void>::success();
60}
61
63 if (width_ <= 0) return;
64 std::fill(cells_.begin(), cells_.end(), Cell{});
65 machines_.clear();
66 itemType_.clear();
67 itemCellX_.clear();
68 itemCellY_.clear();
69 itemLayer_.clear();
70 itemProgress_.clear();
71 itemDir_.clear();
72 occupancy_.assign(cells_.size(), -1);
73 nextMachineId_ = 1;
74 sunkTotal_ = 0;
75 craftsTotal_ = 0;
76 tick_ = SimulationTick::zero();
77}
78
79Result<void> Logistics::ensureConfigured() const {
80 if (width_ <= 0 || height_ <= 0 || layers_ <= 0)
81 return fail(DiagnosticCode::InvalidArgument, "logistics grid is not configured", "configure");
82 return Result<void>::success();
83}
84
85bool Logistics::inBounds(int cx, int cy, int layer) const noexcept {
86 return cx >= 0 && cy >= 0 && layer >= 0 && cx < width_ && cy < height_ && layer < layers_;
87}
88
89std::size_t Logistics::cellIndex(int cx, int cy, int layer) const noexcept {
90 return (static_cast<std::size_t>(layer) * static_cast<std::size_t>(height_) + static_cast<std::size_t>(cy)) *
91 static_cast<std::size_t>(width_) +
92 static_cast<std::size_t>(cx);
93}
94
95void Logistics::dirDelta(Dir dir, int& dx, int& dy) noexcept {
96 switch (dir) {
97 case Dir::East:
98 dx = 1;
99 dy = 0;
100 break;
101 case Dir::South:
102 dx = 0;
103 dy = 1;
104 break;
105 case Dir::West:
106 dx = -1;
107 dy = 0;
108 break;
109 case Dir::North:
110 dx = 0;
111 dy = -1;
112 break;
113 }
114}
115
116Result<int> Logistics::registerRecipe(std::string id, int inputType, int inputCount, int outputType, int outputCount,
117 float durationSec) {
118 if (id.empty()) return failT<int>(DiagnosticCode::InvalidArgument, "recipe id must be non-empty", "id");
119 if (inputCount <= 0 || outputCount <= 0)
120 return failT<int>(DiagnosticCode::InvalidArgument, "recipe counts must be positive", "count");
121 if (!(durationSec > 0.f) || !std::isfinite(durationSec))
122 return failT<int>(DiagnosticCode::InvalidArgument, "recipe duration must be positive finite", "duration");
123 for (std::size_t i = 0; i < recipes_.size(); ++i) {
124 if (recipes_[i].id == id) {
125 recipes_[i] = Recipe{std::move(id), inputType, inputCount, outputType, outputCount, durationSec};
126 return Result<int>::success(static_cast<int>(i));
127 }
128 }
129 recipes_.push_back(Recipe{std::move(id), inputType, inputCount, outputType, outputCount, durationSec});
130 return Result<int>::success(static_cast<int>(recipes_.size() - 1));
131}
132
134 if (auto ready = ensureConfigured(); !ready.ok()) return ready;
135 if (!inBounds(cx, cy, layer)) return fail(DiagnosticCode::InvalidArgument, "cell out of bounds", "placeBelt");
136 if (dir < 0 || dir > 3) return fail(DiagnosticCode::InvalidArgument, "dir must be 0..3", "dir");
137 Cell& cell = cells_[cellIndex(cx, cy, layer)];
138 if (cell.kind == CellKind::Machine)
139 return fail(DiagnosticCode::Conflict, "cannot place belt on machine footprint", "placeBelt");
140 cell.kind = CellKind::Belt;
141 cell.dir = static_cast<Dir>(dir);
142 cell.machineSlot = -1;
143 cell.itemType = 0;
144 cell.spawnRate = 0.f;
145 cell.spawnAcc = 0.f;
146 return Result<void>::success();
147}
148
150 if (auto ready = ensureConfigured(); !ready.ok()) return ready;
151 if (!inBounds(cx, cy, layer)) return fail(DiagnosticCode::InvalidArgument, "cell out of bounds", "clearCell");
152 Cell& cell = cells_[cellIndex(cx, cy, layer)];
153 if (cell.kind == CellKind::Machine)
154 return fail(DiagnosticCode::Conflict, "use removeMachine for machine footprints", "clearCell");
155 const int item = findItemAt(cx, cy, layer);
156 if (item >= 0) destroyItemAt(static_cast<std::size_t>(item));
157 cell = Cell{};
158 return Result<void>::success();
159}
160
161Result<int> Logistics::placeMachine(int cx, int cy, int width, int height, std::string_view recipeId, int layer) {
162 if (auto ready = ensureConfigured(); !ready.ok()) return Result<int>::failure(ready.status());
163 if (width <= 0 || height <= 0)
164 return failT<int>(DiagnosticCode::InvalidArgument, "machine size must be positive", "size");
165 if (!inBounds(cx, cy, layer) || !inBounds(cx + width - 1, cy + height - 1, layer))
166 return failT<int>(DiagnosticCode::InvalidArgument, "machine footprint out of bounds", "placeMachine");
167 int recipeIndex = -1;
168 for (std::size_t i = 0; i < recipes_.size(); ++i) {
169 if (recipes_[i].id == recipeId) {
170 recipeIndex = static_cast<int>(i);
171 break;
172 }
173 }
174 if (recipeIndex < 0) return failT<int>(DiagnosticCode::NotFound, "recipe id is not registered", "recipeId");
175 for (int y = cy; y < cy + height; ++y) {
176 for (int x = cx; x < cx + width; ++x) {
177 if (cells_[cellIndex(x, y, layer)].kind != CellKind::Empty)
178 return failT<int>(DiagnosticCode::Conflict, "machine footprint overlaps occupied cells",
179 "placeMachine");
180 if (findItemAt(x, y, layer) >= 0)
181 return failT<int>(DiagnosticCode::Conflict, "machine footprint overlaps items", "placeMachine");
182 }
183 }
184 Machine machine;
185 machine.alive = true;
186 machine.id = nextMachineId_++;
187 machine.originX = cx;
188 machine.originY = cy;
189 machine.width = width;
190 machine.height = height;
191 machine.layer = layer;
192 machine.recipeIndex = recipeIndex;
193 machine.ownerId = "machine:" + std::to_string(machine.id);
194 const int slot = static_cast<int>(machines_.size());
195 machines_.push_back(std::move(machine));
196 for (int y = cy; y < cy + height; ++y) {
197 for (int x = cx; x < cx + width; ++x) {
198 Cell& cell = cells_[cellIndex(x, y, layer)];
199 cell.kind = CellKind::Machine;
200 cell.machineSlot = slot;
201 }
202 }
203 return Result<int>::success(machines_.back().id);
204}
205
207 if (auto ready = ensureConfigured(); !ready.ok()) return ready;
208 for (std::size_t i = 0; i < machines_.size(); ++i) {
209 Machine& machine = machines_[i];
210 if (!machine.alive || machine.id != machineId) continue;
211 for (int y = machine.originY; y < machine.originY + machine.height; ++y) {
212 for (int x = machine.originX; x < machine.originX + machine.width; ++x) {
213 cells_[cellIndex(x, y, machine.layer)] = Cell{};
214 }
215 }
216 machine = Machine{};
217 return Result<void>::success();
218 }
219 return fail(DiagnosticCode::NotFound, "machine id not found", "removeMachine");
220}
221
222Result<void> Logistics::placeSource(int cx, int cy, int itemType, float itemsPerSec, int layer) {
223 if (auto ready = ensureConfigured(); !ready.ok()) return ready;
224 if (!inBounds(cx, cy, layer)) return fail(DiagnosticCode::InvalidArgument, "cell out of bounds", "placeSource");
225 if (!(itemsPerSec > 0.f) || !std::isfinite(itemsPerSec))
226 return fail(DiagnosticCode::InvalidArgument, "itemsPerSec must be positive finite", "itemsPerSec");
227 Cell& cell = cells_[cellIndex(cx, cy, layer)];
228 if (cell.kind == CellKind::Machine)
229 return fail(DiagnosticCode::Conflict, "cannot place source on machine footprint", "placeSource");
230 cell.kind = CellKind::Source;
231 cell.itemType = itemType;
232 cell.spawnRate = itemsPerSec;
233 cell.spawnAcc = 0.f;
234 cell.dir = Dir::East;
235 cell.machineSlot = -1;
236 return Result<void>::success();
237}
238
240 if (auto ready = ensureConfigured(); !ready.ok()) return ready;
241 if (!inBounds(cx, cy, layer)) return fail(DiagnosticCode::InvalidArgument, "cell out of bounds", "placeSink");
242 Cell& cell = cells_[cellIndex(cx, cy, layer)];
243 if (cell.kind == CellKind::Machine)
244 return fail(DiagnosticCode::Conflict, "cannot place sink on machine footprint", "placeSink");
245 cell.kind = CellKind::Sink;
246 cell.machineSlot = -1;
247 cell.itemType = 0;
248 cell.spawnRate = 0.f;
249 cell.spawnAcc = 0.f;
250 return Result<void>::success();
251}
252
253int Logistics::findItemAt(int cx, int cy, int layer) const noexcept {
254 if (!inBounds(cx, cy, layer) || occupancy_.empty()) return -1;
255 return occupancy_[cellIndex(cx, cy, layer)];
256}
257
258void Logistics::destroyItemAt(std::size_t index) {
259 EV_ASSERT(index < itemType_.size());
260 const int cx = itemCellX_[index];
261 const int cy = itemCellY_[index];
262 const int layer = itemLayer_[index];
263 if (inBounds(cx, cy, layer)) occupancy_[cellIndex(cx, cy, layer)] = -1;
264 const std::size_t last = itemType_.size() - 1;
265 if (index != last) {
266 itemType_[index] = itemType_[last];
267 itemCellX_[index] = itemCellX_[last];
268 itemCellY_[index] = itemCellY_[last];
269 itemLayer_[index] = itemLayer_[last];
270 itemProgress_[index] = itemProgress_[last];
271 itemDir_[index] = itemDir_[last];
272 if (inBounds(itemCellX_[index], itemCellY_[index], itemLayer_[index]))
273 occupancy_[cellIndex(itemCellX_[index], itemCellY_[index], itemLayer_[index])] =
274 static_cast<std::int32_t>(index);
275 }
276 itemType_.pop_back();
277 itemCellX_.pop_back();
278 itemCellY_.pop_back();
279 itemLayer_.pop_back();
280 itemProgress_.pop_back();
281 itemDir_.pop_back();
282}
283
284Result<int> Logistics::spawnItem(int cx, int cy, int itemType, int layer) {
285 if (auto ready = ensureConfigured(); !ready.ok()) return Result<int>::failure(ready.status());
286 if (!inBounds(cx, cy, layer)) return failT<int>(DiagnosticCode::InvalidArgument, "cell out of bounds", "spawnItem");
287 const Cell& cell = cells_[cellIndex(cx, cy, layer)];
288 if (cell.kind != CellKind::Belt)
289 return failT<int>(DiagnosticCode::Conflict, "items may only spawn on belt cells", "spawnItem");
290 if (findItemAt(cx, cy, layer) >= 0)
291 return failT<int>(DiagnosticCode::Conflict, "belt cell already occupied", "spawnItem");
292 const int index = static_cast<int>(itemType_.size());
293 itemType_.push_back(itemType);
294 itemCellX_.push_back(cx);
295 itemCellY_.push_back(cy);
296 itemLayer_.push_back(layer);
297 itemProgress_.push_back(0.f);
298 itemDir_.push_back(static_cast<std::uint8_t>(cell.dir));
299 occupancy_[cellIndex(cx, cy, layer)] = index;
301}
302
303ItemState Logistics::makeItemState(const Item& item) const noexcept {
305 state.cellX = item.cellX;
306 state.cellY = item.cellY;
307 state.type = item.type;
308 state.progress = item.progress;
309 state.dir = static_cast<int>(item.dir);
310 int dx = 0, dy = 0;
311 dirDelta(item.dir, dx, dy);
312 const float along = item.progress * cellSize_;
313 state.x = originX_ + (static_cast<float>(item.cellX) + 0.5f) * cellSize_ + static_cast<float>(dx) * along;
314 state.y = originY_ + (static_cast<float>(item.cellY) + 0.5f) * cellSize_ + static_cast<float>(dy) * along;
315 return state;
316}
317
319 if (index < 0 || index >= itemCount())
320 return failT<ItemState>(DiagnosticCode::NotFound, "item index out of range", "itemAt");
321 Item item;
322 item.cellX = itemCellX_[static_cast<std::size_t>(index)];
323 item.cellY = itemCellY_[static_cast<std::size_t>(index)];
324 item.layer = itemLayer_[static_cast<std::size_t>(index)];
325 item.type = itemType_[static_cast<std::size_t>(index)];
326 item.progress = itemProgress_[static_cast<std::size_t>(index)];
327 item.dir = static_cast<Dir>(itemDir_[static_cast<std::size_t>(index)]);
328 return Result<ItemState>::success(makeItemState(item));
329}
330
332 std::vector<float> out;
333 out.resize(static_cast<std::size_t>(itemCount()) * 6u);
334 for (int i = 0; i < itemCount(); ++i) {
335 const std::size_t base = static_cast<std::size_t>(i) * 6u;
336 out[base + 0] = static_cast<float>(itemCellX_[static_cast<std::size_t>(i)]);
337 out[base + 1] = static_cast<float>(itemCellY_[static_cast<std::size_t>(i)]);
338 out[base + 2] = itemProgress_[static_cast<std::size_t>(i)];
339 out[base + 3] = static_cast<float>(itemDir_[static_cast<std::size_t>(i)]);
340 out[base + 4] = static_cast<float>(itemType_[static_cast<std::size_t>(i)]);
341 out[base + 5] = static_cast<float>(itemLayer_[static_cast<std::size_t>(i)]);
342 }
343 return Result<std::vector<float>>::success(std::move(out));
344}
345
347 std::vector<float> out;
348 out.resize(static_cast<std::size_t>(itemCount()) * 3u);
349 for (int i = 0; i < itemCount(); ++i) {
350 auto state = itemAt(i);
351 if (!state.ok()) {
352 state.ignore("packItemWorldFloats skipped missing item");
353 continue;
354 }
355 const ItemState& snap = state.value();
356 const std::size_t base = static_cast<std::size_t>(i) * 3u;
357 out[base + 0] = snap.x;
358 out[base + 1] = snap.y;
359 out[base + 2] = static_cast<float>(snap.type);
360 }
361 return Result<std::vector<float>>::success(std::move(out));
362}
363
365 if (index < 0 || index >= static_cast<int>(machines_.size()))
366 return failT<MachineState>(DiagnosticCode::NotFound, "machine slot out of range", "machineAt");
367 const Machine& machine = machines_[static_cast<std::size_t>(index)];
368 if (!machine.alive) return failT<MachineState>(DiagnosticCode::NotFound, "machine slot is empty", "machineAt");
370 out.id = machine.id;
371 out.originX = machine.originX;
372 out.originY = machine.originY;
373 out.width = machine.width;
374 out.height = machine.height;
375 out.recipeIndex = machine.recipeIndex;
376 out.inputStored = machine.inputStored;
377 out.outputStored = machine.outputStored;
378 out.craftProgress = machine.craftProgress;
379 out.crafting = machine.crafting;
380 out.layer = machine.layer;
382}
383
384std::string Logistics::machineOwnerId(int index) const {
385 if (index < 0 || index >= static_cast<int>(machines_.size())) return {};
386 const Machine& machine = machines_[static_cast<std::size_t>(index)];
387 return machine.alive ? machine.ownerId : std::string{};
388}
389
390int Logistics::cellKind(int cx, int cy, int layer) const noexcept {
391 if (!inBounds(cx, cy, layer)) return static_cast<int>(CellKind::Empty);
392 return static_cast<int>(cells_[cellIndex(cx, cy, layer)].kind);
393}
394
395int Logistics::cellDir(int cx, int cy, int layer) const noexcept {
396 if (!inBounds(cx, cy, layer)) return -1;
397 const Cell& cell = cells_[cellIndex(cx, cy, layer)];
398 return cell.kind == CellKind::Belt ? static_cast<int>(cell.dir) : -1;
399}
400
401int Logistics::cellMachine(int cx, int cy, int layer) const noexcept {
402 if (!inBounds(cx, cy, layer)) return -1;
403 const Cell& cell = cells_[cellIndex(cx, cy, layer)];
404 if (cell.kind != CellKind::Machine || cell.machineSlot < 0) return -1;
405 const Machine& machine = machines_[static_cast<std::size_t>(cell.machineSlot)];
406 return machine.alive ? machine.id : -1;
407}
408
409void Logistics::stepSources(float dt, StepReport& report) {
410 for (int layer = 0; layer < layers_; ++layer) {
411 for (int y = 0; y < height_; ++y) {
412 for (int x = 0; x < width_; ++x) {
413 Cell& cell = cells_[cellIndex(x, y, layer)];
414 if (cell.kind != CellKind::Source) continue;
415 cell.spawnAcc += cell.spawnRate * dt;
416 while (cell.spawnAcc >= 1.f) {
417 const int tx = x + 1;
418 const int ty = y;
419 if (!inBounds(tx, ty, layer) || cells_[cellIndex(tx, ty, layer)].kind != CellKind::Belt) break;
420 if (findItemAt(tx, ty, layer) >= 0) break;
421 auto spawned = spawnItem(tx, ty, cell.itemType, layer);
422 if (!spawned.ok()) {
423 spawned.ignore("source spawn rejected");
424 break;
425 }
426 cell.spawnAcc -= 1.f;
427 ++report.itemsSpawned;
428 }
429 }
430 }
431 }
432}
433
434void Logistics::stepSinks(StepReport& report) {
435 for (int layer = 0; layer < layers_; ++layer) {
436 for (int y = 0; y < height_; ++y) {
437 for (int x = 0; x < width_; ++x) {
438 if (cells_[cellIndex(x, y, layer)].kind != CellKind::Sink) continue;
439 const int sx = x - 1;
440 const int sy = y;
441 if (!inBounds(sx, sy, layer)) continue;
442 const int item = findItemAt(sx, sy, layer);
443 if (item < 0) continue;
444 // Pull when item is near the end of the west belt cell heading east.
445 if (static_cast<Dir>(itemDir_[static_cast<std::size_t>(item)]) != Dir::East) continue;
446 if (itemProgress_[static_cast<std::size_t>(item)] < 0.85f) continue;
447 destroyItemAt(static_cast<std::size_t>(item));
448 ++sunkTotal_;
449 ++report.itemsSunk;
450 }
451 }
452 }
453}
454
455void Logistics::tryPullInputs() {
456 for (Machine& machine : machines_) {
457 if (!machine.alive || machine.recipeIndex < 0) continue;
458 const Recipe& recipe = recipes_[static_cast<std::size_t>(machine.recipeIndex)];
459 if (machine.inputStored >= bufferCapacity_) continue;
460 const int px = machine.originX - 1;
461 const int py = machine.originY;
462 if (!inBounds(px, py, machine.layer)) continue;
463 const int item = findItemAt(px, py, machine.layer);
464 if (item < 0) continue;
465 if (itemType_[static_cast<std::size_t>(item)] != recipe.inputType) continue;
466 if (itemProgress_[static_cast<std::size_t>(item)] < 0.85f) continue;
467 if (static_cast<Dir>(itemDir_[static_cast<std::size_t>(item)]) != Dir::East) continue;
468 destroyItemAt(static_cast<std::size_t>(item));
469 ++machine.inputStored;
470 }
471}
472
473void Logistics::tryPushOutputs() {
474 for (Machine& machine : machines_) {
475 if (!machine.alive || machine.outputStored <= 0 || machine.recipeIndex < 0) continue;
476 const Recipe& recipe = recipes_[static_cast<std::size_t>(machine.recipeIndex)];
477 const int px = machine.originX + machine.width;
478 const int py = machine.originY;
479 if (!inBounds(px, py, machine.layer)) continue;
480 if (cells_[cellIndex(px, py, machine.layer)].kind != CellKind::Belt) continue;
481 if (findItemAt(px, py, machine.layer) >= 0) continue;
482 auto spawned = spawnItem(px, py, recipe.outputType, machine.layer);
483 if (!spawned.ok()) {
484 spawned.ignore("machine output blocked");
485 continue;
486 }
487 --machine.outputStored;
488 }
489}
490
491void Logistics::stepMachines(float dt, StepReport& report) {
492 tryPullInputs();
493 for (Machine& machine : machines_) {
494 if (!machine.alive || machine.recipeIndex < 0) continue;
495 const Recipe& recipe = recipes_[static_cast<std::size_t>(machine.recipeIndex)];
496 if (!machine.crafting) {
497 if (machine.inputStored >= recipe.inputCount &&
498 machine.outputStored + recipe.outputCount <= bufferCapacity_) {
499 machine.inputStored -= recipe.inputCount;
500 machine.crafting = true;
501 machine.craftProgress = 0.f;
502 ++report.craftsStarted;
503 }
504 }
505 if (!machine.crafting) continue;
506 machine.craftProgress += dt / recipe.durationSec;
507 if (machine.craftProgress < 1.f) continue;
508 machine.crafting = false;
509 machine.craftProgress = 0.f;
510 machine.outputStored += recipe.outputCount;
511 ++craftsTotal_;
512 ++report.craftsFinished;
513 }
514 tryPushOutputs();
515}
516
517void Logistics::stepBelts(float dt, StepReport& report) {
518 const float delta = beltSpeed_ * dt;
519 // Move from downstream to upstream by scanning opposite to facing so hand-offs are stable.
520 std::vector<int> order(static_cast<std::size_t>(itemCount()));
521 for (int i = 0; i < itemCount(); ++i) order[static_cast<std::size_t>(i)] = i;
522 std::stable_sort(order.begin(), order.end(), [&](int a, int b) {
523 const int ax = itemCellX_[static_cast<std::size_t>(a)];
524 const int ay = itemCellY_[static_cast<std::size_t>(a)];
525 const int bx = itemCellX_[static_cast<std::size_t>(b)];
526 const int by = itemCellY_[static_cast<std::size_t>(b)];
527 const Dir da = static_cast<Dir>(itemDir_[static_cast<std::size_t>(a)]);
528 if (da == Dir::East) return ax > bx || (ax == bx && ay > by);
529 if (da == Dir::West) return ax < bx || (ax == bx && ay > by);
530 if (da == Dir::South) return ay > by || (ay == by && ax > bx);
531 return ay < by || (ay == by && ax > bx);
532 });
533
534 for (int idx : order) {
535 if (idx < 0 || idx >= itemCount()) continue;
536 float progress = itemProgress_[static_cast<std::size_t>(idx)] + delta;
537 int cx = itemCellX_[static_cast<std::size_t>(idx)];
538 int cy = itemCellY_[static_cast<std::size_t>(idx)];
539 int layer = itemLayer_[static_cast<std::size_t>(idx)];
540 Dir dir = static_cast<Dir>(itemDir_[static_cast<std::size_t>(idx)]);
541 bool moved = false;
542 while (progress >= 1.f) {
543 int dx = 0, dy = 0;
544 dirDelta(dir, dx, dy);
545 const int nx = cx + dx;
546 const int ny = cy + dy;
547 if (!inBounds(nx, ny, layer) || cells_[cellIndex(nx, ny, layer)].kind != CellKind::Belt ||
548 findItemAt(nx, ny, layer) >= 0) {
549 progress = 0.999f;
550 ++report.jammedMoves;
551 break;
552 }
553 occupancy_[cellIndex(cx, cy, layer)] = -1;
554 cx = nx;
555 cy = ny;
556 dir = cells_[cellIndex(nx, ny, layer)].dir;
557 occupancy_[cellIndex(cx, cy, layer)] = idx;
558 progress -= 1.f;
559 moved = true;
560 }
561 itemCellX_[static_cast<std::size_t>(idx)] = cx;
562 itemCellY_[static_cast<std::size_t>(idx)] = cy;
563 itemLayer_[static_cast<std::size_t>(idx)] = layer;
564 itemDir_[static_cast<std::size_t>(idx)] = static_cast<std::uint8_t>(dir);
565 itemProgress_[static_cast<std::size_t>(idx)] = progress;
566 if (moved) ++report.itemsMoved;
567 }
568}
569
571 if (auto ready = ensureConfigured(); !ready.ok()) return Result<StepReport>::failure(ready.status());
572 if (!(step.delta.seconds() > 0.0) || !std::isfinite(step.delta.seconds()))
573 return failT<StepReport>(DiagnosticCode::InvalidArgument, "advance dt must be positive finite", "dt");
574 if (step.tick.value() <= tick_.value())
575 return failT<StepReport>(DiagnosticCode::Conflict, "simulation tick must strictly increase", "tick");
576 StepReport report;
577 report.tick = step.tick;
578 report.elapsed = step.delta;
579 const float dt = static_cast<float>(step.delta.seconds());
580 stepSources(dt, report);
581 stepBelts(dt, report);
582 stepMachines(dt, report);
583 stepSinks(report);
584 tick_ = step.tick;
585 return Result<StepReport>::success(std::move(report));
586}
587
589 if (!(dt > 0.f) || !std::isfinite(dt))
590 return failT<StepReport>(DiagnosticCode::InvalidArgument, "advance dt must be positive finite", "dt");
591 auto duration = Duration::fromSeconds(static_cast<double>(dt));
592 if (!duration.ok()) return Result<StepReport>::failure(duration.status());
593 const SimulationTick next(tick_.value() + 1);
594 return advance(SimulationStep{next, std::move(duration).takeValue()});
595}
596
597} // namespace eve::logistics
double y
double x
float duration
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
Stable, structured diagnostics shared by engine modules.
std::string message
DiagnosticCode code
std::uint32_t spawned
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::int32_t > order
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
glm::dvec3 dx
double dt
BakeRecipe recipe
TileLayer * layer
int idx
std::string path
Definition PlayHost.cpp:111
std::string slot
ScriptStructure out
std::string kind
float dy
Definition Shadow.cpp:151
Cell cell
float step
Definition TreeMesh.cpp:451
V3 dir
Definition TreeMesh.cpp:151
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
Deterministic 2D factory logistics: belts, discrete items, machine buffers, crafts.
Definition Logistics.h:82
int height() const noexcept
Grid height in cells.
Definition Logistics.h:153
Result< void > removeMachine(int machineId)
Remove a machine by id and free its footprint cells.
Result< int > registerRecipe(std::string id, int inputType, int inputCount, int outputType, int outputCount, float durationSec)
Register or replace a named recipe.
Result< int > placeMachine(int cx, int cy, int width, int height, std::string_view recipeId, int layer=0)
Place a rectangular machine footprint and bind a recipe.
int itemCount() const noexcept
Live item count.
Definition Logistics.h:173
Result< void > configure(int width, int height, int layers, float cellSize, float originX, float originY)
Size the factory grid and world mapping.
Definition Logistics.cpp:30
std::string machineOwnerId(int index) const
Stable Production-owner string for machine slot i (empty when invalid).
~Logistics() override
Destroy logistics storage.
Result< std::vector< float > > packItemSimFloats() const
Pack GPU-friendly floats: [cellX,cellY,progress,dir,type,layer] * itemCount. @cost O(items); amortize...
Logistics()
Construct an empty unconfigured logistics world.
Result< void > placeSink(int cx, int cy, int layer=0)
Place a sink that destroys items arriving from the westward adjacent belt.
int cellDir(int cx, int cy, int layer=0) const noexcept
Belt direction at cell, or -1 when not a belt.
float originX() const noexcept
World origin X.
Definition Logistics.h:159
Result< void > placeSource(int cx, int cy, int itemType, float itemsPerSec, int layer=0)
Place an item emitter that injects itemType onto the eastward adjacent belt.
Result< void > clearCell(int cx, int cy, int layer=0)
Remove belt/source/sink content from a cell (machines must use removeMachine).
float cellSize() const noexcept
World units per cell.
Definition Logistics.h:157
Result< StepReport > advance(const SimulationStep &step)
Advance one fixed logistics step.
Result< void > placeBelt(int cx, int cy, int dir, int layer=0)
Place a belt cell facing dir (0=E,1=S,2=W,3=N) on layer.
float originY() const noexcept
World origin Y.
Definition Logistics.h:161
int layers() const noexcept
Configured floor count.
Definition Logistics.h:155
int cellKind(int cx, int cy, int layer=0) const noexcept
Cell kind at (cx,cy,layer); Empty when out of range.
void clear()
Clear every cell, item, machine, recipe and reset the simulation clock.
Definition Logistics.cpp:62
Result< MachineState > machineAt(int index) const
Copy machine slot i; NotFound when empty/out of range.
Result< std::vector< float > > packItemWorldFloats() const
Pack world positions for CPU draw fallback: [x,y,type] * itemCount. @cost O(items).
Result< ItemState > itemAt(int index) const
Copy item i; NotFound when index is out of range.
int cellMachine(int cx, int cy, int layer=0) const noexcept
Machine id occupying the cell, or -1.
Result< int > spawnItem(int cx, int cy, int itemType, int layer=0)
Spawn one item onto a belt cell at progress 0.
int width() const noexcept
Grid width in cells.
Definition Logistics.h:151
Dir
Orthographic belt / port facing on the 2D factory grid (Y grows south).
Definition Logistics.h:16
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Read-only item snapshot for script / GPU packing.
Definition Logistics.h:44
float x
World X (cell center + progress along belt).
Definition Logistics.h:45
Read-only machine snapshot.
Definition Logistics.h:55
Compact recipe: consume inputCount of inputType, emit outputCount of outputType.
Definition Logistics.h:22
One completed fixed logistics step.
Definition Logistics.h:32