载入中...
搜索中...
未找到
TerrainGenerationSession.cpp
浏览该文件的文档.
2#include <bit>
3#include <limits>
4#include <optional>
5#include <string_view>
6#include <type_traits>
7#include <variant>
8#include "common/Value.h"
14
15namespace eve::procgen {
16using namespace raster_detail;
17namespace {
18constexpr std::size_t kMaximumSessionSnapshotBytes = 128U * 1024U * 1024U;
19constexpr std::uint32_t kMaximumSessionCommands = 65536;
20struct SessionWriter {
21 std::string bytes;
22 template <class T> void scalar(T value) {
23 if constexpr (std::is_enum_v<T>) scalar(static_cast<std::underlying_type_t<T>>(value));
24 else if constexpr (std::is_same_v<T, bool>) scalar(static_cast<std::uint8_t>(value));
25 else if constexpr (std::is_same_v<T, float>) scalar(std::bit_cast<std::uint32_t>(value));
26 else if constexpr (std::is_same_v<T, double>) scalar(std::bit_cast<std::uint64_t>(value));
27 else {
28 using U = std::make_unsigned_t<T>;
29 U bits = static_cast<U>(value);
30 for (std::size_t i = 0; i < sizeof(T); ++i) bytes.push_back(static_cast<char>((bits >> (i * 8)) & 255U));
31 }
32 }
33};
34struct SessionReader {
35 int version = 1;
36 std::string_view bytes;
37 std::size_t offset = 0;
38 template <class T> bool scalar(T& value) {
39 if constexpr (std::is_enum_v<T>) {
40 std::underlying_type_t<T> raw{}; if (!scalar(raw)) return false; value = static_cast<T>(raw); return true;
41 } else if constexpr (std::is_same_v<T, bool>) {
42 std::uint8_t raw{}; if (!scalar(raw) || raw > 1) return false; value = raw != 0; return true;
43 } else if constexpr (std::is_same_v<T, float>) {
44 std::uint32_t raw{}; if (!scalar(raw)) return false; value = std::bit_cast<float>(raw); return std::isfinite(value);
45 } else if constexpr (std::is_same_v<T, double>) {
46 std::uint64_t raw{}; if (!scalar(raw)) return false; value = std::bit_cast<double>(raw); return std::isfinite(value);
47 } else {
48 if (bytes.size() - offset < sizeof(T)) return false;
49 using U = std::make_unsigned_t<T>; U bits = 0;
50 for (std::size_t i = 0; i < sizeof(T); ++i)
51 bits |= static_cast<U>(static_cast<unsigned char>(bytes[offset++])) << (i * 8);
52 value = static_cast<T>(bits); return true;
53 }
54 }
55};
56void writeSessionHeightmap(SessionWriter& writer, const Heightmap& map) {
57 writer.scalar(map.getWidth()); writer.scalar(map.getHeight());
58 for (float value : map.data()) writer.scalar(value);
59}
60bool readSessionHeightmap(SessionReader& reader, Heightmap& map) {
61 int width{}, height{};
62 if (!reader.scalar(width) || !reader.scalar(height) || width <= 0 || height <= 0 || width > INT_MAX / height)
63 return false;
64 Heightmap candidate(width, height);
65 for (float& value : candidate.data()) if (!reader.scalar(value)) return false;
66 map = std::move(candidate); return true;
67}
68std::string encodeSessionHex(std::string_view bytes) {
69 static constexpr char digits[] = "0123456789abcdef";
70 std::string result; result.reserve(bytes.size() * 2);
71 for (unsigned char value : bytes) { result.push_back(digits[value >> 4]); result.push_back(digits[value & 15]); }
72 return result;
73}
74Result<std::string> decodeSessionHex(std::string_view text) {
75 if ((text.size() & 1U) != 0 || text.size() / 2 > kMaximumSessionSnapshotBytes)
77 "terrain.session.restore: invalid payload size"));
78 auto nibble = [](char c) { return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; };
79 std::string result(text.size() / 2, '\0');
80 for (std::size_t i = 0; i < result.size(); ++i) {
81 int high = nibble(text[i * 2]), low = nibble(text[i * 2 + 1]);
82 if (high < 0 || low < 0) return Result<std::string>::failure(Diagnostic::error(
83 DiagnosticCode::InvalidArgument, "terrain.session.restore: invalid payload hex"));
84 result[i] = static_cast<char>((high << 4) | low);
85 }
86 return Result<std::string>::success(std::move(result));
87}
88struct SessionState {
89 Heightmap terrain, sediment;
90 TerrainWaterField water;
91};
92struct SimulationResetRecord {
93 float depth;
94};
95struct ThermalRecord {
96 TerrainThermalSettings settings;
97};
98struct HydraulicRecord {
99 TerrainWaterSettings water;
100 TerrainSedimentSettings sediment;
101 TerrainThermalSettings thermal;
103};
104Result<int> execute(SessionState& state, const SimulationResetRecord& c) {
105 auto result = state.water.reset(state.terrain.getWidth(), state.terrain.getHeight(), c.depth);
106 if (!result.ok()) return result;
107 std::fill(state.sediment.data().begin(), state.sediment.data().end(), 0.0F);
108 return result;
109}
110Result<int> execute(SessionState& state, const ThermalRecord& c) {
111 return applyTerrainThermal(state.terrain, state.sediment, c.settings);
112}
113Result<int> execute(SessionState& state, const HydraulicRecord& c) {
114 return state.water.advanceHydraulic(state.terrain, state.sediment, c.water, c.sediment, c.thermal, c.iterations);
115}
116struct StampRecord {
117 Heightmap stamp, local, global;
118 TerrainStampSettings settings;
119};
120struct ContrastRecord {
121 Heightmap mask;
123};
124struct SmoothRecord {
125 Heightmap mask;
126 TerrainSmoothSettings settings;
127};
128struct RidgeRecord {
129 Heightmap mask;
130 TerrainRidgeSettings settings;
131};
132struct TerraceRecord {
133 Heightmap mask;
134 TerrainTerraceSettings settings;
135};
136struct PowerRecord {
137 Heightmap mask;
138 float power;
139};
140struct CurveRecord {
141 Heightmap mask, curve;
143};
144struct MixRecord {
145 Heightmap local, global;
146 TerrainHeightMixSettings settings;
147};
148Result<int> execute(Heightmap& h, const StampRecord& c) {
149 return applyTerrainStamp(h, c.stamp, c.settings, c.local, c.global);
150}
151Result<int> execute(Heightmap& h, const ContrastRecord& c) {
152 return applyTerrainContrast(h, c.mask, c.strength, c.featureSize);
153}
154Result<int> execute(Heightmap& h, const SmoothRecord& c) { return applyTerrainSmooth(h, c.mask, c.settings); }
155Result<int> execute(Heightmap& h, const RidgeRecord& c) { return applyTerrainRidges(h, c.mask, c.settings); }
156Result<int> execute(Heightmap& h, const TerraceRecord& c) { return applyTerrainTerrace(h, c.mask, c.settings); }
157Result<int> execute(Heightmap& h, const PowerRecord& c) { return applyTerrainPower(h, c.mask, c.power); }
158Result<int> execute(Heightmap& h, const CurveRecord& c) {
159 return applyTerrainHeightCurve(h, c.mask, c.curve, c.minimum, c.maximum);
160}
161Result<int> execute(Heightmap& h, const MixRecord& c) {
162 return applyTerrainHeightMix(h, c.local, c.global, c.settings);
163}
164template <class Record>
165Result<int> execute(SessionState& state, const Record& record) {
166 return execute(state.terrain, record);
167}
168} // namespace
170 std::variant<StampRecord, ContrastRecord, SmoothRecord, RidgeRecord, TerraceRecord, PowerRecord, CurveRecord,
171 MixRecord, SimulationResetRecord, ThermalRecord, HydraulicRecord>
173 bool enabled = true;
174};
175namespace {
176#define SESSION_STAMP_FIELDS(X) X(originX) X(originZ) X(spacingX) X(spacingZ) X(centerX) X(centerZ) X(width) X(depth) X(rotation) X(amplitude) X(baseHeight) X(blendStrength) X(operation)
177#define SESSION_SMOOTH_FIELDS(X) X(radius) X(verticality) X(strength)
178#define SESSION_RIDGE_FIELDS(X) X(mixStrength) X(exponent) X(strength) X(minimum) X(maximum) X(passes)
179#define SESSION_TERRACE_FIELDS(X) X(count) X(bevel) X(strength)
180#define SESSION_MIX_FIELDS(X) X(minimum) X(maximum) X(midpoint) X(strength) X(clipMinimum) X(clipMaximum)
181#define SESSION_WATER_FIELDS(X) X(spacingX) X(spacingZ) X(heightScale) X(waterScale) X(dt) X(precipitation) X(evaporation) X(flowAcceleration)
182#define SESSION_SEDIMENT_FIELDS(X) X(effect) X(depositRate) X(bankDeposit) X(bedDeposit)
183#define SESSION_THERMAL_FIELDS(X) X(spacingX) X(spacingZ) X(heightScale) X(reposeSlope) X(dt) X(iterations)
184#define SESSION_WRITE_FIELD(name) writer.scalar(value.name);
185#define SESSION_READ_FIELD(name) if (!reader.scalar(value.name)) return false;
186template <class T> void writeSessionValue(SessionWriter& writer, const T& value);
187template <class T> bool readSessionValue(SessionReader& reader, T& value);
188template <>
189void writeSessionValue(SessionWriter& writer, const TerrainStampSettings& value) {
190 SESSION_STAMP_FIELDS(SESSION_WRITE_FIELD) writer.scalar(value.smoothWidth);
191 writer.scalar(value.edgeFade);
192}
193template <>
194bool readSessionValue(SessionReader& reader, TerrainStampSettings& value) {
196 if (reader.version < 2) return value.operation <= TerrainStampOperation::Subtract;
197 return reader.scalar(value.smoothWidth) && reader.scalar(value.edgeFade) && value.smoothWidth >= 0 &&
198 value.edgeFade >= 0;
199}
200template <> void writeSessionValue(SessionWriter& writer, const TerrainSmoothSettings& value) { SESSION_SMOOTH_FIELDS(SESSION_WRITE_FIELD) }
201template <> bool readSessionValue(SessionReader& reader, TerrainSmoothSettings& value) { SESSION_SMOOTH_FIELDS(SESSION_READ_FIELD) return true; }
202template <> void writeSessionValue(SessionWriter& writer, const TerrainRidgeSettings& value) { SESSION_RIDGE_FIELDS(SESSION_WRITE_FIELD) }
203template <> bool readSessionValue(SessionReader& reader, TerrainRidgeSettings& value) { SESSION_RIDGE_FIELDS(SESSION_READ_FIELD) return true; }
204template <> void writeSessionValue(SessionWriter& writer, const TerrainTerraceSettings& value) { SESSION_TERRACE_FIELDS(SESSION_WRITE_FIELD) }
205template <> bool readSessionValue(SessionReader& reader, TerrainTerraceSettings& value) { SESSION_TERRACE_FIELDS(SESSION_READ_FIELD) return true; }
206template <> void writeSessionValue(SessionWriter& writer, const TerrainHeightMixSettings& value) { SESSION_MIX_FIELDS(SESSION_WRITE_FIELD) }
207template <> bool readSessionValue(SessionReader& reader, TerrainHeightMixSettings& value) { SESSION_MIX_FIELDS(SESSION_READ_FIELD) return true; }
208template <> void writeSessionValue(SessionWriter& writer, const TerrainWaterSettings& value) { SESSION_WATER_FIELDS(SESSION_WRITE_FIELD) }
209template <> bool readSessionValue(SessionReader& reader, TerrainWaterSettings& value) { SESSION_WATER_FIELDS(SESSION_READ_FIELD) return true; }
210template <> void writeSessionValue(SessionWriter& writer, const TerrainSedimentSettings& value) { SESSION_SEDIMENT_FIELDS(SESSION_WRITE_FIELD) }
211template <> bool readSessionValue(SessionReader& reader, TerrainSedimentSettings& value) { SESSION_SEDIMENT_FIELDS(SESSION_READ_FIELD) return true; }
212template <> void writeSessionValue(SessionWriter& writer, const TerrainThermalSettings& value) { SESSION_THERMAL_FIELDS(SESSION_WRITE_FIELD) }
213template <> bool readSessionValue(SessionReader& reader, TerrainThermalSettings& value) { SESSION_THERMAL_FIELDS(SESSION_READ_FIELD) return true; }
214#undef SESSION_WRITE_FIELD
215#undef SESSION_READ_FIELD
216#undef SESSION_STAMP_FIELDS
217#undef SESSION_SMOOTH_FIELDS
218#undef SESSION_RIDGE_FIELDS
219#undef SESSION_TERRACE_FIELDS
220#undef SESSION_MIX_FIELDS
221#undef SESSION_WATER_FIELDS
222#undef SESSION_SEDIMENT_FIELDS
223#undef SESSION_THERMAL_FIELDS
224} // namespace
227 std::shared_ptr<const SessionState> current;
228 std::vector<Command> commands;
229 int cursor = 0;
232 std::optional<SessionState> replayCandidate;
233 int replayNext = 0;
234 Impl() = default;
235 Impl(const Impl& other)
236 : baseline(other.baseline), current(other.current), commands(other.commands), cursor(other.cursor),
237 access(other.access) {}
243 auto next = std::make_shared<SessionState>();
244 next->terrain = baseline;
245 next->sediment = Heightmap(baseline.getWidth(), baseline.getHeight());
246 auto initialized = next->water.reset(baseline.getWidth(), baseline.getHeight());
247 if (!initialized.ok()) return initialized;
248 for (int i = 0; i < cursor; ++i) {
249 const auto& c = commands[size_t(i)];
250 if (!c.enabled) continue;
251 auto result = std::visit([&](const auto& operation) { return execute(*next, operation); }, c.operation);
252 if (!result.ok()) return result;
253 }
254 int changed = 0;
255 for (size_t i = 0; i < baseline.data().size(); ++i)
256 changed += next->terrain.data()[i] != (current ? current->terrain.data()[i] : baseline.data()[i]);
257 current = std::move(next);
259 }
260};
266 return impl_ ? impl_->access : TerrainSessionAccess::Editable;
267}
269 return impl_ ? impl_->replayStatus : TerrainSessionRunStatus::Idle;
270}
272 return impl_ ? impl_->replayNext : 0;
273}
274int TerrainGenerationSession::getOperationCount() const noexcept { return impl_ ? int(impl_->commands.size()) : 0; }
275int TerrainGenerationSession::getAppliedCount() const noexcept { return impl_ ? impl_->cursor : 0; }
279 Diagnostic::error(DiagnosticCode::InvalidArgument, "terrain.session: unknown access policy"));
280 if (impl_ && impl_->replayStatus == TerrainSessionRunStatus::Pending)
282 Diagnostic::error(DiagnosticCode::InvalidArgument, "terrain.session: cancel pending replay first"));
283 if (!impl_) impl_ = std::make_unique<Impl>();
284 impl_->access = access;
285 return Result<void>::success();
286}
289 return invalid("terrain.session.reset: editable session and finite baseline required");
290 auto candidate = std::make_unique<Impl>();
291 candidate->baseline = baseline;
292 auto initialized = candidate->rebuild();
293 if (!initialized.ok()) return initialized;
294 impl_.swap(candidate);
295 return Result<int>::success(int(baseline.data().size()));
296}
301Result<int> TerrainGenerationSession::append(Command command) {
302 if (!impl_ || !impl_->editable() || impl_->cursor == INT_MAX)
303 return invalid("terrain.session.append: initialized editable session required");
304 auto candidate = std::make_unique<Impl>(*impl_);
305 candidate->replayStatus = TerrainSessionRunStatus::Idle;
306 candidate->replayCandidate.reset();
307 candidate->replayNext = 0;
308 candidate->commands.resize(size_t(candidate->cursor));
309 candidate->commands.push_back(std::move(command));
310 ++candidate->cursor;
311 auto result = candidate->rebuild();
312 if (!result.ok()) return result;
313 impl_.swap(candidate);
314 return result;
315}
316
318 return append(Command{ContrastRecord{mask, strength, featureSize}});
319}
330 return append(Command{PowerRecord{mask, power}});
331}
333 float maximum) {
334 return append(Command{CurveRecord{mask, curve, minimum, maximum}});
335}
341 return append(Command{SimulationResetRecord{depth}});
342}
352 if (!impl_ || !impl_->current || !validRaster(output) || output.getWidth() != impl_->baseline.getWidth() ||
353 output.getHeight() != impl_->baseline.getHeight())
354 return invalid("terrain.session: initialized simulation and matching finite output required");
355 return publish(output, impl_->current->sediment.data());
356}
358 if (!impl_ || !impl_->current) return invalid("terrain.session: initialized simulation required");
359 return impl_->current->water.exportChannel(output, channel);
360}
361Result<int> TerrainGenerationSession::moveCursor(int delta) {
362 if (!impl_ || !impl_->editable() || (delta < 0 && impl_->cursor == 0) ||
363 (delta > 0 && size_t(impl_->cursor) == impl_->commands.size()))
364 return invalid("terrain.session: unavailable history or locked/empty session");
365 auto candidate = std::make_unique<Impl>(*impl_);
366 candidate->replayStatus = TerrainSessionRunStatus::Idle;
367 candidate->replayCandidate.reset();
368 candidate->replayNext = 0;
369 candidate->cursor += delta;
370 auto result = candidate->rebuild();
371 if (!result.ok()) return result;
372 impl_.swap(candidate);
373 return result;
374}
377 if (!impl_ || !impl_->editable())
380 "terrain.session.beginReplay: initialized editable session required"));
381 SessionState candidate;
382 candidate.terrain = impl_->baseline;
383 candidate.sediment = Heightmap(impl_->baseline.getWidth(), impl_->baseline.getHeight());
384 auto initialized = candidate.water.reset(impl_->baseline.getWidth(), impl_->baseline.getHeight());
385 if (!initialized.ok()) return Result<TerrainSessionRunStatus>::failure(initialized.status());
386 impl_->replayCandidate = std::move(candidate);
387 impl_->replayNext = 0;
388 impl_->replayStatus = TerrainSessionRunStatus::Pending;
389 return Result<TerrainSessionRunStatus>::success(impl_->replayStatus);
390}
392 if (!impl_ || impl_->replayStatus != TerrainSessionRunStatus::Pending || !impl_->replayCandidate ||
393 maxOperations <= 0)
396 "terrain.session.stepReplay: pending replay and positive operation budget required"));
397 int visited = 0;
398 while (impl_->replayNext < impl_->cursor && visited < maxOperations) {
399 const auto& command = impl_->commands[static_cast<std::size_t>(impl_->replayNext)];
400 if (command.enabled) {
401 auto executed = std::visit(
402 [&](const auto& operation) { return execute(*impl_->replayCandidate, operation); }, command.operation);
403 if (!executed.ok()) {
404 impl_->replayCandidate.reset();
405 impl_->replayStatus = TerrainSessionRunStatus::Failed;
406 return Result<TerrainSessionRunStatus>::failure(executed.status());
407 }
408 }
409 ++impl_->replayNext;
410 ++visited;
411 }
412 if (impl_->replayNext == impl_->cursor) {
413 impl_->current = std::make_shared<const SessionState>(std::move(*impl_->replayCandidate));
414 impl_->replayCandidate.reset();
415 impl_->replayStatus = TerrainSessionRunStatus::Completed;
416 }
417 return Result<TerrainSessionRunStatus>::success(impl_->replayStatus);
418}
420 if (!impl_ || impl_->replayStatus != TerrainSessionRunStatus::Pending)
422 Diagnostic::error(DiagnosticCode::InvalidArgument, "terrain.session.cancelReplay: no pending replay"));
423 impl_->replayCandidate.reset();
424 impl_->replayStatus = TerrainSessionRunStatus::Cancelled;
425 return Result<TerrainSessionRunStatus>::success(impl_->replayStatus);
426}
427Result<int> TerrainGenerationSession::undo() { return moveCursor(-1); }
430 if (!impl_ || !impl_->editable() || index < 0 || size_t(index) >= impl_->commands.size())
431 return invalid("terrain.session: valid operation and editable session required");
432 auto candidate = std::make_unique<Impl>(*impl_);
433 candidate->replayStatus = TerrainSessionRunStatus::Idle;
434 candidate->replayCandidate.reset();
435 candidate->replayNext = 0;
436 candidate->commands[size_t(index)].enabled = enabled;
437 auto result = candidate->rebuild();
438 if (!result.ok()) return result;
439 impl_.swap(candidate);
440 return result;
441}
443 if (!impl_ || index < 0 || size_t(index) >= impl_->commands.size())
445 Diagnostic::error(DiagnosticCode::InvalidArgument, "terrain.session: invalid operation index"));
446 return Result<bool>::success(impl_->commands[size_t(index)].enabled);
447}
449 if (!impl_ || !impl_->current || !validRaster(output) || output.getWidth() != impl_->current->terrain.getWidth() ||
450 output.getHeight() != impl_->current->terrain.getHeight())
451 return invalid("terrain.session: initialized terrain and matching finite output required");
452 return publish(output, impl_->current->terrain.data());
453}
454
456 if (!impl_ || !impl_->current || impl_->replayStatus == TerrainSessionRunStatus::Pending)
458 DiagnosticCode::InvalidArgument, "terrain.session.snapshot: initialized idle session required"));
459 if (impl_->commands.size() > kMaximumSessionCommands)
461 DiagnosticCode::InvalidArgument, "terrain.session.snapshot: command count exceeds limit"));
462 SessionWriter writer;
463 writeSessionHeightmap(writer, impl_->baseline);
464 writer.scalar(impl_->cursor);
465 writer.scalar(impl_->access);
466 writer.scalar(static_cast<std::uint32_t>(impl_->commands.size()));
467 for (const auto& command : impl_->commands) {
468 writer.scalar(command.enabled);
469 writer.scalar(static_cast<std::uint8_t>(command.operation.index()));
470 std::visit([&](const auto& value) {
471 using T = std::decay_t<decltype(value)>;
472 if constexpr (std::is_same_v<T, StampRecord>) {
473 writeSessionHeightmap(writer, value.stamp); writeSessionHeightmap(writer, value.local);
474 writeSessionHeightmap(writer, value.global); writeSessionValue(writer, value.settings);
475 } else if constexpr (std::is_same_v<T, ContrastRecord>) {
476 writeSessionHeightmap(writer, value.mask); writer.scalar(value.strength); writer.scalar(value.featureSize);
477 } else if constexpr (std::is_same_v<T, SmoothRecord> || std::is_same_v<T, RidgeRecord> ||
478 std::is_same_v<T, TerraceRecord>) {
479 writeSessionHeightmap(writer, value.mask); writeSessionValue(writer, value.settings);
480 } else if constexpr (std::is_same_v<T, PowerRecord>) {
481 writeSessionHeightmap(writer, value.mask); writer.scalar(value.power);
482 } else if constexpr (std::is_same_v<T, CurveRecord>) {
483 writeSessionHeightmap(writer, value.mask); writeSessionHeightmap(writer, value.curve);
484 writer.scalar(value.minimum); writer.scalar(value.maximum);
485 } else if constexpr (std::is_same_v<T, MixRecord>) {
486 writeSessionHeightmap(writer, value.local); writeSessionHeightmap(writer, value.global);
487 writeSessionValue(writer, value.settings);
488 } else if constexpr (std::is_same_v<T, SimulationResetRecord>) {
489 writer.scalar(value.depth);
490 } else if constexpr (std::is_same_v<T, ThermalRecord>) {
491 writeSessionValue(writer, value.settings);
492 } else {
493 writeSessionValue(writer, value.water); writeSessionValue(writer, value.sediment);
494 writeSessionValue(writer, value.thermal); writer.scalar(value.iterations);
495 }
496 }, command.operation);
497 }
498 if (writer.bytes.size() > kMaximumSessionSnapshotBytes)
500 DiagnosticCode::InvalidArgument, "terrain.session.snapshot: payload exceeds size limit"));
501 Value::Object root{{"payload", encodeSessionHex(writer.bytes)},
502 {"schema", "eve.procgen.terrain-generation-session"},
503 {"version", 2}};
504 return Value(std::move(root)).toJson();
505}
506
508 if ((impl_ && (impl_->access == TerrainSessionAccess::Locked ||
509 impl_->replayStatus == TerrainSessionRunStatus::Pending)) ||
510 json.size() > kMaximumSessionSnapshotBytes * 2 + 1024)
512 DiagnosticCode::InvalidArgument, "terrain.session.restore: editable idle session and bounded JSON required"));
513 auto decoded = Value::fromJson(json);
514 if (!decoded.ok()) return Result<void>::failure(decoded.status());
515 const auto* root = decoded.value().getIf<Value::Object>();
516 if (!root || root->size() != 3 || !root->contains("schema") || !root->contains("version") ||
517 !root->contains("payload"))
519 DiagnosticCode::InvalidArgument, "terrain.session.restore: missing or unknown root fields"));
520 const auto* schema = root->at("schema").getIf<std::string>();
521 const auto* version = root->at("version").getIf<std::int64_t>();
522 const auto* payload = root->at("payload").getIf<std::string>();
523 if (!schema || *schema != "eve.procgen.terrain-generation-session" || !version ||
524 (*version != 1 && *version != 2) || !payload)
526 DiagnosticCode::InvalidArgument, "terrain.session.restore: unsupported schema or version"));
527 auto bytes = decodeSessionHex(*payload);
528 if (!bytes.ok()) return Result<void>::failure(bytes.status());
529 SessionReader reader{static_cast<int>(*version), bytes.value()};
530 auto candidate = std::make_unique<Impl>();
531 std::uint32_t count{};
532 if (!readSessionHeightmap(reader, candidate->baseline) || !reader.scalar(candidate->cursor) ||
533 !reader.scalar(candidate->access) || !reader.scalar(count) || count > kMaximumSessionCommands ||
534 candidate->cursor < 0 || candidate->cursor > static_cast<int>(count) ||
535 (candidate->access != TerrainSessionAccess::Editable && candidate->access != TerrainSessionAccess::Locked))
537 DiagnosticCode::InvalidArgument, "terrain.session.restore: invalid session header"));
538 candidate->commands.reserve(count);
539 for (std::uint32_t index = 0; index < count; ++index) {
540 bool enabled{}; std::uint8_t kind{};
541 if (!reader.scalar(enabled) || !reader.scalar(kind) || kind > 10)
543 DiagnosticCode::InvalidArgument, "terrain.session.restore: invalid command header"));
544 Command command; command.enabled = enabled;
545 bool valid = true;
546 switch (kind) {
547 case 0: { StampRecord v; valid = readSessionHeightmap(reader, v.stamp) && readSessionHeightmap(reader, v.local) && readSessionHeightmap(reader, v.global) && readSessionValue(reader, v.settings); command.operation = std::move(v); break; }
548 case 1: { ContrastRecord v; valid = readSessionHeightmap(reader, v.mask) && reader.scalar(v.strength) && reader.scalar(v.featureSize); command.operation = std::move(v); break; }
549 case 2: { SmoothRecord v; valid = readSessionHeightmap(reader, v.mask) && readSessionValue(reader, v.settings); command.operation = std::move(v); break; }
550 case 3: { RidgeRecord v; valid = readSessionHeightmap(reader, v.mask) && readSessionValue(reader, v.settings); command.operation = std::move(v); break; }
551 case 4: { TerraceRecord v; valid = readSessionHeightmap(reader, v.mask) && readSessionValue(reader, v.settings); command.operation = std::move(v); break; }
552 case 5: { PowerRecord v; valid = readSessionHeightmap(reader, v.mask) && reader.scalar(v.power); command.operation = std::move(v); break; }
553 case 6: { CurveRecord v; valid = readSessionHeightmap(reader, v.mask) && readSessionHeightmap(reader, v.curve) && reader.scalar(v.minimum) && reader.scalar(v.maximum); command.operation = std::move(v); break; }
554 case 7: { MixRecord v; valid = readSessionHeightmap(reader, v.local) && readSessionHeightmap(reader, v.global) && readSessionValue(reader, v.settings); command.operation = std::move(v); break; }
555 case 8: { SimulationResetRecord v; valid = reader.scalar(v.depth); command.operation = v; break; }
556 case 9: { ThermalRecord v; valid = readSessionValue(reader, v.settings); command.operation = v; break; }
557 default: { HydraulicRecord v; valid = readSessionValue(reader, v.water) && readSessionValue(reader, v.sediment) && readSessionValue(reader, v.thermal) && reader.scalar(v.iterations); command.operation = v; break; }
558 }
560 DiagnosticCode::InvalidArgument, "terrain.session.restore: invalid command payload"));
561 candidate->commands.push_back(std::move(command));
562 }
563 if (reader.offset != reader.bytes.size())
565 DiagnosticCode::InvalidArgument, "terrain.session.restore: trailing payload data"));
566 auto validation = std::make_unique<Impl>(*candidate);
567 validation->cursor = static_cast<int>(validation->commands.size());
568 for (auto& command : validation->commands) command.enabled = true;
569 auto validated = validation->rebuild();
570 if (!validated.ok()) return Result<void>::failure(validated.status());
571 auto rebuilt = candidate->rebuild();
572 if (!rebuilt.ok()) return Result<void>::failure(rebuilt.status());
573 impl_.swap(candidate);
574 return Result<void>::success();
575}
576} // namespace eve::procgen
ActionParameterOperation operation
Value::Object payload
int root
Definition AnimSmr.cpp:119
std::string output
std::string terrain
std::size_t cursor
int mask
bool changed
ScriptComponentRecord record
Definition ECS.cpp:228
double raw
float strength
float maximum[3]
float minimum[3]
float v
std::int32_t c
int h
std::uint32_t height
std::uint32_t width
std::string local
size_t offset
Poco::JSON::Object::Ptr result
std::uint64_t bytes
bool valid
OceanWakeSettings settings
ssq::Object water
Object::Ptr value
float power
Definition RockMesh.cpp:23
std::string text
std::string kind
int count
Heightmap curve
#define SESSION_WRITE_FIELD(name)
#define SESSION_THERMAL_FIELDS(X)
#define SESSION_SMOOTH_FIELDS(X)
#define SESSION_SEDIMENT_FIELDS(X)
#define SESSION_WATER_FIELDS(X)
#define SESSION_MIX_FIELDS(X)
Heightmap stamp
#define SESSION_TERRACE_FIELDS(X)
TerrainThermalSettings thermal
Heightmap global
#define SESSION_STAMP_FIELDS(X)
#define SESSION_RIDGE_FIELDS(X)
#define SESSION_READ_FIELD(name)
Heightmap sediment
int iterations
Definition TreeMesh.cpp:448
std::uint32_t depth
uint32_t index
Owning, renderer-independent dynamic values.
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.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
In-memory terrain heightmap: a dense float grid (row-major, index = y * width + x) materialized from ...
Definition Heightmap.h:21
int getHeight() const
Returns the height.
Definition Heightmap.cpp:17
const std::vector< float > & data() const
Data.
Definition Heightmap.h:48
int getWidth() const
Returns the width.
Definition Heightmap.cpp:16
Owned in-memory terrain operation session; records native stamps, scalar effects and erosion....
Result< int > resetSimulation(float depth=0)
Record a simulation reset: zero sediment, flux and velocity; set uniform nonnegative water depth....
Result< TerrainSessionRunStatus > beginReplay()
Start replaying the applied history into a private candidate without changing current terrain.
Result< std::string > snapshotJson() const
Serialize schema version 2 with the complete replayable operation history.
Result< TerrainSessionRunStatus > stepReplay(int maxOperations)
Execute at most maxOperations commands and publish once when the candidate completes.
Result< int > power(const Heightmap &mask, float power)
Record power transform; copies all borrowed inputs and values.
Result< int > copySediment(Heightmap &output) const
Copy signed current sediment into a matching finite output, including while locked.
Result< bool > operationEnabled(int index) const
Read a command's enabled flag, or InvalidArgument for an out-of-range history index.
Result< int > exportWater(Heightmap &output, TerrainWaterChannel channel) const
Copy a raw water channel into a matching finite output, including while locked.
Result< int > terrace(const Heightmap &mask, const TerrainTerraceSettings &settings)
Record terracing; copies all borrowed inputs and values.
Result< int > contrast(const Heightmap &mask, float strength, float featureSize)
Record nine-tap contrast; copies all borrowed inputs and values.
Result< int > heightCurve(const Heightmap &mask, const Heightmap &curve, float minimum, float maximum)
Record height-curve transform; copies all borrowed inputs and values.
int getReplayCompletedOperations() const noexcept
Return commands visited by the current or most recent staged replay.
Result< int > hydraulic(const TerrainWaterSettings &water, const TerrainSedimentSettings &sediment, const TerrainThermalSettings &thermal, int iterations)
Record complete water/sediment/thermal iterations using preceding simulation state....
Result< int > copyTerrain(Heightmap &output) const
Copy current terrain into an existing matching finite output; allowed while locked.
Result< int > ridges(const Heightmap &mask, const TerrainRidgeSettings &settings)
Record ridge iteration; copies all borrowed inputs and values.
Result< int > setOperationEnabled(int index, bool enabled)
Toggle a command and replay the applied prefix atomically; index is history-local,...
Result< void > setAccess(TerrainSessionAccess access)
Change only the edit policy; unlocking is always permitted, invalid enum values are rejected.
Result< int > smooth(const Heightmap &mask, const TerrainSmoothSettings &settings)
Record two-pass smoothing; copies all borrowed inputs and values.
Result< int > heightMix(const Heightmap &local, const Heightmap &global, const TerrainHeightMixSettings &settings)
Record height mixing; copies all borrowed inputs and values.
Result< int > redo()
Move the applied prefix forward one command and replay; no redo returns InvalidArgument.
TerrainSessionAccess getAccess() const noexcept
Read current edit policy; moved-from sessions are editable.
Result< void > restoreJson(const std::string &json)
Atomically restore schema versions 1/2 (v1 migrates with zero smoothWidth/edgeFade) and rebuild the a...
int getOperationCount() const noexcept
Count all recorded commands, including the redo suffix.
TerrainGenerationSession()
Construct an empty editable session.
Result< int > stamp(const Heightmap &stamp, const TerrainStampSettings &settings, const Heightmap &localMask, const Heightmap &globalMask)
Append an owned stamp command, truncating redo only on success; locked sessions reject it.
Result< TerrainSessionRunStatus > cancelReplay()
Cancel a pending replay and discard its private candidate without changing current terrain.
Result< int > reset(const Heightmap &baseline)
Copy a finite baseline, zero sediment/water and clear history atomically; locked sessions reject rese...
Result< int > undo()
Move the applied prefix back one command and replay; no history returns InvalidArgument.
Result< int > replay()
Re-evaluate the applied history prefix from baseline atomically; locked sessions reject it.
Result< int > thermal(const TerrainThermalSettings &settings)
Record thermal erosion using accumulated sediment; water is preserved. Settings are copied.
TerrainSessionRunStatus getReplayStatus() const noexcept
Return the staged replay lifecycle status.
int getAppliedCount() const noexcept
Count commands in the applied prefix, including disabled commands.
~TerrainGenerationSession()
Destroy owned terrain and command snapshots.
Result< int > publish(Heightmap &target, std::vector< float > candidate)
Publish.
bool validRaster(const Heightmap &map)
Valid raster.
Result< int > invalid(std::string message)
Invalid.
Result< int > applyTerrainTerrace(Heightmap &target, const Heightmap &mask, const TerrainTerraceSettings &settings)
Terrace scalar heights using nearest-even rounding and the shader's one-sided bevel.
Result< int > applyTerrainContrast(Heightmap &target, const Heightmap &mask, float strength, float featureSize)
Apply the nine-tap Pcg contrast equation to native scalar heights.
TerrainSessionRunStatus
Observable lifecycle of a caller-driven staged session replay.
Result< int > applyTerrainHeightMix(Heightmap &target, const Heightmap &local, const Heightmap &global, const TerrainHeightMixSettings &settings)
Mix centered local brush heights into terrain, then globally mask and clip.
Result< int > applyTerrainSmooth(Heightmap &target, const Heightmap &mask, const TerrainSmoothSettings &settings)
Apply Pcg's horizontal then vertical seven-pair weighted smooth passes.
Result< int > applyTerrainPower(Heightmap &target, const Heightmap &mask, float power)
Apply the Pcg PowerOf control: lerp(height,pow(height,4-power),mask).
TerrainSessionAccess
Edit policy for the owned operation history and terrain.
TerrainWaterChannel
Stored scalar channels; Pcg erosion masks read FluxRight or VelocityX, not vector magnitude.
Result< int > applyTerrainStamp(Heightmap &target, const Heightmap &stamp, const TerrainStampSettings &s, const Heightmap &localMask, const Heightmap &globalMask)
Apply a rotated, bilinearly sampled stamp; publish only after all checks succeed.
Result< int > applyTerrainRidges(Heightmap &target, const Heightmap &mask, const TerrainRidgeSettings &settings)
Apply ordered horizontal/vertical ridge powers, neighbor mixing and per-pass clipping.
Result< int > applyTerrainThermal(Heightmap &heights, Heightmap &sediment, const TerrainThermalSettings &settings)
Apply the source thermal equation, publishing height and sediment together.
Result< int > applyTerrainHeightCurve(Heightmap &target, const Heightmap &mask, const Heightmap &curve, float minimum, float maximum)
Apply the height-transform shader's smoothstep and one-row height curve.
std::vector< RuntimeTensor > execute(const Node &n, const std::vector< const RuntimeTensor * > &in, OnnxCompute *compute)
Execute.
bool enabled
std::variant< StampRecord, ContrastRecord, SmoothRecord, RidgeRecord, TerraceRecord, PowerRecord, CurveRecord, MixRecord, SimulationResetRecord, ThermalRecord, HydraulicRecord > operation
Mix-height scalar controls; delta scale is maximum-minimum, independent of clipping bounds....
Ridge controls in caller height units, with explicit clipping bounds. Defaults match the Pcg packed s...
Effective sediment coefficients from Hydraulic.compute, after UI conversion. The source hardcodes har...
Two-pass smoothing controls; radius in texels, verticality in [-1,1], strength in [0,...
Value configuration for a rectangular stamp in world X/Z coordinates.
Terrace frequency in inverse height units, interior bevel in [0,1], strength in [0,...
Explicit simulation controls for the Pcg eight-neighbor thermal kernel. Height differences are multip...
Explicit constants for the source hydraulic water-flow equations, after UI unit conversion.