载入中...
搜索中...
未找到
Procgen.cpp
浏览该文件的文档.
1#include "procgen/Procgen.h"
2#include "graphics/Shader.h"
3#include "procgen/Biome.h"
4#include "procgen/GridGraph.h"
5#include "procgen/MeshGraph.h"
6#include "procgen/Palette.h"
16#include "procgen/SpatialData.h"
25
26#include "common/Capability.h"
30#include "procgen/BiomeScript.h"
44
45#include "image/ImageData.h"
46
52#include "procgen/JsonExport.h"
54#include "procgen/PcgMeshLod.h"
57#include "procgen/Semantic.h"
69#include "procgen/shaders/terrain_material_frag_spv.inc"
70#include "procgen/shaders/terrain_water_compat_frag_spv.inc"
73
74#include "data/ByteData.h"
75#include "graphics/Graphics.h"
77#include "graphics/Mesh.h"
78#include "graphics/Texture.h"
79#include "image/ImageData.h"
80
81#include <simplesquirrel/simplesquirrel.hpp>
82
83#include <any>
84#include <charconv>
85#include <cstdint>
86#include <functional>
87#include <memory>
88#include <mutex>
89#include <optional>
90#include <sstream>
91#include <stdexcept>
92#include <unordered_map>
93#include <unordered_set>
94#include <utility>
95#include <vector>
96
97
98namespace eve::procgen {
99
101
102Procgen::Procgen() : ownership_(std::make_unique<OwnershipState>()) {
103 publishLiveProcgen(this);
109 // Sensible pixel-RPG default palette (games override GIDs to match tileset).
110 setPaletteGid("default", "empty", 0);
111 setPaletteGid("default", "wall", 1);
112 setPaletteGid("default", "floor", 2);
113 setPaletteGid("default", "corridor", 2);
114 setPaletteGid("default", "door", 3);
115 setPaletteGid("default", "water", 4);
116 setPaletteGid("default", "sand", 5);
117 setPaletteGid("default", "grass", 6);
118 setPaletteGid("default", "dirt", 7);
119 setPaletteGid("default", "stone", 8);
120 setPaletteGid("default", "snow", 9);
121 setPaletteGid("default", "road", 3);
122 setPaletteGid("dungeon_default", "empty", 0);
123 setPaletteGid("dungeon_default", "wall", 1);
124 setPaletteGid("dungeon_default", "floor", 2);
125 setPaletteGid("dungeon_default", "corridor", 2);
126 setPaletteGid("dungeon_default", "door", 3);
127 setPaletteGid("dungeon_default", "road", 3);
128}
129
131
134 if (!view.isBound())
136 eve::DiagnosticCode::StaleHandle, "pointData point-set handle is stale", "points", {}, "procgen.squirrel"));
137 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::fromPoints(*view)));
138}
139
140eve::Result<ProcgenSpatialDataHandleRef> Procgen::boxVolumeHandle(float minX, float minY, float minZ, float maxX,
141 float maxY, float maxZ) {
142 return ownership_->spatialData.emplace(
143 std::make_unique<SpatialData>(SpatialData::box(minX, minY, minZ, maxX, maxY, maxZ)));
144}
145
147 if (radius <= 0.f)
149 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "sphereVolume radius must be positive",
150 "radius", {}, "procgen.squirrel"));
151 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::sphere(x, y, z, radius)));
152}
153
155 float minY, float maxY) {
156 auto points = resolvePointSet(controlPoints);
157 if (!points.isBound() || points->getCount() < 3 || !std::isfinite(minY) || !std::isfinite(maxY))
160 "polygonVolume requires a live set with at least three points and finite heights",
161 "controlPoints", {}, "procgen.squirrel"));
162 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::polygon(*points, minY, maxY)));
163}
164
166 float radius) {
167 auto view = resolvePointSet(controlPoints);
168 if (!view.isBound() || view->getCount() < 2 || radius < 0.f)
171 "splineData requires a live set with at least two points and non-negative radius", "controlPoints", {},
172 "procgen.squirrel"));
173 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::spline(*view, radius)));
174}
175
177 float originX, float originZ, float cellSize,
178 float heightScale) {
179 auto view = resolveHeightmap(heightmap);
180 if (!view.isBound() || view->getWidth() <= 0 || view->getHeight() <= 0 || cellSize <= 0.f)
183 "heightfieldData requires a live non-empty heightmap and positive cell size", "heightmap", {},
184 "procgen.squirrel"));
185 return ownership_->spatialData.emplace(
186 std::make_unique<SpatialData>(SpatialData::heightfield(*view, originX, originZ, cellSize, heightScale)));
187}
188
190 float originZ, float cellSize, float minValue,
191 float maxValue, float minY, float maxY) {
193 if (!view.isBound() || view->getWidth() <= 0 || view->getHeight() <= 0 || cellSize <= 0.f)
196 "textureMaskData requires a live non-empty scalar map and positive cell size",
197 "values", {}, "procgen.squirrel"));
198 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(
199 SpatialData::textureMask(*view, originX, originZ, cellSize, minValue, maxValue, minY, maxY)));
200}
201
203 float tolerance) {
204 auto view = resolveMeshBuild(mesh);
205 if (!view.isBound() || view->getVertexCount() < 3 || view->getIndexCount() < 3 || tolerance < 0.f)
208 "meshSurfaceData requires a live triangle mesh and non-negative tolerance", "mesh",
209 {}, "procgen.squirrel"));
210 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::meshSurface(*view, tolerance)));
211}
212
215 auto a = resolveSpatialData(left);
216 auto b = resolveSpatialData(right);
217 if (!a.isBound() || !b.isBound())
219 eve::DiagnosticCode::StaleHandle, "unionSpatial input handle is stale", "spatial", {}, "procgen.squirrel"));
220 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::unite(*a, *b)));
221}
222
225 auto a = resolveSpatialData(left);
226 auto b = resolveSpatialData(right);
227 if (!a.isBound() || !b.isBound())
229 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "intersectSpatial input handle is stale",
230 "spatial", {}, "procgen.squirrel"));
231 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::intersect(*a, *b)));
232}
233
236 auto a = resolveSpatialData(left);
237 auto b = resolveSpatialData(right);
238 if (!a.isBound() || !b.isBound())
240 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "differenceSpatial input handle is stale",
241 "spatial", {}, "procgen.squirrel"));
242 return ownership_->spatialData.emplace(std::make_unique<SpatialData>(SpatialData::subtract(*a, *b)));
243}
244
246 uint32_t seed, float jitter) {
248 if (!view.isBound() || spacing <= 0.f)
251 "sampleSpatial requires live spatial data and positive spacing", "spatial", {}, "procgen.squirrel"));
252 return ownership_->points.emplace(std::make_unique<PointSet>(view->sample(spacing, seed, jitter)));
253}
254
256 ProcgenSpatialDataHandleRef spatial, bool invert) {
259 if (!points.isBound() || !domain.isBound())
261 eve::DiagnosticCode::StaleHandle, "filterSpatial input handle is stale", "input", {}, "procgen.squirrel"));
262 return ownership_->points.emplace(std::make_unique<PointSet>(domain->filter(*points, invert)));
263}
264
269 if (!points.isBound() || !domain.isBound())
271 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "projectToSpatial input handle is stale", "input",
272 {}, "procgen.squirrel"));
273 return ownership_->points.emplace(std::make_unique<PointSet>(domain->project(*points)));
274}
275
279
281 return ownership_->spatialData.erase(reference);
282}
283
285 return ownership_->spatialData.isStale(reference);
286}
287
289 return ownership_->runtimeGenerations.emplace(std::make_unique<RuntimeGeneration>(worldSeed));
290}
291
293 return ownership_->lsystems.emplace(std::make_unique<LSystem>());
294}
295
300
304
309
314
319
323
327
331
335
339
343
345 return ownership_->runtimeGenerations.erase(reference);
346}
348 return ownership_->pointGraphs.erase(reference);
349}
351 return ownership_->meshModifierGraphs.erase(reference);
352}
354 return ownership_->meshDeformationSessions.erase(reference);
355}
357 return ownership_->dynamicMeshUvPaintSessions.erase(reference);
358}
360 return ownership_->splinePaths.erase(reference);
361}
363 return ownership_->gridGraphs.erase(reference);
364}
366 return ownership_->meshGraphs.erase(reference);
367}
369 return ownership_->biomeRules.erase(reference);
370}
372 return ownership_->shapeGrammars.erase(reference);
373}
375
377 return ownership_->runtimeGenerations.isStale(reference);
378}
380 return ownership_->pointGraphs.isStale(reference);
381}
383 return ownership_->meshModifierGraphs.isStale(reference);
384}
386 return ownership_->meshDeformationSessions.isStale(reference);
387}
389 return ownership_->dynamicMeshUvPaintSessions.isStale(reference);
390}
392 return ownership_->splinePaths.isStale(reference);
393}
395 return ownership_->gridGraphs.isStale(reference);
396}
398 return ownership_->meshGraphs.isStale(reference);
399}
401 return ownership_->biomeRules.isStale(reference);
402}
404 return ownership_->shapeGrammars.isStale(reference);
405}
407 return ownership_->lsystems.isStale(reference);
408}
409
410uint32_t Procgen::deriveSeed(uint32_t parent, const std::string& scope) const {
412}
413
415 Procgen* module = Procgen::create();
416 module->ownership_->compatMessage.clear();
417
418 if (name.empty()) {
419 module->ownership_->compatMessage = "beginSystem: name is empty";
421 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, module->ownership_->compatMessage, "context",
422 {}, "procgen.squirrel"));
423 }
424 auto context = std::make_unique<ProcgenContext>(name, seed);
425 const auto previous = module->ownership_->systems.find(name);
426 if (previous != module->ownership_->systems.end()) context->stageCache_ = previous->second.stageCache;
427 return module->ownership_->contexts.emplace(std::move(context));
428}
429
431 const std::string& buildKey) {
432 Procgen* module = Procgen::create();
433 module->ownership_->compatMessage.clear();
434 if (name.empty()) {
435 module->ownership_->compatMessage = "beginCachedSystem: name is empty";
437 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, module->ownership_->compatMessage, "context",
438 {}, "procgen.squirrel"));
439 }
440 if (buildKey.empty()) {
441 module->ownership_->compatMessage = "beginCachedSystem: build key is empty";
443 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, module->ownership_->compatMessage, "buildKey",
444 {}, "procgen.squirrel"));
445 }
446 const uint32_t normalizedSeed = seed ? seed : 1u;
447 const auto found = module->ownership_->systems.find(name);
448 const bool cacheHit = found != module->ownership_->systems.end() && found->second.seed == normalizedSeed &&
449 found->second.buildKey == buildKey;
450 auto context = std::make_unique<ProcgenContext>(name, normalizedSeed, buildKey, cacheHit);
451 if (found != module->ownership_->systems.end()) context->stageCache_ = found->second.stageCache;
452 return module->ownership_->contexts.emplace(std::move(context));
453}
454
456 Procgen* module = liveProcgen();
457 if (!module) return {};
458 return module->ownership_->contexts.resolve(reference);
459}
460
462 Procgen* module = liveProcgen();
463 if (!module)
465 eve::DiagnosticCode::StaleHandle, "Procgen module is no longer loaded", "context", {}, "procgen.squirrel"));
466 return module->ownership_->contexts.erase(reference);
467}
468
470 if (!reference.isValid()) return false;
471 Procgen* module = liveProcgen();
472 return !module || module->ownership_->contexts.isStale(reference);
473}
474
477 if (!view.isBound())
479 "commitSystem context handle is stale", "context", {},
480 "procgen.squirrel"));
481 ProcgenContext* context = view.get();
482 if (!context->isActive())
484 "commitSystem: transaction is closed", "context", {},
485 "procgen.squirrel"));
486 if (context->hasFailed()) {
487 const std::string error = context->getError();
488 context->close();
490 "context", {}, "procgen.squirrel"));
491 }
492 if (!context->openTraces_.empty()) {
493 const std::string trace = context->openTraces_.back().name;
494 context->close();
496 "commitSystem: unfinished trace '" + trace + "'",
497 "context", {}, "procgen.squirrel"));
498 }
499
500 const auto current = ownership_->systems.find(context->name_);
501 if (current != ownership_->systems.end()) ownership_->previousSystems[context->name_] = current->second;
502 auto& snapshot = ownership_->systems[context->name_];
503 snapshot.seed = context->seed_;
504 snapshot.revision = snapshot.revision + 1u;
505 snapshot.buildKey = context->buildKey_;
506 snapshot.outputs = context->outputs_;
507 snapshot.outputOrder = context->outputOrder_;
508 snapshot.debugStages = context->debugStages_;
509 snapshot.debugStageOrder = context->debugStageOrder_;
510 snapshot.stageCache = context->stageCache_;
511 snapshot.stageCacheHits = context->stageCacheHits_;
512 snapshot.stageCacheMisses = context->stageCacheMisses_;
513 snapshot.traces = context->traces_;
514 context->close();
516}
517
520 if (!view.isBound())
522 "abortSystem context handle is stale", "context", {},
523 "procgen.squirrel"));
524 view->abort();
526}
527
529 ownership_->previousSystems.erase(name);
530 if (ownership_->systems.erase(name) == 0)
532 eve::DiagnosticCode::NotFound, "procgen system was not committed", "system", {}, "procgen.squirrel"));
534}
535
536bool Procgen::hasSystem(const std::string& name) const {
537 return ownership_->systems.find(name) != ownership_->systems.end();
538}
539
540uint64_t Procgen::getSystemRevision(const std::string& name) const {
541 const auto found = ownership_->systems.find(name);
542 return found == ownership_->systems.end() ? 0u : found->second.revision;
543}
544
545uint32_t Procgen::getSystemSeed(const std::string& name) const {
546 const auto found = ownership_->systems.find(name);
547 return found == ownership_->systems.end() ? 0u : found->second.seed;
548}
549
550std::string Procgen::getSystemBuildKey(const std::string& name) const {
551 const auto found = ownership_->systems.find(name);
552 return found == ownership_->systems.end() ? std::string() : found->second.buildKey;
553}
554
555int Procgen::getSystemOutputCount(const std::string& name) const {
556 const auto found = ownership_->systems.find(name);
557 return found == ownership_->systems.end() ? 0 : int(found->second.outputOrder.size());
558}
559
560std::string Procgen::getSystemOutputName(const std::string& name, int index) const {
561 const auto found = ownership_->systems.find(name);
562 if (found == ownership_->systems.end() || index < 0 || index >= int(found->second.outputOrder.size())) return {};
563 return found->second.outputOrder[size_t(index)];
564}
565
566int Procgen::getSystemDebugStageCount(const std::string& name) const {
567 const auto found = ownership_->systems.find(name);
568 return found == ownership_->systems.end() ? 0 : int(found->second.debugStageOrder.size());
569}
570
571std::string Procgen::getSystemDebugStageName(const std::string& name, int index) const {
572 const auto found = ownership_->systems.find(name);
573 if (found == ownership_->systems.end() || index < 0 || index >= int(found->second.debugStageOrder.size()))
574 return {};
575 return found->second.debugStageOrder[size_t(index)];
576}
577
579 const std::string& outputName) const {
580 const auto system = ownership_->systems.find(name);
581 if (system == ownership_->systems.end())
583 eve::DiagnosticCode::NotFound, "procgen system is not committed", "system", {}, "procgen.squirrel"));
584 const auto output = system->second.outputs.find(outputName);
585 if (output == system->second.outputs.end())
587 eve::DiagnosticCode::NotFound, "procgen system output was not found", "output", {}, "procgen.squirrel"));
588 return ownProcgenObject(ownership_->points, std::make_unique<PointSet>(output->second));
589}
590
592 const std::string& stageName) const {
593 const auto system = ownership_->systems.find(name);
594 if (system == ownership_->systems.end())
596 eve::DiagnosticCode::NotFound, "procgen system is not committed", "system", {}, "procgen.squirrel"));
597 const auto stage = system->second.debugStages.find(stageName);
598 if (stage == system->second.debugStages.end())
600 eve::DiagnosticCode::NotFound, "procgen debug stage was not found", "stage", {}, "procgen.squirrel"));
601 return ownProcgenObject(ownership_->points, std::make_unique<PointSet>(stage->second));
602}
603
605 const std::string& stageName) const {
606 const auto system = ownership_->previousSystems.find(name);
607 if (system == ownership_->previousSystems.end())
609 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "procgen system has no previous revision", "system",
610 {}, "procgen.squirrel"));
611 const auto stage = system->second.debugStages.find(stageName);
612 if (stage == system->second.debugStages.end())
614 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "previous procgen debug stage was not found", "stage",
615 {}, "procgen.squirrel"));
616 return ownProcgenObject(ownership_->points, std::make_unique<PointSet>(stage->second));
617}
618
619uint64_t Procgen::getPreviousSystemRevision(const std::string& name) const {
620 const auto found = ownership_->previousSystems.find(name);
621 return found == ownership_->previousSystems.end() ? 0u : found->second.revision;
622}
623
624std::string Procgen::getSystemDebugReport(const std::string& name) const {
625 const auto found = ownership_->systems.find(name);
626 if (found == ownership_->systems.end()) return "system '" + name + "' is not committed";
627 const auto& snapshot = found->second;
628 std::ostringstream report;
629 report << name << " revision=" << snapshot.revision << " seed=" << snapshot.seed;
630 if (!snapshot.buildKey.empty()) report << " buildKey=" << snapshot.buildKey;
631 report << " stageCache=" << snapshot.stageCacheHits << " hit/" << snapshot.stageCacheMisses << " miss";
632 for (const auto& trace : snapshot.traces) {
633 report << "\n " << trace.name << " input=" << trace.inputCount << " output=" << trace.outputCount
634 << " ms=" << trace.milliseconds;
635 }
636 for (const auto& outputName : snapshot.outputOrder) {
637 report << "\n output " << outputName << " points=" << snapshot.outputs.at(outputName).getCount();
638 }
639 for (const auto& stageName : snapshot.debugStageOrder) {
640 report << "\n debug " << stageName << " points=" << snapshot.debugStages.at(stageName).getCount();
641 }
642 return report.str();
643}
644
645std::string Procgen::getSystemDebugDiffReport(const std::string& name) const {
646 const auto current = ownership_->systems.find(name);
647 if (current == ownership_->systems.end()) return "system '" + name + "' is not committed";
648 const auto previous = ownership_->previousSystems.find(name);
649 if (previous == ownership_->previousSystems.end()) return name + " has no previous revision";
650
651 std::ostringstream report;
652 report << name << " revision=" << previous->second.revision << " -> " << current->second.revision;
653 for (const auto& stageName : current->second.debugStageOrder) {
654 const int currentCount = current->second.debugStages.at(stageName).getCount();
655 const auto oldStage = previous->second.debugStages.find(stageName);
656 const int oldCount = oldStage == previous->second.debugStages.end() ? 0 : oldStage->second.getCount();
657 report << "\n debug " << stageName << " points=" << currentCount << " delta=";
658 if (currentCount >= oldCount) report << "+";
659 report << currentCount - oldCount;
660 }
661 for (const auto& stageName : previous->second.debugStageOrder) {
662 if (current->second.debugStages.find(stageName) != current->second.debugStages.end()) continue;
663 report << "\n debug " << stageName << " removed delta=-"
664 << previous->second.debugStages.at(stageName).getCount();
665 }
666 return report.str();
667}
668
669bool Procgen::runGenerate(const std::string& algorithmId, const Params& params, Grid2D& out) {
670 ownership_->compatMessage.clear();
672 if (!GeneratorRegistry::instance().generate(algorithmId, params, out, ownership_->compatMessage)) {
673 if (ownership_->compatMessage.empty()) ownership_->compatMessage = "generate failed";
674 return false;
675 }
676 return true;
677}
678
682 if (!input.isBound())
684 eve::DiagnosticCode::StaleHandle, "generate parameters handle is stale", "params", {}, "procgen.squirrel"));
685 auto grid = std::make_unique<Grid2D>();
686 if (!runGenerate(algorithmId, *input, *grid))
689 ownership_->compatMessage.empty() ? "generate failed" : ownership_->compatMessage,
690 "algorithm", {}, "procgen.squirrel"));
691 return ownProcgenObject(ownership_->grids, std::move(grid));
692}
693
696 auto paramsView = Procgen::resolve(params);
697 auto outputView = resolveOutput(output);
698 if (!paramsView.isBound())
700 "generateTo parameter handle is stale", "params", {},
701 "procgen.squirrel"));
702 if (!outputView.isBound())
704 eve::DiagnosticCode::StaleHandle, "generateTo output handle is stale", "output", {}, "procgen.squirrel"));
705 Grid2D grid;
706 if (!runGenerate(algorithmId, *paramsView, grid))
709 ownership_->compatMessage.empty() ? "generateTo failed" : ownership_->compatMessage,
710 "algorithm", {}, "procgen.squirrel"));
711
712 const std::string target = outputView->getTarget();
713 if (target == "grid") {
715 eve::DiagnosticCode::InvalidArgument, "generateTo: target 'grid' has no sink; use generateHandle()",
716 "output.target", {}, "procgen.squirrel"));
717 }
718 if (target == "tilelayer") {
719 auto* layer = outputView->getLayer();
720 if (!layer)
722 "generateTo: tilelayer target has no layer",
723 "output.layer", {}, "procgen.squirrel"));
724 if (!ownership_->palettes.applyToLayer(grid, outputView->getPalette(), layer, &ownership_->compatMessage))
726 eve::DiagnosticCode::Failed, ownership_->compatMessage, "output", {}, "procgen.squirrel"));
728 }
729 if (target == "json") {
730 if (!writeGridJson(grid, outputView->getPath(), &ownership_->compatMessage))
732 eve::DiagnosticCode::Failed, ownership_->compatMessage, "output.path", {}, "procgen.squirrel"));
734 }
736 eve::DiagnosticCode::InvalidArgument, "generateTo: unknown target '" + target + "' (use grid|tilelayer|json)",
737 "output.target", {}, "procgen.squirrel"));
738}
739
741 auto view = Procgen::resolve(grid);
742 if (!view.isBound())
744 eve::DiagnosticCode::StaleHandle, "applyToLayer grid handle is stale", "grid", {}, "procgen.squirrel"));
745 if (!ownership_->palettes.applyToLayer(*view, palette, &layer, &ownership_->compatMessage))
747 "palette", {}, "procgen.squirrel"));
749}
750
751void Procgen::setPaletteGid(const std::string& palette, const std::string& semantic, int gid) {
752 ownership_->palettes.setGid(palette, semantic, gid);
753}
754
755int Procgen::getPaletteGid(const std::string& palette, const std::string& semantic) const {
756 return ownership_->palettes.getGid(palette, semantic);
757}
758
759namespace {
760
761const ParamDescriptor* algorithmParam(const std::string& algorithmId, int index) {
763 if (!descriptor || index < 0 || index >= int(descriptor->params.size())) return nullptr;
764 return &descriptor->params[size_t(index)];
765}
766
767} // namespace
768
770 ownership_->algorithmIdsCache = GeneratorRegistry::instance().list();
771 return int(ownership_->algorithmIdsCache.size());
772}
773
774std::string Procgen::getAlgorithmId(int index) const {
775 if (ownership_->algorithmIdsCache.empty()) ownership_->algorithmIdsCache = GeneratorRegistry::instance().list();
776 if (index < 0 || index >= int(ownership_->algorithmIdsCache.size())) return {};
777 return ownership_->algorithmIdsCache[size_t(index)];
778}
779
780bool Procgen::hasAlgorithm(const std::string& algorithmId) const {
781 return GeneratorRegistry::instance().has(algorithmId);
782}
783
785 const std::string& algorithmId) {
786 const RecipeDescriptor* schema = GeneratorRegistry::instance().descriptor(algorithmId);
787 if (!schema)
789 eve::DiagnosticCode::NotFound, "algorithm schema was not found", "algorithm", {}, "procgen.squirrel"));
791}
792
793std::string Procgen::getAlgorithmDisplayName(const std::string& algorithmId) const {
795 return descriptor ? descriptor->displayName : std::string{};
796}
797
798std::string Procgen::getAlgorithmCategory(const std::string& algorithmId) const {
800 return descriptor ? descriptor->category : std::string{};
801}
802
803int Procgen::getAlgorithmParamCount(const std::string& algorithmId) const {
805 return descriptor ? int(descriptor->params.size()) : 0;
806}
807
808std::string Procgen::getAlgorithmParamKey(const std::string& algorithmId, int index) const {
809 const ParamDescriptor* param = algorithmParam(algorithmId, index);
810 return param ? param->key : std::string{};
811}
812
813std::string Procgen::getAlgorithmParamLabel(const std::string& algorithmId, int index) const {
814 const ParamDescriptor* param = algorithmParam(algorithmId, index);
815 return param ? param->displayName : std::string{};
816}
817
818std::string Procgen::getAlgorithmParamDescription(const std::string& algorithmId, int index) const {
819 const ParamDescriptor* param = algorithmParam(algorithmId, index);
820 return param ? param->description : std::string{};
821}
822
823std::string Procgen::getAlgorithmParamCategory(const std::string& algorithmId, int index) const {
824 const ParamDescriptor* param = algorithmParam(algorithmId, index);
825 return param ? param->category : std::string{};
826}
827
828std::string Procgen::getAlgorithmParamKind(const std::string& algorithmId, int index) const {
829 const ParamDescriptor* param = algorithmParam(algorithmId, index);
830 if (!param) return {};
831 switch (param->kind) {
832 case ParamKind::Integer: return "int";
833 case ParamKind::Float: return "float";
834 case ParamKind::Boolean: return "bool";
835 case ParamKind::String: return "string";
836 case ParamKind::Choice: return "choice";
837 }
838 return {};
839}
840
841std::string Procgen::getAlgorithmParamDefault(const std::string& algorithmId, int index) const {
842 const ParamDescriptor* param = algorithmParam(algorithmId, index);
843 return param ? param->defaultValue : std::string{};
844}
845
846bool Procgen::algorithmParamHasMinimum(const std::string& algorithmId, int index) const {
847 const ParamDescriptor* param = algorithmParam(algorithmId, index);
848 return param && param->hasMinimum;
849}
850
851bool Procgen::algorithmParamHasMaximum(const std::string& algorithmId, int index) const {
852 const ParamDescriptor* param = algorithmParam(algorithmId, index);
853 return param && param->hasMaximum;
854}
855
856float Procgen::getAlgorithmParamMinimum(const std::string& algorithmId, int index) const {
857 const ParamDescriptor* param = algorithmParam(algorithmId, index);
858 return param ? float(param->minimum) : 0.f;
859}
860
861float Procgen::getAlgorithmParamMaximum(const std::string& algorithmId, int index) const {
862 const ParamDescriptor* param = algorithmParam(algorithmId, index);
863 return param ? float(param->maximum) : 0.f;
864}
865
866float Procgen::getAlgorithmParamStep(const std::string& algorithmId, int index) const {
867 const ParamDescriptor* param = algorithmParam(algorithmId, index);
868 return param ? float(param->step) : 0.f;
869}
870
871bool Procgen::isAlgorithmParamAdvanced(const std::string& algorithmId, int index) const {
872 const ParamDescriptor* param = algorithmParam(algorithmId, index);
873 return param && param->advanced;
874}
875
876int Procgen::getAlgorithmParamChoiceCount(const std::string& algorithmId, int index) const {
877 const ParamDescriptor* param = algorithmParam(algorithmId, index);
878 return param ? int(param->choices.size()) : 0;
879}
880
881std::string Procgen::getAlgorithmParamChoice(const std::string& algorithmId, int paramIndex, int choiceIndex) const {
882 const ParamDescriptor* param = algorithmParam(algorithmId, paramIndex);
883 if (!param || choiceIndex < 0 || choiceIndex >= int(param->choices.size())) return {};
884 return param->choices[size_t(choiceIndex)];
885}
886
889 if (!view.isBound())
891 "algorithm default parameters handle is stale",
892 "params", {}, "procgen.squirrel"));
893 if (!GeneratorRegistry::instance().applyDefaults(algorithmId, *view))
895 eve::DiagnosticCode::NotFound, "algorithm schema was not found", "algorithm", {}, "procgen.squirrel"));
897}
898
900 auto view = Procgen::resolve(grid);
901 if (!view.isBound())
903 eve::DiagnosticCode::StaleHandle, "autotileGrid grid handle is stale", "grid", {}, "procgen.squirrel"));
906 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "autotileGrid failed", "grid", {}, "procgen.squirrel"));
908}
909
911
913 auto view = Procgen::resolve(grid);
914 if (!view.isBound())
916 eve::DiagnosticCode::StaleHandle, "gridToJson grid handle is stale", "grid", {}, "procgen.squirrel"));
918}
919
923 if (!input.isBound())
925 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "generateImage parameters handle is stale",
926 "params", {}, "procgen.squirrel"));
927 ownership_->compatMessage.clear();
929 auto image = TextureRecipeRegistry::instance().generate(recipeId, *input, ownership_->compatMessage);
930 if (!image)
933 ownership_->compatMessage.empty() ? "generateImage failed" : ownership_->compatMessage, "recipe", {},
934 "procgen.squirrel"));
935 return ownProcgenObject(ownership_->images, std::move(image));
936}
937
939 Procgen* module = liveProcgen();
940 return module ? module->ownership_->images.resolve(reference) : eve::script::Borrowed<image::ImageData>();
941}
942
944 Procgen* module = liveProcgen();
945 if (!module)
947 eve::DiagnosticCode::StaleHandle, "Procgen module is no longer loaded", "image", {}, "procgen.squirrel"));
948 return module->ownership_->images.erase(reference);
949}
950
952 if (!reference.isValid()) return false;
953 Procgen* module = liveProcgen();
954 return !module || module->ownership_->images.isStale(reference);
955}
956
960 if (!input.isBound())
962 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "generateNormalImage parameters handle is stale",
963 "params", {}, "procgen.squirrel"));
964 auto image = generateImageHandle(recipeId, params);
965 if (!image)
967 eve::DiagnosticCode::Failed, image.status().describe(), "recipe", {}, "procgen.squirrel"));
968 const auto imageRef = std::move(image).takeValue();
969 auto albedo = ownership_->images.resolve(imageRef);
970 if (!albedo.isBound()) {
971 ownership_->images.erase(imageRef).ignore("release unresolvable temporary albedo image");
973 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "generated albedo image handle is stale", "image",
974 {}, "procgen.squirrel"));
975 }
976 const int w = albedo->getWidth();
977 const int h = albedo->getHeight();
978 auto* px = static_cast<const uint8_t*>(albedo->getData());
979 std::vector<float> height(size_t(w * h));
980 for (int i = 0; i < w * h; ++i) {
981 const size_t o = size_t(i) * 4u;
982 height[size_t(i)] = (float(px[o]) * 0.299f + float(px[o + 1]) * 0.587f + float(px[o + 2]) * 0.114f) / 255.f;
983 }
984 const bool seamless = input->getInt("seamless", 1) != 0;
985 const float strength = input->getFloat("normalStrength", 4.f);
987 ownership_->images.erase(imageRef).ignore("release temporary albedo image");
988 if (!normal)
990 eve::DiagnosticCode::Failed, "generateNormalImage failed", "recipe", {}, "procgen.squirrel"));
991 return ownProcgenObject(ownership_->normalImages, std::move(normal));
992}
993
995 Procgen* module = liveProcgen();
996 return module ? module->ownership_->normalImages.resolve(reference) : eve::script::Borrowed<image::ImageData>();
997}
998
1000 Procgen* module = liveProcgen();
1001 if (!module)
1003 "Procgen module is no longer loaded", "normalImage",
1004 {}, "procgen.squirrel"));
1005 return module->ownership_->normalImages.erase(reference);
1006}
1007
1009 if (!reference.isValid()) return false;
1010 Procgen* module = liveProcgen();
1011 return !module || module->ownership_->normalImages.isStale(reference);
1012}
1013
1016 graphics::Graphics* gfx) {
1018 if (!input.isBound() || !gfx) return {};
1019 auto generated = generateImageHandle(recipeId, params);
1020 if (!generated) return {};
1021 const auto imageRef = std::move(generated).takeValue();
1022 auto image = ownership_->images.resolve(imageRef);
1023 if (!image.isBound()) {
1024 ownership_->images.erase(imageRef).ignore("release unresolvable temporary image");
1025 return {};
1026 }
1027 const bool seamless = input->getInt("seamless", 1) != 0;
1028 graphics::Texture* texture = gfx->newTexture(image->getWidth(), image->getHeight(),
1029 static_cast<const uint8_t*>(image->getData()), seamless, seamless);
1030 ownership_->images.erase(imageRef).ignore("release temporary generated image");
1032 static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(gfx)));
1033}
1034
1037 ownership_->textureRecipeIdsCache = TextureRecipeRegistry::instance().list();
1038 return int(ownership_->textureRecipeIdsCache.size());
1039}
1040
1041std::string Procgen::getTextureRecipeId(int index) const {
1042 if (ownership_->textureRecipeIdsCache.empty()) {
1044 ownership_->textureRecipeIdsCache = TextureRecipeRegistry::instance().list();
1045 }
1046 if (index < 0 || index >= int(ownership_->textureRecipeIdsCache.size())) return {};
1047 return ownership_->textureRecipeIdsCache[size_t(index)];
1048}
1049
1050bool Procgen::hasTextureRecipe(const std::string& recipeId) const {
1052 return TextureRecipeRegistry::instance().has(recipeId);
1053}
1054
1056 const std::string& recipeId) {
1059 if (!schema)
1061 eve::DiagnosticCode::NotFound, "texture recipe schema was not found", "recipe", {}, "procgen.squirrel"));
1063}
1064
1068 if (!view.isBound())
1070 "texture default parameters handle is stale", "params",
1071 {}, "procgen.squirrel"));
1073 if (!TextureRecipeRegistry::instance().applyDefaults(recipeId, *view))
1075 eve::DiagnosticCode::NotFound, "texture recipe schema was not found", "recipe", {}, "procgen.squirrel"));
1077}
1078
1080 return ownProcgenObject(ownership_->clouds, std::make_unique<CloudField>());
1081}
1082
1086
1090
1092 return reference.isValid() && ownership_->clouds.isStale(reference);
1093}
1094
1096 return ownProcgenObject(ownership_->shadows, std::make_unique<CloudShadow>());
1097}
1098
1102
1106
1108 return reference.isValid() && ownership_->shadows.isStale(reference);
1109}
1110
1112 auto view = resolveCloudField(field);
1113 if (!view.isBound())
1115 eve::DiagnosticCode::StaleHandle, "cloud field handle is stale", "field", {}, "procgen.squirrel"));
1116 return eve::Result<float>::success(view->coverageAt(x, z, time));
1117}
1118
1120 auto view = resolveCloudShadow(shadow);
1121 if (!view.isBound())
1123 eve::DiagnosticCode::StaleHandle, "cloud shadow handle is stale", "shadow", {}, "procgen.squirrel"));
1124 return eve::Result<float>::success(view->shadowFactorAt(x, z, time));
1125}
1126
1128 float x0, float z0, float extent) {
1129 auto view = resolveCloudField(field);
1130 if (!view.isBound())
1132 eve::DiagnosticCode::StaleHandle, "cloud field handle is stale", "field", {}, "procgen.squirrel"));
1133 if (w <= 0 || h <= 0 || out.size() < static_cast<std::size_t>(w) * static_cast<std::size_t>(h))
1135 "cloud output buffer is smaller than width*height",
1136 "out", {}, "procgen.squirrel"));
1137 view->sample(out.data(), w, h, time, x0, z0, extent);
1139}
1140
1142 float time, float x0, float z0, float extent) {
1143 auto view = resolveCloudShadow(shadow);
1144 if (!view.isBound())
1146 eve::DiagnosticCode::StaleHandle, "cloud shadow handle is stale", "shadow", {}, "procgen.squirrel"));
1147 if (w <= 0 || h <= 0 || out.size() < static_cast<std::size_t>(w) * static_cast<std::size_t>(h))
1149 "cloud output buffer is smaller than width*height",
1150 "out", {}, "procgen.squirrel"));
1151 view->sampleCoverage(out.data(), w, h, time, x0, z0, extent);
1153}
1154
1158 if (!input.isBound())
1160 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "generatePbrMaterial parameters handle is stale",
1161 "params", {}, "procgen.squirrel"));
1162 ownership_->compatMessage.clear();
1164 auto set = PbrRecipeRegistry::instance().generate(recipeId, *input, ownership_->compatMessage);
1165 if (!set)
1168 ownership_->compatMessage.empty() ? "generatePbrMaterial failed" : ownership_->compatMessage, "recipe", {},
1169 "procgen.squirrel"));
1170 return ownProcgenObject(ownership_->pbr, std::move(set));
1171}
1172
1176
1180
1182 return reference.isValid() && ownership_->pbr.isStale(reference);
1183}
1184
1187 ownership_->pbrRecipeIdsCache = PbrRecipeRegistry::instance().list();
1188 return int(ownership_->pbrRecipeIdsCache.size());
1189}
1190
1191std::string Procgen::getPbrRecipeId(int index) const {
1192 if (ownership_->pbrRecipeIdsCache.empty()) {
1194 ownership_->pbrRecipeIdsCache = PbrRecipeRegistry::instance().list();
1195 }
1196 if (index < 0 || index >= int(ownership_->pbrRecipeIdsCache.size())) return {};
1197 return ownership_->pbrRecipeIdsCache[size_t(index)];
1198}
1199
1200bool Procgen::hasPbrRecipe(const std::string& recipeId) const {
1202 return PbrRecipeRegistry::instance().has(recipeId);
1203}
1204
1206 const std::string& recipeId) {
1208 const RecipeDescriptor* schema = PbrRecipeRegistry::instance().descriptor(recipeId);
1209 if (!schema)
1211 eve::DiagnosticCode::NotFound, "PBR recipe schema was not found", "recipe", {}, "procgen.squirrel"));
1213}
1214
1217 if (!view.isBound())
1219 "PBR default parameters handle is stale", "params", {},
1220 "procgen.squirrel"));
1222 if (!PbrRecipeRegistry::instance().applyDefaults(recipeId, *view))
1224 eve::DiagnosticCode::NotFound, "PBR recipe schema was not found", "recipe", {}, "procgen.squirrel"));
1226}
1227
1230 auto built = ProcgenArtifactOps::buildArtifact(*this, recipeId, params,
1232 if (!built)
1234 eve::DiagnosticCode::Failed, built.status().describe(), "recipe", {}, "procgen.squirrel"));
1235 GeneratedArtifact artifact = std::move(built).takeValue();
1236 const MeshBuild* source = nullptr;
1237 if (artifact.type == ArtifactType::MeshData) {
1238 source = &std::get<MeshData>(artifact.payload);
1239 } else if (artifact.type == ArtifactType::Composite) {
1240 const ArtifactPart* part = std::get<CompositeArtifact>(artifact.payload).find("mesh");
1241 if (part && part->type == ArtifactType::MeshData) source = &std::get<MeshData>(part->payload);
1242 }
1243 if (!source)
1245 eve::DiagnosticCode::Failed, "generated artifact has no mesh payload", "recipe", {}, "procgen.squirrel"));
1246 auto mesh = std::make_unique<MeshBuild>(*source);
1247 ArtifactPublisher publisher(ownership_->artifactStore);
1248 auto published = publisher.publish(std::move(artifact), {});
1249 if (!published)
1251 eve::DiagnosticCode::Failed, published.status().describe(), "artifact", {}, "procgen.squirrel"));
1252 std::move(published).takeValue();
1253 return ownProcgenObject(ownership_->meshes, std::move(mesh));
1254}
1255
1259
1263
1265 return reference.isValid() && ownership_->meshes.isStale(reference);
1266}
1267
1271 if (!view.isBound())
1273 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "buildArtifact parameters handle is stale",
1274 "params", {}, "procgen.squirrel"));
1275 return generateMeshArtifact(recipeId, *view, id);
1276}
1277
1281 auto artifact = buildArtifact(module, recipeId, params, id);
1282 if (!artifact.ok()) return eve::Result<ArtifactPublishReceipt>::failure(artifact.status());
1283 ArtifactPublisher publisher(module.ownership_->artifactStore);
1284 return publisher.publish(std::move(artifact).takeValue(), options);
1285}
1286
1288 static const ArtifactId root = [] {
1289 const auto parsed = ArtifactId::parse("6bdf48e2-fca4-4f62-8a66-d952bd6af046");
1290 return parsed ? *parsed : ArtifactId::nil();
1291 }();
1292 return root.child("legacy-facade-" + std::to_string(module.ownership_->nextArtifactSequence++));
1293}
1294
1297 graphics::Graphics* gfx) {
1299 if (!input.isBound() || !gfx) return {};
1300 auto built = buildMeshHandle(recipeId, params);
1301 if (!built) return {};
1302 auto cpu = ownership_->meshes.resolve(std::move(built).takeValue());
1303 if (!cpu.isBound()) return {};
1304 return uploadMeshBorrowed(*cpu, *gfx);
1305}
1306
1308 if (mesh.empty()) return {};
1309 graphics::Mesh* uploaded = gfx.newMeshFromArraysColored(mesh.positions().data(), mesh.normals().data(),
1310 mesh.uvs().data(),mesh.hasVertexColors()?mesh.colors().data():nullptr,mesh.getVertexCount(),
1311 mesh.indices().data(),mesh.getIndexCount());
1313 static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&gfx)));
1314}
1315
1317 const GtsTerrainLodSet& lods,int tileIndex,graphics::Renderable3D& renderable,graphics::Graphics& gfx,
1318 float worldDiameter,float verticalFovDegrees,float originX,float originY,float originZ) {
1319 const auto* tile=lods.tileAt(tileIndex);
1320 if(!tile||tile->levels.empty()||tile->levels.size()>graphics::Renderable3D::MeshRenderer::kMaxLodLevels||
1321 !std::isfinite(worldDiameter)||worldDiameter<=0.f||!std::isfinite(verticalFovDegrees)||
1322 verticalFovDegrees<=0.f||verticalFovDegrees>=180.f||!std::isfinite(originX)||!std::isfinite(originY)||!std::isfinite(originZ))
1324 "GTS terrain tile render configuration is invalid","procgen.configureGtsTerrainTileLods"));
1325 std::vector<graphics::Mesh*> uploaded;uploaded.reserve(tile->levels.size());
1326 for(const auto& level:tile->levels){auto mesh=uploadMeshBorrowed(level,gfx);if(!mesh.isBound())
1328 "GTS terrain tile contains an empty or unuploadable LOD","procgen.configureGtsTerrainTileLods"));uploaded.push_back(mesh.get());}
1329 renderable.clearMeshLod();
1330 for(int level=0;level<static_cast<int>(uploaded.size());++level){float distance=level==0?0.f:lods.getLevelSwitchDistance(level-1,worldDiameter,verticalFovDegrees);renderable.setMeshLod(level,uploaded[level],distance);}
1331 renderable.setMeshLodCullDistance(lods.getLevelSwitchDistance(static_cast<int>(uploaded.size())-1,worldDiameter,verticalFovDegrees));
1332 renderable.setPosition(originX+tile->offsetX,originY,originZ+tile->offsetZ);
1334}
1335
1337 graphics::Renderable3D& renderable,
1338 graphics::Graphics& gfx, float worldDiameter,
1339 float verticalFovDegrees) {
1340 const int count = lods.getLevelCount();
1341 if (count <= 0 || count > graphics::Renderable3D::MeshRenderer::kMaxLodLevels ||
1342 !std::isfinite(worldDiameter) || worldDiameter <= 0.F || !std::isfinite(verticalFovDegrees) ||
1343 verticalFovDegrees <= 0.F || verticalFovDegrees >= 180.F)
1345 eve::DiagnosticCode::InvalidArgument, "Pcg mesh LOD render configuration is invalid",
1346 "procgen.configurePcgMeshLods"));
1347 std::vector<graphics::Mesh*> uploaded;
1348 uploaded.reserve(static_cast<std::size_t>(count));
1349 for (int level = 0; level < count; ++level) {
1350 const MeshBuild* source = lods.meshAt(level);
1352 eve::DiagnosticCode::InvalidArgument, "Pcg mesh LOD level is missing",
1353 "procgen.configurePcgMeshLods"));
1354 auto mesh = uploadMeshBorrowed(*source, gfx);
1356 eve::DiagnosticCode::Unsupported, "Pcg mesh LOD level could not be uploaded",
1357 "procgen.configurePcgMeshLods"));
1358 uploaded.push_back(mesh.get());
1359 }
1360 auto candidate = *renderable.meshRenderer();
1361 candidate.lodCount = 0;
1363 candidate.lodMeshes[level] = nullptr;
1364 candidate.lodRendererStates[level] = {};
1365 }
1366 for (int level = 0; level < count; ++level) {
1367 const float distance = level == 0 ? 0.F : lods.getSwitchDistance(level - 1, worldDiameter, verticalFovDegrees);
1368 candidate.lodMeshes[level] = uploaded[static_cast<std::size_t>(level)];
1369 candidate.lodCount = level + 1;
1370 if (level == 0) candidate.mesh = uploaded[0];
1371 if (level > 0) candidate.lodDistances[level - 1] = distance;
1372 const auto* state = lods.rendererStateAt(level);
1374 eve::DiagnosticCode::InvalidArgument, "Pcg mesh LOD renderer state is missing",
1375 "procgen.configurePcgMeshLods"));
1376 auto& target = candidate.lodRendererStates[level];
1377 target.configured = true;
1378 target.skinQuality = state->skinQuality;
1379 target.shadowCastingMode = state->shadowCastingMode;
1380 target.receiveShadows = state->receiveShadows;
1381 target.motionVectorMode = state->motionVectorMode;
1382 target.skinnedMotionVectors = state->skinnedMotionVectors;
1383 target.lightProbeUsage = state->lightProbeUsage;
1384 target.reflectionProbeUsage = state->reflectionProbeUsage;
1385 candidate.lodFadeWidths[level] = lods.getFadeWidth(level);
1386 }
1387 const float cullDistance = lods.getSwitchDistance(count - 1, worldDiameter, verticalFovDegrees);
1388 candidate.lodCullDistance = cullDistance > 0.F ? cullDistance : 0.F;
1389 candidate.lodFadeMode = lods.getFadeMode();
1390 candidate.lodAnimateCrossFading = lods.getAnimateCrossFading();
1391 candidate.lodCrossFadeDuration = lods.getCrossFadeAnimationDuration();
1392 candidate.lodAnimatedCurrent=-2;candidate.lodAnimatedPrevious=-2;candidate.lodAnimatedProgress=1.F;
1393 *renderable.meshRenderer() = candidate;
1395}
1396
1399 ownership_->meshRecipeIdsCache = MeshRecipeRegistry::instance().list();
1400 return int(ownership_->meshRecipeIdsCache.size());
1401}
1402
1403std::string Procgen::getMeshRecipeId(int index) const {
1404 if (ownership_->meshRecipeIdsCache.empty()) {
1406 ownership_->meshRecipeIdsCache = MeshRecipeRegistry::instance().list();
1407 }
1408 if (index < 0 || index >= int(ownership_->meshRecipeIdsCache.size())) return {};
1409 return ownership_->meshRecipeIdsCache[size_t(index)];
1410}
1411
1412bool Procgen::hasMeshRecipe(const std::string& recipeId) const {
1414 return MeshRecipeRegistry::instance().has(recipeId);
1415}
1416
1418 const std::string& recipeId) {
1420 const RecipeDescriptor* schema = MeshRecipeRegistry::instance().descriptor(recipeId);
1421 if (!schema)
1423 eve::DiagnosticCode::NotFound, "mesh recipe schema was not found", "recipe", {}, "procgen.squirrel"));
1425}
1426
1429 if (!view.isBound())
1431 "mesh default parameters handle is stale", "params",
1432 {}, "procgen.squirrel"));
1433 if (recipeId == "mesh.autoBridge") return road::applyBridgeRecipeDefaults(*view);
1435 if (!MeshRecipeRegistry::instance().applyDefaults(recipeId, *view))
1437 eve::DiagnosticCode::NotFound, "mesh recipe schema was not found", "recipe", {}, "procgen.squirrel"));
1439}
1440
1442 return ownProcgenObject(ownership_->samplers, std::make_unique<TerrainSampler>());
1443}
1444
1449
1453
1455 return reference.isValid() && ownership_->samplers.isStale(reference);
1456}
1457
1459 if (width <= 0 || height <= 0)
1461 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "heightmap dimensions must be positive",
1462 "heightmap", {}, "procgen.squirrel"));
1463 return ownProcgenObject(ownership_->heightmaps, std::make_unique<Heightmap>(width, height));
1464}
1465
1467 if (!heightmap || heightmap->getWidth() <= 0 || heightmap->getHeight() <= 0)
1469 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "decoded heightmap has no samples",
1470 "heightmap", {}, "procgen.squirrel"));
1471 return ownProcgenObject(ownership_->heightmaps, std::move(heightmap));
1472}
1473
1474PaletteTable& Procgen::palettes() { return ownership_->palettes; }
1475
1476const PaletteTable& Procgen::palettes() const { return ownership_->palettes; }
1477
1479 return module.ownership_->artifactStore;
1480}
1481
1485
1489
1491 return reference.isValid() && ownership_->heightmaps.isStale(reference);
1492}
1493
1496 if (!input.isBound())
1498 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "generateHeightmap parameters handle is stale",
1499 "params", {}, "procgen.squirrel"));
1501 return ownProcgenObject(ownership_->heightmaps, std::make_unique<Heightmap>(Heightmap::generate(
1502 sampler, input->getWidth(), input->getHeight())));
1503}
1504
1507 auto map = resolveHeightmap(heightmap);
1509 if (!map.isBound())
1511 eve::DiagnosticCode::StaleHandle, "heightmap handle is stale", "heightmap", {}, "procgen.squirrel"));
1512 if (!input.isBound())
1514 "heightmap parameters handle is stale",
1515 "params", {}, "procgen.squirrel"));
1516 auto grid = std::make_unique<Grid2D>();
1518 if (!map->toGrid(*grid, bands))
1520 eve::DiagnosticCode::Failed, "heightmap is empty", "heightmap", {}, "procgen.squirrel"));
1521 Procgen* module = Procgen::create();
1522 return module->ownership_->grids.emplace(std::move(grid));
1523}
1524
1525bool Procgen::erodeTerrainThermal(Heightmap* heightmap, int iterations, float talus, float strength) {
1526 ownership_->compatMessage.clear();
1527 if (!heightmap || heightmap->getWidth() < 2 || heightmap->getHeight() < 2) {
1528 ownership_->compatMessage = "erodeTerrainThermal: heightmap must be at least 2x2";
1529 return false;
1530 }
1531 TerrainPipeline::erodeThermal(*heightmap, {iterations, talus, strength});
1532 return true;
1533}
1534
1535bool Procgen::erodeTerrainHydraulic(Heightmap* heightmap, int iterations, float rainfall, float evaporation,
1536 float capacity, float erosion, float deposition) {
1537 ownership_->compatMessage.clear();
1538 if (!heightmap || heightmap->getWidth() < 2 || heightmap->getHeight() < 2) {
1539 ownership_->compatMessage = "erodeTerrainHydraulic: heightmap must be at least 2x2";
1540 return false;
1541 }
1542 TerrainPipeline::erodeHydraulic(*heightmap, {iterations, rainfall, evaporation, capacity, erosion, deposition});
1543 return true;
1544}
1545
1546bool Procgen::erodeTerrainFluvial(Heightmap* heightmap, int iterations, float riverThreshold, float incision,
1547 float maxDepth, float bankWidth) {
1548 return erodeTerrainFluvialAdvanced(heightmap, iterations, riverThreshold, incision, maxDepth, bankWidth,
1549 std::min(maxDepth, 0.04f));
1550}
1551
1552bool Procgen::erodeTerrainFluvialAdvanced(Heightmap* heightmap, int iterations, float riverThreshold, float incision,
1553 float maxDepth, float bankWidth, float maxBreachDepth) {
1554 return erodeTerrainFluvialScaled(heightmap, iterations, riverThreshold, incision, maxDepth, bankWidth,
1555 maxBreachDepth, 1.f);
1556}
1557
1558bool Procgen::erodeTerrainFluvialScaled(Heightmap* heightmap, int iterations, float riverThreshold, float incision,
1559 float maxDepth, float bankWidth, float maxBreachDepth, float coordinateScale) {
1560 ownership_->compatMessage.clear();
1561 if (!heightmap || heightmap->getWidth() < 3 || heightmap->getHeight() < 3) {
1562 ownership_->compatMessage = "erodeTerrainFluvial: heightmap must be at least 3x3";
1563 return false;
1564 }
1565 if (!std::isfinite(coordinateScale) || coordinateScale <= 0.f) {
1566 ownership_->compatMessage = "erodeTerrainFluvialScaled: coordinateScale must be positive";
1567 return false;
1568 }
1570 *heightmap, {iterations, riverThreshold, incision, maxDepth, bankWidth, maxBreachDepth, coordinateScale});
1571 return true;
1572}
1573
1575 float incision, float maxDepth, float bankWidth,
1576 float maxBreachDepth, float coordinateScale) {
1577 ownership_->compatMessage.clear();
1578 if (!heightmap || heightmap->getWidth() < 3 || heightmap->getHeight() < 3) {
1579 ownership_->compatMessage = "erodeTerrainFluvialDetailed: heightmap must be at least 3x3";
1580 return nullptr;
1581 }
1582 if (!std::isfinite(coordinateScale) || coordinateScale <= 0.f) {
1583 ownership_->compatMessage = "erodeTerrainFluvialDetailed: coordinateScale must be positive";
1584 return nullptr;
1585 }
1587 *heightmap, {iterations, riverThreshold, incision, maxDepth, bankWidth, maxBreachDepth, coordinateScale});
1588 if (diagnostics.width <= 0) {
1589 ownership_->compatMessage = "erodeTerrainFluvialDetailed: invalid erosion settings";
1590 return nullptr;
1591 }
1592 return new TerrainErosionMap(std::move(diagnostics));
1593}
1594
1595TerrainLayers* Procgen::analyzeTerrain(Heightmap* heightmap, float riverThreshold, float seaLevel, float latitude) {
1596 return analyzeTerrainScaled(heightmap, riverThreshold, seaLevel, latitude, 1.f);
1597}
1598
1599TerrainLayers* Procgen::analyzeTerrainScaled(Heightmap* heightmap, float riverThreshold, float seaLevel, float latitude,
1600 float coordinateScale) {
1601 ownership_->compatMessage.clear();
1602 if (!heightmap || heightmap->getWidth() <= 0 || heightmap->getHeight() <= 0) {
1603 ownership_->compatMessage = "analyzeTerrain: heightmap is empty";
1604 return nullptr;
1605 }
1606 if (!std::isfinite(coordinateScale) || coordinateScale <= 0.f) {
1607 ownership_->compatMessage = "analyzeTerrainScaled: coordinateScale must be positive";
1608 return nullptr;
1609 }
1610 HydrologyMap hydrology = TerrainPipeline::buildHydrology(*heightmap, riverThreshold, seaLevel, coordinateScale);
1611 ClimateMap climate = TerrainPipeline::buildClimate(*heightmap, hydrology, seaLevel, latitude, coordinateScale);
1612 return new TerrainLayers(std::move(hydrology), std::move(climate));
1613}
1614
1616 ownership_->compatMessage.clear();
1617 if (!heightmap || !layers) {
1618 ownership_->compatMessage = "bakeTerrainAsset: heightmap and layers are required";
1619 return nullptr;
1620 }
1621 std::vector<uint8_t> bytes;
1622 if (!TerrainAsset::bake(*heightmap, layers->hydrology(), layers->climate(), chunkSize, bytes,
1623 &ownership_->compatMessage))
1624 return nullptr;
1625 return new data::ByteData(bytes.data(), bytes.size());
1626}
1627
1628TerrainMeshChunk* Procgen::buildTerrainChunk(Heightmap* heightmap, TerrainLayers* layers, int originX, int originY,
1629 int cellsX, int cellsY, int lod, float cellSize, float heightScale,
1630 float skirtDepth) {
1631 ownership_->compatMessage.clear();
1632 if (!heightmap) {
1633 ownership_->compatMessage = "buildTerrainChunk: heightmap is required";
1634 return nullptr;
1635 }
1637 settings.originX = originX;
1638 settings.originY = originY;
1639 settings.cellsX = cellsX;
1640 settings.cellsY = cellsY;
1641 settings.lod = lod;
1642 settings.cellSize = cellSize;
1643 settings.heightScale = heightScale;
1644 settings.skirtDepth = skirtDepth;
1645 auto* chunk = new TerrainMeshChunk();
1646 if (!TerrainMeshBuilder::build(*heightmap, layers, settings, *chunk, &ownership_->compatMessage)) {
1647 delete chunk;
1648 return nullptr;
1649 }
1650 return chunk;
1651}
1652
1653int Procgen::selectTerrainLod(Heightmap* heightmap, int originX, int originY, int cellsX, int cellsY, int maxLod,
1654 float cellSize, float heightScale, float cameraDistance, float viewportHeight,
1655 float verticalFovDegrees, float targetPixelError) {
1656 ownership_->compatMessage.clear();
1657 if (!heightmap) {
1658 ownership_->compatMessage = "selectTerrainLod: heightmap is required";
1659 return -1;
1660 }
1662 settings.originX = originX;
1663 settings.originY = originY;
1664 settings.cellsX = cellsX;
1665 settings.cellsY = cellsY;
1666 settings.cellSize = cellSize;
1667 settings.heightScale = heightScale;
1668 const int lod = TerrainLodSelector::select(*heightmap, settings, maxLod, cameraDistance, viewportHeight,
1669 verticalFovDegrees, targetPixelError);
1670 if (lod < 0) ownership_->compatMessage = "selectTerrainLod: invalid bounds or projection settings";
1671 return lod;
1672}
1673
1675 ownership_->compatMessage.clear();
1676 if (!chunk || !gfx || chunk->mesh().empty()) {
1677 ownership_->compatMessage = "generateTerrainChunkMesh: chunk and graphics are required";
1678 return nullptr;
1679 }
1680 const MeshBuild& mesh = chunk->mesh();
1681 return gfx->newMeshFromArrays(mesh.positions().data(), mesh.normals().data(), mesh.uvs().data(),
1682 mesh.getVertexCount(), mesh.indices().data(), mesh.getIndexCount());
1683}
1684
1686 int originX, int originY, int cellsX, int cellsY, float cellSize,
1687 float heightScale, float minWidth, float maxWidth,
1688 float heightOffset) {
1689 return generateTerrainRiverMeshAdvanced(heightmap, layers, gfx, originX, originY, cellsX, cellsY, cellSize,
1690 heightScale, minWidth, maxWidth, heightOffset, 0.f, 0.30f);
1691}
1692
1694 graphics::Graphics* gfx, int originX, int originY, int cellsX,
1695 int cellsY, float cellSize, float heightScale, float minWidth,
1696 float maxWidth, float heightOffset, float minSurfaceSlope,
1697 float maxSurfaceSlope) {
1698 ownership_->compatMessage.clear();
1699 if (!heightmap || !layers || !gfx) {
1700 ownership_->compatMessage = "generateTerrainRiverMesh: heightmap, layers, and graphics are required";
1701 return nullptr;
1702 }
1704 settings.originX = originX;
1705 settings.originY = originY;
1706 settings.cellsX = cellsX;
1707 settings.cellsY = cellsY;
1708 settings.cellSize = cellSize;
1709 settings.heightScale = heightScale;
1710 settings.minWidth = minWidth;
1711 settings.maxWidth = maxWidth;
1712 settings.heightOffset = heightOffset;
1713 settings.minSurfaceSlope = minSurfaceSlope;
1714 settings.maxSurfaceSlope = maxSurfaceSlope;
1716 if (!TerrainRiverMeshBuilder::build(*heightmap, *layers, settings, river, &ownership_->compatMessage) ||
1717 river.empty())
1718 return nullptr;
1719 return gfx->newMeshFromArrays(river.positions().data(), river.normals().data(), river.uvs().data(),
1720 river.getVertexCount(), river.indices().data(), river.getIndexCount());
1721}
1722
1724 int originX, int originY, int cellsX, int cellsY, float cellSize,
1725 float heightScale, float minimumDepth, float heightOffset) {
1726 ownership_->compatMessage.clear();
1727 if (!heightmap || !layers || !gfx) {
1728 ownership_->compatMessage = "generateTerrainLakeMesh: heightmap, layers, and graphics are required";
1729 return nullptr;
1730 }
1732 settings.originX = originX;
1733 settings.originY = originY;
1734 settings.cellsX = cellsX;
1735 settings.cellsY = cellsY;
1736 settings.cellSize = cellSize;
1737 settings.heightScale = heightScale;
1738 settings.minimumDepth = minimumDepth;
1739 settings.heightOffset = heightOffset;
1741 if (!TerrainLakeMeshBuilder::build(*heightmap, *layers, settings, lake, &ownership_->compatMessage) || lake.empty())
1742 return nullptr;
1743 return gfx->newMeshFromArrays(lake.positions().data(), lake.normals().data(), lake.uvs().data(),
1744 lake.getVertexCount(), lake.indices().data(), lake.getIndexCount());
1745}
1746
1748 ownership_->compatMessage.clear();
1749 if (!chunk || chunk->getSplatWidth() <= 0 || chunk->getSplatHeight() <= 0) {
1750 ownership_->compatMessage = "generateTerrainSplatMap: a built terrain chunk is required";
1751 return nullptr;
1752 }
1753 auto* image = new image::ImageData(chunk->getSplatWidth(), chunk->getSplatHeight(), "RGBA8");
1754 auto* pixels = static_cast<uint8_t*>(image->getData());
1755 for (int vertex = 0; vertex < chunk->getBaseVertexCount(); ++vertex) {
1756 std::array<int, 4> quantized{};
1757 std::array<float, 4> remainder{};
1758 int total = 0;
1759 for (int channel = 0; channel < 4; ++channel) {
1760 const float scaled = std::clamp(chunk->getMaterialWeight(vertex, channel), 0.f, 1.f) * 255.f;
1761 quantized[channel] = int(std::floor(scaled));
1762 remainder[channel] = scaled - float(quantized[channel]);
1763 total += quantized[channel];
1764 }
1765 while (total < 255) {
1766 const int channel = int(std::max_element(remainder.begin(), remainder.end()) - remainder.begin());
1767 ++quantized[channel];
1768 remainder[channel] = -1.f;
1769 ++total;
1770 }
1771 for (int channel = 0; channel < 4; ++channel)
1772 pixels[size_t(vertex) * 4u + size_t(channel)] = uint8_t(quantized[channel]);
1773 }
1774 return image;
1775}
1776
1778 ownership_->compatMessage.clear();
1779 if (!chunk || chunk->getSplatWidth() <= 0 || chunk->getSplatHeight() <= 0) {
1780 ownership_->compatMessage = "generateTerrainAlbedoMap: a built terrain chunk is required";
1781 return nullptr;
1782 }
1783 static constexpr std::array<std::array<float, 3>, 4> palette{{
1784 {{0.55f, 0.40f, 0.22f}}, // sand, dry soil, and river sediment
1785 {{0.15f, 0.38f, 0.12f}}, // vegetation
1786 {{0.36f, 0.35f, 0.33f}}, // exposed rock
1787 {{0.88f, 0.91f, 0.94f}}, // snow
1788 }};
1789 auto* image = new image::ImageData(chunk->getSplatWidth(), chunk->getSplatHeight(), "RGBA8");
1790 auto* pixels = static_cast<uint8_t*>(image->getData());
1791 for (int vertex = 0; vertex < chunk->getBaseVertexCount(); ++vertex) {
1792 const int biome = chunk->getBiome(vertex);
1793 std::array<float, 3> semanticColor{};
1794 bool useSemanticColor = true;
1795 if (biome == int(Biome::Ocean))
1796 semanticColor = {0.035f, 0.16f, 0.25f};
1797 else if (biome == int(Biome::River))
1798 semanticColor = {0.24f, 0.18f, 0.09f};
1799 else if (biome == int(Biome::Lake))
1800 semanticColor = {0.12f, 0.19f, 0.14f};
1801 else if (biome == int(Biome::Wetland))
1802 semanticColor = {0.12f, 0.28f, 0.07f};
1803 else if (biome == int(Biome::Beach))
1804 semanticColor = {0.42f, 0.34f, 0.19f};
1805 else
1806 useSemanticColor = false;
1807 for (int component = 0; component < 3; ++component) {
1808 float value = semanticColor[component];
1809 if (!useSemanticColor) {
1810 value = 0.f;
1811 for (int channel = 0; channel < 4; ++channel)
1812 value += chunk->getMaterialWeight(vertex, channel) * palette[channel][component];
1813 }
1814 pixels[size_t(vertex) * 4u + size_t(component)] = uint8_t(std::lround(std::clamp(value, 0.f, 1.f) * 255.f));
1815 }
1816 pixels[size_t(vertex) * 4u + 3u] = 255;
1817 }
1818 return image;
1819}
1820
1821namespace {
1822float diagnosticScale(const std::vector<float>& values, float exposure) {
1823 if (std::isfinite(exposure) && exposure > 0.f) return exposure;
1824 std::vector<float> positive;
1825 positive.reserve(values.size());
1826 for (float value : values)
1827 if (std::isfinite(value) && value > 0.f) positive.push_back(value);
1828 if (positive.empty()) return 1.f;
1829 const size_t percentile = std::min(positive.size() - 1, size_t(std::floor(float(positive.size() - 1) * 0.99f)));
1830 std::nth_element(positive.begin(), positive.begin() + ptrdiff_t(percentile), positive.end());
1831 return 1.f / std::max(1e-8f, positive[percentile]);
1832}
1833
1834enum class ErosionImageMode { Combined, Wear, Deposit };
1835
1836image::ImageData* erosionDiagnosticImage(TerrainErosionMap* map, float exposure, ErosionImageMode mode) {
1837 if (!map || map->width <= 0 || map->height <= 0 || map->wear.size() != size_t(map->width) * size_t(map->height) ||
1838 map->deposition.size() != map->wear.size())
1839 return nullptr;
1840 const float wearScale = diagnosticScale(map->wear, exposure);
1841 const float depositScale = diagnosticScale(map->deposition, exposure);
1842 auto* result = new image::ImageData(map->width, map->height, "RGBA8");
1843 auto* pixels = static_cast<uint8_t*>(result->getData());
1844 for (size_t i = 0; i < map->wear.size(); ++i) {
1845 const float wear = std::sqrt(std::clamp(map->wear[i] * wearScale, 0.f, 1.f));
1846 const float deposit = std::sqrt(std::clamp(map->deposition[i] * depositScale, 0.f, 1.f));
1847 float r = 0.025f, g = 0.035f, b = 0.050f;
1848 if (mode == ErosionImageMode::Wear) {
1849 r += 0.95f * wear;
1850 g += 0.30f * wear;
1851 b += 0.035f * wear;
1852 } else if (mode == ErosionImageMode::Deposit) {
1853 r += 0.035f * deposit;
1854 g += 0.78f * deposit;
1855 b += 0.95f * deposit;
1856 } else {
1857 r += 0.95f * wear + 0.035f * deposit;
1858 g += 0.30f * wear + 0.78f * deposit;
1859 b += 0.035f * wear + 0.95f * deposit;
1860 }
1861 pixels[i * 4u] = uint8_t(std::lround(std::clamp(r, 0.f, 1.f) * 255.f));
1862 pixels[i * 4u + 1u] = uint8_t(std::lround(std::clamp(g, 0.f, 1.f) * 255.f));
1863 pixels[i * 4u + 2u] = uint8_t(std::lround(std::clamp(b, 0.f, 1.f) * 255.f));
1864 pixels[i * 4u + 3u] = 255;
1865 }
1866 return result;
1867}
1868} // namespace
1869
1871 ownership_->compatMessage.clear();
1872 image::ImageData* result = erosionDiagnosticImage(erosion, exposure, ErosionImageMode::Combined);
1873 if (!result) ownership_->compatMessage = "generateTerrainErosionMap: valid erosion diagnostics are required";
1874 return result;
1875}
1876
1878 ownership_->compatMessage.clear();
1879 image::ImageData* result = erosionDiagnosticImage(erosion, exposure, ErosionImageMode::Wear);
1880 if (!result) ownership_->compatMessage = "generateTerrainWearMap: valid erosion diagnostics are required";
1881 return result;
1882}
1883
1885 ownership_->compatMessage.clear();
1886 image::ImageData* result = erosionDiagnosticImage(erosion, exposure, ErosionImageMode::Deposit);
1887 if (!result) ownership_->compatMessage = "generateTerrainDepositionMap: valid erosion diagnostics are required";
1888 return result;
1889}
1890
1892 ownership_->compatMessage.clear();
1893 if (!gfx) {
1894 ownership_->compatMessage = "createTerrainMaterialShader: graphics is required";
1895 return nullptr;
1896 }
1897 try {
1898 std::vector<uint32_t> fragment(terrain_material_frag_spv,
1899 terrain_material_frag_spv + terrain_material_frag_spv_count);
1900 auto *shader = gfx->newMeshShaderFromSpv({}, fragment);
1901 if (!shader) return nullptr;
1902 for (int slot = 0; slot < 4; ++slot)
1903 shader->declareVec4("terrainLayer" + std::to_string(slot) + "ST");
1904 shader->declareVec4("terrainMetallic");
1905 shader->declareVec4("terrainNormalScale");
1906 shader->sendVec4("terrainNormalScale", 1.f, 1.f, 1.f, 1.f);
1907 shader->declareVec4("terrainSmoothness");
1908 shader->declareVec4("terrainFeatures");
1909 return shader;
1910 } catch (const std::exception &e) {
1911 ownership_->compatMessage = std::string("createTerrainMaterialShader: ") + e.what();
1912 return nullptr;
1913 }
1914}
1915
1917 ownership_->compatMessage.clear();
1918 if (!gfx) {
1919 ownership_->compatMessage = "createTerrainWaterShader: graphics is required";
1920 return nullptr;
1921 }
1922 try {
1923 std::vector<uint32_t> fragment(terrain_water_compat_frag_spv,
1924 terrain_water_compat_frag_spv + terrain_water_compat_frag_spv_count);
1925 return gfx->newMeshShaderFromSpv({}, fragment);
1926 } catch (const std::exception& e) {
1927 ownership_->compatMessage = std::string("createTerrainWaterShader: ") + e.what();
1928 return nullptr;
1929 }
1930}
1931
1932
1933} // namespace eve::procgen
double z
double y
double x
LogicalId target
Trace trace
Definition Agent.cpp:50
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
std::string output
std::string descriptor
eve::action::ActionSpatialBinding spatial
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
float wear
bool seamless
graphics::Texture * albedo
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::string palette
float strength
tensor::Graph g
Definition GpuGraph.cpp:7
std::uint32_t capacity
vk::UniqueSampler sampler
vk::UniqueImage image
float u
Definition Grass.cpp:233
double r
std::vector< ClimateData > climate
Current moisture and cloud state per cell.
HexVec3 left
HexVec3 right
Optional hexmap terrain bake bindings for Procgen.
float river
int biome
bool lake
int h
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
JobScope scope
const ColourScope * parent
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::vector< RecipeParam > params
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
Texture * normal
int level
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
OceanWakeSettings settings
OceanMeshSettings mesh
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
std::string error
Definition Package.cpp:174
Texture * texture
TileLayer * layer
std::shared_ptr< const std::vector< glm::vec2 > > points
Artifact build/publish ops kept off the high-fanout Procgen facade.
Recipe/algorithm schema copies kept off the high-fanout Procgen facade.
std::set< std::string > values
Object::Ptr value
uint8_t * pixels
std::string domain
std::string slot
Shader * shader
int lod
uint32_t semantic
bool found
ScriptStructure out
std::string_view source
double current
const SquirrelValueOptions & options
int count
The single Squirrel projection for common Result, Status and Value.
int spacing
int iterations
Definition TreeMesh.cpp:448
uint32_t seed
Definition TreeMesh.cpp:276
uint32_t index
const VegetationPresetContext & context
float heightScale
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 Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
In-memory byte buffer implementing eve::Data (ref-counted).
Definition ByteData.h:13
Id128 public API.
Definition Identity.h:111
static constexpr Id128 nil() noexcept
Returns the all-zero nil value.
Definition Identity.h:141
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
virtual Shader * newMeshShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv)=0
Create a Mesh3D custom shader (MeshVertex + Frame UBO + albedo). Empty vert → default mesh3d....
virtual Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false)=0
Creates a texture. @ownership Caller deletes unless documented otherwise.
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
virtual Mesh * newMeshFromArraysColored(const float *posXYZ, const float *nrmXYZ, const float *uvST, const float *colorRGBA, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh with an optional packed RGBA color per vertex.
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
EVENGINE_API_BACKENDS public API.
void setMeshLodCullDistance(float distance)
Set the distance that culls the whole mesh LOD chain; zero disables culling.
void setPosition(float x, float y, float z)
void setMeshLod(int index, Mesh *mesh, float switchDistance=0.f)
Configure geometric LOD. index 0 = highest detail. For index > 0, switchDistance is the camera distan...
Custom GPU program.
Definition Shader.h:41
int declareVec4(const std::string &name)
Definition Shader.cpp:58
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
Represents raw pixel data.
Definition ImageData.h:38
ECS tile layer entity. Script mutates tile GIDs / tileset / draw; TileRenderSystem batch-draws atlas ...
Definition TileLayer.h:33
Coordinates adapter preparation and atomic CPU-store publication.
eve::Result< ArtifactPublishReceipt > publish(GeneratedArtifact artifact, ArtifactPublishOptions options)
Publish through required capabilities and then atomically into the store.
In-memory owner and publisher for generated artifacts.
const GeneratorDescriptor * descriptor(const std::string &id) const
Return reflection metadata for an algorithm.
void registerBuiltins()
Register built-in DTL / custom map algorithms (idempotent).
bool has(const std::string &id) const
Return true when an executable algorithm is registered.
static GeneratorRegistry & instance()
Return the process-wide generator registry.
std::vector< std::string > list() const
Return sorted registered algorithm ids.
Intermediate 2D generation result. cells store semantic ids (see Semantic.h), not tile GIDs — convert...
Definition Grid2D.h:37
Owned result of the GTS split-and-sequential-simplify pipeline.
float getLevelSwitchDistance(int level, float worldDiameter, float verticalFovDegrees) const
Convert one level's screen-relative threshold to a perspective-camera distance.
const GtsTerrainLodTile * tileAt(int index) const
Return one tile or nullptr for an invalid index. @ownership The LOD set retains ownership; the caller...
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
static Heightmap generate(const TerrainSampler &sampler, int width, int height)
Materialize a Heightmap by sampling sampler at every pixel center.
Definition Heightmap.cpp:69
int getWidth() const
Returns the width.
Definition Heightmap.cpp:16
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
bool empty() const
Empty.
std::vector< std::string > list() const
List.
void registerBuiltins()
Registers builtins.
static MeshRecipeRegistry & instance()
Access the process-wide mesh recipe registry.
const RecipeDescriptor * descriptor(const std::string &id) const
Look up recipe metadata.
bool has(const std::string &id) const
True when active.
Named palette: semantic name -> tile GID. Unmapped semantics become GID 0.
Definition Palette.h:16
Owning, typed generation parameters.
Definition Params.h:27
const RecipeDescriptor * descriptor(const std::string &id) const
Look up recipe metadata.
static PbrRecipeRegistry & instance()
Access the process-wide PBR registry.
std::vector< std::string > list() const
List recipe ids.
std::unique_ptr< PbrTextureSet > generate(const std::string &id, const Params &params, std::string &error) const
Generates a PBR map set and transfers its unique ownership to the caller.
void registerPbrBuiltins()
Register engine-provided PBR recipes once.
bool has(const std::string &id) const
Test whether a recipe exists.
Owned generic mesh LOD output generated with Pcg's independent-per-level policy.
Definition PcgMeshLod.h:144
bool getAnimateCrossFading() const noexcept
Return whether transitions use injected time.
Definition PcgMeshLod.h:167
const PcgMeshLodRendererState * rendererStateAt(int index) const noexcept
Borrow one generated level's immutable renderer state, or null.
const MeshBuild * meshAt(int index) const noexcept
Borrow a generated mesh, or null for an invalid index. @ownership The set retains ownership....
int getFadeMode() const noexcept
Return Unity LODFadeMode copied from the build profile.
Definition PcgMeshLod.h:165
float getSwitchDistance(int level, float worldDiameter, float verticalFovDegrees) const noexcept
Convert one level threshold to camera distance, or -1 for invalid input.
float getFadeWidth(int index) const noexcept
Return one level's fade width, or -1 for an invalid index.
float getCrossFadeAnimationDuration() const noexcept
Return injected-time transition duration.
Definition PcgMeshLod.h:169
int getLevelCount() const noexcept
Return the number of complete generated levels.
Definition PcgMeshLod.h:147
Staging area for one atomic rebuild of a named procedural system.
Procedural generation module. Phase A: runtime maps (semantic Grid2D → TileLayer)....
Definition Procgen.h:159
eve::Result< void > releaseHeightmap(ProcgenHeightmapHandleRef)
Definition Procgen.cpp:1486
bool erodeTerrainHydraulic(Heightmap *heightmap, int iterations, float rainfall, float evaporation, float capacity, float erosion, float deposition)
Compatibility facade that applies deterministic grid water/sediment erosion.
Definition Procgen.cpp:1535
eve::Result< ProcgenMeshBuildHandleRef > buildMeshHandle(const std::string &recipeId, ProcgenParamsHandleRef params)
CPU mesh (caller owns). Recipes include mesh.marchingcubes, mesh.hexplanet, mesh.castle and the regis...
Definition Procgen.cpp:1228
eve::script::Borrowed< LSystem > resolveLSystem(ProcgenLSystemHandleRef reference) noexcept
Resolve l system.
Definition Procgen.cpp:340
eve::Result< ProcgenImageHandleRef > generateImageHandle(const std::string &recipeId, ProcgenParamsHandleRef params)
Generate image handle.
Definition Procgen.cpp:920
int getTextureRecipeCount() const
Returns the texture recipe count.
Definition Procgen.cpp:1035
std::string getAlgorithmParamDefault(const std::string &algorithmId, int index) const
Schema default encoded as text for lossless dynamic UI transport.
Definition Procgen.cpp:841
bool erodeTerrainFluvialScaled(Heightmap *heightmap, int iterations, float riverThreshold, float incision, float maxDepth, float bankWidth, float maxBreachDepth, float coordinateScale)
Compatibility facade with explicit raster-to-physical scaling.
Definition Procgen.cpp:1558
eve::Result< ProcgenPointSetHandleRef > getSystemDebugStageHandle(const std::string &name, const std::string &stageName) const
Returns the system debug stage handle.
Definition Procgen.cpp:591
image::ImageData * generateTerrainDepositionMap(TerrainErosionMap *erosion, float exposure)
Compatibility deposition facade. @ownership Caller owns the returned image.
Definition Procgen.cpp:1884
eve::Result< ProcgenHeightmapHandleRef > newHeightmapHandle(int width, int height)
Empty in-memory heightmap (caller owns).
Definition Procgen.cpp:1458
uint64_t getPreviousSystemRevision(const std::string &name) const
Revision number of the snapshot retained for hot-reload comparison.
Definition Procgen.cpp:619
static bool isStale(ProcgenParamsHandleRef reference) noexcept
Reports whether a parameter reference is stale.
int getAlgorithmParamCount(const std::string &algorithmId) const
Number of reflected parameters for one algorithm.
Definition Procgen.cpp:803
bool isMeshBuildStale(ProcgenMeshBuildHandleRef) const noexcept
True when mesh build stale.
Definition Procgen.cpp:1264
std::string getSystemDebugReport(const std::string &name) const
Returns the system debug report.
Definition Procgen.cpp:624
eve::Result< ProcgenTerrainSamplerHandleRef > newTerrainSamplerHandle()
Sampling function over continuous map coordinates (caller owns).
Definition Procgen.cpp:1441
eve::script::Borrowed< DynamicMeshUvPaintSession > resolveDynamicMeshUvPaintSession(ProcgenDynamicMeshUvPaintSessionHandleRef reference) noexcept
Resolve dynamic UV paint state for the current synchronous call only.
Definition Procgen.cpp:315
static eve::script::Borrowed< Params > resolve(ProcgenParamsHandleRef reference) noexcept
Resolves parameters as a non-owning observation.
bool isAlgorithmParamAdvanced(const std::string &algorithmId, int index) const
Return true when a parameter should be hidden by compact inspectors.
Definition Procgen.cpp:871
eve::Result< ProcgenSpatialDataHandleRef > differenceSpatialHandle(ProcgenSpatialDataHandleRef left, ProcgenSpatialDataHandleRef right)
Difference spatial handle.
Definition Procgen.cpp:234
bool hasTextureRecipe(const std::string &recipeId) const
True when texture recipe.
Definition Procgen.cpp:1050
eve::script::Borrowed< MeshGraph > resolveMeshGraph(ProcgenMeshGraphHandleRef reference) noexcept
Definition Procgen.cpp:328
eve::Result< ProcgenSpatialDataHandleRef > unionSpatialHandle(ProcgenSpatialDataHandleRef left, ProcgenSpatialDataHandleRef right)
Union spatial handle.
Definition Procgen.cpp:213
eve::script::Borrowed< CloudField > resolveCloudField(ProcgenCloudFieldHandleRef) noexcept
Definition Procgen.cpp:1083
std::string getAlgorithmParamLabel(const std::string &algorithmId, int index) const
Human-readable parameter label at an index.
Definition Procgen.cpp:813
int getAlgorithmParamChoiceCount(const std::string &algorithmId, int index) const
Number of allowed values for a choice parameter.
Definition Procgen.cpp:876
float getAlgorithmParamMaximum(const std::string &algorithmId, int index) const
Numeric maximum.
Definition Procgen.cpp:861
float getAlgorithmParamMinimum(const std::string &algorithmId, int index) const
Numeric minimum.
Definition Procgen.cpp:856
eve::Result< void > configureGtsTerrainTileLods(const GtsTerrainLodSet &lods, int tileIndex, graphics::Renderable3D &renderable, graphics::Graphics &gfx, float worldDiameter, float verticalFovDegrees, float originX=0.f, float originY=0.f, float originZ=0.f)
Upload and atomically attach one GTS tile's LOD chain to a renderable.
Definition Procgen.cpp:1316
float getAlgorithmParamStep(const std::string &algorithmId, int index) const
Suggested numeric editing step.
Definition Procgen.cpp:866
graphics::Mesh * generateTerrainRiverMesh(Heightmap *heightmap, TerrainLayers *layers, graphics::Graphics *gfx, int originX, int originY, int cellsX, int cellsY, float cellSize, float heightScale, float minWidth, float maxWidth, float heightOffset)
Compatibility river mesh facade. @lifetime Returned mesh is owned by Graphics.
Definition Procgen.cpp:1685
bool algorithmParamHasMinimum(const std::string &algorithmId, int index) const
Return true when a numeric minimum is declared.
Definition Procgen.cpp:846
image::ImageData * generateTerrainErosionMap(TerrainErosionMap *erosion, float exposure)
Compatibility erosion facade. @ownership Caller owns the returned image.
Definition Procgen.cpp:1870
data::ByteData * bakeTerrainAsset(Heightmap *heightmap, TerrainLayers *layers, int chunkSize)
Compatibility facade for EVTR baking. @ownership Caller owns the result.
Definition Procgen.cpp:1615
graphics::Shader * createTerrainWaterShader(graphics::Graphics *gfx)
Compatibility water facade. @lifetime Returned shader is owned by Graphics.
Definition Procgen.cpp:1916
TerrainLayers * analyzeTerrainScaled(Heightmap *heightmap, float riverThreshold, float seaLevel, float latitude, float coordinateScale)
Compatibility facade for scaled analysis. @ownership Caller owns the result.
Definition Procgen.cpp:1599
eve::script::Borrowed< ShapeGrammar > resolveShapeGrammar(ProcgenShapeGrammarHandleRef reference) noexcept
Definition Procgen.cpp:336
eve::Result< ProcgenRuntimeGenerationHandleRef > newRuntimeGenerationHandle(uint32_t worldSeed)
Creates a runtime generation handle. @ownership Caller deletes unless documented otherwise.
Definition Procgen.cpp:288
eve::Result< ProcgenPointSetHandleRef > sampleSpatialHandle(ProcgenSpatialDataHandleRef spatial, float spacing, uint32_t seed, float jitter)
Sample spatial handle.
Definition Procgen.cpp:245
graphics::Mesh * generateTerrainRiverMeshAdvanced(Heightmap *heightmap, TerrainLayers *layers, graphics::Graphics *gfx, int originX, int originY, int cellsX, int cellsY, float cellSize, float heightScale, float minWidth, float maxWidth, float heightOffset, float minSurfaceSlope, float maxSurfaceSlope)
Compatibility slope-banded river facade. @lifetime Returned mesh is owned by Graphics.
Definition Procgen.cpp:1693
eve::Result< ProcgenLSystemHandleRef > newLSystemHandle()
Definition Procgen.cpp:292
bool erodeTerrainThermal(Heightmap *heightmap, int iterations, float talus, float strength)
Compatibility facade that applies mass-conserving thermal erosion in place.
Definition Procgen.cpp:1525
eve::Result< float > cloudCoverageAt(ProcgenCloudFieldHandleRef field, float x, float z, float time)
Cloud coverage at world (x, z) and time using a live field handle.
Definition Procgen.cpp:1111
image::ImageData * generateTerrainWearMap(TerrainErosionMap *erosion, float exposure)
Compatibility wear facade. @ownership Caller owns the returned image.
Definition Procgen.cpp:1877
bool isPbrMaterialStale(ProcgenPbrMaterialHandleRef) const noexcept
True when pbr material stale.
Definition Procgen.cpp:1181
image::ImageData * generateTerrainAlbedoMap(TerrainMeshChunk *chunk)
Compatibility albedo facade. @ownership Caller owns the returned image.
Definition Procgen.cpp:1777
eve::script::Borrowed< MeshModifierGraph > resolveMeshModifierGraph(ProcgenMeshModifierGraphHandleRef reference) noexcept
Resolve a mesh modifier graph for the current synchronous call only.
Definition Procgen.cpp:305
void setPaletteGid(const std::string &palette, const std::string &semantic, int gid)
Sets the palette gid.
Definition Procgen.cpp:751
std::string getAlgorithmParamKind(const std::string &algorithmId, int index) const
Parameter kind as int, float, bool, string or choice.
Definition Procgen.cpp:828
eve::Result< void > applyMeshRecipeDefaults(const std::string &recipeId, ProcgenParamsHandleRef params) const
Fill missing mesh parameters in a module-owned parameter object.
Definition Procgen.cpp:1427
std::string getSystemOutputName(const std::string &name, int index) const
Returns the system output name.
Definition Procgen.cpp:560
graphics::Mesh * generateTerrainChunkMesh(TerrainMeshChunk *chunk, graphics::Graphics *gfx)
Compatibility upload facade. @lifetime Returned mesh is owned by Graphics.
Definition Procgen.cpp:1674
eve::Result< ProcgenSpatialDataHandleRef > meshSurfaceDataHandle(ProcgenMeshBuildHandleRef mesh, float tolerance)
Mesh surface data handle.
Definition Procgen.cpp:202
eve::Result< void > applyTextureRecipeDefaults(const std::string &recipeId, ProcgenParamsHandleRef params) const
Fill missing texture parameters in a module-owned parameter object.
Definition Procgen.cpp:1065
eve::Result< void > configurePcgMeshLods(const PcgMeshLodSet &lods, graphics::Renderable3D &renderable, graphics::Graphics &gfx, float worldDiameter, float verticalFovDegrees)
Upload and atomically attach one generic Pcg mesh LOD chain.
Definition Procgen.cpp:1336
eve::script::Borrowed< PbrTextureSet > resolvePbrMaterial(ProcgenPbrMaterialHandleRef) noexcept
Resolve pbr material.
Definition Procgen.cpp:1173
TerrainLayers * analyzeTerrain(Heightmap *heightmap, float riverThreshold, float seaLevel, float latitude)
Compatibility facade for terrain analysis. @ownership Caller owns the result.
Definition Procgen.cpp:1595
eve::Result< ProcgenSpatialDataHandleRef > splineDataHandle(ProcgenPointSetHandleRef controlPoints, float radius)
Spline data handle.
Definition Procgen.cpp:165
std::string getAlgorithmId(int index) const
Returns the algorithm id.
Definition Procgen.cpp:774
bool heightmapToGrid(Heightmap *heightmap, Params *params, Grid2D *out)
Compatibility facade that classifies a heightmap into a semantic Grid2D.
eve::Result< void > applyAlgorithmDefaults(const std::string &algorithmId, ProcgenParamsHandleRef params) const
Fill missing algorithm-specific values from schema defaults.
Definition Procgen.cpp:887
eve::Result< std::string > gridToJson(ProcgenGridHandleRef grid) const
Grid to json.
Definition Procgen.cpp:912
eve::Result< ProcgenNormalImageHandleRef > generateNormalImageHandle(const std::string &recipeId, ProcgenParamsHandleRef params)
Definition Procgen.cpp:957
eve::Result< ProcgenPointSetHandleRef > filterSpatialHandle(ProcgenPointSetHandleRef input, ProcgenSpatialDataHandleRef spatial, bool invert)
Filter spatial handle.
Definition Procgen.cpp:255
image::ImageData * generateTerrainSplatMap(TerrainMeshChunk *chunk)
Compatibility splat facade. @ownership Caller owns the returned image.
Definition Procgen.cpp:1747
eve::script::Borrowed< RuntimeGeneration > resolveRuntimeGeneration(ProcgenRuntimeGenerationHandleRef reference) noexcept
Definition Procgen.cpp:296
eve::Result< ProcgenHeightmapHandleRef > adoptHeightmap(std::unique_ptr< Heightmap > heightmap)
Take ownership of a decoded height field so script can sample it.
Definition Procgen.cpp:1466
eve::Result< void > releaseMeshBuild(ProcgenMeshBuildHandleRef)
Release mesh build.
Definition Procgen.cpp:1260
eve::Result< ProcgenCloudFieldHandleRef > newCloudFieldHandle()
New deterministic, tiling, time-animated cloud field (caller owns).
Definition Procgen.cpp:1079
eve::script::Borrowed< GridGraph > resolveGridGraph(ProcgenGridGraphHandleRef reference) noexcept
Definition Procgen.cpp:324
eve::Result< void > releasePbrMaterial(ProcgenPbrMaterialHandleRef)
Release pbr material.
Definition Procgen.cpp:1177
TerrainErosionMap * erodeTerrainFluvialDetailed(Heightmap *heightmap, int iterations, float riverThreshold, float incision, float maxDepth, float bankWidth, float maxBreachDepth, float coordinateScale)
Compatibility facade for detailed erosion. @ownership Caller owns the result.
Definition Procgen.cpp:1574
eve::Result< ProcgenPointSetHandleRef > getSystemOutputHandle(const std::string &name, const std::string &outputName) const
Returns the system output handle.
Definition Procgen.cpp:578
eve::script::Borrowed< MeshBuild > resolveMeshBuild(ProcgenMeshBuildHandleRef) noexcept
Resolve mesh build.
Definition Procgen.cpp:1256
std::string getAlgorithmParamChoice(const std::string &algorithmId, int paramIndex, int choiceIndex) const
Choice value at an index.
Definition Procgen.cpp:881
bool isCloudFieldStale(ProcgenCloudFieldHandleRef) const noexcept
Definition Procgen.cpp:1091
bool isTerrainSamplerStale(ProcgenTerrainSamplerHandleRef) const noexcept
Definition Procgen.cpp:1454
eve::Result< void > releaseCloudField(ProcgenCloudFieldHandleRef)
Definition Procgen.cpp:1087
eve::Result< ProcgenPbrMaterialHandleRef > generatePbrMaterialHandle(const std::string &recipeId, ProcgenParamsHandleRef params)
Full metallic-roughness PBR set (albedo/normal/roughness/metallic/height/ao) derived from a single di...
Definition Procgen.cpp:1155
std::string getMeshRecipeId(int index) const
Returns the mesh recipe id.
Definition Procgen.cpp:1403
eve::Result< void > abortSystem(ProcgenContextHandleRef context)
Definition Procgen.cpp:518
eve::Result< void > autotileGrid(ProcgenGridHandleRef grid)
Post-process a generated grid: fill each wall cell's detail with an 8-bit neighbour mask (autotile di...
Definition Procgen.cpp:899
eve::script::Borrowed< PointSet > resolvePointSet(ProcgenPointSetHandleRef reference) noexcept
Resolves a point set as a borrowed view.
uint64_t getSystemRevision(const std::string &name) const
Returns the system revision.
Definition Procgen.cpp:540
eve::Result< ProcgenSpatialDataHandleRef > intersectSpatialHandle(ProcgenSpatialDataHandleRef left, ProcgenSpatialDataHandleRef right)
Intersect spatial handle.
Definition Procgen.cpp:223
static eve::Result< ProcgenContextHandleRef > beginCachedSystemHandle(const std::string &name, uint32_t seed, const std::string &buildKey)
Starts a cached module-owned rebuild context and returns its handle.
Definition Procgen.cpp:430
bool hasPbrRecipe(const std::string &recipeId) const
True when pbr recipe.
Definition Procgen.cpp:1200
eve::Result< ProcgenCloudShadowHandleRef > newCloudShadowHandle()
New sun projection over a cloud field → ground shadows (caller owns).
Definition Procgen.cpp:1095
eve::Result< ProcgenSpatialDataHandleRef > boxVolumeHandle(float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
Box volume handle.
Definition Procgen.cpp:140
int getMeshRecipeCount() const
Returns the mesh recipe count.
Definition Procgen.cpp:1397
eve::Result< ProcgenHeightmapHandleRef > generateHeightmapHandle(ProcgenParamsHandleRef params)
Generate heightmap handle.
Definition Procgen.cpp:1494
eve::Result< ProcgenPointSetHandleRef > getPreviousSystemDebugStageHandle(const std::string &name, const std::string &stageName) const
Returns the previous system debug stage handle.
Definition Procgen.cpp:604
std::string getAlgorithmParamKey(const std::string &algorithmId, int index) const
Stable parameter key at an index.
Definition Procgen.cpp:808
uint32_t getSystemSeed(const std::string &name) const
Returns the system seed.
Definition Procgen.cpp:545
eve::Result< void > commitSystem(ProcgenContextHandleRef context)
Definition Procgen.cpp:475
bool hasAlgorithm(const std::string &algorithmId) const
True when algorithm.
Definition Procgen.cpp:780
eve::script::Borrowed< graphics::Texture > generateTextureBorrowed(const std::string &recipeId, ProcgenParamsHandleRef params, graphics::Graphics *gfx)
Uploads a generated recipe to Graphics and returns a borrowed texture.
Definition Procgen.cpp:1014
int getPaletteGid(const std::string &palette, const std::string &semantic) const
Returns the palette gid.
Definition Procgen.cpp:755
std::string getSystemDebugDiffReport(const std::string &name) const
Human-readable point-count changes between the current and previous commits.
Definition Procgen.cpp:645
bool algorithmParamHasMaximum(const std::string &algorithmId, int index) const
Return true when a numeric maximum is declared.
Definition Procgen.cpp:851
eve::Result< ProcgenSpatialDataHandleRef > sphereVolumeHandle(float x, float y, float z, float radius)
Sphere volume handle.
Definition Procgen.cpp:146
std::string getPbrRecipeId(int index) const
Returns the pbr recipe id.
Definition Procgen.cpp:1191
int getSystemOutputCount(const std::string &name) const
Returns the system output count.
Definition Procgen.cpp:555
eve::Result< ProcgenSpatialDataHandleRef > textureMaskDataHandle(ProcgenHeightmapHandleRef values, float originX, float originZ, float cellSize, float minValue, float maxValue, float minY, float maxY)
Texture mask data handle.
Definition Procgen.cpp:189
eve::script::Borrowed< CloudShadow > resolveCloudShadow(ProcgenCloudShadowHandleRef) noexcept
Definition Procgen.cpp:1099
eve::Result< void > releaseTerrainSampler(ProcgenTerrainSamplerHandleRef)
Definition Procgen.cpp:1450
eve::script::Borrowed< PointGraph > resolvePointGraph(ProcgenPointGraphHandleRef reference) noexcept
Resolve point graph.
Definition Procgen.cpp:301
std::string getAlgorithmParamDescription(const std::string &algorithmId, int index) const
Parameter help text at an index.
Definition Procgen.cpp:818
eve::script::Borrowed< Heightmap > resolveHeightmap(ProcgenHeightmapHandleRef) noexcept
Definition Procgen.cpp:1482
std::string getSystemBuildKey(const std::string &name) const
Returns the system build key.
Definition Procgen.cpp:550
eve::script::Borrowed< TerrainSampler > resolveTerrainSampler(ProcgenTerrainSamplerHandleRef) noexcept
Definition Procgen.cpp:1445
int getPbrRecipeCount() const
Returns the pbr recipe count.
Definition Procgen.cpp:1185
eve::Result< ProcgenSpatialDataHandleRef > pointDataHandle(ProcgenPointSetHandleRef points)
Point data handle.
Definition Procgen.cpp:132
std::string getAlgorithmParamCategory(const std::string &algorithmId, int index) const
Parameter group at an index.
Definition Procgen.cpp:823
static eve::Result< ProcgenContextHandleRef > beginSystemHandle(const std::string &name, uint32_t seed)
Starts a module-owned rebuild context and returns its handle.
Definition Procgen.cpp:414
~Procgen() override
Procgen.
Definition Procgen.cpp:130
eve::Result< void > generateTo(const std::string &algorithmId, ProcgenParamsHandleRef params, ProcgenOutputHandleRef output)
Generate to.
Definition Procgen.cpp:694
int getSystemDebugStageCount(const std::string &name) const
Returns the system debug stage count.
Definition Procgen.cpp:566
eve::Result< void > sampleCloud(ProcgenCloudFieldHandleRef field, std::span< float > out, int w, int h, float time, float x0, float z0, float extent)
Samples coverage into a caller-owned buffer after validating its size.
Definition Procgen.cpp:1127
eve::Result< ProcgenPointSetHandleRef > projectToSpatialHandle(ProcgenPointSetHandleRef input, ProcgenSpatialDataHandleRef spatial)
Project to spatial handle.
Definition Procgen.cpp:265
int getAlgorithmCount() const
Returns the algorithm count.
Definition Procgen.cpp:769
eve::script::Borrowed< MeshDeformationSession > resolveMeshDeformationSession(ProcgenMeshDeformationSessionHandleRef reference) noexcept
Resolve a mesh deformation session for the current synchronous call only.
Definition Procgen.cpp:310
uint32_t randomSeed()
Fresh non-zero seed for regenerating a level.
Definition Procgen.cpp:910
eve::Result< float > cloudShadowFactor(ProcgenCloudShadowHandleRef shadow, float x, float z, float time)
Light multiplier in [0,1] using a live shadow handle.
Definition Procgen.cpp:1119
eve::script::Borrowed< SpatialData > resolveSpatialData(ProcgenSpatialDataHandleRef reference) noexcept
Definition Procgen.cpp:276
eve::Result< ProcgenSpatialDataHandleRef > heightfieldDataHandle(ProcgenHeightmapHandleRef heightmap, float originX, float originZ, float cellSize, float heightScale)
Heightfield data handle.
Definition Procgen.cpp:176
bool hasMeshRecipe(const std::string &recipeId) const
True when mesh recipe.
Definition Procgen.cpp:1412
eve::Result< void > releaseCloudShadow(ProcgenCloudShadowHandleRef)
Definition Procgen.cpp:1103
int selectTerrainLod(Heightmap *heightmap, int originX, int originY, int cellsX, int cellsY, int maxLod, float cellSize, float heightScale, float cameraDistance, float viewportHeight, float verticalFovDegrees, float targetPixelError)
Select terrain LOD from measured screen-space geometric error.
Definition Procgen.cpp:1653
PaletteTable & palettes()
Palettes.
Definition Procgen.cpp:1474
bool erodeTerrainFluvialAdvanced(Heightmap *heightmap, int iterations, float riverThreshold, float incision, float maxDepth, float bankWidth, float maxBreachDepth)
Compatibility facade with independent incision and spill-sill limits.
Definition Procgen.cpp:1552
bool hasSystem(const std::string &name) const
Definition Procgen.cpp:536
TerrainMeshChunk * buildTerrainChunk(Heightmap *heightmap, TerrainLayers *layers, int originX, int originY, int cellsX, int cellsY, int lod, float cellSize, float heightScale, float skirtDepth)
Compatibility facade for LOD chunks. @ownership Caller owns the result.
Definition Procgen.cpp:1628
graphics::Mesh * generateTerrainLakeMesh(Heightmap *heightmap, TerrainLayers *layers, graphics::Graphics *gfx, int originX, int originY, int cellsX, int cellsY, float cellSize, float heightScale, float minimumDepth, float heightOffset)
Compatibility lake mesh facade. @lifetime Returned mesh is owned by Graphics.
Definition Procgen.cpp:1723
eve::Result< void > sampleCloudShadow(ProcgenCloudShadowHandleRef shadow, std::span< float > out, int w, int h, float time, float x0, float z0, float extent)
Samples shadow coverage into a caller-owned buffer after validating its size.
Definition Procgen.cpp:1141
std::string getSystemDebugStageName(const std::string &name, int index) const
Returns the system debug stage name.
Definition Procgen.cpp:571
eve::script::Borrowed< SplinePath > resolveSplinePath(ProcgenSplinePathHandleRef reference) noexcept
Resolve a spline path for the current synchronous call only.
Definition Procgen.cpp:320
eve::script::Borrowed< graphics::Mesh > generateMeshBorrowed(const std::string &recipeId, ProcgenParamsHandleRef params, graphics::Graphics *gfx)
Build + upload to GPU Mesh (owned by Graphics).
Definition Procgen.cpp:1295
bool isHeightmapStale(ProcgenHeightmapHandleRef) const noexcept
Definition Procgen.cpp:1490
eve::Result< ProcgenSpatialDataHandleRef > polygonVolumeHandle(ProcgenPointSetHandleRef controlPoints, float minY, float maxY)
Polygon volume handle.
Definition Procgen.cpp:154
static eve::Result< void > release(ProcgenParamsHandleRef reference)
Releases module-owned parameters.
eve::script::Borrowed< OutputSpec > resolveOutput(ProcgenOutputHandleRef reference) noexcept
Resolves an output specification as a borrowed view.
eve::Result< void > applyPbrRecipeDefaults(const std::string &recipeId, ProcgenParamsHandleRef params) const
Fill missing PBR parameters in a module-owned parameter object.
Definition Procgen.cpp:1215
uint32_t deriveSeed(uint32_t parent, const std::string &scope) const
Derive seed.
Definition Procgen.cpp:410
bool isCloudShadowStale(ProcgenCloudShadowHandleRef) const noexcept
Definition Procgen.cpp:1107
std::string getTextureRecipeId(int index) const
Returns the texture recipe id.
Definition Procgen.cpp:1041
bool erodeTerrainFluvial(Heightmap *heightmap, int iterations, float riverThreshold, float incision, float maxDepth, float bankWidth)
Compatibility facade that cuts drainage-connected river valleys in place.
Definition Procgen.cpp:1546
eve::Result< void > applyToLayer(ProcgenGridHandleRef grid, const std::string &palette, map::TileLayer &layer)
Applies to layer.
Definition Procgen.cpp:740
graphics::Shader * createTerrainMaterialShader(graphics::Graphics *gfx)
Compatibility material facade. @lifetime Returned shader is owned by Graphics.
Definition Procgen.cpp:1891
std::string getAlgorithmDisplayName(const std::string &algorithmId) const
Human-readable algorithm label from its schema.
Definition Procgen.cpp:793
eve::script::Borrowed< BiomeRules > resolveBiomeRules(ProcgenBiomeRulesHandleRef reference) noexcept
Definition Procgen.cpp:332
std::string getAlgorithmCategory(const std::string &algorithmId) const
Algorithm category from its schema.
Definition Procgen.cpp:798
eve::Result< void > removeSystem(const std::string &name)
Definition Procgen.cpp:528
eve::Result< ProcgenGridHandleRef > generateHandle(const std::string &algorithmId, ProcgenParamsHandleRef params)
Generate handle.
Definition Procgen.cpp:679
eve::script::Borrowed< graphics::Mesh > uploadMeshBorrowed(const MeshBuild &mesh, graphics::Graphics &gfx)
Upload an existing/composed CPU mesh to Graphics.
Definition Procgen.cpp:1307
static SpatialData meshSurface(const MeshBuild &mesh, float tolerance)
Create a queryable triangle surface from CPU mesh data.
static SpatialData spline(const PointSet &controlPoints, float radius)
Create a polyline domain with a radial influence width.
static SpatialData unite(const SpatialData &a, const SpatialData &b)
Create the union of two domains.
static SpatialData fromPoints(const PointSet &points)
Create spatial data whose domain is the bounds of attributed points.
static SpatialData box(float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
Create an axis-aligned volume; unordered endpoints are normalized.
static SpatialData textureMask(const Heightmap &values, float originX, float originZ, float cellSize, float minValue, float maxValue, float minY, float maxY)
Create an extruded spatial mask from scalar texture data.
static SpatialData subtract(const SpatialData &a, const SpatialData &b)
Create the part of a outside b.
static SpatialData sphere(float x, float y, float z, float radius)
Create a spherical volume. A non-positive radius produces an empty domain.
static SpatialData polygon(const PointSet &controlPoints, float minY, float maxY)
Create an XZ polygon prism between two world-space heights.
static SpatialData intersect(const SpatialData &a, const SpatialData &b)
Create the intersection of two domains.
static SpatialData heightfield(const Heightmap &heightmap, float originX, float originZ, float cellSize, float heightScale)
Create a sampled heightfield surface in world space.
static bool bake(const Heightmap &heightmap, const HydrologyMap &hydrology, const ClimateMap &climate, int chunkSize, std::vector< uint8_t > &out, std::string *error=nullptr)
Compatibility operation that bakes all terrain layers into EVTR.
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.
const HydrologyMap & hydrology() const
Hydrology.
const ClimateMap & climate() const
Climate.
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.
One renderable heightfield chunk plus four ecological material weights.
Definition TerrainMesh.h:27
int getSplatHeight() const
Returns the splat height.
Definition TerrainMesh.h:48
int getBiome(int vertex) const
Return the biome id stored for one mesh vertex, or -1 when out of range.
const MeshBuild & mesh() const
Mesh.
Definition TerrainMesh.h:30
float getMaterialWeight(int vertex, int channel) const
Returns the material weight.
int getSplatWidth() const
Returns the splat width.
Definition TerrainMesh.h:46
int getBaseVertexCount() const
Returns the base vertex count.
Definition TerrainMesh.h:38
static TerrainErosionMap erodeFluvialDetailed(Heightmap &heightmap, const FluvialErosionSettings &settings={})
Cut river valleys and return wear, deposition, and net-change diagnostic layers.
static void erodeHydraulic(Heightmap &heightmap, const HydraulicErosionSettings &settings={})
Grid-based water/sediment simulation that carves channels and deposits sediment.
static HydrologyMap buildHydrology(const Heightmap &heightmap, float riverThreshold=0.025f, float seaLevel=0.25f, float coordinateScale=1.f, bool classifyLakes=true)
Compute D8 drainage, upstream contributing area, and a thresholded river mask.
static ClimateMap buildClimate(const Heightmap &heightmap, const HydrologyMap &hydrology, float seaLevel=0.25f, float latitude=0.35f, float coordinateScale=1.f)
Derive temperature, moisture, and biome layers from terrain and hydrology.
static void erodeThermal(Heightmap &heightmap, const ThermalErosionSettings &settings={})
Relax slopes exceeding the configured talus angle while conserving mass.
static void erodeFluvial(Heightmap &heightmap, const FluvialErosionSettings &settings={})
Cut branching river valleys using depression-free drainage and stream power.
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.
Deterministic terrain height sampling (Red Blob Games / Perlin fBm recipe).
static TerrainSampler fromParams(const Params &params)
From params.
bool has(const std::string &id) const
Test whether a recipe exists.
std::unique_ptr< image::ImageData > generate(const std::string &id, const Params &params, std::string &error) const
Generates an image and transfers its unique ownership to the caller.
const RecipeDescriptor * descriptor(const std::string &id) const
Look up recipe metadata.
std::vector< std::string > list() const
List registered recipe ids.
void registerBuiltins()
Register engine-provided recipes once.
static TextureRecipeRegistry & instance()
Access the process-wide texture recipe registry.
Non-owning observation of a registry-owned object.
Result< void > applyBridgeRecipeDefaults(Params &params)
Atomically fill absent recipe parameters from the selected bridge preset.
void registerProcgenCapabilities()
Registers procgen capabilities.
void clearLiveProcgen(Procgen *instance) noexcept
Clears the live Procgen owner when it matches instance (destructor).
std::string gridToJson(const Grid2D &grid)
Compact JSON for debugging / reload workflows (not full Tiled).
void publishLiveProcgen(Procgen *instance) noexcept
Publishes instance as the live Procgen owner (constructor path).
eve::Result< eve::script::RuntimeHandleRef< Tag > > ownProcgenObject(eve::script::RuntimeObjectRegistry< T, Tag > &registry, eve::script::Owned< T > object)
bool writeGridJson(const Grid2D &grid, const std::string &path, std::string *error)
Writes grid json.
EVENGINE_API_DOMAINS eve::Result< GeneratedArtifact > generateMeshArtifact(std::string_view recipeId, const Params &params, ArtifactId id)
Generate any registered mesh recipe as a CPU artifact.
bool autotileGridInPlace(Grid2D &grid)
Post-process any generated Grid2D: fill each wall cell's detail with an 8-bit neighbour mask describi...
uint32_t deriveSeed(uint32_t parent, const std::string &scope)
Stable label-based seed derivation; independent pipeline branches do not perturb each other.
Definition PointSet.cpp:460
uint32_t randomSeedValue()
Produce a fresh seed suitable for regenerating a level (never 0).
std::unique_ptr< image::ImageData > heightToNormalImage(const std::vector< float > &height, int w, int h, float strength, bool seamless)
Builds a normal-map image and transfers its unique ownership to the caller.
Required provider set for one artifact publication transaction.
One typed, role-named child product inside a composite artifact.
ClimateMap public API.
Complete immutable-once-published artifact record.
HydrologyMap public API.
UI-independent metadata for one procedural recipe parameter.
Definition ParamSchema.h:14
std::vector< std::string > choices
Definition ParamSchema.h:26
static const ArtifactStore & artifactStore(const Procgen &module) noexcept
Borrow the compatibility facade's published CPU artifact store.
Definition Procgen.cpp:1478
static ArtifactId nextCompatibilityArtifactId(Procgen &module) noexcept
Allocates the next compatibility artifact id for legacy mesh-handle paths.
Definition Procgen.cpp:1287
static eve::Result< GeneratedArtifact > buildArtifact(Procgen &module, const std::string &recipeId, ProcgenParamsHandleRef params, ArtifactId id)
Build an owning backend-neutral CPU artifact for a mesh recipe.
Definition Procgen.cpp:1268
static eve::Result< ArtifactPublishReceipt > publishArtifact(Procgen &module, const std::string &recipeId, ProcgenParamsHandleRef params, ArtifactId id, ArtifactPublishOptions options={})
Build then transactionally publish through requested optional adapters.
Definition Procgen.cpp:1278
static eve::Result< RecipeDescriptor > getAlgorithmSchema(const Procgen &module, const std::string &algorithmId)
Returns an owning copy of an algorithm schema or a diagnostic.
Definition Procgen.cpp:784
static eve::Result< RecipeDescriptor > getMeshRecipeSchema(const Procgen &module, const std::string &recipeId)
Returns an owning copy of a mesh schema or a diagnostic.
Definition Procgen.cpp:1417
static eve::Result< RecipeDescriptor > getPbrRecipeSchema(const Procgen &module, const std::string &recipeId)
Returns an owning copy of a PBR schema or a diagnostic.
Definition Procgen.cpp:1205
static eve::Result< RecipeDescriptor > getTextureRecipeSchema(const Procgen &module, const std::string &recipeId)
Returns an owning copy of a texture schema or a diagnostic.
Definition Procgen.cpp:1055
Module-owned registries and mutable caches behind the Procgen facade.
Complete metadata and parameter schema shared by every procgen recipe family.
Definition ParamSchema.h:52
std::vector< ParamDescriptor > params
Definition ParamSchema.h:56
TerrainBands public API.
static TerrainBands fromParams(const Params &params)
From params.
Per-cell diagnostic outputs produced by an erosion stage.
TerrainLakeMeshSettings public API.
TerrainMeshSettings public API.
Definition TerrainMesh.h:12
TerrainRiverMeshSettings public API.
Definition TerrainMesh.h:91
Handle plus owner-lifetime epoch for a non-ECS registry object.