remove superseded morph classes
This commit is contained in:
@@ -1,310 +0,0 @@
|
||||
// /*
|
||||
// * Copyright (C) 2021 The Android Open Source Project
|
||||
// *
|
||||
// * Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// * you may not use this file except in compliance with the License.
|
||||
// * You may obtain a copy of the License at
|
||||
// *
|
||||
// * http://www.apache.org/licenses/LICENSE-2.0
|
||||
// *
|
||||
// * Unless required by applicable law or agreed to in writing, software
|
||||
// * distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// * See the License for the specific language governing permissions and
|
||||
// * limitations under the License.
|
||||
// */
|
||||
|
||||
// #include "CPUMorpher.h"
|
||||
|
||||
// #include <filament/BufferObject.h>
|
||||
// #include <filament/RenderableManager.h>
|
||||
// #include <filament/VertexBuffer.h>
|
||||
// #include <utils/Log.h>
|
||||
|
||||
// #include "GltfHelpers.h"
|
||||
|
||||
// using namespace filament;
|
||||
// using namespace filament::math;
|
||||
// using namespace utils;
|
||||
// using namespace gltfio;
|
||||
|
||||
// namespace agltfio {
|
||||
|
||||
// static const auto FREE_CALLBACK = [](void* mem, size_t, void*) { free(mem); };
|
||||
|
||||
// CPUMorpher::CPUMorpher(FFilamentAsset* asset, FFilamentInstance* instance) : mAsset(asset) {
|
||||
// NodeMap& sourceNodes = asset->isInstanced() ? asset->mInstances[0]->nodeMap : asset->mNodeMap;
|
||||
|
||||
// int i = 0;
|
||||
// for (auto pair : sourceNodes) {
|
||||
// cgltf_node const* node = pair.first;
|
||||
// cgltf_mesh const* mesh = node->mesh;
|
||||
// if (mesh) {
|
||||
// cgltf_primitive const* prims = mesh->primitives;
|
||||
// for (cgltf_size pi = 0, count = mesh->primitives_count; pi < count; ++pi) {
|
||||
// if (mesh->primitives[pi].targets_count > 0) {
|
||||
// addPrimitive(mesh, pi, &mMorphTable[pair.second]);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// CPUMorpher::~CPUMorpher() {
|
||||
// auto engine = mAsset->mEngine;
|
||||
// for (auto& entry : mMorphTable) {
|
||||
// for (auto& prim : entry.second.primitives) {
|
||||
// if (prim.morphBuffer1) engine->destroy(prim.morphBuffer1);
|
||||
// if (prim.morphBuffer2) engine->destroy(prim.morphBuffer2);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// void CPUMorpher::applyWeights(Entity entity, float const* weights, size_t count) noexcept {
|
||||
// auto& engine = *mAsset->mEngine;
|
||||
// auto renderableManager = &engine.getRenderableManager();
|
||||
// auto renderable = renderableManager->getInstance(entity);
|
||||
|
||||
// for (auto& prim : mMorphTable[entity].primitives) {
|
||||
// if (prim.targets.size() < count) {
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// size_t size = prim.floatsCount * sizeof(float);
|
||||
// float* data = (float*) malloc(size);
|
||||
// memset(data, 0, size);
|
||||
|
||||
// for (size_t index = 0; index < count; index ++) {
|
||||
// const float w = weights[index];
|
||||
// if (w < 0.0001f) continue;
|
||||
|
||||
// const GltfTarget& target = prim.targets[index];
|
||||
// cgltf_size dim = cgltf_num_components(target.type);
|
||||
|
||||
// for (size_t i = 0; i < target.indices.size(); ++i) {
|
||||
// uint16_t index = target.indices[i];
|
||||
// for (size_t j = 0; j < dim; ++j) {
|
||||
// data[index * dim + j] += w * target.values[i * dim + j];
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// VertexBuffer* vb = prim.vertexBuffer;
|
||||
// if (!prim.morphBuffer1) {
|
||||
// prim.morphBuffer1 = BufferObject::Builder().size(size).build(engine);
|
||||
// }
|
||||
// if (!prim.morphBuffer2 && count >= 2) {
|
||||
// // This is for dealing with a bug in filament shaders where empty normals are not
|
||||
// // handled correctly.
|
||||
// //
|
||||
// // filament shaders deal with tangent frame quaternions instead of normal vectors.
|
||||
// // But in case of missing inputs, we get a invalid quaternion (0, 0, 0, 0) instead of
|
||||
// // a identity quaterion. This leads to the normals being morphed even no inputs are
|
||||
// // given.
|
||||
// //
|
||||
// // To fix this, we put a empty morph target at slot 2 and give it a weight of -1.
|
||||
// // This won't affect the vertex positions but will cancel out the normal values.
|
||||
// //
|
||||
// // Note that for this to work, at least two morph targets are required.
|
||||
// float* data2 = (float*) malloc(size);
|
||||
// memset(data2, 0, size);
|
||||
// VertexBuffer::BufferDescriptor bd2(data2, size, FREE_CALLBACK);
|
||||
// prim.morphBuffer2 = BufferObject::Builder().size(size).build(engine);
|
||||
// prim.morphBuffer2->setBuffer(engine, std::move(bd2));
|
||||
// vb->setBufferObjectAt(engine, prim.baseSlot+1, prim.morphBuffer2);
|
||||
// }
|
||||
// VertexBuffer::BufferDescriptor bd(data, size, FREE_CALLBACK);
|
||||
// prim.morphBuffer1->setBuffer(engine, std::move(bd));
|
||||
// vb->setBufferObjectAt(engine, prim.baseSlot, prim.morphBuffer1);
|
||||
// }
|
||||
// renderableManager->setMorphWeights(renderable, {1, -1, 0, 0});
|
||||
// }
|
||||
|
||||
// // // This method copies various morphing-related data from the FilamentAsset MeshCache primitive
|
||||
// // // (which lives in transient memory) into the MorphHelper primitive (which will stay resident).
|
||||
// // void MorphHelper::addPrimitive(cgltf_mesh const* mesh, int primitiveIndex, TableEntry* entry) {
|
||||
// // auto& engine = *mAsset->mEngine;
|
||||
// // const cgltf_primitive& prim = mesh->primitives[primitiveIndex];
|
||||
// // const auto& gltfioPrim = mAsset->mMeshCache.at(mesh)[primitiveIndex];
|
||||
// // VertexBuffer* vertexBuffer = gltfioPrim.vertices;
|
||||
|
||||
// // entry->primitives.push_back({ vertexBuffer });
|
||||
// // auto& morphHelperPrim = entry->primitives.back();
|
||||
|
||||
// // for (int i = 0; i < 4; i++) {
|
||||
// // morphHelperPrim.positions[i] = gltfioPrim.morphPositions[i];
|
||||
// // morphHelperPrim.tangents[i] = gltfioPrim.morphTangents[i];
|
||||
// // }
|
||||
|
||||
// // const cgltf_accessor* previous = nullptr;
|
||||
// // for (int targetIndex = 0; targetIndex < prim.targets_count; targetIndex++) {
|
||||
// // const cgltf_morph_target& morphTarget = prim.targets[targetIndex];
|
||||
// // for (cgltf_size aindex = 0; aindex < morphTarget.attributes_count; aindex++) {
|
||||
// // const cgltf_attribute& attribute = morphTarget.attributes[aindex];
|
||||
// // const cgltf_accessor* accessor = attribute.data;
|
||||
// // const cgltf_attribute_type atype = attribute.type;
|
||||
// // if (atype == cgltf_attribute_type_tangent) {
|
||||
// // continue;
|
||||
// // }
|
||||
// // if (atype == cgltf_attribute_type_normal) {
|
||||
|
||||
// // // TODO: use JobSystem for this, like what we do for non-morph tangents.
|
||||
// // TangentsJob job;
|
||||
// // TangentsJob::Params params = { .in = { &prim, targetIndex } };
|
||||
// // TangentsJob::run(¶ms);
|
||||
|
||||
// // if (params.out.results) {
|
||||
// // const size_t size = params.out.vertexCount * sizeof(short4);
|
||||
// // BufferObject* bufferObject = BufferObject::Builder().size(size).build(engine);
|
||||
// // VertexBuffer::BufferDescriptor bd(params.out.results, size, FREE_CALLBACK);
|
||||
// // bufferObject->setBuffer(engine, std::move(bd));
|
||||
// // params.out.results = nullptr;
|
||||
// // morphHelperPrim.targets.push_back({bufferObject, targetIndex, atype});
|
||||
// // }
|
||||
// // continue;
|
||||
// // }
|
||||
// // if (atype == cgltf_attribute_type_position) {
|
||||
// // // All position attributes must have the same data type.
|
||||
// // assert_invariant(!previous || previous->component_type == accessor->component_type);
|
||||
// // assert_invariant(!previous || previous->type == accessor->type);
|
||||
// // previous = accessor;
|
||||
|
||||
// // // This should always be non-null, but don't crash if the glTF is malformed.
|
||||
// // if (accessor->buffer_view) {
|
||||
// // auto bufferData = (const uint8_t*) accessor->buffer_view->buffer->data;
|
||||
// // assert_invariant(bufferData);
|
||||
// // const uint8_t* data = computeBindingOffset(accessor) + bufferData;
|
||||
// // const uint32_t size = computeBindingSize(accessor);
|
||||
|
||||
// // // This creates a copy because we don't know when the user will free the cgltf
|
||||
// // // source data. For non-morphed vertex buffers, we use a sharing mechanism to
|
||||
// // // prevent copies, but here we just want to keep it as simple as possible.
|
||||
// // uint8_t* clone = (uint8_t*) malloc(size);
|
||||
// // memcpy(clone, data, size);
|
||||
|
||||
// // BufferObject* bufferObject = BufferObject::Builder().size(size).build(engine);
|
||||
// // VertexBuffer::BufferDescriptor bd(clone, size, FREE_CALLBACK);
|
||||
// // bufferObject->setBuffer(engine, std::move(bd));
|
||||
// // morphHelperPrim.targets.push_back({bufferObject, targetIndex, atype});
|
||||
// // }
|
||||
// // }
|
||||
// // }
|
||||
// // }
|
||||
// // }
|
||||
|
||||
// void CPUMorpher::addPrimitive(cgltf_mesh const* mesh, int primitiveIndex, TableEntry* entry) {
|
||||
|
||||
// auto& engine = *mAsset->mEngine;
|
||||
// const cgltf_primitive& cgltf_prim = mesh->primitives[primitiveIndex];
|
||||
|
||||
// int posIndex = findPositionAttribute(cgltf_prim);
|
||||
// if (posIndex < 0) return;
|
||||
|
||||
// VertexBuffer* vertexBuffer = mAsset->mMeshCache.at(mesh)[primitiveIndex].vertices;
|
||||
// int slot = determineBaseSlot(cgltf_prim);
|
||||
// entry->primitives.push_back({ vertexBuffer, slot });
|
||||
|
||||
// auto& primitive = entry->primitives.back();
|
||||
|
||||
// cgltf_attribute& positionAttribute = cgltf_prim.attributes[posIndex];
|
||||
// size_t dim = cgltf_num_components(positionAttribute.data->type);
|
||||
// primitive.floatsCount = positionAttribute.data->count * dim;
|
||||
|
||||
// std::vector<GltfTarget>& targets = primitive.targets;
|
||||
|
||||
// for (int targetIndex = 0; targetIndex < cgltf_prim.targets_count; targetIndex++) {
|
||||
// const cgltf_morph_target& morphTarget = cgltf_prim.targets[targetIndex];
|
||||
// for (cgltf_size aindex = 0; aindex < morphTarget.attributes_count; aindex++) {
|
||||
// const cgltf_attribute& attribute = morphTarget.attributes[aindex];
|
||||
// const cgltf_accessor* accessor = attribute.data;
|
||||
// const cgltf_attribute_type atype = attribute.type;
|
||||
|
||||
// // only works for morphing of positions for now
|
||||
// if (atype == cgltf_attribute_type_position || atype == cgltf_attribute_type_normal) {
|
||||
// targets.push_back({targetIndex, atype, accessor->type});
|
||||
// cgltf_size floats_per_element = cgltf_num_components(accessor->type);
|
||||
|
||||
// targets.back().indices.resize(accessor->count);
|
||||
// targets.back().values.resize(accessor->count * floats_per_element);
|
||||
// cgltf_size unpacked = cgltf_accessor_unpack_floats(accessor, targets.back().values.data(), accessor->count * floats_per_element);
|
||||
// for(int i = 0; i < accessor->count; i++) {
|
||||
// targets.back().indices[i] = i;
|
||||
// /* for(int j = 0; j < floats_per_element; j++) {
|
||||
// size_t offset = (i * floats_per_element) + j;
|
||||
// cgltf_element_read_float
|
||||
// float cgv = cgltf_accessor_unpack_floats(accessor->buffer_view + offset, accessor->component_type, accessor->normalized);
|
||||
// if(cgv > 0) {
|
||||
// size_t foo = 1;
|
||||
// targets.back().values[offset] = cgv;
|
||||
// }
|
||||
// targets.back().values[offset] = cgv;
|
||||
// } */
|
||||
// }
|
||||
// //cgltf_size unpacked = cgltf_accessor_unpack_floats(accessor, targets.back().values.data(), floats_per_element);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// // trying to find the slot for the vertex position
|
||||
// int CPUMorpher::determineBaseSlot(const cgltf_primitive& prim) const {
|
||||
// int slot = 0;
|
||||
// bool hasNormals = false;
|
||||
// for (cgltf_size aindex = 0; aindex < prim.attributes_count; aindex++) {
|
||||
// const cgltf_attribute& attribute = prim.attributes[aindex];
|
||||
// const int index = attribute.index;
|
||||
// const cgltf_attribute_type atype = attribute.type;
|
||||
// const cgltf_accessor* accessor = attribute.data;
|
||||
// if (atype == cgltf_attribute_type_tangent) {
|
||||
// continue;
|
||||
// }
|
||||
// if (atype == cgltf_attribute_type_normal) {
|
||||
// slot++;
|
||||
// hasNormals = true;
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// // Filament supports two set of texcoords. But whether or not UV1 is actually used also
|
||||
// // depends on the material.
|
||||
// // Note this is a very specific fix that might not work in all cases.
|
||||
// if (atype == cgltf_attribute_type_texcoord && index > 0) {
|
||||
// bool hasUV1 = false;
|
||||
// cgltf_material* mat = prim.material;
|
||||
// if (mat->has_pbr_metallic_roughness) {
|
||||
// if (mat->pbr_metallic_roughness.base_color_texture.texcoord != 0) {
|
||||
// hasUV1 = true;
|
||||
// }
|
||||
// if (mat->pbr_metallic_roughness.metallic_roughness_texture.texcoord != 0) {
|
||||
// hasUV1 = true;
|
||||
// }
|
||||
// }
|
||||
// if (mat->normal_texture.texcoord != 0) hasUV1 = true;
|
||||
// if (mat->emissive_texture.texcoord != 0) hasUV1 = true;
|
||||
// if (mat->occlusion_texture.texcoord != 0) hasUV1 = true;
|
||||
|
||||
// if (hasUV1) slot++;
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// slot++;
|
||||
// }
|
||||
|
||||
// // If the model has lighting but not normals, then a slot is used for generated flat normals.
|
||||
// if (prim.material && !prim.material->unlit && !hasNormals) {
|
||||
// slot++;
|
||||
// }
|
||||
|
||||
// return slot;
|
||||
// };
|
||||
|
||||
// int CPUMorpher::findPositionAttribute(const cgltf_primitive& prim) const {
|
||||
// for (cgltf_size aindex = 0; aindex < prim.attributes_count; aindex++) {
|
||||
// if (prim.attributes[aindex].type == cgltf_attribute_type_position) {
|
||||
// return aindex;
|
||||
// }
|
||||
// }
|
||||
|
||||
// return -1;
|
||||
// };
|
||||
|
||||
// } // namespace gltfio
|
||||
@@ -1,362 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2021 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include "GPUMorphHelper.h"
|
||||
|
||||
#include <backend/BufferDescriptor.h>
|
||||
#include <filament/BufferObject.h>
|
||||
#include <filament/RenderableManager.h>
|
||||
#include <filament/VertexBuffer.h>
|
||||
#include <filamat/Package.h>
|
||||
#include <filamat/MaterialBuilder.h>
|
||||
#include <filament/Color.h>
|
||||
|
||||
#include "GltfEnums.h"
|
||||
#include "TangentsJob.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include <math.h>
|
||||
|
||||
using namespace filament;
|
||||
using namespace filamat;
|
||||
using namespace filament::math;
|
||||
using namespace utils;
|
||||
|
||||
#include "upcast.h"
|
||||
|
||||
#include <backend/Handle.h>
|
||||
|
||||
#include <filament/Texture.h>
|
||||
|
||||
#include <utils/compiler.h>
|
||||
|
||||
|
||||
namespace gltfio {
|
||||
|
||||
static constexpr uint8_t kUnused = 0xff;
|
||||
|
||||
uint32_t computeBindingSize(const cgltf_accessor *accessor);
|
||||
|
||||
uint32_t computeBindingOffset(const cgltf_accessor *accessor);
|
||||
|
||||
static const auto FREE_CALLBACK = [](void *mem, size_t s, void *) {
|
||||
free(mem);
|
||||
};
|
||||
|
||||
GPUMorphHelper::GPUMorphHelper(FFilamentAsset *asset, const char* meshName, int* primitiveIndices, int numPrimitives) : mAsset(asset) {
|
||||
|
||||
NodeMap &sourceNodes = asset->isInstanced() ? asset->mInstances[0]->nodeMap
|
||||
: asset->mNodeMap;
|
||||
|
||||
for (auto pair : sourceNodes) {
|
||||
|
||||
cgltf_node const *node = pair.first;
|
||||
cgltf_mesh const *mesh = node->mesh;
|
||||
|
||||
if (mesh) {
|
||||
std::cout << "Mesh " << mesh->name << " with " << mesh->weights_count << " weights and " << mesh->primitives_count << " primitives." << std::endl;
|
||||
if(strcmp(meshName, mesh->name) == 0) {
|
||||
targetMesh = mesh;
|
||||
for(int i = 0; i < numPrimitives; i++) {
|
||||
int primitiveIndex = primitiveIndices[i];
|
||||
//for(int primitiveIndex = 0; primitiveIndex < targetMesh->primitives_count; primitiveIndex++) {
|
||||
std::cout << "Adding primitive at index " << primitiveIndex << " to morpher " << std::endl;
|
||||
addPrimitive(mesh, primitiveIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
auto materialInstances = mAsset->getMaterialInstances();
|
||||
|
||||
std::cout << "MaterialInstances in asset:" << std::endl;
|
||||
for(int i = 0; i < mAsset->getMaterialInstanceCount(); i++) {
|
||||
const char* name = materialInstances[i]->getName();
|
||||
std::cout << "Material : " << name << std::endl;
|
||||
}
|
||||
|
||||
createTextures();
|
||||
|
||||
applyWeights(targetMesh->weights, targetMesh->weights_count);
|
||||
|
||||
}
|
||||
|
||||
GPUMorphHelper::~GPUMorphHelper() {
|
||||
|
||||
}
|
||||
|
||||
///
|
||||
/// Creates the texture that will store the morphable attributes. The texture will be sized according to the total number of vertices in the mesh, meaning all primitives share the same texture.
|
||||
///
|
||||
void GPUMorphHelper::createTextures() {
|
||||
auto materialInstances = mAsset->getMaterialInstances();
|
||||
auto &engine = *(mAsset->mEngine);
|
||||
|
||||
for(auto& prim : animatablePrimitives) {
|
||||
|
||||
// for a single morph target, each vertex will be assigned 2 pixels, corresponding to a position vec3 and a normal vec3
|
||||
// these two vectors will be laid out adjacent in memory
|
||||
// the total texture "width" is the total number of these pixels
|
||||
// morph targets are then assigned to the depth channel
|
||||
auto textureWidth = prim->numVertices * numAttributes;
|
||||
|
||||
// the total size of the texture in bytes
|
||||
// equal to (numVertices * numAttributes * vectorSize (3) * sizeof(float) * numMorphTargets)
|
||||
auto textureSize = textureWidth * 3 * sizeof(float) * prim->numTargets;
|
||||
auto textureBuffer = (float *const) malloc(textureSize);
|
||||
|
||||
if(!textureBuffer) {
|
||||
std::cout << "Error allocating texture buffer" << std::endl;
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
memset(textureBuffer, 0, textureSize);
|
||||
|
||||
uint32_t offset = 0;
|
||||
|
||||
// assume the primitive morph target source buffer is laid out like:
|
||||
// |target0_v0_pos * 3|target0_v1_pos * 3|...|target0_v0_norm * 3|target0_v1_norm * 3|...|target1_v0_pos * 3|target1_v1_pos * 3|...|target1_v0_norm * 3|target1_v1_norm * 3|...
|
||||
// where:
|
||||
// - target0/target1/etc is the first/second/etc morph target
|
||||
// - v0/v1/etc is the first/second/etc vertex
|
||||
// - pos/norm are each 3-float vectors
|
||||
for (auto &target : prim->targets) {
|
||||
if(target.type == cgltf_attribute_type_position
|
||||
|| (numAttributes > 1 && target.type == cgltf_attribute_type_normal)
|
||||
) {
|
||||
float attr = (float)textureBuffer[offset];
|
||||
memcpy(textureBuffer+offset, target.bufferObject, target.bufferSize);
|
||||
offset += int(target.bufferSize / sizeof(float));
|
||||
}
|
||||
}
|
||||
|
||||
Texture* texture = Texture::Builder()
|
||||
.width(textureWidth) //
|
||||
.height(1)
|
||||
.depth(prim->numTargets)
|
||||
.sampler(Texture::Sampler::SAMPLER_2D_ARRAY)
|
||||
.format(backend::TextureFormat::RGB32F)
|
||||
.levels(0x01)
|
||||
.build(engine);
|
||||
|
||||
prim->texture = texture; //std::unique_ptr<Texture>(texture);
|
||||
|
||||
Texture::PixelBufferDescriptor descriptor(
|
||||
textureBuffer,
|
||||
textureSize,
|
||||
backend::PixelDataFormat::RGB,
|
||||
backend::PixelDataType::FLOAT,
|
||||
FREE_CALLBACK,
|
||||
nullptr);
|
||||
prim->texture->setImage(engine, 0, 0,0, 0, textureWidth, 1, prim->numTargets, std::move(descriptor));
|
||||
|
||||
for(int i = 0; i < mAsset->getMaterialInstanceCount(); i++) {
|
||||
const char* name = materialInstances[i]->getName();
|
||||
if(strcmp(name, prim->materialName) == 0) {
|
||||
const char* m = materialInstances[i]->getMaterial()->getName();
|
||||
std::cout << "Found material instance for material " << m << " and primitive under name : " << name << std::endl;
|
||||
prim->materialInstance = materialInstances[i]; //std::unique_ptr<MaterialInstance>(materialInstances[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(!prim->materialInstance) {
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
float dimensions[] = { float(prim->numVertices), float(numAttributes), float(prim->numTargets) };
|
||||
|
||||
prim->materialInstance->setParameter("dimensions", dimensions, 3);
|
||||
// TextureSampler sampler(filament::backend::SamplerMagFilter::NEAREST, filament::TextureSampler::WrapMode::REPEAT);
|
||||
|
||||
prim->materialInstance->setParameter("morphTargets", prim->texture, TextureSampler());
|
||||
float weights[prim->numTargets];
|
||||
memset(weights, 0, prim->numTargets * sizeof(float));
|
||||
prim->materialInstance->setParameter("morphTargetWeights", weights, prim->numTargets);
|
||||
}
|
||||
}
|
||||
|
||||
void GPUMorphHelper::applyWeights(float const *weights, size_t count) noexcept {
|
||||
for(auto& prim : animatablePrimitives) {
|
||||
prim->materialInstance->setParameter("morphTargetWeights", weights, count);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
GPUMorphHelper::addPrimitive(cgltf_mesh const *mesh, int primitiveIndex) {
|
||||
auto &engine = *mAsset->mEngine;
|
||||
const cgltf_primitive &prim = mesh->primitives[primitiveIndex];
|
||||
|
||||
const auto &gltfioPrim = mAsset->mMeshCache.at(mesh)[primitiveIndex];
|
||||
VertexBuffer *vertexBuffer = gltfioPrim.vertices;
|
||||
std::unique_ptr<GltfPrimitive> animatedPrimitive = std::make_unique<GltfPrimitive>(GltfPrimitive{vertexBuffer});
|
||||
|
||||
animatedPrimitive->materialName = prim.material->name;
|
||||
animatedPrimitive->numTargets = prim.targets_count;
|
||||
animatedPrimitive->numVertices = vertexBuffer->getVertexCount();
|
||||
|
||||
std::cout << "Found " << animatedPrimitive->numVertices << " vertices in primitive" << std::endl;
|
||||
cgltf_size maxIndex = 0;
|
||||
for(int i = 0; i < prim.indices->count; i++) {
|
||||
maxIndex = std::max(cgltf_accessor_read_index(prim.indices, i), maxIndex);
|
||||
}
|
||||
|
||||
const cgltf_accessor *previous = nullptr;
|
||||
|
||||
// iterate over every target for the primitive,
|
||||
for (int targetIndex = 0; targetIndex < prim.targets_count; targetIndex++) {
|
||||
const cgltf_morph_target &morphTarget = prim.targets[targetIndex];
|
||||
for (cgltf_size aindex = 0; aindex < morphTarget.attributes_count; aindex++) {
|
||||
const cgltf_attribute &attribute = morphTarget.attributes[aindex];
|
||||
const cgltf_accessor *accessor = attribute.data;
|
||||
const cgltf_attribute_type atype = attribute.type;
|
||||
if (atype == cgltf_attribute_type_tangent) {
|
||||
continue;
|
||||
}
|
||||
if (atype == cgltf_attribute_type_position || numAttributes > 1 && atype == cgltf_attribute_type_normal) {
|
||||
assert_invariant(
|
||||
!previous || previous->component_type == accessor->component_type);
|
||||
assert_invariant(!previous || previous->type == accessor->type);
|
||||
previous = accessor;
|
||||
|
||||
// This should always be non-null, but don't crash if the glTF is malformed.
|
||||
if (accessor->buffer_view) {
|
||||
auto bufferData = (const uint8_t *) accessor->buffer_view->buffer->data;
|
||||
assert_invariant(bufferData);
|
||||
const uint8_t *data = computeBindingOffset(accessor) + bufferData;
|
||||
const uint32_t size = computeBindingSize(accessor);
|
||||
|
||||
animatedPrimitive->targets.push_back({data, size, targetIndex, atype});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
animatablePrimitives.push_back(std::move(animatedPrimitive));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// assert(
|
||||
// FTexture::validatePixelFormatAndType(
|
||||
// backend::TextureFormat::RGB32F,
|
||||
// backend::PixelDataFormat::RGB,
|
||||
// backend::PixelDataType::FLOAT));
|
||||
|
||||
// namespace filament {
|
||||
|
||||
// class FEngine;
|
||||
// class FStream;
|
||||
|
||||
// class FTexture : public Texture {
|
||||
// public:
|
||||
// FTexture(FEngine& engine, const Builder& builder);
|
||||
|
||||
// // frees driver resources, object becomes invalid
|
||||
// void terminate(FEngine& engine);
|
||||
|
||||
// backend::Handle<backend::HwTexture> getHwHandle() const noexcept { return mHandle; }
|
||||
|
||||
// size_t getWidth(size_t level = 0) const noexcept;
|
||||
// size_t getHeight(size_t level = 0) const noexcept;
|
||||
// size_t getDepth(size_t level = 0) const noexcept;
|
||||
// size_t getLevelCount() const noexcept { return mLevelCount; }
|
||||
// size_t getMaxLevelCount() const noexcept { return FTexture::maxLevelCount(mWidth, mHeight); }
|
||||
// Sampler getTarget() const noexcept { return mTarget; }
|
||||
// InternalFormat getFormat() const noexcept { return mFormat; }
|
||||
// Usage getUsage() const noexcept { return mUsage; }
|
||||
|
||||
// void setImage(FEngine& engine, size_t level,
|
||||
// uint32_t xoffset, uint32_t yoffset, uint32_t width, uint32_t height,
|
||||
// PixelBufferDescriptor&& buffer) const;
|
||||
|
||||
// void setImage(FEngine& engine, size_t level,
|
||||
// uint32_t xoffset, uint32_t yoffset, uint32_t zoffset,
|
||||
// uint32_t width, uint32_t height, uint32_t depth,
|
||||
// PixelBufferDescriptor&& buffer) const;
|
||||
|
||||
// void setImage(FEngine& engine, size_t level,
|
||||
// PixelBufferDescriptor&& buffer, const FaceOffsets& faceOffsets) const;
|
||||
|
||||
// void generatePrefilterMipmap(FEngine& engine,
|
||||
// PixelBufferDescriptor&& buffer, const FaceOffsets& faceOffsets,
|
||||
// PrefilterOptions const* options);
|
||||
|
||||
// void setExternalImage(FEngine& engine, void* image) noexcept;
|
||||
// void setExternalImage(FEngine& engine, void* image, size_t plane) noexcept;
|
||||
// void setExternalStream(FEngine& engine, FStream* stream) noexcept;
|
||||
|
||||
// void generateMipmaps(FEngine& engine) const noexcept;
|
||||
|
||||
// void setSampleCount(size_t sampleCount) noexcept { mSampleCount = uint8_t(sampleCount); }
|
||||
// size_t getSampleCount() const noexcept { return mSampleCount; }
|
||||
// bool isMultisample() const noexcept { return mSampleCount > 1; }
|
||||
// bool isCompressed() const noexcept { return backend::isCompressedFormat(mFormat); }
|
||||
|
||||
// bool isCubemap() const noexcept { return mTarget == Sampler::SAMPLER_CUBEMAP; }
|
||||
|
||||
// FStream const* getStream() const noexcept { return mStream; }
|
||||
|
||||
// /*
|
||||
// * Utilities
|
||||
// */
|
||||
|
||||
// // synchronous call to the backend. returns whether a backend supports a particular format.
|
||||
// static bool isTextureFormatSupported(FEngine& engine, InternalFormat format) noexcept;
|
||||
|
||||
// // synchronous call to the backend. returns whether a backend supports texture swizzling.
|
||||
// static bool isTextureSwizzleSupported(FEngine& engine) noexcept;
|
||||
|
||||
// // storage needed on the CPU side for texture data uploads
|
||||
// static size_t computeTextureDataSize(Texture::Format format, Texture::Type type,
|
||||
// size_t stride, size_t height, size_t alignment) noexcept;
|
||||
|
||||
// // Size a of a pixel in bytes for the given format
|
||||
// static size_t getFormatSize(InternalFormat format) noexcept;
|
||||
|
||||
// // Returns the with or height for a given mipmap level from the base value.
|
||||
// static inline size_t valueForLevel(uint8_t level, size_t baseLevelValue) {
|
||||
// return std::max(size_t(1), baseLevelValue >> level);
|
||||
// }
|
||||
|
||||
// // Returns the max number of levels for a texture of given max dimensions
|
||||
// static inline uint8_t maxLevelCount(uint32_t maxDimension) noexcept {
|
||||
// return std::max(1, std::ilogbf(maxDimension) + 1);
|
||||
// }
|
||||
|
||||
// // Returns the max number of levels for a texture of given dimensions
|
||||
// static inline uint8_t maxLevelCount(uint32_t width, uint32_t height) noexcept {
|
||||
// return std::max(1, std::ilogbf(std::max(width, height)) + 1);
|
||||
// }
|
||||
|
||||
// static bool validatePixelFormatAndType(backend::TextureFormat internalFormat,
|
||||
// backend::PixelDataFormat format, backend::PixelDataType type) noexcept;
|
||||
|
||||
// private:
|
||||
// friend class Texture;
|
||||
// FStream* mStream = nullptr;
|
||||
// backend::Handle<backend::HwTexture> mHandle;
|
||||
// uint32_t mWidth = 1;
|
||||
// uint32_t mHeight = 1;
|
||||
// uint32_t mDepth = 1;
|
||||
// InternalFormat mFormat = InternalFormat::RGBA8;
|
||||
// Sampler mTarget = Sampler::SAMPLER_2D;
|
||||
// uint8_t mLevelCount = 1;
|
||||
// uint8_t mSampleCount = 1;
|
||||
// Usage mUsage = Usage::DEFAULT;
|
||||
// };
|
||||
|
||||
|
||||
// } // namespace filament
|
||||
@@ -1,299 +0,0 @@
|
||||
#include <gltfio/MaterialProvider.h>
|
||||
|
||||
#include <filamat/MaterialBuilder.h>
|
||||
#include <filament/MaterialInstance.h>
|
||||
#include <filament/Texture.h>
|
||||
#include <filament/TextureSampler.h>
|
||||
|
||||
#include <math/mat4.h>
|
||||
|
||||
#include <utils/Log.h>
|
||||
#include <iostream>
|
||||
|
||||
#include "gltfio/resources/gltfresources_lite.h"
|
||||
|
||||
using namespace filament;
|
||||
using namespace filament::math;
|
||||
using namespace gltfio;
|
||||
using namespace utils;
|
||||
|
||||
namespace {
|
||||
|
||||
using CullingMode = MaterialInstance::CullingMode;
|
||||
|
||||
class GPUMorphShaderLoader : public MaterialProvider {
|
||||
public:
|
||||
GPUMorphShaderLoader(
|
||||
const void* opaqueMaterial,
|
||||
uint64_t opaqueMaterialSize,
|
||||
const void* fadeMaterial,
|
||||
uint64_t fadeMaterialSize,
|
||||
filament::Engine* engine);
|
||||
~GPUMorphShaderLoader() {}
|
||||
|
||||
MaterialInstance* createMaterialInstance(MaterialKey* config, UvMap* uvmap,
|
||||
const char* label) override;
|
||||
|
||||
size_t getMaterialsCount() const noexcept override;
|
||||
const Material* const* getMaterials() const noexcept override;
|
||||
void destroyMaterials() override;
|
||||
|
||||
bool needsDummyData(VertexAttribute attrib) const noexcept override {
|
||||
switch (attrib) {
|
||||
case VertexAttribute::UV0:
|
||||
case VertexAttribute::UV1:
|
||||
case VertexAttribute::COLOR:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const void* opaqueData;
|
||||
const size_t opaqueDataSize;
|
||||
const void* fadeData;
|
||||
const size_t fadeDataSize;
|
||||
|
||||
Material* getMaterial(const MaterialKey& config) const;
|
||||
|
||||
enum ShadingMode {
|
||||
UNLIT = 0,
|
||||
LIT = 1,
|
||||
SPECULAR_GLOSSINESS = 2,
|
||||
};
|
||||
|
||||
mutable Material* mMaterials[12] = {};
|
||||
Texture* mDummyTexture = nullptr;
|
||||
|
||||
Engine* mEngine;
|
||||
};
|
||||
|
||||
|
||||
#define MATINDEX(shading, alpha, sheen, transmit, volume) (volume ? 11 : (transmit ? 10 : (sheen ? 9 : (int(shading) + 3 * int(alpha)))))
|
||||
|
||||
|
||||
GPUMorphShaderLoader::GPUMorphShaderLoader(const void* opaqueData,
|
||||
uint64_t opaqueDataSize,
|
||||
const void* fadeData,
|
||||
uint64_t fadeDataSize,
|
||||
Engine* engine) : opaqueData(opaqueData), opaqueDataSize(opaqueDataSize), fadeData(fadeData), fadeDataSize(fadeDataSize), mEngine(engine) {
|
||||
|
||||
// unsigned char texels[4] = {};
|
||||
// mDummyTexture = Texture::Builder()
|
||||
// .width(1)
|
||||
// .height(1)
|
||||
// .format(backend::TextureFormat::RGBA8)
|
||||
// .sampler(backend::SamplerType::SAMPLER_2D_ARRAY)
|
||||
// .build(*mEngine);
|
||||
// Texture::PixelBufferDescriptor pbd(
|
||||
// texels,
|
||||
// sizeof(texels),
|
||||
// backend::PixelDataFormat::RGBA,
|
||||
// backend::PixelDataType::UBYTE,
|
||||
// nullptr);
|
||||
// mDummyTexture->setImage(*mEngine, 0,0,0,0,0,0,0,std::move(pbd));
|
||||
unsigned char texels[4] = {};
|
||||
mDummyTexture = Texture::Builder()
|
||||
.width(1).height(1)
|
||||
.format(Texture::InternalFormat::RGBA8)
|
||||
.build(*mEngine);
|
||||
Texture::PixelBufferDescriptor pbd(texels, sizeof(texels), Texture::Format::RGBA,
|
||||
Texture::Type::UBYTE);
|
||||
mDummyTexture->setImage(*mEngine, 0, std::move(pbd));
|
||||
}
|
||||
|
||||
|
||||
size_t GPUMorphShaderLoader::getMaterialsCount() const noexcept {
|
||||
return sizeof(mMaterials) / sizeof(mMaterials[0]);
|
||||
}
|
||||
|
||||
const Material* const* GPUMorphShaderLoader::getMaterials() const noexcept {
|
||||
return &mMaterials[0];
|
||||
}
|
||||
|
||||
void GPUMorphShaderLoader::destroyMaterials() {
|
||||
for (auto& material : mMaterials) {
|
||||
mEngine->destroy(material);
|
||||
material = nullptr;
|
||||
}
|
||||
mEngine->destroy(mDummyTexture);
|
||||
}
|
||||
|
||||
Material* GPUMorphShaderLoader::getMaterial(const MaterialKey& config) const {
|
||||
const ShadingMode shading = config.unlit ? UNLIT :
|
||||
(config.useSpecularGlossiness ? SPECULAR_GLOSSINESS : LIT);
|
||||
|
||||
const int matindex = MATINDEX(shading, config.alphaMode, config.hasSheen, config.hasTransmission, config.hasVolume);
|
||||
if (mMaterials[matindex] != nullptr) {
|
||||
return mMaterials[matindex];
|
||||
}
|
||||
switch (matindex) {
|
||||
case MATINDEX(LIT, AlphaMode::OPAQUE, false, false, false):
|
||||
{
|
||||
filamat::Package pkg = filamat::Package(opaqueData, opaqueDataSize);
|
||||
mMaterials[matindex] = Material::Builder().package(pkg.getData(), pkg.getSize()).build(*mEngine);
|
||||
}
|
||||
break;
|
||||
case MATINDEX(LIT, AlphaMode::BLEND, false, false, false):
|
||||
{
|
||||
filamat::Package pkg = filamat::Package(fadeData, fadeDataSize);
|
||||
mMaterials[matindex] = Material::Builder().package(pkg.getData(), pkg.getSize()).build(*mEngine);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
{
|
||||
filamat::Package pkg = filamat::Package(fadeData, fadeDataSize);
|
||||
mMaterials[matindex] = Material::Builder().package(pkg.getData(), pkg.getSize()).build(*mEngine);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return mMaterials[matindex];
|
||||
}
|
||||
|
||||
MaterialInstance* GPUMorphShaderLoader::createMaterialInstance(MaterialKey* config, UvMap* uvmap,
|
||||
const char* label) {
|
||||
// Diagnostics are not supported with LOAD_UBERSHADERS, please use GENERATE_SHADERS instead.
|
||||
if (config->enableDiagnostics) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (config->hasVolume && config->hasSheen) {
|
||||
slog.w << "Volume and sheen are not supported together in ubershader mode,"
|
||||
" removing sheen (" << label << ")." << io::endl;
|
||||
config->hasSheen = false;
|
||||
}
|
||||
|
||||
if (config->hasTransmission && config->hasSheen) {
|
||||
slog.w << "Transmission and sheen are not supported together in ubershader mode,"
|
||||
" removing sheen (" << label << ")." << io::endl;
|
||||
config->hasSheen = false;
|
||||
}
|
||||
|
||||
const bool clearCoatConflict = config->hasVolume || config->hasTransmission || config->hasSheen;
|
||||
|
||||
// Due to sampler overload, disable transmission if necessary and print a friendly warning.
|
||||
if (config->hasClearCoat && clearCoatConflict) {
|
||||
slog.w << "Volume, transmission and sheen are not supported in ubershader mode for clearcoat"
|
||||
" materials (" << label << ")." << io::endl;
|
||||
config->hasVolume = false;
|
||||
config->hasTransmission = false;
|
||||
config->hasSheen = false;
|
||||
}
|
||||
|
||||
constrainMaterial(config, uvmap);
|
||||
auto getUvIndex = [uvmap](uint8_t srcIndex, bool hasTexture) -> int {
|
||||
return hasTexture ? int(uvmap->at(srcIndex)) - 1 : -1;
|
||||
};
|
||||
Material* material = getMaterial(*config);
|
||||
MaterialInstance* mi = material->createInstance(label);
|
||||
mi->setParameter("baseColorIndex",
|
||||
getUvIndex(config->baseColorUV, config->hasBaseColorTexture));
|
||||
mi->setParameter("normalIndex", getUvIndex(config->normalUV, config->hasNormalTexture));
|
||||
mi->setParameter("metallicRoughnessIndex",
|
||||
getUvIndex(config->metallicRoughnessUV, config->hasMetallicRoughnessTexture));
|
||||
mi->setParameter("aoIndex", getUvIndex(config->aoUV, config->hasOcclusionTexture));
|
||||
mi->setParameter("emissiveIndex", getUvIndex(config->emissiveUV, config->hasEmissiveTexture));
|
||||
|
||||
mi->setDoubleSided(config->doubleSided);
|
||||
mi->setCullingMode(config->doubleSided ? CullingMode::NONE : CullingMode::BACK);
|
||||
mi->setTransparencyMode(config->doubleSided ?
|
||||
MaterialInstance::TransparencyMode::TWO_PASSES_TWO_SIDES :
|
||||
MaterialInstance::TransparencyMode::DEFAULT);
|
||||
// Initially, assume that the clear coat texture can be honored. This is changed to false when
|
||||
// running into a sampler count limitation. TODO: check if these constraints can now be relaxed.
|
||||
bool clearCoatNeedsTexture = true;
|
||||
|
||||
mat3f identity;
|
||||
mi->setParameter("baseColorUvMatrix", identity);
|
||||
mi->setParameter("metallicRoughnessUvMatrix", identity);
|
||||
mi->setParameter("normalUvMatrix", identity);
|
||||
mi->setParameter("occlusionUvMatrix", identity);
|
||||
mi->setParameter("emissiveUvMatrix", identity);
|
||||
|
||||
if (config->hasClearCoat) {
|
||||
mi->setParameter("clearCoatIndex",
|
||||
getUvIndex(config->clearCoatUV, config->hasClearCoatTexture));
|
||||
mi->setParameter("clearCoatRoughnessIndex",
|
||||
getUvIndex(config->clearCoatRoughnessUV, config->hasClearCoatRoughnessTexture));
|
||||
mi->setParameter("clearCoatNormalIndex",
|
||||
getUvIndex(config->clearCoatNormalUV, config->hasClearCoatNormalTexture));
|
||||
mi->setParameter("clearCoatUvMatrix", identity);
|
||||
mi->setParameter("clearCoatRoughnessUvMatrix", identity);
|
||||
mi->setParameter("clearCoatNormalUvMatrix", identity);
|
||||
} else {
|
||||
if (config->hasSheen) {
|
||||
clearCoatNeedsTexture = false;
|
||||
mi->setParameter("sheenColorIndex",
|
||||
getUvIndex(config->sheenColorUV, config->hasSheenColorTexture));
|
||||
mi->setParameter("sheenRoughnessIndex",
|
||||
getUvIndex(config->sheenRoughnessUV, config->hasSheenRoughnessTexture));
|
||||
mi->setParameter("sheenColorUvMatrix", identity);
|
||||
mi->setParameter("sheenRoughnessUvMatrix", identity);
|
||||
}
|
||||
if (config->hasVolume) {
|
||||
clearCoatNeedsTexture = false;
|
||||
mi->setParameter("volumeThicknessUvMatrix", identity);
|
||||
mi->setParameter("volumeThicknessIndex",
|
||||
getUvIndex(config->transmissionUV, config->hasVolumeThicknessTexture));
|
||||
}
|
||||
if (config->hasTransmission) {
|
||||
clearCoatNeedsTexture = false;
|
||||
mi->setParameter("transmissionUvMatrix", identity);
|
||||
mi->setParameter("transmissionIndex",
|
||||
getUvIndex(config->transmissionUV, config->hasTransmissionTexture));
|
||||
}
|
||||
}
|
||||
|
||||
TextureSampler sampler;
|
||||
mi->setParameter("normalMap", mDummyTexture, sampler);
|
||||
mi->setParameter("baseColorMap", mDummyTexture, sampler);
|
||||
mi->setParameter("metallicRoughnessMap", mDummyTexture, sampler);
|
||||
// mi->setParameter("roughnessFactor", mDummyTexture, sampler);
|
||||
|
||||
mi->setParameter("occlusionMap", mDummyTexture, sampler);
|
||||
mi->setParameter("emissiveMap", mDummyTexture, sampler);
|
||||
if (clearCoatNeedsTexture) {
|
||||
mi->setParameter("clearCoatMap", mDummyTexture, sampler);
|
||||
mi->setParameter("clearCoatRoughnessMap", mDummyTexture, sampler);
|
||||
mi->setParameter("clearCoatNormalMap", mDummyTexture, sampler);
|
||||
}
|
||||
if (!config->hasClearCoat) {
|
||||
if (config->hasTransmission) {
|
||||
mi->setParameter("transmissionMap", mDummyTexture, sampler);
|
||||
}
|
||||
if (config->hasSheen) {
|
||||
mi->setParameter("sheenColorMap", mDummyTexture, sampler);
|
||||
mi->setParameter("sheenRoughnessMap", mDummyTexture, sampler);
|
||||
}
|
||||
}
|
||||
|
||||
if (mi->getMaterial()->hasParameter("ior")) {
|
||||
mi->setParameter("ior", 1.5f);
|
||||
}
|
||||
if (mi->getMaterial()->hasParameter("reflectance")) {
|
||||
mi->setParameter("reflectance", 0.5f);
|
||||
}
|
||||
|
||||
return mi;
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
namespace gltfio {
|
||||
|
||||
MaterialProvider* createGPUMorphShaderLoader(
|
||||
const void* opaqueData,
|
||||
uint64_t opaqueDataSize,
|
||||
const void* fadeData,
|
||||
uint64_t fadeDataSize,
|
||||
filament::Engine* engine) {
|
||||
return new GPUMorphShaderLoader(
|
||||
opaqueData,
|
||||
opaqueDataSize,
|
||||
fadeData,
|
||||
fadeDataSize,
|
||||
engine);
|
||||
}
|
||||
|
||||
} // namespace gltfio
|
||||
|
||||
@@ -1,308 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <gltfio/MaterialProvider.h>
|
||||
|
||||
#include <filament/MaterialInstance.h>
|
||||
#include <filament/Texture.h>
|
||||
#include <filament/TextureSampler.h>
|
||||
|
||||
#include <math/mat4.h>
|
||||
|
||||
#include <utils/Log.h>
|
||||
|
||||
#include "gltfio/resources/gltfresources.h"
|
||||
|
||||
using namespace filament;
|
||||
using namespace filament::math;
|
||||
using namespace gltfio;
|
||||
using namespace utils;
|
||||
|
||||
namespace {
|
||||
|
||||
using CullingMode = MaterialInstance::CullingMode;
|
||||
|
||||
class UbershaderLoader : public MaterialProvider {
|
||||
public:
|
||||
UbershaderLoader(filament::Engine* engine);
|
||||
~UbershaderLoader() {}
|
||||
|
||||
MaterialInstance* createMaterialInstance(MaterialKey* config, UvMap* uvmap,
|
||||
const char* label) override;
|
||||
|
||||
size_t getMaterialsCount() const noexcept override;
|
||||
const Material* const* getMaterials() const noexcept override;
|
||||
void destroyMaterials() override;
|
||||
|
||||
bool needsDummyData(VertexAttribute attrib) const noexcept override {
|
||||
switch (attrib) {
|
||||
case VertexAttribute::UV0:
|
||||
case VertexAttribute::UV1:
|
||||
case VertexAttribute::COLOR:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Material* getMaterial(const MaterialKey& config) const;
|
||||
|
||||
enum ShadingMode {
|
||||
UNLIT = 0,
|
||||
LIT = 1,
|
||||
SPECULAR_GLOSSINESS = 2,
|
||||
};
|
||||
|
||||
mutable Material* mMaterials[12] = {};
|
||||
Texture* mDummyTexture = nullptr;
|
||||
|
||||
Engine* mEngine;
|
||||
};
|
||||
|
||||
#if GLTFIO_LITE
|
||||
|
||||
#define CREATE_MATERIAL(name) Material::Builder() \
|
||||
.package(GLTFRESOURCES_LITE_ ## name ## _DATA, GLTFRESOURCES_LITE_ ## name ## _SIZE) \
|
||||
.build(*mEngine);
|
||||
|
||||
#else
|
||||
|
||||
#define CREATE_MATERIAL(name) Material::Builder() \
|
||||
.package(GLTFRESOURCES_ ## name ## _DATA, GLTFRESOURCES_ ## name ## _SIZE) \
|
||||
.build(*mEngine);
|
||||
|
||||
#endif
|
||||
|
||||
#define MATINDEX(shading, alpha, sheen, transmit, volume) (volume ? 11 : (transmit ? 10 : (sheen ? 9 : (int(shading) + 3 * int(alpha)))))
|
||||
|
||||
UbershaderLoader::UbershaderLoader(Engine* engine) : mEngine(engine) {
|
||||
unsigned char texels[4] = {};
|
||||
mDummyTexture = Texture::Builder()
|
||||
.width(1).height(1)
|
||||
.format(Texture::InternalFormat::RGBA8)
|
||||
.build(*mEngine);
|
||||
Texture::PixelBufferDescriptor pbd(texels, sizeof(texels), Texture::Format::RGBA,
|
||||
Texture::Type::UBYTE);
|
||||
mDummyTexture->setImage(*mEngine, 0, std::move(pbd));
|
||||
}
|
||||
|
||||
size_t UbershaderLoader::getMaterialsCount() const noexcept {
|
||||
return sizeof(mMaterials) / sizeof(mMaterials[0]);
|
||||
}
|
||||
|
||||
const Material* const* UbershaderLoader::getMaterials() const noexcept {
|
||||
return &mMaterials[0];
|
||||
}
|
||||
|
||||
void UbershaderLoader::destroyMaterials() {
|
||||
for (auto& material : mMaterials) {
|
||||
mEngine->destroy(material);
|
||||
material = nullptr;
|
||||
}
|
||||
mEngine->destroy(mDummyTexture);
|
||||
}
|
||||
|
||||
Material* UbershaderLoader::getMaterial(const MaterialKey& config) const {
|
||||
const ShadingMode shading = config.unlit ? UNLIT :
|
||||
(config.useSpecularGlossiness ? SPECULAR_GLOSSINESS : LIT);
|
||||
const int matindex = MATINDEX(shading, config.alphaMode, config.hasSheen, config.hasTransmission, config.hasVolume);
|
||||
if (mMaterials[matindex] != nullptr) {
|
||||
return mMaterials[matindex];
|
||||
}
|
||||
switch (matindex) {
|
||||
|
||||
case MATINDEX(LIT, AlphaMode::OPAQUE, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(LIT_OPAQUE); break;
|
||||
|
||||
|
||||
|
||||
case MATINDEX(LIT, AlphaMode::BLEND, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(LIT_FADE); break;
|
||||
|
||||
|
||||
|
||||
case MATINDEX(LIT, AlphaMode::MASK, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(LIT_MASKED); break;
|
||||
case MATINDEX(UNLIT, AlphaMode::OPAQUE, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(UNLIT_OPAQUE); break;
|
||||
case MATINDEX(UNLIT, AlphaMode::MASK, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(UNLIT_MASKED); break;
|
||||
case MATINDEX(UNLIT, AlphaMode::BLEND, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(UNLIT_FADE); break;
|
||||
case MATINDEX(SPECULAR_GLOSSINESS, AlphaMode::OPAQUE, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(SPECULARGLOSSINESS_OPAQUE); break;
|
||||
case MATINDEX(SPECULAR_GLOSSINESS, AlphaMode::MASK, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(SPECULARGLOSSINESS_MASKED); break;
|
||||
case MATINDEX(SPECULAR_GLOSSINESS, AlphaMode::BLEND, false, false, false): mMaterials[matindex] = CREATE_MATERIAL(SPECULARGLOSSINESS_FADE); break;
|
||||
case MATINDEX(0, 0, false, true, false): mMaterials[matindex] = CREATE_MATERIAL(LIT_TRANSMISSION); break;
|
||||
case MATINDEX(0, 0, true, false, false): mMaterials[matindex] = CREATE_MATERIAL(LIT_SHEEN); break;
|
||||
case MATINDEX(0, 0, false, false, true): mMaterials[matindex] = CREATE_MATERIAL(LIT_VOLUME); break;
|
||||
|
||||
}
|
||||
if (mMaterials[matindex] == nullptr) {
|
||||
slog.w << "Unsupported glTF material configuration; falling back to LIT_OPAQUE." << io::endl;
|
||||
MaterialKey litOpaque = config;
|
||||
litOpaque.alphaMode = AlphaMode::OPAQUE;
|
||||
litOpaque.hasTransmission = false;
|
||||
litOpaque.hasVolume = false;
|
||||
litOpaque.hasSheen = false;
|
||||
litOpaque.useSpecularGlossiness = false;
|
||||
litOpaque.unlit = false;
|
||||
return getMaterial(litOpaque);
|
||||
}
|
||||
|
||||
return mMaterials[matindex];
|
||||
}
|
||||
|
||||
MaterialInstance* UbershaderLoader::createMaterialInstance(MaterialKey* config, UvMap* uvmap,
|
||||
const char* label) {
|
||||
// Diagnostics are not supported with LOAD_UBERSHADERS, please use GENERATE_SHADERS instead.
|
||||
if (config->enableDiagnostics) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (config->hasVolume && config->hasSheen) {
|
||||
slog.w << "Volume and sheen are not supported together in ubershader mode,"
|
||||
" removing sheen (" << label << ")." << io::endl;
|
||||
config->hasSheen = false;
|
||||
}
|
||||
|
||||
if (config->hasTransmission && config->hasSheen) {
|
||||
slog.w << "Transmission and sheen are not supported together in ubershader mode,"
|
||||
" removing sheen (" << label << ")." << io::endl;
|
||||
config->hasSheen = false;
|
||||
}
|
||||
|
||||
const bool clearCoatConflict = config->hasVolume || config->hasTransmission || config->hasSheen;
|
||||
|
||||
// Due to sampler overload, disable transmission if necessary and print a friendly warning.
|
||||
if (config->hasClearCoat && clearCoatConflict) {
|
||||
slog.w << "Volume, transmission and sheen are not supported in ubershader mode for clearcoat"
|
||||
" materials (" << label << ")." << io::endl;
|
||||
config->hasVolume = false;
|
||||
config->hasTransmission = false;
|
||||
config->hasSheen = false;
|
||||
}
|
||||
|
||||
constrainMaterial(config, uvmap);
|
||||
auto getUvIndex = [uvmap](uint8_t srcIndex, bool hasTexture) -> int {
|
||||
return hasTexture ? int(uvmap->at(srcIndex)) - 1 : -1;
|
||||
};
|
||||
Material* material = getMaterial(*config);
|
||||
MaterialInstance* mi = material->createInstance(label);
|
||||
mi->setParameter("baseColorIndex",
|
||||
getUvIndex(config->baseColorUV, config->hasBaseColorTexture));
|
||||
mi->setParameter("normalIndex", getUvIndex(config->normalUV, config->hasNormalTexture));
|
||||
mi->setParameter("metallicRoughnessIndex",
|
||||
getUvIndex(config->metallicRoughnessUV, config->hasMetallicRoughnessTexture));
|
||||
mi->setParameter("aoIndex", getUvIndex(config->aoUV, config->hasOcclusionTexture));
|
||||
mi->setParameter("emissiveIndex", getUvIndex(config->emissiveUV, config->hasEmissiveTexture));
|
||||
|
||||
mi->setDoubleSided(config->doubleSided);
|
||||
mi->setCullingMode(config->doubleSided ? CullingMode::NONE : CullingMode::BACK);
|
||||
mi->setTransparencyMode(config->doubleSided ?
|
||||
MaterialInstance::TransparencyMode::TWO_PASSES_TWO_SIDES :
|
||||
MaterialInstance::TransparencyMode::DEFAULT);
|
||||
|
||||
#if !GLTFIO_LITE
|
||||
|
||||
// Initially, assume that the clear coat texture can be honored. This is changed to false when
|
||||
// running into a sampler count limitation. TODO: check if these constraints can now be relaxed.
|
||||
bool clearCoatNeedsTexture = true;
|
||||
|
||||
mat3f identity;
|
||||
mi->setParameter("baseColorUvMatrix", identity);
|
||||
mi->setParameter("metallicRoughnessUvMatrix", identity);
|
||||
mi->setParameter("normalUvMatrix", identity);
|
||||
mi->setParameter("occlusionUvMatrix", identity);
|
||||
mi->setParameter("emissiveUvMatrix", identity);
|
||||
|
||||
if (config->hasClearCoat) {
|
||||
mi->setParameter("clearCoatIndex",
|
||||
getUvIndex(config->clearCoatUV, config->hasClearCoatTexture));
|
||||
mi->setParameter("clearCoatRoughnessIndex",
|
||||
getUvIndex(config->clearCoatRoughnessUV, config->hasClearCoatRoughnessTexture));
|
||||
mi->setParameter("clearCoatNormalIndex",
|
||||
getUvIndex(config->clearCoatNormalUV, config->hasClearCoatNormalTexture));
|
||||
mi->setParameter("clearCoatUvMatrix", identity);
|
||||
mi->setParameter("clearCoatRoughnessUvMatrix", identity);
|
||||
mi->setParameter("clearCoatNormalUvMatrix", identity);
|
||||
} else {
|
||||
if (config->hasSheen) {
|
||||
clearCoatNeedsTexture = false;
|
||||
mi->setParameter("sheenColorIndex",
|
||||
getUvIndex(config->sheenColorUV, config->hasSheenColorTexture));
|
||||
mi->setParameter("sheenRoughnessIndex",
|
||||
getUvIndex(config->sheenRoughnessUV, config->hasSheenRoughnessTexture));
|
||||
mi->setParameter("sheenColorUvMatrix", identity);
|
||||
mi->setParameter("sheenRoughnessUvMatrix", identity);
|
||||
|
||||
}
|
||||
if (config->hasVolume) {
|
||||
clearCoatNeedsTexture = false;
|
||||
mi->setParameter("volumeThicknessUvMatrix", identity);
|
||||
mi->setParameter("volumeThicknessIndex",
|
||||
getUvIndex(config->transmissionUV, config->hasVolumeThicknessTexture));
|
||||
}
|
||||
if (config->hasTransmission) {
|
||||
clearCoatNeedsTexture = false;
|
||||
mi->setParameter("transmissionUvMatrix", identity);
|
||||
mi->setParameter("transmissionIndex",
|
||||
getUvIndex(config->transmissionUV, config->hasTransmissionTexture));
|
||||
}
|
||||
}
|
||||
#else
|
||||
|
||||
// In the GLTFIO_LITE configuration we do not support UV matrices, clear coat, sheen, specular
|
||||
// glossiness, or transmission. For more details, see `gltflite.mat.in`. To configure a custom
|
||||
// set of features, create your own MaterialProvider class, perhaps using UbershaderLoader as a
|
||||
// starting point.
|
||||
const bool clearCoatNeedsTexture = false;
|
||||
|
||||
#endif
|
||||
|
||||
TextureSampler sampler;
|
||||
mi->setParameter("normalMap", mDummyTexture, sampler);
|
||||
mi->setParameter("baseColorMap", mDummyTexture, sampler);
|
||||
mi->setParameter("metallicRoughnessMap", mDummyTexture, sampler);
|
||||
mi->setParameter("occlusionMap", mDummyTexture, sampler);
|
||||
mi->setParameter("emissiveMap", mDummyTexture, sampler);
|
||||
if (clearCoatNeedsTexture) {
|
||||
mi->setParameter("clearCoatMap", mDummyTexture, sampler);
|
||||
mi->setParameter("clearCoatRoughnessMap", mDummyTexture, sampler);
|
||||
mi->setParameter("clearCoatNormalMap", mDummyTexture, sampler);
|
||||
}
|
||||
if (!config->hasClearCoat) {
|
||||
if (config->hasTransmission) {
|
||||
mi->setParameter("transmissionMap", mDummyTexture, sampler);
|
||||
}
|
||||
if (config->hasSheen) {
|
||||
mi->setParameter("sheenColorMap", mDummyTexture, sampler);
|
||||
mi->setParameter("sheenRoughnessMap", mDummyTexture, sampler);
|
||||
}
|
||||
}
|
||||
|
||||
if (mi->getMaterial()->hasParameter("ior")) {
|
||||
mi->setParameter("ior", 1.5f);
|
||||
}
|
||||
if (mi->getMaterial()->hasParameter("reflectance")) {
|
||||
mi->setParameter("reflectance", 0.5f);
|
||||
}
|
||||
|
||||
return mi;
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
namespace foo {
|
||||
|
||||
MaterialProvider* createUbershaderLoader(filament::Engine* engine) {
|
||||
return new UbershaderLoader(engine);
|
||||
}
|
||||
|
||||
} // namespace gltfio
|
||||
Reference in New Issue
Block a user