12using Point = std::array<double, 3>;
13using Matrix = std::array<double, 12>;
14constexpr Matrix
identity{1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0};
16std::string trim(std::string
text) {
17 const auto first =
text.find_first_not_of(
" \t\r");
18 if (
first == std::string::npos)
return {};
21std::string pathKey(std::string
text) {
22 std::replace(
text.begin(),
text.end(),
'\\',
'/');
23 if (
text.empty() ||
text.front() ==
'/' ||
text.find(
':') != std::string::npos)
return {};
25 std::istringstream stream(
text);
26 std::string component;
27 while (std::getline(stream, component,
'/')) {
28 if (component ==
".." || component.empty())
return {};
29 if (component ==
".")
continue;
30 for (
char&
c : component)
31 if (
c >=
'A' &&
c <=
'Z')
c = char(
c -
'A' +
'a');
32 if (!
out.empty())
out +=
'/';
37Point transform(
const Matrix&
m,
const Point&
p) {
38 return {
m[0] *
p[0] +
m[1] *
p[1] +
m[2] *
p[2] +
m[9],
m[3] *
p[0] +
m[4] *
p[1] +
m[5] *
p[2] +
m[10],
39 m[6] *
p[0] +
m[7] *
p[1] +
m[8] *
p[2] +
m[11]};
41Matrix compose(
const Matrix&
parent,
const Matrix& child) {
43 for (std::size_t row = 0;
row < 3; ++
row)
45 for (std::size_t k = 0; k < 3; ++k)
out[row * 3 +
column] +=
parent[row * 3 + k] * child[k * 3 +
column];
47 for (std::size_t i = 0; i < 3; ++i)
out[9 + i] = translation[i];
50std::optional<unsigned>
integer(std::string_view
text) {
53 if (
text.starts_with(
"0x") ||
text.starts_with(
"0X")) {
54 text.remove_prefix(2);
57 const auto parsed = std::from_chars(
text.data(),
text.data() +
text.size(),
value, base);
58 if (
text.empty() || parsed.ec != std::errc{} || parsed.ptr !=
text.data() +
text.size())
return {};
61double linear(
unsigned byte) {
62 const double value = double(
byte) / 255;
63 return value <= 0.04045 ?
value / 12.92 : std::pow((
value + 0.055) / 1.055, 2.4);
65std::array<double, 4> rgba(
unsigned rgb,
double alpha = 1) {
66 return {
linear((rgb >> 16) & 255),
linear((rgb >> 8) & 255),
linear(rgb & 255), alpha};
79 explicit Decoder(
const LDrawImportRequest&
request) : request_(
request) {
80 constexpr unsigned rgb[] = {0x05131d, 0x0055bf, 0x237841, 0x008f9b, 0xc91a09, 0xc870a0, 0x583927, 0x9ba19d,
81 0x6d6e5c, 0xb4d2e3, 0x4b9f4a, 0x55a5af, 0xf2705e, 0xfc97ac, 0xf2cd37, 0xffffff};
82 for (
unsigned i = 0; i < 16; ++i) palette_[i] = {rgba(rgb[i]),
"colour-" + std::to_string(i)};
84 Result<PreparedAssetImport>
run() {
85 auto indexed =
index();
87 std::string
root = pathKey(request_.sourceName);
89 auto expanded = expand(
root,
identity, palette_.at(7),
false, 0,
nullptr);
94 std::to_string(edgeLines_) +
" line/conditional-line records are retained in source, not rendered"});
96 "part transforms baked; 1 LDU = 0.4 mm; colours mapped to linear PBR base colour; "
97 "connectivity not inferred"});
99 usedSources_, std::move(findings_), request_.limits);
103 const LDrawImportRequest& request_;
104 std::map<std::string, std::vector<std::string>> documents_;
105 std::map<std::string, std::string> firstSections_;
106 std::map<std::string, std::string> owners_;
107 std::map<std::string, std::vector<std::uint8_t>> usedSources_;
108 std::map<unsigned, Colour> palette_;
109 std::map<std::string, structured_detail::MeshPart> parts_;
110 std::set<std::string> active_;
111 std::vector<ImportFinding> findings_;
112 std::uint64_t expandedLines_ = 0, edgeLines_ = 0, vertices_ = 0;
118 Result<void>
index() {
119 std::uint64_t total = 0,
lines = 0;
120 if (request_.files.size() > request_.limits.maximumAssets || request_.maximumDepth == 0 ||
121 request_.maximumDepth > 256 || request_.maximumExpandedLines == 0)
123 for (
const auto& [
name,
bytes] : request_.files) {
124 if (
bytes.size() > request_.limits.maximumSourceBytes - total)
126 total +=
bytes.size();
128 if (
owner.empty() ||
owner.size() > request_.limits.maximumStringBytes || owners_.contains(
owner))
129 return fail(
"invalid or duplicate case-insensitive source name",
name);
132 std::istringstream stream(std::string(
bytes.begin(),
bytes.end()));
134 bool section =
false, closed =
false;
136 while (std::getline(stream,
line)) {
137 if (++
lines > request_.maximumExpandedLines ||
line.size() > request_.limits.maximumStringBytes)
140 if (
line.starts_with(
"\xEF\xBB\xBF"))
line.erase(0, 3);
141 if (
line.starts_with(
"0 FILE ")) {
143 if (!section) documents_.erase(
owner);
145 return fail(
"duplicate/invalid MPD FILE name",
name);
151 }
else if (
line ==
"0 NOFILE") {
152 if (!section)
return fail(
"NOFILE without FILE",
name);
154 }
else if (!closed) {
157 if (
owner ==
"ldconfig.ldr" &&
line.starts_with(
"0 !COLOUR ")) {
163 if (documents_.size() > request_.limits.maximumAssets)
return fail(
"MPD section budget exceeded",
name);
167 Result<void> readColour(
const std::string&
line,
const std::string&
name, std::map<unsigned, Colour>& definitions,
168 const std::string& suffix) {
169 std::istringstream stream(
line);
170 std::string
token, codeText, valueText, edgeText, alphaText =
"255";
171 while (stream >>
token) {
173 if (
c >=
'a' &&
c <=
'z')
c = char(
c -
'a' +
'A');
176 else if (
token ==
"VALUE")
178 else if (
token ==
"EDGE")
180 else if (
token ==
"ALPHA")
184 if (!
code || *
code == 16 || *
code == 24 || !alpha || *alpha > 255 || edgeText.empty())
185 return fail(
"invalid !COLOUR definition",
name);
186 auto rgb =
integer(valueText.starts_with(
'#') ?
"0x" + valueText.substr(1) : valueText);
187 auto edge =
integer(edgeText.starts_with(
'#') ?
"0x" + edgeText.substr(1) : edgeText);
188 if (!rgb || *rgb > 0xffffffu || !
edge ||
189 !(valueText.starts_with(
'#') || valueText.starts_with(
"0x") || valueText.starts_with(
"0X")))
190 return fail(
"invalid !COLOUR RGB/edge",
name);
192 return fail(
"colour definition budget exceeded",
name);
193 definitions[*
code] = {rgba(*rgb,
double(*alpha) / 255),
"colour-" + std::to_string(*
code) + suffix};
194 if (
line.find(
" MATERIAL ") != std::string::npos ||
line.find(
" CHROME") != std::string::npos ||
195 line.find(
" METAL") != std::string::npos ||
line.find(
" PEARLESCENT") != std::string::npos ||
196 line.find(
" RUBBER") != std::string::npos ||
line.find(
"LUMINANCE") != std::string::npos)
198 "special finish/luminance retained in source; base colour and alpha translated"});
201 std::string resolve(
const std::string&
parent,
const std::string& filename)
const {
202 const auto key = pathKey(filename);
203 if (
key.empty())
return {};
204 const auto slash =
parent.find_last_of(
'/');
207 if (
const auto first = firstSections_.find(candidate);
first != firstSections_.end())
return first->second;
208 if (documents_.contains(candidate)) {
214 Result<Colour> colour(
unsigned code,
const Colour& inherited,
const ColourScope&
scope)
const {
216 if ((
code & 0xff000000u) == 0x02000000u)
221 if (
const auto found = palette_.find(
code);
found != palette_.end())
225 "asset.import.ldraw"));
227 Result<void> expand(
const std::string&
name,
const Matrix&
matrix,
const Colour& inheritedColor,
bool invert,
228 unsigned depth,
const ColourScope* parentScope) {
229 if (
depth >= request_.maximumDepth || active_.contains(
name))
return fail(
"cyclic/deep LDraw reference",
name);
230 const auto document = documents_.find(
name);
232 active_.insert(
name);
234 usedSources_.try_emplace(
owner, request_.files.at(
owner));
235 ColourScope
scope{parentScope, {}};
236 bool clockwise =
false, invertNext =
false;
237 for (std::size_t lineNumber = 0; lineNumber < document->second.size(); ++lineNumber) {
238 if (++expandedLines_ > request_.maximumExpandedLines)
return fail(
"expanded line budget exceeded",
name);
239 const auto&
line = document->second[lineNumber];
240 const auto location =
name +
":" + std::to_string(lineNumber + 1);
241 if (
line.empty())
continue;
242 std::istringstream stream(
line);
243 stream.imbue(std::locale::classic());
245 if (!(stream >>
type) ||
type > 5)
return fail(
"invalid LDraw line type", location);
247 if (
line.starts_with(
"0 !COLOUR ") &&
name !=
"ldconfig.ldr") {
248 auto defined = readColour(
line, location,
scope.definitions,
"@" + location);
249 if (!defined)
return defined;
251 if (
line.starts_with(
"0 !TEXMAP") ||
line.starts_with(
"0 !DATA") ||
line.starts_with(
"0 !:"))
252 return fail(
"textured/embedded geometry extensions are unsupported", location,
254 if (
line.starts_with(
"0 BFC ")) {
255 const auto command = trim(
line.substr(6));
256 if (command ==
"INVERTNEXT")
258 else if (command ==
"CW" || command ==
"CERTIFY CW" || command ==
"CLIP CW")
260 else if (command ==
"CCW" || command ==
"CERTIFY CCW" || command ==
"CLIP CCW" ||
261 command ==
"CERTIFY")
263 else if (command !=
"NOCERTIFY" && command !=
"NOCLIP" && command !=
"CLIP")
268 std::string colorText;
270 const auto decodedColor =
integer(colorText);
271 if (!decodedColor)
return fail(
"invalid LDraw colour", location);
273 auto resolvedColour = colour(*decodedColor, inheritedColor,
scope);
276 for (std::size_t i = 9; i < 12; ++i)
277 if (!(stream >>
local[i]) || !std::isfinite(
local[i]))
278 return fail(
"invalid part translation", location);
279 for (std::size_t i = 0; i < 9; ++i)
280 if (!(stream >>
local[i]) || !std::isfinite(
local[i]))
return fail(
"invalid part matrix", location);
281 std::string filename;
282 std::getline(stream, filename);
283 const auto reference = resolve(
name, trim(std::move(filename)));
289 if (!std::isfinite(det) || det == 0)
return fail(
"singular part transform", location);
292 if (!child)
return child;
296 if (invertNext)
return fail(
"INVERTNEXT must precede a reference", location);
297 std::array<Point, 4>
points{};
299 for (
unsigned i = 0; i <
count; ++i)
301 if (!(stream >>
value) || !
std::isfinite(
value)) return
fail(
"invalid LDraw coordinate", location);
303 if (stream >> extra)
return fail(
"extra LDraw geometry tokens", location);
308 auto resolvedColour = colour(*decodedColor, inheritedColor,
scope);
310 const auto&
key = resolvedColour.value().key;
311 if (!parts_.contains(
key) && parts_.size() * 2 + 3 > request_.limits.maximumAssets)
312 return fail(
"colour part budget exceeded", location);
313 auto& part = parts_[
key];
314 part.color = resolvedColour.value().value;
315 for (
unsigned i = 0; i <
count; ++i) {
317 points[i] = {
p[0] * 0.0004, -
p[1] * 0.0004, -
p[2] * 0.0004};
319 auto triangle = [&](
unsigned a,
unsigned b,
unsigned c) -> Result<void> {
320 if ((vertices_ + 3) * 28 + 24 > request_.limits.maximumDecodedBytes)
321 return fail(
"total mesh byte budget exceeded", location);
323 part.mesh, {points[a], points[clockwise != invert ? c : b], points[clockwise != invert ? b : c]},
325 if (added) vertices_ += 3;
329 if (!added)
return added;
335 if (invertNext)
return fail(
"dangling INVERTNEXT",
name);
AuthorityStoreHandleRef reference
const GltfImportRequest & request
const ColourScope * parent
std::map< unsigned, Colour > definitions
std::shared_ptr< OceanGpuSpectrum > owner
std::shared_ptr< const std::vector< glm::vec2 > > points
std::vector< std::string_view > lines
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.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
Result< void > appendTriangle(asset::CanonicalMeshData &mesh, const std::array< std::array< double, 3 >, 3 > &triangle, const AssetImportLimits &limits)
Result< PreparedAssetImport > packageModel(const ImportPackageIdentity &identity, std::string_view sourceName, std::string_view format, std::map< std::string, MeshPart > parts, const std::map< std::string, std::vector< std::uint8_t > > &sources, std::vector< ImportFinding > findings, const AssetImportLimits &limits)
Result< PreparedAssetImport > prepareLDrawImport(const LDrawImportRequest &request)
Prepare LDR/DAT/MPD triangles, referenced parts and colour-separated static prefab.
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
DiagnosticCode
Stable machine-readable diagnostic codes.
Owning LDraw source set. Names are relative, case-insensitive LDraw paths. Supply the document and re...