载入中...
搜索中...
未找到
HouseComponentLibrary.cpp
浏览该文件的文档.
2#include <assimp/material.h>
3#include <assimp/matrix4x4.h>
4#include <assimp/scene.h>
5#include <assimp/texture.h>
6#include <algorithm>
7#include <cmath>
8#include <cstdlib>
9#include <filesystem>
10#include <fstream>
11#include <functional>
12#include <glm/mat4x4.hpp>
13#include <memory>
14#include <simplesquirrel/simplesquirrel.hpp>
15#include <sstream>
16#include <stdexcept>
17#include <tuple>
18#include <unordered_map>
19#include <unordered_set>
20#include <utility>
21#include "common/Json.h"
23#include "data/ByteData.h"
24#include "graphics/Graphics.h"
26#include "graphics/Texture.h"
27#include "image/Image.h"
28#include "image/ImageData.h"
29#include "model3d/Model3D.h"
30#include "model3d/ModelData.h"
31#include "procgen/Semantic.h"
34
35// HouseComponentLibrary.cpp
36namespace eve::housegen {
37namespace {
38
40
42glm::mat4 aiToGlm(const aiMatrix4x4& m) {
43 return glm::mat4(m.a1, m.b1, m.c1, m.d1, m.a2, m.b2, m.c2, m.d2, m.a3, m.b3, m.c3, m.d3, m.a4, m.b4, m.c4, m.d4);
44}
45
46eve::Result<SocketDirection> parseDirection(std::string_view value) {
54 eve::DiagnosticCode::InvalidArgument, "socket direction is invalid", "direction", {}, "housegen.components"));
55}
56
57eve::Result<HouseComponent> parseComponent(Value object) {
58 if (!object.isObject())
60 eve::DiagnosticCode::ParseError, "component must be an object", {}, {}, "housegen.components"));
61
62 HouseComponent out;
63 out.id = object.getString("id");
64 out.modelPath = object.getString("model");
65 out.category = object.getString("category");
66 out.width = object.getInt("width", 1);
67 out.depth = object.getInt("depth", 1);
68 out.height = object.getInt("height", 1);
69 out.weight = object.getInt("weight", 1);
70 out.tags = object.getStringArray("tags");
71 if (object.get("rotations").isArray()) out.rotations = object.getIntArray("rotations");
72
73 const Value sockets = object.get("sockets");
74 for (size_t i = 0; i < sockets.size(); ++i) {
75 const Value socketObject = sockets.at(i);
76 if (!socketObject.isObject())
78 eve::DiagnosticCode::ParseError, "socket must be an object", "sockets", {}, "housegen.components"));
79 auto direction = parseDirection(socketObject.getString("direction"));
81
82 HouseSocket socket;
83 socket.direction = std::move(direction).takeValue();
84 socket.type = socketObject.getString("type");
85 socket.accepts = socketObject.getStringArray("accepts");
86 if (socket.type.empty())
88 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "socket needs a valid direction and type",
89 "sockets", {}, "housegen.components"));
90 out.sockets.push_back(std::move(socket));
91 }
92
93 const Value material = object.get("material");
94 if (material.isObject()) {
95 const Value color = material.get("baseColor");
96 if (color.isArray()) {
97 if (color.size() != 3 && color.size() != 4)
99 eve::DiagnosticCode::InvalidArgument, "material baseColor needs 3 or 4 values",
100 "material.baseColor", {}, "housegen.components"));
101 out.material.hasBaseColor = true;
102 out.material.baseColorR = color.at(0).asFloat();
103 out.material.baseColorG = color.at(1).asFloat();
104 out.material.baseColorB = color.at(2).asFloat();
105 out.material.baseColorA = color.size() == 4 ? color.at(3).asFloat() : 1.f;
106 }
107 out.material.baseColorTexture = material.getString("baseColorTexture");
108 out.material.normalTexture = material.getString("normalTexture");
109 out.material.heightTexture = material.getString("heightTexture");
110 if (material.has("metallic")) {
111 out.material.hasMetallic = true;
112 out.material.metallic = material.getFloat("metallic");
113 }
114 if (material.has("roughness")) {
115 out.material.hasRoughness = true;
116 out.material.roughness = material.getFloat("roughness");
117 }
118 out.material.parallaxScale = material.getFloat("parallaxScale", 0.f);
119 out.material.parallaxMinLayers = material.getFloat("parallaxMinLayers", 8.f);
120 out.material.parallaxMaxLayers = material.getFloat("parallaxMaxLayers", 32.f);
121 out.material.cellBombScale = material.getFloat("cellBombScale", 4.f);
122 out.material.cellBombStrength = material.getFloat("cellBombStrength", 0.f);
123 out.material.cellBombRotation = material.getFloat("cellBombRotation", 1.f);
124 }
125 return eve::Result<HouseComponent>::success(std::move(out));
126}
127
128} // namespace
129
131 if (component.id.empty() || component.modelPath.empty() || component.category.empty())
133 "component needs id, model and category", {}, {},
134 "housegen.components"));
135 if (component.width < 1 || component.depth < 1 || component.height < 1 || component.weight < 1)
137 "component dimensions and weight must be positive", {},
138 {}, "housegen.components"));
139 for (const int rotation : component.rotations) {
140 if (rotation < 0 || rotation >= 360 || rotation % 90 != 0)
142 "rotations must be cardinal degrees", "rotations",
143 {}, "housegen.components"));
144 }
145
146 const auto inUnitRange = [](float value) { return value >= 0.f && value <= 1.f; };
147 if ((component.material.hasBaseColor &&
148 (!inUnitRange(component.material.baseColorR) || !inUnitRange(component.material.baseColorG) ||
149 !inUnitRange(component.material.baseColorB) || !inUnitRange(component.material.baseColorA))) ||
150 (component.material.hasMetallic && !inUnitRange(component.material.metallic)) ||
151 (component.material.hasRoughness && !inUnitRange(component.material.roughness)) ||
152 !inUnitRange(component.material.cellBombStrength) || !inUnitRange(component.material.cellBombRotation))
154 "material values must be between 0 and 1", "material",
155 {}, "housegen.components"));
156 if (component.material.parallaxScale < 0.f || component.material.parallaxScale > 0.2f ||
157 component.material.parallaxMinLayers < 1.f ||
159 component.material.cellBombScale <= 0.f)
161 "material sampling parameters are invalid", "material",
162 {}, "housegen.components"));
163 if (components_.contains(component.id))
165 eve::DiagnosticCode::Conflict, "duplicate component id: " + component.id, "id", {}, "housegen.components"));
166
167 components_.emplace(component.id, component);
169}
170
172 std::string parseError;
173 const eve::json::Document document = eve::json::Document::parse(std::string(json), &parseError);
174 if (!document.valid())
176 eve::DiagnosticCode::ParseError, parseError.empty() ? "invalid component manifest" : parseError, {}, {},
177 "housegen.components"));
178
179 const Value root = document.root();
180 const Value values = root.isArray() ? root : root.get("components");
181 if (!values.isArray())
183 eve::DiagnosticCode::ParseError, "expected components array", "components", {}, "housegen.components"));
184
185 HouseComponentLibrary candidate;
186 for (size_t i = 0; i < values.size(); ++i) {
187 auto component = parseComponent(values.at(i));
188 if (!component.ok()) return eve::Result<void>::failure(component.status());
189 auto registered = candidate.registerComponent(std::move(component).takeValue());
190 if (!registered.ok()) return registered;
191 }
192 components_ = std::move(candidate.components_);
194}
195
197 const std::string path(filename);
198 std::ifstream input(path, std::ios::binary);
199 if (!input)
201 eve::DiagnosticCode::NotFound, "cannot open component manifest: " + path, path, {}, "housegen.components"));
202
203 std::ostringstream json;
204 json << input.rdbuf();
205 HouseComponentLibrary candidate;
206 auto loaded = candidate.loadFromJson(json.str());
207 if (!loaded.ok()) return loaded;
208
209 const std::filesystem::path assetRoot = std::filesystem::absolute(std::filesystem::path(path)).parent_path();
210 for (auto &[_, component] : candidate.components_) {
211 std::filesystem::path model(component.modelPath);
212 if (model.is_relative()) component.modelPath = (assetRoot / model).lexically_normal().string();
213 }
214 components_ = std::move(candidate.components_);
216}
217
218void HouseComponentLibrary::clear() { components_.clear(); }
219
221 const auto it = components_.find(std::string(id));
222 if (it == components_.end()) return {};
223 return std::cref(it->second);
224}
225
226int HouseComponentLibrary::count() const { return int(components_.size()); }
227
228std::vector<std::string> HouseComponentLibrary::ids() const {
229 std::vector<std::string> result;
230 result.reserve(components_.size());
231 for (const auto &[id, _] : components_) result.push_back(id);
232 std::sort(result.begin(), result.end());
233 return result;
234}
235
236std::vector<std::reference_wrapper<const HouseComponent>> HouseComponentLibrary::byCategory(
237 std::string_view category, std::string_view style) const {
238 std::vector<std::reference_wrapper<const HouseComponent>> result;
239 for (const auto &[_, component] : components_) {
240 if (component.category == category &&
241 (style.empty() || std::find(component.tags.begin(), component.tags.end(), style) != component.tags.end()))
242 result.push_back(std::cref(component));
243 }
244 if (result.empty() && !style.empty()) return byCategory(category, {});
245 std::sort(result.begin(), result.end(),
246 [](const auto &left, const auto &right) { return left.get().id < right.get().id; });
247 return result;
248}
249
250bool HouseComponentLibrary::hasCompletePack(std::string_view style) const {
251 if (style.empty()) return false;
252 static constexpr const char *core[] = {"foundation", "floor", "wall", "door", "roof"};
253 for (const char *category : core) {
254 bool present = false;
255 for (const auto &[_, component] : components_)
256 if (component.category == category &&
257 std::find(component.tags.begin(), component.tags.end(), style) != component.tags.end()) {
258 present = true;
259 break;
260 }
261 if (!present) return false;
262 }
263 return true;
264}
265
266std::vector<std::string> HouseComponentLibrary::completePacks() const {
267 std::vector<std::string> styles;
268 for (const auto &[_, component] : components_)
269 for (const std::string &tag : component.tags)
270 if (std::find(styles.begin(), styles.end(), tag) == styles.end()) styles.push_back(tag);
271 std::vector<std::string> result;
272 for (const std::string &style : styles)
273 if (hasCompletePack(style)) result.push_back(style);
274 std::sort(result.begin(), result.end());
275 return result;
276}
277
278} // namespace eve::housegen
279
280// HouseGen.cpp
281namespace eve::housegen {
282
283eve::Result<void> HouseGen::loadComponentsFromJson(const std::string &json) { return library_.loadFromJson(json); }
285 return library_.loadFromFile(filename);
286}
287void HouseGen::clearComponents() { library_.clear(); }
288int HouseGen::getComponentCount() const { return library_.count(); }
289HouseRequest HouseGen::newRequest() const { return {}; }
290HouseLayout HouseGen::newLayout() const { return {}; }
292 HouseGenerator generator(library_);
293 return generator.generate(request, layout);
294}
295
296void exposeHouseGeneration(ssq::Table &table) {
297 const HSQUIRRELVM vm = table.getHandle();
298 auto cls = table.addClass<HouseGen>("HouseGen", std::function<HouseGen *()>([] { return new HouseGen(); }), true);
300 auto request = table.addClass<HouseRequest>(
301 "HouseRequest", std::function<HouseRequest *()>([] { return new HouseRequest(); }), true);
302 request.addFunc("setSeed", [](HouseRequest *r, int v) { r->seed = uint32_t(v); });
303 request.addFunc("setPlot", [](HouseRequest *r, int w, int d) {
304 r->width = w;
305 r->depth = d;
306 });
307 request.addFunc("setFloors", [](HouseRequest *r, int v) { r->floors = v; });
308 request.addFunc("setModuleSize", [](HouseRequest *r, float v) { r->moduleSize = v; });
309 request.addFunc("setFloorHeight", [](HouseRequest *r, float v) { r->floorHeight = v; });
310 request.addFunc("setStyle", [](HouseRequest *r, const std::string &v) { r->style = v; });
311 request.addFunc("setFootprint", [](HouseRequest *r, const std::string &v) { r->footprint = v; });
312 request.addFunc("setRoof", [](HouseRequest *r, const std::string &v) { r->roof = v; });
313 request.addFunc("setEntrance", [](HouseRequest *r, const std::string &v) { r->entrance = v; });
314 request.addFunc("setRequiredRooms", [](HouseRequest *r, const std::string &csv) {
315 r->requiredRooms.clear();
316 std::string current;
317 for (const char c : csv) {
318 if (c == ',') {
319 if (!current.empty()) r->requiredRooms.push_back(current);
320 current.clear();
321 } else {
322 current.push_back(c);
323 }
324 }
325 if (!current.empty()) r->requiredRooms.push_back(current);
326 });
327 request.addFunc("setPerimeter", [](HouseRequest *r, const std::string &csv) {
328 r->perimeter.clear();
329 std::string segment;
330 for (size_t i = 0; i <= csv.size(); ++i) {
331 if (i == csv.size() || csv[i] == ';') {
332 const size_t comma = segment.find(',');
333 if (comma != std::string::npos)
334 r->perimeter.push_back({float(std::atof(segment.substr(0, comma).c_str())),
335 float(std::atof(segment.substr(comma + 1).c_str()))});
336 segment.clear();
337 } else {
338 segment.push_back(csv[i]);
339 }
340 }
341 });
342 auto layout = table.addClass<HouseLayout>("HouseLayout",
343 std::function<HouseLayout *()>([] { return new HouseLayout(); }), true);
344 layout.addFunc("toJson", &HouseLayout::toJson);
345 layout.addFunc("fromJson", [vm](HouseLayout *value, const std::string &json) {
346 if (!value)
349 "layout receiver must not be null", "layout", {},
350 "housegen.squirrel")));
351 return eve::script::projectResult(vm, value->fromJson(json));
352 });
353 layout.addFunc("getInstanceCount", [](HouseLayout *v) { return int(v->instances.size()); });
354 layout.addFunc("getInstanceComponentId", [](HouseLayout *v, int i) {
355 return (v && i >= 0 && i < int(v->instances.size())) ? v->instances[i].componentId : std::string();
356 });
357 layout.addFunc("getInstanceX", [](HouseLayout *v, int i) {
358 return (v && i >= 0 && i < int(v->instances.size())) ? v->instances[i].x : 0;
359 });
360 layout.addFunc("getInstanceY", [](HouseLayout *v, int i) {
361 return (v && i >= 0 && i < int(v->instances.size())) ? v->instances[i].y : 0;
362 });
363 layout.addFunc("getInstanceZ", [](HouseLayout *v, int i) {
364 return (v && i >= 0 && i < int(v->instances.size())) ? v->instances[i].z : 0;
365 });
366 layout.addFunc("getInstanceRotationDeg", [](HouseLayout *v, int i) {
367 return (v && i >= 0 && i < int(v->instances.size())) ? v->instances[i].rotationDeg : 0;
368 });
369 layout.addFunc("getFloorHeight", [](HouseLayout *v) { return v ? v->floorHeight : 3.f; });
370 layout.addFunc("getFootprintStyle", [](HouseLayout *v) { return v ? v->footprintStyle : std::string(); });
371 layout.addFunc("getRoofStyle", [](HouseLayout *v) { return v ? v->roofStyle : std::string(); });
372 layout.addFunc("getRoomCount", [](HouseLayout *v) { return v ? int(v->rooms.size()) : 0; });
373 layout.addFunc("getDiagnosticCount", [](HouseLayout *v) { return int(v->diagnostics.size()); });
374 layout.addFunc("writeFootprintGrid", [vm](HouseLayout *value, procgen::Grid2D *output) {
375 if (!value || !output)
378 "layout and output grid are required",
379 "writeFootprintGrid", {}, "housegen.squirrel")));
380 return eve::script::projectResult(vm, value->writeFootprintGrid(*output));
381 });
382 layout.addFunc("writeComponentPoints", [vm](HouseLayout *value, procgen::PointSet *output) {
383 if (!value || !output)
386 eve::DiagnosticCode::InvalidArgument, "layout and output point set are required",
387 "writeComponentPoints", {}, "housegen.squirrel")));
388 return eve::script::projectResult(vm, value->writeComponentPoints(*output));
389 });
390}
397
398void HouseGen::expose(ssq::Class &cls) {
399 const HSQUIRRELVM vm = cls.getHandle();
400 cls.addFunc("loadComponentsFromJson", [vm](HouseGen *value, const std::string &json) {
401 if (!value)
404 "HouseGen receiver must not be null", "housegen",
405 {}, "housegen.squirrel")));
406 return eve::script::projectResult(vm, value->loadComponentsFromJson(json));
407 });
408 cls.addFunc("loadComponentsFromFile", [vm](HouseGen *value, const std::string &filename) {
409 if (!value)
412 "HouseGen receiver must not be null", "housegen",
413 {}, "housegen.squirrel")));
414 return eve::script::projectResult(vm, value->loadComponentsFromFile(filename));
415 });
416 cls.addFunc("clearComponents", &HouseGen::clearComponents);
417 cls.addFunc("getComponentCount", &HouseGen::getComponentCount);
418 cls.addFunc("newRequest", &HouseGen::newRequest);
419 cls.addFunc("newLayout", &HouseGen::newLayout);
420 cls.addFunc("generate", [vm](HouseGen *value, HouseRequest *request, HouseLayout *layout) {
421 if (!value || !request || !layout)
424 "HouseGen, request and layout are required",
425 "generate", {}, "housegen.squirrel")));
426 return eve::script::projectResult(vm, value->generate(*request, *layout));
427 });
428 cls.addFunc(
429 "instantiate", [vm](HouseGen *value, HouseLayout *layout, graphics::Graphics *gfx, model3d::Model3D *models) {
430 if (!value || !layout || !gfx || !models)
433 eve::DiagnosticCode::InvalidArgument, "HouseGen, layout, graphics and model3d are required",
434 "instantiate", {}, "housegen.squirrel")));
435 return eve::script::projectResult(vm, value->instantiate(*layout, *gfx, *models));
436 });
437}
438
439} // namespace eve::housegen
440
441// HouseLayout.cpp
442namespace eve::housegen {
443namespace {
444std::string esc(const std::string &v) {
445 std::string o;
446 for (char c : v) {
447 if (c == '\\' || c == '"') o += '\\';
448 o += c;
449 }
450 return o;
451}
452
453graphics::Texture *textureFromEmbedded(graphics::Graphics *gfx, const aiTexture *source) {
454 if (!source || !source->pcData) return nullptr;
455 if (source->mHeight == 0) {
456 data::ByteData bytes(source->pcData, static_cast<size_t>(source->mWidth));
457 std::unique_ptr<image::ImageData> decoded(image::Image::create()->newImageData(&bytes));
458 return gfx->newTexture(decoded.get(), graphics::TextureCreateInfo::withMipmaps(true));
459 }
460 std::vector<uint8_t> rgba(size_t(source->mWidth) * size_t(source->mHeight) * 4);
461 for (size_t pixel = 0; pixel < size_t(source->mWidth) * size_t(source->mHeight); ++pixel) {
462 rgba[pixel * 4 + 0] = source->pcData[pixel].r;
463 rgba[pixel * 4 + 1] = source->pcData[pixel].g;
464 rgba[pixel * 4 + 2] = source->pcData[pixel].b;
465 rgba[pixel * 4 + 3] = source->pcData[pixel].a;
466 }
467 return gfx->newTexture(int(source->mWidth), int(source->mHeight), rgba.data(),
469}
470
471graphics::Texture *textureFromFile(graphics::Graphics *gfx, const std::string &modelPath,
472 const std::string &texturePath) {
473 if (texturePath.empty()) return nullptr;
474 std::filesystem::path resolved(texturePath);
475 if (resolved.is_relative()) resolved = std::filesystem::path(modelPath).parent_path() / resolved;
476 try {
477 if (std::filesystem::is_regular_file(resolved)) {
478 std::ifstream input(resolved, std::ios::binary | std::ios::ate);
479 const std::streamsize size = input.tellg();
480 if (size <= 0) return nullptr;
481 input.seekg(0, std::ios::beg);
482 std::vector<uint8_t> bytes(static_cast<size_t>(size));
483 if (!input.read(reinterpret_cast<char *>(bytes.data()), size)) return nullptr;
484 data::ByteData source(bytes.data(), bytes.size());
485 std::unique_ptr<image::ImageData> decoded(image::Image::create()->newImageData(&source));
486 return gfx->newTexture(decoded.get(), graphics::TextureCreateInfo::withMipmaps(true));
487 }
488 return gfx->newTextureFromFile(resolved.lexically_normal().string());
489 } catch (...) {
490 return nullptr;
491 }
492}
493
494graphics::Texture *assimpTexture(graphics::Graphics *gfx, const aiScene *scene, const aiMaterial *material,
495 const std::string &modelPath, aiTextureType primary, aiTextureType fallback) {
496 if (!scene || !material) return nullptr;
497 aiString texturePath;
498 if (material->GetTexture(primary, 0, &texturePath) != AI_SUCCESS &&
499 material->GetTexture(fallback, 0, &texturePath) != AI_SUCCESS)
500 return nullptr;
501 const std::string path = texturePath.C_Str();
502 if (path.empty()) return nullptr;
503 if (path.front() == '*') {
504 const int index = std::atoi(path.c_str() + 1);
505 if (index < 0 || static_cast<unsigned>(index) >= scene->mNumTextures) return nullptr;
506 try {
507 return textureFromEmbedded(gfx, scene->mTextures[index]);
508 } catch (...) {
509 return nullptr;
510 }
511 }
512 return textureFromFile(gfx, modelPath, path);
513}
514
521struct ModelHandle {
524
526 [[nodiscard]] model3d::ModelData *get() const noexcept {
527 // The cache registry stores Resource, so a pinned entry needs the same explicit
528 // downcast the cache's own loaders use.
529 return owned ? owned.get() : static_cast<model3d::ModelData *>(pinned.get());
530 }
531};
532
533ModelHandle loadModel(model3d::Model3D *models, const std::string &path) {
534 if (!std::filesystem::is_regular_file(std::filesystem::path(path))) {
535 // The module hands back the cache-owned resource, so pin it: this layout keeps
536 // using the model after the cache entry may have been unloaded.
537 model3d::ModelData *cached = models->newModelDataFromFile(path);
538 if (cached == nullptr) return {};
540 if (!pinned.ok()) return {};
541 ModelHandle handle;
542 handle.pinned = std::move(pinned).takeValue();
543 return handle;
544 }
545 std::ifstream input(path, std::ios::binary | std::ios::ate);
546 if (!input) throw std::runtime_error("cannot open model: " + path);
547 const std::streamsize size = input.tellg();
548 if (size <= 0) throw std::runtime_error("model is empty: " + path);
549 input.seekg(0, std::ios::beg);
550 std::vector<uint8_t> bytes(static_cast<size_t>(size));
551 if (!input.read(reinterpret_cast<char *>(bytes.data()), size))
552 throw std::runtime_error("cannot read model: " + path);
553 data::ByteData source(bytes.data(), bytes.size());
554 ModelHandle handle;
555 handle.owned.reset(models->newModelData(&source, std::filesystem::path(path).extension().string()));
556 return handle;
557}
558} // namespace
559
561 instances.clear();
562 rooms.clear();
563 diagnostics.clear();
564 footprintMask.clear();
565 seed = 1;
566 moduleSize = 1.f;
567 floorHeight = 3.f;
568 footprintWidth = 0;
569 footprintDepth = 0;
570 footprintStyle = "rectangle";
571 roofStyle = "gable";
572 entranceSide = "north";
573}
574
575std::string HouseLayout::toJson() const {
576 std::ostringstream o;
577 o << "{\"schema\":\"eve.house-layout\",\"version\":1,\"seed\":" << seed << ",\"moduleSize\":" << moduleSize
578 << ",\"floorHeight\":" << floorHeight << ",\"footprintStyle\":\"" << esc(footprintStyle) << "\",\"roofStyle\":\""
579 << esc(roofStyle) << "\",\"entranceSide\":\"" << esc(entranceSide) << "\",\"footprintWidth\":" << footprintWidth
580 << ",\"footprintDepth\":" << footprintDepth << ",\"footprintMask\":\"";
581 for (const uint8_t cell : footprintMask) o << (cell ? '1' : '0');
582 o << "\",\"instances\":[";
583 for (size_t i = 0; i < instances.size(); ++i) {
584 const auto &v = instances[i];
585 if (i) o << ',';
586 o << "{\"componentId\":\"" << esc(v.componentId) << "\",\"x\":" << v.x << ",\"y\":" << v.y << ",\"z\":" << v.z
587 << ",\"rotationDeg\":" << v.rotationDeg << '}';
588 }
589 o << "],\"rooms\":[";
590 for (size_t i = 0; i < rooms.size(); ++i) {
591 const auto &v = rooms[i];
592 if (i) o << ',';
593 o << "{\"type\":\"" << esc(v.type) << "\",\"x\":" << v.x << ",\"y\":" << v.y << ",\"z\":" << v.z
594 << ",\"width\":" << v.width << ",\"depth\":" << v.depth << '}';
595 }
596 o << "],\"diagnostics\":[";
597 for (size_t i = 0; i < diagnostics.size(); ++i) {
598 if (i) o << ',';
599 o << '"' << esc(diagnostics[i]) << '"';
600 }
601 o << "]}";
602 return o.str();
603}
604
606 using eve::json::Value;
607 std::string parseError;
608 const eve::json::Document doc = eve::json::Document::parse(std::string(json), &parseError);
609 if (!doc.valid())
611 eve::DiagnosticCode::ParseError, parseError.empty() ? "invalid house layout JSON" : parseError, {}, {},
612 "housegen.layout"));
613 const Value o = doc.root();
614 if (!o.isObject())
616 eve::DiagnosticCode::ParseError, "layout must be an object", {}, {}, "housegen.layout"));
617 const std::string schema = o.getString("schema", "eve.house-layout");
618 const int version = o.getInt("version", 1);
619 if (schema != "eve.house-layout" || version != 1)
621 "unsupported house layout schema or version", "schema",
622 {}, "housegen.layout"));
623
624 HouseLayout parsed;
625 parsed.seed = static_cast<unsigned>(o.getInt("seed", 1));
626 parsed.moduleSize = o.getFloat("moduleSize", 1.f);
627 parsed.floorHeight = o.getFloat("floorHeight", 3.f);
628 parsed.footprintStyle = o.getString("footprintStyle", "rectangle");
629 parsed.roofStyle = o.getString("roofStyle", "gable");
630 parsed.entranceSide = o.getString("entranceSide", "north");
631 parsed.footprintWidth = o.getInt("footprintWidth", 0);
632 parsed.footprintDepth = o.getInt("footprintDepth", 0);
633 const std::string footprintBits = o.getString("footprintMask", "");
634 if (parsed.footprintWidth < 0 || parsed.footprintDepth < 0 ||
635 size_t(parsed.footprintWidth) * size_t(parsed.footprintDepth) != footprintBits.size())
637 "invalid canonical footprint mask", "footprintMask",
638 {}, "housegen.layout"));
639 for (const char bit : footprintBits) {
640 if (bit != '0' && bit != '1')
642 "footprint mask must contain only 0 or 1",
643 "footprintMask", {}, "housegen.layout"));
644 parsed.footprintMask.push_back(bit == '1' ? 1 : 0);
645 }
646 if (!std::isfinite(parsed.moduleSize) || parsed.moduleSize <= 0.f || !std::isfinite(parsed.floorHeight) ||
647 parsed.floorHeight <= 0.f)
649 eve::DiagnosticCode::InvalidArgument, "moduleSize and floorHeight must be finite and positive", {}, {},
650 "housegen.layout"));
651
652 const Value instances = o.get("instances");
653 if (!instances.isArray())
655 eve::DiagnosticCode::ParseError, "layout has no instances", "instances", {}, "housegen.layout"));
656 for (size_t i = 0; i < instances.size(); ++i) {
657 const Value v = instances.at(i);
658 // componentId and the cell coordinates are required, not defaulted.
659 if (!v.has("componentId") || !v.has("x") || !v.has("y") || !v.has("z"))
661 "instance needs componentId, x, y and z",
662 "instances", {}, "housegen.layout"));
663 parsed.instances.push_back(
664 {v.getString("componentId"), v.getInt("x"), v.getInt("y"), v.getInt("z"), v.getInt("rotationDeg", 0)});
665 }
666
667 const Value rooms = o.get("rooms");
668 for (size_t i = 0; i < rooms.size(); ++i) {
669 const Value v = rooms.at(i);
670 if (!v.has("type") || !v.has("x") || !v.has("y") || !v.has("width") || !v.has("depth"))
672 "room needs type, x, y, width and depth", "rooms",
673 {}, "housegen.layout"));
674 parsed.rooms.push_back({v.getString("type"), v.getInt("x"), v.getInt("y"), v.getInt("z", 0), v.getInt("width"),
675 v.getInt("depth")});
676 }
677
678 parsed.diagnostics = o.getStringArray("diagnostics");
679 *this = std::move(parsed);
681}
682
684 if (!std::isfinite(moduleSize) || moduleSize <= 0.f || !std::isfinite(floorHeight) || floorHeight <= 0.f)
686 eve::DiagnosticCode::InvalidArgument, "moduleSize and floorHeight must be finite and positive", {}, {},
687 "housegen.layout"));
688 if (footprintWidth <= 0 || footprintDepth <= 0 ||
689 footprintMask.size() != size_t(footprintWidth) * size_t(footprintDepth))
691 "house layout has no canonical footprint mask",
692 "footprintMask", {}, "housegen.layout"));
693 for (const auto &instance : instances)
694 if (instance.x >= footprintWidth || instance.y >= footprintDepth ||
695 !footprintMask[size_t(instance.y * footprintWidth + instance.x)])
697 eve::DiagnosticCode::InvalidArgument, "house instance origin is outside the canonical footprint",
698 instance.componentId, {}, "housegen.layout"));
699 for (const HouseRoom &room : rooms) {
700 if (room.x < 0 || room.y < 0 || room.width <= 0 || room.depth <= 0 || room.x + room.width > footprintWidth ||
701 room.y + room.depth > footprintDepth)
703 "room lies outside the canonical footprint",
704 "rooms", {}, "housegen.layout"));
705 for (int y = room.y; y < room.y + room.depth; ++y)
706 for (int x = room.x; x < room.x + room.width; ++x)
707 if (!footprintMask[size_t(y * footprintWidth + x)])
709 "room contains an inactive footprint cell",
710 "rooms", {}, "housegen.layout"));
711 }
712 std::unordered_set<std::string> occupied;
713 std::unordered_set<std::string> floorCells, roofCells;
714 std::vector<std::tuple<int, int, int>> floors;
715 auto cellKey = [](int x, int y, int z) {
716 return std::to_string(x) + ":" + std::to_string(y) + ":" + std::to_string(z);
717 };
718 bool entrance = false, roof = false;
719 for (const auto &i : instances) {
720 const auto component = library.find(i.componentId);
721 if (!component)
723 "unknown component: " + i.componentId,
724 "componentId", {}, "housegen.layout"));
725 const HouseComponent &c = component->get();
726 const int normalizedRotation = (i.rotationDeg % 360 + 360) % 360;
727 if (normalizedRotation % 90 != 0)
729 eve::DiagnosticCode::InvalidArgument, "non-cardinal rotation", "rotationDeg", {}, "housegen.layout"));
730 const bool rotationAllowed = std::any_of(c.rotations.begin(), c.rotations.end(), [&](int allowed) {
731 return (allowed % 360 + 360) % 360 == normalizedRotation;
732 });
733 if (!rotationAllowed)
735 "component does not allow the requested rotation",
736 "rotationDeg", {}, "housegen.layout"));
737 const bool quarter = (normalizedRotation / 90) % 2 != 0;
738 const int w = quarter ? c.depth : c.width, d = quarter ? c.width : c.depth;
739 for (int y = 0; y < d; ++y)
740 for (int x = 0; x < w; ++x) {
741 // Boundary cells legitimately carry two perpendicular wall modules at corners.
742 const bool orientedBoundary = c.category == "wall" || c.category == "door" ||
743 c.category == "interior_wall" || c.category == "interior_door";
744 const std::string orientation =
745 orientedBoundary ? ":" + std::to_string((i.rotationDeg % 360 + 360) % 360) : "";
746 const std::string key = std::to_string(i.x + x) + ":" + std::to_string(i.y + y) + ":" +
747 std::to_string(i.z) + ":" + c.category + orientation;
748 if (!occupied.insert(key).second)
751 "overlapping " + c.category + " components", {}, {}, "housegen.layout"));
752 if (c.category == "floor") {
753 floorCells.insert(cellKey(i.x + x, i.y + y, i.z));
754 floors.emplace_back(i.x + x, i.y + y, i.z);
755 } else if (c.category == "roof") {
756 roofCells.insert(cellKey(i.x + x, i.y + y, i.z));
757 }
758 }
759 entrance = entrance || (c.category == "door" && i.z == 0);
760 roof = roof || c.category == "roof";
761 }
762 if (!entrance)
764 "house has no entrance", {}, {}, "housegen.layout"));
765 if (!roof)
767 "house has no roof", {}, {}, "housegen.layout"));
768 for (const auto &[x, y, z] : floors) {
769 if (z > 0 && !floorCells.contains(cellKey(x, y, z - 1))) {
771 "upper floor has no structural support", {}, {},
772 "housegen.layout"));
773 }
774 if (!floorCells.contains(cellKey(x, y, z + 1)) && !roofCells.contains(cellKey(x, y, z + 1))) {
776 eve::DiagnosticCode::InvalidArgument, "floor cell has no roof coverage", {}, {}, "housegen.layout"));
777 }
778 }
780}
781
783 if (!std::isfinite(moduleSize) || moduleSize <= 0.f || !std::isfinite(floorHeight) || floorHeight <= 0.f)
785 eve::DiagnosticCode::InvalidArgument, "moduleSize and floorHeight must be finite and positive", {}, {},
786 "housegen.layout"));
787 for (const auto &instance : instances) {
788 if (instance.x < 0 || instance.y < 0 || instance.z < 0)
790 "house instance has a negative grid coordinate",
791 instance.componentId, {}, "housegen.layout"));
792 }
793 if (footprintWidth <= 0 || footprintDepth <= 0 ||
794 footprintMask.size() != size_t(footprintWidth) * size_t(footprintDepth))
796 "house layout has no canonical footprint mask",
797 "footprintMask", {}, "housegen.layout"));
798
799 procgen::Grid2D candidate;
801 candidate.fill(int(procgen::Semantic::Empty));
802 for (int y = 0; y < footprintDepth; ++y)
803 for (int x = 0; x < footprintWidth; ++x)
804 if (footprintMask[size_t(y * footprintWidth + x)] != 0)
805 candidate.setCell(x, y, int(procgen::Semantic::Floor));
806 for (const auto &instance : instances) {
807 if (instance.x >= footprintWidth || instance.y >= footprintDepth) continue;
808 candidate.setDetail(instance.x, instance.y,
809 std::min(255, std::max(candidate.getDetail(instance.x, instance.y), instance.z + 1)));
810 }
811 candidate.setMeta("domain", "house.footprint");
812 candidate.setMeta("seed", std::to_string(seed));
813 candidate.setMeta("footprint", footprintStyle);
814 candidate.setMeta("roof", roofStyle);
815 candidate.setMeta("entrance", entranceSide);
816 out = std::move(candidate);
818}
819
821 if (!std::isfinite(moduleSize) || moduleSize <= 0.f || !std::isfinite(floorHeight) || floorHeight <= 0.f)
823 eve::DiagnosticCode::InvalidArgument, "moduleSize and floorHeight must be finite and positive", {}, {},
824 "housegen.layout"));
825 if (footprintWidth <= 0 || footprintDepth <= 0 ||
826 footprintMask.size() != size_t(footprintWidth) * size_t(footprintDepth))
828 "house layout has no canonical footprint mask",
829 "footprintMask", {}, "housegen.layout"));
830 for (const auto &instance : instances) {
831 const int rotation = (instance.rotationDeg % 360 + 360) % 360;
832 if (instance.x < 0 || instance.y < 0 || instance.z < 0 || instance.x >= footprintWidth ||
833 instance.y >= footprintDepth || !footprintMask[size_t(instance.y * footprintWidth + instance.x)] ||
834 rotation % 90 != 0)
836 "invalid house component point placement",
837 instance.componentId, {}, "housegen.layout"));
838 }
839 procgen::PointSet candidate;
840 candidate.reserve(instances.size());
841 std::uint64_t ordinal = 0;
842 const std::uint64_t pointNamespace = (std::uint64_t(seed) << 32u) | 0x484f5553u;
843 for (const auto &instance : instances) {
844 const int index = candidate.add(float(instance.x) * moduleSize, float(instance.z) * floorHeight,
845 float(instance.y) * moduleSize);
846 candidate.setYaw(index, float(instance.rotationDeg));
847 candidate.setPointSeed(index, seed);
848 candidate.setBounds(index, 0.f, 0.f, 0.f, moduleSize, floorHeight, moduleSize);
849 auto id = candidate.trySetPointId(index, procgen::derivePointId(pointNamespace, ++ordinal));
850 if (!id.ok()) return eve::Result<void>::failure(id.status());
851 auto component = candidate.trySetStringAttribute(index, "component_id", instance.componentId);
852 if (!component.ok()) return eve::Result<void>::failure(component.status());
853 auto cellX = candidate.trySetIntAttribute(index, "cell_x", instance.x);
854 if (!cellX.ok()) return eve::Result<void>::failure(cellX.status());
855 auto cellY = candidate.trySetIntAttribute(index, "cell_y", instance.y);
856 if (!cellY.ok()) return eve::Result<void>::failure(cellY.status());
857 auto floor = candidate.trySetIntAttribute(index, "floor", instance.z);
858 if (!floor.ok()) return eve::Result<void>::failure(floor.status());
859 }
860 out = std::move(candidate);
862}
863
865 const HouseComponentLibrary &library) const {
866 const auto valid = validate(library);
867 if (!valid.ok()) return eve::Result<std::vector<ecs::EntityHandle>>::failure(valid.status());
868 std::vector<ecs::EntityHandle> entities;
869 const auto destroyCreated = [&entities]() noexcept {
870 for (const auto &handle : entities) {
871 if (auto *entity = ecs::try_get(handle)) ecs::DestroyEntity(entity);
872 }
873 entities.clear();
874 };
875 std::unordered_map<std::string, ModelHandle> data;
876 struct CachedPart {
877 graphics::Mesh *mesh = nullptr;
878 graphics::Texture *texture = nullptr;
879 graphics::Texture *normalTexture = nullptr;
880 graphics::Texture *heightTexture = nullptr;
881 float r = 1.f, g = 1.f, b = 1.f, a = 1.f;
882 float metallic = 0.f, roughness = 0.72f;
883 float parallaxScale = 0.f, parallaxMinLayers = 8.f, parallaxMaxLayers = 32.f;
884 float cellBombScale = 4.f, cellBombStrength = 0.f, cellBombRotation = 1.f;
885 };
886 std::unordered_map<std::string, std::vector<CachedPart>> parts;
887 try {
888 for (const auto &i : instances) {
889 const auto component = library.find(i.componentId);
890 if (!component) {
891 destroyCreated();
893 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "unknown component: " + i.componentId,
894 "componentId", {}, "housegen.layout"));
895 }
896 const HouseComponent &c = component->get();
897 // Loads once per path: the handle either owns the decode or pins the cache entry.
898 auto modelIt = data.find(c.modelPath);
899 if (modelIt == data.end()) modelIt = data.emplace(c.modelPath, loadModel(&models, c.modelPath)).first;
900 model3d::ModelData *model = modelIt->second.get();
901 // Material overrides belong to a component, so two components may safely reuse the
902 // same GLB with different architectural finishes.
903 auto &cached = parts[c.id];
904 if (cached.empty()) {
905 const aiScene *scene = model->getScene();
906 if (!scene || !scene->mRootNode) throw std::runtime_error("model has no scene root: " + c.modelPath);
907 std::function<void(const aiNode *, const aiMatrix4x4 &)> walk = [&](const aiNode *node,
908 const aiMatrix4x4 &parent) {
909 const aiMatrix4x4 world = parent * node->mTransformation;
910 for (unsigned ni = 0; ni < node->mNumMeshes; ++ni) {
911 const unsigned mi = node->mMeshes[ni];
912 if (mi >= scene->mNumMeshes || !scene->mMeshes[mi]) continue;
913 const aiMesh *source = scene->mMeshes[mi];
914 CachedPart part;
915 part.mesh = gfx.newMeshFromAssimp(*source, aiToGlm(world));
916 if (scene->mMaterials && source->mMaterialIndex < scene->mNumMaterials) {
917 const aiMaterial *material = scene->mMaterials[source->mMaterialIndex];
918 aiColor4D color(1.f, 1.f, 1.f, 1.f);
919 material->Get(AI_MATKEY_COLOR_DIFFUSE, color);
920 material->Get(AI_MATKEY_BASE_COLOR, color);
921 part.r = color.r;
922 part.g = color.g;
923 part.b = color.b;
924 part.a = color.a;
925 material->Get(AI_MATKEY_METALLIC_FACTOR, part.metallic);
926 material->Get(AI_MATKEY_ROUGHNESS_FACTOR, part.roughness);
927 part.texture = assimpTexture(&gfx, scene, material, c.modelPath, aiTextureType_BASE_COLOR,
928 aiTextureType_DIFFUSE);
929 part.normalTexture = assimpTexture(&gfx, scene, material, c.modelPath,
930 aiTextureType_NORMALS, aiTextureType_NORMAL_CAMERA);
931 part.heightTexture = assimpTexture(&gfx, scene, material, c.modelPath, aiTextureType_HEIGHT,
932 aiTextureType_DISPLACEMENT);
933 }
934 if (c.material.hasBaseColor) {
935 part.r = c.material.baseColorR;
936 part.g = c.material.baseColorG;
937 part.b = c.material.baseColorB;
938 part.a = c.material.baseColorA;
939 }
940 if (!c.material.baseColorTexture.empty())
941 part.texture = textureFromFile(&gfx, c.modelPath, c.material.baseColorTexture);
942 if (!c.material.normalTexture.empty())
943 part.normalTexture = textureFromFile(&gfx, c.modelPath, c.material.normalTexture);
944 if (!c.material.heightTexture.empty())
945 part.heightTexture = textureFromFile(&gfx, c.modelPath, c.material.heightTexture);
946 if (c.material.hasMetallic) part.metallic = c.material.metallic;
947 if (c.material.hasRoughness) part.roughness = c.material.roughness;
948 part.parallaxScale = c.material.parallaxScale;
949 part.parallaxMinLayers = c.material.parallaxMinLayers;
950 part.parallaxMaxLayers = c.material.parallaxMaxLayers;
951 part.cellBombScale = c.material.cellBombScale;
952 part.cellBombStrength = c.material.cellBombStrength;
953 part.cellBombRotation = c.material.cellBombRotation;
954 cached.push_back(part);
955 }
956 for (unsigned child = 0; child < node->mNumChildren; ++child) walk(node->mChildren[child], world);
957 };
958 walk(scene->mRootNode, aiMatrix4x4());
959 }
960 for (const auto &part : cached) {
961 auto *e = graphics::Renderable3D::create();
962 if (!e) {
963 destroyCreated();
965 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "failed to create Renderable3D entity", {},
966 {}, "housegen.layout"));
967 }
968 e->setMesh(part.mesh);
969 e->setPosition(i.x * moduleSize, i.z * floorHeight, i.y * moduleSize);
970 e->setYaw(float(i.rotationDeg) * 3.14159265358979323846f / 180.f);
971 e->setTint(part.r, part.g, part.b, part.a);
972 if (part.texture) e->setTexture(part.texture);
973 if (part.normalTexture) e->setNormalTexture(part.normalTexture);
974 if (part.heightTexture) e->setHeightTexture(part.heightTexture);
975 e->setMetallic(part.metallic);
976 e->setRoughness(part.roughness);
977 e->setTexCellBomb(part.cellBombScale, part.cellBombStrength, part.cellBombRotation);
978 if (part.heightTexture && part.parallaxScale > 0.f)
979 e->setParallax(part.parallaxScale, part.parallaxMinLayers, part.parallaxMaxLayers);
980 entities.push_back(ecs::handle_of(e));
981 }
982 }
983 } catch (const std::exception &e) {
984 destroyCreated();
986 eve::Diagnostic::error(eve::DiagnosticCode::Failed, e.what(), {}, {}, "housegen.layout"));
987 } catch (...) {
988 destroyCreated();
990 eve::DiagnosticCode::Failed, "house layout instantiation failed", {}, {}, "housegen.layout"));
991 }
992 return eve::Result<std::vector<ecs::EntityHandle>>::success(std::move(entities),
994}
995
996} // namespace eve::housegen
double z
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
std::vector< eve::artifact::PartView > parts
std::string output
ActiveSource owned
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
EvpackChunkInput input
Definition Evpack.cpp:170
std::string layout
const GltfImportRequest & request
tensor::Graph g
Definition GpuGraph.cpp:7
wgpu::PopErrorScopeStatus status
double r
float v
HexVec3 left
HexVec3 right
std::int32_t c
eve::ResourcePin pinned
const ColourScope * parent
std::array< float, 4 > rotation
bool present
Poco::JSON::Object::Ptr result
std::uint64_t bytes
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float roughness
float metallic
const std::string * tag
OceanMeshSettings mesh
std::array< uint32_t, 16 > material
Texture * texture
std::string path
Definition PlayHost.cpp:111
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::vector< ecs::EntityHandle > entities
std::weak_ptr< PrimitiveScene > scene
PrimitiveHandle handle
std::set< std::string > values
Object::Ptr value
float d
const EntityFact * entity
glm::mat4 model
RoadNetwork resolved
const RoadNode * node
RoadLaneDirection direction
ScriptStructure out
std::string_view source
double current
bool occupied
Definition Shadow.cpp:155
The single Squirrel projection for common Result, Status and Value.
Cell cell
uint32_t seed
Definition TreeMesh.cpp:276
float size
Definition TreeMesh.cpp:158
const char * category
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
eve::Result< ResourcePin > pin(Resource *resource)
Keeps one cached resource alive across unload()/clear()/reload.
Definition Resource.cpp:311
static ResourceManager & getInstance()
Returns the instance.
Definition Resource.cpp:15
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
bool isArray() const noexcept
Return true when this value is an array.
Definition Value.h:108
bool isObject() const noexcept
Return true when this value is an object.
Definition Value.h:110
Value & at(std::size_t index)
Return a bounds-checked array element.
Definition Value.cpp:226
virtual Mesh * newMeshFromAssimp(const ::aiMesh &mesh)=0
Creates a mesh from assimp. @ownership Caller deletes unless documented otherwise.
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
房屋组件注册表(按 id 索引,支持分类/风格查询)。
eve::Result< void > loadFromJson(std::string_view json)
从 JSON / 文件加载组件。
std::vector< std::string > completePacks() const
所有能构成完整组件包(五个核心分类齐全)的风格标签。
eve::Result< void > loadFromFile(std::string_view filename)
eve::OptionalRef< const HouseComponent > find(std::string_view id) const
按 id 查询组件;缺失是正常查询结果。
std::vector< std::reference_wrapper< const HouseComponent > > byCategory(std::string_view category, std::string_view style={}) const
按分类(可选风格)查询组件。
eve::Result< void > registerComponent(const HouseComponent &component)
注册单个组件(id 重复会报错)。
std::vector< std::string > ids() const
全部组件 id。
bool hasCompletePack(std::string_view style) const
报告一个风格是否构成完整组件包。
程序化房屋生成模块(eve.HouseGen):组件库 + 布局生成。
Definition HouseGen.h:15
eve::Result< void > instantiate(const HouseLayout &layout, graphics::Graphics &gfx, model3d::Model3D &models) const
Instantiate a generated layout through the current component library.
int getComponentCount() const
组件数量。
eve::Result< void > loadComponentsFromJson(const std::string &json)
从 JSON / 文件加载房屋组件库。
void clearComponents()
清空组件库。
static void expose(ssq::Class &cls)
eve::Result< void > generate(const HouseRequest &request, HouseLayout &layout)
按请求生成布局;失败返回结构化诊断。
eve::Result< void > loadComponentsFromFile(const std::string &filename)
HouseRequest newRequest() const
工厂:生成请求 / 布局。
布局生成器:把 HouseRequest 解析为 HouseLayout(组件库驱动)。
eve::Result< void > generate(const HouseRequest &request, HouseLayout &out) const
生成布局;失败时不修改输出布局并返回结构化诊断。
一次生成的房屋布局:实例 + 房间 + 元信息,可 JSON 序列化 / 实例化。
Definition HouseLayout.h:23
std::string footprintStyle
布局风格结果。
Definition HouseLayout.h:30
eve::Result< void > validate(const HouseComponentLibrary &library) const
校验布局是否满足组件库规则。
std::string toJson() const
Serialize or restore the eve.house-layout version 1 JSON schema.
std::vector< HouseRoom > rooms
Definition HouseLayout.h:39
std::vector< uint8_t > footprintMask
Definition HouseLayout.h:36
float moduleSize
生成参数回显。
Definition HouseLayout.h:27
eve::Result< void > writeComponentPoints(procgen::PointSet &out) const
Export component placements as canonical attributed procgen points.
eve::Result< void > fromJson(std::string_view json)
From json.
int footprintWidth
Canonical base-floor occupancy mask owned by this layout.
Definition HouseLayout.h:34
eve::Result< void > writeFootprintGrid(procgen::Grid2D &out) const
Export the generated footprint as the canonical procgen grid value.
std::vector< std::string > diagnostics
Definition HouseLayout.h:40
std::vector< HouseInstance > instances
组件实例 / 房间 / 诊断信息。
Definition HouseLayout.h:38
EVENGINE_API_FOUNDATION public API.
Definition Json.h:137
bool valid() const
Valid.
Definition Json.h:158
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Value root() const
Root.
Definition Json.h:160
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
Resource module for decoding 3D models via medialoader (Assimp). Produces ModelData; GPU upload is gr...
Definition Model3D.h:43
CPU-side decoded 3D model (Assimp scene owned via medialoader::ModelScene). Does not upload to GPU — ...
Definition ModelData.h:39
Intermediate 2D generation result. cells store semantic ids (see Semantic.h), not tile GIDs — convert...
Definition Grid2D.h:37
void setDetail(int x, int y, int value)
Per-cell detail layer (0..255), parallel to cells. Semantics stay in cells (palette/GID compatible); ...
Definition Grid2D.cpp:37
int getDetail(int x, int y) const
Returns the detail.
Definition Grid2D.cpp:42
void resize(int width, int height)
Resize.
Definition Grid2D.cpp:13
void fill(int semantic)
Fill.
Definition Grid2D.cpp:33
void setCell(int x, int y, int semantic)
Sets the cell.
Definition Grid2D.cpp:23
void setMeta(const std::string &key, const std::string &value)
Sets the meta.
Definition Grid2D.cpp:47
Script-friendly collection of attributed 3D samples.
Definition PointSet.h:59
Result< void > trySetPointId(int index, std::uint64_t id)
Assign a unique non-zero point identity without mutating on failure.
Definition PointSet.cpp:295
int add(float x, float y, float z)
Definition PointSet.cpp:98
Result< void > trySetStringAttribute(int index, const std::string &name, const std::string &value)
Canonical checked string metadata write.
Definition PointSet.cpp:422
void setBounds(int index, float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
Set local-space point bounds before scale and rotation are applied.
Definition PointSet.cpp:203
void setYaw(int index, float yaw)
Sets the yaw.
Definition PointSet.cpp:156
void setPointSeed(int index, uint32_t seed)
Sets the point seed.
Definition PointSet.cpp:282
Result< void > trySetIntAttribute(int index, const std::string &name, std::int64_t value)
Canonical checked signed integer metadata write.
Definition PointSet.cpp:352
void reserve(std::size_t count)
Reserve point storage without changing point or attribute row counts.
Definition PointSet.cpp:61
RAII keep-alive for one RuntimeObjectRegistry entry.
T * get() const noexcept
Borrows the pinned object; valid until the pin is released.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
void exposeHouseGeneration(ssq::Table &table)
Register the procgen-owned house generation compatibility API.
constexpr uint32_t Floor
Definition Semantic.h:14
constexpr uint32_t Empty
Definition Semantic.h:12
std::uint64_t derivePointId(std::uint64_t namespaceId, std::uint64_t ordinal)
Deterministically derive a non-zero stable point identity.
Definition PointSet.cpp:470
std::unique_ptr< T > Owned
C++ owning storage used by an object factory.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Definition BorrowedRef.h:24
static TextureCreateInfo withMipmaps(bool aniso=true, float maxAniso=16.f)
With mipmaps.
房屋组件模板(几何 + 连接点 + 权重)。
int width
占地尺寸(格)。
std::vector< int > rotations
允许的旋转(度)。
HouseMaterialOverride material
材质覆盖。
int weight
生成权重(越大越常被选中)。
一次房屋生成请求(参数集)。
布局中的房间标记。
glm::vec4 color