15bool rasterValid(
const Heightmap& map,
bool normalized) {
16 if (map.getWidth() < 1 || map.getHeight() < 1 || map.getWidth() > 4096 || map.getHeight() > 4096 ||
17 map.data().size() !=
static_cast<std::size_t
>(map.getWidth()) * map.getHeight())
19 for (
float v : map.data())
20 if (!
std::isfinite(
v) || (normalized && (
v < 0.f ||
v > 1.f))) return false;
23std::size_t storage(
const std::vector<RoadTerrainTile>&
tiles) {
24 std::size_t
count = 0;
25 for (
const auto& tile :
tiles) {
26 count += tile.heights.data().size() + tile.holes.data().size() + tile.trees.size() * 8u;
36 const RoadTerrainWriteOptions&
options, std::size_t& work) {
38 std::vector<bool> protectedCells(
static_cast<std::size_t
>(
width) *
height,
false);
39 const float dx = tile.sizeX /
static_cast<float>(std::max(1,
width - 1)),
40 dz = tile.sizeZ /
static_cast<float>(std::max(1,
height - 1));
41 for (
int t = 0;
t <
mesh.getIndexCount() / 3; ++
t) {
43 if (
group !=
"asphalt" &&
group !=
"asphalt.bridge" &&
group !=
"asphalt.tunnel" &&
44 group !=
"asphalt.tunnel.portal")
46 const int a =
mesh.getIndex(
t * 3),
b =
mesh.getIndex(
t * 3 + 1),
c =
mesh.getIndex(
t * 3 + 2);
47 const float ax =
mesh.getPositionX(
a), az =
mesh.getPositionZ(
a), bx =
mesh.getPositionX(
b),
49 const float denominator = (bz - cz) * (ax -
cx) + (
cx - bx) * (az - cz);
50 if (std::fabs(denominator) < 1e-7f)
continue;
51 const float minX = std::clamp((std::min({ax, bx,
cx}) - tile.originX) /
dx, 0.f,
static_cast<float>(
width - 1));
52 const float maxX = std::clamp((std::max({ax, bx,
cx}) - tile.originX) /
dx, 0.f,
static_cast<float>(
width - 1));
54 std::clamp((std::min({az, bz, cz}) - tile.originZ) /
dz, 0.f,
static_cast<float>(
height - 1));
56 std::clamp((std::max({az, bz, cz}) - tile.originZ) /
dz, 0.f,
static_cast<float>(
height - 1));
57 for (
int z =
static_cast<int>(std::floor(minZ)); z <= static_cast<int>(std::ceil(maxZ)); ++
z)
58 for (
int x =
static_cast<int>(std::floor(minX)); x <= static_cast<int>(std::ceil(maxX)); ++
x) {
59 if (++work >
options.maximumWork)
return invalid<Coverage>(
"channel rasterization exceeds work budget");
60 const float tx =
width == 1 ? .5f :
static_cast<float>(
x) /
static_cast<float>(
width - 1);
61 const float tz =
height == 1 ? .5f :
static_cast<float>(
z) /
static_cast<float>(
height - 1);
62 const float wx = tile.originX + tx * tile.sizeX,
wz = tile.originZ + tz * tile.sizeZ;
63 const float u = ((bz - cz) * (
wx -
cx) + (
cx - bx) * (
wz - cz)) / denominator;
64 const float v = ((cz - az) * (
wx -
cx) + (ax -
cx) * (
wz - cz)) / denominator,
w = 1.f -
u -
v;
67 const bool portal =
group ==
"asphalt.tunnel.portal";
68 const float tu = portal ? .002f * std::hypot(bx -
cx, bz - cz) / std::fabs(denominator) : 1e-4f;
69 const float tv = portal ? .002f * std::hypot(
cx - ax, cz - az) / std::fabs(denominator) : 1e-4f;
70 const float tw = portal ? .002f * std::hypot(ax - bx, az - bz) / std::fabs(denominator) : 1e-4f;
71 if (
u < -tu ||
v < -tv ||
w < -tw)
continue;
72 const auto index =
static_cast<std::size_t
>(
z) *
width +
x;
73 if (
group ==
"asphalt.tunnel" ||
group ==
"asphalt.tunnel.portal") {
74 if (!
options.tunnelHolesAtPortalsOnly ||
group ==
"asphalt.tunnel.portal")
76 protectedCells[
index] =
true;
77 }
else if (
group ==
"asphalt.bridge")
78 protectedCells[
index] =
true;
80 const float roadY =
u *
mesh.getPositionY(
a) +
v *
mesh.getPositionY(
b) +
w *
mesh.getPositionY(
c);
81 const float terrainY =
82 tile.originY + tile.heights.sampleBilinear(tx * (tile.heights.getWidth() - 1),
83 tz * (tile.heights.getHeight() - 1)) *
85 if (std::fabs(roadY - terrainY) <=
options.maxVerticalDelta)
88 protectedCells[
index] =
true;
92 const auto original =
out.ground.data();
93 const int radiusX =
static_cast<int>(std::ceil(
options.blendDistance /
dx)),
94 radiusZ =
static_cast<int>(std::ceil(
options.blendDistance /
dz));
95 if (radiusX > 256 || radiusZ > 256)
return invalid<Coverage>(
"channel blend radius exceeds 256 cells");
98 if (original[
static_cast<std::size_t
>(
z) *
width +
x] == 0.f)
continue;
99 for (
int oz = -radiusZ; oz <= radiusZ; ++oz)
100 for (
int ox = -radiusX;
ox <= radiusX; ++
ox) {
101 if (++work >
options.maximumWork)
return invalid<Coverage>(
"channel blending exceeds work budget");
105 if (protectedCells[
index] && original[
index] == 0.f)
continue;
106 const float distance = std::hypot(
static_cast<float>(
ox) *
dx,
static_cast<float>(oz) *
dz);
117 if (
tiles.empty() ||
tiles.size() > 256u)
return invalid<void>(
"terrain requires 1..256 tiles");
118 std::set<std::string> tileIds;
119 std::size_t samples = 0;
120 for (
const auto& tile :
tiles) {
121 if (tile.id.empty() || tile.id.size() > 256u || !tileIds.insert(tile.id).second ||
122 !std::isfinite(tile.originX) || !std::isfinite(tile.originY) || !std::isfinite(tile.originZ) ||
123 !std::isfinite(tile.sizeX) || !std::isfinite(tile.sizeZ) || !std::isfinite(tile.heightScale) ||
124 tile.sizeX <= 0.f || tile.sizeZ <= 0.f || tile.heightScale <= 0.f || !rasterValid(tile.heights,
false) ||
125 tile.heights.getWidth() < 2 || tile.heights.getHeight() < 2 || !rasterValid(tile.holes,
true) ||
126 std::fabs(tile.sizeX / (tile.heights.getWidth() - 1) - tile.sizeZ / (tile.heights.getHeight() - 1)) >
128 tile.splatLayers.size() > 64u || tile.details.size() > 256u || tile.trees.size() > 1000000u)
129 return invalid<void>(
"invalid terrain tile identity, geometry or channel topology");
130 samples += tile.heights.data().size() + tile.holes.data().size() + tile.trees.size() * 8u;
131 for (
float v : tile.holes.data())
132 if (
v != 0.f &&
v != 1.f)
return invalid<void>(
"holes must be binary");
133 for (
const auto&
layer : tile.splatLayers) {
134 if (!rasterValid(
layer,
true) ||
layer.getWidth() != tile.splatLayers.front().getWidth() ||
135 layer.getHeight() != tile.splatLayers.front().getHeight())
136 return invalid<void>(
"invalid splat topology");
137 samples +=
layer.data().size();
139 if (!tile.splatLayers.empty())
140 for (std::size_t i = 0; i < tile.splatLayers.front().data().size(); ++i) {
142 for (
const auto&
layer : tile.splatLayers) sum +=
layer.data()[i];
143 if (std::fabs(sum - 1.f) > 1e-4f)
return invalid<void>(
"splat weights must sum to one");
146 for (
const auto&
d : tile.details) {
147 if (
d.resourceId.empty() ||
d.resourceId.size() > 256u || !
resources.insert(
d.resourceId).second ||
148 d.width < 1 ||
d.height < 1 ||
d.width > 4096 ||
d.height > 4096 ||
149 d.density.size() !=
static_cast<std::size_t
>(
d.width) *
d.height)
150 return invalid<void>(
"invalid detail identity or topology");
151 for (
int v :
d.density)
152 if (
v < 0)
return invalid<void>(
"negative detail density");
153 samples +=
d.density.size();
155 for (
const auto& tree : tile.trees) {
156 if (tree.id.empty() || tree.id.size() > 256u || tree.resourceId.empty() || tree.resourceId.size() > 256u ||
157 !trees.insert(tree.id).second || !std::isfinite(tree.x) || !std::isfinite(tree.y) ||
158 !std::isfinite(tree.z) || !std::isfinite(tree.yaw) || !std::isfinite(tree.width) ||
159 !std::isfinite(tree.height) || tree.width <= 0.f || tree.height <= 0.f)
160 return invalid<void>(
"invalid tree instance");
162 if (samples > 16u * 1024u * 1024u)
return invalid<void>(
"terrain channel storage exceeds budget");
174 auto candidate = std::make_unique<Impl>();
175 const int count =
static_cast<int>(
tiles.size());
176 candidate->history.push_back(std::move(
tiles));
177 impl_.swap(candidate);
185 if (!impl_ || impl_->history.empty() || writes.empty() || writes.size() > 4096u || maximumWork == 0
u)
186 return invalid<int>(
"invalid terrain batch or uninitialized owner");
187 for (
const auto&
write : writes) {
189 if (!std::isfinite(
options.blendDistance) ||
options.blendDistance < 0.f ||
190 !std::isfinite(
options.maxVerticalDelta) ||
options.maxVerticalDelta < 0.f ||
options.splatLayer < -1 ||
193 return invalid<int>(
"invalid terrain write options");
195 std::size_t historyStorage = storage(impl_->history[impl_->cursor]);
196 for (std::size_t i = 0; i <= impl_->cursor; ++i) historyStorage += storage(impl_->history[i]);
197 if (historyStorage > 16u * 1024u * 1024u || impl_->cursor >= 4095u)
198 return invalid<int>(
"terrain undo history exceeds save budget");
199 auto frame = impl_->history[impl_->cursor];
200 std::size_t work = 0;
202 for (
const auto&
write : writes) {
203 if (work >= maximumWork)
return invalid<int>(
"terrain batch exceeds shared work budget");
205 options.maximumWork = work + std::min(maximumWork - work,
options.maximumWork);
207 for (
auto& tile :
frame) {
208 if (
options.splatLayer >=
static_cast<int>(tile.splatLayers.size()))
209 return invalid<int>(
"selected splat layer absent on tile");
211 conform.
originX = tile.originX;
212 conform.
originY = tile.originY;
213 conform.
originZ = tile.originZ;
214 conform.
cellSize = tile.sizeX / (tile.heights.getWidth() - 1);
219 if (work >=
options.maximumWork)
return invalid<int>(
"terrain write exceeds shared work budget");
221 const auto baseline = tile.heights;
224 work +=
height.value().workPerformed;
225 changed +=
static_cast<int>(
height.value().sampleIndices.size());
232 tile.splatLayers.front().getHeight(),
options, work);
234 for (std::size_t i = 0; i <
mask.value().
ground.data().size(); ++i) {
236 const auto target =
static_cast<std::size_t
>(
options.splatLayer);
237 if (
weight <= tile.splatLayers[
target].data()[i])
continue;
238 float remainder = 0.f;
239 for (std::size_t l = 0; l < tile.splatLayers.size(); ++l)
240 if (l !=
target) remainder += tile.splatLayers[l].data()[i];
241 for (std::size_t l = 0; l < tile.splatLayers.size(); ++l) {
242 auto&
value = tile.splatLayers[l].data()[i];
243 const float next = l ==
target ? (remainder > 0.f ?
weight : 1.f)
244 : (remainder > 0.f ?
value * ((1.f -
weight) / remainder) : 0.f);
251 for (
auto&
d : tile.details) {
254 for (std::size_t i = 0; i <
d.density.size(); ++i)
255 if (
mask.value().ground.data()[i] > 0.f ||
256 (
options.cutTunnelHoles &&
mask.value().tunnel.data()[i] > 0.f)) {
261 if (
options.clearTrees && !tile.trees.empty()) {
264 const auto oldCount = tile.trees.size();
266 const float x = (tree.x - tile.originX) / tile.sizeX, z = (tree.z - tile.originZ) / tile.sizeZ;
267 if (x < 0.f || z < 0.f || x > 1.f || z > 1.f) return false;
268 const float ground = mask.value().ground.sampleBilinear(x * (mask.value().ground.getWidth() - 1),
269 z * (mask.value().ground.getHeight() - 1));
270 const float tunnel = mask.value().tunnel.sampleBilinear(x * (mask.value().tunnel.getWidth() - 1),
271 z * (mask.value().tunnel.getHeight() - 1));
272 return ground > 0.f || (options.cutTunnelHoles && tunnel > 0.f);
274 changed +=
static_cast<int>(oldCount - tile.trees.size());
279 for (std::size_t i = 0; i < tile.holes.data().
size(); ++i)
280 if (
mask.value().tunnel.data()[i] > 0.f &&
mask.value().ground.data()[i] == 0.f) {
281 changed += tile.holes.data()[i] != 1.f;
282 tile.holes.data()[i] = 1.f;
287 if (
changed > std::numeric_limits<int>::max())
288 return invalid<int>(
"terrain batch change count exceeds result range");
289 auto candidate = std::make_unique<Impl>(*impl_);
290 candidate->history.resize(candidate->cursor + 1u);
291 candidate->history.push_back(std::move(
frame));
293 impl_.swap(candidate);
297 if (!impl_ || impl_->history.empty() || impl_->cursor == 0
u)
return invalid<int>(
"no terrain undo frame");
302 if (!impl_ || impl_->cursor + 1u >= impl_->history.size())
return invalid<int>(
"no terrain redo frame");
307 if (impl_ && !impl_->history.empty())
308 for (
const auto& tile : impl_->history[impl_->cursor])
310 return invalid<RoadTerrainTile>(
"unknown terrain tile");
std::function< void(b3JointId, const Numbers &)> write
std::vector< std::weak_ptr< DeviceBytes > > resources
std::vector< WfcTile > tiles
const SquirrelValueOptions & options
AbilityActivationGroup group
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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.
int getWidth() const
Returns the width.
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Single mutable owner of imported terrain tiles and their complete-channel history....
Result< int > applyBatch(std::span< const RoadTerrainWrite > writes, std::size_t maximumWork)
Apply ordered per-road policies as one complete-channel history frame.
~RoadTerrainWorkspace()
Destroy owned tiles and history.
Result< int > undo()
Restore the previous complete-channel value; no mutation when history is exhausted....
Result< int > redo()
Restore the next complete-channel value; no mutation when history is exhausted. Selects an owned immu...
RoadTerrainWorkspace()
Construct an empty terrain owner.
Result< int > apply(const MeshBuild &mesh, const RoadTerrainWriteOptions &options)
Evaluate road coverage and publish height, texture, details, trees and selected holes together....
Result< RoadTerrainTile > copyTile(const std::string &id) const
Copy one tile snapshot; returned data never aliases the owner. @cost Linear in this tile's channel st...
Result< int > invalid(std::string message)
Invalid.
Result< void > validateTerrainTiles(const std::vector< RoadTerrainTile > &tiles)
Validate bounded independent channel topologies, normalization and stable resource identities.
EVENGINE_API_DOMAINS Result< RoadTerrainConformReceipt > conformHeightmapToRoadWithReceipt(Heightmap &terrain, const MeshBuild &roadMesh, const RoadTerrainConformOptions &options={})
Atomically conform terrain and return the exact reversible sample delta.
Renderer-neutral complete tile value, handed into one RoadTerrainWorkspace owner. Splat layers are no...
std::vector< Heightmap > splatLayers
Owned terrain tree instance; its stable identity survives removal, undo and save.
Explicit channel selection for one all-tile atomic write; no implicit optional providers.
One synchronous terrain operation; mesh is borrowed until the batch returns, options are copied value...