Phase 30 (2/n) : geometrie compacte, pool de sous-allocation, early-Z
- Formats GPU : le format de travail Vertex (68 o) n'est plus televerse. Objets et vegetation : ObjectVertex 44 o (conversion exacte). Terrain : TerrainVertex 16 o (deux altitudes f32 + deux normales snorm16) ; x/z, cible de morphing et UV sont recalcules par terrain.vert depuis gl_VertexIndex et DrawItem::grid, au bit pres (`precise`). - Topologie des tuiles televersee UNE fois, en uint16 (96 Ko de moins par tuile). Indices des maillages d'objets en uint16. - GpuBufferPool + RangeAllocator : toute la geometrie dans des blocs de 4 Mo ; ecriture DIRECTE en memoire unifiee (GPU integre, lavapipe), staging conserve sur GPU discret (--force-staging pour l'eprouver), barriere ecriture-apres-lecture ajoutee devant les copies (validation de synchronisation a zero). - Rendu : terrain dessine apres la vegetation (early-Z) et culling de ses faces arriere. - Tests : +16 verifications (formats, positions recalculees, allocateur). Survol 900 m/s (lavapipe) : pic GPU 286 -> 89 Mo, geometrie terrain 188 -> 33 Mo, ~17 000 -> 21 vkAllocateMemory, streaming 4,5 -> 1,6 ms par image. Foret : 8,3 -> 12,4 images/s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MG5dK27RsN97DDm7CQRhx2
Cette révision appartient à :
1 Parent
16775bf1ff
révision
7f2d538768
26 fichiers modifiés
+1845
-463
Aucun fichier ne correspond à votre recherche
@@ -117,6 +117,7 @@ add_executable(vercora
|
||||
src/editor/SceneFile.cpp
|
||||
src/renderer/VulkanContext.cpp
|
||||
src/renderer/VulkanBuffer.cpp
|
||||
src/renderer/GpuBufferPool.cpp
|
||||
src/renderer/Mesh.cpp
|
||||
src/renderer/TerrainMesh.cpp
|
||||
src/renderer/TerrainNodeMesh.cpp
|
||||
|
||||
+74
-28
@@ -1,10 +1,10 @@
|
||||
#version 450
|
||||
|
||||
// Meme bloc uniforme que les shaders du cube, avec un membre supplementaire en
|
||||
// fin de bloc (terrain). Cote C++ il n'y a qu'une seule struct
|
||||
// UniformBufferObject : les shaders du cube declarent simplement une version
|
||||
// tronquee du bloc, ce qui est legal (la plage du descriptor peut etre plus
|
||||
// grande que le bloc declare, jamais l'inverse).
|
||||
// Meme bloc uniforme que les shaders du cube, avec des membres supplementaires
|
||||
// en fin de bloc. Cote C++ il n'y a qu'une seule struct UniformBufferObject :
|
||||
// les shaders declarent chacun la version tronquee du bloc qui leur suffit, ce
|
||||
// qui est legal (la plage du descriptor peut etre plus grande que le bloc
|
||||
// declare, jamais l'inverse).
|
||||
layout(binding = 0) uniform UniformBufferObject {
|
||||
mat4 view;
|
||||
mat4 proj;
|
||||
@@ -14,39 +14,82 @@ layout(binding = 0) uniform UniformBufferObject {
|
||||
// quels que soient les parametres de generation (et demain, les vraies
|
||||
// altitudes LiDAR, qui seront en metres NGF et pas du tout dans [0,16]).
|
||||
vec4 terrain;
|
||||
vec4 sun;
|
||||
vec4 sunColor;
|
||||
vec4 fog;
|
||||
vec4 precip;
|
||||
vec4 fall;
|
||||
vec4 detail;
|
||||
// PHASE 30 : la grille de la heightmap. x = origine (Heightmap::
|
||||
// worldCoord(0)), y = pas en metres, z = nombre de CELLULES par cote.
|
||||
vec4 terrainGrid;
|
||||
} ubo;
|
||||
|
||||
// Meme push constant que cube.vert : les deux pipelines partagent la meme
|
||||
// Meme push constant que cube.vert : les pipelines partagent la meme
|
||||
// signature de layout, ce qui permet au Renderer de pousser la model matrix de
|
||||
// la meme facon quel que soit le materiau.
|
||||
// params.x = debut de la bande de geomorphing, params.y = fin, en metres depuis
|
||||
// la camera. Bande vide (y <= x) = pas de morphing : c'est le cas du terrain
|
||||
// dessine d'un seul bloc (option --no-lod).
|
||||
// grid (PHASE 30) : place du maillage dans la grille de la heightmap -
|
||||
// x, y = indices (ix, iz) du premier sommet, z = pas en echantillons entre deux
|
||||
// sommets voisins, w = sommets par rangee. Voir renderer/DrawItem.hpp.
|
||||
layout(push_constant) uniform PushConstants {
|
||||
mat4 model;
|
||||
vec4 params;
|
||||
ivec4 grid;
|
||||
} pc;
|
||||
|
||||
layout(location = 0) in vec3 inPosition;
|
||||
layout(location = 1) in vec3 inColor;
|
||||
layout(location = 2) in vec3 inNormal;
|
||||
// UV du sommet sur TOUT le terrain (0,0 au coin nord-ouest, 1,1 au sud-est),
|
||||
// et non sur la tuile de quadtree : c'est ce qui rend la coordonnee continue
|
||||
// d'une tuile a l'autre et independante du niveau de detail. Voir
|
||||
// TerrainNodeMesh.cpp. PHASE 11 : desormais consomme, pour l'orthophoto.
|
||||
layout(location = 3) in vec2 inUV;
|
||||
|
||||
// PHASE 10 - cible de geomorphing : position et normale de ce sommet dans la
|
||||
// grille du niveau de detail SUPERIEUR (voir renderer/TerrainNodeMesh.hpp).
|
||||
layout(location = 4) in vec3 inMorphPos;
|
||||
layout(location = 5) in vec3 inMorphNormal;
|
||||
// PHASE 30 : 16 octets par sommet au lieu de 68 (renderer/GpuVertex.hpp,
|
||||
// TerrainVertex). Le buffer ne porte plus que ce qui ne se DEDUIT pas de
|
||||
// l'indice du sommet : les deux altitudes et les deux normales (x et z en
|
||||
// snorm16, y reconstruit). Position horizontale, cible de morphing horizontale
|
||||
// et UV sont recalcules ci-dessous ; la couleur de sommet valait toujours blanc.
|
||||
layout(location = 0) in float inHeight;
|
||||
layout(location = 1) in float inMorphHeight;
|
||||
layout(location = 2) in vec2 inNormalXZ;
|
||||
layout(location = 3) in vec2 inMorphNormalXZ;
|
||||
|
||||
layout(location = 0) out vec3 fragTint;
|
||||
layout(location = 1) out vec3 fragNormal;
|
||||
layout(location = 2) out vec3 fragWorldPos;
|
||||
layout(location = 3) out vec2 fragUV;
|
||||
|
||||
// Une normale de champ de hauteur pointe toujours vers le haut : y se deduit de
|
||||
// x et z. Meme formule que unpackTerrainNormal (renderer/GpuVertex.hpp).
|
||||
vec3 decodeNormal(vec2 xz) {
|
||||
return vec3(xz.x, sqrt(max(0.0, 1.0 - xz.x * xz.x - xz.y * xz.y)), xz.y);
|
||||
}
|
||||
|
||||
void main() {
|
||||
// --- Place du sommet dans la grille -----------------------------------
|
||||
// gl_VertexIndex est l'indice LOCAL du sommet dans son maillage : le
|
||||
// Renderer lie chaque maillage a son decalage dans le bloc partage plutot
|
||||
// que de passer un vertexOffset au draw (voir Renderer::recordCommandBuffer).
|
||||
// Les indices de grille sont ECRETES sur le bord du terrain exactement comme
|
||||
// le fait TerrainNodeMesh.cpp, et la cible de morphing est le sommet aux
|
||||
// indices locaux arrondis au pair inferieur (grille du parent).
|
||||
const int perRow = pc.grid.w;
|
||||
const int i = gl_VertexIndex % perRow;
|
||||
const int j = gl_VertexIndex / perRow;
|
||||
const int cells = int(ubo.terrainGrid.z);
|
||||
const int gx = min(pc.grid.x + i * pc.grid.z, cells);
|
||||
const int gz = min(pc.grid.y + j * pc.grid.z, cells);
|
||||
const int mx = min(pc.grid.x + (i & ~1) * pc.grid.z, cells);
|
||||
const int mz = min(pc.grid.y + (j & ~1) * pc.grid.z, cells);
|
||||
|
||||
// `precise` : interdit au compilateur de fusionner la multiplication et
|
||||
// l'addition en un FMA. Sans lui le resultat pourrait differer d'un ULP de
|
||||
// Heightmap::worldCoord ; avec lui il est identique AU BIT PRES (addition et
|
||||
// multiplication flottantes sont correctement arrondies en Vulkan).
|
||||
precise float x = ubo.terrainGrid.x + float(gx) * ubo.terrainGrid.y;
|
||||
precise float z = ubo.terrainGrid.x + float(gz) * ubo.terrainGrid.y;
|
||||
precise float morphX = ubo.terrainGrid.x + float(mx) * ubo.terrainGrid.y;
|
||||
precise float morphZ = ubo.terrainGrid.x + float(mz) * ubo.terrainGrid.y;
|
||||
|
||||
const vec3 inPosition = vec3(x, inHeight, z);
|
||||
const vec3 inMorphPos = vec3(morphX, inMorphHeight, morphZ);
|
||||
|
||||
// --- Geomorphing (CDLOD) ------------------------------------------------
|
||||
// La distance est mesuree sur la position NON MORPHEE : c'est ce qui garantit
|
||||
// qu'un sommet partage par deux tuiles voisines obtient le meme facteur des
|
||||
@@ -64,23 +107,26 @@ void main() {
|
||||
}
|
||||
|
||||
vec3 position = mix(inPosition, inMorphPos, morph);
|
||||
vec3 normal = mix(inNormal, inMorphNormal, morph);
|
||||
vec3 normal = mix(decodeNormal(inNormalXZ), decodeNormal(inMorphNormalXZ), morph);
|
||||
|
||||
vec4 worldPos = pc.model * vec4(position, 1.0);
|
||||
|
||||
gl_Position = ubo.proj * ubo.view * worldPos;
|
||||
fragWorldPos = worldPos.xyz;
|
||||
fragTint = inColor;
|
||||
// Teinte neutre, reservee a une future classification LiDAR par sommet :
|
||||
// c'est la valeur que portaient tous les sommets de terrain jusqu'ici.
|
||||
fragTint = vec3(1.0);
|
||||
|
||||
// L'UV n'est PAS morphe. Il est deja une fonction affine de la position dans
|
||||
// la grille du terrain entier, donc la cible de morphing d'un sommet - qui
|
||||
// est un autre noeud de cette meme grille - a naturellement l'UV de sa
|
||||
// propre position. Interpoler entre les deux decalerait la photo par rapport
|
||||
// au relief pendant la transition de niveau, exactement ce qu'on cherche a
|
||||
// L'UV n'est PAS morphe. Il est une fonction affine de la position dans la
|
||||
// grille du terrain entier, donc la cible de morphing d'un sommet - qui est
|
||||
// un autre noeud de cette meme grille - a naturellement l'UV de sa propre
|
||||
// position. Interpoler entre les deux decalerait la photo par rapport au
|
||||
// relief pendant la transition de niveau, exactement ce qu'on cherche a
|
||||
// eviter. Le leger glissement de la texture qu'on pourrait attendre pendant
|
||||
// un morph est en realite le comportement CORRECT : la surface se deforme,
|
||||
// la photo reste accrochee a ses coordonnees geographiques.
|
||||
fragUV = inUV;
|
||||
// la photo reste accrochee a ses coordonnees geographiques. Meme expression
|
||||
// que TerrainNodeMesh.cpp (indice de grille / nombre de cellules).
|
||||
fragUV = vec2(float(gx), float(gz)) / float(cells);
|
||||
|
||||
// Le terrain est genere DIRECTEMENT en espace monde et son DrawItem porte la
|
||||
// matrice IDENTITE : mat3(model) est donc exact ici sans discussion. Il
|
||||
|
||||
+34
-5
@@ -144,6 +144,9 @@ namespace {
|
||||
// vercora.exe [scene] --freeze-anim -> horloge d'animation des shaders
|
||||
// figee : images comparables au
|
||||
// pixel pres d'un run a l'autre
|
||||
// vercora.exe [scene] --force-staging -> geometrie televersee par staging
|
||||
// meme en memoire unifiee (chemin
|
||||
// d'un GPU discret, a eprouver)
|
||||
//
|
||||
// Le terrain synthetique n'est PAS supprime, et pour deux raisons distinctes :
|
||||
// il reste la scene de reference des tests (monde deterministe, arbres a
|
||||
@@ -895,6 +898,9 @@ int main(int argc, char** argv) {
|
||||
// optimisation ne change pas l'image.
|
||||
float quitAfterSeconds = 0.0f;
|
||||
bool freezeAnimation = false;
|
||||
// PHASE 30 : --force-staging televerse la geometrie par staging meme en
|
||||
// memoire unifiee (le chemin d'un GPU discret), pour l'eprouver ici.
|
||||
bool forceStaging = false;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string argument = argv[i];
|
||||
if (argument == "--dump-world") {
|
||||
@@ -1065,6 +1071,8 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
} else if (argument == "--freeze-anim") {
|
||||
freezeAnimation = true;
|
||||
} else if (argument == "--force-staging") {
|
||||
forceStaging = true;
|
||||
} else if (argument.rfind("--", 0) == 0) {
|
||||
logWarn("Option inconnue, ignoree : " + argument);
|
||||
} else if (sceneArgument.empty()) {
|
||||
@@ -1199,7 +1207,10 @@ int main(int argc, char** argv) {
|
||||
CompositeCollisionSolver worldSolver;
|
||||
|
||||
MeshData sceneMesh;
|
||||
// PHASE 30 : le terrain d'un seul bloc (--no-lod) au format GPU compact.
|
||||
TerrainGpuMesh sceneTerrain;
|
||||
RenderOptions renderOptions;
|
||||
renderOptions.forceStaging = forceStaging;
|
||||
|
||||
Inventory inventory;
|
||||
|
||||
@@ -1219,7 +1230,10 @@ int main(int argc, char** argv) {
|
||||
// produisait 25 M de sommets et 50 M de triangles cote CPU,
|
||||
// recopies ensuite sur le GPU.
|
||||
if (!dumpWorldOnly && !useLod) {
|
||||
sceneMesh = terrainMeshData(*heightmap);
|
||||
// PHASE 30 : directement au format GPU du terrain (16 octets par
|
||||
// sommet), sans le MeshData de 68 octets par sommet - 1,7 Go de
|
||||
// moins au pic sur la zone au pas de 1 m.
|
||||
sceneTerrain = terrainGpuMeshData(*heightmap);
|
||||
}
|
||||
|
||||
renderOptions.heightRange = { heightmap->minHeight(), heightmap->maxHeight() };
|
||||
@@ -1301,8 +1315,19 @@ int main(int argc, char** argv) {
|
||||
// nombre d'instances qui les utiliseront ensuite.
|
||||
// Avec le quadtree, il n'y a pas de geometrie de scene unique : chaque
|
||||
// tuile est enregistree et liberee par le TerrainStreamer.
|
||||
const MeshHandle sceneMeshHandle =
|
||||
MeshHandle sceneMeshHandle =
|
||||
sceneMesh.empty() ? kInvalidMesh : renderer.addMesh(sceneMesh);
|
||||
if (!sceneTerrain.vertices.empty()) {
|
||||
sceneMeshHandle = renderer.addTerrainMesh(sceneTerrain.vertices, sceneTerrain.indices,
|
||||
sceneTerrain.name);
|
||||
sceneTerrain = TerrainGpuMesh{}; // la copie CPU n'a plus de raison d'etre
|
||||
}
|
||||
// PHASE 30 : la grille de la heightmap, dont terrain.vert deduit la
|
||||
// position horizontale et l'UV de chaque sommet de terrain.
|
||||
if (terrainScene) {
|
||||
renderer.setTerrainGrid(heightmap->worldCoord(0), heightmap->spacing(),
|
||||
heightmap->resolution() - 1);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 2 bis. Orthophoto (Phase 11). Chargee APRES le Renderer, qui possede
|
||||
@@ -3564,9 +3589,13 @@ int main(int argc, char** argv) {
|
||||
frameProfile.streamingMicros += profileMicros(tf1, tf2);
|
||||
} else if (sceneMeshHandle != kInvalidMesh) {
|
||||
// Terrain d'un seul bloc : sommets deja en coordonnees monde
|
||||
// -> matrice identite, et pas de bande de morphing.
|
||||
drawItems.push_back({ sceneMeshHandle, glm::mat4(1.0f),
|
||||
Material::Terrain });
|
||||
// -> matrice identite, et pas de bande de morphing. PHASE 30 :
|
||||
// une seule "tuile" qui couvre toute la grille au pas 1.
|
||||
DrawItem terrainItem{ sceneMeshHandle, glm::mat4(1.0f),
|
||||
Material::Terrain };
|
||||
terrainItem.grid = glm::ivec4(0, 0, 1,
|
||||
static_cast<int32_t>(heightmap->resolution()));
|
||||
drawItems.push_back(terrainItem);
|
||||
}
|
||||
|
||||
for (const Tree& tree : forest->trees()) {
|
||||
|
||||
@@ -76,6 +76,18 @@ struct DrawItem {
|
||||
// profondeur. Une force nulle - le cas de tous les DrawItem du jeu -
|
||||
// laisse le rendu strictement identique a celui d'avant la Phase 15.
|
||||
glm::vec4 params{0.0f, 0.0f, 0.0f, 0.0f};
|
||||
|
||||
// PHASE 30, Material::Terrain seulement : ou se trouve le maillage dans la
|
||||
// grille de la heightmap, pour que terrain.vert y retrouve la position
|
||||
// horizontale et l'UV de chaque sommet a partir de gl_VertexIndex au lieu
|
||||
// de les lire dans le buffer (voir renderer/GpuVertex.hpp, TerrainVertex).
|
||||
// x, y = indices de grille (ix, iz) du premier sommet
|
||||
// z = pas, en echantillons de grille, entre deux sommets voisins
|
||||
// w = sommets par rangee
|
||||
// Une tuile de quadtree pousse (node.ix0, node.iz0, node.stride, 65) ; le
|
||||
// terrain d'un seul bloc (--no-lod) pousse (0, 0, 1, resolution).
|
||||
// Ignore par les autres materiaux.
|
||||
glm::ivec4 grid{0, 0, 1, 1};
|
||||
};
|
||||
|
||||
// Ce que le Renderer pousse REELLEMENT en push constant, dans cet ordre.
|
||||
@@ -85,12 +97,15 @@ struct DrawItem {
|
||||
// melanger obligerait a garder `mesh` et `material` - inutiles au GPU - dans un
|
||||
// budget de push constants qui ne fait que 128 octets garantis.
|
||||
//
|
||||
// 80 octets : toujours tres en dessous des 128 garantis par la spec Vulkan pour
|
||||
// maxPushConstantsSize.
|
||||
// 96 octets depuis la Phase 30 (le bloc `grid` du terrain) : toujours en
|
||||
// dessous des 128 garantis par la spec Vulkan pour maxPushConstantsSize.
|
||||
struct DrawItemPush {
|
||||
glm::mat4 model{1.0f};
|
||||
glm::vec4 params{0.0f, 0.0f, 0.0f, 0.0f};
|
||||
glm::ivec4 grid{0, 0, 1, 1};
|
||||
};
|
||||
static_assert(sizeof(DrawItemPush) == 96 && sizeof(DrawItemPush) <= 128,
|
||||
"Le bloc de push constants doit tenir dans les 128 octets garantis.");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PHASE 11 : dessin INSTANCIE
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
#include "renderer/GpuBufferPool.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace vercora {
|
||||
|
||||
GpuBufferPool::GpuBufferPool(VulkanContext& context, VkBufferUsageFlags usage,
|
||||
VkMemoryPropertyFlags properties, bool mapped,
|
||||
VkDeviceSize blockSize)
|
||||
: context_(context), usage_(usage), properties_(properties), mapped_(mapped),
|
||||
blockSize_(blockSize) {
|
||||
if (mapped_) {
|
||||
properties_ |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
|
||||
}
|
||||
}
|
||||
|
||||
GpuBufferPool::~GpuBufferPool() {
|
||||
for (std::unique_ptr<Block>& block : blocks_) {
|
||||
if (block) {
|
||||
destroyBlock(*block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<GpuBufferPool::Block> GpuBufferPool::createBlock(VkDeviceSize capacity,
|
||||
bool dedicated) {
|
||||
auto block = std::make_unique<Block>(capacity);
|
||||
block->dedicated = dedicated;
|
||||
|
||||
VkBufferCreateInfo bufferInfo{};
|
||||
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bufferInfo.size = capacity;
|
||||
bufferInfo.usage = usage_;
|
||||
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
if (vkCreateBuffer(context_.device(), &bufferInfo, nullptr, &block->buffer) != VK_SUCCESS) {
|
||||
throw std::runtime_error("GpuBufferPool : echec de la creation d'un bloc de " +
|
||||
std::to_string(capacity) + " octets.");
|
||||
}
|
||||
|
||||
VkMemoryRequirements requirements{};
|
||||
vkGetBufferMemoryRequirements(context_.device(), block->buffer, &requirements);
|
||||
try {
|
||||
block->memory = context_.allocateMemory(requirements, properties_, mapped_);
|
||||
} catch (...) {
|
||||
vkDestroyBuffer(context_.device(), block->buffer, nullptr);
|
||||
throw;
|
||||
}
|
||||
vkBindBufferMemory(context_.device(), block->buffer, block->memory.memory, 0);
|
||||
capacityBytes_ += capacity;
|
||||
return block;
|
||||
}
|
||||
|
||||
void GpuBufferPool::destroyBlock(Block& block) {
|
||||
capacityBytes_ -= block.ranges.capacity();
|
||||
vkDestroyBuffer(context_.device(), block.buffer, nullptr);
|
||||
block.buffer = VK_NULL_HANDLE;
|
||||
context_.freeMemory(block.memory);
|
||||
}
|
||||
|
||||
GpuRange GpuBufferPool::allocate(VkDeviceSize size) {
|
||||
if (size == 0) {
|
||||
throw std::runtime_error("GpuBufferPool : allocation de taille nulle.");
|
||||
}
|
||||
|
||||
uint32_t index = UINT32_MAX;
|
||||
uint64_t offset = RangeAllocator::kInvalid;
|
||||
|
||||
if (size > blockSize_ / 2) {
|
||||
// Bloc DEDIE, a la taille exacte : un tres gros maillage ne doit ni
|
||||
// gacher un bloc standard, ni l'empecher de servir aux autres.
|
||||
for (uint32_t k = 0; k <= blocks_.size(); ++k) {
|
||||
if (k == blocks_.size() || !blocks_[k]) {
|
||||
index = k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
auto block = createBlock(size, true);
|
||||
offset = block->ranges.allocate(size, kAlignment);
|
||||
if (index == blocks_.size()) {
|
||||
blocks_.push_back(std::move(block));
|
||||
} else {
|
||||
blocks_[index] = std::move(block);
|
||||
}
|
||||
} else {
|
||||
// Premier bloc standard qui a la place.
|
||||
for (uint32_t k = 0; k < blocks_.size(); ++k) {
|
||||
Block* block = blocks_[k].get();
|
||||
if (block == nullptr || block->dedicated) {
|
||||
continue;
|
||||
}
|
||||
offset = block->ranges.allocate(size, kAlignment);
|
||||
if (offset != RangeAllocator::kInvalid) {
|
||||
index = k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (offset == RangeAllocator::kInvalid) {
|
||||
for (uint32_t k = 0; k <= blocks_.size(); ++k) {
|
||||
if (k == blocks_.size() || !blocks_[k]) {
|
||||
index = k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
auto block = createBlock(blockSize_, false);
|
||||
offset = block->ranges.allocate(size, kAlignment);
|
||||
if (index == blocks_.size()) {
|
||||
blocks_.push_back(std::move(block));
|
||||
} else {
|
||||
blocks_[index] = std::move(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Block& block = *blocks_[index];
|
||||
GpuRange range;
|
||||
range.buffer = block.buffer;
|
||||
range.offset = offset;
|
||||
range.size = size;
|
||||
range.block = index;
|
||||
if (block.memory.mapped != nullptr) {
|
||||
range.mapped = static_cast<unsigned char*>(block.memory.mapped) + offset;
|
||||
}
|
||||
usedBytes_ += size;
|
||||
return range;
|
||||
}
|
||||
|
||||
void GpuBufferPool::release(const GpuRange& range) {
|
||||
if (!range.valid() || range.block >= blocks_.size() || !blocks_[range.block]) {
|
||||
return;
|
||||
}
|
||||
Block& block = *blocks_[range.block];
|
||||
block.ranges.release(range.offset, range.size);
|
||||
usedBytes_ -= range.size;
|
||||
if (!block.ranges.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Bloc vide. Un bloc dedie part toujours ; un bloc standard part seulement
|
||||
// s'il existe deja un AUTRE bloc standard vide - en survol, les tuiles
|
||||
// evincees et construites se croisent sans cesse, et rendre puis
|
||||
// reallouer 4 Mo a chaque passage a vide ramenerait les allocations que ce
|
||||
// pool supprime.
|
||||
bool keep = !block.dedicated;
|
||||
if (keep) {
|
||||
for (uint32_t k = 0; k < blocks_.size(); ++k) {
|
||||
if (k != range.block && blocks_[k] && !blocks_[k]->dedicated &&
|
||||
blocks_[k]->ranges.empty()) {
|
||||
keep = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!keep) {
|
||||
destroyBlock(block);
|
||||
blocks_[range.block].reset();
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t GpuBufferPool::blockCount() const {
|
||||
uint32_t count = 0;
|
||||
for (const std::unique_ptr<Block>& block : blocks_) {
|
||||
count += block ? 1u : 0u;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
std::string GpuBufferPool::statsLine() const {
|
||||
char text[160];
|
||||
std::snprintf(text, sizeof(text),
|
||||
"%.1f Mo de geometrie dans %u bloc(s) de %.1f Mo au total%s",
|
||||
static_cast<double>(usedBytes_) / (1024.0 * 1024.0), blockCount(),
|
||||
static_cast<double>(capacityBytes_) / (1024.0 * 1024.0),
|
||||
mapped_ ? ", ecriture directe (memoire unifiee)" : ", par staging");
|
||||
return text;
|
||||
}
|
||||
|
||||
} // namespace vercora
|
||||
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include "renderer/RangeAllocator.hpp"
|
||||
#include "renderer/VulkanContext.hpp" // GpuAllocation
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace vercora {
|
||||
|
||||
// PHASE 30. Une plage de geometrie dans un bloc partage.
|
||||
struct GpuRange {
|
||||
VkBuffer buffer = VK_NULL_HANDLE;
|
||||
VkDeviceSize offset = 0;
|
||||
VkDeviceSize size = 0;
|
||||
// Non nul quand le bloc est mappe (memoire unifiee) : l'appelant ECRIT LA,
|
||||
// et le GPU lit exactement ces octets - ni staging, ni copie.
|
||||
void* mapped = nullptr;
|
||||
uint32_t block = UINT32_MAX; // interne au pool
|
||||
|
||||
bool valid() const { return buffer != VK_NULL_HANDLE; }
|
||||
};
|
||||
|
||||
// PHASE 30. Sous-allocation de TOUTE la geometrie du moteur (sommets et
|
||||
// indices, objets et tuiles de terrain) dans quelques gros blocs Vulkan.
|
||||
//
|
||||
// LE PROBLEME MESURE : un vkAllocateMemory par buffer, soit deux par maillage
|
||||
// plus deux de staging par televersement - ~17 000 appels en 30 s de survol
|
||||
// (NOTES-PHASE30.md). Chaque appel est un aller-retour noyau sous Windows,
|
||||
// arrondi a la granularite d'allocation du systeme, et le nombre de blocs
|
||||
// vivants est plafonne par maxMemoryAllocationCount (souvent 4 096) : c'est ce
|
||||
// plafond qui imposait les 512 tuiles residentes au plus.
|
||||
//
|
||||
// LE PRINCIPE : des blocs de kBlockSize octets, chacun un VkBuffer unique dans
|
||||
// lequel les maillages occupent des PLAGES (RangeAllocator, premier
|
||||
// ajustement). Une demande plus grande que la moitie d'un bloc recoit un bloc
|
||||
// DEDIE a sa taille exacte (le terrain d'un seul bloc de --no-lod, ~400 Mo).
|
||||
// Un bloc qui se vide est rendu au pilote, sauf le dernier bloc vide, garde
|
||||
// pour amortir le va-et-vient du streaming.
|
||||
//
|
||||
// SYNCHRONISATION : AUCUNE ici. release() rend la plage IMMEDIATEMENT ; c'est
|
||||
// a l'appelant de ne la rendre que lorsque plus aucune image en vol ne la lit
|
||||
// - ce que fait deja le Renderer pour tout maillage retire (retiredMeshes_,
|
||||
// kMaxFramesInFlight + 1 images, voir Renderer::removeMesh).
|
||||
class GpuBufferPool {
|
||||
public:
|
||||
// `mapped` = true : les blocs sont alloues HOST_VISIBLE | HOST_COHERENT et
|
||||
// mappes en permanence (memoire unifiee), les plages renvoyees portent
|
||||
// alors un pointeur d'ecriture directe.
|
||||
GpuBufferPool(VulkanContext& context, VkBufferUsageFlags usage,
|
||||
VkMemoryPropertyFlags properties, bool mapped,
|
||||
VkDeviceSize blockSize = kDefaultBlockSize);
|
||||
~GpuBufferPool();
|
||||
|
||||
GpuBufferPool(const GpuBufferPool&) = delete;
|
||||
GpuBufferPool& operator=(const GpuBufferPool&) = delete;
|
||||
|
||||
// 4 Mo : 60 tuiles de terrain par bloc ; la perte moyenne au pic (un
|
||||
// demi-bloc) reste sous les 2 Mo.
|
||||
static constexpr VkDeviceSize kDefaultBlockSize = 4ull * 1024 * 1024;
|
||||
|
||||
// 256 : couvre l'alignement de tout format de sommet et d'indice, et le
|
||||
// nonCoherentAtomSize des GPU courants.
|
||||
static constexpr VkDeviceSize kAlignment = 256;
|
||||
|
||||
// Lance std::runtime_error si le pilote refuse un nouveau bloc.
|
||||
GpuRange allocate(VkDeviceSize size);
|
||||
void release(const GpuRange& range);
|
||||
|
||||
bool mapped() const { return mapped_; }
|
||||
|
||||
// Bilan : octets reserves par des plages, octets alloues au pilote, blocs.
|
||||
VkDeviceSize usedBytes() const { return usedBytes_; }
|
||||
VkDeviceSize capacityBytes() const { return capacityBytes_; }
|
||||
uint32_t blockCount() const;
|
||||
std::string statsLine() const;
|
||||
|
||||
private:
|
||||
struct Block {
|
||||
VkBuffer buffer = VK_NULL_HANDLE;
|
||||
GpuAllocation memory;
|
||||
RangeAllocator ranges;
|
||||
bool dedicated = false;
|
||||
|
||||
explicit Block(VkDeviceSize capacity) : ranges(capacity) {}
|
||||
};
|
||||
|
||||
std::unique_ptr<Block> createBlock(VkDeviceSize capacity, bool dedicated);
|
||||
void destroyBlock(Block& block);
|
||||
|
||||
VulkanContext& context_;
|
||||
VkBufferUsageFlags usage_ = 0;
|
||||
VkMemoryPropertyFlags properties_ = 0;
|
||||
bool mapped_ = false;
|
||||
VkDeviceSize blockSize_ = kDefaultBlockSize;
|
||||
|
||||
// Emplacements stables : GpuRange::block est un indice dans ce tableau, un
|
||||
// bloc rendu laisse un trou (nullptr) reutilise par le suivant.
|
||||
std::vector<std::unique_ptr<Block>> blocks_;
|
||||
|
||||
VkDeviceSize usedBytes_ = 0;
|
||||
VkDeviceSize capacityBytes_ = 0;
|
||||
};
|
||||
|
||||
} // namespace vercora
|
||||
@@ -0,0 +1,118 @@
|
||||
#pragma once
|
||||
|
||||
#include "renderer/Vertex.hpp"
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
namespace vercora {
|
||||
|
||||
// PHASE 30. Les formats de sommet tels que le GPU les LIT.
|
||||
//
|
||||
// Jusqu'ici un seul format, `Vertex` (68 octets), servait a tout : il porte la
|
||||
// position, la couleur, la normale, l'UV ET la cible de geomorphing du terrain.
|
||||
// Il reste le format de TRAVAIL cote CPU - tous les generateurs (arbres,
|
||||
// rochers, .obj, terrain) et tous les tests le produisent et le lisent - mais
|
||||
// il n'est plus televerse tel quel. Le Renderer le CONVERTIT au televersement
|
||||
// dans l'un des deux formats ci-dessous, chacun reduit a ce que son shader lit
|
||||
// reellement. Comme Vertex.hpp, ce fichier ne connait pas Vulkan : la
|
||||
// description des attributs au pipeline vit dans renderer/VertexFormat.hpp.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Objets et vegetation (cube.vert, foliage.vert) : 44 octets, conversion EXACTE
|
||||
// ---------------------------------------------------------------------------
|
||||
// `Vertex` sans ses 24 octets de cible de geomorphing, qu'aucun de ces deux
|
||||
// shaders ne lit (le pipeline ne les decrivait deja pas : seul le STRIDE les
|
||||
// payait). Les flottants sont recopies tels quels : l'image est identique au
|
||||
// bit pres, et les maillages d'objets pesent 35 % de moins.
|
||||
struct ObjectVertex {
|
||||
glm::vec3 pos;
|
||||
glm::vec3 color;
|
||||
glm::vec3 normal;
|
||||
glm::vec2 uv;
|
||||
};
|
||||
static_assert(sizeof(ObjectVertex) == 44,
|
||||
"ObjectVertex doit rester sans remplissage : sa taille est le stride "
|
||||
"du binding 0 des pipelines objet et vegetation.");
|
||||
|
||||
inline ObjectVertex toObjectVertex(const Vertex& vertex) {
|
||||
return ObjectVertex{ vertex.pos, vertex.color, vertex.normal, vertex.uv };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Terrain (terrain.vert) : 16 octets au lieu de 68
|
||||
// ---------------------------------------------------------------------------
|
||||
// Une tuile de terrain est une GRILLE REGULIERE : la position horizontale d'un
|
||||
// sommet, celle de sa cible de geomorphing et son UV ne dependent que de son
|
||||
// indice dans la tuile et de trois entiers propres a la tuile (premier
|
||||
// echantillon, pas, sommets par rangee - pousses en push constant, voir
|
||||
// DrawItem::grid). Le vertex shader les recalcule avec EXACTEMENT les memes
|
||||
// operations flottantes que Heightmap::worldCoord : les positions sont donc
|
||||
// identiques au bit pres a celles que portait le format de 68 octets. La
|
||||
// couleur, elle, valait toujours (1, 1, 1).
|
||||
//
|
||||
// Ne restent que ce qui ne se deduit pas de l'indice :
|
||||
// - height : altitude du sommet, flottant EXACT (la verite physique) ;
|
||||
// - morphHeight : altitude de sa cible dans la grille du niveau superieur ;
|
||||
// - normal : composantes x et z de la normale, en snorm16 ; y se
|
||||
// reconstruit (une normale de champ de hauteur pointe
|
||||
// toujours vers le haut) ;
|
||||
// - morphNormal : idem pour la normale de la cible.
|
||||
// Seules les normales sont quantifiees : 1/32767 par composante, soit ~3e-5 -
|
||||
// un ecart d'eclairage de l'ordre du centieme de niveau sur 255.
|
||||
struct TerrainVertex {
|
||||
float height = 0.0f;
|
||||
float morphHeight = 0.0f;
|
||||
int16_t normal[2] = { 0, 0 };
|
||||
int16_t morphNormal[2] = { 0, 0 };
|
||||
};
|
||||
static_assert(sizeof(TerrainVertex) == 16,
|
||||
"TerrainVertex doit rester compact : sa taille est le stride du "
|
||||
"binding 0 du pipeline terrain.");
|
||||
|
||||
// Quantification snorm16, la convention de VK_FORMAT_R16_SNORM : l'entier c
|
||||
// represente max(c / 32767, -1).
|
||||
inline int16_t packSnorm16(float value) {
|
||||
const float clamped = std::clamp(value, -1.0f, 1.0f);
|
||||
return static_cast<int16_t>(std::lround(clamped * 32767.0f));
|
||||
}
|
||||
|
||||
inline float unpackSnorm16(int16_t value) {
|
||||
return std::max(static_cast<float>(value) / 32767.0f, -1.0f);
|
||||
}
|
||||
|
||||
// Normale reconstruite depuis ses composantes x et z quantifiees : la
|
||||
// formule exacte du vertex shader, pour que les tests mesurent ce que le GPU
|
||||
// verra.
|
||||
inline glm::vec3 unpackTerrainNormal(const int16_t packed[2]) {
|
||||
const float x = unpackSnorm16(packed[0]);
|
||||
const float z = unpackSnorm16(packed[1]);
|
||||
return { x, std::sqrt(std::max(0.0f, 1.0f - x * x - z * z)), z };
|
||||
}
|
||||
|
||||
// Conversion d'un sommet de terrain du format de travail. N'utilise que les
|
||||
// altitudes et les normales : le reste se recalcule dans le shader.
|
||||
inline TerrainVertex toTerrainVertex(const Vertex& vertex) {
|
||||
TerrainVertex packed;
|
||||
packed.height = vertex.pos.y;
|
||||
packed.morphHeight = vertex.morphPos.y;
|
||||
packed.normal[0] = packSnorm16(vertex.normal.x);
|
||||
packed.normal[1] = packSnorm16(vertex.normal.z);
|
||||
packed.morphNormal[0] = packSnorm16(vertex.morphNormal.x);
|
||||
packed.morphNormal[1] = packSnorm16(vertex.morphNormal.z);
|
||||
return packed;
|
||||
}
|
||||
|
||||
// La position horizontale d'un echantillon de grille, calculee comme le fait
|
||||
// terrain.vert : `origin + float(index) * spacing`, sans contraction en FMA
|
||||
// (qualificatif `precise` cote shader). C'est l'expression meme de
|
||||
// Heightmap::worldCoord avec origin = worldCoord(0) : le resultat est identique
|
||||
// au bit pres, ce que verifie tests/logic_tests.cpp.
|
||||
inline float terrainGridCoord(float origin, float spacing, uint32_t index) {
|
||||
return origin + static_cast<float>(index) * spacing;
|
||||
}
|
||||
|
||||
} // namespace vercora
|
||||
+12
-99
@@ -1,107 +1,20 @@
|
||||
#include "renderer/Mesh.hpp"
|
||||
|
||||
#include "core/Logger.hpp"
|
||||
#include "renderer/MeshData.hpp"
|
||||
#include "renderer/VulkanBuffer.hpp"
|
||||
#include "renderer/VulkanContext.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace vercora {
|
||||
|
||||
Mesh::Mesh(VulkanContext& context,
|
||||
BufferUploader& uploader,
|
||||
const MeshData& data,
|
||||
bool log) {
|
||||
// --- Validation AVANT toute allocation Vulkan ---------------------------
|
||||
// Un index hors limites ne produit pas d'erreur a la creation du buffer :
|
||||
// il se manifesterait au draw, sous forme de lecture hors du vertex buffer
|
||||
// (comportement indefini cote GPU). Mieux vaut refuser ici, avec un message
|
||||
// qui dit quoi.
|
||||
if (data.vertices.empty()) {
|
||||
throw std::runtime_error("Mesh vide : aucun sommet (" + data.name + ").");
|
||||
Mesh::Mesh(GpuBufferPool& pool, VertexLayout layout,
|
||||
const GpuRange& vertices, uint32_t vertexCount,
|
||||
const GpuRange& indices, VkIndexType indexType, uint32_t indexCount,
|
||||
bool ownsIndices)
|
||||
: pool_(pool), layout_(layout), vertices_(vertices), indices_(indices),
|
||||
indexType_(indexType), vertexCount_(vertexCount), indexCount_(indexCount),
|
||||
ownsIndices_(ownsIndices) {}
|
||||
|
||||
Mesh::~Mesh() {
|
||||
pool_.release(vertices_);
|
||||
if (ownsIndices_) {
|
||||
pool_.release(indices_);
|
||||
}
|
||||
if (data.indices.empty()) {
|
||||
throw std::runtime_error("Mesh vide : aucun index (" + data.name + ").");
|
||||
}
|
||||
if (data.indices.size() % 3 != 0) {
|
||||
throw std::runtime_error(
|
||||
"Mesh non triangule : " + std::to_string(data.indices.size()) +
|
||||
" index, ce qui n'est pas un multiple de 3 (" + data.name + ").");
|
||||
}
|
||||
|
||||
const auto vertexCount = static_cast<uint32_t>(data.vertices.size());
|
||||
for (uint32_t index : data.indices) {
|
||||
if (index >= vertexCount) {
|
||||
throw std::runtime_error(
|
||||
"Index hors limites dans le mesh : " + std::to_string(index) +
|
||||
" pour " + std::to_string(vertexCount) + " sommets (" + data.name + ").");
|
||||
}
|
||||
}
|
||||
|
||||
vertexCount_ = vertexCount;
|
||||
indexCount_ = static_cast<uint32_t>(data.indices.size());
|
||||
|
||||
// --- Upload GPU ---------------------------------------------------------
|
||||
vertexBuffer_ = createDeviceLocalBuffer(
|
||||
context, uploader,
|
||||
data.vertices.data(),
|
||||
sizeof(data.vertices[0]) * data.vertices.size(),
|
||||
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
|
||||
|
||||
indexBuffer_ = createDeviceLocalBuffer(
|
||||
context, uploader,
|
||||
data.indices.data(),
|
||||
sizeof(data.indices[0]) * data.indices.size(),
|
||||
VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
|
||||
|
||||
if (log) {
|
||||
logInfo("Mesh charge sur le GPU : " + data.name + " - " +
|
||||
std::to_string(vertexCount_) + " sommets, " +
|
||||
std::to_string(indexCount_ / 3) + " triangles.");
|
||||
}
|
||||
}
|
||||
|
||||
Mesh::~Mesh() = default; // les buffers se detruisent avec leurs unique_ptr
|
||||
|
||||
std::unique_ptr<VulkanBuffer> Mesh::createDeviceLocalBuffer(
|
||||
VulkanContext& context,
|
||||
BufferUploader& uploader,
|
||||
const void* data,
|
||||
VkDeviceSize size,
|
||||
VkBufferUsageFlags usage) {
|
||||
// 1. Staging host-visible : accessible au CPU, on y ecrit la geometrie.
|
||||
auto staging = std::make_unique<VulkanBuffer>(
|
||||
context, size,
|
||||
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
staging->writeToBuffer(data, size);
|
||||
|
||||
// 2. Buffer final device-local : rapide pour le GPU, non mappable.
|
||||
auto buffer = std::make_unique<VulkanBuffer>(
|
||||
context, size,
|
||||
VK_BUFFER_USAGE_TRANSFER_DST_BIT | usage,
|
||||
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
|
||||
// 3. PHASE 12 : la copie est CONFIEE, pas attendue. Le staging part avec
|
||||
// elle - il doit survivre jusqu'a l'execution de la frame qui portera la
|
||||
// commande de copie, ce qui n'est plus une duree connue ici. C'est tout
|
||||
// le changement : avant, cette ligne bloquait le thread jusqu'a ce que le
|
||||
// GPU ait vide sa queue.
|
||||
uploader.enqueueCopy(std::move(staging), buffer->handle());
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
void Mesh::bind(VkCommandBuffer commandBuffer) const {
|
||||
const VkBuffer buffers[] = { vertexBuffer_->handle() };
|
||||
const VkDeviceSize offsets[] = { 0 };
|
||||
vkCmdBindVertexBuffers(commandBuffer, 0, 1, buffers, offsets);
|
||||
|
||||
// uint32 : suffisant pour de gros meshes, indispensable pour du terrain
|
||||
// LiDAR plus tard (uint16 plafonnerait a 65536 sommets).
|
||||
vkCmdBindIndexBuffer(commandBuffer, indexBuffer_->handle(), 0, VK_INDEX_TYPE_UINT32);
|
||||
}
|
||||
|
||||
void Mesh::draw(VkCommandBuffer commandBuffer) const {
|
||||
|
||||
+46
-46
@@ -1,55 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include "renderer/GpuBufferPool.hpp"
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
|
||||
namespace vercora {
|
||||
|
||||
class VulkanContext;
|
||||
class VulkanBuffer;
|
||||
class BufferUploader;
|
||||
struct MeshData;
|
||||
// PHASE 30. Format des sommets d'un maillage, tel que son pipeline les lit
|
||||
// (voir renderer/GpuVertex.hpp). Un maillage de terrain ne peut etre dessine
|
||||
// qu'avec Material::Terrain, un maillage d'objet qu'avec les autres : le
|
||||
// Renderer ecarte tout DrawItem qui melangerait les deux, plutot que de laisser
|
||||
// le GPU lire 16 octets la ou il en attend 44.
|
||||
enum class VertexLayout : uint8_t {
|
||||
Object, // ObjectVertex, 44 octets
|
||||
Terrain, // TerrainVertex, 16 octets
|
||||
};
|
||||
|
||||
// Un mesh pret a etre dessine : vertex buffer + index buffer device-local et
|
||||
// leurs compteurs. Interchangeable par construction : le Renderer ne sait pas
|
||||
// d'ou vient la geometrie (fichier .obj, cube code en dur, terrain genere plus
|
||||
// tard), il recoit un Mesh et l'affiche.
|
||||
// Un maillage pret a etre dessine : une plage de sommets et une plage d'indices
|
||||
// dans les blocs partages du GpuBufferPool, et leurs compteurs.
|
||||
//
|
||||
// L'upload passe par VulkanBuffer (staging host-visible -> device-local), le
|
||||
// meme chemin que la Phase 1, factorise ici en une seule fonction.
|
||||
// PHASE 30 : un Mesh ne possede PLUS de buffer Vulkan. Il possede des PLAGES,
|
||||
// rendues au pool a sa destruction - laquelle est toujours differee par le
|
||||
// Renderer de kMaxFramesInFlight + 1 images, exactement comme l'etaient les
|
||||
// buffers jusqu'ici (voir Renderer::removeMesh). La topologie peut aussi etre
|
||||
// PARTAGEE (les tuiles de terrain en ont une seule pour toutes) : le Mesh ne la
|
||||
// rend alors pas, c'est le Renderer qui la possede.
|
||||
//
|
||||
// PHASE 12 : cet upload n'ATTEND PLUS le GPU. La copie est confiee a un
|
||||
// BufferUploader (le Renderer), qui l'enregistre en tete du command buffer de la
|
||||
// frame suivante ; le constructeur revient des que la geometrie a ete recopiee
|
||||
// dans un buffer staging, sans aucune synchronisation. Consequence a garder en
|
||||
// tete : les buffers du Mesh ne contiennent la geometrie qu'a partir de
|
||||
// l'execution de cette frame - c'est-a-dire avant tout draw qui pourrait les
|
||||
// lire, puisque la copie est enregistree AVANT le render pass et separee de lui
|
||||
// par une barriere.
|
||||
// Le televersement (conversion des sommets, ecriture directe ou staging) est
|
||||
// fait par le Renderer avant de construire le Mesh : cette classe ne fait que
|
||||
// decrire et dessiner.
|
||||
class Mesh {
|
||||
public:
|
||||
// `uploader` recoit les copies staging -> device-local. Il doit vivre plus
|
||||
// longtemps que la frame en cours (en pratique c'est le Renderer lui-meme).
|
||||
// Lance std::runtime_error si la geometrie est vide ou incoherente.
|
||||
// `log` a false pour les geometries creees en masse (les tuiles du quadtree
|
||||
// de la Phase 10) : une ligne de journal par tuile noierait toute autre
|
||||
// information et couterait plus cher que l'upload lui-meme.
|
||||
Mesh(VulkanContext& context,
|
||||
BufferUploader& uploader,
|
||||
const MeshData& data,
|
||||
bool log = true);
|
||||
Mesh(GpuBufferPool& pool, VertexLayout layout,
|
||||
const GpuRange& vertices, uint32_t vertexCount,
|
||||
const GpuRange& indices, VkIndexType indexType, uint32_t indexCount,
|
||||
bool ownsIndices);
|
||||
~Mesh();
|
||||
|
||||
Mesh(const Mesh&) = delete;
|
||||
Mesh& operator=(const Mesh&) = delete;
|
||||
|
||||
// Lie les buffers du mesh au command buffer courant.
|
||||
void bind(VkCommandBuffer commandBuffer) const;
|
||||
|
||||
// Emet le draw indexe. A appeler apres bind() et apres avoir lie les
|
||||
// descriptor sets / le pipeline.
|
||||
// Emet le draw indexe. A appeler apres avoir lie les plages du maillage
|
||||
// (Renderer::recordCommandBuffer, qui evite les liaisons redondantes), les
|
||||
// descriptor sets et le pipeline.
|
||||
void draw(VkCommandBuffer commandBuffer) const;
|
||||
|
||||
// PHASE 11 : meme dessin, repete `instanceCount` fois. Les instances lisent
|
||||
@@ -60,22 +55,27 @@ public:
|
||||
|
||||
uint32_t vertexCount() const { return vertexCount_; }
|
||||
uint32_t indexCount() const { return indexCount_; }
|
||||
VertexLayout layout() const { return layout_; }
|
||||
|
||||
const GpuRange& vertexRange() const { return vertices_; }
|
||||
const GpuRange& indexRange() const { return indices_; }
|
||||
VkIndexType indexType() const { return indexType_; }
|
||||
|
||||
// Octets de geometrie PROPRES a ce maillage (la topologie partagee n'est
|
||||
// pas comptee : elle n'existe qu'une fois).
|
||||
VkDeviceSize ownedBytes() const {
|
||||
return vertices_.size + (ownsIndices_ ? indices_.size : 0);
|
||||
}
|
||||
|
||||
private:
|
||||
// Cree un buffer device-local et CONFIE a l'uploader la copie depuis un
|
||||
// staging temporaire. Commun au vertex buffer et a l'index buffer.
|
||||
static std::unique_ptr<VulkanBuffer> createDeviceLocalBuffer(
|
||||
VulkanContext& context,
|
||||
BufferUploader& uploader,
|
||||
const void* data,
|
||||
VkDeviceSize size,
|
||||
VkBufferUsageFlags usage);
|
||||
|
||||
std::unique_ptr<VulkanBuffer> vertexBuffer_;
|
||||
std::unique_ptr<VulkanBuffer> indexBuffer_;
|
||||
|
||||
GpuBufferPool& pool_;
|
||||
VertexLayout layout_ = VertexLayout::Object;
|
||||
GpuRange vertices_;
|
||||
GpuRange indices_;
|
||||
VkIndexType indexType_ = VK_INDEX_TYPE_UINT32;
|
||||
uint32_t vertexCount_ = 0;
|
||||
uint32_t indexCount_ = 0;
|
||||
bool ownsIndices_ = true;
|
||||
};
|
||||
|
||||
} // namespace vercora
|
||||
@@ -41,15 +41,15 @@ Pipeline::Pipeline(VkDevice device, VkRenderPass renderPass, VkDescriptorSetLayo
|
||||
|
||||
const std::array<VkPipelineShaderStageCreateInfo, 2> stages = { vertStage, fragStage };
|
||||
|
||||
// Vertex input : un binding entrelace, et autant d'attributs que le vertex
|
||||
// shader en consomme reellement - quatre (pos, color, normal, uv) pour les
|
||||
// objets, six pour le terrain, dont la cible de geomorphing. Le STRIDE, lui,
|
||||
// reste toujours sizeof(Vertex) : le format de sommet cote C++ est unique.
|
||||
const auto bindingDescription = vertexBindingDescription();
|
||||
const auto attributeDescriptions = vertexAttributeDescriptions();
|
||||
const uint32_t attributeCount = shaders.usesMorphAttributes
|
||||
? static_cast<uint32_t>(attributeDescriptions.size())
|
||||
: 4u;
|
||||
// Vertex input : un binding entrelace, au format de la famille de shaders
|
||||
// (PHASE 30, voir renderer/GpuVertex.hpp) - ObjectVertex pour les objets
|
||||
// et la vegetation, TerrainVertex pour le terrain.
|
||||
const VkVertexInputBindingDescription bindingDescription =
|
||||
shaders.terrainVertexLayout ? terrainBindingDescription()
|
||||
: objectBindingDescription();
|
||||
const std::array<VkVertexInputAttributeDescription, 4> attributeDescriptions =
|
||||
shaders.terrainVertexLayout ? terrainAttributeDescriptions()
|
||||
: objectAttributeDescriptions();
|
||||
|
||||
// PHASE 11 : un materiau instancie decrit DEUX bindings (sommets et
|
||||
// instances) et concatene leurs attributs. Les tableaux sont construits ici
|
||||
@@ -59,7 +59,7 @@ Pipeline::Pipeline(VkDevice device, VkRenderPass renderPass, VkDescriptorSetLayo
|
||||
|
||||
std::vector<VkVertexInputBindingDescription> bindings{ bindingDescription };
|
||||
std::vector<VkVertexInputAttributeDescription> attributes(
|
||||
attributeDescriptions.begin(), attributeDescriptions.begin() + attributeCount);
|
||||
attributeDescriptions.begin(), attributeDescriptions.end());
|
||||
|
||||
// PHASE 27 : une passe plein ecran ne lit AUCUN buffer de sommets.
|
||||
if (shaders.fullscreenOverlay) {
|
||||
@@ -99,6 +99,14 @@ Pipeline::Pipeline(VkDevice device, VkRenderPass renderPass, VkDescriptorSetLayo
|
||||
rasterizer.lineWidth = 1.0f;
|
||||
rasterizer.cullMode = VK_CULL_MODE_NONE; // pas de culling : triangle toujours visible
|
||||
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
|
||||
if (shaders.cullBackFaces) {
|
||||
// PHASE 30 : voir ShaderSet::cullBackFaces. Le terrain est enroule
|
||||
// (v00, v01, v11) avec Z vers le sud ; une fois l'axe Y de la
|
||||
// projection retourne (Renderer::projectionMatrix), une face vue
|
||||
// d'en haut est tramee dans le sens ANTIHORAIRE du framebuffer.
|
||||
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
|
||||
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
|
||||
}
|
||||
rasterizer.depthBiasEnable = VK_FALSE;
|
||||
|
||||
VkPipelineMultisampleStateCreateInfo multisampling{};
|
||||
|
||||
@@ -14,22 +14,20 @@ struct ShaderSet {
|
||||
std::string vertexSpv;
|
||||
std::string fragmentSpv;
|
||||
|
||||
// true si le vertex shader consomme les attributs de geomorphing
|
||||
// (locations 4 et 5, voir Vertex.hpp). Seul terrain.vert le fait.
|
||||
// true si le vertex shader lit le format de sommet du TERRAIN
|
||||
// (TerrainVertex, 16 octets) ; false pour le format des objets et de la
|
||||
// vegetation (ObjectVertex, 44 octets). Voir renderer/GpuVertex.hpp.
|
||||
//
|
||||
// Ce drapeau n'est pas une optimisation mais une CORRECTION : declarer dans
|
||||
// le vertex input un attribut qu'aucun shader ne lit fait emettre aux
|
||||
// couches de validation "Vertex attribute at location 4 not consumed by
|
||||
// vertex shader", et le contrat du projet est zero message de validation. Le
|
||||
// format de sommet reste unique cote C++ ; c'est seulement sa DESCRIPTION au
|
||||
// pipeline qui est tronquee pour les materiaux qui n'en lisent qu'une partie
|
||||
// (ce que Vulkan autorise : un binding peut avoir un stride plus grand que
|
||||
// la somme des attributs decrits).
|
||||
bool usesMorphAttributes = false;
|
||||
// PHASE 30 : jusqu'ici ce drapeau (usesMorphAttributes) ne faisait que
|
||||
// TRONQUER la description d'un format unique de 68 octets, pour ne pas
|
||||
// declarer aux shaders d'objets les attributs de morphing qu'ils ne lisent
|
||||
// pas (zero message de validation). Les deux familles ont desormais chacune
|
||||
// leur format, et les octets inutiles ont quitte les buffers eux-memes.
|
||||
bool terrainVertexLayout = false;
|
||||
|
||||
// PHASE 11. true si le pipeline doit decrire le second binding de sommets,
|
||||
// cadence par instance (voir VertexFormat.hpp). Meme raisonnement que
|
||||
// usesMorphAttributes : c'est une CORRECTION, pas une optimisation. Decrire
|
||||
// cadence par instance (voir VertexFormat.hpp). C'est une CORRECTION, pas
|
||||
// une optimisation (zero message de validation). Decrire
|
||||
// un binding d'instances a un pipeline non instancie obligerait a lier un
|
||||
// buffer d'instances avant de dessiner un cube, et ne pas le decrire a un
|
||||
// pipeline instancie ferait echouer la validation sur les locations 6 a 8.
|
||||
@@ -39,6 +37,23 @@ struct ShaderSet {
|
||||
// fabrique un triangle couvrant a partir de gl_VertexIndex), pas de test
|
||||
// ni d'ecriture de profondeur, melange par alpha.
|
||||
bool fullscreenOverlay = false;
|
||||
|
||||
// PHASE 30 : elimine les faces ARRIERE avant le tramage. Reserve au
|
||||
// terrain, et c'est une propriete de la geometrie, pas un reglage : un
|
||||
// champ de hauteurs a toutes ses normales geometriques vers le haut, et un
|
||||
// rayon parti d'un oeil situe AU-DESSUS du relief rencontre toujours une
|
||||
// face avant en premier - une face arriere n'est donc jamais le pixel
|
||||
// visible, elle ne fait que couter du tramage et des tests de profondeur.
|
||||
// (Image identique au bit pres, verifiee - NOTES-PHASE30.md.) Les objets
|
||||
// et la vegetation ne s'y pretent pas : l'herbe est un quad vu des deux
|
||||
// cotes, et rien ne garantit l'enroulement des maillages .obj.
|
||||
//
|
||||
// MESURE (lavapipe, NOTES-PHASE30.md) : -10 % de temps de rendu sur le
|
||||
// panorama. L'image n'est PAS identique au bit pres : 315 pixels isoles
|
||||
// (0,03 %) changent, tous sur des parois quasi verticales vues en rasant,
|
||||
// la ou une face arriere l'emportait d'un cheveu sur la face avant par
|
||||
// erreur d'arrondi de profondeur. C'est desormais toujours la face avant.
|
||||
bool cullBackFaces = false;
|
||||
};
|
||||
|
||||
// Shaders de la Phase 2 : couleur par sommet + Blinn-Phong. Utilises par le
|
||||
@@ -46,7 +61,8 @@ struct ShaderSet {
|
||||
inline const ShaderSet kObjectShaders{ "cube.vert.spv", "cube.frag.spv" };
|
||||
|
||||
// Shaders de la Phase 4 : coloration par altitude et par pente + Blinn-Phong.
|
||||
inline const ShaderSet kTerrainShaders{ "terrain.vert.spv", "terrain.frag.spv", true };
|
||||
inline const ShaderSet kTerrainShaders{ "terrain.vert.spv", "terrain.frag.spv", true,
|
||||
false, false, true };
|
||||
|
||||
// Shaders de la Phase 11 : vegetation instanciee (arbres de decor et herbe).
|
||||
// Ne lit PAS les attributs de geomorphing, mais lit le binding d'instances.
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
namespace vercora {
|
||||
|
||||
// PHASE 30. Gestion des plages libres d'UN bloc de memoire : premier
|
||||
// ajustement, alignement, fusion des voisins a la liberation.
|
||||
//
|
||||
// C'est toute la logique de sous-allocation de GpuBufferPool, isolee ici sans
|
||||
// la moindre dependance Vulkan pour etre testee headless (tests/logic_tests.cpp)
|
||||
// : un decalage faux dans un allocateur ne se voit pas a l'ecran avant d'avoir
|
||||
// ecrase la geometrie d'un autre maillage.
|
||||
//
|
||||
// Les tailles en jeu ne justifient pas mieux qu'une liste triee : quelques
|
||||
// dizaines de plages par bloc au pire (les tuiles de terrain ont toutes la meme
|
||||
// taille, donc un trou laisse par une tuile evincee est exactement celui que la
|
||||
// suivante remplit).
|
||||
class RangeAllocator {
|
||||
public:
|
||||
static constexpr uint64_t kInvalid = std::numeric_limits<uint64_t>::max();
|
||||
|
||||
explicit RangeAllocator(uint64_t capacity) : capacity_(capacity) {
|
||||
if (capacity > 0) {
|
||||
free_.push_back({ 0, capacity });
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t capacity() const { return capacity_; }
|
||||
uint64_t used() const { return used_; }
|
||||
bool empty() const { return used_ == 0; }
|
||||
|
||||
// Plus grande plage libre : sert a decider s'il faut un nouveau bloc.
|
||||
uint64_t largestFree() const {
|
||||
uint64_t best = 0;
|
||||
for (const Span& span : free_) {
|
||||
best = (span.size > best) ? span.size : best;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Reserve `size` octets alignes sur `alignment` (puissance de deux).
|
||||
// Renvoie le decalage, ou kInvalid si aucune plage ne convient.
|
||||
uint64_t allocate(uint64_t size, uint64_t alignment) {
|
||||
if (size == 0 || alignment == 0 || (alignment & (alignment - 1)) != 0) {
|
||||
return kInvalid;
|
||||
}
|
||||
for (std::size_t k = 0; k < free_.size(); ++k) {
|
||||
const Span span = free_[k];
|
||||
const uint64_t aligned = (span.offset + alignment - 1) & ~(alignment - 1);
|
||||
const uint64_t padding = aligned - span.offset;
|
||||
if (padding > span.size || span.size - padding < size) {
|
||||
continue;
|
||||
}
|
||||
// La plage est decoupee en (rembourrage avant) + (reserve) + (reste).
|
||||
// Le rembourrage reste LIBRE : il n'est perdu que tant qu'aucune
|
||||
// demande plus petite ne le reclame.
|
||||
const uint64_t tailOffset = aligned + size;
|
||||
const uint64_t tailSize = span.offset + span.size - tailOffset;
|
||||
free_.erase(free_.begin() + static_cast<std::ptrdiff_t>(k));
|
||||
std::size_t insertAt = k;
|
||||
if (padding > 0) {
|
||||
free_.insert(free_.begin() + static_cast<std::ptrdiff_t>(insertAt),
|
||||
Span{ span.offset, padding });
|
||||
++insertAt;
|
||||
}
|
||||
if (tailSize > 0) {
|
||||
free_.insert(free_.begin() + static_cast<std::ptrdiff_t>(insertAt),
|
||||
Span{ tailOffset, tailSize });
|
||||
}
|
||||
used_ += size;
|
||||
return aligned;
|
||||
}
|
||||
return kInvalid;
|
||||
}
|
||||
|
||||
// Rend une plage obtenue par allocate. Fusionne avec les plages libres
|
||||
// contigues, pour qu'une serie d'evictions reconstitue de grands trous.
|
||||
void release(uint64_t offset, uint64_t size) {
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
std::size_t k = 0;
|
||||
while (k < free_.size() && free_[k].offset < offset) {
|
||||
++k;
|
||||
}
|
||||
free_.insert(free_.begin() + static_cast<std::ptrdiff_t>(k), Span{ offset, size });
|
||||
used_ -= size;
|
||||
// Fusion avec le suivant, puis avec le precedent.
|
||||
if (k + 1 < free_.size() && free_[k].offset + free_[k].size == free_[k + 1].offset) {
|
||||
free_[k].size += free_[k + 1].size;
|
||||
free_.erase(free_.begin() + static_cast<std::ptrdiff_t>(k + 1));
|
||||
}
|
||||
if (k > 0 && free_[k - 1].offset + free_[k - 1].size == free_[k].offset) {
|
||||
free_[k - 1].size += free_[k].size;
|
||||
free_.erase(free_.begin() + static_cast<std::ptrdiff_t>(k));
|
||||
}
|
||||
}
|
||||
|
||||
// Nombre de plages libres disjointes : 1 pour un bloc vide, et c'est
|
||||
// l'invariant que les tests verifient apres une liberation complete.
|
||||
std::size_t freeSpanCount() const { return free_.size(); }
|
||||
|
||||
private:
|
||||
struct Span {
|
||||
uint64_t offset;
|
||||
uint64_t size;
|
||||
};
|
||||
|
||||
uint64_t capacity_ = 0;
|
||||
uint64_t used_ = 0;
|
||||
std::vector<Span> free_; // trie par decalage croissant, jamais deux contigues
|
||||
};
|
||||
|
||||
} // namespace vercora
|
||||
+327
-18
@@ -18,6 +18,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
@@ -25,6 +26,26 @@ namespace vercora {
|
||||
|
||||
namespace {
|
||||
|
||||
// PHASE 30 : barriere d'EXECUTION placee AVANT les copies staging -> pool.
|
||||
//
|
||||
// Avant le pool, chaque copie ecrivait un buffer neuf, que rien n'avait jamais
|
||||
// lu. Desormais une plage du pool est RECYCLEE : la copie ecrit des octets que
|
||||
// des images precedentes ont lus comme sommets ou indices. Le delai de retrait
|
||||
// (Renderer::removeMesh) garantit que ces images sont terminees, mais il le
|
||||
// garantit cote CPU, par les fences ; la validation de SYNCHRONISATION signale
|
||||
// a juste titre que rien ne l'exprime cote GPU (SYNC-HAZARD-WRITE-AFTER-READ,
|
||||
// 414 messages en 30 s de survol avec --force-staging). Un danger ecriture
|
||||
// apres lecture ne demande qu'une dependance d'EXECUTION : pas de masque
|
||||
// d'acces, l'etage d'assemblage des sommets avant, le transfert apres. Le
|
||||
// chemin d'ecriture directe (memoire unifiee) n'a pas de copie, donc pas de
|
||||
// barriere.
|
||||
void recordCopyAfterReadBarrier(VkCommandBuffer commandBuffer) {
|
||||
vkCmdPipelineBarrier(commandBuffer,
|
||||
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
0, 0, nullptr, 0, nullptr, 0, nullptr);
|
||||
}
|
||||
|
||||
// Paire de shaders associee a chaque materiau. L'ordre suit celui de l'enum
|
||||
// Material : c'est ce tableau qui fait le lien entre le vocabulaire du gameplay
|
||||
// ("cet objet est du terrain") et celui du rendu ("ces .spv").
|
||||
@@ -44,6 +65,23 @@ Renderer::Renderer(VulkanContext& context, Window& window,
|
||||
: context_(context), window_(window), options_(options) {
|
||||
swapChain_ = std::make_unique<SwapChain>(context_, window_);
|
||||
|
||||
// PHASE 30 : le pool de geometrie. En memoire unifiee (GPU integre,
|
||||
// lavapipe), ses blocs sont mappes et la geometrie y est ecrite DIRECTEMENT
|
||||
// : ni staging, ni copie, ni barriere. Sur un GPU discret, la memoire
|
||||
// device-local n'est pas (ou peu) mappable : chemin staging de la Phase 12.
|
||||
const bool directWrites = context_.preferDirectGeometryWrites() && !options_.forceStaging;
|
||||
geometryPool_ = std::make_unique<GpuBufferPool>(
|
||||
context_,
|
||||
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
|
||||
VK_BUFFER_USAGE_TRANSFER_DST_BIT,
|
||||
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, directWrites);
|
||||
logInfo(std::string("Geometrie : pool de blocs de ") +
|
||||
std::to_string(GpuBufferPool::kDefaultBlockSize / (1024 * 1024)) + " Mo, " +
|
||||
(directWrites ? "ecriture DIRECTE (memoire unifiee, sans staging)."
|
||||
: (options_.forceStaging
|
||||
? "televersement par staging (FORCE, --force-staging)."
|
||||
: "televersement par staging (memoire device-local non mappable).")));
|
||||
|
||||
createCommandPool(); // requis avant les buffers (transferts staging)
|
||||
|
||||
createDescriptorSetLayout();
|
||||
@@ -88,6 +126,15 @@ Renderer::Renderer(VulkanContext& context, Window& window,
|
||||
Renderer::~Renderer() {
|
||||
VkDevice device = context_.device();
|
||||
|
||||
// PHASE 30 : rien ne doit plus lire la geometrie quand ses plages sont
|
||||
// rendues au pool (les Mesh le font en se detruisant, apres ce corps).
|
||||
vkDeviceWaitIdle(device);
|
||||
pendingTerrainWrites_.clear();
|
||||
for (SharedIndices& shared : sharedIndices_) {
|
||||
geometryPool_->release(shared.range);
|
||||
}
|
||||
sharedIndices_.clear();
|
||||
|
||||
for (VkSemaphore s : imageAvailableSemaphores_) {
|
||||
vkDestroySemaphore(device, s, nullptr);
|
||||
}
|
||||
@@ -116,32 +163,236 @@ void Renderer::waitIdle() const {
|
||||
vkDeviceWaitIdle(context_.device());
|
||||
}
|
||||
|
||||
MeshHandle Renderer::addMesh(const MeshData& meshData, bool log) {
|
||||
// Le Mesh valide les donnees et leve une exception si elles sont
|
||||
// incoherentes, avant toute allocation durable. Construit AVANT de toucher
|
||||
// aux tableaux : si la construction echoue, aucun emplacement n'a ete
|
||||
// consomme.
|
||||
auto mesh = std::make_unique<Mesh>(context_, *this, meshData, log);
|
||||
MeshHandle Renderer::registerMesh(std::unique_ptr<Mesh> mesh) {
|
||||
++liveMeshCount_;
|
||||
|
||||
if (!freeMeshSlots_.empty()) {
|
||||
const MeshHandle handle = freeMeshSlots_.back();
|
||||
freeMeshSlots_.pop_back();
|
||||
meshes_[handle] = std::move(mesh);
|
||||
return handle;
|
||||
}
|
||||
|
||||
meshes_.push_back(std::move(mesh));
|
||||
return static_cast<MeshHandle>(meshes_.size() - 1);
|
||||
}
|
||||
|
||||
Renderer::RangeWrite Renderer::beginRangeWrite(const GpuRange& range) {
|
||||
RangeWrite write;
|
||||
write.range = range;
|
||||
if (range.mapped != nullptr) {
|
||||
// Memoire unifiee : on ecrit la ou le GPU lira. Sans danger pour la
|
||||
// synchronisation - une plage n'est rendue au pool qu'une fois que plus
|
||||
// aucune image en vol ne la lit (Renderer::removeMesh), et l'ecriture
|
||||
// hote est visible du GPU a la soumission suivante (memoire coherente).
|
||||
write.destination = range.mapped;
|
||||
return write;
|
||||
}
|
||||
write.staging = std::make_unique<VulkanBuffer>(
|
||||
context_, range.size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
write.staging->map();
|
||||
write.destination = write.staging->mapped();
|
||||
return write;
|
||||
}
|
||||
|
||||
void Renderer::finishRangeWrite(RangeWrite& write) {
|
||||
if (write.staging) {
|
||||
write.staging->unmap();
|
||||
enqueueCopy(std::move(write.staging), write.range.buffer, write.range.offset);
|
||||
}
|
||||
write.destination = nullptr;
|
||||
}
|
||||
|
||||
MeshHandle Renderer::addMesh(const MeshData& meshData, bool log) {
|
||||
// --- Validation AVANT toute allocation ----------------------------------
|
||||
// Un index hors limites ne produit pas d'erreur a la creation du buffer :
|
||||
// il se manifesterait au draw, sous forme de lecture hors du vertex buffer
|
||||
// (comportement indefini cote GPU). Mieux vaut refuser ici, avec un message
|
||||
// qui dit quoi. Si la geometrie est refusee, aucun emplacement n'a ete
|
||||
// consomme.
|
||||
if (meshData.vertices.empty()) {
|
||||
throw std::runtime_error("Mesh vide : aucun sommet (" + meshData.name + ").");
|
||||
}
|
||||
if (meshData.indices.empty()) {
|
||||
throw std::runtime_error("Mesh vide : aucun index (" + meshData.name + ").");
|
||||
}
|
||||
if (meshData.indices.size() % 3 != 0) {
|
||||
throw std::runtime_error(
|
||||
"Mesh non triangule : " + std::to_string(meshData.indices.size()) +
|
||||
" index, ce qui n'est pas un multiple de 3 (" + meshData.name + ").");
|
||||
}
|
||||
const auto vertexCount = static_cast<uint32_t>(meshData.vertices.size());
|
||||
for (uint32_t index : meshData.indices) {
|
||||
if (index >= vertexCount) {
|
||||
throw std::runtime_error(
|
||||
"Index hors limites dans le mesh : " + std::to_string(index) +
|
||||
" pour " + std::to_string(vertexCount) + " sommets (" + meshData.name + ").");
|
||||
}
|
||||
}
|
||||
const auto indexCount = static_cast<uint32_t>(meshData.indices.size());
|
||||
|
||||
// PHASE 30 : sommets au format ObjectVertex (44 octets, conversion exacte)
|
||||
// et indices en uint16 des que le maillage a au plus 65 536 sommets - le
|
||||
// cas de TOUS les maillages d'objets du jeu. Les valeurs sont les memes,
|
||||
// seule leur largeur change.
|
||||
const bool shortIndices = vertexCount <= 65536u;
|
||||
const VkDeviceSize vertexBytes = static_cast<VkDeviceSize>(vertexCount) * sizeof(ObjectVertex);
|
||||
const VkDeviceSize indexBytes = static_cast<VkDeviceSize>(indexCount) *
|
||||
(shortIndices ? sizeof(uint16_t) : sizeof(uint32_t));
|
||||
|
||||
const GpuRange vertexRange = geometryPool_->allocate(vertexBytes);
|
||||
GpuRange indexRange;
|
||||
try {
|
||||
indexRange = geometryPool_->allocate(indexBytes);
|
||||
} catch (...) {
|
||||
geometryPool_->release(vertexRange);
|
||||
throw;
|
||||
}
|
||||
|
||||
RangeWrite vertexWrite = beginRangeWrite(vertexRange);
|
||||
auto* vertices = static_cast<ObjectVertex*>(vertexWrite.destination);
|
||||
for (uint32_t v = 0; v < vertexCount; ++v) {
|
||||
vertices[v] = toObjectVertex(meshData.vertices[v]);
|
||||
}
|
||||
finishRangeWrite(vertexWrite);
|
||||
|
||||
RangeWrite indexWrite = beginRangeWrite(indexRange);
|
||||
if (shortIndices) {
|
||||
auto* indices = static_cast<uint16_t*>(indexWrite.destination);
|
||||
for (uint32_t k = 0; k < indexCount; ++k) {
|
||||
indices[k] = static_cast<uint16_t>(meshData.indices[k]);
|
||||
}
|
||||
} else {
|
||||
std::memcpy(indexWrite.destination, meshData.indices.data(),
|
||||
static_cast<std::size_t>(indexBytes));
|
||||
}
|
||||
finishRangeWrite(indexWrite);
|
||||
|
||||
if (log) {
|
||||
logInfo("Mesh charge sur le GPU : " + meshData.name + " - " +
|
||||
std::to_string(vertexCount) + " sommets, " +
|
||||
std::to_string(indexCount / 3) + " triangles, " +
|
||||
std::to_string((vertexBytes + indexBytes + 1023) / 1024) + " Ko.");
|
||||
}
|
||||
return registerMesh(std::make_unique<Mesh>(
|
||||
*geometryPool_, VertexLayout::Object, vertexRange, vertexCount, indexRange,
|
||||
shortIndices ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32, indexCount, true));
|
||||
}
|
||||
|
||||
MeshHandle Renderer::addTerrainMesh(const std::vector<TerrainVertex>& vertices,
|
||||
const std::vector<uint32_t>& indices,
|
||||
const std::string& name, bool log) {
|
||||
if (vertices.empty() || indices.empty() || indices.size() % 3 != 0) {
|
||||
throw std::runtime_error("Terrain : geometrie vide ou non triangulee (" + name + ").");
|
||||
}
|
||||
const auto vertexCount = static_cast<uint32_t>(vertices.size());
|
||||
for (uint32_t index : indices) {
|
||||
if (index >= vertexCount) {
|
||||
throw std::runtime_error("Terrain : index " + std::to_string(index) +
|
||||
" hors des " + std::to_string(vertexCount) +
|
||||
" sommets (" + name + ").");
|
||||
}
|
||||
}
|
||||
const VkDeviceSize vertexBytes = static_cast<VkDeviceSize>(vertexCount) * sizeof(TerrainVertex);
|
||||
const VkDeviceSize indexBytes = static_cast<VkDeviceSize>(indices.size()) * sizeof(uint32_t);
|
||||
const GpuRange vertexRange = geometryPool_->allocate(vertexBytes);
|
||||
GpuRange indexRange;
|
||||
try {
|
||||
indexRange = geometryPool_->allocate(indexBytes);
|
||||
} catch (...) {
|
||||
geometryPool_->release(vertexRange);
|
||||
throw;
|
||||
}
|
||||
RangeWrite vertexWrite = beginRangeWrite(vertexRange);
|
||||
std::memcpy(vertexWrite.destination, vertices.data(), static_cast<std::size_t>(vertexBytes));
|
||||
finishRangeWrite(vertexWrite);
|
||||
RangeWrite indexWrite = beginRangeWrite(indexRange);
|
||||
std::memcpy(indexWrite.destination, indices.data(), static_cast<std::size_t>(indexBytes));
|
||||
finishRangeWrite(indexWrite);
|
||||
|
||||
if (log) {
|
||||
logInfo("Terrain charge sur le GPU : " + name + " - " + std::to_string(vertexCount) +
|
||||
" sommets, " + std::to_string(indices.size() / 3) + " triangles, " +
|
||||
std::to_string((vertexBytes + indexBytes) / (1024 * 1024)) + " Mo.");
|
||||
}
|
||||
return registerMesh(std::make_unique<Mesh>(
|
||||
*geometryPool_, VertexLayout::Terrain, vertexRange, vertexCount, indexRange,
|
||||
VK_INDEX_TYPE_UINT32, static_cast<uint32_t>(indices.size()), true));
|
||||
}
|
||||
|
||||
uint32_t Renderer::addSharedIndices(const std::vector<uint32_t>& indices) {
|
||||
if (indices.empty() || indices.size() % 3 != 0) {
|
||||
throw std::runtime_error("Topologie partagee vide ou non triangulee.");
|
||||
}
|
||||
const uint32_t highest = *std::max_element(indices.begin(), indices.end());
|
||||
const bool shortIndices = highest <= 0xFFFFu;
|
||||
SharedIndices shared;
|
||||
shared.count = static_cast<uint32_t>(indices.size());
|
||||
shared.type = shortIndices ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32;
|
||||
shared.range = geometryPool_->allocate(static_cast<VkDeviceSize>(indices.size()) *
|
||||
(shortIndices ? sizeof(uint16_t) : sizeof(uint32_t)));
|
||||
RangeWrite write = beginRangeWrite(shared.range);
|
||||
if (shortIndices) {
|
||||
auto* out = static_cast<uint16_t*>(write.destination);
|
||||
for (std::size_t k = 0; k < indices.size(); ++k) {
|
||||
out[k] = static_cast<uint16_t>(indices[k]);
|
||||
}
|
||||
} else {
|
||||
std::memcpy(write.destination, indices.data(), indices.size() * sizeof(uint32_t));
|
||||
}
|
||||
finishRangeWrite(write);
|
||||
sharedIndices_.push_back(shared);
|
||||
return static_cast<uint32_t>(sharedIndices_.size() - 1);
|
||||
}
|
||||
|
||||
Renderer::TerrainMeshWrite Renderer::beginTerrainMesh(uint32_t vertexCount,
|
||||
uint32_t sharedIndices) {
|
||||
if (sharedIndices >= sharedIndices_.size() || vertexCount == 0) {
|
||||
throw std::runtime_error("Tuile de terrain : topologie partagee inconnue.");
|
||||
}
|
||||
const SharedIndices& shared = sharedIndices_[sharedIndices];
|
||||
const GpuRange range = geometryPool_->allocate(
|
||||
static_cast<VkDeviceSize>(vertexCount) * sizeof(TerrainVertex));
|
||||
RangeWrite write = beginRangeWrite(range);
|
||||
|
||||
TerrainMeshWrite result;
|
||||
result.vertices = static_cast<TerrainVertex*>(write.destination);
|
||||
result.mesh = registerMesh(std::make_unique<Mesh>(
|
||||
*geometryPool_, VertexLayout::Terrain, range, vertexCount, shared.range,
|
||||
shared.type, shared.count, false));
|
||||
if (write.staging) {
|
||||
pendingTerrainWrites_.emplace(result.mesh, std::move(write));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void Renderer::endTerrainMesh(MeshHandle mesh) {
|
||||
const auto it = pendingTerrainWrites_.find(mesh);
|
||||
if (it == pendingTerrainWrites_.end()) {
|
||||
return; // ecriture directe : rien a livrer, le GPU lit deja ces octets
|
||||
}
|
||||
finishRangeWrite(it->second);
|
||||
pendingTerrainWrites_.erase(it);
|
||||
}
|
||||
|
||||
void Renderer::setTerrainGrid(float origin, float spacing, uint32_t cells) {
|
||||
terrainGrid_ = glm::vec4(origin, spacing, static_cast<float>(cells), 0.0f);
|
||||
}
|
||||
|
||||
std::string Renderer::geometryLine() const {
|
||||
return "Geometrie : " + geometryPool_->statsLine();
|
||||
}
|
||||
|
||||
void Renderer::removeMesh(MeshHandle handle) {
|
||||
if (handle >= meshes_.size() || !meshes_[handle]) {
|
||||
return; // deja libere, ou poignee invalide : ne rien faire est sans risque
|
||||
}
|
||||
// PHASE 30 : une tuile commencee mais jamais livree (ecriture en echec)
|
||||
// abandonne son staging : il n'y a rien a copier.
|
||||
pendingTerrainWrites_.erase(handle);
|
||||
|
||||
// Le mesh sort de la table tout de suite (sa poignee redevient disponible)
|
||||
// mais ses buffers Vulkan survivent le temps que les frames deja soumises
|
||||
// aient fini de les lire. Voir le commentaire de declaration.
|
||||
// mais ses plages de geometrie survivent le temps que les frames deja
|
||||
// soumises aient fini de les lire. Voir le commentaire de declaration.
|
||||
retiredMeshes_.push_back({ std::move(meshes_[handle]), kMaxFramesInFlight + 1 });
|
||||
freeMeshSlots_.push_back(handle);
|
||||
--liveMeshCount_;
|
||||
@@ -441,6 +692,7 @@ void Renderer::updateUniformBuffer(uint32_t frameIndex, const Camera& camera) {
|
||||
ubo.precip = precip_;
|
||||
ubo.fall = fall_;
|
||||
ubo.detail = detail_;
|
||||
ubo.terrainGrid = terrainGrid_;
|
||||
|
||||
std::memcpy(uniformBuffers_[frameIndex]->mapped(), &ubo, sizeof(ubo));
|
||||
}
|
||||
@@ -524,13 +776,15 @@ void Renderer::destroyImageSyncObjects() {
|
||||
// - la tuile est lisible DES CETTE FRAME : le repli sur l'ancetre ne sert donc
|
||||
// qu'aux tuiles pas encore CONSTRUITES (budget), pas a une latence de
|
||||
// transfert.
|
||||
void Renderer::enqueueCopy(std::unique_ptr<VulkanBuffer> staging, VkBuffer destination) {
|
||||
void Renderer::enqueueCopy(std::unique_ptr<VulkanBuffer> staging, VkBuffer destination,
|
||||
VkDeviceSize destinationOffset) {
|
||||
if (!staging || destination == VK_NULL_HANDLE) {
|
||||
return;
|
||||
}
|
||||
PendingCopy copy;
|
||||
copy.size = staging->size();
|
||||
copy.destination = destination;
|
||||
copy.destinationOffset = destinationOffset;
|
||||
copy.staging = std::move(staging);
|
||||
stagingBytesInFlight_ += static_cast<std::size_t>(copy.size);
|
||||
pendingCopies_.push_back(std::move(copy));
|
||||
@@ -565,8 +819,10 @@ void Renderer::flushCopiesNow() {
|
||||
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
|
||||
vkBeginCommandBuffer(commandBuffer, &beginInfo);
|
||||
|
||||
recordCopyAfterReadBarrier(commandBuffer);
|
||||
for (const PendingCopy& copy : pendingCopies_) {
|
||||
VkBufferCopy region{};
|
||||
region.dstOffset = copy.destinationOffset;
|
||||
region.size = copy.size;
|
||||
vkCmdCopyBuffer(commandBuffer, copy.staging->handle(), copy.destination,
|
||||
1, ®ion);
|
||||
@@ -603,8 +859,10 @@ void Renderer::recordPendingCopies(VkCommandBuffer commandBuffer) {
|
||||
return;
|
||||
}
|
||||
|
||||
recordCopyAfterReadBarrier(commandBuffer);
|
||||
for (PendingCopy& copy : pendingCopies_) {
|
||||
VkBufferCopy region{};
|
||||
region.dstOffset = copy.destinationOffset;
|
||||
region.size = copy.size;
|
||||
vkCmdCopyBuffer(commandBuffer, copy.staging->handle(), copy.destination,
|
||||
1, ®ion);
|
||||
@@ -694,9 +952,56 @@ void Renderer::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t image
|
||||
// n'est lie qu'une fois par materiau reellement utilise (au plus deux fois
|
||||
// par frame ici). Avec quelques dizaines d'objets, ce tri "par balayage"
|
||||
// coute moins cher qu'un vrai tri, et evite de copier la liste.
|
||||
for (uint32_t m = 0; m < kMaterialCount; ++m) {
|
||||
const Material material = static_cast<Material>(m);
|
||||
//
|
||||
// PHASE 30 : le TERRAIN en dernier. Son shader de fragment est le plus
|
||||
// lourd du jeu (orthophoto, micro-relief, adret/ubac, brouillard) ; dessine
|
||||
// apres les troncs, les houppiers et l'herbe, il trouve leur profondeur
|
||||
// deja ecrite et le test de profondeur PRECOCE ecarte ses fragments caches
|
||||
// avant de les ombrer. Tout est opaque et le test est LESS : l'ordre ne
|
||||
// change l'image qu'a profondeur RIGOUREUSEMENT EGALE - le pied d'un brin
|
||||
// ou d'un tronc, pose exactement sur la surface du sol. Mesure : 24 pixels
|
||||
// sur 921 600 en foret, et une variante qui rend ces egalites au terrain
|
||||
// redonne l'image de reference au bit pres (NOTES-PHASE30.md). Gain : -26 %
|
||||
// de temps de rendu en foret (lavapipe).
|
||||
static constexpr std::array<Material, kMaterialCount> kDrawOrder{
|
||||
Material::Object, Material::Foliage, Material::Terrain };
|
||||
|
||||
// PHASE 30 : liaisons de buffers EVITEES quand elles ne changent rien. Les
|
||||
// tuiles de terrain partagent une seule topologie : elle est liee une fois
|
||||
// par image au lieu d'une fois par tuile. Les liaisons survivent aux
|
||||
// changements de pipeline (etat du command buffer, pas du pipeline).
|
||||
VkBuffer boundVertexBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceSize boundVertexOffset = 0;
|
||||
VkBuffer boundIndexBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceSize boundIndexOffset = 0;
|
||||
VkIndexType boundIndexType = VK_INDEX_TYPE_MAX_ENUM;
|
||||
// Decalage de LIAISON plutot que vertexOffset dans le draw : gl_VertexIndex
|
||||
// reste ainsi l'indice LOCAL du sommet dans son maillage, ce dont
|
||||
// terrain.vert se sert pour retrouver sa place dans la grille de la tuile.
|
||||
const auto bindMesh = [&](const Mesh& mesh) {
|
||||
const GpuRange& vertices = mesh.vertexRange();
|
||||
if (vertices.buffer != boundVertexBuffer || vertices.offset != boundVertexOffset) {
|
||||
vkCmdBindVertexBuffers(commandBuffer, 0, 1, &vertices.buffer, &vertices.offset);
|
||||
boundVertexBuffer = vertices.buffer;
|
||||
boundVertexOffset = vertices.offset;
|
||||
}
|
||||
const GpuRange& indices = mesh.indexRange();
|
||||
if (indices.buffer != boundIndexBuffer || indices.offset != boundIndexOffset ||
|
||||
mesh.indexType() != boundIndexType) {
|
||||
vkCmdBindIndexBuffer(commandBuffer, indices.buffer, indices.offset, mesh.indexType());
|
||||
boundIndexBuffer = indices.buffer;
|
||||
boundIndexOffset = indices.offset;
|
||||
boundIndexType = mesh.indexType();
|
||||
}
|
||||
};
|
||||
|
||||
for (const Material material : kDrawOrder) {
|
||||
const uint32_t m = static_cast<uint32_t>(material);
|
||||
bool pipelineBound = false;
|
||||
// PHASE 30 : un maillage de terrain (16 octets par sommet) ne se lit
|
||||
// qu'avec le pipeline du terrain, et reciproquement.
|
||||
const VertexLayout expectedLayout = (material == Material::Terrain)
|
||||
? VertexLayout::Terrain : VertexLayout::Object;
|
||||
|
||||
for (const DrawItem& item : items) {
|
||||
if (item.material != material) {
|
||||
@@ -709,6 +1014,9 @@ void Renderer::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t image
|
||||
// un pointeur nul). Signaler serait bruyant a 60 Hz.
|
||||
continue;
|
||||
}
|
||||
if (meshes_[item.mesh]->layout() != expectedLayout) {
|
||||
continue; // meme raison : le GPU lirait des octets d'un autre format
|
||||
}
|
||||
|
||||
if (!pipelineBound) {
|
||||
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||||
@@ -723,17 +1031,17 @@ void Renderer::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t image
|
||||
pipelineBound = true;
|
||||
}
|
||||
|
||||
// Transformation et parametres propres a cet objet. Les deux sont
|
||||
// Transformation et parametres propres a cet objet. Tous sont
|
||||
// pousses d'un seul coup : ils sont contigus dans DrawItemPush,
|
||||
// dont le layout reproduit exactement le bloc push_constant des
|
||||
// shaders (voir DrawItem.hpp).
|
||||
const DrawItemPush push{ item.model, item.params };
|
||||
const DrawItemPush push{ item.model, item.params, item.grid };
|
||||
vkCmdPushConstants(commandBuffer, pipelines_[m]->layout(),
|
||||
VK_SHADER_STAGE_VERTEX_BIT, 0,
|
||||
static_cast<uint32_t>(sizeof(DrawItemPush)), &push);
|
||||
|
||||
const Mesh& mesh = *meshes_[item.mesh];
|
||||
mesh.bind(commandBuffer);
|
||||
bindMesh(mesh);
|
||||
mesh.draw(commandBuffer);
|
||||
}
|
||||
|
||||
@@ -746,7 +1054,8 @@ void Renderer::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t image
|
||||
if (item.material != material || item.count == 0) {
|
||||
continue;
|
||||
}
|
||||
if (item.mesh >= meshes_.size() || !meshes_[item.mesh]) {
|
||||
if (item.mesh >= meshes_.size() || !meshes_[item.mesh] ||
|
||||
meshes_[item.mesh]->layout() != expectedLayout) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -765,7 +1074,7 @@ void Renderer::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t image
|
||||
static_cast<uint32_t>(sizeof(DrawItemPush)), &push);
|
||||
|
||||
const Mesh& mesh = *meshes_[item.mesh];
|
||||
mesh.bind(commandBuffer);
|
||||
bindMesh(mesh);
|
||||
|
||||
// Binding 1 : la tranche du buffer d'instances qui appartient a cet
|
||||
// objet. L'offset a ete calcule par uploadInstances, dans le meme
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "renderer/DrawItem.hpp"
|
||||
#include "renderer/GpuBufferPool.hpp"
|
||||
#include "renderer/GpuVertex.hpp"
|
||||
#include "renderer/Pipeline.hpp" // pour ShaderSet
|
||||
#include "renderer/VulkanBuffer.hpp" // pour BufferUploader
|
||||
|
||||
@@ -11,6 +13,8 @@
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace vercora {
|
||||
@@ -49,6 +53,12 @@ struct RenderOptions {
|
||||
// deux se recouvrent bien. Sans texture chargee, la valeur est ignoree (le
|
||||
// binding pointe alors sur un texel blanc).
|
||||
float orthoMix = 0.0f;
|
||||
|
||||
// PHASE 30. Force le televersement de la geometrie par STAGING meme en
|
||||
// memoire unifiee, ou elle est sinon ecrite directement la ou le GPU la
|
||||
// lit. Sert a eprouver sur la machine de developpement le chemin d'un GPU
|
||||
// discret (option --force-staging).
|
||||
bool forceStaging = false;
|
||||
};
|
||||
|
||||
// Orchestre le rendu : geometries enregistrees, UBO/descriptors, command
|
||||
@@ -85,6 +95,48 @@ public:
|
||||
// toute autre information.
|
||||
MeshHandle addMesh(const MeshData& meshData, bool log = true);
|
||||
|
||||
// PHASE 30 : GEOMETRIE DE TERRAIN, au format compact TerrainVertex (16
|
||||
// octets, voir renderer/GpuVertex.hpp). Un tel maillage ne se dessine
|
||||
// qu'avec Material::Terrain et un DrawItem::grid qui dit ou il se trouve
|
||||
// dans la heightmap.
|
||||
//
|
||||
// Terrain d'un seul bloc (--no-lod) : sommets et topologie propres.
|
||||
MeshHandle addTerrainMesh(const std::vector<TerrainVertex>& vertices,
|
||||
const std::vector<uint32_t>& indices,
|
||||
const std::string& name, bool log = true);
|
||||
|
||||
// Topologie PARTAGEE par plusieurs maillages de terrain : les tuiles du
|
||||
// quadtree ont toutes la meme (Phase 18), et la televerser une fois au lieu
|
||||
// d'une par tuile economise 96 Ko par tuile residente. Stockee en uint16
|
||||
// quand les indices le permettent (65 x 65 sommets par tuile). Vit aussi
|
||||
// longtemps que le Renderer.
|
||||
uint32_t addSharedIndices(const std::vector<uint32_t>& indices);
|
||||
|
||||
// Tuile de terrain sur une topologie partagee, ECRITE PAR L'APPELANT :
|
||||
// beginTerrainMesh reserve la place et rend un pointeur sur `vertexCount`
|
||||
// sommets a remplir - directement la memoire que le GPU lira en memoire
|
||||
// unifiee, un staging sinon - et endTerrainMesh la livre. Entre les deux,
|
||||
// l'ecriture peut se faire depuis N'IMPORTE QUEL thread (aucun appel
|
||||
// Vulkan) : c'est ce qui laisse le maillage parallele de la Phase 19
|
||||
// ecrire sans copie intermediaire. begin et end, eux, restent sur le
|
||||
// thread de rendu, et chaque begin doit etre suivi de son end (ou d'un
|
||||
// removeMesh si l'ecriture a echoue).
|
||||
struct TerrainMeshWrite {
|
||||
MeshHandle mesh = kInvalidMesh;
|
||||
TerrainVertex* vertices = nullptr;
|
||||
};
|
||||
TerrainMeshWrite beginTerrainMesh(uint32_t vertexCount, uint32_t sharedIndices);
|
||||
void endTerrainMesh(MeshHandle mesh);
|
||||
|
||||
// PHASE 30 : grille de la heightmap, lue par terrain.vert pour recalculer
|
||||
// la position horizontale et l'UV des sommets de terrain (voir
|
||||
// UniformBufferObject::terrainGrid). A appeler une fois, avant la premiere
|
||||
// image, des qu'un terrain est charge.
|
||||
void setTerrainGrid(float origin, float spacing, uint32_t cells);
|
||||
|
||||
// PHASE 30 : bilan du pool de geometrie, pour le journal.
|
||||
std::string geometryLine() const;
|
||||
|
||||
// Libere une geometrie et rend sa poignee reutilisable. Indispensable depuis
|
||||
// la Phase 10 : le streaming par tuiles cree et detruit des maillages en
|
||||
// permanence, alors que jusque-la une geometrie enregistree vivait aussi
|
||||
@@ -233,7 +285,7 @@ public:
|
||||
// garanti par construction - le seul appelant est addMesh, et removeMesh
|
||||
// DIFFERE la destruction des buffers de kMaxFramesInFlight + 1 frames.
|
||||
void enqueueCopy(std::unique_ptr<VulkanBuffer> staging,
|
||||
VkBuffer destination) override;
|
||||
VkBuffer destination, VkDeviceSize destinationOffset) override;
|
||||
|
||||
// Octets de staging en attente d'enregistrement + en attente d'execution.
|
||||
// Sert au journal de diagnostic du streaming.
|
||||
@@ -266,6 +318,7 @@ private:
|
||||
glm::vec4 precip_{0.0f, 0.0f, 0.0f, 0.0f};
|
||||
glm::vec4 fall_{0.0f, -6.5f, 0.0f, 0.0f};
|
||||
glm::vec4 detail_{0.0f, 0.0f, 1.0f, 1.0f};
|
||||
glm::vec4 terrainGrid_{0.0f, 1.0f, 1.0f, 0.0f}; // PHASE 30, voir setTerrainGrid()
|
||||
|
||||
static constexpr int kMaxFramesInFlight = 2;
|
||||
|
||||
@@ -306,12 +359,45 @@ private:
|
||||
void uploadInstances(const std::vector<InstancedDrawItem>& instanced);
|
||||
void recreateSwapChain();
|
||||
|
||||
// PHASE 30. Ecriture dans une plage du pool : `destination` pointe soit
|
||||
// dans la plage elle-meme (memoire unifiee), soit dans un staging, et
|
||||
// finishRangeWrite confie alors la copie a la prochaine image.
|
||||
struct RangeWrite {
|
||||
GpuRange range;
|
||||
void* destination = nullptr;
|
||||
std::unique_ptr<VulkanBuffer> staging;
|
||||
};
|
||||
RangeWrite beginRangeWrite(const GpuRange& range);
|
||||
void finishRangeWrite(RangeWrite& write);
|
||||
|
||||
// Inscrit un Mesh dans la table et rend sa poignee (emplacement libre
|
||||
// reutilise s'il y en a un).
|
||||
MeshHandle registerMesh(std::unique_ptr<Mesh> mesh);
|
||||
|
||||
VulkanContext& context_;
|
||||
Window& window_;
|
||||
RenderOptions options_;
|
||||
|
||||
std::unique_ptr<SwapChain> swapChain_;
|
||||
|
||||
// PHASE 30 : TOUTE la geometrie (sommets et indices, objets et terrain)
|
||||
// vit dans les blocs de ce pool. Declare AVANT les tables de maillages :
|
||||
// les membres etant detruits dans l'ordre inverse, il survit a tous les
|
||||
// Mesh, qui lui rendent leurs plages en se detruisant.
|
||||
std::unique_ptr<GpuBufferPool> geometryPool_;
|
||||
|
||||
// Topologies partagees (addSharedIndices), rendues a la destruction.
|
||||
struct SharedIndices {
|
||||
GpuRange range;
|
||||
uint32_t count = 0;
|
||||
VkIndexType type = VK_INDEX_TYPE_UINT16;
|
||||
};
|
||||
std::vector<SharedIndices> sharedIndices_;
|
||||
|
||||
// Tuiles commencees (beginTerrainMesh) dont l'ecriture passe par un
|
||||
// staging, en attente de leur endTerrainMesh.
|
||||
std::unordered_map<MeshHandle, RangeWrite> pendingTerrainWrites_;
|
||||
|
||||
// Un pipeline par materiau, indexe par la valeur de l'enum Material. Tous
|
||||
// partagent le meme descriptor set layout et le meme push constant range :
|
||||
// seuls les shaders different.
|
||||
@@ -348,6 +434,7 @@ private:
|
||||
struct PendingCopy {
|
||||
std::unique_ptr<VulkanBuffer> staging;
|
||||
VkBuffer destination = VK_NULL_HANDLE;
|
||||
VkDeviceSize destinationOffset = 0;
|
||||
VkDeviceSize size = 0;
|
||||
};
|
||||
std::vector<PendingCopy> pendingCopies_;
|
||||
|
||||
@@ -9,6 +9,58 @@
|
||||
|
||||
namespace vercora {
|
||||
|
||||
namespace {
|
||||
|
||||
// Normale analytique de la surface y = h(x,z) au noeud (ix, iz) : le vecteur
|
||||
// normal vaut (-dh/dx, 1, -dh/dz). Les derivees sont estimees par difference
|
||||
// CENTREE sur les deux voisins (plus precis et plus symetrique qu'un produit
|
||||
// vectoriel sur une seule face). Sur les bords, at() ecrete les indices : la
|
||||
// difference devient unilaterale, d'ou le pas reel (xp - xm) au denominateur
|
||||
// plutot qu'un 2 en dur - sinon les normales du bord seraient deux fois trop
|
||||
// plates.
|
||||
//
|
||||
// PHASE 30 : sortie de la boucle de terrainMeshData pour etre partagee avec
|
||||
// terrainGpuMeshData - les deux formats ont ainsi, par construction, les memes
|
||||
// normales.
|
||||
glm::vec3 gridNormal(const Heightmap& heightmap, uint32_t ix, uint32_t iz, uint32_t res,
|
||||
float spacing) {
|
||||
const int64_t xm = (ix > 0) ? ix - 1 : ix;
|
||||
const int64_t xp = (ix + 1 < res) ? ix + 1 : ix;
|
||||
const int64_t zm = (iz > 0) ? iz - 1 : iz;
|
||||
const int64_t zp = (iz + 1 < res) ? iz + 1 : iz;
|
||||
|
||||
const float dhdx = (heightmap.at(xp, iz) - heightmap.at(xm, iz)) /
|
||||
(static_cast<float>(xp - xm) * spacing);
|
||||
const float dhdz = (heightmap.at(ix, zp) - heightmap.at(ix, zm)) /
|
||||
(static_cast<float>(zp - zm) * spacing);
|
||||
|
||||
return glm::normalize(glm::vec3(-dhdx, 1.0f, -dhdz));
|
||||
}
|
||||
|
||||
// Deux triangles par cellule, coupes le long de la diagonale v00-v11 (voir le
|
||||
// commentaire de l'etape 2 de terrainMeshData).
|
||||
void appendGridIndices(uint32_t res, std::vector<uint32_t>& indices) {
|
||||
const uint32_t cells = res - 1;
|
||||
for (uint32_t iz = 0; iz < cells; ++iz) {
|
||||
for (uint32_t ix = 0; ix < cells; ++ix) {
|
||||
const uint32_t v00 = iz * res + ix;
|
||||
const uint32_t v10 = v00 + 1;
|
||||
const uint32_t v01 = v00 + res;
|
||||
const uint32_t v11 = v01 + 1;
|
||||
|
||||
indices.push_back(v00);
|
||||
indices.push_back(v01);
|
||||
indices.push_back(v11);
|
||||
|
||||
indices.push_back(v00);
|
||||
indices.push_back(v11);
|
||||
indices.push_back(v10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
MeshData terrainMeshData(const Heightmap& heightmap) {
|
||||
const uint32_t res = heightmap.resolution();
|
||||
if (res < 2) {
|
||||
@@ -53,25 +105,8 @@ MeshData terrainMeshData(const Heightmap& heightmap) {
|
||||
// LiDAR : sol / vegetation / bati) sans toucher au shader.
|
||||
vertex.color = { 1.0f, 1.0f, 1.0f };
|
||||
|
||||
// Normale analytique de la surface y = h(x,z) : le vecteur normal
|
||||
// vaut (-dh/dx, 1, -dh/dz). Les derivees sont estimees par
|
||||
// difference CENTREE sur les deux voisins (plus precis et plus
|
||||
// symetrique qu'un produit vectoriel sur une seule face).
|
||||
// Sur les bords, at() ecrete les indices : la difference devient
|
||||
// unilaterale, d'ou le pas reel (xp - xm) au denominateur plutot
|
||||
// qu'un 2 en dur - sinon les normales du bord seraient deux fois
|
||||
// trop plates.
|
||||
const int64_t xm = (ix > 0) ? ix - 1 : ix;
|
||||
const int64_t xp = (ix + 1 < res) ? ix + 1 : ix;
|
||||
const int64_t zm = (iz > 0) ? iz - 1 : iz;
|
||||
const int64_t zp = (iz + 1 < res) ? iz + 1 : iz;
|
||||
|
||||
const float dhdx = (heightmap.at(xp, iz) - heightmap.at(xm, iz)) /
|
||||
(static_cast<float>(xp - xm) * spacing);
|
||||
const float dhdz = (heightmap.at(ix, zp) - heightmap.at(ix, zm)) /
|
||||
(static_cast<float>(zp - zm) * spacing);
|
||||
|
||||
vertex.normal = glm::normalize(glm::vec3(-dhdx, 1.0f, -dhdz));
|
||||
// Normale par differences centrees, voir gridNormal.
|
||||
vertex.normal = gridNormal(heightmap, ix, iz, res, spacing);
|
||||
|
||||
// UV sur tout le terrain. Pas encore consomme (pas de texturing),
|
||||
// mais c'est le repere naturel pour y plaquer une orthophoto le jour
|
||||
@@ -90,33 +125,11 @@ MeshData terrainMeshData(const Heightmap& heightmap) {
|
||||
// ici oblige a la changer la-bas aussi.
|
||||
//
|
||||
// Enroulement anti-horaire vu de dessus (+Y), coherent avec la convention
|
||||
// des .obj de la Phase 3. Le culling est desactive dans Pipeline, donc c'est
|
||||
// sans effet visible aujourd'hui, mais ca rend le back-face culling
|
||||
// activable sans retoucher la geometrie.
|
||||
for (uint32_t iz = 0; iz < cells; ++iz) {
|
||||
for (uint32_t ix = 0; ix < cells; ++ix) {
|
||||
const uint32_t v00 = iz * res + ix;
|
||||
const uint32_t v10 = v00 + 1;
|
||||
const uint32_t v01 = v00 + res;
|
||||
const uint32_t v11 = v01 + 1;
|
||||
// des .obj de la Phase 3. C'est ce qui a rendu le back-face culling du
|
||||
// terrain activable sans retoucher la geometrie (PHASE 30, voir
|
||||
// ShaderSet::cullBackFaces).
|
||||
appendGridIndices(res, mesh.indices);
|
||||
|
||||
mesh.indices.push_back(v00);
|
||||
mesh.indices.push_back(v01);
|
||||
mesh.indices.push_back(v11);
|
||||
|
||||
mesh.indices.push_back(v00);
|
||||
mesh.indices.push_back(v11);
|
||||
mesh.indices.push_back(v10);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 3. Controle de coherence ------------------------------------------
|
||||
// Meme esprit que les gardes-fous du loader .obj (Phase 3) : on refuse de
|
||||
// pousser vers le GPU une geometrie qu'on sait cassee, plutot que d'afficher
|
||||
// une fenetre vide sans explication. Ici le generateur est deterministe,
|
||||
// donc ces tests attrapent une erreur de code (indexation, resolution), pas
|
||||
// une donnee douteuse - ils resteront pertinents quand la grille viendra du
|
||||
// LiDAR.
|
||||
if (mesh.indices.size() % 3 != 0) {
|
||||
throw std::runtime_error("TerrainMesh : nombre d'index non multiple de 3.");
|
||||
}
|
||||
@@ -145,4 +158,49 @@ MeshData terrainMeshData(const Heightmap& heightmap) {
|
||||
return mesh;
|
||||
}
|
||||
|
||||
TerrainGpuMesh terrainGpuMeshData(const Heightmap& heightmap) {
|
||||
const uint32_t res = heightmap.resolution();
|
||||
if (res < 2) {
|
||||
throw std::runtime_error(
|
||||
"TerrainMesh : une grille de " + std::to_string(res) +
|
||||
" echantillons par cote ne forme aucune cellule.");
|
||||
}
|
||||
const uint32_t cells = res - 1;
|
||||
const float spacing = heightmap.spacing();
|
||||
|
||||
TerrainGpuMesh mesh;
|
||||
mesh.name = heightmap.describe();
|
||||
mesh.vertices.resize(static_cast<std::size_t>(res) * res);
|
||||
mesh.indices.reserve(static_cast<std::size_t>(cells) * cells * 6);
|
||||
|
||||
for (uint32_t iz = 0; iz < res; ++iz) {
|
||||
for (uint32_t ix = 0; ix < res; ++ix) {
|
||||
const float height = heightmap.at(ix, iz);
|
||||
const glm::vec3 normal = gridNormal(heightmap, ix, iz, res, spacing);
|
||||
if (!std::isfinite(height) || !std::isfinite(normal.y)) {
|
||||
throw std::runtime_error(
|
||||
"TerrainMesh : coordonnee ou normale non finie (NaN/infini) "
|
||||
"produite par la heightmap.");
|
||||
}
|
||||
// Pas de geomorphing pour un bloc unique (bande de morphing vide) :
|
||||
// la cible est le sommet lui-meme, comme le laissait a zero le
|
||||
// format de 68 octets - sans effet puisque jamais lue.
|
||||
TerrainVertex& vertex = mesh.vertices[static_cast<std::size_t>(iz) * res + ix];
|
||||
vertex.height = height;
|
||||
vertex.morphHeight = height;
|
||||
vertex.normal[0] = packSnorm16(normal.x);
|
||||
vertex.normal[1] = packSnorm16(normal.z);
|
||||
vertex.morphNormal[0] = vertex.normal[0];
|
||||
vertex.morphNormal[1] = vertex.normal[1];
|
||||
}
|
||||
}
|
||||
appendGridIndices(res, mesh.indices);
|
||||
|
||||
logInfo("Maillage terrain (format GPU compact) : " + std::to_string(mesh.vertices.size()) +
|
||||
" sommets, " + std::to_string(mesh.indices.size() / 3) + " triangles, " +
|
||||
std::to_string(mesh.vertices.size() * sizeof(TerrainVertex) / (1024 * 1024)) +
|
||||
" Mo de sommets.");
|
||||
return mesh;
|
||||
}
|
||||
|
||||
} // namespace vercora
|
||||
@@ -1,7 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "renderer/GpuVertex.hpp"
|
||||
#include "renderer/MeshData.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace vercora {
|
||||
|
||||
class Heightmap;
|
||||
@@ -20,4 +25,17 @@ class Heightmap;
|
||||
// Lance std::runtime_error si la grille ne peut pas produire un maillage sain.
|
||||
MeshData terrainMeshData(const Heightmap& heightmap);
|
||||
|
||||
// PHASE 30. Le meme terrain d'un seul bloc, au format GPU du terrain
|
||||
// (TerrainVertex, 16 octets) : c'est ce que televerse le chemin --no-lod, sans
|
||||
// construire au passage le MeshData de 68 octets par sommet (1,7 Go sur la zone
|
||||
// au pas de 1 m). vertices[v] == toTerrainVertex(terrainMeshData(h).vertices[v])
|
||||
// au bit pres et les indices sont identiques (verifie par les tests). Les
|
||||
// sommets n'ont pas de cible de geomorphing : elle vaut le sommet lui-meme.
|
||||
struct TerrainGpuMesh {
|
||||
std::vector<TerrainVertex> vertices;
|
||||
std::vector<uint32_t> indices;
|
||||
std::string name;
|
||||
};
|
||||
TerrainGpuMesh terrainGpuMeshData(const Heightmap& heightmap);
|
||||
|
||||
} // namespace vercora
|
||||
@@ -89,9 +89,16 @@ std::vector<uint32_t> terrainNodeIndices(uint32_t nodeCells) {
|
||||
return indices;
|
||||
}
|
||||
|
||||
MeshData terrainNodeMeshData(const Heightmap& heightmap, const TerrainQuadtree& quadtree,
|
||||
uint32_t nodeIndex, bool withIndices,
|
||||
bool reuseParentGrid) {
|
||||
namespace {
|
||||
|
||||
// PHASE 30 : le parcours d'un noeud, commun aux deux formats de sortie
|
||||
// (MeshData de reference et TerrainVertex du GPU). `sink(v, gx, gz, here,
|
||||
// parent)` recoit chaque sommet - son indice dans la tuile, ses indices de
|
||||
// grille ecretes, son echantillon et celui de sa cible de geomorphing. Un seul
|
||||
// parcours, donc deux sorties qui ne PEUVENT PAS diverger.
|
||||
template <typename Sink>
|
||||
void forEachNodeVertex(const Heightmap& heightmap, const TerrainQuadtree& quadtree,
|
||||
uint32_t nodeIndex, bool reuseParentGrid, Sink&& sink) {
|
||||
if (nodeIndex >= quadtree.nodeCount()) {
|
||||
throw std::runtime_error("TerrainNodeMesh : indice de noeud hors limites.");
|
||||
}
|
||||
@@ -133,11 +140,6 @@ MeshData terrainNodeMeshData(const Heightmap& heightmap, const TerrainQuadtree&
|
||||
}
|
||||
}
|
||||
|
||||
MeshData mesh;
|
||||
mesh.name = "tuile L" + std::to_string(static_cast<int>(node.level)) + " (" +
|
||||
std::to_string(node.ix0) + "," + std::to_string(node.iz0) + ")";
|
||||
mesh.vertices.resize(static_cast<std::size_t>(verts) * verts);
|
||||
|
||||
for (uint32_t j = 0; j < verts; ++j) {
|
||||
for (uint32_t i = 0; i < verts; ++i) {
|
||||
// Indices de grille du sommet, ECRETES sur le bord du terrain.
|
||||
@@ -157,43 +159,97 @@ MeshData terrainNodeMeshData(const Heightmap& heightmap, const TerrainQuadtree&
|
||||
? parentGrid[static_cast<std::size_t>(j / 2u) * parentVerts + (i / 2u)]
|
||||
: parentSample;
|
||||
|
||||
Vertex& vertex = mesh.vertices[static_cast<std::size_t>(j) * verts + i];
|
||||
vertex.pos = here.position;
|
||||
vertex.normal = here.normal;
|
||||
vertex.morphPos = parent.position;
|
||||
vertex.morphNormal = parent.normal;
|
||||
|
||||
// Teinte neutre : le fragment shader colore par altitude et par
|
||||
// pente. Reserve a une future classification LiDAR par sommet.
|
||||
vertex.color = { 1.0f, 1.0f, 1.0f };
|
||||
|
||||
// UV sur TOUT le terrain (et non sur la tuile) : c'est le repere
|
||||
// naturel d'une future orthophoto, et il doit rester continu d'une
|
||||
// tuile a l'autre.
|
||||
vertex.uv = { static_cast<float>(gx) / static_cast<float>(cells),
|
||||
static_cast<float>(gz) / static_cast<float>(cells) };
|
||||
sink(static_cast<std::size_t>(j) * verts + i, gx, gz, here, parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Controle de coherence, meme esprit que TerrainMesh : on refuse de pousser
|
||||
// vers le GPU une geometrie qu'on sait cassee. Le generateur etant
|
||||
// deterministe, ce test attrape une erreur de CODE (indexation, pas de
|
||||
// parcours), pas une donnee douteuse.
|
||||
[[noreturn]] void throwNonFinite() {
|
||||
throw std::runtime_error(
|
||||
"TerrainNodeMesh : coordonnee ou normale non finie (NaN/infini) "
|
||||
"produite par la heightmap.");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
MeshData terrainNodeMeshData(const Heightmap& heightmap, const TerrainQuadtree& quadtree,
|
||||
uint32_t nodeIndex, bool withIndices,
|
||||
bool reuseParentGrid) {
|
||||
if (nodeIndex >= quadtree.nodeCount()) {
|
||||
throw std::runtime_error("TerrainNodeMesh : indice de noeud hors limites.");
|
||||
}
|
||||
const TerrainQuadtree::Node& node = quadtree.node(nodeIndex);
|
||||
const uint32_t nodeCells = quadtree.nodeCells();
|
||||
const uint32_t verts = nodeCells + 1;
|
||||
const uint32_t cells = heightmap.resolution() - 1;
|
||||
|
||||
MeshData mesh;
|
||||
mesh.name = "tuile L" + std::to_string(static_cast<int>(node.level)) + " (" +
|
||||
std::to_string(node.ix0) + "," + std::to_string(node.iz0) + ")";
|
||||
mesh.vertices.resize(static_cast<std::size_t>(verts) * verts);
|
||||
|
||||
forEachNodeVertex(heightmap, quadtree, nodeIndex, reuseParentGrid,
|
||||
[&](std::size_t v, uint32_t gx, uint32_t gz,
|
||||
const GridSample& here, const GridSample& parent) {
|
||||
Vertex& vertex = mesh.vertices[v];
|
||||
vertex.pos = here.position;
|
||||
vertex.normal = here.normal;
|
||||
vertex.morphPos = parent.position;
|
||||
vertex.morphNormal = parent.normal;
|
||||
|
||||
// Teinte neutre : le fragment shader colore par altitude et par
|
||||
// pente. Reserve a une future classification LiDAR par sommet.
|
||||
vertex.color = { 1.0f, 1.0f, 1.0f };
|
||||
|
||||
// UV sur TOUT le terrain (et non sur la tuile) : c'est le repere
|
||||
// naturel d'une future orthophoto, et il doit rester continu d'une
|
||||
// tuile a l'autre.
|
||||
vertex.uv = { static_cast<float>(gx) / static_cast<float>(cells),
|
||||
static_cast<float>(gz) / static_cast<float>(cells) };
|
||||
});
|
||||
|
||||
if (withIndices) {
|
||||
mesh.indices = terrainNodeIndices(nodeCells);
|
||||
}
|
||||
|
||||
// Controle de coherence, meme esprit que TerrainMesh : on refuse de pousser
|
||||
// vers le GPU une geometrie qu'on sait cassee. Le generateur etant
|
||||
// deterministe, ce test attrape une erreur de CODE (indexation, pas de
|
||||
// parcours), pas une donnee douteuse.
|
||||
for (const Vertex& vertex : mesh.vertices) {
|
||||
if (!std::isfinite(vertex.pos.x) || !std::isfinite(vertex.pos.y) ||
|
||||
!std::isfinite(vertex.pos.z) || !std::isfinite(vertex.normal.y) ||
|
||||
!std::isfinite(vertex.morphPos.y)) {
|
||||
throw std::runtime_error(
|
||||
"TerrainNodeMesh : coordonnee ou normale non finie (NaN/infini) "
|
||||
"produite par la heightmap.");
|
||||
throwNonFinite();
|
||||
}
|
||||
}
|
||||
|
||||
return mesh;
|
||||
}
|
||||
|
||||
void writeTerrainNodeVertices(const Heightmap& heightmap, const TerrainQuadtree& quadtree,
|
||||
uint32_t nodeIndex, TerrainVertex* out,
|
||||
bool reuseParentGrid) {
|
||||
bool finite = true;
|
||||
forEachNodeVertex(heightmap, quadtree, nodeIndex, reuseParentGrid,
|
||||
[&](std::size_t v, uint32_t /*gx*/, uint32_t /*gz*/,
|
||||
const GridSample& here, const GridSample& parent) {
|
||||
// Les memes octets que toTerrainVertex(Vertex) appliquee au sommet de
|
||||
// terrainNodeMeshData : altitudes recopiees, normales quantifiees.
|
||||
TerrainVertex packed;
|
||||
packed.height = here.position.y;
|
||||
packed.morphHeight = parent.position.y;
|
||||
packed.normal[0] = packSnorm16(here.normal.x);
|
||||
packed.normal[1] = packSnorm16(here.normal.z);
|
||||
packed.morphNormal[0] = packSnorm16(parent.normal.x);
|
||||
packed.morphNormal[1] = packSnorm16(parent.normal.z);
|
||||
out[v] = packed;
|
||||
finite = finite && std::isfinite(here.position.y) && std::isfinite(here.normal.y) &&
|
||||
std::isfinite(parent.position.y);
|
||||
});
|
||||
if (!finite) {
|
||||
throwNonFinite();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vercora
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "renderer/GpuVertex.hpp"
|
||||
#include "renderer/MeshData.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -63,4 +64,23 @@ MeshData terrainNodeMeshData(const Heightmap& heightmap, const TerrainQuadtree&
|
||||
// diagonale que TerrainMesh. Calculee une fois par appelant et reutilisee.
|
||||
std::vector<uint32_t> terrainNodeIndices(uint32_t nodeCells);
|
||||
|
||||
// PHASE 30. Les MEMES sommets que terrainNodeMeshData, ecrits directement au
|
||||
// format GPU du terrain (TerrainVertex, 16 octets) dans `out`, qui doit pouvoir
|
||||
// en recevoir (nodeCells + 1)^2. C'est le chemin du TerrainStreamer : `out`
|
||||
// pointe dans la memoire que le GPU lira (ou dans un staging), et aucun
|
||||
// MeshData de 287 Ko n'est plus construit puis recopie par tuile.
|
||||
//
|
||||
// Garantie, verifiee par tests/logic_tests.cpp : pour tout noeud,
|
||||
// out[v] == toTerrainVertex(terrainNodeMeshData(...).vertices[v]) AU BIT PRES -
|
||||
// memes altitudes, memes normales avant quantification. C'est
|
||||
// terrainNodeMeshData qui reste la reference testee de la geometrie (positions,
|
||||
// morphing, bords) ; cette fonction n'en est qu'un autre format de sortie.
|
||||
//
|
||||
// Pure et sans etat partage, comme terrainNodeMeshData : appelable depuis
|
||||
// plusieurs threads sur des noeuds et des sorties distincts (Phase 19).
|
||||
// Lance std::runtime_error pour les memes raisons.
|
||||
void writeTerrainNodeVertices(const Heightmap& heightmap, const TerrainQuadtree& quadtree,
|
||||
uint32_t nodeIndex, TerrainVertex* out,
|
||||
bool reuseParentGrid = true);
|
||||
|
||||
} // namespace vercora
|
||||
@@ -20,15 +20,19 @@ TerrainStreamer::TerrainStreamer(const Heightmap& heightmap, Renderer& renderer,
|
||||
quadtree_(heightmap, params.quadtree) {
|
||||
logInfo(quadtree_.describe());
|
||||
|
||||
const std::size_t bytesPerNode = static_cast<std::size_t>(quadtree_.nodeCells() + 1) *
|
||||
(quadtree_.nodeCells() + 1) * sizeof(Vertex) +
|
||||
static_cast<std::size_t>(quadtree_.trianglesPerNode()) *
|
||||
3 * sizeof(uint32_t);
|
||||
// PHASE 30 : une tuile ne pese plus que ses sommets, au format compact
|
||||
// (16 octets au lieu de 68) ; sa topologie est televersee UNE fois pour
|
||||
// toutes, ici, en uint16.
|
||||
bytesPerNode_ = static_cast<std::size_t>(quadtree_.nodeCells() + 1) *
|
||||
(quadtree_.nodeCells() + 1) * sizeof(TerrainVertex);
|
||||
sharedIndexSet_ = renderer_.addSharedIndices(sharedIndices());
|
||||
logInfo("Streaming terrain : au plus " + std::to_string(params_.maxResidentNodes) +
|
||||
" tuiles residentes (" +
|
||||
std::to_string(params_.maxResidentNodes * bytesPerNode / (1024 * 1024)) +
|
||||
" Mo de geometrie GPU), " + std::to_string(params_.maxUploadsPerFrame) +
|
||||
" construites par frame.");
|
||||
std::to_string(params_.maxResidentNodes * bytesPerNode_ / (1024 * 1024)) +
|
||||
" Mo de geometrie GPU, " + std::to_string(bytesPerNode_ / 1024) +
|
||||
" Ko par tuile, topologie partagee de " +
|
||||
std::to_string(sharedIndices().size() * sizeof(uint16_t) / 1024) + " Ko), " +
|
||||
std::to_string(params_.maxUploadsPerFrame) + " construites par frame.");
|
||||
|
||||
pinTopLevels();
|
||||
}
|
||||
@@ -46,11 +50,6 @@ void TerrainStreamer::pinTopLevels() {
|
||||
const int lowest = std::max(0, static_cast<int>(quadtree_.rootLevel()) -
|
||||
static_cast<int>(params_.pinnedTopLevels) + 1);
|
||||
|
||||
const std::size_t bytesPerNode =
|
||||
static_cast<std::size_t>(quadtree_.nodeCells() + 1) *
|
||||
(quadtree_.nodeCells() + 1) * sizeof(Vertex) +
|
||||
static_cast<std::size_t>(quadtree_.trianglesPerNode()) * 3 * sizeof(uint32_t);
|
||||
|
||||
for (uint32_t index = 0; index < quadtree_.nodeCount(); ++index) {
|
||||
if (static_cast<int>(quadtree_.node(index).level) < lowest) {
|
||||
continue;
|
||||
@@ -61,19 +60,19 @@ void TerrainStreamer::pinTopLevels() {
|
||||
}
|
||||
ResidentNode node;
|
||||
node.mesh = mesh;
|
||||
node.bytes = bytesPerNode;
|
||||
node.bytes = bytesPerNode_;
|
||||
node.pinned = true;
|
||||
// Jamais rajeunie ensuite : elle n'est de toute facon pas evincable.
|
||||
node.lastUsedFrame = 0;
|
||||
resident_.emplace(index, node);
|
||||
residentBytes_ += bytesPerNode;
|
||||
residentBytes_ += bytesPerNode_;
|
||||
++pinnedCount_;
|
||||
}
|
||||
|
||||
logInfo("Sommet du quadtree epingle : " + std::to_string(pinnedCount_) +
|
||||
" tuiles de niveau " + std::to_string(lowest) + " a " +
|
||||
std::to_string(static_cast<int>(quadtree_.rootLevel())) + " (" +
|
||||
std::to_string(pinnedCount_ * bytesPerNode / (1024 * 1024)) +
|
||||
std::to_string(pinnedCount_ * bytesPerNode_ / (1024 * 1024)) +
|
||||
" Mo), jamais evincees. C'est ce qui rend le repli sur l'ancetre "
|
||||
"toujours disponible.");
|
||||
}
|
||||
@@ -107,11 +106,11 @@ const std::vector<uint32_t>& TerrainStreamer::sharedIndices() const {
|
||||
// n'aurait parie sur la boucle d'indices.
|
||||
//
|
||||
// Construite a la premiere tuile puis simplement RECOPIEE dans le MeshData.
|
||||
// Ne pas la recopier du tout - partager un unique buffer d'indices GPU entre
|
||||
// toutes les tuiles - economiserait en plus 96 Ko par tuile residente, mais
|
||||
// demanderait de dissocier sommets et indices dans Renderer::addMesh : c'est
|
||||
// un chantier de renderer, pas de streaming (voir NOTES-PHASE18.md).
|
||||
if (indexTemplate_.empty() || !params_.cacheTileWork) {
|
||||
// PHASE 30 : elle n'est meme plus recopiee. Le chantier de renderer que
|
||||
// cette note annoncait (NOTES-PHASE18.md) est fait : un UNIQUE buffer
|
||||
// d'indices GPU, en uint16, sert toutes les tuiles - 96 Ko economises par
|
||||
// tuile residente, et une seule liaison d'indices par image.
|
||||
if (indexTemplate_.empty()) {
|
||||
indexTemplate_ = terrainNodeIndices(quadtree_.nodeCells());
|
||||
}
|
||||
return indexTemplate_;
|
||||
@@ -148,19 +147,40 @@ bool TerrainStreamer::wantsParallel(std::size_t count) const {
|
||||
}
|
||||
|
||||
void TerrainStreamer::meshBatch(const std::vector<uint32_t>& nodes) {
|
||||
batchMeshes_.clear();
|
||||
batchErrors_.clear();
|
||||
batchMeshes_.resize(nodes.size());
|
||||
batchErrors_.resize(nodes.size());
|
||||
batchMeshes_.assign(nodes.size(), kInvalidMesh);
|
||||
batchWrites_.assign(nodes.size(), Renderer::TerrainMeshWrite{});
|
||||
if (nodes.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Le corps d'un travailleur. Il ne touche QUE batchMeshes_[k] et
|
||||
// batchErrors_[k] pour k dans [begin, end) - des elements deja alloues, donc
|
||||
// ni le vecteur ni sa capacite ne bougent pendant l'execution. Tout le reste
|
||||
// de ce qu'il lit (heightmap_, quadtree_, params_) est const pour la duree
|
||||
// de la session.
|
||||
// --- 1. Reservation, thread de rendu -----------------------------------
|
||||
// Faire de la place AVANT de reserver, sinon le pic de residence depasserait
|
||||
// le plafond le temps du lot. Les tuiles deja reservees de ce lot comptent
|
||||
// comme residentes : elles le seront a la fin de la frame.
|
||||
const auto t0 = Clock::now();
|
||||
for (std::size_t k = 0; k < nodes.size(); ++k) {
|
||||
while (resident_.size() + k >= params_.maxResidentNodes) {
|
||||
if (!evictOne()) {
|
||||
break; // tout est utilise cette frame : on laisse deborder
|
||||
}
|
||||
}
|
||||
try {
|
||||
batchWrites_[k] = renderer_.beginTerrainMesh(
|
||||
(quadtree_.nodeCells() + 1) * (quadtree_.nodeCells() + 1), sharedIndexSet_);
|
||||
} catch (const std::exception& e) {
|
||||
batchErrors_[k] = e.what();
|
||||
}
|
||||
}
|
||||
uploadMicros_ += microsBetween(t0, Clock::now());
|
||||
|
||||
// --- 2. Ecriture des sommets, eventuellement en parallele ----------------
|
||||
// Le corps d'un travailleur. Il ne touche QUE la zone reservee
|
||||
// batchWrites_[k].vertices et batchErrors_[k] pour k dans [begin, end) -
|
||||
// deja allouees, donc ni les vecteurs ni leur capacite ne bougent pendant
|
||||
// l'execution. Tout le reste de ce qu'il lit (heightmap_, quadtree_,
|
||||
// params_) est const pour la duree de la session.
|
||||
//
|
||||
// Le chronometrage par tuile est fait ICI, mais il n'est PAS accumule dans
|
||||
// geometryMicros_ depuis un thread : chaque tuile depose sa duree dans son
|
||||
@@ -173,21 +193,22 @@ void TerrainStreamer::meshBatch(const std::vector<uint32_t>& nodes) {
|
||||
|
||||
const auto worker = [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t k = begin; k < end; ++k) {
|
||||
const auto t0 = Clock::now();
|
||||
if (batchWrites_[k].vertices == nullptr) {
|
||||
continue; // reservation echouee, message deja depose
|
||||
}
|
||||
const auto t1 = Clock::now();
|
||||
try {
|
||||
batchMeshes_[k] = terrainNodeMeshData(heightmap_, quadtree_, nodes[k],
|
||||
false, params_.cacheTileWork);
|
||||
writeTerrainNodeVertices(heightmap_, quadtree_, nodes[k],
|
||||
batchWrites_[k].vertices, params_.cacheTileWork);
|
||||
} catch (const std::exception& e) {
|
||||
// Une exception ne doit JAMAIS traverser la frontiere d'un
|
||||
// std::thread : elle appellerait std::terminate. Elle est donc
|
||||
// capturee ici et rendue a l'appelant comme une donnee.
|
||||
batchErrors_[k] = e.what();
|
||||
batchMeshes_[k] = MeshData{};
|
||||
} catch (...) {
|
||||
batchErrors_[k] = "exception inconnue";
|
||||
batchMeshes_[k] = MeshData{};
|
||||
}
|
||||
perTileMicros[k] = microsBetween(t0, Clock::now());
|
||||
perTileMicros[k] = microsBetween(t1, Clock::now());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -226,60 +247,68 @@ void TerrainStreamer::meshBatch(const std::vector<uint32_t>& nodes) {
|
||||
for (uint64_t micros : perTileMicros) {
|
||||
geometryMicros_ += micros;
|
||||
}
|
||||
|
||||
// --- 3. Livraison, thread de rendu ---------------------------------------
|
||||
const auto t2 = Clock::now();
|
||||
for (std::size_t k = 0; k < nodes.size(); ++k) {
|
||||
const MeshHandle mesh = batchWrites_[k].mesh;
|
||||
if (!batchErrors_[k].empty()) {
|
||||
if (mesh != kInvalidMesh) {
|
||||
renderer_.removeMesh(mesh);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
renderer_.endTerrainMesh(mesh);
|
||||
batchMeshes_[k] = mesh;
|
||||
++builtNodes_;
|
||||
}
|
||||
uploadMicros_ += microsBetween(t2, Clock::now());
|
||||
}
|
||||
|
||||
MeshHandle TerrainStreamer::uploadNode(uint32_t nodeIndex, MeshData& data) {
|
||||
MeshHandle TerrainStreamer::buildNode(uint32_t nodeIndex) {
|
||||
// Chemin SEQUENTIEL : reserve, ecrit, livre une tuile. C'est le chemin du
|
||||
// sommet epingle (construit avant la premiere frame) et, depuis que le
|
||||
// defaut est meshThreads = 1, celui de la construction courante.
|
||||
//
|
||||
// PHASE 30 : plus aucun MeshData ici. Les sommets sont ecrits au format
|
||||
// compact directement dans la zone reservee - la memoire que le GPU lira
|
||||
// en memoire unifiee, un staging sinon. Le poste "televersement" ne compte
|
||||
// plus que la reservation et la livraison.
|
||||
const auto t0 = Clock::now();
|
||||
Renderer::TerrainMeshWrite write;
|
||||
try {
|
||||
const auto t1 = Clock::now();
|
||||
// Les indices sont poses ICI et non dans terrainNodeMeshData, pour que
|
||||
// les deux postes soient chronometres separement (voir buildProfile).
|
||||
data.indices = sharedIndices();
|
||||
const auto t2 = Clock::now();
|
||||
// log = false : plusieurs tuiles par frame, une ligne chacune rendrait la
|
||||
// sortie inexploitable (et couterait plus que l'upload).
|
||||
const MeshHandle mesh = renderer_.addMesh(data, false);
|
||||
const auto t3 = Clock::now();
|
||||
|
||||
++builtNodes_;
|
||||
indicesMicros_ += microsBetween(t1, t2);
|
||||
uploadMicros_ += microsBetween(t2, t3);
|
||||
return mesh;
|
||||
write = renderer_.beginTerrainMesh(
|
||||
(quadtree_.nodeCells() + 1) * (quadtree_.nodeCells() + 1), sharedIndexSet_);
|
||||
} catch (const std::exception& e) {
|
||||
// Une tuile qu'on ne sait pas construire ne doit pas arreter le jeu :
|
||||
// elle sera simplement absente, et le message dit laquelle. Le cas
|
||||
// realiste est un manque de memoire GPU, pas une donnee invalide.
|
||||
uploadMicros_ += microsBetween(t0, Clock::now());
|
||||
// Le cas realiste est un manque de memoire GPU, pas une donnee
|
||||
// invalide : la tuile sera simplement absente, et le message dit
|
||||
// laquelle.
|
||||
logWarn("Streaming terrain : tuile " + std::to_string(nodeIndex) +
|
||||
" non televersee (" + e.what() + ").");
|
||||
return kInvalidMesh;
|
||||
}
|
||||
}
|
||||
|
||||
MeshHandle TerrainStreamer::buildNode(uint32_t nodeIndex) {
|
||||
// Chemin SEQUENTIEL : maille une tuile puis la televerse, sans jamais garder
|
||||
// plus d'un MeshData en vie. C'est le chemin du sommet epingle (construit
|
||||
// avant la premiere frame) et, depuis que le defaut est meshThreads = 1,
|
||||
// celui de la construction courante.
|
||||
//
|
||||
// Ne pas passer par meshBatch ici n'est pas une duplication gratuite :
|
||||
// meshBatch dimensionne un vecteur de MeshData pour TOUT le lot, ce qui fait
|
||||
// vivre jusqu'a 53 tuiles simultanement (~15 Mo) la ou ce chemin-ci n'en
|
||||
// tient qu'une. Mesure : le pic memoire du processus montait de 5,6 Mo quand
|
||||
// tout passait par le lot. Le chemin par defaut retrouve ainsi exactement le
|
||||
// profil memoire d'avant la Phase 19.
|
||||
const auto t0 = Clock::now();
|
||||
const auto t1 = Clock::now();
|
||||
try {
|
||||
scratchMesh_ = terrainNodeMeshData(heightmap_, quadtree_, nodeIndex, false,
|
||||
params_.cacheTileWork);
|
||||
writeTerrainNodeVertices(heightmap_, quadtree_, nodeIndex, write.vertices,
|
||||
params_.cacheTileWork);
|
||||
} catch (const std::exception& e) {
|
||||
geometryMicros_ += microsBetween(t0, Clock::now());
|
||||
geometryMicros_ += microsBetween(t1, Clock::now());
|
||||
renderer_.removeMesh(write.mesh);
|
||||
logWarn("Streaming terrain : tuile " + std::to_string(nodeIndex) +
|
||||
" non maillee (" + e.what() + ").");
|
||||
return kInvalidMesh;
|
||||
}
|
||||
const uint64_t micros = microsBetween(t0, Clock::now());
|
||||
const auto t2 = Clock::now();
|
||||
renderer_.endTerrainMesh(write.mesh);
|
||||
const auto t3 = Clock::now();
|
||||
|
||||
const uint64_t micros = microsBetween(t1, t2);
|
||||
geometryMicros_ += micros;
|
||||
meshWallMicros_ += micros;
|
||||
return uploadNode(nodeIndex, scratchMesh_);
|
||||
uploadMicros_ += microsBetween(t0, t1) + microsBetween(t2, t3);
|
||||
++builtNodes_;
|
||||
return write.mesh;
|
||||
}
|
||||
|
||||
bool TerrainStreamer::evictOne() {
|
||||
@@ -354,11 +383,6 @@ void TerrainStreamer::appendDrawItems(const glm::vec3& cameraPosition,
|
||||
fallbackCount_ = 0;
|
||||
uncoveredCount_ = 0;
|
||||
|
||||
const std::size_t bytesPerNode =
|
||||
static_cast<std::size_t>(quadtree_.nodeCells() + 1) *
|
||||
(quadtree_.nodeCells() + 1) * sizeof(Vertex) +
|
||||
static_cast<std::size_t>(quadtree_.trianglesPerNode()) * 3 * sizeof(uint32_t);
|
||||
|
||||
const bool priming = (frameCounter_ <= params_.primingFrames);
|
||||
uint32_t uploadsLeft = priming ? std::numeric_limits<uint32_t>::max()
|
||||
: params_.maxUploadsPerFrame;
|
||||
@@ -402,14 +426,13 @@ void TerrainStreamer::appendDrawItems(const glm::vec3& cameraPosition,
|
||||
// --- 1b/1c. Maillage puis televersement ---------------------------------
|
||||
// Deux chemins, et le choix se fait sur la TAILLE DU LOT :
|
||||
//
|
||||
// - lot parallelisable : tout le lot est maille d'abord (meshBatch, aucun
|
||||
// appel Vulkan, plusieurs threads), puis televerse en sequence ;
|
||||
// - sinon : chaque tuile est maillee et televersee a la suite, sans jamais
|
||||
// garder plus d'un MeshData en vie. C'est le chemin par DEFAUT, et il
|
||||
// est identique a celui d'avant la Phase 19, cout memoire compris.
|
||||
// - lot parallelisable : tout le lot est reserve, puis ecrit (meshBatch,
|
||||
// aucun appel Vulkan pendant l'ecriture, plusieurs threads), puis livre ;
|
||||
// - sinon : chaque tuile est reservee, ecrite et livree a la suite. C'est
|
||||
// le chemin par DEFAUT.
|
||||
//
|
||||
// Dans les deux cas les addMesh ont lieu sur le thread de rendu, en
|
||||
// sequence, et dans l'ordre de selection - donc du plus proche au plus
|
||||
// Dans les deux cas les appels au Renderer ont lieu sur le thread de rendu,
|
||||
// en sequence, et dans l'ordre de selection - donc du plus proche au plus
|
||||
// lointain.
|
||||
|
||||
// Suivi du plus gros lot : il doit compter les DEUX chemins, sinon le bilan
|
||||
@@ -429,17 +452,19 @@ void TerrainStreamer::appendDrawItems(const glm::vec3& cameraPosition,
|
||||
" non maillee (" + batchErrors_[k] + ").");
|
||||
continue;
|
||||
}
|
||||
// Faire de la place AVANT de televerser, sinon le pic de residence
|
||||
// depasserait le plafond le temps d'un upload. (Le maillage, lui,
|
||||
// n'alloue rien sur le GPU : c'est bien l'upload qui doit etre couvert.)
|
||||
while (resident_.size() >= params_.maxResidentNodes) {
|
||||
if (!evictOne()) {
|
||||
break; // tout est utilise cette frame : on laisse deborder
|
||||
MeshHandle mesh = kInvalidMesh;
|
||||
if (parallel) {
|
||||
mesh = batchMeshes_[k]; // place deja faite par meshBatch
|
||||
} else {
|
||||
// Faire de la place AVANT de reserver, sinon le pic de residence
|
||||
// depasserait le plafond le temps d'une tuile.
|
||||
while (resident_.size() >= params_.maxResidentNodes) {
|
||||
if (!evictOne()) {
|
||||
break; // tout est utilise cette frame : on laisse deborder
|
||||
}
|
||||
}
|
||||
mesh = buildNode(nodeIndex);
|
||||
}
|
||||
|
||||
const MeshHandle mesh = parallel ? uploadNode(nodeIndex, batchMeshes_[k])
|
||||
: buildNode(nodeIndex);
|
||||
if (mesh == kInvalidMesh) {
|
||||
continue;
|
||||
}
|
||||
@@ -447,20 +472,13 @@ void TerrainStreamer::appendDrawItems(const glm::vec3& cameraPosition,
|
||||
|
||||
ResidentNode node;
|
||||
node.mesh = mesh;
|
||||
node.bytes = bytesPerNode;
|
||||
node.bytes = bytesPerNode_;
|
||||
node.lastUsedFrame = frameCounter_;
|
||||
resident_.emplace(nodeIndex, node);
|
||||
residentBytes_ += bytesPerNode;
|
||||
residentBytes_ += bytesPerNode_;
|
||||
--pendingCount_; // finalement servie dans la frame meme
|
||||
}
|
||||
|
||||
// Le lot ne doit pas garder ses maillages en vie jusqu'a la frame suivante :
|
||||
// ce sont ~287 Ko par tuile.
|
||||
if (parallel) {
|
||||
batchMeshes_.clear();
|
||||
batchMeshes_.shrink_to_fit();
|
||||
}
|
||||
|
||||
// --- 2. Choix des ancetres de repli (PHASE 12) --------------------------
|
||||
// Rien a faire dans le cas courant : en regime etabli toute la selection est
|
||||
// residente, l'ensemble reste vide et les passes suivantes ne coutent rien.
|
||||
@@ -489,6 +507,7 @@ void TerrainStreamer::appendDrawItems(const glm::vec3& cameraPosition,
|
||||
// --- 3. Emission ---------------------------------------------------------
|
||||
const bool hasFallback = !fallbackAncestors_.empty();
|
||||
|
||||
const int32_t vertsPerRow = static_cast<int32_t>(quadtree_.nodeCells() + 1);
|
||||
auto emit = [&](const TerrainQuadtree::SelectedNode& node, MeshHandle mesh) {
|
||||
DrawItem item;
|
||||
item.mesh = mesh;
|
||||
@@ -497,6 +516,11 @@ void TerrainStreamer::appendDrawItems(const glm::vec3& cameraPosition,
|
||||
item.model = glm::mat4(1.0f);
|
||||
item.material = Material::Terrain;
|
||||
item.params = glm::vec4(node.morphStart, node.morphEnd, 0.0f, 0.0f);
|
||||
// PHASE 30 : ou est la tuile dans la grille - terrain.vert en deduit la
|
||||
// position horizontale, la cible de morphing et l'UV de chaque sommet.
|
||||
const TerrainQuadtree::Node& grid = quadtree_.node(node.nodeIndex);
|
||||
item.grid = glm::ivec4(static_cast<int32_t>(grid.ix0), static_cast<int32_t>(grid.iz0),
|
||||
static_cast<int32_t>(grid.stride), vertsPerRow);
|
||||
out.push_back(item);
|
||||
++drawnCount_;
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "core/Frustum.hpp"
|
||||
#include "renderer/DrawItem.hpp"
|
||||
#include "renderer/MeshData.hpp"
|
||||
#include "renderer/Renderer.hpp" // Renderer::TerrainMeshWrite
|
||||
#include "world/TerrainQuadtree.hpp"
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
@@ -16,7 +17,6 @@
|
||||
namespace vercora {
|
||||
|
||||
class Heightmap;
|
||||
class Renderer;
|
||||
|
||||
// Fait le lien entre le quadtree (qui decide QUOI dessiner) et le Renderer (qui
|
||||
// possede les geometries GPU) : cache de tuiles residentes, construction a la
|
||||
@@ -36,10 +36,12 @@ class Renderer;
|
||||
// recopier). Il est passe de 4 a 64 pour cette raison. Les tuiles au-dela du
|
||||
// budget sont servies dans les frames suivantes, les plus PROCHES d'abord.
|
||||
//
|
||||
// 2. PLAFOND DE RESIDENCE (maxResidentNodes). Chaque tuile consomme deux
|
||||
// allocations Vulkan (vertex + index), et vkAllocateMemory est plafonne par
|
||||
// maxMemoryAllocationCount (typiquement 4096). Le plafond garde une marge
|
||||
// confortable en plus de borner la RAM.
|
||||
// 2. PLAFOND DE RESIDENCE (maxResidentNodes). Il bornait a l'origine deux
|
||||
// choses : la memoire, et le nombre d'allocations Vulkan (deux par tuile,
|
||||
// plafonnees par maxMemoryAllocationCount, typiquement 4096). PHASE 30 :
|
||||
// les tuiles vivent dans les blocs partages du GpuBufferPool, une tuile ne
|
||||
// coute plus d'allocation - le plafond ne borne plus que la memoire, a
|
||||
// 68 Ko par tuile au lieu de 385.
|
||||
//
|
||||
// 3. EVICTION LRU, jamais sur une tuile utilisee dans la frame courante, ni
|
||||
// sur une tuile du sommet epingle (point 4).
|
||||
@@ -87,8 +89,9 @@ public:
|
||||
// staging vivant simultanement (64 tuiles ~ 25 Mo).
|
||||
uint32_t maxUploadsPerFrame = 64;
|
||||
|
||||
// Plafond de tuiles gardees sur le GPU. 512 tuiles = 1024 allocations
|
||||
// Vulkan et ~200 Mo au format de sommet de la Phase 10.
|
||||
// Plafond de tuiles gardees sur le GPU. 512 tuiles = ~200 Mo au format
|
||||
// de sommet de la Phase 10, ~35 Mo depuis la Phase 30 (sommet de 16
|
||||
// octets, topologie partagee), en une dizaine de blocs de 4 Mo.
|
||||
uint32_t maxResidentNodes = 512;
|
||||
|
||||
// Frames pendant lesquelles le budget par frame est LEVE, au demarrage :
|
||||
@@ -245,33 +248,34 @@ private:
|
||||
bool pinned = false;
|
||||
};
|
||||
|
||||
// PHASE 19. Maille les tuiles `nodes` dans `batchMeshes_`, en parallele
|
||||
// au-dela de deux tuiles. AUCUN appel Vulkan : c'est toute la raison pour
|
||||
// laquelle cette etape peut quitter le thread de rendu sans rien changer a
|
||||
// la synchronisation du moteur.
|
||||
// PHASE 19. Construit les tuiles `nodes` dans `batchMeshes_`, le maillage
|
||||
// en parallele au-dela de deux tuiles. PHASE 30 : les emplacements sont
|
||||
// reserves d'abord sur le thread de rendu (Renderer::beginTerrainMesh), les
|
||||
// threads y ECRIVENT les sommets - sans le moindre appel Vulkan, c'est
|
||||
// toute la raison pour laquelle cette etape peut quitter le thread de
|
||||
// rendu - puis le thread de rendu les livre (endTerrainMesh).
|
||||
//
|
||||
// Chaque thread ecrit dans des ELEMENTS DISJOINTS de vecteurs deja
|
||||
// dimensionnes : il n'y a ni verrou, ni file, ni compteur partage - donc
|
||||
// aucun etat sur lequel une course serait possible. Une tuile qui echoue
|
||||
// depose son message dans `batchErrors_[k]`, jamais dans un journal (les
|
||||
// fonctions de journalisation ne sont pas prevues pour plusieurs threads) :
|
||||
// c'est l'appelant qui journalise, apres la jonction.
|
||||
// Chaque thread ecrit dans des ZONES DISJOINTES deja reservees : il n'y a
|
||||
// ni verrou, ni file, ni compteur partage - donc aucun etat sur lequel une
|
||||
// course serait possible. Une tuile qui echoue depose son message dans
|
||||
// `batchErrors_[k]`, jamais dans un journal (les fonctions de
|
||||
// journalisation ne sont pas prevues pour plusieurs threads) : c'est
|
||||
// l'appelant qui journalise, apres la jonction.
|
||||
void meshBatch(const std::vector<uint32_t>& nodes);
|
||||
|
||||
// true si un lot de `count` tuiles vaut la peine de partir sur des threads.
|
||||
bool wantsParallel(std::size_t count) const;
|
||||
|
||||
// Pose la topologie commune puis televerse. SEQUENTIEL, thread de rendu.
|
||||
// Renvoie kInvalidMesh en cas d'echec (la tuile est alors simplement
|
||||
// sautee : un trou d'une frame vaut mieux qu'un arret du jeu).
|
||||
MeshHandle uploadNode(uint32_t nodeIndex, MeshData& data);
|
||||
|
||||
// Maille ET televerse une tuile, en sequence, sans jamais garder plus d'un
|
||||
// MeshData en vie. Chemin par DEFAUT depuis que meshThreads vaut 1, et
|
||||
// chemin du sommet epingle.
|
||||
// PHASE 30. Construit une tuile : reserve sa place dans le pool de
|
||||
// geometrie (Renderer::beginTerrainMesh), y ECRIT ses sommets au format
|
||||
// compact, la livre. SEQUENTIEL, thread de rendu. Chemin par DEFAUT depuis
|
||||
// que meshThreads vaut 1, et chemin du sommet epingle. Renvoie kInvalidMesh
|
||||
// en cas d'echec (la tuile est alors simplement sautee : un trou d'une
|
||||
// frame vaut mieux qu'un arret du jeu).
|
||||
MeshHandle buildNode(uint32_t nodeIndex);
|
||||
|
||||
// PHASE 18 : la topologie d'une tuile, commune a toutes.
|
||||
// PHASE 18 : la topologie d'une tuile, commune a toutes. PHASE 30 : elle
|
||||
// n'est plus recopiee par tuile mais televersee UNE fois (sharedIndexSet_).
|
||||
const std::vector<uint32_t>& sharedIndices() const;
|
||||
|
||||
// Libere la tuile la moins recemment utilisee qui n'a pas servi dans la
|
||||
@@ -341,12 +345,16 @@ private:
|
||||
// locales, uniquement pour garder leur capacite d'une frame a l'autre -
|
||||
// meme raison que selection_ et fallbackAncestors_.
|
||||
std::vector<uint32_t> batchNodes_;
|
||||
std::vector<MeshData> batchMeshes_; // rempli seulement sur le chemin parallele
|
||||
std::vector<std::string> batchErrors_;
|
||||
// PHASE 30 : emplacements reserves par le chemin parallele, ou les threads
|
||||
// ecrivent directement (plus aucun MeshData de 287 Ko par tuile du lot).
|
||||
std::vector<Renderer::TerrainMeshWrite> batchWrites_;
|
||||
std::vector<MeshHandle> batchMeshes_;
|
||||
|
||||
// Maillage de travail du chemin sequentiel. Membre pour garder sa capacite
|
||||
// d'une tuile a l'autre ; il n'en vit jamais qu'un.
|
||||
MeshData scratchMesh_;
|
||||
// PHASE 30 : la topologie commune, televersee une fois (Renderer::
|
||||
// addSharedIndices), et la taille GPU d'une tuile (ses sommets seuls).
|
||||
uint32_t sharedIndexSet_ = 0;
|
||||
std::size_t bytesPerNode_ = 0;
|
||||
|
||||
// PHASE 19 : temps de MUR de l'etape de maillage, a comparer a
|
||||
// geometryMicros_ qui reste, lui, la somme du travail par tuile. Les deux
|
||||
|
||||
@@ -85,6 +85,14 @@ struct UniformBufferObject {
|
||||
alignas(16) glm::vec4 precip{0.0f, 0.0f, 0.0f, 0.0f};
|
||||
alignas(16) glm::vec4 fall{0.0f, -6.5f, 0.0f, 0.0f};
|
||||
alignas(16) glm::vec4 detail{0.0f, 0.0f, 1.0f, 1.0f};
|
||||
|
||||
// PHASE 30. Offset 256. Grille de la heightmap, pour que terrain.vert
|
||||
// recalcule la position horizontale et l'UV d'un sommet a partir de son
|
||||
// indice (voir renderer/GpuVertex.hpp, TerrainVertex) :
|
||||
// x = origine (Heightmap::worldCoord(0)), y = pas en metres,
|
||||
// z = nombre de CELLULES par cote (resolution - 1), w = reserve.
|
||||
// Constant sur toute la partie ; seuls les shaders du terrain le declarent.
|
||||
alignas(16) glm::vec4 terrainGrid{0.0f, 1.0f, 1.0f, 0.0f};
|
||||
};
|
||||
|
||||
} // namespace vercora
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "renderer/GpuVertex.hpp"
|
||||
#include "renderer/InstanceData.hpp"
|
||||
#include "renderer/Vertex.hpp"
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
@@ -24,60 +24,82 @@ namespace vercora {
|
||||
// Consequence concrete : la logique de jeu se compile et se teste sans GPU (voir
|
||||
// tests/logic_tests.cpp), y compris sur une machine ou le SDK n'est pas installe.
|
||||
|
||||
// Un seul binding, sommets entrelaces.
|
||||
inline VkVertexInputBindingDescription vertexBindingDescription() {
|
||||
// PHASE 30 : DEUX formats de sommet, un par famille de shaders (voir
|
||||
// renderer/GpuVertex.hpp) - le format de travail CPU `Vertex` n'est plus
|
||||
// televerse tel quel. Un seul binding entrelace dans les deux cas.
|
||||
|
||||
// --- Objets et vegetation : ObjectVertex, 44 octets -------------------------
|
||||
inline VkVertexInputBindingDescription objectBindingDescription() {
|
||||
VkVertexInputBindingDescription binding{};
|
||||
binding.binding = 0;
|
||||
binding.stride = sizeof(Vertex);
|
||||
binding.stride = sizeof(ObjectVertex);
|
||||
binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
|
||||
return binding;
|
||||
}
|
||||
|
||||
// Mapping des attributs vers les location(...) du vertex shader.
|
||||
//
|
||||
// Six attributs depuis la Phase 10 : les deux derniers portent la cible de
|
||||
// geomorphing du terrain (voir Vertex.hpp) et ne sont decrits qu'aux pipelines
|
||||
// dont le vertex shader les lit reellement.
|
||||
// `includeMorph` a false pour un vertex shader qui ne lit pas les locations 4/5
|
||||
// (cube.vert) : les decrire quand meme declencherait un avertissement de
|
||||
// validation. Voir ShaderSet::usesMorphAttributes.
|
||||
inline std::array<VkVertexInputAttributeDescription, 6> vertexAttributeDescriptions() {
|
||||
std::array<VkVertexInputAttributeDescription, 6> attrs{};
|
||||
// Locations 0 a 3 : position, couleur, normale, UV - les memes que depuis la
|
||||
// Phase 3, seul le stride a change (les 24 octets de morphing, qu'aucun de ces
|
||||
// shaders ne lisait, ne sont plus dans le buffer).
|
||||
inline std::array<VkVertexInputAttributeDescription, 4> objectAttributeDescriptions() {
|
||||
std::array<VkVertexInputAttributeDescription, 4> attrs{};
|
||||
|
||||
attrs[0].binding = 0;
|
||||
attrs[0].location = 0;
|
||||
attrs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
|
||||
attrs[0].offset = offsetof(Vertex, pos);
|
||||
attrs[0].offset = offsetof(ObjectVertex, pos);
|
||||
|
||||
attrs[1].binding = 0;
|
||||
attrs[1].location = 1;
|
||||
attrs[1].format = VK_FORMAT_R32G32B32_SFLOAT;
|
||||
attrs[1].offset = offsetof(Vertex, color);
|
||||
attrs[1].offset = offsetof(ObjectVertex, color);
|
||||
|
||||
attrs[2].binding = 0;
|
||||
attrs[2].location = 2;
|
||||
attrs[2].format = VK_FORMAT_R32G32B32_SFLOAT;
|
||||
attrs[2].offset = offsetof(Vertex, normal);
|
||||
attrs[2].offset = offsetof(ObjectVertex, normal);
|
||||
|
||||
// Deux composantes seulement -> format R32G32.
|
||||
attrs[3].binding = 0;
|
||||
attrs[3].location = 3;
|
||||
attrs[3].format = VK_FORMAT_R32G32_SFLOAT;
|
||||
attrs[3].offset = offsetof(Vertex, uv);
|
||||
attrs[3].offset = offsetof(ObjectVertex, uv);
|
||||
|
||||
// Position et normale du meme sommet dans la grille du niveau de detail
|
||||
// SUPERIEUR (plus grossier). Nulles sur toute geometrie qui n'est pas une
|
||||
// tuile de quadtree : sans effet, le shader ne morphe que si la bande de
|
||||
// morphing poussee par le DrawItem est non vide.
|
||||
attrs[4].binding = 0;
|
||||
attrs[4].location = 4;
|
||||
attrs[4].format = VK_FORMAT_R32G32B32_SFLOAT;
|
||||
attrs[4].offset = offsetof(Vertex, morphPos);
|
||||
return attrs;
|
||||
}
|
||||
|
||||
attrs[5].binding = 0;
|
||||
attrs[5].location = 5;
|
||||
attrs[5].format = VK_FORMAT_R32G32B32_SFLOAT;
|
||||
attrs[5].offset = offsetof(Vertex, morphNormal);
|
||||
// --- Terrain : TerrainVertex, 16 octets --------------------------------------
|
||||
inline VkVertexInputBindingDescription terrainBindingDescription() {
|
||||
VkVertexInputBindingDescription binding{};
|
||||
binding.binding = 0;
|
||||
binding.stride = sizeof(TerrainVertex);
|
||||
binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
|
||||
return binding;
|
||||
}
|
||||
|
||||
// Deux altitudes en flottant, deux normales en snorm16 (x et z, y reconstruit
|
||||
// par terrain.vert). Tout le reste se deduit de gl_VertexIndex.
|
||||
inline std::array<VkVertexInputAttributeDescription, 4> terrainAttributeDescriptions() {
|
||||
std::array<VkVertexInputAttributeDescription, 4> attrs{};
|
||||
|
||||
attrs[0].binding = 0;
|
||||
attrs[0].location = 0;
|
||||
attrs[0].format = VK_FORMAT_R32_SFLOAT;
|
||||
attrs[0].offset = offsetof(TerrainVertex, height);
|
||||
|
||||
attrs[1].binding = 0;
|
||||
attrs[1].location = 1;
|
||||
attrs[1].format = VK_FORMAT_R32_SFLOAT;
|
||||
attrs[1].offset = offsetof(TerrainVertex, morphHeight);
|
||||
|
||||
attrs[2].binding = 0;
|
||||
attrs[2].location = 2;
|
||||
attrs[2].format = VK_FORMAT_R16G16_SNORM;
|
||||
attrs[2].offset = offsetof(TerrainVertex, normal);
|
||||
|
||||
attrs[3].binding = 0;
|
||||
attrs[3].location = 3;
|
||||
attrs[3].format = VK_FORMAT_R16G16_SNORM;
|
||||
attrs[3].offset = offsetof(TerrainVertex, morphNormal);
|
||||
|
||||
return attrs;
|
||||
}
|
||||
@@ -98,7 +120,7 @@ inline VkVertexInputBindingDescription instanceBindingDescription() {
|
||||
return binding;
|
||||
}
|
||||
|
||||
// Locations 6 a 8 : les locations 0 a 5 appartiennent au sommet (voir plus haut),
|
||||
// Locations 6 a 8 : les locations basses appartiennent au sommet (voir plus haut),
|
||||
// et un pipeline instancie decrit les deux flux dans le meme espace de numeros.
|
||||
// Les trois flottants scalaires (scale, yaw, variation, fade) sont regroupes en
|
||||
// deux attributs plutot qu'en quatre : moins d'attributs a decrire, et le shader
|
||||
|
||||
@@ -33,10 +33,12 @@ public:
|
||||
virtual ~BufferUploader() = default;
|
||||
|
||||
// Enregistre une copie de `staging` (integralite de sa taille) vers
|
||||
// `destination`. Prend possession de `staging`, qui sera detruit quand la
|
||||
// frame ayant execute la copie sera terminee.
|
||||
// `destination`, a partir de l'octet `destinationOffset` (PHASE 30 : la
|
||||
// destination est une PLAGE d'un bloc partage, voir GpuBufferPool). Prend
|
||||
// possession de `staging`, qui sera detruit quand la frame ayant execute la
|
||||
// copie sera terminee.
|
||||
virtual void enqueueCopy(std::unique_ptr<VulkanBuffer> staging,
|
||||
VkBuffer destination) = 0;
|
||||
VkBuffer destination, VkDeviceSize destinationOffset) = 0;
|
||||
};
|
||||
|
||||
// Buffer Vulkan reutilisable : creation, allocation memoire, bind, map,
|
||||
|
||||
@@ -235,6 +235,7 @@ void VulkanContext::pickPhysicalDevice() {
|
||||
VkPhysicalDeviceProperties props{};
|
||||
vkGetPhysicalDeviceProperties(physicalDevice_, &props);
|
||||
logInfo(std::string("GPU selectionne : ") + props.deviceName);
|
||||
deviceType_ = props.deviceType;
|
||||
|
||||
// PHASE 30 : proprietes memoire lues UNE fois (voir findMemoryType), et
|
||||
// detection de la memoire unifiee.
|
||||
|
||||
@@ -133,6 +133,17 @@ public:
|
||||
// Faux sur un GPU discret classique (hors BAR redimensionnable).
|
||||
bool unifiedMemory() const { return unifiedMemory_; }
|
||||
|
||||
// PHASE 30. true si la geometrie doit etre ecrite DIRECTEMENT dans sa
|
||||
// memoire device-local mappee plutot que par staging : memoire unifiee ET
|
||||
// GPU integre (ou logiciel). Un GPU discret peut aussi exposer une memoire
|
||||
// device-local mappable (BAR, 256 Mo sans ReBAR) ; elle est trop petite et
|
||||
// trop precieuse pour y loger le terrain, il garde donc le staging.
|
||||
bool preferDirectGeometryWrites() const {
|
||||
return unifiedMemory_ &&
|
||||
(deviceType_ == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU ||
|
||||
deviceType_ == VK_PHYSICAL_DEVICE_TYPE_CPU);
|
||||
}
|
||||
|
||||
private:
|
||||
void createInstance();
|
||||
void setupDebugMessenger();
|
||||
@@ -160,6 +171,7 @@ private:
|
||||
|
||||
bool anisotropyEnabled_ = false;
|
||||
bool unifiedMemory_ = false;
|
||||
VkPhysicalDeviceType deviceType_ = VK_PHYSICAL_DEVICE_TYPE_OTHER;
|
||||
|
||||
// Proprietes memoire du GPU, lues une fois : findMemoryType les
|
||||
// interrogeait a CHAQUE allocation (deux par tuile de terrain).
|
||||
|
||||
@@ -37,6 +37,8 @@
|
||||
#include "editor/PlacedObject.hpp"
|
||||
#include "editor/SceneFile.hpp"
|
||||
#include "renderer/DrawItem.hpp"
|
||||
#include "renderer/GpuVertex.hpp"
|
||||
#include "renderer/RangeAllocator.hpp"
|
||||
#include "renderer/TerrainMesh.hpp"
|
||||
#include "renderer/TerrainNodeMesh.hpp"
|
||||
#include "world/AnimalMesh.hpp"
|
||||
@@ -10098,6 +10100,210 @@ void testBushPlacement() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PHASE 30 : formats GPU compacts et sous-allocation de la geometrie
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ce que le GPU lit n'est plus le format de travail `Vertex` (68 octets) mais
|
||||
// ObjectVertex (44) et TerrainVertex (16), et toute la geometrie vit dans des
|
||||
// plages de blocs partages. Rien de cela ne se VOIT si c'est faux d'un octet :
|
||||
// un decalage d'allocateur ecrase la geometrie d'un voisin, une position
|
||||
// recalculee differemment fait trembler les jointures de tuiles. D'ou ces
|
||||
// verifications, faites sans GPU.
|
||||
void testGpuFormatsPhase30() {
|
||||
section("Phase 30 : formats GPU compacts et pool de geometrie");
|
||||
|
||||
check(sizeof(ObjectVertex) == 44 && sizeof(TerrainVertex) == 16 &&
|
||||
sizeof(DrawItemPush) == 96,
|
||||
"Phase 30 : 44 / 16 octets par sommet, 96 octets de push constants");
|
||||
|
||||
// --- ObjectVertex : conversion EXACTE -----------------------------------
|
||||
{
|
||||
Vertex v{};
|
||||
v.pos = { 1.25f, -3.5f, 1234.567f };
|
||||
v.color = { 0.42f, 0.13f, 0.99f };
|
||||
v.normal = { 0.1f, 0.9f, -0.2f };
|
||||
v.uv = { 0.333f, 0.777f };
|
||||
v.morphPos = { 9.0f, 9.0f, 9.0f };
|
||||
const ObjectVertex o = toObjectVertex(v);
|
||||
check(o.pos == v.pos && o.color == v.color && o.normal == v.normal && o.uv == v.uv,
|
||||
"ObjectVertex : position, couleur, normale et UV recopiees au bit pres");
|
||||
}
|
||||
|
||||
// --- snorm16 : la convention de VK_FORMAT_R16_SNORM ---------------------
|
||||
{
|
||||
float worst = 0.0f;
|
||||
for (int k = -2000; k <= 2000; ++k) {
|
||||
const float value = static_cast<float>(k) / 2000.0f;
|
||||
worst = std::max(worst, std::abs(unpackSnorm16(packSnorm16(value)) - value));
|
||||
}
|
||||
check(worst <= 0.5f / 32767.0f + 1e-7f,
|
||||
"snorm16 : erreur d'aller-retour d'au plus un demi-pas (1,5e-5)");
|
||||
check(packSnorm16(1.0f) == 32767 && packSnorm16(-1.0f) == -32767 &&
|
||||
packSnorm16(7.0f) == 32767 && packSnorm16(-7.0f) == -32767 &&
|
||||
unpackSnorm16(-32768) == -1.0f,
|
||||
"snorm16 : bornes et ecretage");
|
||||
|
||||
// Normales de champ de hauteur, du plat a la paroi (pente 20) : la
|
||||
// reconstruction de y depuis x et z quantifies reste a 1e-3 pres
|
||||
// (et a 1e-4 pres jusqu'a une pente de 5, soit 79 degres).
|
||||
float worstNormal = 0.0f;
|
||||
float worstNormalModerate = 0.0f;
|
||||
for (int a = 0; a < 64; ++a) {
|
||||
for (int b = 0; b < 16; ++b) {
|
||||
const float slope = 20.0f * static_cast<float>(b) / 15.0f;
|
||||
const float angle = 6.2831853f * static_cast<float>(a) / 64.0f;
|
||||
const glm::vec3 n = glm::normalize(
|
||||
glm::vec3(-slope * std::cos(angle), 1.0f, -slope * std::sin(angle)));
|
||||
const int16_t packed[2] = { packSnorm16(n.x), packSnorm16(n.z) };
|
||||
const float error = glm::length(unpackTerrainNormal(packed) - n);
|
||||
worstNormal = std::max(worstNormal, error);
|
||||
if (slope <= 5.0f) {
|
||||
worstNormalModerate = std::max(worstNormalModerate, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
check(worstNormal < 1e-3f && worstNormalModerate < 1e-4f,
|
||||
"TerrainVertex : normale reconstruite a 1e-4 pres jusqu'a 79 degres");
|
||||
}
|
||||
|
||||
// --- Tuiles : le format GPU est le format de reference, compacte --------
|
||||
// writeTerrainNodeVertices (chemin du streamer) doit rendre EXACTEMENT
|
||||
// toTerrainVertex(terrainNodeMeshData) pour CHAQUE noeud, grilles paire et
|
||||
// impaire, avec et sans la grille du parent mise en cache.
|
||||
{
|
||||
Heightmap::Params even;
|
||||
even.resolution = 513;
|
||||
even.worldSize = 512.0f;
|
||||
even.seed = 3030u;
|
||||
Heightmap::Params odd;
|
||||
odd.resolution = 128;
|
||||
odd.worldSize = 127.0f;
|
||||
odd.seed = 3031u;
|
||||
TerrainQuadtree::Params qparams;
|
||||
qparams.nodeCells = 64;
|
||||
|
||||
bool identical = true;
|
||||
bool positionsExact = true;
|
||||
bool uvExact = true;
|
||||
uint32_t nodesChecked = 0;
|
||||
for (const Heightmap::Params& hp : { even, odd }) {
|
||||
const Heightmap heightmap(hp);
|
||||
const TerrainQuadtree quadtree(heightmap, qparams);
|
||||
const uint32_t verts = qparams.nodeCells + 1;
|
||||
const uint32_t cells = heightmap.resolution() - 1;
|
||||
const float origin = heightmap.worldCoord(0);
|
||||
std::vector<TerrainVertex> written(static_cast<std::size_t>(verts) * verts);
|
||||
for (uint32_t index = 0; index < quadtree.nodeCount(); ++index) {
|
||||
for (const bool cached : { true, false }) {
|
||||
const MeshData reference =
|
||||
terrainNodeMeshData(heightmap, quadtree, index, false, cached);
|
||||
writeTerrainNodeVertices(heightmap, quadtree, index, written.data(), cached);
|
||||
for (std::size_t v = 0; v < written.size() && identical; ++v) {
|
||||
const TerrainVertex expected = toTerrainVertex(reference.vertices[v]);
|
||||
identical = std::memcmp(&expected, &written[v], sizeof(TerrainVertex)) == 0;
|
||||
}
|
||||
}
|
||||
// Ce que terrain.vert recalcule a partir de gl_VertexIndex et de
|
||||
// DrawItem::grid : memes indices ecretes, memes operations.
|
||||
const TerrainQuadtree::Node& node = quadtree.node(index);
|
||||
const MeshData reference = terrainNodeMeshData(heightmap, quadtree, index, false);
|
||||
for (uint32_t v = 0; v < verts * verts; ++v) {
|
||||
const uint32_t i = v % verts;
|
||||
const uint32_t j = v / verts;
|
||||
const uint32_t gx = std::min(node.ix0 + i * node.stride, cells);
|
||||
const uint32_t gz = std::min(node.iz0 + j * node.stride, cells);
|
||||
const uint32_t mx = std::min(node.ix0 + (i & ~1u) * node.stride, cells);
|
||||
const uint32_t mz = std::min(node.iz0 + (j & ~1u) * node.stride, cells);
|
||||
const Vertex& r = reference.vertices[v];
|
||||
positionsExact = positionsExact &&
|
||||
terrainGridCoord(origin, heightmap.spacing(), gx) == r.pos.x &&
|
||||
terrainGridCoord(origin, heightmap.spacing(), gz) == r.pos.z &&
|
||||
terrainGridCoord(origin, heightmap.spacing(), mx) == r.morphPos.x &&
|
||||
terrainGridCoord(origin, heightmap.spacing(), mz) == r.morphPos.z;
|
||||
uvExact = uvExact &&
|
||||
static_cast<float>(gx) / static_cast<float>(cells) == r.uv.x &&
|
||||
static_cast<float>(gz) / static_cast<float>(cells) == r.uv.y;
|
||||
}
|
||||
++nodesChecked;
|
||||
}
|
||||
}
|
||||
check(nodesChecked > 80, "Tuiles : toutes les tuiles des deux grilles verifiees");
|
||||
check(identical,
|
||||
"Tuiles : writeTerrainNodeVertices == toTerrainVertex(reference), au bit pres");
|
||||
check(positionsExact,
|
||||
"Tuiles : x/z et cible de morphing recalcules depuis l'indice, au bit pres");
|
||||
check(uvExact, "Tuiles : UV recalcule depuis l'indice de grille, au bit pres (CPU)");
|
||||
|
||||
const std::vector<uint32_t> topology = terrainNodeIndices(qparams.nodeCells);
|
||||
check(*std::max_element(topology.begin(), topology.end()) <= 0xFFFFu,
|
||||
"Tuiles : la topologie partagee tient en uint16");
|
||||
}
|
||||
|
||||
// --- Terrain d'un seul bloc (--no-lod) ------------------------------------
|
||||
{
|
||||
Heightmap::Params hp;
|
||||
hp.resolution = 97;
|
||||
hp.worldSize = 96.0f;
|
||||
hp.seed = 3032u;
|
||||
const Heightmap heightmap(hp);
|
||||
const MeshData reference = terrainMeshData(heightmap);
|
||||
const TerrainGpuMesh gpu = terrainGpuMeshData(heightmap);
|
||||
bool same = gpu.vertices.size() == reference.vertices.size() &&
|
||||
gpu.indices == reference.indices;
|
||||
for (std::size_t v = 0; v < gpu.vertices.size() && same; ++v) {
|
||||
TerrainVertex expected = toTerrainVertex(reference.vertices[v]);
|
||||
// Sans geomorphing, la cible est le sommet lui-meme (elle valait
|
||||
// zero dans le format de 68 octets, et n'etait jamais lue).
|
||||
expected.morphHeight = expected.height;
|
||||
expected.morphNormal[0] = expected.normal[0];
|
||||
expected.morphNormal[1] = expected.normal[1];
|
||||
same = std::memcmp(&expected, &gpu.vertices[v], sizeof(TerrainVertex)) == 0;
|
||||
}
|
||||
check(same, "Bloc unique : terrainGpuMeshData == reference compactee, memes indices");
|
||||
}
|
||||
|
||||
// --- RangeAllocator : la logique du pool, sans GPU ----------------------
|
||||
{
|
||||
RangeAllocator block(1 << 20);
|
||||
struct Taken { uint64_t offset; uint64_t size; };
|
||||
std::vector<Taken> taken;
|
||||
bool aligned = true;
|
||||
for (uint64_t k = 0; k < 40; ++k) {
|
||||
const uint64_t size = 1000 + 777 * (k % 7);
|
||||
const uint64_t offset = block.allocate(size, 256);
|
||||
if (offset == RangeAllocator::kInvalid) { aligned = false; break; }
|
||||
aligned = aligned && (offset % 256 == 0);
|
||||
taken.push_back({ offset, size });
|
||||
}
|
||||
bool disjoint = true;
|
||||
for (std::size_t a = 0; a < taken.size(); ++a) {
|
||||
for (std::size_t b = a + 1; b < taken.size(); ++b) {
|
||||
disjoint = disjoint && (taken[a].offset + taken[a].size <= taken[b].offset ||
|
||||
taken[b].offset + taken[b].size <= taken[a].offset);
|
||||
}
|
||||
}
|
||||
check(aligned && taken.size() == 40, "RangeAllocator : 40 plages alignees sur 256");
|
||||
check(disjoint, "RangeAllocator : aucune plage n'en chevauche une autre");
|
||||
|
||||
// Un trou laisse par une plage liberee est reutilise par une demande de
|
||||
// meme taille (le cas des tuiles, toutes de la meme taille).
|
||||
const Taken hole = taken[10];
|
||||
block.release(hole.offset, hole.size);
|
||||
check(block.allocate(hole.size, 256) == hole.offset,
|
||||
"RangeAllocator : un trou est reutilise par une demande de meme taille");
|
||||
|
||||
for (const Taken& t : taken) {
|
||||
block.release(t.offset, t.size);
|
||||
}
|
||||
check(block.empty() && block.freeSpanCount() == 1 &&
|
||||
block.largestFree() == block.capacity(),
|
||||
"RangeAllocator : tout liberer refusionne le bloc en une seule plage");
|
||||
check(block.allocate(block.capacity() + 1, 256) == RangeAllocator::kInvalid &&
|
||||
block.allocate(16, 3) == RangeAllocator::kInvalid,
|
||||
"RangeAllocator : demande trop grande ou alignement invalide refuses");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::printf("=== Tests logiques Vercora (headless, sans Vulkan) ===\n");
|
||||
|
||||
@@ -10118,6 +10324,7 @@ int main() {
|
||||
testGrassMesh();
|
||||
testGrassPhase18();
|
||||
testTileMeshingIsThreadSafe();
|
||||
testGpuFormatsPhase30();
|
||||
testVegetationPlacement();
|
||||
testGrassPlacement();
|
||||
testInstanceLayout();
|
||||
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur