载入中...
搜索中...
未找到
BuildingAssemblyPersistence.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <limits>
4#include <set>
5#include <stdexcept>
8#include "grid/GridConfig.h"
9
10namespace eve::building {
11using namespace assembly_detail;
12namespace {
13void knownFields(const Value& value, std::initializer_list<const char*> names) {
14 if (!value.isObject()) throw std::runtime_error("Expected schema object");
15 for (const auto& key : value.keys()) {
16 if (std::none_of(names.begin(), names.end(), [&](const char* name) { return key == name; }))
17 throw std::runtime_error("Unknown core field: " + key);
18 }
19}
20void knownInstance(const Value& value) {
21 const auto shape = codec::instanceValue(BuildingInstanceSnapshot{});
22 if (!value.isObject()) throw std::runtime_error("Expected instance object");
23 for (const auto& key : value.keys()) {
24 const auto* expected = shape.find(key);
25 const auto* actual = value.find(key);
26 if (!expected || (expected->type() != actual->type() && !(expected->isDouble() && actual->isInt64())))
27 throw std::runtime_error("Unknown or incorrectly typed instance field: " + key);
28 }
29}
30void knownCurve(const Value& value) {
31 knownFields(value, {"groupId", "buildingId", "level", "subdivisions", "controlPoints", "surfaceProviderName",
32 "surfaceId", "surfaceRevision", "surfaceSamples", "instances"});
33 if (const auto* values = value.find("instances"); values && values->isArray())
34 for (const auto& instance : *values->getIf<Value::Array>()) knownInstance(instance);
35}
36const Value& required(const Value& v, const char* key) {
37 const auto* p = v.find(key);
38 if (!p) throw std::runtime_error(std::string("Missing field: ") + key);
39 return *p;
40}
41int integer(const Value& v, int min = std::numeric_limits<int>::min(), int max = std::numeric_limits<int>::max()) {
42 if (!v.isInt64() || v.asInt() < min || v.asInt() > max) throw std::runtime_error("Integer outside schema range");
43 return int(v.asInt());
44}
45float number(const Value& v) {
46 if (!v.isNumeric()) throw std::runtime_error("Expected number");
47 double n = v.isInt64() ? double(v.asInt()) : v.asDouble();
48 if (!std::isfinite(n) || std::abs(n) > 1e10) throw std::runtime_error("Invalid finite number");
49 return float(n);
50}
51const std::string& text(const Value& v) {
52 if (!v.isString()) throw std::runtime_error("Expected string");
53 return v.asString();
54}
55const Value::Array& array(const Value& v) {
56 auto* a = v.getIf<Value::Array>();
57 if (!a) throw std::runtime_error("Expected array");
58 return *a;
59}
60void schema(const Value& v, const char* id) {
61 if (text(required(v, "schema")) != id || integer(required(v, "version")) != 1)
62 throw std::runtime_error("Unsupported schema/version; no implicit migration");
63}
64template <class T>
65T identity(const Value& v) {
66 auto id = T::parse(text(v));
67 if (!id || id->isNil()) throw std::runtime_error("Invalid persistent identity");
68 return *id;
69}
70template <class Map>
71Value strings(const Map& map) {
73 for (const auto& [k, v] : map) o[k] = v;
74 return o;
75}
76} // namespace
78 Value::Array parts, curves;
79 for (const auto& p : b.parts)
80 parts.emplace_back(Value::Object{{"key", int64_t(p.id.value)}, {"instance", codec::instanceValue(p.local)}});
81 for (const auto& c : b.curves) curves.emplace_back(codec::edgeCurveValue(c.group, c.instances));
82 Value v = Value::Object{{"schema", "eve.building.blueprint"},
83 {"version", 1},
84 {"id", b.id.format()},
85 {"assetVersion", int64_t(b.version)},
86 {"cellSize", b.cellSize},
87 {"floorHeight", b.floorHeight},
88 {"parts", std::move(parts)},
89 {"curves", std::move(curves)},
90 {"definitions", b.definitions}};
91 auto check = decodeBlueprint(v);
92 if (!check.ok()) return fail<Value>("Cannot encode invalid blueprint");
93 return Result<Value>::success(std::move(v));
94}
95Result<BuildingBlueprint> AssemblyService::decodeBlueprint(const Value& v) {
96 try {
97 knownFields(v, {"schema", "version", "id", "assetVersion", "cellSize", "floorHeight", "parts", "curves",
98 "definitions"});
99 schema(v, "eve.building.blueprint");
101 b.id = identity<AssetGuid>(required(v, "id"));
102 b.version = uint64_t(integer(required(v, "assetVersion"), 1));
103 b.cellSize = number(required(v, "cellSize"));
104 b.floorHeight = number(required(v, "floorHeight"));
105 if (b.cellSize <= 0 || b.floorHeight <= 0) throw std::runtime_error("Invalid blueprint scale");
106 b.definitions = required(v, "definitions");
107 auto defs = checkDefinitions(b.definitions);
108 if (!defs.ok())
109 return fail<BuildingBlueprint>("Blueprint definitions missing or changed", DiagnosticCode::Conflict);
110 std::set<int> keys;
111 for (const auto& p : array(required(v, "parts"))) {
112 knownFields(p, {"key", "instance"});
113 knownInstance(required(p, "instance"));
114 int key = integer(required(p, "key"), 1, std::numeric_limits<int>::max() - 1);
115 auto part = codec::parseInstance(required(p, "instance"));
116 const bool partOk = part.ok();
117 if (!keys.insert(key).second || !partOk || part.value().instanceId != key ||
118 !part.value().garrison.empty() || !b.definitions.find(part.value().buildingId))
119 throw std::runtime_error("Invalid blueprint part or external entity reference");
120 b.parts.push_back({{uint32_t(key)}, std::move(part).takeValue()});
121 }
122 if (b.parts.empty() || b.parts.size() > 100000)
123 throw std::runtime_error("Blueprint must contain 1..100000 parts");
124 std::set<int> curveMembers;
125 for (const auto& c : array(required(v, "curves"))) {
126 knownCurve(c);
127 auto curve = codec::parseEdgeCurve(c);
128 if (!curve.ok()) throw std::runtime_error("Invalid curve payload");
129 for (const auto& p : curve.value().instances) {
130 auto found = std::find_if(b.parts.begin(), b.parts.end(),
131 [&](const auto& part) { return part.local.instanceId == p.instanceId; });
132 if (found == b.parts.end() || !curveMembers.insert(p.instanceId).second ||
133 codec::instanceValue(found->local) != codec::instanceValue(p))
134 throw std::runtime_error("Curve membership differs from blueprint parts");
135 }
136 b.curves.push_back(std::move(curve).takeValue());
137 }
138 return Result<BuildingBlueprint>::success(std::move(b));
139 } catch (const std::exception& e) {
140 return fail<BuildingBlueprint>(e.what());
141 }
142}
143Result<Value> AssemblyService::snapshotWorld(const PlacementWorld& w) {
144 auto checked = checkGrid(w);
145 if (!checked.ok()) return fail<Value>("World grid is not serializable by house schema");
146 Value::Array instances, terrain, curves, houses;
147 for (int id : w.instanceOrder_) {
148 auto it = w.buildings_.find(id);
149 if (it == w.buildings_.end()) return fail<Value>("Invalid world instance order");
150 instances.emplace_back(codec::instanceValue(codec::snapshot(it->second)));
151 }
152 for (int y = 0; y < w.height_; ++y)
153 for (int x = 0; x < w.width_; ++x) terrain.emplace_back(w.getTerrain(x, y));
154 for (auto id : w.edgeCurveGroupIds()) {
155 const auto& g = w.edgeCurveGroups_.at(id.value);
156 std::vector<BuildingInstanceSnapshot> members;
157 for (int member : g.instanceIds) {
158 auto it = w.buildings_.find(member);
159 if (it == w.buildings_.end()) return fail<Value>("Dangling curve member");
160 members.push_back(codec::snapshot(it->second));
161 }
162 curves.emplace_back(codec::edgeCurveValue(g, members));
163 }
164 for (const auto& [id, a] : w.assemblyState_->records) {
166 for (const auto& [key, member] : a.members)
167 members.emplace_back(Value::Object{
168 {"key", int64_t(key)}, {"record", member}, {"persistentId", id.child(std::to_string(key)).format()}});
169 houses.emplace_back(Value::Object{{"id", id.format()},
170 {"blueprint", a.blueprint.format()},
171 {"nextPartKey", int64_t(a.nextPartKey)},
172 {"blueprintVersion", int64_t(a.blueprintVersion)},
173 {"frame", poseValue(a.frame)},
174 {"members", std::move(members)}});
175 }
176 Value result = Value::Object{{"schema", "eve.building.world"},
177 {"version", 1},
178 {"worldId", w.id_},
179 {"width", w.width_},
180 {"height", w.height_},
181 {"cellSize", w.getCellSize()},
182 {"plane", w.getGridPlaneName()},
183 {"originX", w.getOriginX()},
184 {"originY", w.getOriginY()},
185 {"floorHeight", w.floorHeight_},
186 {"activeLevel", w.activeLevel_},
187 {"snapMode", w.snapMode_},
188 {"validateRule", w.validateRule_},
189 {"extra", strings(w.extra_)},
190 {"nextInstance", w.instanceCounter_},
191 {"nextCurve", int64_t(w.nextEdgeCurveGroupId_)},
192 {"terrain", std::move(terrain)},
193 {"instances", std::move(instances)},
194 {"curves", std::move(curves)},
195 {"assemblies", std::move(houses)},
196 {"definitions", definitionsFor(w)}};
197 return Result<Value>::success(std::move(result));
198}
199Result<std::unique_ptr<PlacementWorld>> AssemblyService::decodeWorld(const Value& v) {
200 try {
201 knownFields(
202 v, {"schema", "version", "worldId", "width", "height", "cellSize", "plane",
203 "originX", "originY", "floorHeight", "activeLevel", "snapMode", "validateRule", "extra",
204 "nextInstance", "nextCurve", "terrain", "instances", "curves", "assemblies", "definitions"});
205 schema(v, "eve.building.world");
206 auto defs = checkDefinitions(required(v, "definitions"));
207 if (!defs.ok()) throw std::runtime_error("World definitions missing or changed");
208 int width = integer(required(v, "width"), 1, 4096), height = integer(required(v, "height"), 1, 4096);
209 if (int64_t(width) * height > 4000000) throw std::runtime_error("World exceeds cell budget");
210 float size = number(required(v, "cellSize"));
211 if (size <= 0) throw std::runtime_error("Invalid cell size");
212 auto w = std::make_unique<PlacementWorld>(width, height, size);
213 w->publishEvents_ = false;
214 w->id_ = text(required(v, "worldId"));
215 auto plane = text(required(v, "plane"));
216 if (plane != "xz" && plane != "xy") throw std::runtime_error("Invalid plane");
217 w->setGridPlane(plane);
218 w->setOrigin(number(required(v, "originX")), number(required(v, "originY")));
219 w->floorHeight_ = number(required(v, "floorHeight"));
220 if (w->floorHeight_ <= 0) throw std::runtime_error("Invalid floor height");
221 w->activeLevel_ = integer(required(v, "activeLevel"));
222 w->snapMode_ = text(required(v, "snapMode"));
223 w->validateRule_ = text(required(v, "validateRule"));
224 const auto& extra = required(v, "extra");
225 if (!extra.isObject()) throw std::runtime_error("Invalid extras");
226 for (const auto& key : extra.keys()) w->extra_[key] = text(*extra.find(key));
227 const auto& terrain = array(required(v, "terrain"));
228 if (terrain.size() != size_t(width) * height) throw std::runtime_error("Terrain dimensions mismatch");
229 for (size_t i = 0; i < terrain.size(); ++i) w->terrain_[i] = integer(terrain[i]);
230 w->terrainOverrides_.assign(terrain.size(), 1);
231 w->instanceCounter_ = integer(required(v, "nextInstance"), 0);
232 const auto& nextCurve = required(v, "nextCurve");
233 if (!nextCurve.isInt64() || nextCurve.asInt() <= 0) throw std::runtime_error("Invalid curve sequence");
234 w->nextEdgeCurveGroupId_ = uint64_t(nextCurve.asInt());
235 for (const auto& record : array(required(v, "instances"))) {
236 knownInstance(record);
237 auto p = codec::parseInstance(record);
238 if (!p.ok()) throw std::runtime_error("Invalid instance payload");
239 int id = p.value().instanceId;
240 if (id > w->instanceCounter_ || !required(v, "definitions").find(p.value().buildingId) ||
241 !w->buildings_.emplace(id, codec::runtime(p.value())).second)
242 throw std::runtime_error("Duplicate/unpinned instance record");
243 w->instanceOrder_.push_back(id);
244 }
245 for (const auto& record : array(required(v, "curves"))) {
246 knownCurve(record);
247 auto c = codec::parseEdgeCurve(record);
248 if (!c.ok()) throw std::runtime_error("Invalid curve");
249 auto& payload = c.value();
250 for (const auto& p : payload.instances) {
251 auto it = w->buildings_.find(p.instanceId);
252 if (it == w->buildings_.end() ||
253 codec::instanceValue(codec::snapshot(it->second)) != codec::instanceValue(p))
254 throw std::runtime_error("Curve member payload mismatch");
255 }
256 if (payload.group.id.value >= w->nextEdgeCurveGroupId_ ||
257 !w->edgeCurveGroups_.emplace(payload.group.id.value, payload.group).second)
258 throw std::runtime_error("Duplicate curve record");
259 }
260 for (const auto& record : array(required(v, "assemblies"))) {
261 knownFields(record, {"id", "blueprint", "blueprintVersion", "frame", "members", "nextPartKey"});
262 BuildingAssembly a;
263 a.id = identity<AssemblyId>(required(record, "id"));
264 a.blueprint = identity<AssetGuid>(required(record, "blueprint"));
265 a.blueprintVersion = uint64_t(integer(required(record, "blueprintVersion"), 1));
266 a.nextPartKey = uint32_t(integer(required(record, "nextPartKey"), 1));
267 auto pose = parsePose(required(record, "frame"));
268 if (!pose.ok()) throw std::runtime_error("Invalid house frame");
269 a.frame = pose.value();
270 for (const auto& m : array(required(record, "members"))) {
271 knownFields(m, {"key", "record", "persistentId"});
272 int key = integer(required(m, "key"), 1), member = integer(required(m, "record"), 1);
273 if (!a.members.emplace(uint32_t(key), member).second ||
274 text(required(m, "persistentId")) != a.id.child(std::to_string(key)).format())
275 throw std::runtime_error("Invalid persistent part identity");
276 }
277 if (!w->assemblyState_->records.emplace(a.id, a).second)
278 throw std::runtime_error("Duplicate house identity");
279 w->assemblyState_->handles[a.id] = eve::RuntimeHandle<AssemblyHandleTag>(w->assemblyState_->nextSlot++, 1);
280 }
281 auto valid = validateFinal(*w);
282 if (!valid.ok())
283 return fail<std::unique_ptr<PlacementWorld>>("Saved world failed final-state validation",
285 return Result<std::unique_ptr<PlacementWorld>>::success(std::move(w));
286 } catch (const std::exception& e) {
287 return fail<std::unique_ptr<PlacementWorld>>(e.what());
288 }
289}
290Result<void> AssemblyService::restoreWorld(PlacementWorld& w, const Value& v) {
291 auto parsed = decodeWorld(v);
292 if (!parsed.ok()) return fail<void>("World restore rejected without mutation", DiagnosticCode::Conflict);
293 w.swapState(*parsed.value());
294 if (w.publishEvents_) {
296 e.action = "reset";
297 e.worldId = w.getId();
298 PlacementSystem::pushEvent(std::move(e));
299 }
300 return Result<void>::success();
301}
302Result<void> AssemblyService::applyReceipt(PlacementWorld& w, const Value& expected, const Value& desired) {
303 auto current = snapshotWorld(w);
304 if (!current.ok() || current.value() != expected)
305 return fail<void>("Undo/redo endpoint no longer matches world", DiagnosticCode::Conflict);
306 return restoreWorld(w, desired);
307}
308} // namespace eve::building
double y
double m[16]
double x
Value::Object payload
float w
Definition AnimClip.cpp:738
std::vector< eve::artifact::PartView > parts
std::string terrain
eve::EntitySpatialPose pose
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
tensor::Graph g
Definition GpuGraph.cpp:7
ShaderImageInput shape
glm::vec3 n
Definition Grass.cpp:63
Module-neutral grid topology and sizing (no building/map dependency).
float v
std::int32_t second
std::int32_t c
std::uint32_t height
std::uint32_t width
bool required
std::string id
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::set< std::string > values
Object::Ptr value
double number
bool found
std::string text
double current
AbilityActivationGroup group
Heightmap curve
float size
Definition TreeMesh.cpp:158
float(ui::Theme::* member)[4]
std::map< std::string, std::span< const std::uint8_t > > members
uint64_t identity
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
Process-local slot identity tagged by the registry that owns it.
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static Result< Value > encodeBlueprint(const BuildingBlueprint &blueprint)
Encode a blueprint in the versioned canonical schema. @cost Copies and validates all parts and curve ...
格子型建筑放置世界(脚本可直接操作)。
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
Value definitionsFor(const PlacementWorld &w)
Result< AssemblyPose > parsePose(const Value &v)
Result< void > checkDefinitions(const Value &value)
Result< void > checkGrid(const PlacementWorld &world)
Value instanceValue(const BuildingInstanceSnapshot &instance)
Encode a complete owning instance; pure, caller-thread, linear in instance metadata.
建筑放置模块入口:定义 / 放置世界 / 鬼影 / 变更事件的脚本绑定点。 设计文档:docs/dev/建筑放置系统设计.md
Definition Building.cpp:10
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
void keys(const Value &value, std::initializer_list< const char * > names)
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120
Versioned house recipe; admission validates all fields before use. @ownership Owns local parts,...
一次成功放置变更的事件(供脚本 poll / C++ hook)。
std::string action
place / remove / move / rotate