19 const float t = std::clamp((
v -
a) / (
b -
a), 0.f, 1.f);
20 return t *
t * (3.f - 2.f *
t);
23std::array<float, 3> normalAt(
const Heightmap &hm,
int x,
int y,
float cell,
float heightScale) {
24 const int x0 = std::max(0,
x - 1), x1 = std::min(hm.getWidth() - 1,
x + 1);
25 const int y0 = std::max(0,
y - 1), y1 = std::min(hm.getHeight() - 1,
y + 1);
26 const float dx = (hm.height(x1,
y) - hm.height(x0,
y)) *
heightScale / (
float(std::max(1, x1 - x0)) *
cell);
27 const float dz = (hm.height(
x, y1) - hm.height(
x, y0)) *
heightScale / (
float(std::max(1, y1 - y0)) *
cell);
28 const float inv = 1.f / std::sqrt(
dx *
dx + 1.f +
dz *
dz);
29 return {-
dx * inv, inv, -
dz * inv};
32std::array<float, 4> weightsAt(
const Heightmap &hm,
const TerrainLayers *layers,
int x,
int y,
33 const std::array<float, 3> &
normal,
float minH,
float rangeH) {
34 std::array<float, 4>
w{0.05f, 0.05f, 0.05f, 0.05f};
73 float kernelSum = 0.f;
74 for (
int oy = -1;
oy <= 1; ++
oy)
75 for (
int ox = -1;
ox <= 1; ++
ox) {
76 const int sx = std::clamp(
x +
ox, 0, hm.getWidth() - 1);
77 const int sy = std::clamp(
y +
oy, 0, hm.getHeight() - 1);
78 const float kernel = float((
ox == 0 ? 2 : 1) * (
oy == 0 ? 2 : 1));
86 const float slope = 1.f -
normal[1];
89 const float drainage = std::log1p(std::max(0.f, layers->getFlowAccumulation(
x,
y))) /
90 std::log1p(
float(std::max(2, hm.getWidth() * hm.getHeight())));
91 const float lowGradient = 1.f -
smoothstep(0.025f, 0.16f, slope);
92 const float alluvium =
smoothstep(0.42f, 0.72f, drainage) * lowGradient;
97 w[0] += alluvium * 0.72f;
98 w[2] += alluvium * 0.10f;
100 const float elevation = rangeH > 0.f ? (hm.height(
x,
y) - minH) / rangeH : 0.f;
103 if (layers)
w[1] += layers->getMoisture(
x,
y) * (1.f -
smoothstep(0.05f, 0.3f, slope)) * 0.25f;
104 const float sum =
w[0] +
w[1] +
w[2] +
w[3];
110 std::vector<int>
axis;
118 if (vertex < 0 || vertex >=
getVertexCount() || channel < 0 || channel >= 4)
return 0.f;
119 return weights_[size_t(vertex) * 4u + size_t(channel)];
123 if (vertex < 0 ||
size_t(vertex) >= biomes_.size())
return -1;
124 return int(biomes_[
size_t(vertex)]);
129 if (
s.cellsX <= 0 ||
s.cellsY <= 0 ||
s.originX < 0 ||
s.originY < 0 ||
s.originX +
s.cellsX >= hm.
getWidth() ||
130 s.originY +
s.cellsY >= hm.
getHeight() ||
s.lod < 0 ||
s.lod > 20 || !std::isfinite(
s.cellSize) ||
131 s.cellSize <= 0.f || !std::isfinite(
s.heightScale) || !std::isfinite(
s.skirtDepth) ||
s.skirtDepth < 0.f) {
132 if (
error) *
error =
"terrain mesh: invalid bounds or settings";
136 if (
error) *
error =
"terrain mesh: layer dimensions do not match heightmap";
139 const int step = 1 <<
s.lod;
140 const std::vector<int> xs = sampleAxis(
s.originX,
s.cellsX,
step);
141 const std::vector<int> ys = sampleAxis(
s.originY,
s.cellsY,
step);
142 const auto [minIt, maxIt] = std::minmax_element(hm.
data().begin(), hm.
data().end());
143 const float minH = *minIt, rangeH = *maxIt - *minIt;
146 out.originX_ =
s.originX;
147 out.originY_ =
s.originY;
149 const int cols = int(xs.size()),
rows = int(ys.size());
153 auto addVertex = [&](
int gx,
int gy,
float yOffset,
const std::array<float, 3> &
n) {
154 out.mesh_.addVertex(
float(gx -
s.originX) *
s.cellSize, hm.
height(gx, gy) *
s.heightScale + yOffset,
155 float(gy -
s.originY) *
s.cellSize,
n[0],
n[1],
n[2],
156 float(gx -
s.originX) / float(
s.cellsX), float(gy -
s.originY) / float(
s.cellsY));
158 weightsAt(hm, layers, gx, gy, normalAt(hm, gx, gy,
s.cellSize,
s.heightScale), minH, rangeH);
160 out.biomes_.push_back(
164 for (
int gx : xs) addVertex(gx, gy, 0.f, normalAt(hm, gx, gy,
s.cellSize,
s.heightScale));
165 out.baseVertexCount_ =
out.mesh_.getVertexCount();
166 for (
int y = 0;
y + 1 <
rows; ++
y)
167 for (
int x = 0;
x + 1 <
cols; ++
x) {
168 const uint32_t
a = uint32_t(
y *
cols +
x),
b =
a + 1,
c =
a + uint32_t(
cols),
d =
c + 1;
169 out.mesh_.addTriangle(
a,
c,
b);
170 out.mesh_.addTriangle(
b,
c,
d);
173 if (
s.skirtDepth > 0.f) {
175 std::vector<std::pair<int, int>>
points;
176 std::array<float, 3>
normal;
178 std::array<Edge, 4>
edges;
179 for (
int gx : xs)
edges[0].
points.emplace_back(gx, ys.front());
180 for (
int gy : ys)
edges[1].
points.emplace_back(xs.back(), gy);
181 for (
auto it = xs.rbegin(); it != xs.rend(); ++it)
edges[2].
points.emplace_back(*it, ys.back());
182 for (
auto it = ys.rbegin(); it != ys.rend(); ++it)
edges[3].
points.emplace_back(xs.front(), *it);
183 edges[0].normal = {0.f, 0.f, -1.f};
184 edges[1].normal = {1.f, 0.f, 0.f};
185 edges[2].normal = {0.f, 0.f, 1.f};
186 edges[3].normal = {-1.f, 0.f, 0.f};
188 const uint32_t
start = uint32_t(
out.mesh_.getVertexCount());
189 for (
const auto &[gx, gy] :
edge.points) {
190 addVertex(gx, gy, 0.f,
edge.normal);
191 addVertex(gx, gy, -
s.skirtDepth,
edge.normal);
193 for (uint32_t i = 0; i + 1 <
edge.points.size(); ++i) {
194 const uint32_t topA =
start + i * 2, bottomA = topA + 1, topB = topA + 2, bottomB = topB + 1;
195 out.mesh_.addTriangle(topA, topB, bottomA);
196 out.mesh_.addTriangle(topB, bottomB, bottomA);
200 out.mesh_.setMeta(
"kind",
"terrain.chunk");
201 out.mesh_.setMeta(
"lod", std::to_string(
s.lod));
202 out.mesh_.setMeta(
"originX", std::to_string(
s.originX));
203 out.mesh_.setMeta(
"originY", std::to_string(
s.originY));
208 if (
s.lod <= 0 ||
s.originX < 0 ||
s.originY < 0 ||
s.cellsX <= 0 ||
s.cellsY <= 0 ||
210 !std::isfinite(
s.heightScale))
212 const int step = 1 << std::min(
s.lod, 20);
214 for (
int by = 0; by <
s.cellsY; by +=
step) {
215 const int y0 =
s.originY + by;
216 const int y1 =
s.originY + std::min(by +
step,
s.cellsY);
217 for (
int bx = 0; bx <
s.cellsX; bx +=
step) {
218 const int x0 =
s.originX + bx;
219 const int x1 =
s.originX + std::min(bx +
step,
s.cellsX);
220 const float h00 = hm.
height(x0, y0), h10 = hm.
height(x1, y0);
221 const float h01 = hm.
height(x0, y1), h11 = hm.
height(x1, y1);
222 for (
int y = y0;
y <= y1; ++
y)
223 for (
int x = x0;
x <= x1; ++
x) {
224 const float tx = x1 > x0 ? float(
x - x0) / float(x1 - x0) : 0.f;
225 const float ty = y1 > y0 ? float(
y - y0) / float(y1 - y0) : 0.f;
226 const float approximation = std::lerp(std::lerp(h00, h10, tx), std::lerp(h01, h11, tx), ty);
235 float viewportHeight,
float verticalFovDegrees,
float targetPixelError) {
236 if (maxLod < 0 || maxLod > 20 || !std::isfinite(distanceToCamera) || distanceToCamera <= 0.f ||
237 !std::isfinite(viewportHeight) || viewportHeight <= 0.f || !std::isfinite(verticalFovDegrees) ||
238 verticalFovDegrees <= 1.f || verticalFovDegrees >= 179.f || !std::isfinite(targetPixelError) ||
239 targetPixelError <= 0.f ||
s.originX < 0 ||
s.originY < 0 ||
s.cellsX <= 0 ||
s.cellsY <= 0 ||
241 !std::isfinite(
s.heightScale))
243 const float radians = verticalFovDegrees * 0.01745329251994329577f;
244 const float projectionScale = viewportHeight / (2.f * std::tan(radians * 0.5f));
245 for (
int lod = maxLod;
lod >= 0; --
lod) {
248 if (projected <= targetPixelError)
return lod;
255 if (
s.cellsX <= 0 ||
s.cellsY <= 0 ||
s.originX < 0 ||
s.originY < 0 ||
s.originX +
s.cellsX >= hm.
getWidth() ||
258 !std::isfinite(
s.heightScale) || !std::isfinite(
s.minWidth) || !std::isfinite(
s.maxWidth) ||
259 s.minWidth <= 0.f ||
s.maxWidth <
s.minWidth || !std::isfinite(
s.heightOffset) ||
260 !std::isfinite(
s.minSurfaceSlope) || !std::isfinite(
s.maxSurfaceSlope) ||
s.minSurfaceSlope < 0.f ||
261 s.maxSurfaceSlope <=
s.minSurfaceSlope) {
262 if (
error) *
error =
"terrain river mesh: invalid bounds or settings";
266 static constexpr std::array<int, 8> flowDx{-1, 0, 1, -1, 1, -1, 0, 1};
267 static constexpr std::array<int, 8> flowDy{-1, -1, -1, 0, 0, 1, 1, 1};
268 const size_t layerCells = size_t(layers.
getWidth()) * size_t(layers.
getHeight());
269 std::vector<float> channelFlow(layerCells, 0.f);
270 std::vector<uint16_t> riverIndegree(layerCells, 0);
273 const size_t i = size_t(
y * layers.
getWidth() +
x);
277 if (direction < 0 || direction >= 8)
continue;
280 ++riverIndegree[size_t(ry * layers.
getWidth() + rx)];
282 std::queue<size_t> riverQueue;
283 for (
size_t i = 0; i < layerCells; ++i)
284 if (channelFlow[i] > 0.f && riverIndegree[i] == 0) riverQueue.push(i);
285 while (!riverQueue.empty()) {
286 const size_t i = riverQueue.front();
288 const int x = int(i %
size_t(layers.
getWidth()));
289 const int y = int(i /
size_t(layers.
getWidth()));
291 if (direction < 0 || direction >= 8)
continue;
295 const size_t receiver = size_t(ry * layers.
getWidth() + rx);
296 channelFlow[receiver] = std::max(channelFlow[receiver], channelFlow[i]);
297 if (riverIndegree[receiver] > 0 && --riverIndegree[receiver] == 0) riverQueue.push(receiver);
300 for (
float flow : channelFlow) maxFlow = std::max(maxFlow, flow);
301 std::vector<uint8_t> calmReach(layerCells, 0);
305 if (!layers.
isRiver(
x,
y) || d < 0 || d >= 8)
continue;
306 const int rx =
x + flowDx[size_t(
d)], ry =
y + flowDy[size_t(
d)];
310 std::sqrt(
float(flowDx[
size_t(
d)] * flowDx[
size_t(
d)] + flowDy[
size_t(
d)] * flowDy[
size_t(
d)]));
311 const float rise = std::abs(hm.
height(rx, ry) - hm.
height(
x,
y)) *
s.heightScale;
312 const float grade = rise /
run;
313 calmReach[size_t(
y * layers.
getWidth() +
x)] =
314 uint8_t(grade >=
s.minSurfaceSlope && grade <
s.maxSurfaceSlope);
318 std::vector<uint8_t> closedReach = calmReach;
321 const size_t i = size_t(
y * layers.
getWidth() +
x);
323 if (calmReach[i] || !layers.
isRiver(
x,
y) || d < 0 || d >= 8)
continue;
324 const int rx =
x + flowDx[size_t(
d)], ry =
y + flowDy[size_t(
d)];
325 const size_t receiver = size_t(ry * layers.
getWidth() + rx);
326 if (!calmReach[receiver])
continue;
327 bool calmDonor =
false;
328 for (
int incoming = 0; incoming < 8 && !calmDonor; ++incoming) {
329 const int nx =
x + flowDx[size_t(incoming)],
ny =
y + flowDy[size_t(incoming)];
331 if (nd < 0 || nd >= 8)
continue;
333 calmDonor = calmReach[
n] &&
nx + flowDx[size_t(nd)] ==
x &&
ny + flowDy[size_t(nd)] ==
y;
335 if (calmDonor) closedReach[i] = 1;
337 auto strongestDonor = [&](
int sx,
int sy) {
338 float donorFlow = -1.f;
339 int donorX =
sx, donorY =
sy;
340 for (
int candidate = 0; candidate < 8; ++candidate) {
341 const int dxCell =
sx + flowDx[size_t(candidate)];
342 const int dyCell =
sy + flowDy[size_t(candidate)];
343 if (dxCell < 0 || dyCell < 0 || dxCell >= layers.
getWidth() || dyCell >= layers.
getHeight())
continue;
345 if (donorDirection < 0 || donorDirection >= 8 || dxCell + flowDx[
size_t(donorDirection)] !=
sx ||
346 dyCell + flowDy[
size_t(donorDirection)] !=
sy)
349 if (flow > donorFlow) {
355 return std::array<int, 2>{donorX, donorY};
357 auto receiver = [&](
int sx,
int sy) {
359 if (direction < 0 || direction >= 8)
return std::array<int, 2>{
sx,
sy};
360 const int receiverX =
sx + flowDx[size_t(
direction)];
361 const int receiverY =
sy + flowDy[size_t(
direction)];
362 if (receiverX < 0 || receiverY < 0 || receiverX >= layers.
getWidth() || receiverY >= layers.
getHeight())
363 return std::array<int, 2>{
sx,
sy};
364 return std::array<int, 2>{receiverX, receiverY};
366 auto smoothCenter = [&](
int sx,
int sy) {
372 const auto pMinus1 = strongestDonor(
sx,
sy);
373 const auto pMinus2 = strongestDonor(pMinus1[0], pMinus1[1]);
374 const auto pPlus1 = receiver(
sx,
sy);
375 const auto pPlus2 = receiver(pPlus1[0], pPlus1[1]);
376 return std::array<float, 2>{(float(pMinus2[0]) + 4.f * float(pMinus1[0]) + 6.f * float(
sx) +
377 4.f * float(pPlus1[0]) + float(pPlus2[0])) /
379 (
float(pMinus2[1]) + 4.f * float(pMinus1[1]) + 6.f * float(
sy) +
380 4.f * float(pPlus1[1]) + float(pPlus2[1])) /
383 auto sampleHeight = [&](
float sx,
float sy) {
386 const int x0 = int(std::floor(
sx)), y0 = int(std::floor(
sy));
387 const int x1 = std::min(x0 + 1, hm.
getWidth() - 1);
388 const int y1 = std::min(y0 + 1, hm.
getHeight() - 1);
389 const float tx =
sx - float(x0), ty =
sy - float(y0);
390 return std::lerp(std::lerp(hm.
height(x0, y0), hm.
height(x1, y0), tx),
391 std::lerp(hm.
height(x0, y1), hm.
height(x1, y1), tx), ty);
393 for (
int y =
s.originY;
y <=
s.originY +
s.cellsY; ++
y) {
394 for (
int x =
s.originX;
x <=
s.originX +
s.cellsX; ++
x) {
396 if (!layers.
isRiver(
x,
y) || direction < 0 || direction >= 8)
continue;
397 if (!closedReach[
size_t(
y * layers.
getWidth() +
x)])
continue;
398 const int receiverX =
x + flowDx[size_t(
direction)];
399 const int receiverY =
y + flowDy[size_t(
direction)];
400 const auto startCenter = smoothCenter(
x,
y);
401 const auto endCenter = smoothCenter(receiverX, receiverY);
402 const float tx0 = endCenter[0] - startCenter[0];
403 const float tz0 = endCenter[1] - startCenter[1];
404 const float tangentLengthSquared = tx0 * tx0 + tz0 * tz0;
405 if (tangentLengthSquared <= 1e-8f)
continue;
406 const float invLength = 1.f / std::sqrt(tangentLengthSquared);
407 const float tx = tx0 * invLength, tz = tz0 * invLength;
408 auto widthAt = [&](
int sampleX,
int sampleY) {
412 const float discharge = channelFlow[size_t(sampleY * layers.
getWidth() + sampleX)];
413 const float areaScale =
414 maxFlow > 1.f ? std::pow(std::clamp(discharge / maxFlow, 0.f, 1.f), 0.36f) : 0.f;
415 const float orderScale =
416 std::clamp((
float(layers.
getStreamOrder(sampleX, sampleY)) - 1.f) / 4.f, 0.f, 1.f);
417 const float flowScale = std::max(areaScale, orderScale * 0.82f);
418 return 0.5f * std::lerp(
s.minWidth,
s.maxWidth, flowScale);
420 const float startWidth = widthAt(
x,
y);
421 const float endWidth = layers.
isRiver(receiverX, receiverY) ? widthAt(receiverX, receiverY) : startWidth;
426 if (std::hypot(startFlowX, startFlowY) < 0.1f) {
430 if (std::hypot(endFlowX, endFlowY) < 0.1f) {
434 const float chordCells = std::sqrt(tangentLengthSquared);
435 auto curvePoint = [&](
float t) {
436 const float t2 =
t *
t, t3 = t2 *
t;
437 const float h00 = 2.f * t3 - 3.f * t2 + 1.f;
438 const float h10 = t3 - 2.f * t2 +
t;
439 const float h01 = -2.f * t3 + 3.f * t2;
440 const float h11 = t3 - t2;
441 return std::array<float, 2>{h00 * startCenter[0] + h10 * startFlowX * chordCells + h01 * endCenter[0] +
442 h11 * endFlowX * chordCells,
443 h00 * startCenter[1] + h10 * startFlowY * chordCells + h01 * endCenter[1] +
444 h11 * endFlowY * chordCells};
446 constexpr int curveSegments = 5;
447 std::array<std::array<float, 2>, curveSegments + 1>
curve{};
449 curve[
size_t(
point)] = curvePoint(
float(
point) /
float(curveSegments));
450 const uint32_t stripStart = uint32_t(
out.getVertexCount());
453 const int following = std::min(curveSegments,
point + 1);
456 const float t = float(
point) / float(curveSegments);
465 float frameX = std::lerp(startFlowX, endFlowX,
t);
466 float frameY = std::lerp(startFlowY, endFlowY,
t);
471 if (
point == curveSegments) {
476 if (frameLength < 1e-5f) {
479 frameLength = std::max(1e-5f, std::hypot(
frameX,
frameY));
481 const float qpx = -
frameY / frameLength;
482 const float qpz =
frameX / frameLength;
483 const float width = std::lerp(startWidth, endWidth,
t);
485 const float qx = (
q[0] - float(
s.originX)) *
s.cellSize;
486 const float qz = (
q[1] - float(
s.originY)) *
s.cellSize;
487 const float widthCells =
width /
s.cellSize;
488 const float centerBed = sampleHeight(
q[0],
q[1]);
489 const float leftBed = sampleHeight(
q[0] - qpx * widthCells,
q[1] - qpz * widthCells);
490 const float rightBed = sampleHeight(
q[0] + qpx * widthCells,
q[1] + qpz * widthCells);
495 const float qy = std::max({centerBed, leftBed, rightBed}) *
s.heightScale +
s.heightOffset;
499 for (
int segment = 0; segment < curveSegments; ++segment) {
500 const uint32_t
a = stripStart + uint32_t(segment * 2);
501 const uint32_t
b =
a + 1u,
c =
a + 2u, dVertex =
a + 3u;
503 out.addTriangle(
b,
c, dVertex);
507 out.setMeta(
"kind",
"terrain.rivers");
513 if (
s.cellsX <= 0 ||
s.cellsY <= 0 ||
s.originX < 0 ||
s.originY < 0 ||
s.originX +
s.cellsX >= hm.
getWidth() ||
516 !std::isfinite(
s.heightScale) || !std::isfinite(
s.minimumDepth) ||
s.minimumDepth < 0.f ||
517 !std::isfinite(
s.heightOffset)) {
518 if (
error) *
error =
"terrain lake mesh: invalid bounds or settings";
525 for (
int y =
s.originY;
y <
s.originY +
s.cellsY; ++
y) {
526 for (
int x =
s.originX;
x <
s.originX +
s.cellsX; ++
x) {
531 if (std::max({d00, d10, d01, d11}) <
s.minimumDepth)
continue;
532 auto surface = [&](
int sx,
int sy,
float depth) {
535 const float x0 = float(
x -
s.originX) *
s.cellSize;
536 const float x1 = float(
x + 1 -
s.originX) *
s.cellSize;
537 const float z0 = float(
y -
s.originY) *
s.cellSize;
538 const float z1 = float(
y + 1 -
s.originY) *
s.cellSize;
542 std::vector<ShoreVertex> polygon{
543 {x0, surface(
x,
y, d00), z0, d00},
544 {x1, surface(
x + 1,
y, d10), z0, d10},
545 {x1, surface(
x + 1,
y + 1, d11), z1, d11},
546 {x0, surface(
x,
y + 1, d01), z1, d01},
548 std::vector<ShoreVertex> clipped;
550 const ShoreVertex &
a = polygon[
edge];
551 const ShoreVertex &
b = polygon[(
edge + 1) % polygon.size()];
552 const bool aInside =
a.depth >=
s.minimumDepth;
553 const bool bInside =
b.depth >=
s.minimumDepth;
554 if (aInside) clipped.push_back(
a);
555 if (aInside == bInside)
continue;
556 const float t = std::clamp((
s.minimumDepth -
a.depth) / (
b.depth -
a.depth), 0.f, 1.f);
558 {std::lerp(
a.x,
b.x,
t), std::lerp(
a.y,
b.y,
t), std::lerp(
a.z,
b.z,
t),
s.minimumDepth});
560 if (clipped.size() < 3)
continue;
561 const uint32_t
first = uint32_t(
out.getVertexCount());
562 for (
const ShoreVertex &
v : clipped) {
563 const float u = (
v.x / (float(
s.cellsX) *
s.cellSize));
564 const float texV = (
v.z / (float(
s.cellsY) *
s.cellSize));
565 out.addVertex(
v.x,
v.y,
v.z, 0.f, 1.f, 0.f,
u, texV);
567 for (uint32_t vertex = 1; vertex + 1 < clipped.size(); ++vertex)
571 out.setMeta(
"kind",
"terrain.lakes");
580uint64_t TerrainStreamingCache::key(
int chunkX,
int chunkY) {
581 return uint64_t(uint32_t(chunkX)) | (uint64_t(uint32_t(chunkY)) << 32);
586 if (!next.open(data,
size,
error))
return false;
587 asset_ = std::move(next);
594 auto opened = next.openSource(std::move(
source));
595 if (!opened)
return opened;
596 asset_ = std::move(next);
604 std::string *
error) {
611 const int centerX = worldX >= 0 ? worldX / chunkSize : -((-worldX - 1) / chunkSize) - 1;
612 const int centerY = worldY >= 0 ? worldY / chunkSize : -((-worldY - 1) / chunkSize) - 1;
615 for (
auto it = resident_.begin(); it != resident_.end();) {
616 const int cx = int32_t(uint32_t(it->first));
617 const int cy = int32_t(uint32_t(it->first >> 32));
618 const int64_t
dx = int64_t(
cx) - centerX,
dy = int64_t(
cy) - centerY;
620 it = resident_.erase(it);
630 std::vector<Request> requests;
633 const int64_t distanceSq = int64_t(
dx) *
dx + int64_t(
dy) *
dy;
634 if (distanceSq > radiusSq)
continue;
635 const int chunkX = centerX +
dx, chunkY = centerY +
dy;
637 requests.push_back({chunkX, chunkY, distanceSq});
640 std::sort(requests.begin(), requests.end(), [](
const Request &
a,
const Request &
b) {
641 return std::tie(a.distanceSq, a.y, a.x) < std::tie(b.distanceSq, b.y, b.x);
643 const size_t loadCount = maxLoads > 0 ? std::min(requests.size(),
size_t(maxLoads)) : requests.size();
644 for (
size_t i = 0; i < loadCount; ++i) {
646 std::string chunkError;
647 if (!asset_.
loadChunk(requests[i].x, requests[i].y, chunk, &chunkError)) {
652 resident_.emplace(
key(requests[i].
x, requests[i].
y), std::move(chunk));
655 stats.pending = int(requests.size() - loadCount);
661 const auto it = resident_.find(
key(chunkX, chunkY));
662 return it == resident_.end() ? nullptr : &it->second;
666 if (worldX < 0 || worldY < 0 || worldX >= asset_.
getWidth() || worldY >= asset_.
getHeight())
return false;
669 if (!chunk)
return false;
670 const int lx = worldX -
cx * cs, ly = worldY -
cy * cs;
671 if (lx >= chunk->
width || ly >= chunk->
height)
return false;
672 const size_t i = size_t(ly) * size_t(chunk->
width) + size_t(lx);
680 out.lake =
out.lakeDepth > 0.001f;
689 static constexpr int dx[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
690 static constexpr int dy[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
693 receiverX = worldX +
dx[
source.flowDirection];
694 receiverY = worldY +
dy[
source.flowDirection];
696 return sampleCell(receiverX, receiverY, receiver);
700 std::vector<std::pair<int, int>> &
out)
const {
704 out.emplace_back(worldX, worldY);
708 if (
current.flowDirection < 0)
return true;
709 int nextX = 0, nextY = 0;
710 if (!
getReceiver(worldX, worldY, nextX, nextY))
return false;
711 if (std::find(
out.begin(),
out.end(), std::pair<int, int>{nextX, nextY}) !=
out.end())
return false;
712 out.emplace_back(nextX, nextY);
726 next.originX = originX;
727 next.originY = originY;
729 next.hydrology.width =
width;
730 next.hydrology.height =
height;
731 next.climate.width =
width;
732 next.climate.height =
height;
734 next.hydrology.flowDirection.resize(
count);
735 next.hydrology.flowVectorX.resize(
count);
736 next.hydrology.flowVectorY.resize(
count);
737 next.hydrology.flowAccumulation.resize(
count);
738 next.hydrology.lakeDepth.resize(
count);
739 next.hydrology.rivers.resize(
count);
740 next.hydrology.streamOrder.resize(
count);
741 next.climate.temperature.resize(
count);
742 next.climate.moisture.resize(
count);
743 next.climate.biomes.resize(
count);
748 const size_t i = size_t(
y) * size_t(
width) + size_t(
x);
749 next.heights.setHeight(
x,
y,
sample.height);
750 next.hydrology.flowDirection[i] = int8_t(
sample.flowDirection);
751 next.hydrology.flowVectorX[i] =
sample.flowVectorX;
752 next.hydrology.flowVectorY[i] =
sample.flowVectorY;
753 next.hydrology.flowAccumulation[i] =
sample.flowAccumulation;
754 next.hydrology.lakeDepth[i] =
sample.lakeDepth;
755 next.hydrology.rivers[i] = uint8_t(
sample.river);
756 next.hydrology.streamOrder[i] = uint8_t(
sample.streamOrder);
757 next.climate.temperature[i] =
sample.temperature;
758 next.climate.moisture[i] =
sample.moisture;
759 next.climate.biomes[i] =
sample.biome;
761 out = std::move(next);
766 if (!std::isfinite(worldX) || !std::isfinite(worldY) || worldX < 0.f || worldY < 0.f ||
769 const int x0 = int(std::floor(worldX)), y0 = int(std::floor(worldY));
770 const int x1 = std::min(x0 + 1, asset_.
getWidth() - 1), y1 = std::min(y0 + 1, asset_.
getHeight() - 1);
774 const float tx = worldX - float(x0), ty = worldY - float(y0);
775 const float top =
a.height + (
b.height -
a.height) * tx;
776 const float bottom =
c.height + (
d.height -
c.height) * tx;
786bool valid(
const TerrainTerraceRemovalSettings &
s) {
787 const std::array<float, 7>
values = {
s.perlinScale,
789 s.slopeTerraceThreshold,
791 s.verticalGradientThreshold,
792 s.minimumTerraceThreshold,
793 s.maximumTerraceThreshold};
794 return std::all_of(
values.begin(),
values.end(), [](
float value) { return std::isfinite(value) && value >= 0; }) &&
795 s.minimumTerraceThreshold <=
s.maximumTerraceThreshold &&
s.noiseSeed >= 0;
797bool matching(
const Heightmap &
a,
const Heightmap &
b) {
799 a.getHeight() ==
b.getHeight();
804 using namespace raster_detail;
807 "terrain.terraceRemoval.analyze: distinct matching finite rasters and valid thresholds required");
812 for (
int x = 1;
x <
width - 1; ++
x) {
814 const float gradientX =
816 const float gradientY =
818 const float gradient = gradientX + gradientY;
821 if (gradient <
s.slopeTerraceThreshold && vertical <
s.verticalGradientThreshold)
826 const bool flat = gradient <
s.flatThreshold;
827 const bool mountain = vertical >
s.verticalGradientThreshold;
828 const bool terrace = vertical >=
s.minimumTerraceThreshold && vertical <=
s.maximumTerraceThreshold;
840 using namespace raster_detail;
843 "terrain.terraceRemoval.apply: matching finite rasters, distinct class output and valid settings required");
845 const auto& original =
source.data();
847 std::vector<unsigned char>
mask(original.size(), 0);
849 for (
int x = 1;
x <
width - 1; ++
x) {
858 auto smooth = original;
863 for (
int dy = -1;
dy <= 1; ++
dy)
865 smooth[
index(
x,
y)] = float(sum / 9.0);
868 NoiseField noise{
static_cast<unsigned int>(
s.noiseSeed)};
869 const float workflowScale =
s.terrainWorkflow ? 0.00042F / 0.0035F : 1.F;
873 const float dx = std::abs(smooth[
index(
x + 1,
y)] - smooth[
index(
x - 1,
y)]);
874 const float dy = std::abs(smooth[
index(
x,
y + 1)] - smooth[
index(
x,
y - 1)]);
875 const float gradient = std::sqrt(
dx *
dx +
dy *
dy);
876 const float strength =
s.perlinStrength * workflowScale * (1.F - std::clamp(gradient * 10.F, 0.F, 1.F));
878 double(smooth[
index(
x,
y)]) + noise.perlinNoise(
x *
s.perlinScale,
y *
s.perlinScale) *
strength;
880 return invalid(
"terrain.terraceRemoval.apply: noise result exceeds float range");
883 auto directional = noisy;
884 constexpr int weights[3][3] = {{1, 2, 1}, {2, 4, 2}, {1, 2, 1}};
886 for (
int x = 1;
x <
width - 1; ++
x) {
888 for (
int dy = -1;
dy <= 1; ++
dy)
890 directional[
index(
x,
y)] = float(sum / 16.0);
892 std::array<double, 25> kernel{};
893 double kernelSum = 0;
894 for (
int ky = -2; ky <= 2; ++ky)
895 for (
int kx = -2; kx <= 2; ++kx) {
896 const double weight = std::exp(-(kx * kx + ky * ky) / 2.0);
897 kernel[size_t(ky + 2) * 5 + kx + 2] =
weight;
900 auto output = directional;
902 for (
int x = 2;
x <
width - 2; ++
x) {
904 for (
int ky = -2; ky <= 2; ++ky)
905 for (
int kx = -2; kx <= 2; ++kx)
906 sum += directional[
index(
x + kx,
y + ky)] * kernel[size_t(ky + 2) * 5 + kx + 2];
907 const double value = sum / kernelSum;
909 return invalid(
"terrain.terraceRemoval.apply: filtered result exceeds float range");
std::array< double, 10 > q
std::array< float, 3 > scale
std::shared_ptr< const OceanSprayFrame > previous
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::shared_ptr< const std::vector< glm::vec2 > > points
std::set< std::string > values
std::vector< EquipmentStat > stats
RoadLaneDirection direction
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
In-memory terrain heightmap: a dense float grid (row-major, index = y * width + x) materialized from ...
int getHeight() const
Returns the height.
const std::vector< float > & data() const
Data.
float height(int x, int y) const
Height.
int getWidth() const
Returns the width.
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Versioned, random-access terrain archive.
const TerrainChunkEntry * findChunk(int chunkX, int chunkY) const noexcept
Find one chunk directory entry without scanning the full directory.
bool loadChunk(int chunkX, int chunkY, TerrainChunkData &out, std::string *error=nullptr) const
Compatibility operation that loads and verifies one chunk.
int getChunkSize() const
Returns the chunk size.
int getHeight() const
Returns the height.
int getWidth() const
Returns the width.
static bool build(const Heightmap &heightmap, const TerrainLayers &layers, const TerrainLakeMeshSettings &settings, MeshBuild &out, std::string *error=nullptr)
Compatibility operation that builds lake surface geometry.
Script-friendly ownership wrapper for baked hydrology and climate layers.
int getStreamOrder(int x, int y) const
Return Strahler river order, or zero outside the river network.
int getBiome(int x, int y) const
Returns the biome.
int getWidth() const
Returns the width.
int getHeight() const
Returns the height.
bool isRiver(int x, int y) const
True when river.
int getFlowDirection(int x, int y) const
Return the D8 receiver direction for one cell, or -1 at an outlet/out of bounds.
float getFlowAccumulation(int x, int y) const
Returns the flow accumulation.
float getFlowVectorY(int x, int y) const
Return the continuous normalized downslope Y component.
float getLakeDepth(int x, int y) const
Return filled-depression water depth, or zero outside a lake.
float getFlowVectorX(int x, int y) const
Return the continuous normalized downslope X component.
static int select(const Heightmap &heightmap, TerrainMeshSettings settings, int maxLod, float distance, float viewportHeight, float verticalFovDegrees, float targetPixelError)
Select the coarsest LOD whose projected geometric error is within budget.
static bool build(const Heightmap &heightmap, const TerrainLayers *layers, const TerrainMeshSettings &settings, TerrainMeshChunk &out, std::string *error=nullptr)
Compatibility operation that builds a terrain mesh chunk.
static float estimateGeometricError(const Heightmap &heightmap, const TerrainMeshSettings &settings)
Maximum world-space deviation between a LOD grid and the source heightfield.
One renderable heightfield chunk plus four ecological material weights.
int getBiome(int vertex) const
Return the biome id stored for one mesh vertex, or -1 when out of range.
float getMaterialWeight(int vertex, int channel) const
Returns the material weight.
int getVertexCount() const
Returns the vertex count.
static bool build(const Heightmap &heightmap, const TerrainLayers &layers, const TerrainRiverMeshSettings &settings, MeshBuild &out, std::string *error=nullptr)
Compatibility operation that builds river surface geometry.
const TerrainChunkData * getChunk(int chunkX, int chunkY) const
Borrow a resident chunk. @lifetime Pointer remains valid until cache mutation.
bool getReceiver(int worldX, int worldY, int &receiverX, int &receiverY) const
Resolve a cell's D8 receiver in global coordinates, including an adjacent chunk.
int getResidentCount() const
Returns the resident count.
bool buildWindow(int originX, int originY, int width, int height, TerrainStreamingWindow &out) const
Compatibility operation that assembles a dense hydrology window.
bool open(const uint8_t *data, size_t size, std::string *error=nullptr)
Compatibility operation that opens EVTR and clears decoded chunks.
bool traceFlow(int worldX, int worldY, int maxSteps, std::vector< std::pair< int, int > > &out) const
Compatibility operation that follows D8 receivers across chunks.
bool sampleHeight(float worldX, float worldY, float &out) const
Compatibility operation for cross-chunk bilinear height sampling.
Result< void > openSource(std::shared_ptr< const ITerrainArchiveSource > source)
Open EVTR through a retained random-access source without loading chunk payloads.
TerrainStreamStats streamAround(int worldX, int worldY, int radiusChunks, int maxLoads=0, std::string *error=nullptr)
Stream chunks around a world-space sample coordinate.
bool sampleCell(int worldX, int worldY, TerrainSample &out) const
Compatibility operation that reads a resident integer world cell.
float smoothstep(float edge0, float edge1, float value)
double sample(const Heightmap &map, double u, double v)
Sample.
Result< int > publish(Heightmap &target, std::vector< float > candidate)
Publish.
bool validRaster(const Heightmap &map)
Valid raster.
Result< int > invalid(std::string message)
Invalid.
bool isRepresentable(double value)
True when representable.
Result< int > analyzeTerrainTerraces(Heightmap &target, const Heightmap &source, const TerrainTerraceRemovalSettings &s)
Classify a heightmap into Pcg's black/red/green/blue important-detail categories.
Result< int > removeTerrainTerraces(Heightmap &target, const Heightmap &source, const Heightmap &classes, const TerrainTerraceRemovalSettings &s)
Apply Pcg's adaptive smoothing, gradient noise, 3x3 filter, and fixed 5x5 Gaussian blur.
Deterministic 2D noise helpers for pixel textures and masks.
Decoded terrain chunk containing all baked runtime layers.
std::vector< float > flowAccumulation
std::vector< float > moisture
std::vector< float > lakeDepth
std::vector< float > flowVectorX
std::vector< uint8_t > rivers
std::vector< Biome > biomes
std::vector< uint8_t > streamOrder
std::vector< int8_t > flowDirection
std::vector< float > flowVectorY
std::vector< float > temperature
TerrainLakeMeshSettings public API.
TerrainMeshSettings public API.
TerrainRiverMeshSettings public API.
TerrainSample public API.
TerrainStreamStats public API.
A rectangular, globally addressed terrain window assembled from resident chunks.
Portable controls for Pcg HeightmapTerraceRemover's analysis and processing pipeline.