17#include <unordered_map>
23std::atomic<std::uint64_t> nextPixelWorldId{1};
25int floorDiv(
int value)
noexcept {
29int floorMod(
int value)
noexcept {
37 friend bool operator==(
const ChunkCoord&,
const ChunkCoord&) =
default;
38 friend bool operator<(
const ChunkCoord&
a,
const ChunkCoord&
b) {
39 return a.y !=
b.y ?
a.y <
b.y :
a.x <
b.x;
43struct ChunkCoordHash {
44 std::size_t operator()(ChunkCoord coord)
const noexcept {
45 const auto x = std::uint64_t(std::uint32_t(coord.x));
46 const auto y = std::uint64_t(std::uint32_t(coord.y));
47 return std::size_t((
x << 32U) ^
y);
52 std::array<PixelCell, kPixelChunkSize * kPixelChunkSize>
cells{};
53 std::array<std::uint64_t, kPixelChunkSize * kPixelChunkSize>
updated{};
67 static std::size_t
index(
int x,
int y)
noexcept {
74 "snapshot", {},
"pixelworld"));
78void append(std::vector<std::byte>&
out, T
value) {
79 const auto*
first =
reinterpret_cast<const std::byte*
>(&
value);
99 std::unordered_map<ChunkCoord, Chunk, ChunkCoordHash>
chunks;
100 std::unordered_map<ChunkCoord, std::uint64_t, ChunkCoordHash>
removedChunks;
112 std::uint64_t
worldId = nextPixelWorldId.fetch_add(1, std::memory_order_relaxed);
159 std::uint8_t(targetFluid && targetDef.density < sourceDef.density);
163 for (std::size_t ruleIndex = 0; ruleIndex <
reactions.size(); ++ruleIndex) {
165 const std::size_t
first = std::size_t(rule.first);
166 const std::size_t
second = std::size_t(rule.second);
168 ruleIndex > std::size_t(std::numeric_limits<std::uint16_t>::max()))
171 std::uint16_t(ruleIndex));
174 std::uint16_t(ruleIndex));
179 const std::size_t sourceIndex = std::size_t(
source);
180 const std::size_t targetIndex = std::size_t(
target);
187 const std::size_t sourceIndex = std::size_t(
source);
188 const std::size_t targetIndex = std::size_t(
target);
207 if (
cell.thermalRemainder != 0) ++chunk.thermalRemainderCells;
209 if (
material < chunk.materialCounts.size())
212 ++chunk.materialOverflow;
213 chunk.minimumTemperature = std::min(chunk.minimumTemperature,
cell.temperature);
214 chunk.maximumTemperature = std::max(chunk.maximumTemperature,
cell.temperature);
221 if (
cell.thermalRemainder != 0) --chunk.thermalRemainderCells;
223 if (
material < chunk.materialCounts.size())
226 --chunk.materialOverflow;
227 if (
cell.temperature == chunk.minimumTemperature ||
cell.temperature == chunk.maximumTemperature)
228 chunk.temperatureBoundsDirty =
true;
232 chunk.materialCounts.fill(0);
235 chunk.thermalRemainderCells = 0;
236 chunk.materialOverflow = 0;
237 chunk.minimumTemperature = 32767;
238 chunk.maximumTemperature = -32768;
239 chunk.temperatureBoundsDirty =
false;
244 if (!chunk.temperatureBoundsDirty)
return;
245 chunk.minimumTemperature = 32767;
246 chunk.maximumTemperature = -32768;
249 chunk.minimumTemperature = std::min(chunk.minimumTemperature,
cell.temperature);
250 chunk.maximumTemperature = std::max(chunk.maximumTemperature,
cell.temperature);
252 chunk.temperatureBoundsDirty =
false;
257 return chunk ? chunk->cells[Chunk::index(floorMod(
x), floorMod(
y))] :
PixelCell{};
266 std::int64_t energy = std::int64_t(
cell.temperature) *
capacity +
cell.thermalRemainder;
268 std::int64_t remainder = energy %
capacity;
273 if (
temperature < std::numeric_limits<std::int16_t>::min()) {
274 temperature = std::numeric_limits<std::int16_t>::min();
276 }
else if (
temperature > std::numeric_limits<std::int16_t>::max()) {
277 temperature = std::numeric_limits<std::int16_t>::max();
281 cell.thermalRemainder = std::uint16_t(remainder);
287 return chunk ? chunk->updated[Chunk::index(floorMod(
x), floorMod(
y))] : 0;
291 const int cx = floorDiv(
x),
cy = floorDiv(
y);
292 for (
int oy = -1;
oy <= 1; ++
oy)
293 for (
int ox = -1;
ox <= 1; ++
ox) {
303 const auto index = Chunk::index(floorMod(
x), floorMod(
y));
305 if (oldCell !=
cell) {
310 if (markUpdated) chunk.updated[
index] = updatedTick;
313 chunk.touched =
true;
317 std::uint64_t updatedTick,
bool markUpdated =
true) {
319 if (oldCell !=
cell) {
324 if (markUpdated) chunk.updated[
index] = updatedTick;
327 chunk.touched =
true;
331 std::uint64_t updatedTick,
bool markUpdated =
true) {
335 bool moveOrSwap(
int x,
int y,
int tx,
int ty, std::uint64_t currentTick) {
341 std::uint64_t currentTick) {
352 std::uint64_t currentTick) {
353 const auto sourceIndex = Chunk::index(
sourceX, sourceY);
354 const auto targetIndex = Chunk::index(
targetX, targetY);
357 chunk.cells[targetIndex] =
source;
358 chunk.cells[sourceIndex] =
target;
359 chunk.updated[targetIndex] = currentTick;
360 chunk.updated[sourceIndex] = currentTick;
363 chunk.touched =
true;
374 bool pseudoBit(
int x,
int y, std::uint64_t currentTick)
const noexcept {
375 std::uint64_t
value =
seed ^ (std::uint64_t(std::uint32_t(
x)) << 32U) ^
376 std::uint64_t(std::uint32_t(
y)) ^ (currentTick * 0x9E3779B97F4A7C15ULL);
378 value *= 0xBF58476D1CE4E5B9ULL;
380 return (
value & 1U) != 0;
389 : impl_(
std::make_unique<
Impl>(
std::move(catalog))) {
400 if (
this == &other)
return *
this;
402 impl_ = std::move(other.impl_);
413 return impl_->catalog.definition(
material).displayRgba;
424 "material Catalog reload requires a paused world",
"paused");
425 if (expectedFingerprint != impl_->catalog.fingerprint())
427 "material Catalog expected fingerprint is stale",
"expectedFingerprint");
428 const auto current = impl_->catalog.definitions();
430 if (
current.size() != replacement.size())
432 "live Catalog reload cannot add or remove material ids",
"materials");
436 "live Catalog reload must preserve every material id and name",
437 "materials[" + std::to_string(
index) +
"]");
448 impl_->catalog = std::move(catalog);
449 impl_->rebuildMaterialRuntimeTables();
452 impl_->lastEditSequence = 0;
453 for (
auto& [coord, chunk] : impl_->chunks) {
455 impl_->rebuildActivity(chunk);
456 impl_->refreshTemperatureBounds(chunk);
457 chunk.revision = impl_->revision;
459 chunk.touched =
true;
471 impl_->put(
x,
y,
cell, impl_->tick);
472 impl_->wakeAround(
x,
y);
485 cell.temperature = impl_->catalog.definition(
cell.material).defaultTemperature;
486 cell.lifetime = std::uint8_t(std::min<std::uint16_t>(impl_->catalog.definition(
cell.material).defaultLifetime,
487 std::numeric_limits<std::uint8_t>::max()));
494 .expect(
"PixelWorld::paintCircle requires a registered material");
506 const int dx =
x - centerX,
dy =
y - centerY;
510 cell.temperature = impl_->catalog.definition(
id).defaultTemperature;
511 cell.lifetime = std::uint8_t(std::min<std::uint16_t>(impl_->catalog.definition(
id).defaultLifetime,
512 std::numeric_limits<std::uint8_t>::max()));
520 const auto reject = [](std::string
message, std::string
path) {
524 if (command.
sequence != impl_->lastEditSequence + 1)
525 return reject(
"edit sequence must be exactly previous sequence + 1",
"sequence");
527 return reject(
"edit radius must be in [0, 4096]",
"radius");
528 if (command.
centerX < -100'000'000 || command.
centerX > 100'000'000 ||
530 return reject(
"edit center is outside the supported coordinate range",
"center");
532 std::size_t(command.
material) >= impl_->catalog.definitions().size())
533 return reject(
"paint command references an unknown material id",
"material");
535 return reject(
"explosion strength must be in [0, 1000000]",
"strength");
545 const std::int64_t radiusSquared = std::int64_t(command.
radius) * command.
radius;
548 const std::int64_t
dx = std::int64_t(
x) - command.
centerX;
549 const std::int64_t
dy = std::int64_t(
y) - command.
centerY;
550 const std::int64_t distanceSquared =
dx *
dx +
dy *
dy;
551 if (distanceSquared > radiusSquared)
continue;
559 const auto& definition = impl_->catalog.definition(command.
material);
560 newCell.
temperature = definition.defaultTemperature;
561 newCell.
lifetime = std::uint8_t(std::min<std::uint16_t>(
562 definition.defaultLifetime, std::numeric_limits<std::uint8_t>::max()));
565 newCell.
temperature = std::int16_t(std::clamp<int>(
570 const std::int64_t denominator = std::max<std::int64_t>(1, radiusSquared);
571 const int radialStrength = int(std::int64_t(command.
strength) *
572 (radiusSquared - distanceSquared + 1) / denominator);
573 if (radialStrength >= impl_->catalog.definition(oldCell.
material).blastResistance) {
578 (radiusSquared - distanceSquared + 1) / denominator);
579 newCell.
temperature = std::int16_t(std::clamp<int>(
580 int(oldCell.
temperature) + radialHeat, -32768, 32767));
584 if (newCell == oldCell)
continue;
591 for (
const Candidate& candidate :
candidates) {
592 impl_->put(candidate.x, candidate.y, candidate.cell, impl_->tick);
593 impl_->wakeAround(candidate.x, candidate.y);
598 impl_->lastEditSequence = command.
sequence;
605 std::int16_t temperatureDelta) {
607 command.
sequence = impl_->lastEditSequence + 1;
614 return std::move(
applyEdit(command)).expect(
"PixelWorld::explode generated an invalid edit command");
625 if (
region.minX < -100'000'000 ||
region.maxX > 100'000'000 ||
626 region.minY < -100'000'000 ||
region.maxY > 100'000'000)
628 "fragment scan region is outside the supported coordinate range",
"region");
629 if (
width <= 0 || height <= 0 || width * height > 16'777'216)
631 "fragment scan region must be non-empty and contain at most 16777216 cells",
"region");
632 if (minimumCells == 0)
635 using Coord = std::pair<int, int>;
636 std::set<Coord> visited;
637 std::vector<PixelFragment> fragments;
638 constexpr std::array<Coord, 4> neighbors{{{0, -1}, {-1, 0}, {1, 0}, {0, 1}}};
639 const auto isSolid = [
this](
int x,
int y) {
645 if (!isSolid(
x,
y) || visited.contains({
x,
y}))
continue;
647 std::vector<Coord> component;
648 visited.emplace(
x,
y);
649 bool supported =
false;
650 int minX =
x, maxX =
x, minY =
y, maxY =
y;
654 component.emplace_back(
cx,
cy);
655 minX = std::min(minX,
cx);
656 maxX = std::max(maxX,
cx);
657 minY = std::min(minY,
cy);
658 maxY = std::max(maxY,
cy);
659 if (
cy >= supportY) supported =
true;
660 for (
const auto& [
dx,
dy] : neighbors) {
665 if (isSolid(
nx,
ny)) supported =
true;
668 if (isSolid(
nx,
ny) && visited.emplace(
nx,
ny).second)
672 if (supported || component.size() < minimumCells)
continue;
676 fragment.
id = impl_->nextFragmentId++;
679 fragment.
width = maxX - minX + 1;
680 fragment.
height = maxY - minY + 1;
682 fragment.
cells.resize(std::size_t(fragment.
width) * std::size_t(fragment.
height));
683 for (
const auto& [
cx,
cy] : component)
684 fragment.
cells[std::size_t(
cy - minY) * std::size_t(fragment.
width) + std::size_t(
cx - minX)] =
686 fragments.push_back(std::move(fragment));
689 if (!fragments.empty()) {
691 for (
int y = 0;
y < fragment.height; ++
y)
692 for (
int x = 0;
x < fragment.width; ++
x) {
693 const PixelCell&
cell = fragment.cells[std::size_t(
y) * std::size_t(fragment.width) +
x];
695 impl_->put(fragment.originX +
x, fragment.originY +
y, {}, impl_->tick);
696 impl_->wakeAround(fragment.originX +
x, fragment.originY +
y);
711 "fragment belongs to another world or an invalidated world epoch",
"source");
712 if (fragment.
id == 0 || fragment.
width <= 0 || fragment.
height <= 0 ||
713 std::uint64_t(fragment.
width) * std::uint64_t(fragment.
height) != fragment.
cells.size())
715 std::uint32_t cellsPlaced = 0;
716 for (
int y = 0;
y < fragment.
height; ++
y)
717 for (
int x = 0;
x < fragment.
width; ++
x) {
720 if (std::size_t(
cell.material) >= impl_->catalog.definitions().size())
722 const std::int64_t
wx = std::int64_t(originX) +
x,
wy = std::int64_t(originY) +
y;
723 if (
wx < std::numeric_limits<int>::min() ||
wx > std::numeric_limits<int>::max() ||
724 wy < std::numeric_limits<int>::min() ||
wy > std::numeric_limits<int>::max())
737 for (
int y = 0;
y < fragment.
height; ++
y)
738 for (
int x = 0;
x < fragment.
width; ++
x) {
741 impl_->put(originX +
x, originY +
y,
cell, impl_->tick);
742 impl_->wakeAround(originX +
x, originY +
y);
744 if (cellsPlaced != 0) ++impl_->revision;
752 impl_->chunks.clear();
753 impl_->removedChunks.clear();
756 impl_->lastEditSequence = 0;
762 return advanceImpl(
tick,
nullptr);
768 return advanceImpl(
tick, &scheduler);
773 if (
tick.value() <= impl_->tick)
776 "PixelWorld ticks must increase monotonically",
"tick", {},
"pixelworld"));
778 const auto stepStarted = std::chrono::steady_clock::now();
779 impl_->tick =
tick.value();
782 std::vector<ChunkCoord>
order;
783 order.reserve(impl_->chunks.size());
784 for (
auto& [coord, chunk] : impl_->chunks) {
785 if (chunk.active)
order.push_back(coord);
786 chunk.touched =
false;
790 struct ChunkPhaseSummary {
794 std::uint64_t materialMask = 0;
797 bool materialMaskOverflow =
false;
799 const auto summarize = [](
const Chunk& chunk) {
800 ChunkPhaseSummary summary;
801 summary.nonAir = chunk.nonAir;
802 summary.mobile = chunk.mobile;
803 summary.thermalRemainderCells = chunk.thermalRemainderCells;
804 summary.minimumTemperature = chunk.minimumTemperature;
805 summary.maximumTemperature = chunk.maximumTemperature;
806 summary.materialMaskOverflow = chunk.materialOverflow != 0;
808 if (chunk.materialCounts[
material] != 0)
809 summary.materialMask |= std::uint64_t(1) <<
material;
812 std::unordered_map<ChunkCoord, ChunkPhaseSummary, ChunkCoordHash> phaseSummaries;
813 const auto rebuildSummaries = [&] {
814 phaseSummaries.clear();
815 phaseSummaries.reserve(impl_->chunks.size());
816 for (
auto& [coord, chunk] : impl_->chunks) {
817 impl_->refreshTemperatureBounds(chunk);
818 phaseSummaries.emplace(coord, summarize(chunk));
823 struct MovementRows {
824 std::array<std::uint64_t, kPixelChunkSize>
mobile{};
825 std::array<std::uint64_t, kPixelChunkSize> rightFirst{};
827 std::vector<MovementRows> movementCandidates(
order.size());
828 std::vector<std::size_t> movementWork;
829 movementWork.reserve(
order.size());
831 const auto summary = phaseSummaries.find(
order[
index]);
832 if (summary != phaseSummaries.end() && summary->second.mobile != 0)
833 movementWork.push_back(
index);
835 const auto generateMovementCandidates = [&](std::size_t workIndex) {
836 const std::size_t orderIndex = movementWork[workIndex];
837 const ChunkCoord coord =
order[orderIndex];
838 auto&
candidates = movementCandidates[orderIndex];
841 const auto found = impl_->chunks.find(coord);
842 if (
found == impl_->chunks.end())
return;
843 const Chunk& chunk =
found->second;
846 const auto cellIndex = Chunk::index(lx, ly);
847 if (chunk.updated[cellIndex] ==
tick.value())
continue;
848 const PixelCell
cell = chunk.cells[cellIndex];
849 const auto state = impl_->materialState(
cell.material);
854 const std::uint64_t bit = std::uint64_t(1) << lx;
860 if (scheduler && movementWork.size() > 1) {
861 scheduler->
parallelFor(movementWork.size(), generateMovementCandidates);
862 stats.parallelTasks += std::uint32_t(movementWork.size());
865 generateMovementCandidates(
index);
867 for (std::size_t orderIndex = 0; orderIndex <
order.size(); ++orderIndex) {
868 ++
stats.chunksVisited;
869 const ChunkCoord sourceCoord =
order[orderIndex];
870 auto sourceFound = impl_->chunks.find(sourceCoord);
871 if (sourceFound == impl_->chunks.end())
continue;
872 Chunk& sourceChunk = sourceFound->second;
873 const MovementRows&
candidates = movementCandidates[orderIndex];
874 for (
int sourceLocalY =
kPixelChunkSize - 1; sourceLocalY >= 0; --sourceLocalY) {
875 std::uint64_t remaining =
candidates.mobile[std::size_t(sourceLocalY)];
876 const bool leftFirst = ((
tick.value() + std::uint64_t(sourceLocalY)) & 1U) == 0;
877 while (remaining != 0) {
878 const int sourceLocalX = leftFirst
879 ? int(std::countr_zero(remaining))
880 : 63 - int(
std::countl_zero(remaining));
881 const std::uint64_t candidateBit = std::uint64_t(1) << sourceLocalX;
882 remaining &= ~candidateBit;
884 (
candidates.rightFirst[std::size_t(sourceLocalY)] & candidateBit) != 0 ? 1 : -1;
885 const auto sourceIndex = Chunk::index(sourceLocalX, sourceLocalY);
886 if (sourceChunk.updated[sourceIndex] ==
tick.value())
continue;
887 const PixelCell
cell = sourceChunk.cells[sourceIndex];
888 const auto state = impl_->materialState(
cell.material);
890 ++
stats.cellsVisited;
891 const auto tryMove = [&](
int targetLocalX,
int targetLocalY) {
894 return impl_->moveOrSwapWithinChunk(
895 sourceCoord, sourceChunk, sourceLocalX, sourceLocalY,
cell,
896 targetLocalX, targetLocalY,
tick.value());
899 return impl_->moveOrSwapKnownSource(
904 bool moved = tryMove(sourceLocalX, sourceLocalY + 1);
906 moved = tryMove(sourceLocalX +
direction, sourceLocalY + 1);
908 moved = tryMove(sourceLocalX -
direction, sourceLocalY + 1);
910 moved = tryMove(sourceLocalX +
direction, sourceLocalY);
912 moved = tryMove(sourceLocalX -
direction, sourceLocalY);
915 stats.cellsChanged += 2;
921 if (
stats.cellsMoved != 0) rebuildSummaries();
926 struct ThermalChunkContributions {
927 std::array<std::int64_t, kPixelChunkSize * kPixelChunkSize>
local{};
928 std::array<std::int64_t, kPixelChunkSize> rightHalo{};
929 std::array<std::int64_t, kPixelChunkSize> bottomHalo{};
931 std::vector<ThermalChunkContributions> thermalCandidates(
order.size());
932 std::vector<std::uint32_t> transferCounts(
order.size());
933 std::vector<std::uint64_t> transferEnergy(
order.size());
934 const auto hasPossibleThermalGradient = [&](ChunkCoord coord) {
935 const auto ownSummary = phaseSummaries.find(coord);
936 if (ownSummary == phaseSummaries.end() || ownSummary->second.nonAir == 0)
return false;
937 const auto& own = ownSummary->second;
938 if (own.thermalRemainderCells != 0)
return true;
939 if (own.minimumTemperature != own.maximumTemperature)
return true;
940 for (
const auto& [
dx,
dy] :
941 std::array<
std::pair<int, int>, 4>{{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}}) {
942 const auto neighbor = phaseSummaries.find({coord.x +
dx, coord.y +
dy});
943 if (
neighbor == phaseSummaries.end() ||
neighbor->second.nonAir == 0)
continue;
944 if (
neighbor->second.minimumTemperature != own.minimumTemperature ||
945 neighbor->second.maximumTemperature != own.maximumTemperature)
950 std::vector<std::size_t> thermalWork;
951 thermalWork.reserve(
order.size());
953 if (hasPossibleThermalGradient(
order[
index])) thermalWork.push_back(
index);
954 const auto& readOnlyChunks = impl_->chunks;
955 const auto calculateThermalChunk = [&](std::size_t workIndex) {
956 const std::size_t orderIndex = thermalWork[workIndex];
957 const ChunkCoord coord =
order[orderIndex];
958 const auto ownFound = readOnlyChunks.find(coord);
959 if (ownFound == readOnlyChunks.end())
return;
960 const Chunk& ownChunk = ownFound->second;
961 const auto rightFound = readOnlyChunks.find({coord.x + 1, coord.y});
962 const auto bottomFound = readOnlyChunks.find({coord.x, coord.y + 1});
963 const Chunk* rightChunk = rightFound == readOnlyChunks.end() ? nullptr : &rightFound->second;
964 const Chunk* bottomChunk = bottomFound == readOnlyChunks.end() ? nullptr : &bottomFound->second;
965 auto&
candidates = thermalCandidates[orderIndex];
966 transferCounts[orderIndex] = 0;
967 transferEnergy[orderIndex] = 0;
970 const PixelCell
source = ownChunk.cells[Chunk::index(lx, ly)];
972 for (
const auto& [
ox,
oy] :
std::array<
std::pair<int, int>, 2>{{{1, 0}, {0, 1}}}) {
975 if (rightChunk ==
nullptr)
continue;
976 target = rightChunk->cells[Chunk::index(0, ly)];
978 if (bottomChunk ==
nullptr)
continue;
979 target = bottomChunk->cells[Chunk::index(lx, 0)];
981 target = ownChunk.cells[Chunk::index(lx +
ox, ly +
oy)];
984 const int conductivity = std::min<int>(
985 impl_->thermalConductivity(
source.material),
986 impl_->thermalConductivity(
target.material));
987 if (conductivity == 0)
continue;
988 const std::int64_t sourceCapacity = impl_->heatCapacity(
source.material);
989 const std::int64_t targetCapacity = impl_->heatCapacity(
target.material);
990 const std::int64_t sourceEnergy =
991 std::int64_t(
source.temperature) * sourceCapacity +
source.thermalRemainder;
992 const std::int64_t targetEnergy =
993 std::int64_t(
target.temperature) * targetCapacity +
target.thermalRemainder;
994 const std::int64_t equilibriumTransfer =
995 (targetEnergy * sourceCapacity - sourceEnergy * targetCapacity) /
996 (sourceCapacity + targetCapacity);
997 if (equilibriumTransfer == 0)
continue;
998 std::int64_t transfer = equilibriumTransfer * conductivity / 255;
999 if (transfer == 0) transfer = equilibriumTransfer < 0 ? -1 : 1;
1000 const std::size_t sourceIndex = Chunk::index(lx, ly);
1003 candidates.rightHalo[std::size_t(ly)] -= transfer;
1005 candidates.bottomHalo[std::size_t(lx)] -= transfer;
1008 ++transferCounts[orderIndex];
1009 transferEnergy[orderIndex] += std::uint64_t(transfer < 0 ? -transfer : transfer);
1013 if (scheduler && thermalWork.size() > 1) {
1014 scheduler->
parallelFor(thermalWork.size(), calculateThermalChunk);
1015 stats.parallelTasks += std::uint32_t(thermalWork.size());
1019 using ThermalDeltaChunk = std::array<std::int64_t, kPixelChunkSize * kPixelChunkSize>;
1020 std::unordered_map<ChunkCoord, ThermalDeltaChunk, ChunkCoordHash> thermalEnergyDeltas;
1021 thermalEnergyDeltas.reserve(
order.size());
1022 for (std::size_t
index = 0;
index < thermalCandidates.size(); ++
index) {
1023 stats.temperatureTransfers += transferCounts[
index];
1024 stats.thermalEnergyTransferred += transferEnergy[
index];
1026 const ThermalChunkContributions& contributions = thermalCandidates[
index];
1027 auto& localDeltas = thermalEnergyDeltas[coord];
1028 for (std::size_t cellIndex = 0; cellIndex < contributions.local.size(); ++cellIndex)
1029 localDeltas[cellIndex] += contributions.local[cellIndex];
1030 auto& rightDeltas = thermalEnergyDeltas[{coord.x + 1, coord.y}];
1031 auto& bottomDeltas = thermalEnergyDeltas[{coord.x, coord.y + 1}];
1033 rightDeltas[Chunk::index(0,
int(
offset))] += contributions.rightHalo[
offset];
1034 bottomDeltas[Chunk::index(
int(
offset), 0)] += contributions.bottomHalo[
offset];
1037 std::vector<ChunkCoord> thermalChunkOrder;
1038 thermalChunkOrder.reserve(thermalEnergyDeltas.size());
1039 for (
const auto& [coord, deltas] : thermalEnergyDeltas) {
1041 thermalChunkOrder.push_back(coord);
1043 std::sort(thermalChunkOrder.begin(), thermalChunkOrder.end());
1044 struct ThermalCommitStats {
1045 std::uint32_t cellsChanged = 0;
1046 std::uint64_t energyClamped = 0;
1048 std::vector<Chunk*> thermalCommitChunks;
1049 std::vector<const ThermalDeltaChunk*> thermalCommitDeltas;
1050 thermalCommitChunks.reserve(thermalChunkOrder.size());
1051 thermalCommitDeltas.reserve(thermalChunkOrder.size());
1052 for (
const ChunkCoord coord : thermalChunkOrder) {
1053 auto chunkFound = impl_->chunks.find(coord);
1054 if (chunkFound == impl_->chunks.end())
continue;
1055 thermalCommitChunks.push_back(&chunkFound->second);
1056 thermalCommitDeltas.push_back(&thermalEnergyDeltas.at(coord));
1058 std::vector<ThermalCommitStats> thermalCommitStats(thermalCommitChunks.size());
1059 const auto commitThermalChunk = [&](std::size_t
index) {
1060 Chunk& chunk = *thermalCommitChunks[
index];
1061 const ThermalDeltaChunk& deltas = *thermalCommitDeltas[
index];
1062 ThermalCommitStats& commitStats = thermalCommitStats[
index];
1065 const std::size_t cellIndex = Chunk::index(localX, localY);
1066 const std::int64_t energyDelta = deltas[cellIndex];
1067 if (energyDelta == 0)
continue;
1068 PixelCell
cell = chunk.cells[cellIndex];
1070 impl_->catalog.definition(
cell.material).heatCapacity;
1071 const std::int64_t beforeEnergy =
1073 const std::int64_t requestedEnergy = beforeEnergy + energyDelta;
1075 std::int64_t remainder = requestedEnergy %
capacity;
1076 if (remainder < 0) {
1080 if (
temperature < std::numeric_limits<std::int16_t>::min()) {
1081 temperature = std::numeric_limits<std::int16_t>::min();
1083 }
else if (
temperature > std::numeric_limits<std::int16_t>::max()) {
1084 temperature = std::numeric_limits<std::int16_t>::max();
1088 cell.thermalRemainder = std::uint16_t(remainder);
1089 const std::int64_t appliedEnergy =
1091 if (appliedEnergy != requestedEnergy)
1092 commitStats.energyClamped += std::uint64_t(
1093 appliedEnergy > requestedEnergy ? appliedEnergy - requestedEnergy
1094 : requestedEnergy - appliedEnergy);
1095 if (appliedEnergy == beforeEnergy)
continue;
1096 impl_->putNormalizedWithinChunk(chunk, cellIndex,
cell,
tick.value(),
false);
1097 ++commitStats.cellsChanged;
1100 if (scheduler && thermalCommitChunks.size() > 1) {
1101 scheduler->
parallelFor(thermalCommitChunks.size(), commitThermalChunk);
1102 stats.parallelTasks += std::uint32_t(thermalCommitChunks.size());
1104 for (std::size_t
index = 0;
index < thermalCommitChunks.size(); ++
index)
1105 commitThermalChunk(
index);
1107 for (
const ThermalCommitStats& commitStats : thermalCommitStats) {
1108 stats.cellsChanged += commitStats.cellsChanged;
1109 stats.thermalEnergyClamped += commitStats.energyClamped;
1113 for (
const ChunkCoord coord :
order) {
1114 if (impl_->chunks.find(coord) == impl_->chunks.end())
continue;
1115 const auto summary = phaseSummaries.find(coord);
1116 if (summary != phaseSummaries.end() && !summary->second.materialMaskOverflow) {
1117 bool mayTransition =
false;
1118 for (
const auto& rule : impl_->catalog.phaseRules()) {
1119 const auto material = std::size_t(rule.source);
1121 (summary->second.materialMask & (std::uint64_t(1) <<
material)) == 0)
1123 const bool temperatureMayMatch =
1125 ? summary->second.maximumTemperature >= rule.threshold
1126 : summary->second.minimumTemperature <= rule.threshold;
1127 if (temperatureMayMatch) {
1128 mayTransition =
true;
1132 if (!mayTransition)
continue;
1138 PixelCell
cell = impl_->get(
x,
y);
1141 for (
const auto& rule : impl_->catalog.phaseRules()) {
1142 if (rule.source !=
cell.material)
continue;
1144 ?
cell.temperature >= rule.threshold
1145 :
cell.temperature <= rule.threshold;
1146 if (!matches)
continue;
1147 cell.material = rule.result;
1148 cell.temperature = std::int16_t(std::clamp<int>(
1149 int(
cell.temperature) + rule.temperatureDelta, -32768, 32767));
1150 cell.lifetime = std::uint8_t(std::min<std::uint16_t>(
1151 impl_->catalog.definition(
cell.material).defaultLifetime,
1152 std::numeric_limits<std::uint8_t>::max()));
1154 ++
stats.phaseChanges;
1155 ++
stats.cellsChanged;
1161 if (
stats.phaseChanges != 0) rebuildSummaries();
1163 std::uint64_t worldMaterialMask = 0;
1164 bool worldMaterialMaskOverflow =
false;
1165 for (
const auto& [coord, summary] : phaseSummaries) {
1167 worldMaterialMask |= summary.materialMask;
1168 worldMaterialMaskOverflow = worldMaterialMaskOverflow || summary.materialMaskOverflow;
1170 bool worldCanReact = worldMaterialMaskOverflow;
1172 for (
const auto& rule : impl_->catalog.
reactions()) {
1173 const auto first = std::size_t(rule.first),
second = std::size_t(rule.second);
1175 ((worldMaterialMask & (std::uint64_t(1) <<
first)) != 0 &&
1176 (worldMaterialMask & (std::uint64_t(1) <<
second)) != 0)) {
1177 worldCanReact =
true;
1182 for (
auto it =
order.rbegin(); it !=
order.rend(); ++it) {
1183 const ChunkCoord coord = *it;
1184 auto sourceFound = impl_->chunks.find(coord);
1185 if (sourceFound == impl_->chunks.end())
continue;
1186 Chunk* sourceChunk = &sourceFound->second;
1187 const auto summary = phaseSummaries.find(coord);
1188 if (summary != phaseSummaries.end() && !summary->second.materialMaskOverflow) {
1189 bool requiresScan = worldCanReact;
1190 if (!requiresScan) {
1192 if ((summary->second.materialMask & (std::uint64_t(1) <<
material)) == 0)
continue;
1195 requiresScan =
true;
1200 if (!requiresScan)
continue;
1206 const std::size_t sourceIndex = Chunk::index(lx, ly);
1207 if (sourceChunk->updated[sourceIndex] ==
tick.value())
continue;
1208 PixelCell
cell = sourceChunk->cells[sourceIndex];
1210 ++
stats.cellsVisited;
1211 bool reacted =
false;
1212 if (impl_->catalog.canReact(
cell.material))
1213 for (
const auto& [
ox,
oy] :
1214 std::array<
std::pair<int, int>, 4>{{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}}) {
1215 const int neighborLocalX = lx +
ox;
1216 const int neighborLocalY = ly +
oy;
1217 const bool sameChunk = neighborLocalX >= 0 &&
1219 neighborLocalY >= 0 &&
1221 const std::size_t neighborIndex =
1222 sameChunk ? Chunk::index(neighborLocalX, neighborLocalY) : 0;
1223 PixelCell
neighbor = sameChunk ? sourceChunk->cells[neighborIndex]
1224 : impl_->get(
x +
ox,
y +
oy);
1225 for (
const std::uint16_t ruleIndex :
1227 const auto& rule = impl_->catalog.reactions()[ruleIndex];
1228 const bool direct = rule.first ==
cell.material && rule.second ==
neighbor.material;
1229 const bool reverse = rule.second ==
cell.material && rule.first ==
neighbor.material;
1230 if ((!direct && !reverse) ||
1231 std::max(
cell.temperature,
neighbor.temperature) < rule.minimumTemperature)
1233 cell.material = direct ? rule.firstResult : rule.secondResult;
1234 neighbor.material = direct ? rule.secondResult : rule.firstResult;
1235 cell.temperature = std::int16_t(std::clamp<int>(
int(
cell.temperature) + rule.heatDelta,
1237 neighbor.temperature = std::int16_t(std::clamp<int>(
1238 int(
neighbor.temperature) + rule.heatDelta, -32768, 32767));
1239 if (
cell.lifetime == 0)
1240 cell.lifetime = std::uint8_t(std::min<std::uint16_t>(
1241 impl_->catalog.definition(
cell.material).defaultLifetime,
1242 std::numeric_limits<std::uint8_t>::max()));
1244 neighbor.lifetime = std::uint8_t(std::min<std::uint16_t>(
1245 impl_->catalog.definition(
neighbor.material).defaultLifetime,
1246 std::numeric_limits<std::uint8_t>::max()));
1248 impl_->putWithinChunk(*sourceChunk, neighborIndex,
neighbor,
1254 sourceFound = impl_->chunks.find(coord);
1255 if (sourceFound == impl_->chunks.end())
break;
1256 sourceChunk = &sourceFound->second;
1259 ++
stats.cellsChanged;
1263 if (reacted) ++
stats.reactions;
1264 const auto state = impl_->catalog.definition(
cell.material).state;
1266 impl_->putWithinChunk(*sourceChunk, sourceIndex,
cell,
tick.value());
1268 if (
cell.lifetime > 0) {
1270 ++
stats.cellsChanged;
1276 bool moved = impl_->moveOrSwap(
x,
y,
x,
y - 1,
tick.value());
1277 if (!moved) moved = impl_->moveOrSwap(
x,
y,
x +
direction,
y - 1,
tick.value());
1280 stats.cellsChanged += 2;
1282 sourceFound = impl_->chunks.find(coord);
1283 if (sourceFound == impl_->chunks.end())
break;
1284 sourceChunk = &sourceFound->second;
1289 std::vector<ChunkCoord> reclaimed;
1290 for (
auto& [coord, chunk] : impl_->chunks) {
1291 if (chunk.touched) {
1292 chunk.idleTicks = 0;
1293 chunk.active =
true;
1298 if (!chunk.active && chunk.nonAir == 0)
1299 reclaimed.push_back(coord);
1301 for (
const ChunkCoord coord : reclaimed) {
1302 impl_->chunks.erase(coord);
1303 impl_->removedChunks[coord] = impl_->revision + 1;
1304 ++
stats.chunksReclaimed;
1306 if (
stats.cellsChanged != 0 ||
stats.chunksReclaimed != 0) ++impl_->revision;
1307 const auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(
1308 std::chrono::steady_clock::now() - stepStarted)
1316 return std::move(
result).expect(
"PixelWorld::step generated an invalid tick");
1328 return int(std::count_if(impl_->chunks.begin(), impl_->chunks.end(), [](
const auto& entry) {
1329 return entry.second.active;
1335 std::vector<ChunkCoord>
order;
1336 order.reserve(impl_->chunks.size());
1337 for (
const auto& [coord, chunk] : impl_->chunks)
1338 if (chunk.revision > sinceRevision)
order.push_back(coord);
1339 for (
const auto& [coord,
revision] : impl_->removedChunks)
1343 std::vector<PixelChunkSnapshot> snapshots;
1344 snapshots.reserve(
order.size());
1345 for (
const ChunkCoord coord :
order) {
1349 const auto chunk = impl_->chunks.find(coord);
1350 if (chunk != impl_->chunks.end()) {
1351 snapshot.revision = chunk->second.revision;
1352 snapshot.cells.assign(chunk->second.cells.begin(), chunk->second.cells.end());
1354 snapshot.revision = impl_->removedChunks.at(coord);
1357 snapshots.push_back(std::move(
snapshot));
1367 "pixelworld.chunk-region"));
1368 const std::uint64_t
width = std::uint64_t(std::int64_t(
region.maxX) -
region.minX) + 1;
1369 const std::uint64_t
height = std::uint64_t(std::int64_t(
region.maxY) -
region.minY) + 1;
1373 "pixelworld.chunk-region"));
1375 std::vector<PixelChunkSnapshot>
result;
1378 const ChunkCoord coord{
x,
y};
1379 const auto present = impl_->chunks.find(coord);
1380 if (
present != impl_->chunks.end() &&
present->second.revision > sinceRevision) {
1388 const auto removed = impl_->removedChunks.find(coord);
1389 if (
removed != impl_->removedChunks.end() &&
removed->second > sinceRevision)
1404 "pixelworld.chunk-diagnostics"));
1405 const std::uint64_t
width = std::uint64_t(std::int64_t(
region.maxX) -
region.minX) + 1;
1406 const std::uint64_t
height = std::uint64_t(std::int64_t(
region.maxY) -
region.minY) + 1;
1410 "pixelworld.chunk-diagnostics"));
1411 std::vector<PixelChunkDiagnostic>
result;
1414 const auto found = impl_->chunks.find({
x,
y});
1415 if (
found != impl_->chunks.end()) {
1416 const Chunk& chunk =
found->second;
1418 20, 20, chunk.idleTicks, chunk.active};
1419 if (chunk.nonAir != 0) {
1420 diagnostic.minimumTemperature = 32767;
1421 diagnostic.maximumTemperature = -32768;
1423 if (
cell.material == MaterialId::Air)
continue;
1424 diagnostic.minimumTemperature = std::min(diagnostic.minimumTemperature,
1426 diagnostic.maximumTemperature = std::max(diagnostic.maximumTemperature,
1430 result.push_back(diagnostic);
1445 if (impl_->revision != expectedRevision)
1449 "catalogFingerprint");
1457 if (batch.
chunks.size() > 1'000'000U)
1460 std::optional<ChunkCoord>
previous;
1466 "Chunk batch must be unique canonical y/x order",
"chunks");
1470 "Chunk revision must be positive and no newer than source",
"chunks.revision");
1474 "removed Chunk must not contain cells",
"chunks.cells");
1479 "present Chunk must contain exactly 64x64 cells",
"chunks.cells");
1481 if (std::size_t(
cell.material) >= impl_->catalog.definitions().size())
1483 "Chunk references an unknown material",
"chunks.cells.material");
1484 const auto capacity = impl_->catalog.definition(
cell.material).heatCapacity;
1485 if ((
cell.material == MaterialId::Air &&
cell.thermalRemainder != 0) ||
1488 "Chunk contains a non-canonical thermal remainder",
1489 "chunks.cells.thermalRemainder");
1496 candidate.
worldId = impl_->worldId;
1497 candidate.
epoch = impl_->epoch;
1499 candidate.
paused = impl_->paused;
1506 candidate.
chunks.erase(coord);
1512 std::copy(
snapshot.cells.begin(),
snapshot.cells.end(), chunk.cells.begin());
1513 chunk.revision =
snapshot.revision;
1514 chunk.active =
true;
1515 chunk.touched =
true;
1516 chunk.idleTicks = 0;
1518 candidate.
chunks.insert_or_assign(coord, std::move(chunk));
1528 *impl_ = std::move(candidate);
1533 std::vector<ChunkCoord>
order;
1534 order.reserve(impl_->chunks.size());
1535 for (
const auto& [coord, chunk] : impl_->chunks) {
1537 order.push_back(coord);
1540 std::vector<std::byte>
out;
1541 out.insert(
out.end(), {std::byte{0x45}, std::byte{0x56}, std::byte{0x50}, std::byte{0x57}});
1542 append<std::uint16_t>(
out, 4);
1543 append(
out, impl_->catalog.fingerprint());
1544 append(
out, impl_->seed);
1545 append(
out, impl_->revision);
1546 append(
out, impl_->tick);
1547 append(
out, impl_->lastEditSequence);
1548 append<std::uint32_t>(
out, std::uint32_t(
order.size()));
1549 for (
const ChunkCoord coord :
order) {
1550 append<std::int32_t>(
out, coord.x);
1551 append<std::int32_t>(
out, coord.y);
1552 const Chunk& chunk = impl_->chunks.at(coord);
1554 append<std::uint16_t>(
out, std::uint16_t(
cell.material));
1555 append(
out,
cell.temperature);
1557 append(
out,
cell.thermalRemainder);
1565 if (
bytes.size() < 4 ||
bytes[0] != std::byte{0x45} ||
bytes[1] != std::byte{0x56} ||
1566 bytes[2] != std::byte{0x50} ||
bytes[3] != std::byte{0x57})
1570 Impl candidate(impl_->catalog);
1571 std::uint32_t
count = 0;
1579 }
else if (impl_->catalog.fingerprint() != MaterialCatalog::builtIn().fingerprint()) {
1589 for (std::uint32_t i = 0; i <
count; ++i) {
1603 if ((
cell.material == MaterialId::Air &&
cell.thermalRemainder != 0) ||
1607 const auto [ignored, inserted] = candidate.
chunks.emplace(coord, std::move(chunk));
1612 for (
auto& [coord, chunk] : candidate.
chunks) {
1615 chunk.revision = candidate.
revision;
1617 candidate.
worldId = impl_->worldId;
1618 candidate.
epoch = impl_->epoch + 1;
1620 candidate.
paused = impl_->paused;
1621 *impl_ = std::move(candidate);
std::vector< QuestEvent > pending
std::function< Numbers(b3JointId)> read
std::shared_ptr< const OceanSprayFrame > previous
std::array< uint32_t, 16 > material
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
std::int16_t maximumTemperature
std::array< std::uint16_t, 64 > materialCounts
std::uint32_t materialOverflow
bool temperatureBoundsDirty
std::int16_t minimumTemperature
std::uint32_t thermalRemainderCells
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::vector< EquipmentStat > stats
RoadLaneDirection direction
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Structured operation status used by the common Result foundation.
Battle::Reactions reactions
std::vector< char > inside
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
void expect(std::string_view message) const
Require success for a void operation.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
Structured status and zero or more diagnostics for an operation.
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
Owning immutable material and reaction table used by one PixelWorld.
const MaterialDefinition & definition(MaterialId id) const noexcept
Resolve a validated id; invalid ids safely project to air.
static MaterialCatalog builtIn()
Construct the engine's canonical built-in catalog.
std::span< const MaterialReactionRule > reactions() const noexcept
Borrow immutable canonical-priority reaction rules.
std::span< const MaterialDefinition > definitions() const noexcept
Borrow immutable definitions until this catalog is destroyed.
std::uint64_t fingerprint() const noexcept
Stable deterministic fingerprint included in world snapshots.
Synchronous executor for owning PixelWorld candidate buffers.
virtual void parallelFor(std::size_t workItems, const std::function< void(std::size_t)> &body)=0
Execute every index in [0, workItems) exactly once and synchronously join.
Sparse, chunked, deterministic 2D falling-material world.
int activeChunkCount() const noexcept
Active chunk count.
std::uint64_t lastEditSequence() const noexcept
Last edit sequence.
eve::Result< PixelEditReceipt > applyEdit(const PixelEditCommand &command)
Validate and atomically apply one strictly sequenced edit command.
std::uint64_t materialCatalogFingerprint() const noexcept
Fingerprint of the immutable catalog that gives cell ids their meaning.
void setMaterial(int x, int y, std::string_view material)
Set one cell from a stable built-in material name.
eve::Result< PixelCatalogReloadReceipt > reloadMaterialCatalog(MaterialCatalog catalog, std::uint64_t expectedFingerprint)
Transactionally hot-reload a compatible Catalog while paused.
eve::Result< void > setMaterialChecked(int x, int y, std::string_view material)
Canonical checked name-based setter; unknown names leave the world unchanged.
PixelEditReceipt explode(int centerX, int centerY, int radius, int strength, std::int16_t temperatureDelta)
Script/demo explosion facade that emits the next command sequence.
std::size_t paintCircle(int centerX, int centerY, int radius, std::string_view material)
Paint a filled material circle and return the number of changed cells.
eve::Result< std::size_t > paintCircleChecked(int centerX, int centerY, int radius, std::string_view material)
Canonical checked circle edit; unknown names leave the world unchanged.
~PixelWorld()
Pixel world.
eve::Result< std::vector< PixelChunkSnapshot > > snapshotChunksInRegion(PixelChunkRegion region, std::uint64_t sinceRevision=0) const
Copy present Chunks and retained tombstones in one finite Chunk-coordinate region.
std::uint64_t seed() const noexcept
Seed.
std::uint64_t tickValue() const noexcept
Tick value.
void setCell(int x, int y, PixelCell cell)
Set one cell and wake its chunk and neighbors. Air never allocates a missing chunk.
PixelWorld & operator=(PixelWorld &&) noexcept
Operator =.
eve::Result< PixelFragmentRasterReceipt > rasterizeFragment(const PixelFragment &fragment, int originX, int originY)
Transactionally rasterize a detached fragment at a new world-space origin.
StepStats step()
Script/demo facade that advances the next integral tick.
bool isPaused() const noexcept
Whether ordinary simulation entry points are currently paused.
std::uint32_t materialDisplayRgba(MaterialId material) const noexcept
Query the Catalog-owned preview/render color encoded as 0xRRGGBBAA.
PixelWorldLink worldLink() const noexcept
Current runtime link used for stale fragment detection.
int chunkCount() const noexcept
Chunk count.
bool isSolidMaterial(MaterialId material) const noexcept
Query whether a validated material id participates in structural solid collision.
PixelWorld(std::uint64_t seed=1)
Construct an empty world with an explicit deterministic seed.
eve::Result< StepStats > advance(eve::SimulationTick tick)
Advance exactly one scheduler-owned tick.
int getMaterial(int x, int y) const noexcept
Convenience query returning the numeric material id.
eve::Result< std::vector< PixelFragment > > extractUnsupportedFragments(PixelRegion region, int supportY, std::uint32_t minimumCells=1)
Atomically detach unsupported solid components inside a finite region.
PixelCell getCell(int x, int y) const noexcept
Return the cell at world coordinates; absent chunks read as air.
std::uint64_t revision() const noexcept
Revision.
eve::Result< StepStats > advanceScheduled(eve::SimulationTick tick, PixelWorkScheduler &scheduler)
Advance one deterministic tick using a synchronous candidate scheduler.
void clear() noexcept
Remove all chunks and reset the simulation tick.
void setPaused(bool paused) noexcept
Pause or resume ordinary simulation entry points without changing state.
std::vector< PixelChunkSnapshot > snapshotChangedChunks(std::uint64_t sinceRevision) const
Copy chunks changed after sinceRevision in canonical y/x order.
PixelWorldControlService & pixelWorldControlService()
Process-lifetime PixelWorld tooling registry.
MaterialId
Compact stable material identifier stored in each authoritative cell.
constexpr std::uint8_t kPixelSleepHysteresisTicks
MaterialState
Broad movement class for one pixel material.
constexpr int kPixelChunkSize
DiagnosticCode
Stable machine-readable diagnostic codes.
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
std::uint16_t heatCapacity
Receipt for one transactional compatible material Catalog hot reload.
std::uint64_t fingerprintBefore
bool replayHistoryInvalidated
std::uint64_t revisionAfter
std::uint64_t revisionBefore
std::uint64_t fingerprintAfter
std::uint32_t chunksRebuilt
Compact authoritative state for one simulated world pixel.
std::uint16_t thermalRemainder
Canonical sub-degree thermal energy in [0, material heatCapacity).
Receipt for one all-or-nothing authoritative Chunk batch application.
std::uint64_t revisionBefore
std::uint64_t revisionAfter
std::uint32_t chunksRemoved
std::uint32_t chunksReplaced
Owning authoritative Chunk correction with source world metadata.
std::uint64_t sourceRevision
bool fullResync
Replace the replica projection instead of applying an incremental correction.
std::vector< PixelChunkSnapshot > chunks
std::uint64_t catalogFingerprint
eve::SimulationTick sourceTick
std::uint64_t sourceLastEditSequence
Read-only per-Chunk simulation diagnostics for tooling and overlays.
Inclusive finite rectangle expressed in Chunk coordinates.
Owning, immutable projection of one authoritative simulation chunk.
Owning replayable edit command. Sequence must be exactly previous + 1.
std::int16_t temperatureDelta
Deterministic receipt for one atomically accepted edit command.
std::uint64_t revisionAfter
std::uint32_t cellsChanged
std::uint32_t cellsHeated
std::uint64_t revisionBefore
std::uint32_t cellsRemoved
Receipt for one all-or-nothing fragment rasterization.
std::uint32_t cellsPlaced
std::uint64_t revisionAfter
std::uint64_t revisionBefore
Owning material bitmap detached atomically from a PixelWorld.
std::vector< PixelCell > cells
std::uint32_t solidCellCount
Finite inclusive world-space rectangle used by structural queries.
Runtime identity of the world epoch from which a fragment was detached.
MaterialState materialState(MaterialId material) const noexcept
Chunk & ensureChunk(int x, int y)
bool pseudoBit(int x, int y, std::uint64_t currentTick) const noexcept
std::vector< std::uint16_t > heatCapacities
void putWithinChunk(Chunk &chunk, std::size_t index, PixelCell cell, std::uint64_t updatedTick, bool markUpdated=true)
bool isMobile(MaterialId material) const noexcept
void wakeAround(int x, int y)
std::uint8_t thermalConductivity(MaterialId material) const noexcept
void refreshTemperatureBounds(Chunk &chunk) const noexcept
Chunk * findChunk(int x, int y) noexcept
std::vector< std::vector< std::uint16_t > > reactionRulesByPair
const Chunk * findChunk(int x, int y) const noexcept
void put(int x, int y, PixelCell cell, std::uint64_t updatedTick, bool markUpdated=true)
std::vector< std::uint8_t > canDisplaceTable
std::uint16_t heatCapacity(MaterialId material) const noexcept
std::vector< std::uint8_t > thermalConductivities
void rebuildMaterialRuntimeTables()
std::uint64_t nextFragmentId
std::span< const std::uint16_t > reactionRules(MaterialId source, MaterialId target) const noexcept
void addActivity(Chunk &chunk, const PixelCell &cell) const noexcept
std::unordered_map< ChunkCoord, std::uint64_t, ChunkCoordHash > removedChunks
std::size_t materialRuntimeCount
Impl(MaterialCatalog ownedCatalog=MaterialCatalog::builtIn())
std::uint64_t updatedAt(int x, int y) const noexcept
std::unordered_map< ChunkCoord, Chunk, ChunkCoordHash > chunks
std::vector< MaterialState > materialStates
void putNormalizedWithinChunk(Chunk &chunk, std::size_t index, const PixelCell &cell, std::uint64_t updatedTick, bool markUpdated=true)
bool moveOrSwap(int x, int y, int tx, int ty, std::uint64_t currentTick)
PixelCell normalizeCell(PixelCell cell) const noexcept
bool canDisplace(MaterialId source, MaterialId target) const noexcept
PixelCell get(int x, int y) const noexcept
void rebuildActivity(Chunk &chunk) const noexcept
bool moveOrSwapWithinChunk(ChunkCoord coord, Chunk &chunk, int sourceX, int sourceY, PixelCell source, int targetX, int targetY, std::uint64_t currentTick)
bool moveOrSwapKnownSource(int x, int y, PixelCell source, int tx, int ty, std::uint64_t currentTick)
std::uint64_t lastEditSequence
void removeActivity(Chunk &chunk, const PixelCell &cell) const noexcept
Counters produced by one deterministic simulation step.