Assimp — Chargement de modèles 3D
Assimp (Open Asset Import Library) est une bibliothèque C++ open source qui charge plus de 40 formats 3D — OBJ, FBX, GLTF, GLB, DAE, 3DS … et les convertit en une structure unifiée : l'aiScene. Notre classe AssimpBlender la lit, puis la convertit en buffers et en textures Metal.
Un personnage, un véhicule ou un décor se modélisent dans Blender (gratuit), 3ds Max ou Maya, pas dans du code : des milliers de sommets, leurs normales, leurs UV, un squelette et ses animations. Ton moteur, lui, ne connaît que des buffers et des textures Metal.
Entre les deux, un fichier d'échange. Ce chapitre utilise le glTF binaire (.glb) : un seul fichier qui contient géométrie, matériaux, textures et animations, et que Blender exporte nativement. Les réglages d'export sont dans le chapitre ↘ Script pour Blender 5.x.
- Installer Assimp et l'ajouter au projet (Makefile ou Xcode)
- Charger un .glb : meshes, normales, tangentes, UV
- Envoyer vertices et textures au GPU (vertex descriptor, mipmaps)
- Animer un squelette : bones, poids, keyframes, couches
- Régler les paramètres : temps des animations, nombre de bones maximum
- Charger et décharger des modèles avec des handles
Lire ces formats soi-même — le JSON et les buffers binaires du glTF, l'arbre de nodes du FBX — demanderait un parser par format. Assimp s'en charge et livre toujours la même structure en mémoire. Notre travail porte sur ce qui nous intéresse : ce qu'il faut envoyer au GPU, et sous quelle forme.
Licence — ce que tu peux faire
// Mention obligatoire quelque part dans ton app (About, README.md, CREDITS) :
// "This software uses the Assimp library (https://github.com/assimp/assimp)"
// "Copyright (c) 2006-2026, assimp team — BSD 3-Clause License"
Le dépôt affiche aussi les licences CC-PDDC, MIT, BSL-1.0, Unlicense et Zlib : ce sont celles des bibliothèques tierces intégrées à Assimp (parseurs de formats, zlib…). Chacune garde sa propre licence, et toutes autorisent un usage commercial.
Documentation officielle
Les liens essentiels pour ne pas se perdre :
Installer Assimp sur macOS
Via Git (moins recommandé)
## Shell
# clone le projet Assimp :
cd && git clone https://github.com/assimp/assimp.git repoAssimp
cd repoAssimp
# copier include/ ne suffit pas : il faut la bibliothèque compilée,
# et include/assimp/config.h, que CMake génère :
cmake -B build -DCMAKE_BUILD_TYPE=Release -DASSIMP_BUILD_TESTS=OFF
cmake --build build -j8
# installe headers et libassimp.dylib dans /usr/local/include et /usr/local/lib :
sudo cmake --install build
Tes flags pointent alors vers /usr/local/include et /usr/local/lib, au lieu du préfixe Homebrew.
Via Homebrew (le plus simple)
## Shell
brew install assimp
# vérifier l'installation
brew info assimp
# → /opt/homebrew/Cellar/assimp/6.0.5 (Apple Silicon)
# → /usr/local/Cellar/assimp/… (Mac Intel)
Flags Makefile déjà en place dans le chapitre dédié
## Shell
# headers et librairie dans le Makefile :
ASSIMP_PREFIX := $(shell brew --prefix assimp)
CXXFLAGS += -I$(ASSIMP_PREFIX)/include
LDFLAGS += -L$(ASSIMP_PREFIX)/lib -lassimp
Assimp sur Xcode
# Shell — update:25/06/26
## trouve ton identité de signature :
security find-identity -v -p basic
## signer la dylib Homebrew avec ton certificat Apple Developer :
codesign --force --sign "Apple Development: toi@icloud.com (HELLO4YOU2)" "$(realpath $(brew --prefix assimp)/lib/libassimp.dylib)"
Avec le Hardened Runtime, macOS refuse de charger une bibliothèque signée par une autre équipe que ton application : code signature … not valid for use in process. Signer la dylib de Homebrew avec ton identité règle le problème en développement, mais brew upgrade remplace le fichier et la signature disparaît : relance la commande après chaque mise à jour.
Autre option en développement : l'entitlement com.apple.security.cs.disable-library-validation.
Ajoute Assimp au projet : MSLearn.xcodeproj (le 1er en bleu), dans "Targets" → "LearnMSL macOS" → dans Build Settings : 2 étapes
→ Header Search Paths → ajoute /opt/homebrew/opt/assimp/include (double-click)
→ Other Linker Flags → ajoute les 2 flags séparément -lassimp-L/opt/homebrew/opt/assimp/lib
4 fichiers supplémentaires comme d'habitude + tes modèles & scènes externes.
libassimp.dylib n'existe pas sur le Mac de tes joueurs. Elle doit voyager dans le bundle : copie-la dans MSLearn.app/Contents/Frameworks (Xcode : Frameworks, Libraries, and Embedded Content → Embed & Sign). L'exécutable doit ensuite la chercher là : install_name_tool -change remplace le chemin Homebrew par @rpath/libassimp.dylib, et -Wl,-rpath,@executable_path/../Frameworks indique où se trouve @rpath.
Structure minimale du projet
MSLearn/
├── MSLearn.entitlements
├── Application/
│ ├── main.m
│ ├── AppViewController.h
│ ├── AppViewController.mm
│ └── macOS/ …
│ └── macOSInfo.plist
├── Frameworks/
│ ├── metal-cpp/ …
│ └── metal-cpp-extensions/ …
├── Renderer/ …
│ ├── AssimpBlender.cpp
│ ├── AssimpBlender.hpp
│ ├── Renderer.cpp
│ └── Renderer.hpp
├── Shaders/ …
│ └── AssimpBlender.metal
├── includes/ …
│ ├── SharedGPU/ …
│ │ └── AssimpBlender_shared.h
│ ├── extern/
│ │ └── stb_image.h
│ └── SharedAPP/
│ └── InputState.h
├── Odonata.glb # export glTF 2.0 (Binary .glb)
├── .gitignore
├── .git
└── Makefile
Ton fichier partagé
Pour les modèles ne possédant pas de squelette, nous ne déclarons pas de matrices pour stocker les os :
/// C++ — AssimpBlender_shared.h — update:16/10/26
#include <simd/simd.h>
// Nombre de bones maximum que possède ton + grand modèle (Odonata.glb : 89).
// Partagé C++ / MSL : loadModel() refuse un modèle qui dépasse au lieu de déborder du buffer.
#define BLENDER_MAX_BONES 89
struct BlenderUniforms
{
simd::float4x4 modelMatrix;
simd::float4x4 viewProjectionMatrix;
};
struct BlenderUniformsFull
{
simd::float4x4 modelMatrix;
simd::float4x4 viewProjectionMatrix;
simd::float4x4 boneMatrices[BLENDER_MAX_BONES];
};
Une matrice 4x4 pèse 64 octets : 89 bones font 5,7 Ko par modèle animé. C'est trop pour setVertexBytes(), limité à 4 Ko, d'où un vrai MTL::Buffer par modèle.
Choisis la valeur d'après ton modèle le plus riche : debugBones() affiche le nombre de bones, et loadModel() refuse un modèle qui dépasse, avec un message qui donne les deux chiffres. Le define est partagé avec le shader : une seule valeur à changer.
Ton fichier header AssimpBlender
/// C++ — AssimpBlender.hpp — update:25/06/26
#ifndef AssimpBlender_hpp
#define AssimpBlender_hpp
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "../includes/SharedGPU/AssimpBlender_shared.h"
#include "../includes/SharedGPU/Renderer_shared.h"
Un seul modèle comprend énormément d'éléments
Un moteur charge des dizaines de modèles, certains le temps d'un seul niveau. Il faut pouvoir en décharger un sans casser les références que le reste du code garde vers les autres.
D'où les slots et les handles ci-dessous : un modèle déchargé libère son slot, que le chargement suivant réutilise, et tout handle vers l'ancien occupant devient invalide au lieu de pointer sur le nouveau. Le principe complet est dans le chapitre ↘ Handles — index + génération.
Pour commencer, 2 fonctions pour convertir les données et créer nos matrices 4x4, nous travaillons avec la bibliothèque simd alors que aiScene utilise aiMatrix4x4.
/// C++ — AssimpBlender.cpp — update:16/10/26
#include "AssimpBlender.hpp"
#include <algorithm> // std::min, std::max
#include <cmath> // std::log2, std::floor
#include "../includes/extern/stb_image.h"
static simd::float4x4 aiToSimd(const aiMatrix4x4& m) // ai vers simd — matrice
{
return simd::float4x4{simd::float4{m.a1, m.b1, m.c1, m.d1},
simd::float4{m.a2, m.b2, m.c2, m.d2},
simd::float4{m.a3, m.b3, m.c3, m.d3},
simd::float4{m.a4, m.b4, m.c4, m.d4} };
}
static simd::float4x4 makeTRS(simd::float3 t, simd::quatf rotation, simd::float3 s)
{ // faire la translation, rotation et mise à l'échelle
simd::float4x4 translation{simd::float4{ 1, 0, 0, 0 },
simd::float4{ 0, 1, 0, 0 },
simd::float4{ 0, 0, 1, 0 },
simd::float4{ t.x, t.y, t.z, 1 } };
simd::float4x4 scale{simd::float4{ s.x, 0, 0, 0 },
simd::float4{ 0, s.y, 0, 0 },
simd::float4{ 0, 0, s.z, 0 },
simd::float4{ 0, 0, 0, 1 } };
return translation * simd::float4x4(rotation) * scale;
}
Une seule classe qui va charger et afficher tes modèles — du solide
/// C++ — AssimpBlender.cpp — update:16/10/26
AssimpBlender::AssimpBlender(MTL::Device* device, MTL::Library* shaderLibrary,
MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat,
const std::string& resourcesPath)
: m_device(device->retain())
{
m_commandQueue = m_device->newCommandQueue(); // sert uniquement à générer les mipmaps au chargement
createPipeline(shaderLibrary, colorPixelFormat, depthPixelFormat);
createSampler();
}
AssimpBlender::~AssimpBlender()
{
for (auto& model : m_models) // un slot déchargé est vide : release() ignore ses nullptr
model.release();
if (m_renderPipelineStateFull) m_renderPipelineStateFull->release();
if (m_renderPipelineState) m_renderPipelineState->release();
m_depthStencilState->release();
m_samplerState->release();
m_commandQueue->release();
m_device->release();
}
/// C++ — AssimpBlender.hpp — update:16/10/26
struct ModelHandle // un « generational index » : un index + un numéro de génération
{
uint32_t index = UINT32_MAX;
uint32_t generation = 0;
bool isValid() const { return index != UINT32_MAX; }
// voir chapitre POO
bool operator==(const ModelHandle& other) const
{
return index == other.index && generation == other.generation;
}
bool operator!=(const ModelHandle& other) const {
return !(*this == other);
}
};
// Handle nul explicite, pratique pour initialiser des membres ailleurs dans le moteur.
static constexpr ModelHandle kInvalidModelHandle{};
- Handle
- → est juste une valeur (souvent un entier, ou une petite struct comme ici) que tu passes à un système qui, lui, sait comment la traduire en accès réel — via une table de lookup interne (ici resolveSlot()). Le système peut détecter si le handle est encore valide avant de te donner l'accès.
- Pointeur
- → Donne l'adresse mémoire exacte de l'objet. Si l'objet est déplacé, détruit, ou que le vector qui le contient réalloue, ton pointeur devient invalide silencieusement — accès mémoire indéfini (crash, ou pire, corruption silencieuse).
/// C++ — AssimpBlender.cpp — update:23/08/26
const AssimpBlender::ModelSlot* AssimpBlender::resolveSlot(ModelHandle handle) const
{
if (!handle.isValid() || handle.index >= m_slots.size())
return nullptr;
const ModelSlot& slot = m_slots[handle.index];
if (!slot.alive || slot.generation != handle.generation)
return nullptr;
return &slot;
}
AssimpBlender::ModelSlot* AssimpBlender::resolveSlot(ModelHandle handle)
{
if (!handle.isValid() || handle.index >= m_slots.size())
return nullptr;
ModelSlot& slot = m_slots[handle.index];
if (!slot.alive || slot.generation != handle.generation)
return nullptr; // handle périmé : slot recyclé pour un autre modèle
return &slot;
}
bool AssimpBlender::isValid(ModelHandle handle) const
{
return resolveSlot(handle) != nullptr;
}
Les slots
/// C++ — AssimpBlender.hpp — update:16/10/26
#include <MetalKit/MetalKit.hpp>
#include <simd/simd.h>
#include <vector>
#include <string>
#include <unordered_map>
#include <functional>
#include <cstdint>
class AssimpBlender
{
public:
AssimpBlender(MTL::Device*, MTL::Library*,
MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat,
const std::string& resourcePath);
~AssimpBlender();
void unloadModel(ModelHandle handle);
ModelHandle getHandle(size_t index) const; // kInvalidModelHandle si le slot est vide
void createPipeline(MTL::Library*, MTL::PixelFormat, MTL::PixelFormat);
void update(float deltaTime);
void draw(MTL::RenderCommandEncoder*, const GlobalUniforms& uniforms);
void drawBlender(MTL::RenderCommandEncoder*, size_t index, const simd::float4x4& model,
const GlobalUniforms&); // nul besoin de spécifier un nom dans les .h
private:
struct ModelSlot // m_slots[i] décrit m_models[i]
{
uint32_t generation = 0; // +1 à chaque déchargement : périme les anciens handles
bool alive = false;
}; // m_slots[5] = { generation = 3, alive = true }
MTL::Device* m_device;
MTL::CommandQueue* m_commandQueue = nullptr;
MTL::SamplerState* m_samplerState = nullptr;
MTL::DepthStencilState* m_depthStencilState = nullptr;
MTL::RenderPipelineState* m_renderPipelineState = nullptr;
MTL::RenderPipelineState* m_renderPipelineStateFull = nullptr;
std::vector<ModelSlot> m_slots; // même taille que m_models
std::vector<uint32_t> m_freeList; // index des slots vides, réutilisés par loadModel()
std::unordered_map<std::string, ModelHandle> m_modelNameToHandle;
size_t m_aliveCount = 0; // nb de modèles chargés
// Résout un handle vers son slot, ou nullptr si invalide/périmé.
// Toutes les méthodes publiques passent par ici — un seul point de vérité
// pour la validation, pas de borne-check dupliqué partout.
ModelSlot* resolveSlot(ModelHandle handle);
const ModelSlot* resolveSlot(ModelHandle handle) const;
bool isValid(ModelHandle handle) const;
};
#endif /* AssimpBlender_hpp */
Pour une meilleure compréhension de ce qui se passe sous le capot, je t'invite à te rendre dans le parcours, tu y trouveras un programme qui simule la gestion des modèles.
Après lecture des documentations
glTF 2.0 — en particulier la section "Meshes" qui liste exactement les attributs standards et leurs types & les headers Assimp et leurs commentaires — assimp/mesh.h qui documente aiMesh et aiBone en détail, la classe peut se construire.
Voici toutes les données qu'un modèle peut contenir :
/// C++ — AssimpBlender.hpp — update:16/10/26
struct VertexBlender // 64 octets : simd::float3 occupe 16 octets (alignement), pas 12
{
simd::float3 position;
simd::float3 normal;
simd::float2 texCoord;
simd::float4 tangent; // xyz = tangente, w = ±1 sens de la bitangente
};
struct VertexBlenderFull
{
simd::float3 position;
simd::float3 normal;
simd::float2 texCoord;
simd::float4 tangent;
simd::int4 joints;
simd::float4 weights;
};
struct BoneInfo
{
int id;
simd::float4x4 offset; // inverse bind pose
};
template<typename T>
struct KeyFrame
{
float time;
T value;
};
struct BoneAnimation
{
std::string boneName; // Bone -> Bone.088
std::vector<KeyFrame<simd::float3>> positions;
std::vector<KeyFrame<simd::quatf>> rotations;
std::vector<KeyFrame<simd::float3>> scales;
};
struct AnimationAssimp
{
std::string name;
float duration;
float ticksPerSec;
std::vector<BoneAnimation> channels;
};
struct AnimationLayer
{
size_t animationIndex = 0;
float weight = 1.0f;
float currentTime = 0.0f;
bool isPlaying = false;
bool loop = true;
float speedMultiplier = 1.0f;
};
struct AnimationController
{
bool isPlaying = false;
float speedMultiplier = 1.0f;
bool loop = true;
bool isInTransitioning = false;
size_t targetAnimation = 0;
float transitionDuration = 0.3f;
float transitionTime = 0.0f;
float targetTime = 0.0f; // temps de l'animation cible : elle avance déjà pendant le fondu
};
struct NodeData
{
std::string name;
simd::float4x4 transform;
std::vector<NodeData> children;
};
struct Blender // structure reprenant toutes les données de ton modèle exporté
{
std::string name;
std::string parent;
std::vector<VertexBlender> vertices;
std::vector<VertexBlenderFull> verticesFull;
std::vector<uint32_t> indices;
MTL::Buffer* vertexBuffer = nullptr;
MTL::Buffer* indexBuffer = nullptr;
bool hasAnimation = false;
bool shouldAnimate = true;
std::unordered_map<std::string, BoneInfo> boneMap; // std::map<std::string, BoneInfo> m_boneMap;
std::vector<simd::float4x4> boneMatrices;
std::vector<AnimationAssimp> animations;
std::unordered_map<std::string, size_t> animationMap;
AnimationController animController;
std::vector<AnimationLayer> animationLayers;
bool useLayeredAnimation = false;
NodeData rootNode;
int boneCount = 0;
size_t currentAnimation = 0;
float currentTime = 0.0f;
MTL::Buffer* uniformBuffer = nullptr;
MTL::Texture* diffuseTexture = nullptr;
MTL::Texture* normalTexture = nullptr;
MTL::Texture* roughnessTexture = nullptr;
MTL::Texture* metallicTexture = nullptr;
MTL::Texture* ambientOcclusion = nullptr;
simd::float4x4 transform = matrix_identity_float4x4;
simd::float3 position = {};
bool hasAnimations(const std::string& name) const
{
return animationMap.find(name) != animationMap.end();
}
size_t getAnimationIndex(const std::string& name) const
{
auto it = animationMap.find(name);
return it != animationMap.end() ? it->second : 0;
}
size_t getVertexCount() const
{
return hasAnimation ? verticesFull.size() : vertices.size();
}
void release()
{
if (vertexBuffer) vertexBuffer->release();
if (indexBuffer) indexBuffer->release();
if (uniformBuffer) uniformBuffer->release();
if (diffuseTexture) diffuseTexture->release();
if (normalTexture) normalTexture->release();
if (roughnessTexture) roughnessTexture->release();
if (metallicTexture) metallicTexture->release();
if (ambientOcclusion) ambientOcclusion->release();
}
};
Déchargement éventuel de modèles/scènes
/// C++ — AssimpBlender.cpp — update:16/10/26
void AssimpBlender::unloadModel(ModelHandle handle)
{
ModelSlot* slot = resolveSlot(handle);
if (!slot)
return; // déjà déchargé, ou handle jamais valide -> no-op silencieux
Blender& model = m_models[handle.index];
m_modelNameToHandle.erase(model.name);
m_modelNameToIndex.erase(model.name);
model.release();
model = Blender{}; // vide les vecteurs CPU (vertices, indices, animations, …)
slot->alive = false;
slot->generation++; // périme tous les handles existants vers ce slot
m_freeList.push_back(handle.index); // le prochain loadModel() réutilisera cet index
m_aliveCount--;
}
La structure aiScene — comment tout est organisé
aiScene regroupe tout ce que contenait le fichier, dans des tableaux à plat : mMeshes, mMaterials, mTextures, mAnimations. Par-dessus, un arbre de nœuds décrit l'assemblage : chaque nœud a une matrice locale (sa place par rapport à son parent), des index vers mMeshes et ses enfants. Les bones d'un squelette sont des nœuds de cet arbre comme les autres : c'est ce qui permet de les animer avec le même parcours.
/// C++ — AssimpBlender.cpp — update:16/10/26
size_t AssimpBlender::loadModel(const std::string& resourcesPath, const std::string& name)
{
Assimp::Importer importer;
// Triangulate découpe les polygones, mais laisse les points et les lignes tels quels.
// SortByPType les isole dans leurs propres meshes, cette propriété les supprime :
// il ne reste que des triangles dans l'index buffer.
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE);
const aiScene* scene = importer.ReadFile(resourcesPath,
aiProcess_Triangulate | // polygones → triangles
aiProcess_FlipUVs | // UV : origine en haut à gauche, comme Metal
aiProcess_CalcTangentSpace | // tangentes pour les normal maps
aiProcess_JoinIdenticalVertices | // déduplique les vertices
aiProcess_LimitBoneWeights | // 4 bones max par vertex (réglage par défaut)
aiProcess_SortByPType | // sépare points / lignes / triangles
aiProcess_GenSmoothNormals | // rendu lisse (organique)
aiProcess_MakeLeftHanded | // repère main gauche, comme notre projection
aiProcess_FlipWindingOrder); // garde les faces avant après le changement de repère
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
printf("Assimp Error: %s\n", importer.GetErrorString());
return static_cast<size_t>(-1);
}
Blender model;
model.name = name.empty() ? resourcesPath : name;
if (m_modelNameToIndex.find(model.name) != m_modelNameToIndex.end())
{
printf("Warning: model name '%s' already loaded, overwriting index in name map\n", model.name.c_str());
}
model.rootNode = copyNodeHierarchy(scene->mRootNode);
bool hasBones = modelHasBones(scene->mRootNode, scene);
if (hasBones && scene->mNumAnimations > 0)
{
model.hasAnimation = true;
processNodeSkinned(scene->mRootNode, scene, model);
if (model.boneCount > BLENDER_MAX_BONES)
{ // le shader lirait boneMatrices[89+] hors du buffer : on refuse le modèle
printf("Assimp Error: '%s' a %d bones, BLENDER_MAX_BONES = %d (AssimpBlender_shared.h)\n",
model.name.c_str(), model.boneCount, BLENDER_MAX_BONES);
return static_cast<size_t>(-1);
}
model.boneMatrices.resize(model.boneCount, matrix_identity_float4x4);
model.uniformBuffer = m_device->newBuffer(sizeof(BlenderUniformsFull), MTL::ResourceStorageModeShared);
loadAnimations(scene, model);
model.vertexBuffer = m_device->newBuffer(model.verticesFull.data(), model.verticesFull.size() * sizeof(VertexBlenderFull), MTL::ResourceStorageModeShared);
}
else
{
model.hasAnimation = false;
processNodeStatic(scene->mRootNode, scene, model, matrix_identity_float4x4);
model.uniformBuffer = m_device->newBuffer(sizeof(BlenderUniforms), MTL::ResourceStorageModeShared);
model.vertexBuffer = m_device->newBuffer(model.vertices.data(), model.vertices.size() * sizeof(VertexBlender), MTL::ResourceStorageModeShared);
}
// Les textures externes sont cherchées à côté du fichier : « …/Resources/Odonata.glb » → « …/Resources »
std::string directory = resourcesPath.substr(0, resourcesPath.find_last_of('/'));
loadTextures(scene, model, directory);
model.indexBuffer = m_device->newBuffer(model.indices.data(), model.indices.size() * sizeof(uint32_t), MTL::ResourceStorageModeShared);
// Un slot libéré par unloadModel() est réutilisé : les index restent stables
size_t index;
if (!m_freeList.empty())
{
index = m_freeList.back();
m_freeList.pop_back();
m_models[index] = std::move(model);
}
else
{
index = m_models.size();
m_models.push_back(std::move(model));
m_slots.push_back({});
}
m_slots[index].alive = true; // la génération a déjà été incrémentée par unloadModel()
m_aliveCount++;
const std::string& modelName = m_models[index].name;
m_modelNameToIndex[modelName] = index; // enregistrement O(1)
m_modelNameToHandle[modelName] = getHandle(index);
return index;
}
Assimp livre toujours la scène dans le même repère : main droite, Y vers le haut, faces avant dans le sens anti-horaire. Notre caméra regarde vers +Z (chapitre Caméra) : c'est un repère main gauche. aiProcess_MakeLeftHanded retourne l'axe Z de toute la scène, bones et animations compris. Un miroir inverse le sens des triangles, d'où aiProcess_FlipWindingOrder.
Ces deux flags et aiProcess_FlipUVs existent aussi en un seul : aiProcess_ConvertToLeftHanded.
Triangulate | Quads et polygones en triangles. Les points et les lignes restent : AI_CONFIG_PP_SBP_REMOVE les supprime. |
FlipUVs | Assimp place l'origine des UV en bas à gauche, Metal en haut à gauche : on inverse V. |
CalcTangentSpace | Tangentes et bitangentes, indispensables aux normal maps. Il faut des UV. |
JoinIdenticalVertices | Fusionne les vertices identiques : un vrai index buffer au lieu de 3 vertices par triangle. |
LimitBoneWeights | Garde les 4 influences les plus fortes par vertex (AI_CONFIG_PP_LBW_MAX_WEIGHTS). |
SortByPType | Un mesh par type de primitive : points, lignes et triangles ne sont plus mélangés. |
ValidateDataStructure | Non utilisé ici. Pendant le debug d'un export, ajoute-le : il vérifie la scène et GetErrorString() dit ce qui cloche. |
Ces flags n'agissent que si le fichier n'a pas de normales. Un export glTF de Blender en contient toujours : dans ce cas, ils ne font rien. Ils sont incompatibles entre eux, n'en garde qu'un.
aiProcess_GenSmoothNormals → une normale par sommet, moyenne des faces qui le partagent : la lumière glisse sur la surface. Personnages, créatures, carrosseries : c'est le bon choix par défaut. Les arêtes plus vives que AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE (175° par défaut) restent nettes.
aiProcess_GenNormals → une normale par face : chaque triangle a sa propre teinte, le rendu est facetté. Pour du low-poly ou des pièces mécaniques. Les sommets ne sont plus partagés entre triangles, le vertex buffer grossit.
Pour un rendu plat sur un modèle qui a déjà ses normales, fais-le dans Blender (Shade Flat) avant l'export.
Setter — Getter
/// C++ — AssimpBlender.cpp — update:16/10/26
Blender* AssimpBlender::getModel(size_t index)
{
// un slot déchargé existe encore dans m_models, mais il est vide
return (index < m_models.size() && m_slots[index].alive) ? &m_models[index] : nullptr;
}
Blender* AssimpBlender::getModel(const std::string& name)
{
auto it = m_modelNameToIndex.find(name);
if (it == m_modelNameToIndex.end())
return nullptr;
return getModel(it->second);
}
ModelHandle AssimpBlender::getHandle(size_t index) const
{
if (index >= m_slots.size() || !m_slots[index].alive)
return kInvalidModelHandle;
return { static_cast<uint32_t>(index), m_slots[index].generation };
}
Hiérarchie de nodes — copyNodeHierarchy()
L'arbre d'aiNode appartient à l'Assimp::Importer : il est détruit à la fin de loadModel(). copyNodeHierarchy() le recopie en NodeData avant, parce que les animations en auront besoin à chaque frame.
/// C++ — AssimpBlender.cpp — update:16/10/26
NodeData AssimpBlender::copyNodeHierarchy(aiNode* node)
{
// PIÈGE : l'Importer détruit la scene à la fin du scope
// → tu ne peux PAS garder des pointeurs aiNode* après loadModel()
// → c'est pour ça que copyNodeHierarchy() existe dans AssimpBlender
NodeData data;
data.name = node->mName.C_Str();
data.transform = aiToSimd(node->mTransformation); // copie la matrice
data.children.reserve(node->mNumChildren);
for (unsigned i = 0; i < node->mNumChildren; i++)
data.children.push_back(copyNodeHierarchy(node->mChildren[i]));
return data; // tout est copié par valeur — safe
}
bool AssimpBlender::modelHasBones(aiNode* pNode, const aiScene* pScene)
{
for (unsigned i = 0; i < pNode->mNumMeshes; i++)
if (pScene->mMeshes[pNode->mMeshes[i]]->mNumBones > 0) return true;
for (unsigned i = 0; i < pNode->mNumChildren; i++)
if (modelHasBones(pNode->mChildren[i], pScene)) return true;
return false;
}
void AssimpBlender::processNodeStatic(aiNode* pNode, const aiScene* pScene, Blender& model, const simd::float4x4& parentTf)
{
// Les vertices d'un mesh sont exprimés dans le repère de son node :
// on cumule les transformations depuis la racine et on les applique aux vertices.
simd::float4x4 nodeTf = parentTf * aiToSimd(pNode->mTransformation);
for (unsigned i = 0; i < pNode->mNumMeshes; i++)
processMeshStatic(pScene->mMeshes[pNode->mMeshes[i]], model, nodeTf);
for (unsigned i = 0; i < pNode->mNumChildren; i++)
processNodeStatic(pNode->mChildren[i], pScene, model, nodeTf);
}
void AssimpBlender::processNodeSkinned(aiNode* pNode, const aiScene* pScene, Blender& model)
{
// Pas de cumul ici : en skinning, ce sont les bones (computeBoneTransforms) qui placent les vertices
for (unsigned i = 0; i < pNode->mNumMeshes; i++)
processMeshSkinned(pScene->mMeshes[pNode->mMeshes[i]], pNode, model);
for (unsigned i = 0; i < pNode->mNumChildren; i++)
processNodeSkinned(pNode->mChildren[i], pScene, model);
}
Meshes — extraire vertices et indices
/// C++ — AssimpBlender.cpp — update:16/10/26
static simd::float4 tangentOf(const aiMesh* pMesh, unsigned i, simd::float3 normal)
{ // xyz = tangente, w = ±1 : sens de la bitangente (UV en miroir → -1). Dans le shader : B = cross(N, T) * w
if (!pMesh->HasTangentsAndBitangents())
return {1, 0, 0, 1}; // pas d'UV : aiProcess_CalcTangentSpace n'a rien pu calculer
simd::float3 t = {pMesh->mTangents[i].x, pMesh->mTangents[i].y, pMesh->mTangents[i].z};
simd::float3 b = {pMesh->mBitangents[i].x, pMesh->mBitangents[i].y, pMesh->mBitangents[i].z};
float w = simd::dot(simd::cross(normal, t), b) < 0.0f ? -1.0f : 1.0f;
return {t.x, t.y, t.z, w};
}
void AssimpBlender::processMeshStatic(aiMesh* pMesh, Blender& model, const simd::float4x4& meshToModel)
{
uint32_t baseVertex = static_cast<uint32_t>(model.vertices.size()); // offset si plusieurs meshes
// Les normales ne se transforment pas comme les positions : matrice normale = (M⁻¹)ᵀ, sur la partie 3x3.
// Sans ça, une échelle non uniforme (2, 1, 1) penche les normales et fausse l'éclairage.
simd::float3x3 m3 = simd::float3x3(meshToModel.columns[0].xyz, meshToModel.columns[1].xyz, meshToModel.columns[2].xyz);
simd::float3x3 normalMatrix = simd::transpose(simd::inverse(m3));
float mirror = simd::determinant(m3) < 0.0f ? -1.0f : 1.0f; // une échelle négative inverse la bitangente
for (unsigned i = 0; i < pMesh->mNumVertices; i++)
{
VertexBlender v;
// Position — toujours présente
simd::float3 position = { pMesh->mVertices[i].x, pMesh->mVertices[i].y, pMesh->mVertices[i].z };
// Normale — vérifier avec HasNormals() avant d'accéder
simd::float3 normal = pMesh->HasNormals()
? simd::float3{pMesh->mNormals[i].x, pMesh->mNormals[i].y, pMesh->mNormals[i].z}
: simd::float3{0, 1, 0};
simd::float4 tangent = tangentOf(pMesh, i, normal);
v.position = (meshToModel * simd::float4{position.x, position.y, position.z, 1.0f}).xyz;
v.normal = simd::normalize(normalMatrix * normal);
v.tangent = simd::float4{0, 0, 0, tangent.w * mirror};
v.tangent.xyz = simd::normalize(m3 * tangent.xyz);
// UV — mTextureCoords[0] = premier canal UV
// Assimp supporte jusqu'à AI_MAX_NUMBER_OF_TEXTURECOORDS (8) canaux
v.texCoord = pMesh->mTextureCoords[0]
? simd::float2{pMesh->mTextureCoords[0][i].x, pMesh->mTextureCoords[0][i].y}
: simd::float2{0, 0};
model.vertices.push_back(v);
}
// Indices — aiFace contient les indices d'un triangle
for (unsigned i = 0; i < pMesh->mNumFaces; i++)
{
aiFace& face = pMesh->mFaces[i];
if (face.mNumIndices != 3)
continue; // point ou ligne : décalerait tous les triangles suivants de l'index buffer
for (unsigned j = 0; j < face.mNumIndices; j++)
model.indices.push_back(baseVertex + face.mIndices[j]);
}
}
void AssimpBlender::processMeshSkinned(aiMesh* pMesh, aiNode* pNode, Blender& model)
{
uint32_t baseVertex = static_cast<uint32_t>(model.verticesFull.size());
for (unsigned i = 0; i < pMesh->mNumVertices; i++)
{
VertexBlenderFull v;
v.position = {pMesh->mVertices[i].x, pMesh->mVertices[i].y, pMesh->mVertices[i].z};
v.normal = pMesh->HasNormals()
? simd::float3{pMesh->mNormals[i].x, pMesh->mNormals[i].y, pMesh->mNormals[i].z}
: simd::float3{0, 1, 0};
v.tangent = tangentOf(pMesh, i, v.normal);
v.texCoord = pMesh->mTextureCoords[0]
? simd::float2{pMesh->mTextureCoords[0][i].x, pMesh->mTextureCoords[0][i].y}
: simd::float2{0, 0};
v.joints = {-1, -1, -1, -1}; // -1 = emplacement libre, rempli par loadBones()
v.weights = {0, 0, 0, 0};
model.verticesFull.push_back(v);
}
if (pMesh->mNumBones > 0)
loadBones(pMesh, model, baseVertex);
// Un vertex sans poids (mesh sans bones, ou mal peint dans Blender) suit le node qui porte le mesh :
// ce node devient un « bone » d'offset identité, que computeBoneTransforms() anime comme les autres.
int nodeBone = -1;
for (unsigned i = baseVertex; i < model.verticesFull.size(); i++)
{
auto& v = model.verticesFull[i];
// Après tous les bones — normaliser les weights (somme = 1.0) :
float sum = v.weights.x + v.weights.y + v.weights.z + v.weights.w;
if (sum > 0.0f)
v.weights /= sum;
else
{
if (nodeBone < 0)
nodeBone = nodeBoneID(pNode->mName.C_Str(), model);
v.joints = {nodeBone, 0, 0, 0};
v.weights = {1, 0, 0, 0};
}
// Le shader lit boneMatrices[joints[k]] même quand le poids vaut 0 :
// un -1 restant lirait hors du buffer
for (int k = 0; k < 4; k++)
if (v.joints[k] < 0)
v.joints[k] = 0;
}
for (unsigned i = 0; i < pMesh->mNumFaces; i++)
{
aiFace& face = pMesh->mFaces[i];
// Triangulate découpe les polygones, pas les points ni les lignes :
// sans AI_CONFIG_PP_SBP_REMOVE, il peut rester des faces à 1 ou 2 indices
if (face.mNumIndices != 3)
continue;
for (unsigned j = 0; j < face.mNumIndices; j++)
model.indices.push_back(baseVertex + face.mIndices[j]);
}
}
Skeletal animation — bones et weights
Le skinning GPU consiste à déformer chaque vertex selon la position actuelle de ses os. Chaque vertex a jusqu'à 4 paires (bone_id, weight). Ce n'est pas une limite du GPU : c'est la convention glTF (JOINTS_0 et WEIGHTS_0 sont des vec4), et aiProcess_LimitBoneWeights garde les 4 influences les plus fortes. Pour 8 influences, il faudrait un second couple d'attributs.
/// C++ — AssimpBlender.cpp — update:16/10/26
void AssimpBlender::loadBones(aiMesh* pMesh, Blender& model, uint32_t baseVertex)
{
for (unsigned i = 0; i < pMesh->mNumBones; i++)
{
aiBone* pBone = pMesh->mBones[i];
std::string name = pBone->mName.C_Str();
int boneID;
auto it = model.boneMap.find(name);
// BoneMap : nom → {id, offset matrix}
// L'offset matrix = inverse bind pose : elle ramène le vertex de l'espace du mesh
// vers l'espace du bone, dans la pose de repos (bind pose)
if (it == model.boneMap.end())
{
boneID = model.boneCount++;
model.boneMap[name] = {boneID, aiToSimd(pBone->mOffsetMatrix)};
}
else
boneID = it->second.id;
// Remplir joints[] et weights[] pour chaque vertex influencé
for (unsigned j = 0; j < pBone->mNumWeights; j++)
{ // Chercher un slot libre dans les 4 joints
unsigned vertID = baseVertex + pBone->mWeights[j].mVertexId;
float weight = pBone->mWeights[j].mWeight;
auto& v = model.verticesFull[vertID];
for (int k = 0; k < 4; k++)
{
if (v.joints[k] < 0)
{
v.joints[k] = boneID;
v.weights[k] = weight;
break;
}
}
}
}
}
int AssimpBlender::nodeBoneID(const std::string& nodeName, Blender& model)
{ // Un mesh sans bones suit le node qui le porte : on enregistre ce node comme un bone
// d'offset identité — ses vertices sont déjà dans le repère du node
auto it = model.boneMap.find(nodeName);
if (it != model.boneMap.end())
return it->second.id;
int id = model.boneCount++;
model.boneMap[nodeName] = {id, matrix_identity_float4x4};
return id;
}
Un vertex sans aucun poids — mesh sans bones dans un modèle animé, ou zone oubliée au weight painting — n'a aucune matrice de skinning : il s'écraserait à l'origine. nodeBoneID() enregistre le node qui porte le mesh comme un bone d'offset identité : le vertex suit ce node, qu'il soit animé ou non. Ce bone compte dans BLENDER_MAX_BONES.
Le pipeline
Deux pipelines : un pour les modèles statiques, un pour les modèles animés, qui lisent en plus joints et weights. Le vertex descriptor décrit à Metal où trouver chaque attribut dans le buffer.
Un simd::float3 occupe 16 octets, pas 12 : il est aligné comme un float4. VertexBlender fait donc 64 octets : position 16, normale 16, UV 8, 8 octets de remplissage, puis la tangente à l'offset 48. offsetof() et sizeof() donnent toujours les vraies valeurs, même si tu ajoutes un attribut.
/// C++ — AssimpBlender.cpp — update:16/10/26
void AssimpBlender::createPipeline(MTL::Library* shaderLibrary, MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat)
{
NS::SharedPtr<MTL::VertexDescriptor> vertexDescriptor = NS::TransferPtr(MTL::VertexDescriptor::alloc()->init());
vertexDescriptor->attributes()->object(0)->setFormat(MTL::VertexFormatFloat3);
vertexDescriptor->attributes()->object(0)->setOffset(offsetof(VertexBlender, position));
vertexDescriptor->attributes()->object(0)->setBufferIndex(0);
vertexDescriptor->attributes()->object(1)->setFormat(MTL::VertexFormatFloat3);
vertexDescriptor->attributes()->object(1)->setOffset(offsetof(VertexBlender, normal));
vertexDescriptor->attributes()->object(1)->setBufferIndex(0);
vertexDescriptor->attributes()->object(2)->setFormat(MTL::VertexFormatFloat2);
vertexDescriptor->attributes()->object(2)->setOffset(offsetof(VertexBlender, texCoord));
vertexDescriptor->attributes()->object(2)->setBufferIndex(0);
vertexDescriptor->attributes()->object(3)->setFormat(MTL::VertexFormatFloat4);
vertexDescriptor->attributes()->object(3)->setOffset(offsetof(VertexBlender, tangent));
vertexDescriptor->attributes()->object(3)->setBufferIndex(0);
vertexDescriptor->layouts()->object(0)->setStride(sizeof(VertexBlender));
NS::SharedPtr<MTL::VertexDescriptor> vertexDescriptorAnyme = NS::TransferPtr(MTL::VertexDescriptor::alloc()->init());
vertexDescriptorAnyme->attributes()->object(0)->setFormat(MTL::VertexFormatFloat3);
vertexDescriptorAnyme->attributes()->object(0)->setOffset(offsetof(VertexBlenderFull, position));
vertexDescriptorAnyme->attributes()->object(0)->setBufferIndex(0);
vertexDescriptorAnyme->attributes()->object(1)->setFormat(MTL::VertexFormatFloat3);
vertexDescriptorAnyme->attributes()->object(1)->setOffset(offsetof(VertexBlenderFull, normal));
vertexDescriptorAnyme->attributes()->object(1)->setBufferIndex(0);
vertexDescriptorAnyme->attributes()->object(2)->setFormat(MTL::VertexFormatFloat2);
vertexDescriptorAnyme->attributes()->object(2)->setOffset(offsetof(VertexBlenderFull, texCoord));
vertexDescriptorAnyme->attributes()->object(2)->setBufferIndex(0);
vertexDescriptorAnyme->attributes()->object(3)->setFormat(MTL::VertexFormatInt4);
vertexDescriptorAnyme->attributes()->object(3)->setOffset(offsetof(VertexBlenderFull, joints));
vertexDescriptorAnyme->attributes()->object(3)->setBufferIndex(0);
vertexDescriptorAnyme->attributes()->object(4)->setFormat(MTL::VertexFormatFloat4);
vertexDescriptorAnyme->attributes()->object(4)->setOffset(offsetof(VertexBlenderFull, weights));
vertexDescriptorAnyme->attributes()->object(4)->setBufferIndex(0);
vertexDescriptorAnyme->attributes()->object(5)->setFormat(MTL::VertexFormatFloat4);
vertexDescriptorAnyme->attributes()->object(5)->setOffset(offsetof(VertexBlenderFull, tangent));
vertexDescriptorAnyme->attributes()->object(5)->setBufferIndex(0);
vertexDescriptorAnyme->layouts()->object(0)->setStride(sizeof(VertexBlenderFull));
// vertexDescFull->layouts()->object(0)->setStepFunction(MTL::VertexStepFunctionPerVertex);
NS::SharedPtr<MTL::RenderPipelineDescriptor> renderPipelineDesc = NS::TransferPtr(MTL::RenderPipelineDescriptor::alloc()->init());
// newFunction() renvoie un objet déjà retenu (+1) : TransferPtr le libère à la fin de la fonction,
// le pipeline garde sa propre référence
auto vertexFn = NS::TransferPtr(shaderLibrary->newFunction(MTLSTR("vertex_Assimp")));
auto vertexAnimFn = NS::TransferPtr(shaderLibrary->newFunction(MTLSTR("vertex_AssimpAnyme")));
auto fragmentFn = NS::TransferPtr(shaderLibrary->newFunction(MTLSTR("fragment_Assimp")));
renderPipelineDesc->setVertexFunction(vertexFn.get());
renderPipelineDesc->setFragmentFunction(fragmentFn.get());
renderPipelineDesc->setVertexDescriptor(vertexDescriptor.get());
renderPipelineDesc->colorAttachments()->object(0)->setPixelFormat(colorPixelFormat);
renderPipelineDesc->setDepthAttachmentPixelFormat(depthPixelFormat);
NS::Error* pError = nullptr;
m_renderPipelineState = m_device->newRenderPipelineState(renderPipelineDesc.get(), &pError);
if (!m_renderPipelineState)
printf("AssimpBlender — pipeline statique : %s\n", pError->localizedDescription()->utf8String());
renderPipelineDesc->setVertexFunction(vertexAnimFn.get());
renderPipelineDesc->setVertexDescriptor(vertexDescriptorAnyme.get());
m_renderPipelineStateFull = m_device->newRenderPipelineState(renderPipelineDesc.get(), &pError);
if (!m_renderPipelineStateFull)
printf("AssimpBlender — pipeline skinné : %s\n", pError->localizedDescription()->utf8String());
NS::SharedPtr<MTL::DepthStencilDescriptor> depthStencilDesc = NS::TransferPtr(MTL::DepthStencilDescriptor::alloc()->init());
depthStencilDesc->setDepthCompareFunction(MTL::CompareFunctionLess);
depthStencilDesc->setDepthWriteEnabled(true);
m_depthStencilState = m_device->newDepthStencilState(depthStencilDesc.get());
}
static float advanceTime(float time, float delta, const AnimationAssimp& anim, float speed, bool loop, bool* finished = nullptr)
{ // avance le temps d'une animation, en ticks, et gère la boucle ou l'arrêt en fin de clip
time += delta * anim.ticksPerSec * speed;
if (time > anim.duration)
{
if (loop)
time = fmod(time, anim.duration);
else
{
time = anim.duration;
if (finished) *finished = true;
}
}
return time;
}
void AssimpBlender::update(float delta)
{
for (auto& model : m_models) // un slot déchargé (Blender{}) n'a pas d'animation : ignoré
{
if (!model.hasAnimation || model.animations.empty())
continue;
if (model.useLayeredAnimation && !model.animationLayers.empty())
{
for (auto& layer : model.animationLayers)
{
if (!layer.isPlaying)
continue;
AnimationAssimp& anim = model.animations[layer.animationIndex];
layer.currentTime += delta * anim.ticksPerSec * layer.speedMultiplier;
if (layer.currentTime > anim.duration)
{
if (layer.loop)
layer.currentTime = fmod(layer.currentTime, anim.duration);
else
{
layer.currentTime = anim.duration;
layer.isPlaying = false;
}
}
}
// Une seule passe sur la hiérarchie : chaque os mélange les poses de tous les layers
computeBoneTransformsLayered(model.rootNode, matrix_identity_float4x4, model, model.animationLayers);
}
else
{
if (!model.animController.isPlaying)
continue;
AnimationController& ctrl = model.animController;
if (ctrl.isInTransitioning)
{ // Fondu enchaîné : les deux animations continuent d'avancer, et leurs poses
// sont mélangées os par os — même mélange TRS que les layers
const AnimationAssimp& from = model.animations[model.currentAnimation];
const AnimationAssimp& to = model.animations[ctrl.targetAnimation];
model.currentTime = advanceTime(model.currentTime, delta, from, ctrl.speedMultiplier, true);
ctrl.targetTime = advanceTime(ctrl.targetTime, delta, to, ctrl.speedMultiplier, ctrl.loop);
ctrl.transitionTime += delta; // en secondes, pas en ticks
float t = std::min(ctrl.transitionTime / ctrl.transitionDuration, 1.0f);
if (t < 1.0f)
{
float w = t * t * (3.0f - 2.0f * t); // SmoothStep : le fondu démarre et finit en douceur
std::vector<AnimationLayer> blend = {
{ model.currentAnimation, 1.0f - w, model.currentTime, true },
{ ctrl.targetAnimation, w, ctrl.targetTime, true },
};
computeBoneTransformsLayered(model.rootNode, matrix_identity_float4x4, model, blend);
continue;
}
// fondu terminé : la cible devient l'animation courante, là où elle en était
model.currentAnimation = ctrl.targetAnimation;
model.currentTime = ctrl.targetTime;
ctrl.isInTransitioning = false;
}
else
{
bool finished = false;
model.currentTime = advanceTime(model.currentTime, delta, model.animations[model.currentAnimation],
ctrl.speedMultiplier, ctrl.loop, &finished);
if (finished)
ctrl.isPlaying = false;
}
// Chaque bone est un node de la hiérarchie : ce parcours recalcule toutes leurs matrices
computeBoneTransforms(model.currentTime, model.rootNode, matrix_identity_float4x4, model);
}
}
}
Textures embarquées — GLB
Le .glb embarque ses textures dans le fichier, en général en PNG ou en JPG. Assimp les range dans scene->mTextures[], et le matériau y renvoie par un chemin « *0 », « *1 »… GetEmbeddedTexture() résout ce chemin. loadEmbeddedTexture() décode les images compressées avec stb_image ; les rares textures non compressées arrivent en BGRA. Un .gltf ou un .obj référence des fichiers à côté de lui : loadTexture() les charge depuis le même dossier.
/// C++ — AssimpBlender.cpp — update:16/10/26
MTL::Texture* AssimpBlender::createTexture(const unsigned char* pixels, int width, int height, MTL::PixelFormat pixelFormat)
{
// Toute la chaîne de mipmaps : 1024 → 512 → … → 1, soit 1 + log2(1024) = 11 niveaux.
// Sans elles, une texture vue de loin scintille, et le filtre de mip du sampler ne sert à rien.
NS::UInteger mipCount = 1 + static_cast<NS::UInteger>(std::floor(std::log2(std::max(width, height))));
NS::SharedPtr<MTL::TextureDescriptor> textureDescriptor = NS::TransferPtr(MTL::TextureDescriptor::alloc()->init());
textureDescriptor->setTextureType(MTL::TextureType2D);
textureDescriptor->setPixelFormat(pixelFormat);
textureDescriptor->setWidth(width);
textureDescriptor->setHeight(height);
textureDescriptor->setMipmapLevelCount(mipCount);
textureDescriptor->setUsage(MTL::TextureUsageShaderRead);
MTL::Texture* texture = m_device->newTexture(textureDescriptor.get());
MTL::Region region = MTL::Region::Make2D(0, 0, width, height);
texture->replaceRegion(region, 0, pixels, width * 4); // niveau 0 seulement
generateMipmaps(texture);
return texture;
}
void AssimpBlender::generateMipmaps(MTL::Texture* texture)
{
if (texture->mipmapLevelCount() < 2)
return;
// Le GPU calcule les niveaux 1…n à partir du niveau 0. Une seule fois, au chargement :
// attendre la fin ici ne coûte rien pendant le jeu.
NS::AutoreleasePool* pool = NS::AutoreleasePool::alloc()->init(); // commandBuffer() est autoreleased
MTL::CommandBuffer* commandBuffer = m_commandQueue->commandBuffer();
MTL::BlitCommandEncoder* blit = commandBuffer->blitCommandEncoder();
blit->generateMipmaps(texture);
blit->endEncoding();
commandBuffer->commit();
commandBuffer->waitUntilCompleted();
pool->release();
}
MTL::Texture* AssimpBlender::loadEmbeddedTexture(const aiTexture* pTexture, bool sRGB)
{
if (pTexture->mHeight == 0) // compressée (PNG, JPG…) : mWidth = taille du fichier en octets
{
int width, height, channels;
unsigned char* data = stbi_load_from_memory(reinterpret_cast<const unsigned char*>(pTexture->pcData), pTexture->mWidth, &width, &height, &channels, 4);
if (!data)
{
printf("Texture embarquée illisible : %s\n", stbi_failure_reason());
return nullptr;
}
MTL::Texture* texture = createTexture(data, width, height, sRGB ? MTL::PixelFormatRGBA8Unorm_sRGB : MTL::PixelFormatRGBA8Unorm);
stbi_image_free(data);
return texture;
}
// Décompressée : mWidth × mHeight texels aiTexel, rangés { b, g, r, a } → format BGRA,
// sinon le rouge et le bleu sont inversés
return createTexture(reinterpret_cast<const unsigned char*>(pTexture->pcData), pTexture->mWidth, pTexture->mHeight,
sRGB ? MTL::PixelFormatBGRA8Unorm_sRGB : MTL::PixelFormatBGRA8Unorm);
}
void AssimpBlender::loadTextures(const aiScene* scene, Blender& model, const std::string& directory)
{
if (scene->mNumMaterials == 0 || scene->mNumMeshes == 0) return;
// Un Blender = un seul jeu de textures : celui du matériau du premier mesh.
// (mMaterials[0] peut être le matériau par défaut qu'Assimp ajoute, sans aucune texture.)
aiMaterial* mat = scene->mMaterials[scene->mMeshes[0]->mMaterialIndex];
aiString path;
auto loadTex = [&](aiTextureType type, bool sRGB) -> MTL::Texture*
{
if (mat->GetTexture(type, 0, &path) != AI_SUCCESS) return nullptr;
// Texture embarquée (.glb) : chemin « *0 », « *1 »… ou nom de fichier connu de la scène
if (const aiTexture* embedded = scene->GetEmbeddedTexture(path.C_Str()))
return loadEmbeddedTexture(embedded, sRGB);
return loadTexture(directory, path.C_Str(), sRGB); // fichier à côté du .gltf / .obj
};
// Couleur en sRGB (le GPU la linéarise à la lecture), données (normales, rugosité…) en linéaire
model.diffuseTexture = loadTex(aiTextureType_DIFFUSE, true);
model.normalTexture = loadTex(aiTextureType_NORMALS, false);
model.roughnessTexture = loadTex(aiTextureType_DIFFUSE_ROUGHNESS, false);
model.metallicTexture = loadTex(aiTextureType_METALNESS, false);
model.ambientOcclusion = loadTex(aiTextureType_AMBIENT_OCCLUSION, false);
}
MTL::Texture* AssimpBlender::loadTexture(const std::string& directory, const char* path, bool sRGB)
{
std::string fullPath = directory + "/" + std::string(path);
int width, height, channels;
unsigned char* data = stbi_load(fullPath.c_str(), &width, &height, &channels, 4);
if (!data)
{
printf("Texture introuvable : %s (%s)\n", fullPath.c_str(), stbi_failure_reason());
return nullptr;
}
MTL::Texture* texture = createTexture(data, width, height, sRGB ? MTL::PixelFormatRGBA8Unorm_sRGB : MTL::PixelFormatRGBA8Unorm);
stbi_image_free(data);
return texture;
}
void AssimpBlender::addAnimationLayer(size_t modelIndex, const std::string& animName, float weight)
{
if (modelIndex >= m_models.size())
return;
Blender& model = m_models[modelIndex];
if (!model.hasAnimations(animName))
{
printf("Warning: AnimationAssimp '%s' not found\n", animName.c_str());
return;
}
AnimationLayer layer;
layer.animationIndex = model.getAnimationIndex(animName);
layer.weight = weight;
layer.currentTime = 0.0f;
layer.isPlaying = true;
layer.loop = true;
model.animationLayers.push_back(layer);
model.useLayeredAnimation = true;
printf("Added layer: '%s' (weight: %.2f)\n", animName.c_str(), weight);
}
void AssimpBlender::clearAnimationLayers(size_t modelIndex)
{
if (modelIndex >= m_models.size())
return;
m_models[modelIndex].animationLayers.clear();
m_models[modelIndex].useLayeredAnimation = false;
}
Couleur en sRGB, données en linéaire. La couleur de base est stockée en sRGB : le format _sRGB la fait linéariser par le GPU à la lecture. Normales, rugosité et métal sont des données : en sRGB, elles seraient faussées.
Rugosité et métal partagent une image : rugosité dans le canal G, métal dans le canal B. Assimp la donne à la fois pour aiTextureType_DIFFUSE_ROUGHNESS et aiTextureType_METALNESS : le shader lit .g d'un côté, .b de l'autre.
Mipmaps. createTexture() alloue toute la chaîne de niveaux, puis le GPU la calcule une fois, au chargement. Sans elles, une texture vue de loin scintille.
Un matériau par modèle. Tous les meshes sont fusionnés dans un seul vertex buffer, avec les textures du matériau du premier mesh. Un modèle à plusieurs matériaux demande un draw call par mesh : ce sera l'objet d'un chapitre à part.
Animations — aiAnimation → BoneAnimation
/// C++ — AssimpBlender.cpp — update:17/10/26
void AssimpBlender::loadAnimations(const aiScene *scene, Blender& model)
{
for (unsigned i = 0; i < scene->mNumAnimations; i++)
{
aiAnimation* anim = scene->mAnimations[i];
AnimationAssimp anyme;
anyme.name = anim->mName.C_Str();
anyme.duration = (float)anim->mDuration;
// Durée en ticks : ticksPerSec convertit en secondes. Ce n'est PAS le framerate du rendu.
// glTF/GLB via Assimp : temps en millisecondes → mTicksPerSecond = 1000.
// 120.0f ne sert que si le fichier ne précise rien (0).
anyme.ticksPerSec = anim->mTicksPerSecond > 0 ? (float)anim->mTicksPerSecond : 120.0f;
// Chaque channel = un bone animé
for (unsigned c = 0; c < anim->mNumChannels; c++)
{
aiNodeAnim* ch = anim->mChannels[c];
BoneAnimation ba;
ba.boneName = ch->mNodeName.C_Str(); // = nom du bone dans la hiérarchie (Bone.089)
// ch->mPositionKeys, mRotationKeys, mScalingKeys = keyframes TRS
for (unsigned p = 0; p < ch->mNumPositionKeys; p++)
{
auto& key = ch->mPositionKeys[p];
ba.positions.push_back({(float)(key.mTime), {key.mValue.x, key.mValue.y, key.mValue.z}}); //ch->mPositionKeys[p].mTime, {ch->mPositionKeys[p].mValue.x, ch->mPositionKeys[p].mValue.y, ch->mPositionKeys[p].mValue.z}});
}
for (unsigned r = 0; r < ch->mNumRotationKeys; r++)
{
auto& key = ch->mRotationKeys[r];
ba.rotations.push_back({(float)(key.mTime), simd_quaternion(key.mValue.x, key.mValue.y, key.mValue.z, key.mValue.w)});//ch->mRotationKeys[r].mTime, simd_quaternion(q.x, q.y, q.z, q.w)});
}
for (unsigned s = 0; s < ch->mNumScalingKeys; s++)
{
auto& key = ch->mScalingKeys[s];
ba.scales.push_back({(float)(key.mTime), {key.mValue.x, key.mValue.y, key.mValue.z}});
}
anyme.channels.push_back(ba);
}
model.animationMap[anyme.name] = i;
model.animations.push_back(anyme);
}
}
Une animation est stockée en ticks : duration / ticksPerSec donne sa durée en secondes. Avec un .glb, Assimp compte en millisecondes : mTicksPerSecond vaut 1000. Forcé à 500, l'animation jouait deux fois trop lentement.
120.0f n'est que la valeur de secours, si le fichier ne précise rien. Le framerate du rendu (60, 120 Hz…) ne change rien : update() avance le temps de delta × ticksPerSec, et l'interpolation entre deux keyframes calcule une pose exacte à chaque image, que le jeu tourne à 30 ou à 120 FPS.
Sampler pour un résultat optimal
/// C++ — AssimpBlender.cpp — update:16/10/26
void AssimpBlender::createSampler()
{
NS::SharedPtr<MTL::SamplerDescriptor> samplerDesc = NS::TransferPtr(MTL::SamplerDescriptor::alloc()->init());
samplerDesc->setMinFilter(MTL::SamplerMinMagFilterLinear);
samplerDesc->setMagFilter(MTL::SamplerMinMagFilterLinear);
samplerDesc->setMipFilter(MTL::SamplerMipFilterLinear);
samplerDesc->setSAddressMode(MTL::SamplerAddressModeRepeat);
samplerDesc->setTAddressMode(MTL::SamplerAddressModeRepeat);
samplerDesc->setMaxAnisotropy(16);
m_samplerState = m_device->newSamplerState(samplerDesc.get());
}
void AssimpBlender::computeBoneTransforms(float time, const NodeData& node, const simd::float4x4& parentTf, Blender& model)
{
simd::float4x4 localTf = node.transform; // pose du fichier si ce node n'est pas animé
if (!model.animations.empty())
{
AnimationAssimp& anim = model.animations[model.currentAnimation];
for (auto& ch : anim.channels)
{
if (ch.boneName == node.name)
{
localTf = makeTRS(interpolatePosition(time, ch), interpolateRotation(time, ch), interpolateScale(time, ch));
break;
}
}
}
simd::float4x4 globalTf = parentTf * localTf;
auto it = model.boneMap.find(node.name);
if (it != model.boneMap.end())
model.boneMatrices[it->second.id] = globalTf * it->second.offset;
for (const auto& child : node.children)
computeBoneTransforms(time, child, globalTf, model);
}
void AssimpBlender::computeBoneTransformsLayered(const NodeData& node, const simd::float4x4& parentTf, Blender& model,
const std::vector<AnimationLayer>& layers)
{
// On mélange position / rotation / échelle de chaque layer, PUIS on reconstruit une matrice.
// Mélanger les matrices finales écrase le maillage (les rotations ne s'additionnent pas).
simd::float3 position = {0, 0, 0};
simd::float3 scale = {0, 0, 0};
simd::float4 rotation = {0, 0, 0, 0}; // quaternion (x, y, z, w) accumulé
float totalWeight = 0.0f;
for (const auto& layer : layers)
{
if (!layer.isPlaying || layer.weight <= 0.0f)
continue;
const AnimationAssimp& anim = model.animations[layer.animationIndex];
for (const auto& ch : anim.channels)
{
if (ch.boneName != node.name)
continue;
simd::float4 q = interpolateRotation(layer.currentTime, ch).vector;
if (totalWeight > 0.0f && simd::dot(rotation, q) < 0.0f)
q = -q; // q et -q = même rotation : on reste du même côté, sinon le mélange tourne « par l'autre côté »
position += interpolatePosition(layer.currentTime, ch) * layer.weight;
scale += interpolateScale(layer.currentTime, ch) * layer.weight;
rotation += q * layer.weight;
totalWeight += layer.weight;
break;
}
}
simd::float4x4 localTf = node.transform; // aucun layer n'anime ce node : pose du fichier
if (totalWeight > 0.0f) // poids relatifs : 0.7 + 0.3 ou 7 + 3 donnent le même mélange
localTf = makeTRS(position / totalWeight, simd_quaternion(simd::normalize(rotation)), scale / totalWeight);
simd::float4x4 globalTf = parentTf * localTf;
auto it = model.boneMap.find(node.name);
if (it != model.boneMap.end())
model.boneMatrices[it->second.id] = globalTf * it->second.offset;
for (const auto& child : node.children)
computeBoneTransformsLayered(child, globalTf, model, layers);
}
simd::float3 AssimpBlender::interpolatePosition(float time, const BoneAnimation& anim)
{
if (anim.positions.size() == 1) return anim.positions[0].value;
size_t i = 0;
while (i < anim.positions.size() - 1 && anim.positions[i + 1].time < time) i++;
size_t j = (i + 1) % anim.positions.size();
float dt = anim.positions[j].time - anim.positions[i].time;
float t = (dt > 0) ? (time - anim.positions[i].time) / dt : 0;
return simd_mix(anim.positions[i].value, anim.positions[j].value, t);
}
simd::quatf AssimpBlender::interpolateRotation(float time, const BoneAnimation& anim)
{
if (anim.rotations.size() == 1) return anim.rotations[0].value;
size_t i = 0;
while (i < anim.rotations.size() - 1 && anim.rotations[i + 1].time < time) i++;
size_t j = (i + 1) % anim.rotations.size();
float dt = anim.rotations[j].time - anim.rotations[i].time;
float t = (dt > 0) ? (time - anim.rotations[i].time) / dt : 0;
return simd::slerp(anim.rotations[i].value, anim.rotations[j].value, t);
}
simd::float3 AssimpBlender::interpolateScale(float time, const BoneAnimation& anim)
{
if (anim.scales.size() == 1) return anim.scales[0].value;
size_t i = 0;
while (i < anim.scales.size() - 1 && anim.scales[i + 1].time < time) i++;
size_t j = (i + 1) % anim.scales.size();
float dt = anim.scales[j].time - anim.scales[i].time;
float t = (dt > 0) ? (time - anim.scales[i].time) / dt : 0;
return simd_mix(anim.scales[i].value, anim.scales[j].value, t);
}
void AssimpBlender::printMemoryStats() const
{
size_t totalVertexMem = 0, totalIndexMem = 0, totalUniformMem = 0;
size_t staticCount = 0, skinnedCount = 0;
printf("\n=== AssimpBlender Memory Stats ===\n");
for (size_t index = 0; index < m_models.size(); index++)
{
if (!m_slots[index].alive) continue; // slot déchargé
const Blender& m = m_models[index];
size_t vertMem, unifMem;
if (m.hasAnimation) {
vertMem = m.verticesFull.size() * sizeof(VertexBlenderFull);
unifMem = sizeof(BlenderUniformsFull);
skinnedCount++;
} else {
vertMem = m.vertices.size() * sizeof(VertexBlender);
unifMem = sizeof(BlenderUniforms);
staticCount++;
}
size_t idxMem = m.indices.size() * sizeof(uint32_t);
printf(" %-20s %s V:%.1fKB I:%.1fKB U:%.1fKB\n",
m.name.c_str(), m.hasAnimation ? "[SKIN]" : "[STAT]",
vertMem / 1024.f, idxMem / 1024.f, unifMem / 1024.f);
totalVertexMem += vertMem;
totalIndexMem += idxMem;
totalUniformMem += unifMem;
}
printf("--------------------------------\n");
printf(" Models: %zu static, %zu skinned\n", staticCount, skinnedCount);
printf(" Total: %.1f KB (V:%.1f + I:%.1f + U:%.1f)\n",
(totalVertexMem + totalIndexMem + totalUniformMem) / 1024.f,
totalVertexMem / 1024.f, totalIndexMem / 1024.f, totalUniformMem / 1024.f);
printf("================================\n\n");
}
void AssimpBlender::printAnimations(size_t modelIndex) const
{
if (modelIndex >= m_models.size()) return;
const Blender& model = m_models[modelIndex];
printf("\n=== Animations for '%s' ===\n", model.name.c_str());
for (size_t i = 0; i < model.animations.size(); i++)
{
const AnimationAssimp& anim = model.animations[i];
printf(" [%zu] '%s' - %.2fs @ %.1f tps\n",
i, anim.name.c_str(),
anim.duration / anim.ticksPerSec,
anim.ticksPerSec);
}
printf("========================\n\n");
}
void AssimpBlender::debugBones(size_t modelIndex) const
{
if (modelIndex >= m_models.size()) return;
const Blender& model = m_models[modelIndex];
printf("\n=== BONES DEBUG ===\n");
printf("Model: %s\n", model.name.c_str());
printf("Bone count: %d\n\n", model.boneCount);
for (const auto& bonePair : model.boneMap)
{
const std::string& boneName = bonePair.first;
const BoneInfo& boneInfo = bonePair.second;
printf("Bone [%d]: %s\n", boneInfo.id, boneName.c_str());
printf(" Offset matrix:\n");
for (int row = 0; row < 4; row++)
{
printf(" [%.3f, %.3f, %.3f, %.3f]\n",
boneInfo.offset.columns[row].x,
boneInfo.offset.columns[row].y,
boneInfo.offset.columns[row].z,
boneInfo.offset.columns[row].w);
}
printf("\n");
}
}
void AssimpBlender::playAnimation(size_t modelIndex, const std::string& animName, bool loop)
{
if (modelIndex >= m_models.size())
return;
Blender& model = m_models[modelIndex];
if (!model.hasAnimations(animName))
{
printf("Warning: AnimationAssimp '%s' not found in model '%s'\n",
animName.c_str(), model.name.c_str());
return;
}
size_t animIndex = model.getAnimationIndex(animName);
model.currentAnimation = animIndex;
model.currentTime = 0.0f;
model.animController.isPlaying = true;
model.animController.loop = loop;
model.animController.isInTransitioning = false;
printf("Playing animation '%s' on model '%s'\n", animName.c_str(), model.name.c_str());
}
void AssimpBlender::playAnimation(const std::string& modelName, const std::string& animName, bool loop)
{
auto it = m_modelNameToIndex.find(modelName);
if (it == m_modelNameToIndex.end())
{
printf("Warning: Model '%s' not found\n", modelName.c_str());
return;
}
playAnimation(it->second, animName, loop);
}
void AssimpBlender::transitionToAnimation(size_t modelIndex, const std::string& animName, float duration)
{
if (modelIndex >= m_models.size())
return;
Blender& model = m_models[modelIndex];
if (!model.hasAnimations(animName))
return;
size_t targetIndex = model.getAnimationIndex(animName);
if (targetIndex == model.currentAnimation && !model.animController.isInTransitioning)
return;
model.animController.isInTransitioning = true;
model.animController.isPlaying = true;
model.animController.targetAnimation = targetIndex;
model.animController.targetTime = 0.0f; // la cible démarre à son début
model.animController.transitionDuration = std::max(duration, 0.001f); // en secondes ; 0 = bascule immédiate
model.animController.transitionTime = 0.0f;
}
void AssimpBlender::stopAnimation(size_t modelIndex)
{
if (modelIndex >= m_models.size())
return;
m_models[modelIndex].animController.isPlaying = false;
}
void AssimpBlender::setAnimationSpeed(size_t modelIndex, float speed)
{
if (modelIndex >= m_models.size())
return;
m_models[modelIndex].animController.speedMultiplier = speed;
}
void AssimpBlender::draw(MTL::RenderCommandEncoder* renderCommandEncoder, const GlobalUniforms &uniforms)
{
for (size_t i = 0; i < m_models.size(); i++)
drawBlender(renderCommandEncoder, i, m_models[i].transform, uniforms);
}
void AssimpBlender::drawBlender(MTL::RenderCommandEncoder* renderCommandEncoder, size_t index, const simd::float4x4 &modelMatrix, const GlobalUniforms &uniforms)
{
if (index >= m_models.size() || !m_slots[index].alive) return; // slot vide : rien à dessiner
Blender& model = m_models[index];
if (model.hasAnimation)
{
BlenderUniformsFull* modelUniforms = (BlenderUniformsFull *)model.uniformBuffer->contents();
modelUniforms->modelMatrix = modelMatrix;
modelUniforms->viewProjectionMatrix = uniforms.cameraUniforms.viewProjectionMatrix;
// boneMatrices[BLENDER_MAX_BONES] : jamais plus, même si loadModel() a déjà filtré
size_t boneCount = std::min<size_t>(model.boneCount, BLENDER_MAX_BONES);
memcpy(modelUniforms->boneMatrices, model.boneMatrices.data(), boneCount * sizeof(simd::float4x4));
renderCommandEncoder->setRenderPipelineState(m_renderPipelineStateFull);
}
else
{
BlenderUniforms* modelUniforms = (BlenderUniforms *)model.uniformBuffer->contents();
modelUniforms->modelMatrix = modelMatrix;
modelUniforms->viewProjectionMatrix = uniforms.cameraUniforms.viewProjectionMatrix;
renderCommandEncoder->setRenderPipelineState(m_renderPipelineState);
}
renderCommandEncoder->setDepthStencilState(m_depthStencilState);
renderCommandEncoder->setCullMode(MTL::CullModeNone);
renderCommandEncoder->setFrontFacingWinding(MTL::WindingCounterClockwise);
renderCommandEncoder->setVertexBuffer(model.vertexBuffer, 0, 0);
renderCommandEncoder->setVertexBuffer(model.uniformBuffer, 0, 1);
renderCommandEncoder->setFragmentBuffer(model.uniformBuffer, 0, 0);
renderCommandEncoder->setFragmentBytes(&uniforms.sun, sizeof(Sun), 1);
renderCommandEncoder->setFragmentTexture(model.diffuseTexture, 0);
renderCommandEncoder->setFragmentTexture(model.normalTexture, 1);
renderCommandEncoder->setFragmentTexture(model.roughnessTexture, 2);
renderCommandEncoder->setFragmentTexture(model.metallicTexture, 3);
renderCommandEncoder->setFragmentSamplerState(m_samplerState, 0);
renderCommandEncoder->drawIndexedPrimitives(MTL::PrimitiveTypeTriangle, model.indices.size(), MTL::IndexTypeUInt32, model.indexBuffer, 0);
}
drawBlender() réécrit l'uniform buffer à chaque frame. Tant que le Renderer attend la fin du GPU (waitUntilCompleted()), le GPU a fini de lire la frame précédente : aucun conflit. Le jour où cette attente disparaît (↘ Synchronisation), il faudra un buffer par frame en vol, sinon le CPU écrase des matrices que le GPU est encore en train de lire.
Le Shader
/// MSL — AssimpBlender.metal — update:16/10/26
#include <metal_stdlib>
#include "../includes/SharedGPU/AssimpBlender_shared.h"
#include "../includes/SharedGPU/Renderer_shared.h"
using namespace metal;
struct VertexBlender
{
float3 position [[attribute(0)]];
float3 normal [[attribute(1)]];
float2 texCoord [[attribute(2)]];
float4 tangent [[attribute(3)]]; // xyz = tangente, w = ±1 sens de la bitangente
};
struct VertexBlenderFull
{
float3 position [[attribute(0)]];
float3 normal [[attribute(1)]];
float2 texCoord [[attribute(2)]];
int4 joints [[attribute(3)]]; // 4 os par vertex : la convention glTF (JOINTS_0 est un vec4)
float4 weights [[attribute(4)]];
float4 tangent [[attribute(5)]];
};
struct VertexOut
{
float4 position [[position]];
float3 normal;
float4 tangent;
float2 texCoord;
float3 worldPos;
};
vertex VertexOut vertex_Assimp(VertexBlender in [[stage_in]],
constant BlenderUniforms& uniforms [[buffer(1)]])
{
VertexOut out;
float4 worldPos = uniforms.modelMatrix * float4(in.position, 1.0);
out.position = uniforms.viewProjectionMatrix * worldPos;
out.worldPos = worldPos.xyz;
// modelMatrix à échelle uniforme (makeScale({3, 3, 3})) : elle sert aussi pour les normales
out.normal = normalize((uniforms.modelMatrix * float4(in.normal, 0.0)).xyz);
out.tangent = float4(normalize((uniforms.modelMatrix * float4(in.tangent.xyz, 0.0)).xyz), in.tangent.w);
out.texCoord = in.texCoord;
return out;
}
vertex VertexOut vertex_AssimpAnyme(VertexBlenderFull in [[stage_in]],
constant BlenderUniformsFull& uniforms [[buffer(1)]])
{
VertexOut out;
float4x4 skin = uniforms.boneMatrices[in.joints.x] * in.weights.x + uniforms.boneMatrices[in.joints.y] * in.weights.y + uniforms.boneMatrices[in.joints.z] * in.weights.z + uniforms.boneMatrices[in.joints.w] * in.weights.w;
float4 skinnedPos = skin * float4(in.position, 1.0);
float3 skinnedNormal = normalize((skin * float4(in.normal, 0.0)).xyz);
float3 skinnedTangent = normalize((skin * float4(in.tangent.xyz, 0.0)).xyz);
float4 worldPos = uniforms.modelMatrix * skinnedPos;
out.position = uniforms.viewProjectionMatrix * worldPos;
out.worldPos = worldPos.xyz;
out.normal = normalize((uniforms.modelMatrix * float4(skinnedNormal, 0.0)).xyz);
out.tangent = float4(normalize((uniforms.modelMatrix * float4(skinnedTangent, 0.0)).xyz), in.tangent.w);
out.texCoord = in.texCoord;
return out;
}
fragment float4 fragment_Assimp(VertexOut in [[stage_in]],
texture2d<float> diffuseTexture [[texture(0)]],
texture2d<float> normalTexture [[texture(1)]],
texture2d<float> roughnessTexture [[texture(2)]],
texture2d<float> metallicTexture [[texture(3)]],
sampler textureSampler [[sampler(0)]],
constant Sun& sun [[buffer(1)]])
{
// Un modèle n'a pas toujours toutes ses textures : une texture non liée se lit comme nullptr,
// is_null_texture() évite de l'échantillonner et donne une valeur neutre à la place.
float4 albedo = is_null_texture(diffuseTexture) ? float4(1.0) : diffuseTexture.sample(textureSampler, in.texCoord);
// glTF range rugosité et métal dans UNE image : rugosité en G, métal en B
float roughness = is_null_texture(roughnessTexture) ? 0.5 : roughnessTexture.sample(textureSampler, in.texCoord).g;
float metallic = is_null_texture(metallicTexture) ? 0.0 : metallicTexture.sample(textureSampler, in.texCoord).b;
float3 N = normalize(in.normal);
if (!is_null_texture(normalTexture))
{ // Normal map : une normale en espace tangent (T, B, N), encodée de [-1, 1] vers [0, 1]
float3 T = normalize(in.tangent.xyz - dot(in.tangent.xyz, N) * N); // Gram-Schmidt : T bien perpendiculaire à N
float3 B = cross(N, T) * in.tangent.w;
float3 tangentNormal = normalTexture.sample(textureSampler, in.texCoord).rgb * 2.0 - 1.0;
N = normalize(float3x3(T, B, N) * tangentNormal);
}
float3 lightDir = normalize(sun.sunDirection.xyz);
float NdotL = max(dot(N, lightDir), 0.0);
// Un métal n'a pas de diffus : sa couleur passe dans le reflet
float3 diffuse = albedo.rgb * (1.0 - metallic) * NdotL * sun.sunColor.xyz;
float3 ambient = albedo.rgb * 0.3;
// Specular — Blinn-Phong : plus la surface est rugueuse, plus le reflet est large et faible
float3 viewDir = normalize(sun.cameraPosition.xyz - in.worldPos);
float3 halfDir = normalize(lightDir + viewDir);
float shininess = 32.f;
float spec = pow(max(dot(N, halfDir), 0.0), shininess * (1.0 - roughness));
float3 specularColor = mix(float3(0.04), albedo.rgb, metallic); // 4 % de reflet pour un non-métal
float3 specular = specularColor * spec * (1.0 - roughness);
float3 finalColor = ambient + diffuse + specular;
return float4(finalColor, albedo.a);
}
En-tête de notre classe
/// C++ — AssimpBlender.hpp — update:16/10/26
public:
size_t loadModel(const std::string& resourcesPath, const std::string& name = "");
void printMemoryStats() const;
void printAnimations(size_t modelIndex) const;
void debugBones(size_t modelIndex) const;
Blender* getModel(size_t index);
Blender* getModel(const std::string& name);
size_t getModelCount() const { return m_aliveCount; } // modèles chargés, slots vides exclus
void addAnimationLayer(size_t modelIndex, const std::string& animName, float weight);
void clearAnimationLayers(size_t modelIndex);
void playAnimation(size_t modelIndex, const std::string& animName, bool loop = true);
void playAnimation(const std::string& modelName, const std::string& animName, bool loop = true);
void transitionToAnimation(size_t modelIndex, const std::string& animName, float duration = 0.3f);
void stopAnimation(size_t modelIndex);
void setAnimationSpeed(size_t modelIndex, float speed);
private:
std::vector<Blender> m_models; // indexé comme m_slots : un slot déchargé y reste, vide
std::unordered_map<std::string, size_t> m_modelNameToIndex;
bool modelHasBones(aiNode* node, const aiScene* scene);
MTL::Texture* loadTexture(const std::string& directory, const char* path, bool sRGB);
MTL::Texture* loadEmbeddedTexture(const aiTexture* pTexture, bool sRGB);
MTL::Texture* createTexture(const unsigned char* pixels, int width, int height, MTL::PixelFormat pixelFormat);
void generateMipmaps(MTL::Texture* texture);
void createSampler();
void processNodeStatic(aiNode* node, const aiScene* scene, Blender& model, const simd::float4x4& parentTf);
void processNodeSkinned(aiNode* node, const aiScene* scene, Blender& model);
void processMeshStatic(aiMesh* mesh, Blender& model, const simd::float4x4& meshToModel);
void processMeshSkinned(aiMesh* mesh, aiNode* node, Blender& model);
void loadBones(aiMesh* mesh, Blender& model, uint32_t baseVertex);
int nodeBoneID(const std::string& nodeName, Blender& model);
void loadAnimations(const aiScene* scene, Blender& model);
void loadTextures(const aiScene* scene, Blender& model, const std::string& directory);
NodeData copyNodeHierarchy(aiNode* node);
void computeBoneTransforms(float time, const NodeData& node, const simd::float4x4& parentTf, Blender& model);
void computeBoneTransformsLayered(const NodeData& node, const simd::float4x4& parentTf, Blender& model,
const std::vector<AnimationLayer>& layers);
simd::float3 interpolatePosition(float time, const BoneAnimation& anim);
simd::quatf interpolateRotation(float time, const BoneAnimation& anim);
simd::float3 interpolateScale(float time, const BoneAnimation& anim);
Pour aller plus loin : une machine à états
Au lieu d'appeler playAnimation() à la main, une machine à états choisit l'animation selon des conditions : « marche » si la vitesse dépasse 0.1, « repos » sinon. Ce bloc n'a pas d'en-tête de fichier : à toi de choisir où le ranger (un AnimationStateMachine.hpp par exemple).
class AnimationStateMachine
{
public:
void addState(const std::string& name, const std::string& animName)
{
states[name] = animName;
}
void addTransition(const std::string& from, const std::string& to, std::function<bool()> condition)
{
transitions[from].push_back({to, condition});
}
void update(AssimpBlender& blender, size_t modelIndex)
{
for (auto& trans : transitions[currentState])
{
if (trans.condition())
{
setState(blender, modelIndex, trans.targetState);
break;
}
}
}
void setState(AssimpBlender& blender, size_t modelIndex, const std::string& state)
{
if (states.find(state) == states.end() || state == currentState)
return;
currentState = state;
blender.playAnimation(modelIndex, states[state]);
}
std::string getCurrentState() const { return currentState; }
private:
struct Transition
{
std::string targetState;
std::function<bool()> condition;
};
std::unordered_map<std::string, std::string> states;
std::unordered_map<std::string, std::vector<Transition>> transitions;
std::string currentState;
};
Implémentation / Intégration dans la classe principale
/// C++ — Renderer.hpp — update:16/10/26
#include "AssimpBlender.hpp"
private:
GlobalUniforms m_globalUniforms;
AssimpBlender m_assimp;
bool m_prevKeyE = false; // état de E à la frame précédente : détecte l'appui
/// C++ — Renderer.cpp — update:25/06/26
m_cursor3D(m_device, m_shaderLibrary, m_pixelFormat, m_depthPixelFormat), // ou m_skybox du projet
m_assimp(m_device, m_shaderLibrary, m_pixelFormat, m_depthPixelFormat, resourcePath),
/// C++ — Renderer.cpp — update:16/10/26 — constructeur
{
m_assimp.loadModel(resourcePath + "/Odonata.glb", "player_libell");
if (Blender* model = m_assimp.getModel("player_libell")) // nullptr si le chargement a échoué
model->transform = math::makeTranslate({0, 50, 0}) * math::makeScale({3, 3, 3}); // TRS
}
/// C++ — Renderer.cpp — update:25/06/26 — constructeur — debug
{
m_assimp.printAnimations(0);
}
/// C++ — Renderer.cpp — update:16/10/26 — update
m_cameraPerspective.setPosition(m_globalUniforms.sun.cameraPosition.xyz);
m_assimp.update(delta);
// keyE reste à true tant que la touche est enfoncée : on ne réagit qu'à l'appui,
// sinon playAnimation() remet l'animation à 0 à chaque frame et le modèle reste figé
if (m_input.keyE && !m_prevKeyE)
m_assimp.playAnimation("player_libell", "ArmatureAction", true);
m_prevKeyE = m_input.keyE;
/// C++ — Renderer.cpp — update:25/06/26 — & draw
renderCommandEncoder->setViewport(m_viewport);
m_assimp.draw(renderCommandEncoder, m_globalUniforms);
Le chemin : aiScene → MTL::Buffer
AssimpBlender fait exactement ce pipeline. Voici comment les pièces s'articulent :