15#include <assimp/GltfMaterial.h>
16#include <assimp/material.h>
17#include <assimp/matrix4x4.h>
18#include <assimp/mesh.h>
19#include <assimp/scene.h>
23#include <glm/mat4x4.hpp>
31#include <unordered_map>
44glm::mat4 aiToGlm(
const aiMatrix4x4&
m) {
45 return glm::mat4(
m.a1,
m.b1,
m.c1,
m.d1,
m.a2,
m.b2,
m.c2,
m.d2,
m.a3,
m.b3,
m.c3,
m.d3,
m.a4,
m.b4,
m.c4,
m.d4);
48Texture *textureFromImageData(IResourceFactory *gfx, image::ImageData *img) {
49 if (!img)
return nullptr;
51 return gfx->newTexture(img);
57std::string importedTextureContentKey(
const image::ImageData &image) {
60 constexpr uint64_t prime = 1099511628211ull;
61 uint64_t
a = 14695981039346656037ull;
62 uint64_t
b = 7809847782465536322ull;
63 const auto mix = [&](uint64_t &
hash, uint8_t byte) {
67 const auto feed32 = [&](uint64_t &
hash, uint32_t
value) {
68 for (
unsigned shift = 0; shift < 32; shift += 8) mix(
hash, uint8_t(
value >> shift));
70 feed32(
a, uint32_t(
image.getWidth()));
71 feed32(
a, uint32_t(
image.getHeight()));
72 feed32(
b, uint32_t(
image.getHeight()));
73 feed32(
b, uint32_t(
image.getWidth()));
74 const auto *
bytes =
static_cast<const uint8_t *
>(
image.getData());
75 const size_t count = size_t(
image.getWidth()) * size_t(
image.getHeight()) * 4;
76 for (
size_t i = 0; i <
count; ++i) {
80 return "model3d-rgba8:" + std::to_string(
image.getWidth()) +
"x" + std::to_string(
image.getHeight()) +
":" +
81 std::to_string(
a) +
":" + std::to_string(
b);
84Texture *loadEmbeddedTexture(IResourceFactory *gfx, ModelData *
model,
int idx) {
85 image::ImageData *img =
model->getEmbeddedTextureImageData(
idx);
89 auto shared = gfx->newSharedTexture(img, importedTextureContentKey(*img));
90 if (!shared)
throw eve::Exception(
"%s", shared.status().describe().c_str());
91 tex = &shared.value().get();
99std::string basenameOf(
const std::string &
path) {
100 const size_t slash =
path.find_last_of(
"/\\");
101 return slash == std::string::npos ?
path :
path.substr(slash + 1);
104Texture *loadExternalTexture(IResourceFactory *gfx,
const std::string &
path) {
105 auto *fs = filesystem::Filesystem::create();
106 std::unique_ptr<filesystem::FileData> fd;
108 fd.reset(fs->read(
path));
111 if (!fd || fd->getSize() == 0) {
112 const std::string base = basenameOf(
path);
114 fd.reset(fs->read(base));
117 if (!fd || fd->getSize() == 0) {
119 fd.reset(fs->read(
"Textures/" + base));
124 if (!fd || fd->getSize() == 0)
return nullptr;
126 image::ImageData *img = image::Image::create()->newImageData(fd.get());
127 Texture *tex = textureFromImageData(gfx, img);
135Texture* loadModelTexture(IResourceFactory* gfx, ModelData*
model,
const std::string&
path) {
139 if (
uri.rfind(
"file://", 0) == 0)
uri.erase(0, 7);
141 if (!
uri.empty() &&
uri.find(
"://") == std::string::npos) {
145 const auto resolved = (std::filesystem::path(
uri).parent_path() /
relative).lexically_normal();
148 return loadExternalTexture(gfx,
path);
151Texture* loadTextureSlot(IResourceFactory* gfx, ModelData*
model,
int matIndex,
const std::string&
type) {
152 if (
model->getMaterialTextureSlotCount(matIndex,
type) <= 0)
return nullptr;
153 const int embedded =
model->getMaterialTextureEmbeddedIndex(matIndex,
type, 0);
154 if (embedded >= 0)
return loadEmbeddedTexture(gfx,
model, embedded);
155 const std::string
path =
model->getMaterialTexturePath(matIndex,
type, 0);
156 if (
path.empty())
return nullptr;
157 return loadModelTexture(gfx,
model,
path);
174void extendedLook(IResourceFactory* gfx, ModelData*
model,
int index, TextureLook& look,
175 const ModelRenderOptions&
options) {
180 if (
material->Get(AI_MATKEY_GLTF_ALPHAMODE, alpha) != AI_SUCCESS)
return;
181 look.extendedPbr =
true;
182 look.ta =
model->getMaterialBaseColorA(
index);
184 auto scalar = [&](
const char*
key,
unsigned type,
unsigned slot,
float fallback) {
185 float value = fallback;
190 auto unit = [&](
const char*
key,
unsigned type,
unsigned slot,
float fallback) {
192 if (value < 0 || value > 1)
193 std::fprintf(stderr,
"[model3d] warning %s=%g clamped to [0,1]\n",
key,
double(
value));
194 return std::clamp(
value, 0.f, 1.f);
196 p.specularFactor =
unit(AI_MATKEY_SPECULAR_FACTOR, 1);
197 aiColor3D
color(1, 1, 1);
203 p.emissiveStrength = scalar(AI_MATKEY_EMISSIVE_INTENSITY, 1);
204 p.ior = scalar(AI_MATKEY_REFRACTI, 1.5f);
205 p.clearcoatFactor =
unit(AI_MATKEY_CLEARCOAT_FACTOR, 0);
206 p.clearcoatRoughness =
unit(AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR, 0);
207 p.anisotropyStrength =
unit(AI_MATKEY_ANISOTROPY_FACTOR, 0);
208 p.normalScale = scalar(AI_MATKEY_GLTF_TEXTURE_SCALE(aiTextureType_NORMALS, 0), 1);
209 p.clearcoatNormalScale = scalar(AI_MATKEY_GLTF_TEXTURE_SCALE(aiTextureType_CLEARCOAT, 2), 1);
210 p.occlusionStrength =
unit(
"$tex.file.strength", aiTextureType_LIGHTMAP, 0, 1);
212 material->Get(AI_MATKEY_SHADING_MODEL, shading);
213 p.unlit = shading == aiShadingMode_Unlit;
214 const std::pair<aiTextureType, unsigned> roles[] = {
215 {aiTextureType_BASE_COLOR, 0}, {aiTextureType_UNKNOWN, 0}, {aiTextureType_NORMALS, 0},
216 {aiTextureType_LIGHTMAP, 0}, {aiTextureType_EMISSIVE, 0}, {aiTextureType_SPECULAR, 0},
217 {aiTextureType_SPECULAR, 1}, {aiTextureType_NONE, 0}, {aiTextureType_CLEARCOAT, 0},
218 {aiTextureType_CLEARCOAT, 1}, {aiTextureType_CLEARCOAT, 2}};
219 for (
size_t i = 0; i < 11; i++) {
220 if ((i == 0 && !
options.importAlbedo) || ((i == 2 || i == 10) && !
options.importNormalMaps))
continue;
222 if (
type == aiTextureType_NONE)
continue;
225 aiTextureMapMode wrap[2] = {aiTextureMapMode_Wrap, aiTextureMapMode_Wrap};
226 if (
material->GetTexture(
type,
slot, &
path,
nullptr, &
uv,
nullptr,
nullptr, wrap) != AI_SUCCESS)
continue;
228 if (i == 0 && look.albedo)
230 else if (i == 2 && look.normal)
232 else if (
path.length > 1 &&
path.C_Str()[0] ==
'*')
233 binding.texture = loadEmbeddedTexture(gfx,
model, std::stoi(
path.C_Str() + 1));
239 std::fprintf(stderr,
"[model3d] warning: missing material texture %s (model %s); using material factors\n",
244 auto wrapEnum = [](aiTextureMapMode mode) {
245 return mode == aiTextureMapMode_Clamp ? 33071u : mode == aiTextureMapMode_Mirror ? 33648u : 10497u;
247 binding.wrapS = wrapEnum(wrap[0]);
248 binding.wrapT = wrapEnum(wrap[1]);
255 aiUVTransform transform;
256 if (
material->Get(AI_MATKEY_UVTRANSFORM(
type,
slot), transform) == AI_SUCCESS) {
258 if (
model->hasFlippedUvs()) {
259 transform.mRotation = -transform.mRotation;
260 transform.mTranslation.y = -transform.mTranslation.y;
262 const float r = -transform.mRotation,
c = std::cos(
r), sn = std::sin(
r);
263 const float sx = transform.mScaling.x,
sy = transform.mScaling.y;
266 binding.offset = {transform.mTranslation.x - .5f *
sx * (-
c + sn + 1),
267 1 -
sy - transform.mTranslation.y + .5f *
sy * (sn +
c - 1)};
270 look.albedo =
p.textures[0].texture;
271 look.normal =
p.textures[2].texture;
274TextureLook materialLook(IResourceFactory *gfx, ModelData *
model,
int matIndex,
const ModelRenderOptions &
options,
275 std::unordered_map<int, TextureLook> &cache) {
276 auto it = cache.find(matIndex);
277 if (it != cache.end())
return it->second;
281 look.tr =
model->getMaterialBaseColorR(matIndex);
282 look.tg =
model->getMaterialBaseColorG(matIndex);
283 look.tb =
model->getMaterialBaseColorB(matIndex);
284 look.ta =
model->getMaterialBaseColorA(matIndex);
285 look.metallic =
model->getMaterialMetallicFactor(matIndex);
286 look.roughness =
model->getMaterialRoughnessFactor(matIndex);
287 look.ta *=
model->getMaterialOpacity(matIndex);
288 look.alphaMode =
model->getMaterialAlphaMode(matIndex);
289 look.alphaCutoff =
model->getMaterialAlphaCutoff(matIndex);
290 look.doubleSided =
model->getMaterialTwoSided(matIndex);
292 look.albedo = loadTextureSlot(gfx,
model, matIndex,
"base_color");
293 if (!look.albedo) look.albedo = loadTextureSlot(gfx,
model, matIndex,
"diffuse");
296 look.normal = loadTextureSlot(gfx,
model, matIndex,
"normals");
298 look.height = loadTextureSlot(gfx,
model, matIndex,
"height");
301 cache.emplace(matIndex, look);
305Renderable3D *makeRenderable(IResourceFactory *gfx, ModelData *
model,
int meshIndex,
const aiMatrix4x4 &world,
306 const ModelRenderOptions &
options, std::unordered_map<int, TextureLook> &cache) {
308 if (!scene || meshIndex < 0 ||
static_cast<unsigned>(meshIndex) >=
scene->mNumMeshes)
310 const aiMesh *ai =
scene->mMeshes[meshIndex];
311 if (!ai || ai->mNumVertices == 0 || ai->mNumFaces == 0)
return nullptr;
318 const bool bakeWorld =
options.bakeWorldTransform && !ai->HasBones();
319 Mesh*
mesh = bakeWorld ? gfx->newMeshFromAssimp(*ai, aiToGlm(world)) : gfx->newMeshFromAssimp(*ai);
320 if (!
mesh)
return nullptr;
322 const int matIndex =
model->getMaterialIndex(meshIndex);
323 const TextureLook look = materialLook(gfx,
model, matIndex,
options, cache);
325 Renderable3D *ent = Renderable3D::create();
326 ent->meshRenderer()->visible =
true;
331 if (look.albedo) ent->setTexture(look.albedo);
332 if (look.normal) ent->setNormalTexture(look.normal);
333 if (look.height) ent->setHeightTexture(look.height);
334 ent->setTint(look.tr, look.tg, look.tb, look.ta);
335 ent->setMetallic(look.metallic);
336 ent->setRoughness(look.roughness);
340 material->setAlbedoTexture(look.albedo);
341 material->setNormalTexture(look.normal);
342 material->setHeightTexture(look.height);
343 material->setTint(look.tr, look.tg, look.tb, look.ta);
344 material->setMetallic(look.metallic);
345 material->setRoughness(look.roughness);
346 material->setDoubleSided(look.doubleSided);
347 material->setAlphaCutoff(look.alphaCutoff);
348 if (look.alphaMode ==
"MASK")
350 else if (look.alphaMode ==
"BLEND")
351 material->setSurfaceMode(
"transparent");
354 if (look.extendedPbr) {
355 auto configured =
material->setPbrSurface(look.pbr);
356 if (!configured)
throw eve::Exception(
"%s", configured.error()->message().c_str());
357 for (
unsigned channel = 0; channel < AI_MAX_NUMBER_OF_TEXTURECOORDS; channel++) {
358 if (!ai->mTextureCoords[channel])
continue;
359 std::vector<float>
values;
360 values.reserve(
size_t(ai->mNumVertices) * 2);
361 for (
unsigned v = 0;
v < ai->mNumVertices;
v++) {
362 values.push_back(ai->mTextureCoords[channel][
v].x);
363 values.push_back(
model->hasFlippedUvs() ? ai->mTextureCoords[channel][
v].y
364 : 1 - ai->mTextureCoords[channel][
v].
y);
366 auto attached =
mesh->setTexcoordSet(channel,
values);
367 if (!attached)
throw eve::Exception(
"%s", attached.error()->message().c_str());
374void walkNodes(
const aiNode *
node,
const aiMatrix4x4 &
parent, IResourceFactory *gfx, ModelData *
model,
375 const ModelRenderOptions &
options, std::vector<Renderable3D *> &
out,
376 std::unordered_map<int, TextureLook> &cache) {
378 const aiMatrix4x4 world =
parent *
node->mTransformation;
379 for (
unsigned i = 0; i <
node->mNumMeshes; ++i) {
381 makeRenderable(gfx,
model,
static_cast<int>(
node->mMeshes[i]), world,
options, cache);
382 if (ent)
out.push_back(ent);
384 for (
unsigned c = 0;
c <
node->mNumChildren; ++
c)
388bool findMeshTransform(
const aiNode *
node,
const aiMatrix4x4 &
parent,
unsigned meshIndex,
390 if (!
node)
return false;
391 const aiMatrix4x4 world =
parent *
node->mTransformation;
392 for (
unsigned i = 0; i <
node->mNumMeshes; ++i) {
393 if (
node->mMeshes[i] == meshIndex) {
398 for (
unsigned c = 0;
c <
node->mNumChildren; ++
c)
399 if (findMeshTransform(
node->mChildren[
c], world, meshIndex,
out))
return true;
407 if (!
model)
return nullptr;
409 if (!
scene || !
scene->mRootNode)
return nullptr;
412 if (!findMeshTransform(
scene->mRootNode, aiMatrix4x4(),
static_cast<unsigned>(meshIndex),
414 world = aiMatrix4x4();
416 std::unordered_map<int, TextureLook> cache;
417 return makeRenderable(&gfx,
model, meshIndex, world,
options, cache);
422 std::vector<Renderable3D *>
out;
426 std::unordered_map<int, TextureLook> cache;
433 Mesh *
mesh = renderable.getMesh();
434 auto invalid = [](
const char *
message) {
438 if (!
scene || !
scene->mRootNode || meshIndex < 0 ||
unsigned(meshIndex) >=
scene->mNumMeshes || !
mesh)
439 return invalid(
"model, mesh index, and matching renderable are required");
442 return invalid(
"source and render mesh vertex counts must match");
443 if (
source->HasBones() ||
mesh->hasGpuSkinning())
444 return invalid(
"foliage deformation requires an unskinned static mesh");
447 if (!findMeshTransform(
scene->mRootNode, aiMatrix4x4(),
unsigned(meshIndex), world)) world = aiMatrix4x4();
450 float minY = std::numeric_limits<float>::infinity();
451 float maxY = -std::numeric_limits<float>::infinity();
452 for (
unsigned i = 0; i <
source->mNumVertices; ++i) {
453 const aiVector3D
p = world *
source->mVertices[i];
454 if (!std::isfinite(
p.x) || !std::isfinite(
p.y) || !std::isfinite(
p.z))
455 return invalid(
"foliage source positions must be finite");
457 minY = std::min(minY,
p.y);
458 maxY = std::max(maxY,
p.y);
460 const float height = maxY - minY;
461 if (!std::isfinite(
height) ||
height <= 1e-6f)
return invalid(
"foliage mesh must have positive height");
466 std::vector<float> factors;
467 factors.reserve(
size_t(
source->mNumVertices) * 9u);
468 for (
unsigned i = 0; i <
source->mNumVertices; ++i) {
470 const float normalizedHeight = std::clamp((
p.y - minY) /
height, 0.f, 1.f);
471 const float radial = std::clamp(std::hypot(
p.x,
p.z) /
radius, 0.f, 1.f);
472 const uint32_t
hash = (i + 1u) * 747796405u + 2891336453u;
473 const float variation = float((
hash >> 8u) & 0xffffu) / 65535.f;
474 factors.insert(factors.end(), {0.f, minY, 0.f, normalizedHeight * normalizedHeight, normalizedHeight * radial,
475 normalizedHeight, variation, height, radius});
477 return mesh->adoptVegetationDeformationFactors(std::move(factors));
graphics::Texture * albedo
std::vector< float > positions
const ColourScope * parent
eve::action::ActionVfxBinding binding
std::array< uint32_t, 16 > material
std::weak_ptr< PrimitiveScene > scene
std::set< std::string > values
const SquirrelValueOptions & options
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result failure(Status status)
Construct a failed result from a structured status.
Texture / mesh / shader / canvas creation and release.
Packages shading method + surface parameters into one attachable asset.
GPU mesh handle (+ optional CPU morph targets).
EVENGINE_API_BACKENDS public API.
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
CPU-side decoded 3D model (Assimp scene owned via medialoader::ModelScene). Does not upload to GPU — ...
Result< void > prepareFoliageDeformation(ModelData &model, int meshIndex, Renderable3D &renderable)
Renderable3D * buildRenderable(IResourceFactory &gfx, ModelData *model, int meshIndex, const ModelRenderOptions &options)
std::vector< Renderable3D * > buildRenderables(IResourceFactory &gfx, ModelData *model, const ModelRenderOptions &options)
ModelRenderOptions public API.