13constexpr std::string_view controlGuid =
"504b8163e405ec24bab88beccbe43d42";
14constexpr std::string_view detailsGuid =
"f3cf74665658f2249a2a56df92106e94";
15constexpr std::string_view motionGuid =
"c879218671cebf84d9385947d79161cd";
16constexpr std::string_view volumeGuid =
"eaf239e2056652741929c4183efd08b2";
17constexpr std::string_view elementGuid =
"2d447c3f2fda29f41a5b7e81398c0ab0";
19struct SceneComponent {
24std::vector<SceneComponent> components(std::string_view
source, std::string_view scriptGuid) {
25 std::vector<SceneComponent>
result;
26 const std::regex document(
27 R
"((?:^|\n)--- !u!114 &(-?[0-9]+)[^\n]*\nMonoBehaviour:\s*\n([\s\S]*?)(?=\n--- !u!|$))");
28 const std::regex
script(
"(?:^|\\n) m_Script: *\\{fileID: *11500000, guid: *" +
29 std::string(scriptGuid) + R
"(, type: *3\})");
31 const auto body = (*it)[2].str();
32 if (!std::regex_search(
body,
script))
continue;
34 result.push_back({std::stoll((*it)[1].str()),
body});
42std::optional<std::string> component(std::string_view
source, std::string_view scriptGuid) {
43 const std::regex document(R
"((?:^|\n)--- !u!114 &-?[0-9]+[^\n]*\nMonoBehaviour:\s*\n([\s\S]*?)(?=\n--- !u!|$))");
44 const std::regex
script(
"(?:^|\\n) m_Script: *\\{fileID: *11500000, guid: *" +
45 std::string(scriptGuid) + R
"(, type: *3\})");
47 auto body = (*it)[1].str();
48 if (std::regex_search(
body, script))
return body;
53Result<double>
number(std::string_view
body, std::string_view
name,
double fallback) {
55 const std::regex
field(
"(?:^|\\n) " + std::string(
name) + R
"(: *([^\r\n]+))");
56 if (!std::regex_search(
body.data(),
body.data() +
body.size(), match, field))
60 const auto token = match[1].str();
62 if (
end !=
token.size() || !std::isfinite(
value))
throw std::invalid_argument(
"number");
66 std::string(
name), {},
"asset.import"));
70Result<Value> array(std::string_view
body,
71 std::initializer_list<std::pair<std::string_view, double>>
fields) {
81Result<Value>
color(std::string_view
body, std::string_view
name, std::array<double, 4> fallback) {
83 const std::regex
field(
"(?:^|\\n) " + std::string(
name) +
84 R
"(: *\{r: *([^,]+), *g: *([^,]+), *b: *([^,]+), *a: *([^}]+)\})");
85 if (!std::regex_search(
body.data(),
body.data() +
body.size(), match, field))
93 if (
end !=
token.size() || !std::isfinite(
value))
throw std::invalid_argument(
"color");
97 std::string(
name), {},
"asset.import"));
103std::string guid(std::string_view
body, std::string_view
name) {
105 const std::regex
field(
"(?:^|\\n) " + std::string(
name) +
106 R
"(: *\{fileID: *-?[0-9]+, guid: *([0-9a-fA-F]{32}), type: *[23]\})");
107 return std::regex_search(
body.data(),
body.data() +
body.size(), match, field)
112Result<Value> details(std::string_view
body) {
113 auto layers = array(
body, {{
"layerColors", 0}, {
"layerExtras", 0}, {
"layerMotion", 0}});
114 auto global = array(
body, {{
"globalColor", 1}, {
"globalAlpha", 1}, {
"globalOverlay", 1}, {
"globalWetness", 1}});
115 auto colorMask = array(
body, {{
"colorMaskMin", .4}, {
"colorMaskMax", .6}});
116 auto overlayMask = array(
body, {{
"overlayMaskMin", .4}, {
"overlayMaskMax", .6}});
117 auto perspective = array(
body, {{
"perspectivePush", 0}, {
"perspectiveNoise", 0}, {
"perspectiveAngle", 1}});
119 auto bending = array(
body, {{
"bendingAmplitude", 1}, {
"bendingSpeed", 6}, {
"bendingScale", 2}});
120 auto flutter = array(
body, {{
"flutterAmplitude", .1}, {
"flutterSpeed", 20}, {
"flutterScale", 2}});
121 auto alpha =
number(
body,
"alphaTreshold", .5), interaction =
number(
body,
"interactionAmplitude", 1);
122 const bool layersOk = bool(layers), globalOk = bool(
global), colorMaskOk = bool(colorMask),
123 overlayMaskOk = bool(overlayMask), perspectiveOk = bool(perspective), highlightOk = bool(
highlight),
124 bendingOk = bool(bending), flutterOk = bool(flutter), alphaOk = bool(alpha),
125 interactionOk = bool(interaction);
126 if (!layersOk || !globalOk || !colorMaskOk || !overlayMaskOk || !perspectiveOk || !highlightOk || !bendingOk ||
127 !flutterOk || !alphaOk || !interactionOk)
130 auto highlightValue = std::move(
highlight).takeValue();
133 {
"layers", std::move(layers).takeValue()}, {
"global", std::move(
global).takeValue()},
134 {
"colorMask", std::move(colorMask).takeValue()}, {
"overlayMask", std::move(overlayMask).takeValue()},
135 {
"alphaThreshold", alpha.value()}, {
"perspective", std::move(perspective).takeValue()},
136 {
"motionHighlight", std::move(highlightValue)}, {
"bending", std::move(bending).takeValue()},
137 {
"flutter", std::move(flutter).takeValue()}, {
"interactionAmplitude", interaction.value()}}));
140Result<Value> control(std::string_view
body) {
142 auto overlay =
color(
body,
"overlayColor", {1, 1, 1, 1});
143 auto values = array(
body, {{
"seasonControl", 2}, {
"globalAlpha", 1}, {
"globalOverlay", 0},
144 {
"globalWetness", 0}, {
"globalEmissive", 1}, {
"globalSubsurface", 1},
145 {
"globalSizeFade", 1}, {
"overlaySmoothness", .5}, {
"overlayNormalScale", .5},
146 {
"overlaySubsurface", .5}, {
"overlayScale", 1}, {
"wetnessContrast", .5},
147 {
"wetnessNormalScale", .5}, {
"noiseTextureTilling", 1},
148 {
"proximityDistanceFade", 1}, {
"sizeFadeDistanceBias", 1},
149 {
"defaultConformHeight", 0}});
150 const bool tintOk = bool(
tint), overlayOk = bool(overlay), valuesOk = bool(
values);
151 if (!tintOk || !overlayOk || !valuesOk)
155 {
"values", std::move(
values).takeValue()}, {
"globalColor", std::move(
tint).takeValue()},
156 {
"overlayColor", std::move(overlay).takeValue()}, {
"overlayAlbedoGuid", guid(
body,
"overlayAlbedo")},
157 {
"overlayNormalGuid", guid(
body,
"overlayNormal")}, {
"noiseTextureGuid", guid(
body,
"noiseTexture3D")}}));
160Result<Value> motion(std::string_view
body) {
161 auto values = array(
body, {{
"windPower", .5}, {
"noiseTilling", 1}, {
"motionBending", 1},
162 {
"motionBranch", 1}, {
"motionFlutter", 1}, {
"motionSpeed", 1},
163 {
"useAnimatedMotionTime", 1}, {
"motionFadeDistance", 100}});
166 {
"noiseTextureGuid", guid(
body,
"noiseTexture")}}));
169struct SceneTransform {
176std::optional<std::int64_t>
fileId(std::string_view
body, std::string_view
name) {
177 const std::string
field =
" " + std::string(
name) +
":";
181 if (
position == std::string_view::npos)
return {};
183 if (
position == std::string_view::npos)
return {};
198std::optional<double> rotationComponent(std::string_view
line, std::string_view
name) {
199 const std::string
field = std::string(
name) +
":";
201 if (
position == std::string_view::npos)
return {};
216std::optional<std::array<double, 3>> vector3Field(std::string_view
body, std::string_view
name) {
217 const std::string
field =
" " + std::string(
name) +
":";
219 if (
start == std::string_view::npos)
return {};
222 const auto x = rotationComponent(
line,
"x"),
y = rotationComponent(
line,
"y"),
z = rotationComponent(
line,
"z");
223 if (!
x || !
y || !
z)
return {};
224 return std::array<double, 3>{*
x, *
y, *
z};
227std::map<std::int64_t, SceneTransform> transforms(std::string_view
source) {
228 std::map<std::int64_t, SceneTransform>
result;
229 constexpr std::string_view marker =
"--- !u!4 &";
236 const auto idBegin =
cursor + marker.size();
237 const auto headerEnd =
source.find(
'\n', idBegin);
238 if (headerEnd == std::string_view::npos)
break;
239 const auto bodyBegin = headerEnd + 1;
240 if (!
source.substr(bodyBegin).starts_with(
"Transform:")) {
244 const auto bodyContent =
source.find(
'\n', bodyBegin);
245 if (bodyContent == std::string_view::npos)
break;
246 const auto next =
source.find(
"\n--- !u!", bodyContent + 1);
247 const auto body =
source.substr(bodyContent + 1,
248 next == std::string_view::npos ?
source.size() - bodyContent - 1
249 :
next - bodyContent - 1);
250 SceneTransform transform;
252 transform.gameObject =
fileId(
body,
"m_GameObject").value_or(0);
253 transform.parent =
fileId(
body,
"m_Father").value_or(0);
254 transform.position = vector3Field(
body,
"m_LocalPosition").value_or(std::array<double, 3>{0, 0, 0});
255 transform.scale = vector3Field(
body,
"m_LocalScale").value_or(std::array<double, 3>{1, 1, 1});
256 const auto rotationStart =
body.find(
" m_LocalRotation:");
257 if (rotationStart == std::string_view::npos) {
261 const auto rotationEnd =
body.find(
'\n', rotationStart);
262 const auto line =
body.substr(rotationStart, rotationEnd - rotationStart);
263 const auto x = rotationComponent(
line,
"x"),
y = rotationComponent(
line,
"y"),
264 z = rotationComponent(
line,
"z"),
w = rotationComponent(
line,
"w");
265 if (!
x || !
y || !
z || !
w)
return {};
266 transform.rotation = {*
x, *
y, *
z, *
w};
267 result.emplace(std::stoll(std::string(
source.substr(idBegin, headerEnd - idBegin))), transform);
276struct WorldTransform {
278 std::array<double, 4>
rotation{0, 0, 0, 1};
281std::array<double, 4> multiply(std::array<double, 4> lhs, std::array<double, 4> rhs);
283Result<std::array<double, 4>> normalized(std::array<double, 4>
value) {
290 return Result<std::array<double, 4>>::success(
value);
293std::array<double, 3>
rotate(std::array<double, 4>
q, std::array<double, 3>
v) {
294 const std::array<double, 4>
p{
v[0],
v[1],
v[2], 0};
295 const std::array<double, 4> conjugate{-
q[0], -
q[1], -
q[2],
q[3]};
296 const auto result = multiply(multiply(
q,
p), conjugate);
300Result<WorldTransform> worldTransform(
const std::map<std::int64_t, SceneTransform>& sceneTransforms,
302 auto found = std::find_if(sceneTransforms.begin(), sceneTransforms.end(),
303 [&](
const auto& entry) { return entry.second.gameObject == gameObject; });
304 if (
found == sceneTransforms.end())
307 std::vector<const SceneTransform*> chain{&
found->second};
308 std::set<std::int64_t> visited{
found->first};
311 const auto ancestor = sceneTransforms.find(
parent);
312 if (ancestor == sceneTransforms.end() || !visited.emplace(
parent).second)
315 chain.push_back(&ancestor->second);
316 parent = ancestor->second.parent;
318 WorldTransform world;
319 for (
auto it = chain.rbegin(); it != chain.rend(); ++it) {
320 auto localRotation = normalized((*it)->rotation);
322 std::array<double, 3>
local{(*it)->position[0] * world.scale[0], (*it)->position[1] * world.scale[1],
323 (*it)->position[2] * world.scale[2]};
327 world.scale[
axis] *= (*it)->scale[
axis];
329 auto composed = normalized(multiply(world.rotation, localRotation.value()));
331 world.rotation = std::move(composed).takeValue();
333 world.position[2] = -world.position[2];
334 world.rotation[0] = -world.rotation[0];
335 world.rotation[1] = -world.rotation[1];
339std::optional<std::string_view> propertyBlock(std::string_view
body, std::string_view
name) {
340 const std::string marker =
" prop: " + std::string(
name);
342 if (
begin == std::string_view::npos)
return {};
344 if (
begin == std::string_view::npos)
return {};
346 if (
end == std::string_view::npos)
end =
body.size();
350double materialNumber(std::string_view
body, std::string_view
name,
double fallback) {
351 const auto block = propertyBlock(
body,
name);
352 if (!block)
return fallback;
353 const auto value =
number(*block,
" value", fallback);
357Value materialVector(std::string_view
body, std::string_view
name, std::array<double, 4> fallback) {
358 const auto block = propertyBlock(
body,
name);
359 if (!block)
return Value::array({fallback[0], fallback[1], fallback[2], fallback[3]});
360 auto value =
color(*block,
" vector", fallback);
361 return value ? std::move(
value).takeValue() :
Value::array({fallback[0], fallback[1], fallback[2], fallback[3]});
364std::string materialTexture(std::string_view
body, std::string_view
name) {
365 const auto block = propertyBlock(
body,
name);
366 return block ? guid(*block,
" texture") :
std::
string{};
369Result<Value> materialProperties(std::string_view
body) {
372 constexpr std::string_view marker =
" - type:";
373 const std::regex namePattern(R
"((?:^|\n) prop: *([A-Za-z_][A-Za-z0-9_]{0,127})\s*(?:\r?\n|$))");
375 const auto next =
body.find(
"\n - type:",
cursor + marker.size());
378 if (!std::regex_search(block.data(), block.data() + block.size(),
name, namePattern))
382 auto vector =
color(block,
" vector", {0, 0, 0, 0});
386 "TVE element property value is malformed",
name[1].str(),
387 {},
"asset.import"));
389 {
"textureGuid", guid(block,
" texture")},
390 {
"vector", std::move(vector).takeValue()}, {
"value",
value.value()}}));
399void collectTextureGuids(
const Value&
value, std::set<std::string>&
output) {
403 collectTextureGuids(child,
output);
406 for (
const auto& child : *array) collectTextureGuids(
child,
output);
410bool importedImageAvailable(
const UnityProjectImportRequest&
request, std::string_view targetGuid) {
412 if (!
path.ends_with(
".meta"))
continue;
413 const std::string meta(
bytes.begin(),
bytes.end());
414 if (meta.find(
"guid: " + std::string(targetGuid)) == std::string::npos)
continue;
420 if (extension ==
".png" || extension ==
".tga" || extension ==
".tif" || extension ==
".tiff")
return true;
421 if (extension !=
".asset")
return false;
423 return text.find(
"\nTexture2D:") != std::string::npos;
428Result<void> bindTextureAssets(Value&
value,
const UnityProjectImportRequest&
request) {
430 const auto guidValue =
object->find(
"textureGuid");
431 if (guidValue !=
object->end() && guidValue->second.isString()) {
433 if (!guidValue->second.asString().empty() && importedImageAvailable(
request, guidValue->second.asString())) {
439 object->emplace(
"textureAsset", std::move(asset));
443 auto bound = bindTextureAssets(child,
request);
444 if (!bound)
return bound;
447 for (
auto& child : *array) {
448 auto bound = bindTextureAssets(child,
request);
449 if (!bound)
return bound;
456 const std::map<std::string_view, std::pair<std::string_view, int>>
shaders{
457 {
"1179777fe2a84944798f2df69a9616a5", {
"color-effect", 0}},
458 {
"ebee0293d9bb4564889bd81c801438b7", {
"color-map", 0}},
459 {
"da183c57da5cee64c9d1fd3e840427b6", {
"color-noise", 0}},
460 {
"853be43322d350648a82ec17b27de5cf", {
"color-tint", 0}},
461 {
"94b5d04d01c0973498bbb16cea8449ec", {
"extras-alpha", 1}},
462 {
"47fd4a0e901c8844a9f5ae6bcdef7ca4", {
"extras-emissive", 1}},
463 {
"b3820571eb3f04f4f855cc7161c165d7", {
"extras-overlay", 1}},
464 {
"3a8db8eb5154b6c44940a6c8616408d8", {
"extras-wetness", 1}},
465 {
"c2aed2f308142f94fa04326437ee0005", {
"motion-advanced", 2}},
466 {
"8aca4d3e46e8b7b458ec65a9bb11f144", {
"motion-interaction", 2}},
467 {
"c52053b6a008e1544bad0837b518fa94", {
"motion-wind-power", 2}},
468 {
"1e5171ac7b63ed441960da6cf37146a2", {
"vertex-conform-model", 3}},
469 {
"3f514efeb56cd5149a0f4c127eab8a8c", {
"vertex-conform-simple", 3}},
470 {
"4bcfd77507de42d40ad7ce2543a44cd8", {
"vertex-conform-terrain", 3}},
471 {
"387db0d42ba361645a8443beadc8bdd6", {
"vertex-height-offset", 3}},
472 {
"abb24a67f2ce88d498809438c1104783", {
"vertex-height", 3}},
473 {
"ab583b89d93bd5846883c513711e769a", {
"vertex-orientation-model", 3}},
474 {
"74b163185090aaf41b8df93640d24c50", {
"vertex-orientation-terrain", 3}},
475 {
"4776cc0409f0f4e4da64e5837bff4b0d", {
"vertex-size", 3}},
477 const auto sceneTransforms = transforms(
source);
479 std::size_t invalidMaterials = 0;
480 for (
const auto& component : components(
source, elementGuid)) {
482 auto world = worldTransform(sceneTransforms,
gameObject);
484 const auto shader = guid(component.body,
" shader");
486 if (shaderDefinition ==
shaders.end()) { ++invalidMaterials;
continue; }
487 const std::string
kind(shaderDefinition->second.first);
488 const int channel = shaderDefinition->second.second;
489 std::array<double, 4>
main{1, 1, 1, 1};
490 if (
kind ==
"color-tint")
main = {.5019608, .5019608, .5019608, 1};
491 double layerMask = 1;
492 if (propertyBlock(component.body,
"_ElementLayerMask")) {
493 layerMask = materialNumber(component.body,
"_ElementLayerMask", 1);
494 }
else if (propertyBlock(component.body,
"_ElementLayerValue")) {
495 layerMask = materialNumber(component.body,
"_ElementLayerValue", 1);
497 const auto legacyLayer = materialNumber(component.body,
"_ElementLayer", 0);
498 if (legacyLayer < 0 || legacyLayer > 8 || std::floor(legacyLayer) != legacyLayer)
500 "TVE legacy element layer is outside 0..8",
501 std::string(
path), {},
"asset.import"));
502 layerMask = double(std::uint16_t(1u << std::uint32_t(legacyLayer)));
504 const auto seasonal = materialNumber(component.body,
"_ElementMode", 0) >= .5;
507 if (
kind ==
"color-tint")
508 seasons.push_back(materialVector(component.body,
"_AdditionalColor" + std::to_string(
index),
main));
510 const auto value = materialNumber(component.body,
"_AdditionalValue" + std::to_string(
index), 1);
514 const auto& transform = world.value();
515 auto enabledValue =
number(component.body,
"m_Enabled", 1);
516 auto visibilityValue =
number(component.body,
"customVisibility", -1);
517 auto propertiesValue = materialProperties(component.body);
518 if (!enabledValue || !visibilityValue || !propertiesValue)
520 : !visibilityValue ? visibilityValue.
status()
521 : propertiesValue.
status());
522 const double mainValue = materialNumber(component.body,
"_MainValue",
main[0]);
523 Value channelValue = materialVector(component.body,
"_MainColor",
main);
524 if (
kind ==
"extras-overlay") channelValue =
Value::array({1, 0, mainValue, 1});
525 else if (
kind ==
"motion-interaction") channelValue =
Value::array({1, 0, 0, mainValue});
526 else if (
kind ==
"motion-wind-power") channelValue =
Value::array({0, 0, mainValue, 1});
527 else if (
kind ==
"vertex-size") channelValue =
Value::array({0, 0, 0, mainValue});
529 {
"sourceFileId", component.fileId}, {
"shaderGuid",
shader}, {
"kind",
kind}, {
"channel", channel},
530 {
"properties", std::move(propertiesValue).takeValue()},
531 {
"enabled", enabledValue.value() >= .5},
532 {
"visibility", std::int64_t(visibilityValue.value())},
533 {
"position",
Value::array({transform.position[0], transform.position[1], transform.position[2]})},
534 {
"rotation",
Value::array({transform.rotation[0], transform.rotation[1], transform.rotation[2], transform.rotation[3]})},
535 {
"scale",
Value::array({std::abs(transform.scale[0]), std::abs(transform.scale[1]), std::abs(transform.scale[2])})},
536 {
"layers", std::int64_t(layerMask)}, {
"intensity", materialNumber(component.body,
"_ElementIntensity", 1)},
537 {
"value", std::move(channelValue)},
538 {
"seasonal", seasonal}, {
"seasons",
Value(std::move(seasons))},
539 {
"textureGuid", materialTexture(component.body,
"_MainTex")},
540 {
"remap",
Value::array({materialNumber(component.body,
"_MainTexColorMinValue", 0),
541 materialNumber(component.body,
"_MainTexColorMaxValue", 1),
542 materialNumber(component.body,
"_MainTexAlphaMinValue", 0),
543 materialNumber(component.body,
"_MainTexAlphaMaxValue", 1),
544 materialNumber(component.body,
"_MainTexFallofMinValue", 0),
545 materialNumber(component.body,
"_MainTexFallofMaxValue", 0)})},
546 {
"blendRgb", std::int64_t(materialNumber(component.body,
"_ElementBlendRGB", 0))},
547 {
"blendAlpha", std::int64_t(materialNumber(component.body,
"_ElementBlendA", 0))},
548 {
"directionMode", std::int64_t(materialNumber(component.body,
"_ElementDirectionMode", 20))},
549 {
"invertDirection", materialNumber(component.body,
"_ElementInvertMode",
550 materialNumber(component.body,
"_InvertX", 0)) >= .5},
551 {
"volumeFade", materialNumber(component.body,
"_ElementVolumeFadeMode",
552 materialNumber(component.body,
"_ElementFadeSupport", 0)) >= .5},
553 {
"motionMode", std::int64_t(materialNumber(component.body,
"_ElementMotionMode", 15))},
554 {
"motionPower", materialNumber(component.body,
"_MotionPower", 0)}}));
557 std::to_string(
output.size()) +
" executable element definitions normalized"});
558 if (invalidMaterials != 0)
560 std::to_string(invalidMaterials) +
" source elements have no executable material"});
564std::array<double, 4> multiply(std::array<double, 4> lhs, std::array<double, 4> rhs) {
565 return {lhs[3] * rhs[0] + lhs[0] * rhs[3] + lhs[1] * rhs[2] - lhs[2] * rhs[1],
566 lhs[3] * rhs[1] - lhs[0] * rhs[2] + lhs[1] * rhs[3] + lhs[2] * rhs[0],
567 lhs[3] * rhs[2] + lhs[0] * rhs[1] - lhs[1] * rhs[0] + lhs[2] * rhs[3],
568 lhs[3] * rhs[3] - lhs[0] * rhs[0] - lhs[1] * rhs[1] - lhs[2] * rhs[2]};
571Result<Value> motionDirection(std::string_view
source, std::string_view
body) {
572 const auto manager =
fileId(
body,
"m_GameObject").value_or(0);
575 const auto sceneTransforms = transforms(
source);
576 auto found = std::find_if(sceneTransforms.begin(), sceneTransforms.end(),
577 [&](
const auto& entry) { return entry.second.gameObject == gameObject; });
578 if (
found == sceneTransforms.end())
580 "TVE motion direction Transform is missing",
"mainDirection",
581 {},
"asset.import"));
583 std::set<std::int64_t> visited{
found->first};
586 const auto ancestor = sceneTransforms.find(
parent);
587 if (ancestor == sceneTransforms.end() || !visited.emplace(
parent).second)
589 "TVE motion direction Transform hierarchy is invalid",
590 "mainDirection", {},
"asset.import"));
592 parent = ancestor->second.parent;
598 "TVE motion direction rotation is invalid",
"mainDirection", {},
603 const double horizontal = std::hypot(unityX, unityZ);
604 if (!std::isfinite(horizontal) || horizontal <= 1e-12)
606 "mainDirection", {},
"asset.import"));
610Result<Value> volumeChannel(std::string_view
body, std::string_view
name) {
612 const std::regex legacyField(
"(?:^|\\n) " + std::string(
name) + R
"(: *(-?[0-9]+)\s*(?:\r?\n|$))");
613 if (std::regex_search(
body.data(),
body.data() +
body.size(), legacy, legacyField)) {
615 const auto resolution =
static_cast<std::int64_t
>(std::stoll(legacy[1].str()));
620 "TVE legacy volume resolution is invalid",
621 std::string(
name), {},
"asset.import"));
625 const std::regex section(
"(?:^|\\n) " + std::string(
name) + R
"(:\s*\n([\s\S]*?)(?=\n [A-Za-z_][^\n]*:|$))");
626 if (!std::regex_search(
body.data(),
body.data() +
body.size(), match, section))
628 std::string(
name), {},
"asset.import"));
629 const auto nested = match[1].str();
630 auto read = [&](std::string_view
field) -> Result<double> {
632 const std::regex
pattern(
"(?:^|\\n) " + std::string(field) + R
"(: *([^\r\n]+))");
633 if (!std::regex_search(nested.data(), nested.data() + nested.size(),
value,
pattern))
636 std::string(
name) +
"." + std::string(field), {},
"asset.import"));
640 const auto decoded = std::stod(
token, &
end);
641 if (
end !=
token.size() || !std::isfinite(decoded))
throw std::invalid_argument(
"number");
646 std::string(
name) +
"." + std::string(field), {},
"asset.import"));
650 const bool modeOk = bool(mode), widthOk = bool(
width), heightOk = bool(
height);
651 if (!modeOk || !widthOk || !heightOk)
657 auto values = array(
body, {{
"renderScale", 1}, {
"elementsVisibility", 0}, {
"elementsSorting", 0},
658 {
"elementsEdgeFade", .75}});
659 auto colors = volumeChannel(
body,
"renderColors"), extras = volumeChannel(
body,
"renderExtras"),
660 motion = volumeChannel(
body,
"renderMotion"), vertex = volumeChannel(
body,
"renderVertex");
661 const bool valuesOk = bool(
values), colorsOk = bool(
colors), extrasOk = bool(extras), motionOk = bool(motion),
662 vertexOk = bool(vertex);
663 if (!valuesOk || !colorsOk || !extrasOk || !motionOk || !vertexOk)
666 : !extrasOk ? extras.
status()
667 : !motionOk ? motion.
status()
670 {
"colors", std::move(
colors).takeValue()},
671 {
"extras", std::move(extras).takeValue()},
672 {
"motion", std::move(motion).takeValue()},
673 {
"vertex", std::move(vertex).takeValue()}}));
681 const auto controlBody = component(
text, controlGuid), detailsBody = component(
text, detailsGuid),
682 motionBody = component(
text, motionGuid), volumeBody = component(
text, volumeGuid);
683 if (!controlBody && !detailsBody && !motionBody && !volumeBody)
686 source.path, {},
"asset.import"));
687 if (!controlBody || !detailsBody || !motionBody || !volumeBody)
689 "TVE scene manager component set is incomplete",
690 source.path, {},
"asset.import"));
691 std::vector<ImportFinding> elementFindings;
692 auto controlValue = control(*controlBody), detailsValue = details(*detailsBody), motionValue = motion(*motionBody),
694 const bool controlOk = bool(controlValue), detailsOk = bool(detailsValue), motionOk = bool(motionValue),
695 volumeOk = bool(volumeValue), elementsOk = bool(elementsValue);
696 if (!controlOk || !detailsOk || !motionOk || !volumeOk || !elementsOk)
699 auto directionValue = motionDirection(
text, *motionBody);
701 (*motionValue.value().getIf<
Value::Object>())[
"direction"] = std::move(directionValue).takeValue();
702 std::set<std::string> textureGuids;
703 auto boundTextures = bindTextureAssets(elementsValue.value(),
request);
705 collectTextureGuids(elementsValue.value(), textureGuids);
706 for (
const auto name : {
"overlayAlbedo",
"overlayNormal",
"noiseTexture3D"}) {
708 if (!
value.empty()) textureGuids.insert(std::move(
value));
710 auto motionNoise = guid(*motionBody,
"noiseTexture");
711 if (!motionNoise.empty()) textureGuids.insert(std::move(motionNoise));
712 Value definition =
Value::object({{
"schema",
"eve.vegetation-scene"}, {
"schemaVersion", 1},
713 {
"sourceGuid",
source.guid}, {
"control", std::move(controlValue).takeValue()},
714 {
"details", std::move(detailsValue).takeValue()},
715 {
"motion", std::move(motionValue).takeValue()},
716 {
"volume", std::move(volumeValue).takeValue()},
717 {
"elements", std::move(elementsValue).takeValue()}});
718 auto encoded = definition.toJson();
727 for (
const auto& textureGuid : textureGuids) {
728 if (!importedImageAvailable(
request, textureGuid))
continue;
732 "elementTexture:" + textureGuid, {},
"eve.image/3", {}});
734 const std::string
path =
"assets/" +
id.format() +
"/asset.json";
735 const std::vector<std::uint8_t>
payload(encoded.value().begin(), encoded.value().end());
738 out.manifest.entrypoints.emplace(
"default", ref.value());
740 out.sourceMappings.push_back({
"TVE.Manager", ref.value()});
742 "Global Control, Details, Motion and Volume serialized as native scene state"});
743 out.findings.insert(
out.findings.end(), std::make_move_iterator(elementFindings.begin()),
744 std::make_move_iterator(elementFindings.end()));
748 const auto templateAsset = std::find_if(hierarchy.value().manifest.assets.begin(),
749 hierarchy.value().manifest.assets.end(), [](
const auto& asset) {
750 return asset.type ==
"eve.scene-template";
752 if (templateAsset == hierarchy.value().manifest.assets.end())
755 {},
"asset.import"));
756 const AssetRef templateRef = templateAsset->asset;
758 "vegetationScene", {},
"eve.vegetation-scene/1", {}});
759 out.manifest.entrypoints.emplace(
"scene", templateRef);
760 for (
auto& asset : hierarchy.value().manifest.assets)
out.manifest.assets.push_back(std::move(asset));
761 for (
auto& dependency : hierarchy.value().manifest.dependencies)
762 out.manifest.dependencies.push_back(std::move(dependency));
763 for (
auto& entry : hierarchy.value().entries)
out.entries.push_back(std::move(entry));
764 for (
auto& mapping : hierarchy.value().sourceMappings)
out.sourceMappings.push_back(std::move(mapping));
765 for (
auto& finding : hierarchy.value().findings)
out.findings.push_back(std::move(finding));
784std::optional<std::string> match(
const std::string&
s,
const std::string&
pattern) {
785 const std::regex expression(
pattern);
786 auto it = std::sregex_iterator(
s.begin(),
s.end(), expression);
787 if (it == std::sregex_iterator())
return {};
788 auto result = (*it)[1].str();
789 if (++it != std::sregex_iterator())
throw Invalid{};
792double numeric(
const Value&
value) {
794 const double n =
value.isInt64() ? double(
value.asInt()) :
value.asDouble();
795 if (!std::isfinite(
n) || std::abs(
n) > std::numeric_limits<float>::max())
throw Invalid{};
798double scalar(
const std::string&
text,
const std::string&
name,
double fallback) {
799 const auto raw = match(
text,
"(?:^|\\n)\\s*- " +
name +
": *([^\\r\\n]+)");
800 if (!
raw)
return fallback;
803 return numeric(decoded.value());
805double importerScalar(
const std::string&
text,
const std::string&
name,
double fallback) {
806 const auto raw = match(
text,
"(?:^|\\n)[ \\t]*" +
name +
": *([^\\r\\n]+)");
807 if (!
raw)
return fallback;
810 return numeric(decoded.value());
812std::array<double, 4>
vector(
const std::string&
text,
const std::string&
name, std::array<double, 4> fallback) {
813 auto raw = match(
text,
"(?:^|\\n)\\s*- " +
name +
": *(\\{[^\\r\\n]+\\})");
814 if (!
raw)
return fallback;
819 for (
const auto key : {
"r",
"g",
"b",
"a"}) {
820 if (!
object.contains(
key))
throw Invalid{};
821 fallback[i++] = numeric(
object.
at(
key));
825std::optional<std::string>
texture(
const std::string&
text,
const std::string&
name) {
826 auto block = match(
text,
"- " +
name +
":([\\s\\S]*?)(?:\\n - |\\n m_|$)");
827 if (!block)
return {};
828 if (match(*block, R
"(m_Texture: *\{fileID: *(0)\})")) return {};
829 auto guid = match(*block, R
"(m_Texture: *\{fileID: *2800000, guid: *([0-9a-fA-F]{32}), type: *[23]\})");
833Result<std::string> texturePath(
const UnityProjectImportRequest&
request,
const std::string& guid) {
836 if (
path.ends_with(
".meta")) {
850Result<Value::Object> textureSampler(
const UnityProjectImportRequest&
request,
const std::string&
path) {
851 const bool native =
path.ends_with(
".asset");
854 const auto u = importerScalar(
settings, native ?
"m_WrapU" :
"wrapU", -1);
855 const auto v = importerScalar(
settings, native ?
"m_WrapV" :
"wrapV", -1);
856 for (
const auto wrap : {
u,
v}) {
857 if (wrap != -1 && wrap != 0 && wrap != 1 && wrap != 2 && wrap != 3)
throw Invalid{};
861 path, {},
"asset.import"));
863 auto convert = [](
double wrap) {
return wrap == 1 ? 33071 : wrap == 2 ? 33648 : 10497; };
864 auto filter = importerScalar(
settings, native ?
"m_FilterMode" :
"filterMode", -1);
868 const auto heightNormal = importerScalar(
settings,
"convertToNormalMap", 0);
869 if (heightNormal != 0 && heightNormal != 1)
throw Invalid{};
870 filter = heightNormal == 1 ? 2 : 1;
872 const auto mipSetting = importerScalar(
settings, native ?
"m_MipCount" :
"enableMipMap", 1);
873 if (native ? (mipSetting < 1 || mipSetting != std::floor(mipSetting)) : (mipSetting != 0 && mipSetting != 1))
875 const bool mipmaps = native ? mipSetting > 1 : mipSetting == 1;
876 const int mag =
filter == 0 ? 9728 : 9729;
877 const int min = !mipmaps ? mag :
filter == 0 ? 9984 :
filter == 2 ? 9987 : 9985;
879 {{
"wrapS", convert(
u)}, {
"wrapT", convert(
v)}, {
"minFilter",
min}, {
"magFilter", mag}});
881Result<PreparedAssetImport> ormImage(
const UnityProjectImportRequest&
request,
const std::string&
text,
882 const PersistentId& materialId,
double occlusion,
double smoothness) {
883 std::vector<std::uint8_t> rgba{255, 255, 255, 255};
893 const auto definition =
imported.value().manifest.assets.front().definition;
895 if (entry.
path == definition) {
899 auto read32 = [&](std::size_t
p) {
900 const auto&
b = cooked.value().bulk;
901 return std::uint32_t(
b[
p]) | (std::uint32_t(
b[
p + 1]) << 8) | (std::uint32_t(
b[
p + 2]) << 16) |
902 (std::uint32_t(
b[
p + 3]) << 24);
906 rgba.assign(cooked.value().bulk.begin() + 28, cooked.value().bulk.end());
909 for (std::size_t
p = 0;
p < rgba.size();
p += 4) {
910 const auto ao = 255.0 + (double(rgba[
p + 1]) - 255.0) * occlusion;
911 const auto roughness = 255.0 - double(rgba[
p + 3]) * smoothness;
912 const auto mask = rgba[
p + 2];
913 rgba[
p] = std::uint8_t(std::lround(
ao));
914 rgba[
p + 1] = std::uint8_t(std::lround(
roughness));
923enum class NormalSource {
Authored, Height };
924uint32_t normalExtent(uint32_t extent,
int mode) {
925 if (mode == 0 || (extent & (extent - 1)) == 0)
return extent;
927 while (lower <= extent / 2) lower *= 2;
928 if (lower > UINT32_MAX / 2)
throw Invalid{};
929 const auto upper = lower * 2;
930 return mode == 3 || (mode == 1 && extent - lower < upper - extent) ? lower : upper;
932struct NormalResizeTap {
936std::vector<NormalResizeTap> normalResizeTaps(uint32_t
source, uint32_t
target, uint32_t coordinate,
int algorithm) {
940 std::vector<NormalResizeTap> taps;
942 taps.push_back({uint32_t(std::clamp(
index, int64_t(0), int64_t(
source - 1))),
weight});
944 if (algorithm == 1) {
958 x < 1 ? ((12 - 9 *
b - 6 *
c) *
x *
x *
x + (-18 + 12 *
b + 6 *
c) *
x *
x + 6 - 2 *
b) / 6
960 ? ((-
b - 6 *
c) *
x *
x *
x + (6 *
b + 30 *
c) *
x *
x + (-12 *
b - 48 *
c) *
x + 8 *
b + 24 *
c) / 6
965 for (
auto& tap : taps) tap.
weight /= sum;
968std::vector<double> normalResizeRgb(
const std::vector<uint8_t>& bulk, uint32_t
width, uint32_t
height,
969 uint32_t targetWidth, uint32_t targetHeight,
int algorithm) {
970 std::vector<double> rgb(
size_t(targetWidth) * targetHeight * 3);
971 for (uint32_t
y = 0;
y < targetHeight; ++
y) {
972 const auto vertical = normalResizeTaps(
height, targetHeight,
y, algorithm);
973 for (uint32_t
x = 0;
x < targetWidth; ++
x) {
974 const auto horizontal = normalResizeTaps(
width, targetWidth,
x, algorithm);
975 std::array<double, 3>
value{};
976 for (
const auto&
sy : vertical)
977 for (const auto&
sx : horizontal)
978 for (size_t
c = 0;
c < 3; ++
c)
980 for (
size_t c = 0;
c < 3; ++
c) {
981 const auto clamped = std::clamp(
value[
c], 0.0, 255.0);
984 rgb[(size_t(
y) * targetWidth +
x) * 3 +
c] =
985 algorithm == 0 ?
double(std::lround(
float(clamped))) / 255.0 : clamped / 255.0;
991Result<PreparedAssetImport> normalImage(
const UnityProjectImportRequest&
request,
const std::string&
path,
993 bool flipGreen, NormalSource
source) {
994 const bool fromHeight =
source == NormalSource::Height;
995 const size_t channels = fromHeight ? 1 : 2;
1000 if (!image)
return image;
1001 const auto definition =
image.value().manifest.assets.front().definition;
1003 if (entry.path != definition)
continue;
1007 const auto& bulk = cooked.value().bulk;
1008 auto read32 = [&](std::size_t
p) {
1009 return std::uint32_t(bulk[
p]) | (std::uint32_t(bulk[
p + 1]) << 8) | (std::uint32_t(bulk[
p + 2]) << 16) |
1010 (std::uint32_t(bulk[
p + 3]) << 24);
1013 const auto& metaBytes =
request.files.at(
path +
".meta");
1014 const std::string meta(metaBytes.begin(), metaBytes.end());
1015 if (mipmaps && importerScalar(meta,
"mipMapMode", 0) != 0)
1018 const auto npot = importerScalar(meta,
"nPOTScale", 1);
1019 if (npot < 0 || npot > 3 || npot != std::floor(npot))
throw Invalid{};
1020 const auto targetWidth = normalExtent(
width,
int(npot)), targetHeight = normalExtent(
height,
int(npot));
1021 std::vector<double> resized;
1022 int resizeAlgorithm = 0;
1023 if (targetWidth !=
width || targetHeight !=
height) {
1024 const std::regex algorithms(R
"((?:^|\n)[ \t]*resizeAlgorithm: *([^\r\n]+))");
1026 for (
auto it = std::sregex_iterator(meta.begin(), meta.end(), algorithms); it != std::sregex_iterator();
1030 const auto algorithm = numeric(
value.value());
1031 if (algorithm != 0 && algorithm != 1)
throw Invalid{};
1035 "platform-specific normal resize algorithms require target-specific image variants",
path, {},
1039 resizeAlgorithm =
selected.value_or(0);
1043 path, {},
"asset.import"));
1044 resized = normalResizeRgb(bulk,
width,
height, targetWidth, targetHeight, resizeAlgorithm);
1045 width = targetWidth;
1051 const uint64_t
bytes = uint64_t(
w) *
h * 4;
1058 if (!mipmaps || (
w == 1 &&
h == 1))
break;
1059 w = std::max(
w / 2, 1u);
1060 h = std::max(
h / 2, 1u);
1066 path, {},
"asset.import"));
1068 for (
size_t i = 0; i < size_t(
width) *
height; ++i) {
1069 if (!resized.empty()) {
1071 heights[i] = (resized[i * 3] + resized[i * 3 + 1] + resized[i * 3 + 2]) / 3;
1073 heights[i * 2] = resized[i * 3];
1074 heights[i * 2 + 1] = resized[i * 3 + 1];
1079 heights[i] = (double(bulk[28 + i * 4]) + bulk[29 + i * 4] + bulk[30 + i * 4]) / 765.0;
1081 heights[i * 2] = double(bulk[28 + i * 4]) / 255.0;
1082 heights[i * 2 + 1] = double(bulk[29 + i * 4]) / 255.0;
1085 std::vector<uint8_t> rgba;
1086 rgba.reserve(
size_t(total));
1090 auto sample = [&](int64_t
x, int64_t
y) {
1093 return heights[size_t(
y) *
w + size_t(
x)];
1095 const double factor = .04 * (double(
w) +
h) * (std::pow(10.0,
strength) - 1.0);
1096 for (int64_t
y = 0;
y <
h; ++
y) {
1097 for (int64_t
x = 0;
x <
w; ++
x) {
1099 const auto at = (size_t(
y) *
w + size_t(
x)) * 2;
1100 const auto green = flipGreen ? 1.0 - heights[
at + 1] : heights[
at + 1];
1101 rgba.insert(rgba.end(), {uint8_t(std::lround(heights[
at] * 255)),
1102 uint8_t(std::lround(green * 255)), 255, 255});
1116 dy *= flipGreen ? -factor : factor;
1118 rgba.insert(rgba.end(), {uint8_t(std::lround((dx / length * .5 + .5) * 255)),
1119 uint8_t(std::lround((dy / length * .5 + .5) * 255)), 255, 255});
1122 if (
level + 1 == levels)
break;
1123 const uint32_t nextW = std::max(
w / 2, 1u), nextH = std::max(
h / 2, 1u);
1124 std::vector<double>
next(
size_t(nextW) * nextH *
channels);
1125 for (uint32_t
y = 0;
y < nextH; ++
y) {
1126 for (uint32_t
x = 0;
x < nextW; ++
x) {
1127 const double sx = (
x + .5) *
w / nextW - .5,
sy = (
y + .5) *
h / nextH - .5;
1128 const auto ix = uint32_t(std::floor(
sx)), iy = uint32_t(std::floor(
sy));
1129 const double fx =
sx - ix, fy =
sy - iy;
1130 const auto x1 = std::min(ix + 1,
w - 1), y1 = std::min(iy + 1,
h - 1);
1133 (heights[(size_t(iy) *
w + ix) *
channels +
c] * (1 - fx) +
1134 heights[(size_t(iy) *
w + x1) *
channels +
c] * fx) *
1136 (heights[(
size_t(y1) *
w + ix) *
channels +
c] * (1 - fx) +
1137 heights[(size_t(y1) *
w + x1) *
channels +
c] * fx) *
1141 heights = std::move(next);
1145 auto parsed =
Value::fromJson(std::string(entry.bytes.begin(), entry.bytes.end()));
1148 const auto oldBlob =
object.at(
"blob").asString();
1149 const auto newBlob = definition.substr(0, definition.rfind(
'/') + 1) +
"normal.rgba8-mips";
1150 object[
"encoding"] =
Value(
"rgba8-mips");
1151 object[
"blob"] =
Value(newBlob);
1152 object[
"mipCount"] =
Value(int64_t(levels));
1155 object[
"usage"] =
Value(
"normal");
1156 auto encoded = parsed.value().toJson();
1158 auto result = std::move(image).takeValue();
1160 if (
output.path == definition)
1161 output.bytes.assign(encoded.value().begin(), encoded.value().end());
1162 else if (
output.path == oldBlob) {
1164 output.bytes = std::move(rgba);
1167 auto& asset =
result.manifest.assets.front();
1169 detail::sha256({
reinterpret_cast<const uint8_t*
>(encoded.value().data()), encoded.value().size()});
1170 asset.tags = {
"image",
"usage:normal"};
1171 std::erase_if(
result.entries, [](
const auto&
output) { return output.path ==
"reports/import.json"; });
1173 {
path, fromHeight ?
"TextureImporter.HeightNormal" :
"TextureImporter.AuthoredNormal",
1175 fromHeight ?
"height resampled and normals regenerated independently per mip"
1176 :
"linear source RG resampled independently per mip before green flip and quantization"}};
1178 {{
"fromHeight",
Value(fromHeight)},
1179 {
"npotScale",
Value(int64_t(npot))},
1180 {
"resizeAlgorithm",
Value(int64_t(resizeAlgorithm))},
1182 {
"sobel",
Value(sobel)},
1183 {
"flipGreen",
Value(flipGreen)},
1184 {
"mipCount",
Value(int64_t(levels))}});
1198 const auto shader = match(
text, R
"(m_Shader: *\{fileID: *4800000, guid: *([0-9a-fA-F]{32}), type: *3\})");
1200 (*
shader !=
"7befaa6f41d00a6478d5f4af21d66518" && *
shader !=
"a933075b367f9b24981408633f72ff34" &&
1201 *
shader !=
"6e6307b56f9201d40ad738f21cf03495" && *
shader !=
"d9a724745053dee46bf301b216cdd348"))
1204 {},
"asset.import"));
1205 auto unit = [](
double v) {
1206 if (v < 0 || v > 1)
throw Invalid{};
1209 const auto mode = scalar(
text,
"_RenderMode", 0), cull = scalar(
text,
"_RenderCull", 0),
1211 specular = scalar(
text,
"_RenderSpecular", 1);
1212 if ((mode != 0 && mode != 1) || cull < 0 || cull > 2 || cull != std::floor(cull) || (
clip != 0 &&
clip != 1) ||
1216 source.path, {},
"asset.import"));
1217 auto color = vector(
text,
"_MainColor", {1, 1, 1, 1});
1218 auto second = vector(
text,
"_MainColorTwo", {1, 1, 1, 1});
1219 const auto uv = vector(
text,
"_MainUVs", {1, 1, 0, 0});
1220 for (
unsigned c = 0;
c < 4; ++
c)
1224 const auto dual = scalar(
text,
"_MainColorMode", 0);
1225 if (dual != 0 && dual != 1)
throw Invalid{};
1226 const auto occlusion =
unit(scalar(
text,
"_MainOcclusionValue", 0)),
1227 smoothness =
unit(scalar(
text,
"_MainSmoothnessValue", 0));
1229 cutoff =
unit(scalar(
text,
"_AlphaClipValue", .5));
1232 if (
float(
maximum) -
float(
minimum) + .0001f == 0)
throw Invalid{};
1241 {
"schemaVersion", 15},
1242 {
"shadingModel",
"pbr"},
1243 {
"surfaceMode", mode == 1 ?
"transparent"
1244 :
clip == 1 ?
"masked"
1246 {
"doubleSided", cull == 0},
1247 {
"cullMode", cull == 0 ?
"none" : (cull == 1 ?
"back" :
"front")},
1252 {
"specularFactor",
unit(specular)},
1253 {
"alphaCutoff", cutoff},
1254 {
"albedoTextureStrength",
albedo}};
1255 const auto extrasLayer = scalar(
text,
"_LayerExtrasValue", 0);
1256 if (extrasLayer < 0 || extrasLayer > 8 || extrasLayer != std::floor(extrasLayer))
throw Invalid{};
1257 const auto colorsLayer = scalar(
text,
"_LayerColorsValue", 0);
1258 if (colorsLayer < 0 || colorsLayer > 8 || colorsLayer != std::floor(colorsLayer))
throw Invalid{};
1259 const auto motionLayer = scalar(
text,
"_LayerMotionValue", 0);
1260 if (motionLayer < 0 || motionLayer > 8 || motionLayer != std::floor(motionLayer))
throw Invalid{};
1261 const auto vertexLayer = scalar(
text,
"_LayerVertexValue", 0);
1262 if (vertexLayer < 0 || vertexLayer > 8 || vertexLayer != std::floor(vertexLayer))
throw Invalid{};
1263 auto binary = [&](
const char*
name,
double fallback) {
1265 if (
value != 0 &&
value != 1)
throw Invalid{};
1269 {
"variation",
unit(scalar(
text,
"_AlphaVariationValue", .5))},
1270 {
"detailFade", binary(
"_DetailFadeMode", 0) == 1},
1271 {
"glancing",
unit(scalar(
text,
"_FadeGlancingValue", 0))},
1272 {
"camera",
unit(scalar(
text,
"_FadeCameraValue", 1))},
1273 {
"constant",
unit(scalar(
text,
"_FadeConstantValue", 0))}};
1274 const auto emissiveMode = binary(
"_EmissiveMode", 0);
1275 if (emissiveMode == 1) {
1276 const auto emissiveColor = vector(
text,
"_EmissiveColor", {0, 0, 0, 0});
1277 for (
size_t c = 0;
c < 3; ++
c)
1278 if (emissiveColor[
c] < 0)
throw Invalid{};
1279 const auto intensityMode = binary(
"_EmissiveIntensityMode", 0);
1280 const auto authoredPower = scalar(
text,
"_EmissiveIntensityValue", 1);
1281 const auto fallbackPower = intensityMode == 0 ? authoredPower : .125 * std::pow(2., authoredPower);
1282 const auto intensity = scalar(
text,
"_emissive_intensity_value", fallbackPower);
1283 if (intensity < 0 || intensity > 1000000)
throw Invalid{};
1284 const auto emissionMinimum =
unit(scalar(
text,
"_EmissiveTexMinValue", 0));
1285 const auto emissionMaximum =
unit(scalar(
text,
"_EmissiveTexMaxValue", 1));
1286 if (
float(emissionMaximum) -
float(emissionMinimum) + .0001f == 0)
throw Invalid{};
1287 definition[
"emissive"] =
Value::Array{emissiveColor[0], emissiveColor[1], emissiveColor[2]};
1288 definition[
"emissiveStrength"] = intensity;
1289 definition[
"vegetationEmission"] =
Value::Object{{
"minimum", emissionMinimum},
1290 {
"maximum", emissionMaximum},
1291 {
"phase",
unit(scalar(
text,
"_EmissivePhaseValue", 1))},
1292 {
"global",
unit(scalar(
text,
"_GlobalEmissive", 1))}};
1294 const auto gradientOne = vector(
text,
"_GradientColorOne", {1, 1, 1, 1});
1295 const auto gradientTwo = vector(
text,
"_GradientColorTwo", {1, 1, 1, 1});
1296 for (
size_t c = 0;
c < 3; ++
c)
1297 if (gradientOne[
c] < 0 || gradientTwo[
c] < 0)
throw Invalid{};
1298 const auto gradientMinimum =
unit(scalar(
text,
"_GradientMinValue", 0));
1299 const auto gradientMaximum =
unit(scalar(
text,
"_GradientMaxValue", 1));
1300 if (
float(gradientMaximum) -
float(gradientMinimum) + .0001f == 0)
throw Invalid{};
1301 definition[
"vegetationGradient"] =
1303 {
"colorTwo",
Value::Array{gradientTwo[0], gradientTwo[1], gradientTwo[2]}},
1304 {
"minimum", gradientMinimum},
1305 {
"maximum", gradientMaximum}};
1306 definition[
"vegetationFields"] =
1308 {
"colorsUsePivotPosition", binary(
"_ColorsPositionMode", 0) == 1},
1309 {
"extrasLayer", int64_t(extrasLayer)},
1310 {
"extrasUsePivotPosition", binary(
"_ExtrasPositionMode", 0) == 1},
1311 {
"motionLayer", int64_t(motionLayer)},
1312 {
"vertexLayer", int64_t(vertexLayer)},
1313 {
"globalSize",
unit(scalar(
text,
"_GlobalSize", 1))},
1314 {
"sizeFadeStart", scalar(
text,
"_SizeFadeStartValue", 0)},
1315 {
"sizeFadeEnd", scalar(
text,
"_SizeFadeEndValue", 100)}};
1316 auto nonnegative = [&](
const char*
name,
double fallback) {
1318 if (value < 0 || value > 1000000)
throw Invalid{};
1321 definition[
"vegetationMotion"] =
1323 {
"rigidity",
unit(scalar(
text,
"_MotionPosition_10", .5))},
1324 {
"facing",
unit(scalar(
text,
"_MotionFacingValue", .5))},
1325 {
"bending", nonnegative(
"_MotionAmplitude_10", .2)},
1326 {
"bendingSpeed", nonnegative(
"_MotionSpeed_10", 2)},
1327 {
"bendingScale", nonnegative(
"_MotionScale_10", 1)},
1328 {
"bendingVariation", nonnegative(
"_MotionVariation_10", 0)},
1329 {
"branch", nonnegative(
"_MotionAmplitude_20", .2)},
1330 {
"rolling", nonnegative(
"_MotionAmplitude_22", .2)},
1331 {
"branchSpeed", nonnegative(
"_MotionSpeed_20", 6)},
1332 {
"branchScale", nonnegative(
"_MotionScale_20", 3)},
1333 {
"branchVariation", nonnegative(
"_MotionVariation_20", 0)},
1334 {
"flutter", nonnegative(
"_MotionAmplitude_32", .2)},
1335 {
"flutterSpeed", nonnegative(
"_MotionSpeed_32", 20)},
1336 {
"flutterScale", nonnegative(
"_MotionScale_32", 10)},
1337 {
"flutterVariation", nonnegative(
"_MotionVariation_32", 0)},
1338 {
"interaction", nonnegative(
"_InteractionAmplitude", 1)},
1339 {
"interactionMask",
unit(scalar(
text,
"_InteractionMaskValue", 1))},
1340 {
"perspectivePush", nonnegative(
"_PerspectivePushValue", 0)},
1341 {
"perspectiveNoise", nonnegative(
"_PerspectiveNoiseValue", 0)},
1342 {
"perspectiveAngle", nonnegative(
"_PerspectiveAngleValue", 1)}};
1343 const auto occlusionColor = vector(
text,
"_VertexOcclusionColor", {1, 1, 1, .5019608});
1344 for (
size_t c = 0;
c < 3; ++
c)
1345 if (occlusionColor[
c] < 0)
throw Invalid{};
1346 const auto colorsOcclusionMode = scalar(
text,
"_VertexOcclusionColorsMode", 0);
1347 if (colorsOcclusionMode != 0 && colorsOcclusionMode != 1)
throw Invalid{};
1348 const auto colorsOcclusionMinimum =
unit(scalar(
text,
"_VertexOcclusionMinValue", 0));
1349 const auto colorsOcclusionMaximum =
unit(scalar(
text,
"_VertexOcclusionMaxValue", 1));
1350 if (
float(colorsOcclusionMaximum) -
float(colorsOcclusionMinimum) + .0001f == 0)
throw Invalid{};
1351 const auto colorsIntensity = scalar(
text,
"_ColorsIntensityValue", 1);
1352 if (colorsIntensity < 0 || colorsIntensity > 2)
throw Invalid{};
1353 const auto backfaceNormalMode = scalar(
text,
"_RenderNormals", 0);
1354 if (backfaceNormalMode < 0 || backfaceNormalMode > 2 || backfaceNormalMode != std::floor(backfaceNormalMode))
1357 {
"sourceFamily",
"tve-12"},
1358 {
"overlay",
unit(scalar(
text,
"_GlobalOverlay", 1))},
1359 {
"wetness",
unit(scalar(
text,
"_GlobalWetness", 1))},
1360 {
"overlayVariation",
unit(scalar(
text,
"_OverlayVariationValue", .5))},
1361 {
"overlayProjection",
unit(scalar(
text,
"_OverlayProjectionValue", .5))},
1362 {
"vertexOcclusionAlpha",
unit(occlusionColor[3])},
1363 {
"vertexOcclusionColor",
Value::Array{occlusionColor[0], occlusionColor[1], occlusionColor[2]}},
1364 {
"invertVertexOcclusion", scalar(
text,
"_VertexOcclusionOverlayMode", 0) == 1},
1365 {
"colors",
unit(scalar(
text,
"_GlobalColors", 1))},
1366 {
"colorsIntensity", colorsIntensity},
1367 {
"colorsMask",
unit(scalar(
text,
"_ColorsMaskValue", 1))},
1368 {
"colorsVariation",
unit(scalar(
text,
"_ColorsVariationValue", .5))},
1369 {
"vertexOcclusionMinimum", colorsOcclusionMinimum},
1370 {
"vertexOcclusionMaximum", colorsOcclusionMaximum},
1371 {
"invertVertexOcclusionColors", colorsOcclusionMode == 1},
1372 {
"backfaceNormalMode", int64_t(backfaceNormalMode)}};
1373 const auto detailMode = scalar(
text,
"_DetailMode", 0);
1374 if (detailMode != 0 && detailMode != 1)
throw Invalid{};
1375 if (detailMode == 1) {
1376 const auto detailUv = vector(
text,
"_SecondUVs", {1, 1, 0, 0});
1377 const auto detailColor = vector(
text,
"_SecondColor", {1, 1, 1, 1});
1378 const auto detailColorTwo = vector(
text,
"_SecondColorTwo", {1, 1, 1, 1});
1379 const auto uvMode = scalar(
text,
"_SecondUVsMode", 0);
1380 if (uvMode < 0 || uvMode > 2 || uvMode != std::floor(uvMode))
throw Invalid{};
1381 auto signedNormal = scalar(
text,
"_SecondNormalValue", 1);
1382 if (signedNormal < -8 || signedNormal > 8 || detailUv[0] == 0 || detailUv[1] == 0)
throw Invalid{};
1384 {
"value",
unit(scalar(
text,
"_DetailValue", 1))},
1385 {
"uvMode", int64_t(uvMode)},
1386 {
"inverseUvScale", binary(
"_SecondUVsScaleMode", 0) == 1},
1388 {
"uvOffset",
Value::Array{detailUv[2], 1.0 - detailUv[1] - detailUv[3]}},
1389 {
"color",
Value::Array{detailColor[0], detailColor[1], detailColor[2], detailColor[3]}},
1390 {
"colorTwo",
Value::Array{detailColorTwo[0], detailColorTwo[1], detailColorTwo[2], detailColorTwo[3]}},
1391 {
"colorMode", int64_t(binary(
"_SecondColorMode", 0))},
1392 {
"albedoValue",
unit(scalar(
text,
"_SecondAlbedoValue", 1))},
1393 {
"normalValue", signedNormal},
1394 {
"normalBlendValue",
unit(scalar(
text,
"_DetailNormalValue", 1))},
1395 {
"metallicValue",
unit(scalar(
text,
"_SecondMetallicValue", 0))},
1396 {
"occlusionValue",
unit(scalar(
text,
"_SecondOcclusionValue", 1))},
1397 {
"smoothnessValue",
unit(scalar(
text,
"_SecondSmoothnessValue", 1))},
1398 {
"blendMode", int64_t(binary(
"_DetailBlendMode", 0))},
1399 {
"alphaMode", int64_t(binary(
"_DetailAlphaMode", 1))},
1400 {
"maskMode", int64_t(binary(
"_DetailMaskMode", 0))},
1401 {
"meshMode", int64_t(binary(
"_DetailMeshMode", 0))},
1402 {
"blendMinimum",
unit(scalar(
text,
"_DetailBlendMinValue", 0))},
1403 {
"blendMaximum",
unit(scalar(
text,
"_DetailBlendMaxValue", 1))},
1404 {
"maskMinimum",
unit(scalar(
text,
"_DetailMaskMinValue", 0))},
1405 {
"maskMaximum",
unit(scalar(
text,
"_DetailMaskMaxValue", 1))},
1406 {
"meshMinimum",
unit(scalar(
text,
"_DetailMeshMinValue", 0))},
1407 {
"meshMaximum",
unit(scalar(
text,
"_DetailMeshMaxValue", 1))}};
1409 auto bindWithUv = [&](
const std::string& role,
const AssetRef&
image,
const std::array<double, 4>& transform) {
1410 definition[role] =
image.format();
1411 definition[role +
"Transform"] =
1413 {
"offset",
Value::Array{transform[2], 1.0 - transform[1] - transform[3]}}};
1414 out.manifest.dependencies.push_back(
1417 auto bind = [&](
const std::string& role,
const AssetRef&
image) { bindWithUv(role,
image,
uv); };
1418 if (
auto guid =
texture(
text,
"_MainAlbedoTex")) {
1423 bind(
"baseColorTexture",
image.value());
1426 definition[
"baseColorTextureSampler"] = std::move(
sampler).takeValue();
1428 if (emissiveMode == 1) {
1430 if (!guid)
throw Invalid{};
1435 const auto emissiveUv = vector(
text,
"_EmissiveUVs", {1, 1, 0, 0});
1436 if (emissiveUv[0] == 0 || emissiveUv[1] == 0)
throw Invalid{};
1437 bindWithUv(
"emissiveTexture",
image.value(), emissiveUv);
1440 definition[
"emissiveTextureSampler"] = std::move(
sampler).takeValue();
1442 if (
auto guid =
texture(
text,
"_MainNormalTex")) {
1446 const std::string meta(
bytes.begin(),
bytes.end());
1447 const auto normalType = importerScalar(meta,
"textureType", 0);
1448 const auto fromHeight = importerScalar(meta,
"convertToNormalMap", 0);
1449 const auto flipGreen = importerScalar(meta,
"flipGreenChannel", 0);
1450 if (normalType == 1 && (fromHeight == 0 || fromHeight == 1) && (flipGreen == 0 || flipGreen == 1)) {
1453 definition[
"normalTextureSampler"] = std::move(
sampler).takeValue();
1454 const auto strength = scalar(
text,
"_MainNormalValue", 1);
1455 if (strength < -8 || strength > 8)
throw Invalid{};
1459 const auto scale = importerScalar(meta,
"heightScale", .25);
1460 const auto filter = importerScalar(meta,
"normalMapFilter", 0);
1461 if (scale < 0 || scale > 1 || (
filter != 0 &&
filter != 1))
throw Invalid{};
1463 importerScalar(meta,
"enableMipMap", 1) == 1, flipGreen == 1,
1464 fromHeight == 1 ? NormalSource::Height : NormalSource::Authored);
1465 if (!generated)
return generated;
1467 for (
auto&
a : generated.value().manifest.assets)
out.manifest.assets.push_back(std::move(
a));
1468 for (
auto& e : generated.value().entries)
1469 if (e.path.starts_with(
"assets/"))
out.entries.push_back(std::move(e));
1470 for (
auto& finding : generated.value().findings)
out.findings.push_back(std::move(finding));
1472 bind(
"normalTexture",
image.value());
1473 definition[
"normalEncoding"] =
"tve-rg";
1474 definition[
"normalScale"] =
strength;
1475 out.findings.push_back(
1477 "authored or height-generated RG linked as linear data; signed strength and fixed-Z "
1478 "reconstruction run after filtering"});
1480 out.findings.push_back(
1482 "normal source retained; invalid settings or non-normal importer encoding requires conversion"});
1485 if (*
shader ==
"a933075b367f9b24981408633f72ff34" || *
shader ==
"d9a724745053dee46bf301b216cdd348") {
1486 auto tint = vector(
text,
"_SubsurfaceColor", {1, 1, 1, 1});
1487 for (
size_t c = 0;
c < 3; ++
c) {
1488 if (
tint[
c] < 0)
throw Invalid{};
1490 const auto power = scalar(
text,
"_SubsurfaceScatteringValue", 2);
1491 const auto angle = scalar(
text,
"_SubsurfaceAngleValue", 8);
1492 if (power < 0 || power > 16 || angle < 1 || angle > 16)
throw Invalid{};
1495 {
"intensity",
unit(scalar(
text,
"_SubsurfaceValue", 1))},
1496 {
"strength",
power},
1497 {
"scattering",
angle},
1498 {
"normalDistortion",
unit(scalar(
text,
"_SubsurfaceNormalValue", 0))},
1499 {
"direct",
unit(scalar(
text,
"_SubsurfaceDirectValue", 1))},
1500 {
"ambient",
unit(scalar(
text,
"_SubsurfaceAmbientValue", .2))},
1501 {
"shadow",
unit(scalar(
text,
"_SubsurfaceShadowValue", 1))},
1503 *
shader ==
"a933075b367f9b24981408633f72ff34" ?
unit(scalar(
text,
"_SubsurfaceMaskValue", 1)) : 0},
1507 "visible subsurface controls mapped to per-light translucency; field wetness is "
1508 "composed by the vegetation runtime"});
1510 if (*
shader ==
"a933075b367f9b24981408633f72ff34" || *
shader ==
"7befaa6f41d00a6478d5f4af21d66518") {
1511 auto highlight = vector(
text,
"_MotionHighlightColor", {0, 0, 0, 0});
1512 for (
size_t c = 0;
c < 3; ++
c) {
1516 out.findings.push_back(
1518 "Plant motion highlight RGB retained; runtime requires evaluated per-vertex highlight stream"});
1520 if (detailMode == 1) {
1521 for (
const auto& [property, role] :
1522 std::array<std::pair<const char*, const char*>, 3>{{{
"_SecondAlbedoTex",
"detailAlbedoTexture"},
1523 {
"_SecondNormalTex",
"detailNormalTexture"},
1524 {
"_SecondMaskTex",
"detailMaskTexture"}}}) {
1526 if (!guid)
continue;
1531 definition[role] =
image.value().format();
1534 definition[std::string(role) +
"Sampler"] = std::move(
sampler).takeValue();
1535 out.manifest.dependencies.push_back({ref.value(),
1544 auto orm = ormImage(
request,
text,
id, occlusion, smoothness);
1545 if (!orm)
return orm;
1546 const auto mask = orm.value().manifest.assets.front().asset;
1547 bind(
"metallicRoughnessTexture",
mask);
1548 bind(
"occlusionTexture",
mask);
1554 definition[
"metallicRoughnessTextureSampler"] =
sampler.value();
1555 definition[
"occlusionTextureSampler"] = std::move(
sampler).takeValue();
1557 for (
auto&
a : orm.value().manifest.assets)
out.manifest.assets.push_back(std::move(
a));
1558 for (
auto& e : orm.value().entries)
1559 if (e.path.starts_with(
"assets/"))
out.entries.push_back(std::move(e));
1564 const auto path =
"assets/" +
id.format() +
"/asset.json";
1565 auto json =
Value(std::move(definition)).
toJson();
1567 std::vector<std::uint8_t> encoded(json.value().begin(), json.value().end());
1568 out.manifest.assets.push_back({ref.value(),
1573 {
"material",
"source:unity",
"vegetation"}});
1574 out.entries.push_back({
path, std::move(encoded)});
1575 out.manifest.entrypoints.emplace(
"default", ref.value());
1576 out.sourceMappings.push_back({
"2100000", ref.value()});
1578 "TVE 12.6.0 primary RGB, albedo, UV transform, AO/smoothness and RGB mask converted"});
1580 "specular, facing normal, culling and alpha-to-coverage state translated; "
1581 "Direct/Ambient/Shadow and generated noise/rim declarations are inactive in the "
1582 "inspected 12.6 shader calculations"});
1584 }
catch (
const Invalid&) {
std::map< std::string, std::vector< Key >, std::less<> > channels
AuthorityStoreHandleRef reference
std::unordered_map< std::string, QuestRuntime > entries
Safe source-image conversion to runtime EVIMG payloads.
graphics::Texture * albedo
std::vector< std::string > fields
const GltfImportRequest & request
vk::UniqueSampler sampler
wgpu::PopErrorScopeStatus status
std::array< double, 10 > q
std::function< Numbers(b3JointId)> read
const ColourScope * parent
std::array< float, 4 > rotation
std::array< float, 3 > position
std::array< float, 3 > scale
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
OceanWakeSettings settings
std::unordered_map< std::string, ShaderEntry > shaders
std::set< std::string > values
Direct Unity text-serialization adapter for TerrainData and Prefab assets.
std::vector< ImportFinding > findings
const AssetImportLimits & limits
Stable asset identity backed by PersistentId.
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.
The canonical owning dynamic value used by data-facing protocols.
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
std::map< std::string, Value > Object
std::vector< Value > Array
static Value array(Array value)
Compatibility factory for an array value.
static Value object(Object value)
Compatibility factory for an object value.
Id128 child(std::string_view role) const noexcept
Derives a deterministic child UUID for a hierarchical identity.
size_t size() const
Returns the size of .
int main(int argc, char **argv)
Result< std::vector< std::uint8_t > > encodeSourcePng(std::uint32_t width, std::uint32_t height, std::span< const std::uint8_t > pixels, std::uint64_t maximumBytes)
Encode top-down RGBA8 source pixels without transfer conversion.
std::string sha256(std::span< const std::uint8_t > bytes)
Sha 256.
std::string extension(std::string_view name)
Extension.
EVENGINE_API_PLATFORM Result< void > finalizeImportReport(PreparedAssetImport &prepared, const ImportPackageIdentity &package, std::string_view sourceEngine, std::string_view sourceVersion, Value::Object options={})
Append the deterministic mandatory import report and bind it from provenance.
Result< asset::EvaManifest > baseManifest(const ImportPackageIdentity &package, std::string_view importer)
Base manifest.
Result< AssetRef > assetRef(PersistentId id)
Asset ref.
std::string foldAscii(std::string value)
Fold ascii.
Result< std::string > metaScalar(std::span< const std::uint8_t > bytes, std::string_view key, std::string_view path)
Read an unindented scalar from .meta; rejects duplicate keys and binary metadata.
Result< PreparedAssetImport > prepareUnityPrefab(const UnityProjectImportRequest &request, const std::string &path)
Prepare one prefab without copying or re-indexing the source collection.
Result< PreparedAssetImport > prepareUnityVegetationScene(const UnityProjectImportRequest &request, const UnitySourceAsset &source)
Convert a complete TVE manager component set from one Unity scene.
Result< PreparedAssetImport > prepareUnityVegetationMaterial(const UnityProjectImportRequest &request, const UnitySourceAsset &source)
Convert admitted TVE primary material data; remaining source features are reported explicitly.
EVENGINE_API_PLATFORM Result< PreparedAssetImport > prepareImageImport(const ImageImportRequest &request)
Decode image metadata and prepare one canonical eve.image source asset.
Result< CookedCanonicalImage > cookCanonicalImageRgba8(std::span< const std::uint8_t > definition, std::span< const std::uint8_t > encodedSource, std::uint64_t maximumDecodedBytes)
Decode image/2 base images or image/3 explicit linear RGBA8 mip chains into bounded EVIMG.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Value vector(glm::dvec3 v)
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
SocketDirection rotate(SocketDirection direction, int degrees)
double dot(ForceVector a, ForceVector b)
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...
double sample(const Heightmap &map, double u, double v)
Sample.
StrongUuid< detail::PersistentIdTag > PersistentId
Stable instance identity for persistence, networking and process boundaries.
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
std::uint64_t maximumDecodedBytes
std::uint64_t maximumSourceBytes
ImportPackageIdentity package
Owning, validated source archive candidate not yet published to disk/database.
asset::EvaManifest manifest
In-memory Unity project slice; keys are normalized project-relative paths.
Immutable-by-convention owning source index entry; no borrowed source addresses.