载入中...
搜索中...
未找到
CanonicalMeshEncode.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <bit>
3#include <cmath>
4#include <iomanip>
5#include <limits>
6#include <new>
7#include <sstream>
11#include "common/Value.h"
12
13// CanonicalMeshEncode.cpp
14namespace eve::asset {
18 auto invalid = [] {
20 "invalid canonical mesh or byte budget", {}, {}, "asset.mesh"));
21 };
22 const auto count = mesh.positions.size() / 3;
23 if (!count || mesh.positions.size() % 3 || count > limits.maximumVertices || mesh.indices.empty() ||
24 mesh.indices.size() % 3 || mesh.indices.size() > limits.maximumIndices ||
25 (!mesh.normals.empty() && mesh.normals.size() != mesh.positions.size()) ||
26 (!mesh.colors.empty() && mesh.colors.size() != count * 4) ||
27 (!mesh.colors.empty() && !mesh.attributes.empty()) || mesh.texcoords.size() > UINT32_MAX ||
28 mesh.attributes.size() > UINT32_MAX)
29 return invalid();
30 const bool extended = !mesh.attributes.empty();
31 uint64_t floats =
32 3 + (mesh.normals.empty() ? 0 : 3) + uint64_t(mesh.texcoords.size()) * 2 + (mesh.colors.empty() ? 0 : 4);
33 auto validValues = [](const auto& values) {
34 return std::all_of(values.begin(), values.end(), [](float v) { return std::isfinite(v); });
35 };
36 if (!validValues(mesh.positions) || !validValues(mesh.normals) || !validValues(mesh.colors)) return invalid();
37 for (const auto& [set, values] : mesh.texcoords)
38 if (values.size() != count * 2 || !validValues(values)) return invalid();
39 for (const auto& [name, attribute] : mesh.attributes) {
40 if (name.empty() || name.size() > 63 || name == "POSITION" || name == "NORMAL" ||
41 name.starts_with("TEXCOORD_") || !attribute.components || attribute.components > 4 ||
42 attribute.values.size() != count * attribute.components || !validValues(attribute.values) ||
43 !std::all_of(name.begin(), name.end(),
44 [](char c) { return (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; }))
45 return invalid();
46 floats += attribute.components;
47 }
48 for (auto index : mesh.indices)
49 if (index >= count) return invalid();
50 const uint64_t header =
51 (extended ? 28ull : 24ull) + uint64_t(mesh.texcoords.size()) * 4 + uint64_t(mesh.attributes.size()) * 72;
52 const uint64_t indexBytes = uint64_t(mesh.indices.size()) * 4;
53 if (header > limits.maximumDecodedBytes || indexBytes > limits.maximumDecodedBytes - header ||
54 floats > (limits.maximumDecodedBytes - header - indexBytes) / 4 / count)
55 return invalid();
56 const uint64_t size = header + uint64_t(count) * floats * 4 + indexBytes;
57 if (size > std::numeric_limits<size_t>::max()) return invalid();
58 try {
59 std::vector<uint8_t> bytes;
60 bytes.reserve(size_t(size));
61 bytes.insert(bytes.end(), {'E', 'V', 'M', 'E', 'S', 'H', 0, uint8_t(extended || !mesh.colors.empty() ? 3 : 2)});
62 auto put = [&](uint32_t value) {
63 for (unsigned i = 0; i < 4; ++i) bytes.push_back(uint8_t(value >> (i * 8)));
64 };
65 put(uint32_t(count));
66 put(uint32_t(mesh.indices.size()));
67 put((mesh.normals.empty() ? 0u : 1u) | (mesh.colors.empty() ? 0u : 2u));
68 put(uint32_t(mesh.texcoords.size()));
69 if (extended) put(uint32_t(mesh.attributes.size()));
70 for (const auto& [set, values] : mesh.texcoords) put(set);
71 for (const auto& [name, attribute] : mesh.attributes) {
72 bytes.insert(bytes.end(), name.begin(), name.end());
73 bytes.insert(bytes.end(), 64 - name.size(), 0);
74 put(attribute.components);
75 put(0);
76 }
77 auto stream = [&](const auto& values, size_t vertex, size_t components) {
78 for (size_t j = 0; j < components; ++j) put(std::bit_cast<uint32_t>(values[vertex * components + j]));
79 };
80 for (size_t v = 0; v < count; ++v) {
81 stream(mesh.positions, v, 3);
82 if (!mesh.normals.empty()) stream(mesh.normals, v, 3);
83 for (const auto& [set, values] : mesh.texcoords) stream(values, v, 2);
84 for (const auto& [name, attribute] : mesh.attributes) stream(attribute.values, v, attribute.components);
85 if (!mesh.colors.empty()) stream(mesh.colors, v, 4);
86 }
87 for (auto index : mesh.indices) put(index);
88 return Output::success(std::move(bytes));
89 } catch (const std::bad_alloc&) {
90 return Output::failure(
91 Diagnostic::error(DiagnosticCode::Failed, "canonical mesh allocation failed", {}, {}, "asset.mesh"));
92 }
93}
94} // namespace eve::asset
95
96// CanonicalPcgCook.cpp
97namespace eve::asset {
98namespace {
99
100const Value* field(const Value::Object& object, std::string_view name) {
101 const auto found = object.find(std::string(name));
102 return found == object.end() ? nullptr : &found->second;
103}
104
105bool number(const Value* value, double& output) {
106 if (!value || !value->isNumeric()) return false;
107 output = value->isInt64() ? double(value->asInt()) : value->asDouble();
108 return std::isfinite(output);
109}
110
111void node(std::ostringstream& out, std::string_view id, std::string_view operation) {
112 out << "NODE " << std::quoted(std::string(id)) << ' ' << std::quoted(std::string(operation)) << '\n';
113}
114
115void edge(std::ostringstream& out, std::string_view from, std::string_view to) {
116 out << "EDGE " << std::quoted(std::string(from)) << ' ' << std::quoted(std::string(to)) << " 0\n";
117}
118
119} // namespace
120
121Result<CookedCanonicalPcgGraph> cookCanonicalPcgGraph(std::span<const std::uint8_t> definition,
122 std::uint32_t maximumRules, std::uint64_t maximumPlanBytes) {
123 auto parsed =
124 Value::fromJson(std::string_view(reinterpret_cast<const char*>(definition.data()), definition.size()));
125 if (!parsed) return Result<CookedCanonicalPcgGraph>::failure(parsed.status());
126 const auto* root = parsed.value().getIf<Value::Object>();
127 const Value* schema = root ? field(*root, "schema") : nullptr;
128 const Value* version = root ? field(*root, "schemaVersion") : nullptr;
129 const Value* algorithm = root ? field(*root, "algorithm") : nullptr;
130 const Value* rulesValue = root ? field(*root, "rules") : nullptr;
131 const auto* rules = rulesValue ? rulesValue->getIf<Value::Array>() : nullptr;
132 if (!schema || !schema->isString() || schema->asString() != "eve.pcg-graph" || !version || !version->isInt64() ||
133 version->asInt() != 1 || !algorithm || !algorithm->isString() ||
134 algorithm->asString() != "terrain-layer-scatter-v1" || !rules)
136 DiagnosticCode::Unsupported, "unsupported eve.pcg-graph/1 definition", {}, {}, "asset.cook.pcg"));
137 if (rules->empty() || rules->size() > maximumRules)
139 DiagnosticCode::InvalidArgument, "PCG rule count exceeds Cook limits", "$.rules", {}, "asset.cook.pcg"));
140
141 std::ostringstream plan;
142 plan << "EVPCG_POINT_GRAPH 1\n" << std::setprecision(9);
143 std::vector<std::string> outputs;
145 constexpr double radiansToDegrees = 57.29577951308232;
146 for (std::size_t i = 0; i < rules->size(); ++i) {
147 const auto* rule = (*rules)[i].getIf<Value::Object>();
148 const Value* id = rule ? field(*rule, "id") : nullptr;
149 const Value* prototype = rule ? field(*rule, "prototype") : nullptr;
150 const Value* layer = rule ? field(*rule, "layer") : nullptr;
151 const Value* seed = rule ? field(*rule, "seed") : nullptr;
152 double density = 0, minimumSlope = 0, maximumSlope = 0;
153 if (!id || !id->isString() || id->asString().empty() || !prototype || !prototype->isString() ||
154 prototype->asString().empty() || !layer || !layer->isString() || !seed || !seed->isInt64() ||
155 seed->asInt() < 0 || !number(rule ? field(*rule, "densityPerSquareMeter") : nullptr, density) ||
156 density < 0 || !number(rule ? field(*rule, "minimumSlopeRadians") : nullptr, minimumSlope) ||
157 !number(rule ? field(*rule, "maximumSlopeRadians") : nullptr, maximumSlope) || minimumSlope < 0 ||
158 maximumSlope < minimumSlope || maximumSlope > 3.141592653589793)
160 Diagnostic::error(DiagnosticCode::InvalidArgument, "PCG scatter rule is invalid",
161 "$.rules[" + std::to_string(i) + "]", {}, "asset.cook.pcg"));
162 const std::string suffix = std::to_string(i);
163 const std::string sample = "sample." + suffix;
164 const std::string project = "project." + suffix;
165 const std::string slope = "slope." + suffix;
166 const std::string taggedPrototype = "prototype." + suffix;
167 const std::string taggedLayer = "layer." + suffix;
168 node(plan, sample, "spatial.sample");
169 plan << "FLOAT " << std::quoted(sample) << " \"spacing\" " << (density > 0 ? std::sqrt(1.0 / density) : 1.0)
170 << '\n';
171 plan << "INT " << std::quoted(sample) << " \"seed\" " << (seed->asInt() & 0x7fffffff) << '\n';
172 node(plan, project, "spatial.project");
173 edge(plan, sample, project);
174 node(plan, slope, "filter.slope");
175 edge(plan, project, slope);
176 plan << "FLOAT " << std::quoted(slope) << " \"minDegrees\" " << minimumSlope * radiansToDegrees << '\n';
177 plan << "FLOAT " << std::quoted(slope) << " \"maxDegrees\" " << maximumSlope * radiansToDegrees << '\n';
178 std::string scatterOutput = slope;
179 if (density == 0) {
180 const std::string culled = "cull." + suffix;
181 node(plan, culled, "density.cull");
182 edge(plan, slope, culled);
183 plan << "FLOAT " << std::quoted(culled) << " \"multiplier\" 0\n";
184 scatterOutput = culled;
185 }
186 node(plan, taggedPrototype, "attribute.set.string");
187 edge(plan, scatterOutput, taggedPrototype);
188 plan << "STRING " << std::quoted(taggedPrototype) << " \"attribute\" \"prototype\"\n"
189 << "STRING " << std::quoted(taggedPrototype) << " \"value\" " << std::quoted(prototype->asString())
190 << '\n';
191 node(plan, taggedLayer, "attribute.set.string");
192 edge(plan, taggedPrototype, taggedLayer);
193 plan << "STRING " << std::quoted(taggedLayer) << " \"attribute\" \"layer\"\n"
194 << "STRING " << std::quoted(taggedLayer) << " \"value\" " << std::quoted(layer->asString()) << '\n';
195 outputs.push_back(taggedLayer);
196 slots.emplace_back(Value::Object{{"node", Value(sample)}, {"role", Value("terrain")}});
197 slots.emplace_back(Value::Object{{"node", Value(project)}, {"role", Value("terrain")}});
198 }
199 std::string output = outputs.front();
200 for (std::size_t i = 1; i < outputs.size(); ++i) {
201 const std::string merged = "merge." + std::to_string(i);
202 node(plan, merged, "merge");
203 edge(plan, output, merged);
204 plan << "EDGE " << std::quoted(outputs[i]) << ' ' << std::quoted(merged) << " 1\n";
205 output = merged;
206 }
207 plan << "END\n";
208 const std::string encodedPlan = plan.str();
209 if (encodedPlan.size() > maximumPlanBytes)
211 DiagnosticCode::InvalidArgument, "compiled PCG plan exceeds Cook budget", {}, {}, "asset.cook.pcg"));
212 Value::Object runtime{{"schema", Value("eve.pcg-graph")}, {"schemaVersion", Value(std::int64_t(1))},
213 {"executionPlan", Value("chunk:1")}, {"executionPlanFormat", Value("EVPCG_POINT_GRAPH/1")},
214 {"outputNode", Value(output)}, {"spatialSlots", Value(std::move(slots))}};
215 auto encodedDefinition = Value(std::move(runtime)).toJson();
216 if (!encodedDefinition) return Result<CookedCanonicalPcgGraph>::failure(encodedDefinition.status());
218 {{encodedDefinition.value().begin(), encodedDefinition.value().end()},
219 {encodedPlan.begin(), encodedPlan.end()}});
220}
221
222} // namespace eve::asset
223
224// CanonicalVolumeTextureCook.cpp
225namespace eve::asset {
226namespace {
227const Value* field(const Value::Object& object, const char* name) {
228 const auto found = object.find(name);
229 return found == object.end() ? nullptr : &found->second;
230}
231bool exactString(const Value::Object& object, const char* name, const char* expected) {
232 const auto* value = field(object, name);
233 return value && value->isString() && value->asString() == expected;
234}
235bool positive32(const Value::Object& object, const char* name, uint32_t& output) {
236 const auto* value = field(object, name);
237 if (!value || !value->isInt64() || value->asInt() <= 0 || uint64_t(value->asInt()) > UINT32_MAX) return false;
238 output = uint32_t(value->asInt());
239 return true;
240}
241void put32(std::vector<uint8_t>& bytes, uint32_t value) {
242 for (unsigned shift = 0; shift < 32; shift += 8) bytes.push_back(uint8_t(value >> shift));
243}
244} // namespace
245
247 std::span<const uint8_t> sourceR8,
248 uint64_t maximumDecodedBytes) {
249 auto decoded =
250 Value::fromJson(std::string_view(reinterpret_cast<const char*>(definition.data()), definition.size()));
251 if (!decoded) return Result<CookedCanonicalVolumeTexture>::failure(decoded.status());
252 const auto* object = decoded.value().getIf<Value::Object>();
253 uint32_t width = 0, height = 0, depth = 0;
254 const auto* blob = object ? field(*object, "blob") : nullptr;
255 if (!object || object->size() != 8 || !exactString(*object, "schema", "eve.volume-texture") ||
256 !exactString(*object, "encoding", "r8") || !exactString(*object, "usage", "noise") || !blob ||
257 !blob->isString() || !blob->asString().ends_with("/source.r8") || !positive32(*object, "width", width) ||
258 !positive32(*object, "height", height) || !positive32(*object, "depth", depth))
260 Diagnostic::error(DiagnosticCode::ParseError, "volume definition shape or members are invalid", {}, {},
261 "asset.cook.volume-texture"));
262 const auto* version = field(*object, "schemaVersion");
263 if (!version || !version->isInt64() || version->asInt() != 1 ||
264 uint64_t(width) > std::numeric_limits<uint64_t>::max() / height ||
265 uint64_t(width) * height > std::numeric_limits<uint64_t>::max() / depth)
267 DiagnosticCode::InvalidArgument, "volume dimensions, version, source bytes or budget are invalid", {}, {},
268 "asset.cook.volume-texture"));
269 const uint64_t voxels = uint64_t(width) * height * depth;
270 if (voxels > SIZE_MAX || voxels != sourceR8.size() || maximumDecodedBytes < 24 ||
271 voxels > (maximumDecodedBytes - 24) / 4)
273 DiagnosticCode::InvalidArgument, "volume dimensions, version, source bytes or budget are invalid", {}, {},
274 "asset.cook.volume-texture"));
275
276 auto runtime = *object;
277 runtime["encoding"] = Value("rgba8");
278 runtime["blob"] = Value("chunk:1");
279 auto encoded = Value(std::move(runtime)).toJson();
280 if (!encoded) return Result<CookedCanonicalVolumeTexture>::failure(encoded.status());
282 result.definition.assign(encoded.value().begin(), encoded.value().end());
283 result.bulk.insert(result.bulk.end(), {'E', 'V', 'V', 'O', 'L', 0, 1, 0});
284 put32(result.bulk, width);
285 put32(result.bulk, height);
286 put32(result.bulk, depth);
287 put32(result.bulk, 0);
288 result.bulk.reserve(24 + size_t(voxels) * 4);
289 for (uint8_t value : sourceR8) result.bulk.insert(result.bulk.end(), {value, value, value, 255});
291}
292
293} // namespace eve::asset
ActionParameterOperation operation
int root
Definition AnimSmr.cpp:119
std::string output
Canonical PCG graph compilation to runtime execution plans.
Bounded R8 volume conversion to runtime EVVOL.
std::string name
Definition ECS.cpp:154
float density
std::vector< std::uint8_t > blob
float u
Definition Grass.cpp:233
float v
std::int32_t c
std::uint32_t height
std::uint32_t width
std::string to
std::string from
std::string id
Poco::JSON::Object::Ptr result
std::uint64_t bytes
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
OceanMeshSettings mesh
TileLayer * layer
std::set< std::string > values
Object::Ptr value
std::string attribute
const RoadNode * node
double number
bool found
ScriptStructure out
size_t begin
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
Json object
uint32_t seed
Definition TreeMesh.cpp:276
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
const AssetImportLimits & limits
uint32_t index
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
Definition Value.cpp:187
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
bool isString() const noexcept
Return true when this value is a string.
Definition Value.h:106
std::vector< Value > Array
Definition Value.h:33
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
bool isInt64() const
True when the JSON number was an integer literal that fits Int64.
Definition Json.cpp:329
Result< CookedCanonicalVolumeTexture > cookCanonicalVolumeTextureRgba8(std::span< const uint8_t > definition, std::span< const uint8_t > sourceR8, uint64_t maximumDecodedBytes)
EVENGINE_API_FOUNDATION Result< std::vector< std::uint8_t > > encodeCanonicalMesh(const CanonicalMeshData &mesh, const CanonicalMeshLimits &limits={})
Encode an owning snapshot to EVMESH v3, or v2 when no named attributes exist. Borrows input synchrono...
Result< CookedCanonicalPcgGraph > cookCanonicalPcgGraph(std::span< const std::uint8_t > definition, std::uint32_t maximumRules, std::uint64_t maximumPlanBytes)
Compile eve.pcg-graph/1 terrain scatter rules to a bounded PointGraph plan.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
void put32(std::vector< char > &b, uint32_t v)
Put 32.
Definition zip_writer.h:56
Owning CPU mesh snapshot; UV arrays are packed ST pairs indexed by source set number....
Allocation limits checked before decoding any vertex arrays. UV count is byte-budget bounded.
Runtime definition and RGBA8 bulk generated from one canonical volume.