| 1 | /* |
| 2 | * Copyright (C) 2015 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #define GL_NEAREST 0x2600 |
| 18 | #define GL_LINEAR 0x2601 |
| 19 | #define GL_NEAREST_MIPMAP_NEAREST 0x2700 |
| 20 | #define GL_LINEAR_MIPMAP_NEAREST 0x2701 |
| 21 | #define GL_NEAREST_MIPMAP_LINEAR 0x2702 |
| 22 | #define GL_LINEAR_MIPMAP_LINEAR 0x2703 |
| 23 | #define GL_TEXTURE_MAG_FILTER 0x2800 |
| 24 | #define GL_TEXTURE_MIN_FILTER 0x2801 |
| 25 | #define GL_TEXTURE_WRAP_S 0x2802 |
| 26 | #define GL_TEXTURE_WRAP_T 0x2803 |
| 27 | |
| 28 | #include <filamentapp/MeshAssimp.h> |
| 29 | |
| 30 | #include <stdlib.h> |
| 31 | #include <string.h> |
| 32 | |
| 33 | #include <array> |
| 34 | #include <iostream> |
| 35 | |
| 36 | #include <filament/Color.h> |
| 37 | #include <filament/VertexBuffer.h> |
| 38 | #include <filament/Engine.h> |
| 39 | #include <filament/IndexBuffer.h> |
| 40 | #include <filament/Material.h> |
| 41 | #include <filament/Renderer.h> |
| 42 | #include <filament/Scene.h> |
| 43 | #include <filament/RenderableManager.h> |
| 44 | #include <filament/TransformManager.h> |
| 45 | |
| 46 | #include <math/norm.h> |
| 47 | #include <math/vec3.h> |
| 48 | #include <math/TVecHelpers.h> |
| 49 | |
| 50 | #include <assimp/Importer.hpp> |
| 51 | #include <assimp/postprocess.h> |
| 52 | #include <assimp/cimport.h> |
| 53 | #include <assimp/scene.h> |
| 54 | #include <assimp/pbrmaterial.h> |
| 55 | |
| 56 | #include <stb_image.h> |
| 57 | |
| 58 | #include <backend/DriverEnums.h> |
| 59 | |
| 60 | #include "generated/resources/filamentapp.h" |
| 61 | |
| 62 | using namespace filament; |
| 63 | using namespace filamat; |
| 64 | using namespace filament::math; |
| 65 | using namespace utils; |
| 66 | |
| 67 | enum class AlphaMode : uint8_t { |
| 68 | OPAQUE, |
| 69 | MASKED, |
| 70 | TRANSPARENT |
| 71 | }; |
| 72 | |
| 73 | struct MaterialConfig { |
| 74 | bool doubleSided = false; |
| 75 | bool unlit = false; |
| 76 | bool hasVertexColors = false; |
| 77 | AlphaMode alphaMode = AlphaMode::OPAQUE; |
| 78 | float maskThreshold = 0.5f; |
| 79 | uint8_t baseColorUV = 0; |
| 80 | uint8_t metallicRoughnessUV = 0; |
| 81 | uint8_t emissiveUV = 0; |
| 82 | uint8_t aoUV = 0; |
| 83 | uint8_t normalUV = 0; |
| 84 | |
| 85 | uint8_t maxUVIndex() { |
| 86 | return std::max({baseColorUV, metallicRoughnessUV, emissiveUV, aoUV, normalUV}); |
| 87 | } |
| 88 | }; |
| 89 | |
| 90 | void appendBooleanToBitMask(uint64_t &bitmask, bool b) { |
| 91 | bitmask <<= 1; |
| 92 | bitmask |= b; |
| 93 | } |
| 94 | |
| 95 | uint64_t hashMaterialConfig(MaterialConfig config) { |
| 96 | uint64_t bitmask = 0; |
| 97 | memcpy(&bitmask, &config.maskThreshold, sizeof(config.maskThreshold)); |
| 98 | appendBooleanToBitMask(bitmask, config.doubleSided); |
| 99 | appendBooleanToBitMask(bitmask, config.unlit); |
| 100 | appendBooleanToBitMask(bitmask, config.hasVertexColors); |
| 101 | appendBooleanToBitMask(bitmask, config.alphaMode == AlphaMode::OPAQUE); |
| 102 | appendBooleanToBitMask(bitmask, config.alphaMode == AlphaMode::MASKED); |
| 103 | appendBooleanToBitMask(bitmask, config.alphaMode == AlphaMode::TRANSPARENT); |
| 104 | appendBooleanToBitMask(bitmask, config.baseColorUV == 0); |
| 105 | appendBooleanToBitMask(bitmask, config.metallicRoughnessUV == 0); |
| 106 | appendBooleanToBitMask(bitmask, config.emissiveUV == 0); |
| 107 | appendBooleanToBitMask(bitmask, config.aoUV == 0); |
| 108 | appendBooleanToBitMask(bitmask, config.normalUV == 0); |
| 109 | return bitmask; |
| 110 | } |
| 111 | |
| 112 | std::string shaderFromConfig(MaterialConfig config) { |
| 113 | std::string shader = R"SHADER( |
| 114 | void material(inout MaterialInputs material) { |
| 115 | )SHADER"; |
| 116 | |
| 117 | shader += "float2 normalUV = getUV" + std::to_string(config.normalUV) + "();\n"; |
| 118 | shader += "float2 baseColorUV = getUV" + std::to_string(config.baseColorUV) + "();\n"; |
| 119 | shader += "float2 metallicRoughnessUV = getUV" + std::to_string(config.metallicRoughnessUV) + "();\n"; |
| 120 | shader += "float2 aoUV = getUV" + std::to_string(config.aoUV) + "();\n"; |
| 121 | shader += "float2 emissiveUV = getUV" + std::to_string(config.emissiveUV) + "();\n"; |
| 122 | |
| 123 | if (!config.unlit) { |
| 124 | shader += R"SHADER( |
| 125 | material.normal = texture(materialParams_normalMap, normalUV).xyz * 2.0 - 1.0; |
| 126 | material.normal.y = -material.normal.y; |
| 127 | )SHADER"; |
| 128 | } |
| 129 | |
| 130 | shader += R"SHADER( |
| 131 | prepareMaterial(material); |
| 132 | material.baseColor = texture(materialParams_baseColorMap, baseColorUV); |
| 133 | material.baseColor *= materialParams.baseColorFactor; |
| 134 | )SHADER"; |
| 135 | |
| 136 | if (config.alphaMode == AlphaMode::TRANSPARENT) { |
| 137 | shader += R"SHADER( |
| 138 | material.baseColor.rgb *= material.baseColor.a; |
| 139 | )SHADER"; |
| 140 | } |
| 141 | |
| 142 | if (!config.unlit) { |
| 143 | shader += R"SHADER( |
| 144 | vec4 metallicRoughness = texture(materialParams_metallicRoughnessMap, metallicRoughnessUV); |
| 145 | material.roughness = materialParams.roughnessFactor * metallicRoughness.g; |
| 146 | material.metallic = materialParams.metallicFactor * metallicRoughness.b; |
| 147 | material.ambientOcclusion = texture(materialParams_aoMap, aoUV).r; |
| 148 | material.emissive.rgb = texture(materialParams_emissiveMap, emissiveUV).rgb; |
| 149 | material.emissive.rgb *= materialParams.emissiveFactor.rgb; |
| 150 | material.emissive.a = 0.0; |
| 151 | )SHADER"; |
| 152 | } |
| 153 | |
| 154 | shader += "}\n"; |
| 155 | return shader; |
| 156 | } |
| 157 | |
| 158 | Material* createMaterialFromConfig(Engine& engine, MaterialConfig config ) { |
| 159 | std::string shader = shaderFromConfig(config); |
| 160 | MaterialBuilder::init(); |
| 161 | MaterialBuilder builder = MaterialBuilder() |
| 162 | .name("material") |
| 163 | .material(shader.c_str()) |
| 164 | .doubleSided(config.doubleSided) |
| 165 | .require(VertexAttribute::UV0) |
| 166 | .parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "baseColorMap") |
| 167 | .parameter(MaterialBuilder::UniformType::FLOAT4, "baseColorFactor") |
| 168 | .parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "metallicRoughnessMap") |
| 169 | .parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "aoMap") |
| 170 | .parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "emissiveMap") |
| 171 | .parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "normalMap") |
| 172 | .parameter(MaterialBuilder::UniformType::FLOAT, "metallicFactor") |
| 173 | .parameter(MaterialBuilder::UniformType::FLOAT, "roughnessFactor") |
| 174 | .parameter(MaterialBuilder::UniformType::FLOAT, "normalScale") |
| 175 | .parameter(MaterialBuilder::UniformType::FLOAT, "aoStrength") |
| 176 | .parameter(MaterialBuilder::UniformType::FLOAT3, "emissiveFactor"); |
| 177 | |
| 178 | if (config.maxUVIndex() > 0) { |
| 179 | builder.require(VertexAttribute::UV1); |
| 180 | } |
| 181 | |
| 182 | switch(config.alphaMode) { |
| 183 | case AlphaMode::MASKED : builder.blending(MaterialBuilder::BlendingMode::MASKED); |
| 184 | builder.maskThreshold(config.maskThreshold); |
| 185 | break; |
| 186 | case AlphaMode::TRANSPARENT : builder.blending(MaterialBuilder::BlendingMode::TRANSPARENT); |
| 187 | break; |
| 188 | default : builder.blending(MaterialBuilder::BlendingMode::OPAQUE); |
| 189 | } |
| 190 | |
| 191 | builder.shading(config.unlit ? Shading::UNLIT : Shading::LIT); |
| 192 | |
| 193 | Package pkg = builder.build(engine.getJobSystem()); |
| 194 | return Material::Builder().package(pkg.getData(), pkg.getSize()).build(engine); |
| 195 | } |
| 196 | |
| 197 | Texture* MeshAssimp::createOneByOneTexture(uint32_t pixel) { |
| 198 | uint32_t *textureData = (uint32_t *) malloc(sizeof(uint32_t)); |
| 199 | *textureData = pixel; |
| 200 | |
| 201 | Texture *texturePtr = Texture::Builder() |
| 202 | .width(uint32_t(1)) |
| 203 | .height(uint32_t(1)) |
| 204 | .levels(0xff) |
| 205 | .format(Texture::InternalFormat::RGBA8) |
| 206 | .build(mEngine); |
| 207 | |
| 208 | Texture::PixelBufferDescriptor defaultNormalBuffer(textureData, |
| 209 | size_t(1 * 1 * 4), |
| 210 | Texture::Format::RGBA, |
| 211 | Texture::Type::UBYTE, |
| 212 | (Texture::PixelBufferDescriptor::Callback) &free); |
| 213 | |
| 214 | texturePtr->setImage(mEngine, 0, std::move(defaultNormalBuffer)); |
| 215 | texturePtr->generateMipmaps(mEngine); |
| 216 | |
| 217 | return texturePtr; |
| 218 | } |
| 219 | |
| 220 | void getMinMaxUV(const aiScene *scene, const aiNode* node, float2 &minUV, |
| 221 | float2 &maxUV, uint32_t uvIndex) { |
| 222 | for (size_t i = 0; i < node->mNumMeshes; ++i) { |
| 223 | const aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; |
| 224 | if (!mesh->HasTextureCoords(uvIndex)) { |
| 225 | continue; |
| 226 | } |
| 227 | const float3* uv = reinterpret_cast<const float3*>(mesh->mTextureCoords[uvIndex]); |
| 228 | const size_t numVertices = mesh->mNumVertices; |
| 229 | const size_t numFaces = mesh->mNumFaces; |
| 230 | if (numVertices == 0 || numFaces == 0) { |
| 231 | continue; |
| 232 | } |
| 233 | if (uv) { |
| 234 | for (size_t j = 0; j < numVertices; j++) { |
| 235 | minUV = min(uv[j].xy, minUV); |
| 236 | maxUV = max(uv[j].xy, maxUV); |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | for (size_t i = 0 ; i < node->mNumChildren ; ++i) { |
| 241 | getMinMaxUV(scene, node->mChildren[i], minUV, maxUV, uvIndex); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | template<bool SNORMUVS> |
| 246 | static ushort2 convertUV(float2 uv) { |
| 247 | if (SNORMUVS) { |
| 248 | short2 uvshort(packSnorm16(uv)); |
| 249 | return bit_cast<ushort2>(uvshort); |
| 250 | } else { |
| 251 | half2 uvhalf(uv); |
| 252 | return bit_cast<ushort2>(uvhalf); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | MeshAssimp::MeshAssimp(Engine& engine) : mEngine(engine) { |
| 257 | mDefaultMap = createOneByOneTexture(0xffffffff); |
| 258 | mDefaultNormalMap = createOneByOneTexture(0xffff8080); |
| 259 | |
| 260 | mDefaultColorMaterial = Material::Builder() |
| 261 | .package(FILAMENTAPP_AIDEFAULTMAT_DATA, FILAMENTAPP_AIDEFAULTMAT_SIZE) |
| 262 | .build(mEngine); |
| 263 | |
| 264 | mDefaultColorMaterial->setDefaultParameter("baseColor", RgbType::LINEAR, float3{0.8}); |
| 265 | mDefaultColorMaterial->setDefaultParameter("metallic", 0.0f); |
| 266 | mDefaultColorMaterial->setDefaultParameter("roughness", 0.4f); |
| 267 | mDefaultColorMaterial->setDefaultParameter("reflectance", 0.5f); |
| 268 | |
| 269 | mDefaultTransparentColorMaterial = Material::Builder() |
| 270 | .package(FILAMENTAPP_AIDEFAULTTRANS_DATA, FILAMENTAPP_AIDEFAULTTRANS_SIZE) |
| 271 | .build(mEngine); |
| 272 | |
| 273 | mDefaultTransparentColorMaterial->setDefaultParameter("baseColor", RgbType::LINEAR, float3{0.8}); |
| 274 | mDefaultTransparentColorMaterial->setDefaultParameter("metallic", 0.0f); |
| 275 | mDefaultTransparentColorMaterial->setDefaultParameter("roughness", 0.4f); |
| 276 | } |
| 277 | |
| 278 | MeshAssimp::~MeshAssimp() { |
| 279 | mEngine.destroy(mVertexBuffer); |
| 280 | mEngine.destroy(mIndexBuffer); |
| 281 | mEngine.destroy(mDefaultColorMaterial); |
| 282 | mEngine.destroy(mDefaultTransparentColorMaterial); |
| 283 | mEngine.destroy(mDefaultNormalMap); |
| 284 | mEngine.destroy(mDefaultMap); |
| 285 | |
| 286 | for (auto& item : mGltfMaterialCache) { |
| 287 | auto material = item.second; |
| 288 | mEngine.destroy(material); |
| 289 | } |
| 290 | |
| 291 | for (Entity renderable : mRenderables) { |
| 292 | mEngine.destroy(renderable); |
| 293 | } |
| 294 | |
| 295 | for (Texture* texture : mTextures) { |
| 296 | mEngine.destroy(texture); |
| 297 | } |
| 298 | |
| 299 | // destroy the Entities itself |
| 300 | EntityManager::get().destroy(mRenderables.size(), mRenderables.data()); |
| 301 | } |
| 302 | |
| 303 | template<typename T> |
| 304 | struct State { |
| 305 | std::vector<T> state; |
| 306 | explicit State(std::vector<T>&& state) : state(std::move(state)) { } |
| 307 | static void free(void* buffer, size_t size, void* user) { |
| 308 | auto* const that = static_cast<State<T>*>(user); |
| 309 | delete that; |
| 310 | } |
| 311 | size_t size() const { return state.size() * sizeof(T); } |
| 312 | T const * data() const { return state.data(); } |
| 313 | }; |
| 314 | |
| 315 | //TODO: Remove redundant method from sample_full_pbr |
| 316 | static void loadTexture(Engine *engine, const std::string &filePath, Texture **map, |
| 317 | bool sRGB, bool hasAlpha) { |
| 318 | |
| 319 | if (!filePath.empty()) { |
| 320 | Path path(filePath); |
| 321 | if (path.exists()) { |
| 322 | int w, h, n; |
| 323 | int numChannels = hasAlpha ? 4 : 3; |
| 324 | |
| 325 | Texture::InternalFormat inputFormat; |
| 326 | if (sRGB) { |
| 327 | inputFormat = hasAlpha ? Texture::InternalFormat::SRGB8_A8 : Texture::InternalFormat::SRGB8; |
| 328 | } else { |
| 329 | inputFormat = hasAlpha ? Texture::InternalFormat::RGBA8 : Texture::InternalFormat::RGB8; |
| 330 | } |
| 331 | |
| 332 | Texture::Format outputFormat = hasAlpha ? Texture::Format::RGBA : Texture::Format::RGB; |
| 333 | |
| 334 | uint8_t *data = stbi_load(path.getAbsolutePath().c_str(), &w, &h, &n, numChannels); |
| 335 | if (data != nullptr) { |
| 336 | *map = Texture::Builder() |
| 337 | .width(uint32_t(w)) |
| 338 | .height(uint32_t(h)) |
| 339 | .levels(0xff) |
| 340 | .format(inputFormat) |
| 341 | .build(*engine); |
| 342 | |
| 343 | Texture::PixelBufferDescriptor buffer(data, |
| 344 | size_t(w * h * numChannels), |
| 345 | outputFormat, |
| 346 | Texture::Type::UBYTE, |
| 347 | (Texture::PixelBufferDescriptor::Callback) &stbi_image_free); |
| 348 | |
| 349 | (*map)->setImage(*engine, 0, std::move(buffer)); |
| 350 | (*map)->generateMipmaps(*engine); |
| 351 | } else { |
| 352 | std::cout << "The texture " << path << " could not be loaded" << std::endl; |
| 353 | } |
| 354 | } else { |
| 355 | std::cout << "The texture " << path << " does not exist" << std::endl; |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | void loadEmbeddedTexture(Engine *engine, aiTexture *embeddedTexture, Texture **map, |
| 361 | bool sRGB, bool hasAlpha) { |
| 362 | |
| 363 | int w, h, n; |
| 364 | int numChannels = hasAlpha ? 4 : 3; |
| 365 | |
| 366 | Texture::InternalFormat inputFormat; |
| 367 | if (sRGB) { |
| 368 | inputFormat = hasAlpha ? Texture::InternalFormat::SRGB8_A8 : Texture::InternalFormat::SRGB8; |
| 369 | } else { |
| 370 | inputFormat = hasAlpha ? Texture::InternalFormat::RGBA8 : Texture::InternalFormat::RGB8; |
| 371 | } |
| 372 | |
| 373 | Texture::Format outputFormat = hasAlpha ? Texture::Format::RGBA : Texture::Format::RGB; |
| 374 | |
| 375 | uint8_t *data = stbi_load_from_memory((unsigned char *) embeddedTexture->pcData, |
| 376 | embeddedTexture->mWidth, &w, &h, &n, numChannels); |
| 377 | |
| 378 | *map = Texture::Builder() |
| 379 | .width(uint32_t(w)) |
| 380 | .height(uint32_t(h)) |
| 381 | .levels(0xff) |
| 382 | .format(inputFormat) |
| 383 | .build(*engine); |
| 384 | |
| 385 | Texture::PixelBufferDescriptor defaultBuffer(data, |
| 386 | size_t(w * h * numChannels), |
| 387 | outputFormat, |
| 388 | Texture::Type::UBYTE, |
| 389 | (Texture::PixelBufferDescriptor::Callback) &free); |
| 390 | |
| 391 | (*map)->setImage(*engine, 0, std::move(defaultBuffer)); |
| 392 | (*map)->generateMipmaps(*engine); |
| 393 | } |
| 394 | |
| 395 | // Takes a texture filename and returns the index of the embedded texture, |
| 396 | // -1 if the texture is not embedded |
| 397 | int32_t getEmbeddedTextureId(const aiString& path) { |
| 398 | const char *pathStr = path.C_Str(); |
| 399 | if (path.length >= 2 && pathStr[0] == '*') { |
| 400 | for (int i = 1; i < path.length; i++) { |
| 401 | if (!isdigit(pathStr[i])) { |
| 402 | return -1; |
| 403 | } |
| 404 | } |
| 405 | return std::atoi(pathStr + 1); // NOLINT |
| 406 | } |
| 407 | return -1; |
| 408 | } |
| 409 | |
| 410 | TextureSampler::WrapMode aiToFilamentMapMode(aiTextureMapMode mapMode) { |
| 411 | switch(mapMode) { |
| 412 | case aiTextureMapMode_Clamp : |
| 413 | return TextureSampler::WrapMode::CLAMP_TO_EDGE; |
| 414 | case aiTextureMapMode_Mirror : |
| 415 | return TextureSampler::WrapMode::MIRRORED_REPEAT; |
| 416 | default: |
| 417 | return TextureSampler::WrapMode::REPEAT; |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | TextureSampler::MinFilter aiMinFilterToFilament(unsigned int aiMinFilter) { |
| 422 | switch(aiMinFilter) { |
| 423 | case GL_NEAREST: return TextureSampler::MinFilter::NEAREST; |
| 424 | case GL_LINEAR: return TextureSampler::MinFilter::LINEAR; |
| 425 | case GL_NEAREST_MIPMAP_NEAREST: return TextureSampler::MinFilter::NEAREST_MIPMAP_NEAREST; |
| 426 | case GL_LINEAR_MIPMAP_NEAREST: return TextureSampler::MinFilter::LINEAR_MIPMAP_NEAREST; |
| 427 | case GL_NEAREST_MIPMAP_LINEAR: return TextureSampler::MinFilter::NEAREST_MIPMAP_LINEAR; |
| 428 | case GL_LINEAR_MIPMAP_LINEAR: return TextureSampler::MinFilter::LINEAR_MIPMAP_LINEAR; |
| 429 | default: return TextureSampler::MinFilter::LINEAR_MIPMAP_LINEAR; |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | TextureSampler::MagFilter aiMagFilterToFilament(unsigned int aiMagFilter) { |
| 434 | switch(aiMagFilter) { |
| 435 | case GL_NEAREST: return TextureSampler::MagFilter::NEAREST; |
| 436 | default: return TextureSampler::MagFilter::LINEAR; |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | // TODO: Change this to a member function (requires some alteration of cmakelsts.txt) |
| 441 | void setTextureFromPath(const aiScene *scene, Engine *engine, |
| 442 | std::vector<filament::Texture*> textures, const aiString &textureFile, |
| 443 | const std::string &materialName, const std::string &textureDirectory, |
| 444 | aiTextureMapMode *mapMode, const char *parameterName, |
| 445 | std::map<std::string, MaterialInstance *> &outMaterials, |
| 446 | unsigned int aiMinFilterType=0, unsigned int aiMagFilterType=0) { |
| 447 | |
| 448 | TextureSampler::MinFilter minFilterType = aiMinFilterToFilament(aiMinFilterType); |
| 449 | TextureSampler::MagFilter magFilterType = aiMagFilterToFilament(aiMagFilterType); |
| 450 | |
| 451 | TextureSampler sampler; |
| 452 | if (mapMode) { |
| 453 | sampler = TextureSampler( |
| 454 | minFilterType, |
| 455 | magFilterType, |
| 456 | aiToFilamentMapMode(mapMode[0]), |
| 457 | aiToFilamentMapMode(mapMode[1]), |
| 458 | aiToFilamentMapMode(mapMode[2])); |
| 459 | } else { |
| 460 | sampler = TextureSampler( |
| 461 | minFilterType, |
| 462 | magFilterType, |
| 463 | TextureSampler::WrapMode::REPEAT); |
| 464 | } |
| 465 | |
| 466 | Texture* textureMap = nullptr; |
| 467 | int32_t embeddedId = getEmbeddedTextureId(textureFile); |
| 468 | |
| 469 | // TODO: change this in refactor |
| 470 | bool isSRGB = strcmp(parameterName, "baseColorMap") == 0 || strcmp(parameterName, "emissiveMap") == 0; |
| 471 | bool hasAlpha = strcmp(parameterName, "baseColorMap") == 0; |
| 472 | |
| 473 | if (embeddedId != -1) { |
| 474 | loadEmbeddedTexture(engine, scene->mTextures[embeddedId], &textureMap, isSRGB, hasAlpha); |
| 475 | } else { |
| 476 | loadTexture(engine, textureDirectory + textureFile.C_Str(), &textureMap, isSRGB, hasAlpha); |
| 477 | } |
| 478 | |
| 479 | textures.push_back(textureMap); |
| 480 | |
| 481 | if (textureMap != nullptr) { |
| 482 | outMaterials[materialName]->setParameter(parameterName, textureMap, sampler); |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | template<typename VECTOR, typename INDEX> |
| 487 | Box computeTransformedAABB(VECTOR const* vertices, INDEX const* indices, size_t count, |
| 488 | const mat4f& transform) noexcept { |
| 489 | size_t stride = sizeof(VECTOR); |
| 490 | filament::math::float3 bmin(std::numeric_limits<float>::max()); |
| 491 | filament::math::float3 bmax(std::numeric_limits<float>::lowest()); |
| 492 | for (size_t i = 0; i < count; ++i) { |
| 493 | VECTOR const* p = reinterpret_cast<VECTOR const*>( |
| 494 | (char const*) vertices + indices[i] * stride); |
| 495 | const filament::math::float3 v(p->x, p->y, p->z); |
| 496 | float3 tv = (transform * float4(v, 1.0f)).xyz; |
| 497 | bmin = min(bmin, tv); |
| 498 | bmax = max(bmax, tv); |
| 499 | } |
| 500 | return Box().set(bmin, bmax); |
| 501 | } |
| 502 | |
| 503 | void MeshAssimp::addFromFile(const Path& path, |
| 504 | std::map<std::string, MaterialInstance*>& materials, bool overrideMaterial) { |
| 505 | |
| 506 | Asset asset; |
| 507 | asset.file = path; |
| 508 | |
| 509 | { // This scope to make sure we're not using std::move()'d objects later |
| 510 | |
| 511 | // TODO: if we had a way to allocate temporary buffers from the engine with a |
| 512 | // "command buffer" lifetime, we wouldn't need to have to deal with freeing the |
| 513 | // std::vectors here. |
| 514 | |
| 515 | //TODO: a lot of these method arguments should probably be class or global variables |
| 516 | if (!setFromFile(asset, materials)) { |
| 517 | return; |
| 518 | } |
| 519 | |
| 520 | VertexBuffer::Builder vertexBufferBuilder = VertexBuffer::Builder() |
| 521 | .vertexCount((uint32_t)asset.positions.size()) |
| 522 | .bufferCount(4) |
| 523 | .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::HALF4) |
| 524 | .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::SHORT4) |
| 525 | .normalized(VertexAttribute::TANGENTS); |
| 526 | |
| 527 | if (asset.snormUV0) { |
| 528 | vertexBufferBuilder.attribute(VertexAttribute::UV0, 2, VertexBuffer::AttributeType::SHORT2) |
| 529 | .normalized(VertexAttribute::UV0); |
| 530 | } else { |
| 531 | vertexBufferBuilder.attribute(VertexAttribute::UV0, 2, VertexBuffer::AttributeType::HALF2); |
| 532 | } |
| 533 | |
| 534 | if (asset.snormUV1) { |
| 535 | vertexBufferBuilder.attribute(VertexAttribute::UV1, 3, VertexBuffer::AttributeType::SHORT2) |
| 536 | .normalized(VertexAttribute::UV1); |
| 537 | } else { |
| 538 | vertexBufferBuilder.attribute(VertexAttribute::UV1, 3, VertexBuffer::AttributeType::HALF2); |
| 539 | } |
| 540 | |
| 541 | mVertexBuffer = vertexBufferBuilder.build(mEngine); |
| 542 | |
| 543 | auto ps = new State<half4>(std::move(asset.positions)); |
| 544 | auto ns = new State<short4>(std::move(asset.tangents)); |
| 545 | auto t0s = new State<ushort2>(std::move(asset.texCoords0)); |
| 546 | auto t1s = new State<ushort2>(std::move(asset.texCoords1)); |
| 547 | auto is = new State<uint32_t>(std::move(asset.indices)); |
| 548 | |
| 549 | mVertexBuffer->setBufferAt(mEngine, 0, |
| 550 | VertexBuffer::BufferDescriptor(ps->data(), ps->size(), State<half4>::free, ps)); |
| 551 | |
| 552 | mVertexBuffer->setBufferAt(mEngine, 1, |
| 553 | VertexBuffer::BufferDescriptor(ns->data(), ns->size(), State<short4>::free, ns)); |
| 554 | |
| 555 | mVertexBuffer->setBufferAt(mEngine, 2, |
| 556 | VertexBuffer::BufferDescriptor(t0s->data(), t0s->size(), State<ushort2>::free, t0s)); |
| 557 | |
| 558 | mVertexBuffer->setBufferAt(mEngine, 3, |
| 559 | VertexBuffer::BufferDescriptor(t1s->data(), t1s->size(), State<ushort2>::free, t1s)); |
| 560 | |
| 561 | mIndexBuffer = IndexBuffer::Builder().indexCount(uint32_t(is->size())).build(mEngine); |
| 562 | mIndexBuffer->setBuffer(mEngine, |
| 563 | IndexBuffer::BufferDescriptor(is->data(), is->size(), State<uint32_t>::free, is)); |
| 564 | } |
| 565 | |
| 566 | // always add the DefaultMaterial (with its default parameters), so we don't pick-up |
| 567 | // whatever defaults is used in mesh |
| 568 | if (materials.find(AI_DEFAULT_MATERIAL_NAME) == materials.end()) { |
| 569 | materials[AI_DEFAULT_MATERIAL_NAME] = mDefaultColorMaterial->createInstance(); |
| 570 | } |
| 571 | |
| 572 | size_t startIndex = mRenderables.size(); |
| 573 | mRenderables.resize(startIndex + asset.meshes.size()); |
| 574 | EntityManager::get().create(asset.meshes.size(), mRenderables.data() + startIndex); |
| 575 | EntityManager::get().create(1, &rootEntity); |
| 576 | |
| 577 | TransformManager& tcm = mEngine.getTransformManager(); |
| 578 | //Add root instance |
| 579 | tcm.create(rootEntity, TransformManager::Instance{}, mat4f()); |
| 580 | |
| 581 | for (auto& mesh : asset.meshes) { |
| 582 | RenderableManager::Builder builder(mesh.parts.size()); |
| 583 | builder.boundingBox(mesh.aabb); |
| 584 | builder.screenSpaceContactShadows(true); |
| 585 | |
| 586 | size_t partIndex = 0; |
| 587 | for (auto& part : mesh.parts) { |
| 588 | builder.geometry(partIndex, RenderableManager::PrimitiveType::TRIANGLES, |
| 589 | mVertexBuffer, mIndexBuffer, part.offset, part.count); |
| 590 | |
| 591 | if (overrideMaterial) { |
| 592 | builder.material(partIndex, materials[AI_DEFAULT_MATERIAL_NAME]); |
| 593 | } else { |
| 594 | auto pos = materials.find(part.material); |
| 595 | |
| 596 | if (pos != materials.end()) { |
| 597 | builder.material(partIndex, pos->second); |
| 598 | } else { |
| 599 | MaterialInstance* colorMaterial; |
| 600 | if (part.opacity < 1.0f) { |
| 601 | colorMaterial = mDefaultTransparentColorMaterial->createInstance(); |
| 602 | colorMaterial->setParameter("baseColor", RgbaType::sRGB, |
| 603 | sRGBColorA { part.baseColor, part.opacity }); |
| 604 | } else { |
| 605 | colorMaterial = mDefaultColorMaterial->createInstance(); |
| 606 | colorMaterial->setParameter("baseColor", RgbType::sRGB, part.baseColor); |
| 607 | colorMaterial->setParameter("reflectance", part.reflectance); |
| 608 | } |
| 609 | colorMaterial->setParameter("metallic", part.metallic); |
| 610 | colorMaterial->setParameter("roughness", part.roughness); |
| 611 | builder.material(partIndex, colorMaterial); |
| 612 | materials[part.material] = colorMaterial; |
| 613 | } |
| 614 | } |
| 615 | partIndex++; |
| 616 | } |
| 617 | |
| 618 | const size_t meshIndex = &mesh - asset.meshes.data(); |
| 619 | Entity entity = mRenderables[startIndex + meshIndex]; |
| 620 | if (!mesh.parts.empty()) { |
| 621 | builder.build(mEngine, entity); |
| 622 | } |
| 623 | auto pindex = asset.parents[meshIndex]; |
| 624 | TransformManager::Instance parent((pindex < 0) ? |
| 625 | tcm.getInstance(rootEntity) : tcm.getInstance(mRenderables[pindex])); |
| 626 | tcm.create(entity, parent, mesh.transform); |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | using Assimp::Importer; |
| 631 | |
| 632 | bool MeshAssimp::setFromFile(Asset& asset, std::map<std::string, MaterialInstance*>& outMaterials) { |
| 633 | Importer importer; |
| 634 | importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, |
| 635 | aiPrimitiveType_LINE | aiPrimitiveType_POINT); |
| 636 | importer.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true); |
| 637 | importer.SetPropertyBool(AI_CONFIG_PP_PTV_KEEP_HIERARCHY, true); |
| 638 | |
| 639 | aiScene const* scene = importer.ReadFile(asset.file, |
| 640 | // normals and tangents |
| 641 | aiProcess_GenSmoothNormals | |
| 642 | aiProcess_CalcTangentSpace | |
| 643 | // UV Coordinates |
| 644 | aiProcess_GenUVCoords | |
| 645 | // topology optimization |
| 646 | aiProcess_FindInstances | |
| 647 | aiProcess_OptimizeMeshes | |
| 648 | aiProcess_JoinIdenticalVertices | |
| 649 | // misc optimization |
| 650 | aiProcess_ImproveCacheLocality | |
| 651 | aiProcess_SortByPType | |
| 652 | // we only support triangles |
| 653 | aiProcess_Triangulate); |
| 654 | |
| 655 | size_t index = importer.GetImporterIndex(asset.file.getExtension().c_str()); |
| 656 | const aiImporterDesc* importerDesc = importer.GetImporterInfo(index); |
| 657 | bool isGLTF = importerDesc && |
| 658 | (!strncmp("glTF Importer", importerDesc->mName, 13) || |
| 659 | !strncmp("glTF2 Importer", importerDesc->mName, 14)); |
| 660 | |
| 661 | if (!scene) { |
| 662 | std::cout << "No scene" << std::endl; |
| 663 | } |
| 664 | |
| 665 | if (scene && !scene->mRootNode) { |
| 666 | std::cout << "No root node" << std::endl; |
| 667 | } |
| 668 | |
| 669 | // we could use those, but we want to keep the graph if any, for testing |
| 670 | // aiProcess_OptimizeGraph |
| 671 | // aiProcess_PreTransformVertices |
| 672 | |
| 673 | const std::function<void(aiNode const* node, size_t& totalVertexCount, size_t& totalIndexCount)> |
| 674 | countVertices = [scene, &countVertices] |
| 675 | (aiNode const* node, size_t& totalVertexCount, size_t& totalIndexCount) { |
| 676 | for (size_t i = 0; i < node->mNumMeshes; i++) { |
| 677 | aiMesh const *mesh = scene->mMeshes[node->mMeshes[i]]; |
| 678 | totalVertexCount += mesh->mNumVertices; |
| 679 | |
| 680 | const aiFace *faces = mesh->mFaces; |
| 681 | const size_t numFaces = mesh->mNumFaces; |
| 682 | totalIndexCount += numFaces * faces[0].mNumIndices; |
| 683 | } |
| 684 | |
| 685 | for (size_t i = 0; i < node->mNumChildren; i++) { |
| 686 | countVertices(node->mChildren[i], totalVertexCount, totalIndexCount); |
| 687 | } |
| 688 | }; |
| 689 | |
| 690 | if (scene) { |
| 691 | size_t deep = 0; |
| 692 | size_t depth = 0; |
| 693 | size_t matCount = 0; |
| 694 | |
| 695 | aiNode const* node = scene->mRootNode; |
| 696 | |
| 697 | size_t totalVertexCount = 0; |
| 698 | size_t totalIndexCount = 0; |
| 699 | |
| 700 | countVertices(node, totalVertexCount, totalIndexCount); |
| 701 | |
| 702 | asset.positions.reserve(asset.positions.size() + totalVertexCount); |
| 703 | asset.tangents.reserve(asset.tangents.size() + totalVertexCount); |
| 704 | asset.texCoords0.reserve(asset.texCoords0.size() + totalVertexCount); |
| 705 | asset.texCoords1.reserve(asset.texCoords1.size() + totalVertexCount); |
| 706 | asset.indices.reserve(asset.indices.size() + totalIndexCount); |
| 707 | |
| 708 | float2 minUV0 = float2(std::numeric_limits<float>::max()); |
| 709 | float2 maxUV0 = float2(std::numeric_limits<float>::lowest()); |
| 710 | getMinMaxUV(scene, node, minUV0, maxUV0, 0); |
| 711 | float2 minUV1 = float2(std::numeric_limits<float>::max()); |
| 712 | float2 maxUV1 = float2(std::numeric_limits<float>::lowest()); |
| 713 | getMinMaxUV(scene, node, minUV1, maxUV1, 1); |
| 714 | |
| 715 | asset.snormUV0 = minUV0.x >= -1.0f && minUV0.x <= 1.0f && maxUV0.x >= -1.0f && maxUV0.x <= 1.0f && |
| 716 | minUV0.y >= -1.0f && minUV0.y <= 1.0f && maxUV0.y >= -1.0f && maxUV0.y <= 1.0f; |
| 717 | |
| 718 | asset.snormUV1 = minUV1.x >= -1.0f && minUV1.x <= 1.0f && maxUV1.x >= -1.0f && maxUV1.x <= 1.0f && |
| 719 | minUV1.y >= -1.0f && minUV1.y <= 1.0f && maxUV1.y >= -1.0f && maxUV1.y <= 1.0f; |
| 720 | |
| 721 | if (asset.snormUV0) { |
| 722 | if (asset.snormUV1) { |
| 723 | processNode<true, true>(asset, outMaterials, |
| 724 | scene, isGLTF, deep, matCount, node, -1, depth); |
| 725 | } else { |
| 726 | processNode<true, false>(asset, outMaterials, |
| 727 | scene, isGLTF, deep, matCount, node, -1, depth); |
| 728 | } |
| 729 | } else { |
| 730 | if (asset.snormUV1) { |
| 731 | processNode<false, true>(asset, outMaterials, |
| 732 | scene, isGLTF, deep, matCount, node, -1, depth); |
| 733 | } else { |
| 734 | processNode<false, false>(asset, outMaterials, |
| 735 | scene, isGLTF, deep, matCount, node, -1, depth); |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | // compute the aabb and find bounding box of entire model |
| 740 | for (auto& mesh : asset.meshes) { |
| 741 | mesh.aabb = RenderableManager::computeAABB( |
| 742 | asset.positions.data(), |
| 743 | asset.indices.data() + mesh.offset, |
| 744 | mesh.count); |
| 745 | |
| 746 | Box transformedAabb = computeTransformedAABB( |
| 747 | asset.positions.data(), |
| 748 | asset.indices.data() + mesh.offset, |
| 749 | mesh.count, |
| 750 | mesh.accTransform); |
| 751 | |
| 752 | float3 aabbMin = transformedAabb.getMin(); |
| 753 | float3 aabbMax = transformedAabb.getMax(); |
| 754 | |
| 755 | if (!isinf(aabbMin.x) && !isinf(aabbMax.x)) { |
| 756 | if (minBound.x > maxBound.x) { |
| 757 | minBound.x = aabbMin.x; |
| 758 | maxBound.x = aabbMax.x; |
| 759 | } else { |
| 760 | minBound.x = fmin(minBound.x, aabbMin.x); |
| 761 | maxBound.x = fmax(maxBound.x, aabbMax.x); |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | if (!isinf(aabbMin.y) && !isinf(aabbMax.y)) { |
| 766 | if (minBound.y > maxBound.y) { |
| 767 | minBound.y = aabbMin.y; |
| 768 | maxBound.y = aabbMax.y; |
| 769 | } else { |
| 770 | minBound.y = fmin(minBound.y, aabbMin.y); |
| 771 | maxBound.y = fmax(maxBound.y, aabbMax.y); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | if (!isinf(aabbMin.z) && !isinf(aabbMax.z)) { |
| 776 | if (minBound.z > maxBound.z) { |
| 777 | minBound.z = aabbMin.z; |
| 778 | maxBound.z = aabbMax.z; |
| 779 | } else { |
| 780 | minBound.z = fmin(minBound.z, aabbMin.z); |
| 781 | maxBound.z = fmax(maxBound.z, aabbMax.z); |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | return true; |
| 787 | } |
| 788 | return false; |
| 789 | } |
| 790 | |
| 791 | template<bool SNORMUV0, bool SNORMUV1> |
| 792 | void MeshAssimp::processNode(Asset& asset, |
| 793 | std::map<std::string, |
| 794 | MaterialInstance *> &outMaterials, |
| 795 | const aiScene *scene, |
| 796 | bool isGLTF, |
| 797 | size_t deep, |
| 798 | size_t matCount, |
| 799 | const aiNode *node, |
| 800 | int parentIndex, |
| 801 | size_t &depth) const { |
| 802 | mat4f const& current = transpose(*reinterpret_cast<mat4f const*>(&node->mTransformation)); |
| 803 | |
| 804 | size_t totalIndices = 0; |
| 805 | asset.parents.push_back(parentIndex); |
| 806 | asset.meshes.push_back(Mesh{}); |
| 807 | asset.meshes.back().offset = asset.indices.size(); |
| 808 | asset.meshes.back().transform = current; |
| 809 | |
| 810 | mat4f parentTransform = parentIndex >= 0 ? asset.meshes[parentIndex].accTransform : mat4f(); |
| 811 | asset.meshes.back().accTransform = parentTransform * current; |
| 812 | |
| 813 | for (size_t i = 0; i < node->mNumMeshes; i++) { |
| 814 | aiMesh const* mesh = scene->mMeshes[node->mMeshes[i]]; |
| 815 | |
| 816 | float3 const* positions = reinterpret_cast<float3 const*>(mesh->mVertices); |
| 817 | float3 const* tangents = reinterpret_cast<float3 const*>(mesh->mTangents); |
| 818 | float3 const* bitangents = reinterpret_cast<float3 const*>(mesh->mBitangents); |
| 819 | float3 const* normals = reinterpret_cast<float3 const*>(mesh->mNormals); |
| 820 | float3 const* texCoords0 = reinterpret_cast<float3 const*>(mesh->mTextureCoords[0]); |
| 821 | float3 const* texCoords1 = reinterpret_cast<float3 const*>(mesh->mTextureCoords[1]); |
| 822 | |
| 823 | const size_t numVertices = mesh->mNumVertices; |
| 824 | |
| 825 | if (numVertices > 0) { |
| 826 | const aiFace* faces = mesh->mFaces; |
| 827 | const size_t numFaces = mesh->mNumFaces; |
| 828 | |
| 829 | if (numFaces > 0) { |
| 830 | size_t indicesOffset = asset.positions.size(); |
| 831 | |
| 832 | for (size_t j = 0; j < numVertices; j++) { |
| 833 | float3 normal = normals[j]; |
| 834 | float3 tangent; |
| 835 | float3 bitangent; |
| 836 | |
| 837 | // Assimp always returns 3D tex coords but we only support 2D tex coords. |
| 838 | float2 texCoord0 = texCoords0 ? texCoords0[j].xy : float2{0.0}; |
| 839 | float2 texCoord1 = texCoords1 ? texCoords1[j].xy : float2{0.0}; |
| 840 | // If the tangent and bitangent don't exist, make arbitrary ones. This only |
| 841 | // occurs when the mesh is missing texture coordinates, because assimp |
| 842 | // computes tangents for us. (search up for aiProcess_CalcTangentSpace) |
| 843 | if (!tangents) { |
| 844 | bitangent = normalize(cross(normal, float3{1.0, 0.0, 0.0})); |
| 845 | tangent = normalize(cross(normal, bitangent)); |
| 846 | } else { |
| 847 | tangent = tangents[j]; |
| 848 | bitangent = bitangents[j]; |
| 849 | } |
| 850 | |
| 851 | quatf q = filament::math::details::TMat33<float>::packTangentFrame({tangent, bitangent, normal}); |
| 852 | asset.tangents.push_back(packSnorm16(q.xyzw)); |
| 853 | asset.texCoords0.emplace_back(convertUV<SNORMUV0>(texCoord0)); |
| 854 | asset.texCoords1.emplace_back(convertUV<SNORMUV1>(texCoord1)); |
| 855 | |
| 856 | asset.positions.emplace_back(positions[j], 1.0_h); |
| 857 | } |
| 858 | |
| 859 | // Populate the index buffer. All faces are triangles at this point because we |
| 860 | // asked assimp to perform triangulation. |
| 861 | size_t indicesCount = numFaces * faces[0].mNumIndices; |
| 862 | size_t indexBufferOffset = asset.indices.size(); |
| 863 | totalIndices += indicesCount; |
| 864 | |
| 865 | for (size_t j = 0; j < numFaces; ++j) { |
| 866 | const aiFace& face = faces[j]; |
| 867 | for (size_t k = 0; k < face.mNumIndices; ++k) { |
| 868 | asset.indices.push_back(uint32_t(face.mIndices[k] + indicesOffset)); |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | uint32_t materialId = mesh->mMaterialIndex; |
| 873 | aiMaterial const* material = scene->mMaterials[materialId]; |
| 874 | |
| 875 | aiString name; |
| 876 | std::string materialName; |
| 877 | |
| 878 | if (material->Get(AI_MATKEY_NAME, name) != AI_SUCCESS) { |
| 879 | if (isGLTF) { |
| 880 | while (outMaterials.find("_mat_" + std::to_string(matCount)) |
| 881 | != outMaterials.end()) { |
| 882 | matCount++; |
| 883 | } |
| 884 | materialName = "_mat_" + std::to_string(matCount); |
| 885 | } else { |
| 886 | materialName = AI_DEFAULT_MATERIAL_NAME; |
| 887 | } |
| 888 | } else { |
| 889 | materialName = name.C_Str(); |
| 890 | } |
| 891 | |
| 892 | if (isGLTF && outMaterials.find(materialName) == outMaterials.end()) { |
| 893 | std::string dirName = asset.file.getParent(); |
| 894 | processGLTFMaterial(scene, material, materialName, dirName, outMaterials); |
| 895 | } |
| 896 | |
| 897 | aiColor3D color; |
| 898 | sRGBColor baseColor{1.0f}; |
| 899 | if (material->Get(AI_MATKEY_COLOR_DIFFUSE, color) == AI_SUCCESS) { |
| 900 | baseColor = *reinterpret_cast<sRGBColor*>(&color); |
| 901 | } |
| 902 | |
| 903 | float opacity; |
| 904 | if (material->Get(AI_MATKEY_OPACITY, opacity) != AI_SUCCESS) { |
| 905 | opacity = 1.0f; |
| 906 | } |
| 907 | if (opacity <= 0.0f) opacity = 1.0f; |
| 908 | |
| 909 | float shininess; |
| 910 | if (material->Get(AI_MATKEY_SHININESS, shininess) != AI_SUCCESS) { |
| 911 | shininess = 0.0f; |
| 912 | } |
| 913 | |
| 914 | // convert shininess to roughness |
| 915 | float roughness = sqrt(2.0f / (shininess + 2.0f)); |
| 916 | |
| 917 | float metallic = 0.0f; |
| 918 | float reflectance = 0.5f; |
| 919 | if (material->Get(AI_MATKEY_COLOR_SPECULAR, color) == AI_SUCCESS) { |
| 920 | // if there's a non-grey specular color, assume a metallic surface |
| 921 | if (color.r != color.g && color.r != color.b) { |
| 922 | metallic = 1.0f; |
| 923 | baseColor = *reinterpret_cast<sRGBColor*>(&color); |
| 924 | } else { |
| 925 | if (baseColor.r == 0.0f && baseColor.g == 0.0f && baseColor.b == 0.0f) { |
| 926 | metallic = 1.0f; |
| 927 | baseColor = *reinterpret_cast<sRGBColor*>(&color); |
| 928 | } else { |
| 929 | // TODO: the conversion formula is correct |
| 930 | // reflectance = sqrtf(color.r / 0.16f); |
| 931 | } |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | asset.meshes.back().parts.push_back({ |
| 936 | indexBufferOffset, indicesCount, materialName, |
| 937 | baseColor, opacity, metallic, roughness, reflectance |
| 938 | }); |
| 939 | } |
| 940 | } |
| 941 | } |
| 942 | |
| 943 | if (node->mNumMeshes > 0) { |
| 944 | asset.meshes.back().count = totalIndices; |
| 945 | } |
| 946 | |
| 947 | if (node->mNumChildren) { |
| 948 | parentIndex = static_cast<int>(asset.meshes.size()) - 1; |
| 949 | deep++; |
| 950 | depth = std::max(deep, depth); |
| 951 | for (size_t i = 0, c = node->mNumChildren; i < c; i++) { |
| 952 | processNode<SNORMUV0, SNORMUV1>(asset, outMaterials, scene, |
| 953 | isGLTF, deep, matCount, node->mChildren[i], parentIndex, depth); |
| 954 | } |
| 955 | deep--; |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | void MeshAssimp::processGLTFMaterial(const aiScene* scene, const aiMaterial* material, |
| 960 | const std::string& materialName, const std::string& dirName, |
| 961 | std::map<std::string, MaterialInstance*>& outMaterials) const { |
| 962 | |
| 963 | aiString baseColorPath; |
| 964 | aiString AOPath; |
| 965 | aiString MRPath; |
| 966 | aiString normalPath; |
| 967 | aiString emissivePath; |
| 968 | aiTextureMapMode mapMode[3]; |
| 969 | MaterialConfig matConfig; |
| 970 | |
| 971 | material->Get(AI_MATKEY_TWOSIDED, matConfig.doubleSided); |
| 972 | material->Get(AI_MATKEY_GLTF_UNLIT, matConfig.unlit); |
| 973 | |
| 974 | aiString alphaMode; |
| 975 | material->Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode); |
| 976 | if (strcmp(alphaMode.C_Str(), "BLEND") == 0) { |
| 977 | matConfig.alphaMode = AlphaMode::TRANSPARENT; |
| 978 | } else if (strcmp(alphaMode.C_Str(), "MASK") == 0) { |
| 979 | matConfig.alphaMode = AlphaMode::MASKED; |
| 980 | float maskThreshold = 0.5; |
| 981 | material->Get(AI_MATKEY_GLTF_ALPHACUTOFF, maskThreshold); |
| 982 | matConfig.maskThreshold = maskThreshold; |
| 983 | } |
| 984 | |
| 985 | material->Get(_AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, |
| 986 | matConfig.baseColorUV); |
| 987 | material->Get(_AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, |
| 988 | matConfig.metallicRoughnessUV); |
| 989 | material->Get(_AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, aiTextureType_LIGHTMAP, 0, matConfig.aoUV); |
| 990 | material->Get(_AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, aiTextureType_NORMALS, 0, matConfig.normalUV); |
| 991 | material->Get(_AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, aiTextureType_EMISSIVE, 0, matConfig.emissiveUV); |
| 992 | |
| 993 | uint64_t configHash = hashMaterialConfig(matConfig); |
| 994 | |
| 995 | if (mGltfMaterialCache.find(configHash) == mGltfMaterialCache.end()) { |
| 996 | mGltfMaterialCache[configHash] = createMaterialFromConfig(mEngine, matConfig); |
| 997 | } |
| 998 | |
| 999 | outMaterials[materialName] = mGltfMaterialCache[configHash]->createInstance(); |
| 1000 | |
| 1001 | // TODO: is there a way to use the same material for multiple mask threshold values? |
| 1002 | // if (matConfig.alphaMode == masked) { |
| 1003 | // float maskThreshold = 0.5; |
| 1004 | // material->Get(AI_MATKEY_GLTF_ALPHACUTOFF, maskThreshold); |
| 1005 | // outMaterials[materialName]->setParameter("maskThreshold", maskThreshold); |
| 1006 | // } |
| 1007 | |
| 1008 | // Load property values for gltf files |
| 1009 | aiColor4D baseColorFactor; |
| 1010 | aiColor3D emissiveFactor; |
| 1011 | float metallicFactor = 1.0; |
| 1012 | float roughnessFactor = 1.0; |
| 1013 | |
| 1014 | // TODO: is occlusion strength available on Assimp now? |
| 1015 | |
| 1016 | // Load texture images for gltf files |
| 1017 | TextureSampler sampler( |
| 1018 | TextureSampler::MinFilter::LINEAR_MIPMAP_LINEAR, |
| 1019 | TextureSampler::MagFilter::LINEAR, |
| 1020 | TextureSampler::WrapMode::REPEAT); |
| 1021 | |
| 1022 | if (material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, &baseColorPath, |
| 1023 | nullptr, nullptr, nullptr, nullptr, mapMode) == AI_SUCCESS) { |
| 1024 | unsigned int minType = 0; |
| 1025 | unsigned int magType = 0; |
| 1026 | material->Get("$tex.mappingfiltermin", AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, minType); |
| 1027 | material->Get("$tex.mappingfiltermag", AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, magType); |
| 1028 | |
| 1029 | setTextureFromPath(scene, &mEngine, mTextures, baseColorPath, |
| 1030 | materialName, dirName, mapMode, "baseColorMap", outMaterials, minType, magType); |
| 1031 | } else { |
| 1032 | outMaterials[materialName]->setParameter("baseColorMap", mDefaultMap, sampler); |
| 1033 | } |
| 1034 | |
| 1035 | if (material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &MRPath, |
| 1036 | nullptr, nullptr, nullptr, nullptr, mapMode) == AI_SUCCESS) { |
| 1037 | unsigned int minType = 0; |
| 1038 | unsigned int magType = 0; |
| 1039 | material->Get("$tex.mappingfiltermin", AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, minType); |
| 1040 | material->Get("$tex.mappingfiltermag", AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, magType); |
| 1041 | |
| 1042 | setTextureFromPath(scene, &mEngine, mTextures, MRPath, materialName, |
| 1043 | dirName, mapMode, "metallicRoughnessMap", outMaterials, minType, magType); |
| 1044 | } else { |
| 1045 | outMaterials[materialName]->setParameter("metallicRoughnessMap", mDefaultMap, sampler); |
| 1046 | outMaterials[materialName]->setParameter("metallicFactor", mDefaultMetallic); |
| 1047 | outMaterials[materialName]->setParameter("roughnessFactor", mDefaultRoughness); |
| 1048 | } |
| 1049 | |
| 1050 | if (material->GetTexture(aiTextureType_LIGHTMAP, 0, &AOPath, nullptr, |
| 1051 | nullptr, nullptr, nullptr, mapMode) == AI_SUCCESS) { |
| 1052 | unsigned int minType = 0; |
| 1053 | unsigned int magType = 0; |
| 1054 | material->Get("$tex.mappingfiltermin", aiTextureType_LIGHTMAP, 0, minType); |
| 1055 | material->Get("$tex.mappingfiltermag", aiTextureType_LIGHTMAP, 0, magType); |
| 1056 | setTextureFromPath(scene, &mEngine, mTextures, AOPath, materialName, |
| 1057 | dirName, mapMode, "aoMap", outMaterials, minType, magType); |
| 1058 | } else { |
| 1059 | outMaterials[materialName]->setParameter("aoMap", mDefaultMap, sampler); |
| 1060 | } |
| 1061 | |
| 1062 | if (material->GetTexture(aiTextureType_NORMALS, 0, &normalPath, nullptr, |
| 1063 | nullptr, nullptr, nullptr, mapMode) == AI_SUCCESS) { |
| 1064 | unsigned int minType = 0; |
| 1065 | unsigned int magType = 0; |
| 1066 | material->Get("$tex.mappingfiltermin", aiTextureType_NORMALS, 0, minType); |
| 1067 | material->Get("$tex.mappingfiltermag", aiTextureType_NORMALS, 0, magType); |
| 1068 | setTextureFromPath(scene, &mEngine, mTextures, normalPath, materialName, |
| 1069 | dirName, mapMode, "normalMap", outMaterials, minType, magType); |
| 1070 | } else { |
| 1071 | outMaterials[materialName]->setParameter("normalMap", mDefaultNormalMap, sampler); |
| 1072 | } |
| 1073 | |
| 1074 | if (material->GetTexture(aiTextureType_EMISSIVE, 0, &emissivePath, nullptr, |
| 1075 | nullptr, nullptr, nullptr, mapMode) == AI_SUCCESS) { |
| 1076 | unsigned int minType = 0; |
| 1077 | unsigned int magType = 0; |
| 1078 | material->Get("$tex.mappingfiltermin", aiTextureType_EMISSIVE, 0, minType); |
| 1079 | material->Get("$tex.mappingfiltermag", aiTextureType_EMISSIVE, 0, magType); |
| 1080 | setTextureFromPath(scene, &mEngine, mTextures, emissivePath, materialName, |
| 1081 | dirName, mapMode, "emissiveMap", outMaterials, minType, magType); |
| 1082 | } else { |
| 1083 | outMaterials[materialName]->setParameter("emissiveMap", mDefaultMap, sampler); |
| 1084 | outMaterials[materialName]->setParameter("emissiveFactor", mDefaultEmissive); |
| 1085 | } |
| 1086 | |
| 1087 | //If the gltf has texture factors, override the default factor values |
| 1088 | if (material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, metallicFactor) == AI_SUCCESS) { |
| 1089 | outMaterials[materialName]->setParameter("metallicFactor", metallicFactor); |
| 1090 | } |
| 1091 | |
| 1092 | if (material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, roughnessFactor) == AI_SUCCESS) { |
| 1093 | outMaterials[materialName]->setParameter("roughnessFactor", roughnessFactor); |
| 1094 | } |
| 1095 | |
| 1096 | if (material->Get(AI_MATKEY_COLOR_EMISSIVE, emissiveFactor) == AI_SUCCESS) { |
| 1097 | sRGBColor emissiveFactorCast = *reinterpret_cast<sRGBColor*>(&emissiveFactor); |
| 1098 | outMaterials[materialName]->setParameter("emissiveFactor", emissiveFactorCast); |
| 1099 | } |
| 1100 | |
| 1101 | if (material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, baseColorFactor) == AI_SUCCESS) { |
| 1102 | sRGBColorA baseColorFactorCast = *reinterpret_cast<sRGBColorA*>(&baseColorFactor); |
| 1103 | outMaterials[materialName]->setParameter("baseColorFactor", baseColorFactorCast); |
| 1104 | } |
| 1105 | |
| 1106 | aiBool isSpecularGlossiness = false; |
| 1107 | if (material->Get(AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS, isSpecularGlossiness) == AI_SUCCESS) { |
| 1108 | if (isSpecularGlossiness) { |
| 1109 | std::cout << "Warning: pbrSpecularGlossiness textures are not currently supported" << std::endl; |
| 1110 | } |
| 1111 | } |
| 1112 | } |