1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
| GameObject* ModelLoader::loadModel(std::string path, bool loadTextures) {
//std::cout<<"load model : "<<path<<std::endl;
Model* model = new Model(math::Vec3f(0.f, 0.f, 0.f), math::Vec3f(0.f, 0.f, 0.f),math::Vec3f(0.f, 0.f, 0.f), "E_MODEL");
Assimp::Importer importer;
//std::cout<<"import"<<std::endl;
const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate |
/*aiProcess_JoinIdenticalVertices |
aiProcess_SortByPType |
aiProcess_GenNormals |
aiProcess_ImproveCacheLocality |
aiProcess_OptimizeMeshes |
aiProcess_OptimizeGraph |
aiProcess_GlobalScale |*/
aiProcess_FlipUVs);
//std::cout<<"imported"<<std::endl;
if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
std::cerr << "ERROR::ASSIMP::" << importer.GetErrorString() << std::endl;
return model;
}
if(path.find("/") != std::string::npos)
directory = path.substr(0, path.find_last_of('/'));
else
directory = "";
math::Matrix4f transform;
transform.identity();
clk2.restart();
processNode(transform, scene->mRootNode, scene, model, loadTextures);
//Material::updateIds();
std::vector<ImageLoader> imageLoaders;
size_t totalImagesSize = 0;
for (unsigned int i = 0; i < textureManager.getAliases().size(); i++) {
std::string alias = textureManager.getAliases()[i];
ImageLoader imageLoader;
if (textureManager.getAliases()[i].length() > 0 && textureManager.getAliases()[i].at(0) == '*') {
//std::cout<<"load texture from memory!"<<std::endl;
int index = atoi(textureManager.getAliases()[i].data() + 1);
aiTexture* tex = scene->mTextures[index];
//std::cout<<"enqueue!"<<std::endl;
imageLoader.loadFromMemory(tex->pcData, tex->mWidth);
} else {
imageLoader.loadFromFile(alias);
}
/*std::cout << "Texture " << i
<<" size=" << imageLoaders[i].getDataSize()
<<" w=" << imageLoaders[i].getSize().x()
<<" h=" << imageLoaders[i].getSize().y()
<<" offset=" << dataOffset
<<" offset + size : "<<dataOffset+imageLoaders[i].getDataSize()
<<" total image size : "<<totalImagesSize.load()
<< std::endl;*/
Texture* texture = textureManager.getResourceByAlias(alias);
if (imageLoader.isCompressed()) {
texture->setFormat(imageLoader.getVkFormat());
} else {
texture->setFormat(VK_FORMAT_R8G8B8A8_SRGB);
}
texture->setSize(imageLoader.getSize());
texture->create(imageLoader.getSize().x(), imageLoader.getSize().y(),1, imageLoader.getMipLevels());
for (unsigned int j = 0; j < imageLoader.getMipLevels(); j++) {
totalImagesSize = (totalImagesSize + 15) & ~15;
totalImagesSize += imageLoader.getDataSize(j);
}
imageLoaders.push_back(imageLoader);
}
commandPool.beginRecordCommandBuffer(0);
staggingBuffer.create(totalImagesSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_ONLY);
std::size_t dataOffset = 0;
for (unsigned int i = 0; i < imageLoaders.size(); i++) {
//std::cout<<"compressée ? : "<<imageLoaders[i].isCompressed()<<std::endl;
for (unsigned int j = 0; j < imageLoaders[i].getMipLevels(); j++) {
// align offset to 16 bytes
/*for (unsigned int p = 0; p < imageLoaders[i].getDataSize(j); p++) {
std::cout<<"pixel : "<<(int)imageLoaders[i].getPixelsPtr(j)[p]<<std::endl;
}*/
dataOffset = (dataOffset + 15) & ~15;
staggingBuffer.update(imageLoaders[i].getPixelsPtr(j), imageLoaders[i].getDataSize(j), dataOffset);
textureManager.getResourceByAlias(textureManager.getAliases()[i])->update(commandPool, staggingBuffer, imageLoaders[i].getSize(j).x(), imageLoaders[i].getSize(j).y(), 0, 0, dataOffset, j);
/*std::cout << "mip " << j << " size = " << imageLoaders[i].getDataSize(j)
<< " offset : " << dataOffset << std::endl;*/
dataOffset += imageLoaders[i].getDataSize(j);
}
}
commandPool.endRecordCommandBuffer(0);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandPool.getHandle(0);
Device::QueueFamilyIndices indices = device.findQueueFamilies(device.getPhysicalDevice());
if (vkQueueSubmit(device.getQueue(indices.graphicsFamily.value(), 0), 1, &submitInfo, VK_NULL_HANDLE) != VK_SUCCESS) {
throw std::runtime_error("Echec de l'envoi d'un command buffer!");
}
vkDeviceWaitIdle(device.getDevice());
std::cout<<"scene loading time : "<<clk2.getElapsedTime().asMilliseconds()<<"ms"<<std::endl;
return model;
}
void ModelLoader::processNode(math::Matrix4f parentTransform, aiNode *node, const aiScene *scene, Model* model, bool loadTextures)
{
//std::cout<<"process node"<<std::endl;
// process all the node's meshes (if any)
math::Matrix4f nodeLocal = AssimpHelpers::convertAssimpToODFAEGMatrix(node->mTransformation);
math::Matrix4f world = parentTransform * nodeLocal;
//std::cout<<"parent : "<<parentTransform<<std::endl<<"node : "<<nodeLocal<<std::endl;
//std::cout<<"nb meshes to load : "<<node->mNumMeshes<<std::endl;
clk.restart();
jobFence.reset(node->mNumMeshes);
for(unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
threadPool.enqueue([this, world, mesh, node, scene, model, loadTextures] {
processMesh(world, node, mesh, scene, model, loadTextures);
jobFence.jobDone();
});
}
jobFence.wait();
//std::cout<<"loading meshes time : "<<clk.getElapsedTime().asMilliseconds()<<"ms"<<std::endl;
// then do the same for each of its children
for(unsigned int i = 0; i < node->mNumChildren; i++)
{
processNode(world, node->mChildren[i], scene, model, loadTextures);
}
}
void ModelLoader::processMesh(math::Matrix4f world, aiNode* node, aiMesh *mesh, const aiScene *scene, Model* model, bool loadTextures) {
//world = world.transpose();
//std::lock_guard<std::recursive_mutex> lock(rec_mutex);
SubMesh subMesh(device);
for (unsigned int i = 0; i < Material::NBTEXTYPES; i++)
subMesh.getMaterial().setTexture(nullptr, static_cast<Material::TexType>(i));
if(mesh->mMaterialIndex >= 0) {
//std::cout<<"load materials"<<std::endl;
aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
if (loadTextures) {
std::vector<Texture*> diffuseMaps = loadMaterialTextures(scene, material,
aiTextureType_DIFFUSE);
for (unsigned int i = 0; i < diffuseMaps.size(); i++) {
subMesh.getMaterial().setTexture(diffuseMaps[i], Material::DIFFUSE, i);
}
std::vector<Texture*> specularMaps = loadMaterialTextures(scene, material,
aiTextureType_SPECULAR);
for (unsigned int i = 0; i < specularMaps.size(); i++) {
specularMaps[i]->setTexType(Material::SPECULAR);
subMesh.getMaterial().setTexture(specularMaps[i], Material::SPECULAR, i);
}
std::vector<Texture*> normalMaps = loadMaterialTextures(scene, material, aiTextureType_NORMALS);
for (unsigned int i = 0; i < normalMaps.size(); i++) {
//std::cout<<"normals"<<std::endl;
normalMaps[i]->setTexType(Material::NORMAL);
subMesh.getMaterial().setTexture(normalMaps[i], Material::NORMAL,i);
}
std::vector<Texture*> metalnessMaps = loadMaterialTextures(scene, material, aiTextureType_METALNESS);
for (unsigned int i = 0; i < metalnessMaps.size(); i++) {
//std::cout<<"metalness"<<std::endl;
metalnessMaps[i]->setTexType(Material::METALNESS);
subMesh.getMaterial().setTexture(metalnessMaps[i], Material::METALNESS, i);
}
std::vector<Texture*> roughnessMaps = loadMaterialTextures(scene, material, aiTextureType_DIFFUSE_ROUGHNESS);
for (unsigned int i = 0; i < roughnessMaps.size(); i++) {
//std::cout<<"roughness"<<std::endl;
roughnessMaps[i]->setTexType(Material::ROUGHNESS);
subMesh.getMaterial().setTexture(roughnessMaps[i], Material::ROUGHNESS, i);
}
std::vector<Texture*> aoMaps = loadMaterialTextures(scene, material, aiTextureType_AMBIENT_OCCLUSION);
for (unsigned int i = 0; i < aoMaps.size(); i++) {
//std::cout<<"ao"<<std::endl;
aoMaps[i]->setTexType(Material::AO);
subMesh.getMaterial().setTexture(aoMaps[i], Material::AO, i);
}
std::vector<Texture*> emissiveMaps = loadMaterialTextures(scene, material, aiTextureType_EMISSIVE);
for (unsigned int i = 0; i < emissiveMaps.size(); i++) {
//std::cout<<"emissive"<<std::endl;
emissiveMaps[i]->setTexType(Material::EMISSIVE);
subMesh.getMaterial().setTexture(emissiveMaps[i], Material::EMISSIVE, i);
}
}
}
int upAxis = 1;
int upSign = 1;
int frontAxis = 2; // default Z-forward
int frontSign = 1;
int coordAxis = 0; // default X-right
int coordSign = 1;
if (scene->mMetaData) {
scene->mMetaData->Get("UpAxis", upAxis);
scene->mMetaData->Get("UpAxisSign", upSign);
scene->mMetaData->Get("FrontAxis", frontAxis);
scene->mMetaData->Get("FrontAxisSign", frontSign);
scene->mMetaData->Get("CoordAxis", coordAxis);
scene->mMetaData->Get("CoordAxisSign", coordSign);
}
enum Axis { X = 0, Y = 1, Z = 2 };
Axis sceneUpAxis = (Axis)upAxis;
Axis sceneFrontAxis = (Axis)frontAxis;
Axis sceneCoordAxis = (Axis)coordAxis;
int sceneUpSign = upSign;
int sceneFrontSign = frontSign;
int sceneCoordSign = coordSign;
bool isLeftHandled = false;
//math::Matrix4f m = AssimpHelpers::convertAssimpToODFAEGMatrix(node->mTransformation);
float det = world.getDet();
bool isLeftHanded = false;
if (det > 0.0f) {
//std::cout<<"left handed!"<<std::endl;
isLeftHanded = true;
}
entity::TransformMatrix axisCorrection, handednessCorrection, scaleCorrection;
axisCorrection.reset();
handednessCorrection.reset();
scaleCorrection.reset();
// 1. Correction UP (Z-up → Y-up)
if (sceneUpAxis == Axis::Z) {
axisCorrection.setRotation(math::Vec3f(1.f,0.f,0.f), -90.f);
}
// 2. Correction FRONT (Y-forward → -Z-forward)
if (sceneFrontAxis == Axis::Y) {
axisCorrection.setRotation(math::Vec3f(0.f,0.f,1.f), 180.f);
}
// 3. Correction handedness
if (isLeftHanded) {
axisCorrection.setScale(math::Vec3f(1.f,1.f,-1.f));
}
//std::cout<<"materials loaded : "<<mat.getTexture()<<std::endl;
std::vector<Vertex> vertices;
vertices.resize(mesh->mNumVertices);
VertexBuffer vb(device, Triangles, MAX_FRAMES_IN_FLIGHT);
vb.resize(mesh->mNumVertices, 0);
/*unsigned int uvCount = 0;
for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; i++) {
if (mesh->mTextureCoords[i] != nullptr)
uvCount++;
}
std::cout<<"nb uvs : "<<uvCount<<std::endl;*/
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
vertices[i].position[0] = mesh->mVertices[i].x;
vertices[i].position[1] = mesh->mVertices[i].y;
vertices[i].position[2] = mesh->mVertices[i].z;
if (mesh->mTextureCoords[0] && subMesh.getMaterial().getTexture(Material::DIFFUSE) != nullptr)
{
vertices[i].texCoords[0] = mesh->mTextureCoords[0][i].x/* * mat.getTexture()->getSize().x()*/;
vertices[i].texCoords[1] = mesh->mTextureCoords[0][i].y/* * mat.getTexture()->getSize().y()*/;
/*if (vertices[i].texCoords[0] == 0 && vertices[i].texCoords[1] == 0) {
std::cout<<"error!"<<std::endl;
}*/
/*std::cout<<"tex coords : "<<vertices[i].texCoords[0]<<std::endl;
std::cout<<"tex coords : "<<vertices[i].texCoords[1]<<std::endl;*/
} else {
vertices[i].texCoords = math::Vec2f(0.f, 0.f);
}
vertices[i].normal[0] = mesh->mNormals[i].x;
vertices[i].normal[1] = mesh->mNormals[i].y;
vertices[i].normal[2] = mesh->mNormals[i].z;
vb[i] = vertices[i];
}
physic::BoundingBox bounds = vb.getBounds();
if (bounds.getSize().x() > 1000 && bounds.getSize().y() > 1000 && bounds.getSize().z() > 1000) {
scaleCorrection.setScale(math::Vec3f(0.01f, 0.01f, 0.01f));
}
math::Matrix4f finalCorrection = scaleCorrection.getMatrix() *
axisCorrection.getMatrix() *
handednessCorrection.getMatrix();
math::Matrix4f finalTransform = world * finalCorrection;
//std::cout<<"final correction : "<<finalCorrection<<std::endl;
for (unsigned int i = 0; i < vb.getVertexCount(); i++) {
vb[i].position = finalTransform * vb[i].position;
vb[i].normal = finalCorrection * vb[i].normal;
//std::cout<<"vertex position : "<<vb[i].position<<std::endl;
}
for(unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
//std::cout<<"add face : "<<face.mNumIndices<<std::endl;
for(unsigned int j = 0; j < face.mNumIndices; j++) {
//std::cout<<"index : "<<face.mIndices[j]<<std::endl;
vb.addIndex(face.mIndices[j]);
}
}
subMesh.setVertexBuffer(vb);
std::lock_guard<std::recursive_mutex> lock(rec_mutex);
/*math::Vec3f center = vb.getBounds().getCenter();
math::Vec3f worldPos = finalTransform * center;
std::cout << "Mesh world pos = " << worldPos << std::endl;*/
//std::cout<<"vertices loaded"<<std::endl;
extractBoneWeightForVertices(vertices, mesh, scene, model);
//std::cout<<"bone loaded"<<std::endl;
//std::cout<<"vertices : "<<vb.getVertexCount()<<std::endl;
//std::cout<<"indexes : "<<vb.getIndexCount()<<std::endl;
/*if (mat.getTexture() == nullptr) {
std::cout<<"material id : "<<mat.getId()<<std::endl;
} else {
//std::cout<<"texture"<<std::endl;
}*/
model->addSubMesh(std::move(subMesh));
model->setSize(vb.getBounds().getSize());
} |
Partager