15#include <SDL2/SDL_vulkan.h>
33#include "common/config.h"
37#include "zeroerr/assert.h"
42#include <assimp/mesh.h>
43#include <assimp/matrix3x3.h>
44#include <assimp/matrix4x4.h>
45#include <assimp/vector3.h>
46#include <glm/gtc/matrix_transform.hpp>
56 if (!initialized)
throw Exception(
"newMeshFromAssimp: graphics not initialized");
57 if (
mesh.mNumVertices == 0 ||
mesh.mNumFaces == 0)
58 throw Exception(
"newMeshFromAssimp: empty mesh");
60 std::vector<MeshVertex>
verts;
62 std::vector<float> basePos;
63 std::vector<float> baseNrm;
64 std::vector<float> baseUv;
65 if (
mesh.mNumAnimMeshes > 0) {
66 basePos.reserve(
mesh.mNumVertices * 3);
67 baseNrm.reserve(
mesh.mNumVertices * 3);
68 baseUv.reserve(
mesh.mNumVertices * 2);
70 for (
unsigned i = 0; i <
mesh.mNumVertices; ++i) {
73 if (
mesh.HasNormals())
74 v.normal = {
mesh.mNormals[i].x,
mesh.mNormals[i].y,
mesh.mNormals[i].z};
76 v.normal = {0.f, 1.f, 0.f};
77 if (
mesh.HasTangentsAndBitangents()) {
78 const auto &tangent =
mesh.mTangents[i];
79 const auto &bitangent =
mesh.mBitangents[i];
80 const glm::vec3
t(tangent.x, tangent.y, tangent.z);
81 const glm::vec3
b(bitangent.x, bitangent.y, bitangent.z);
82 v.tangent = glm::vec4(
t, glm::dot(glm::cross(
v.normal,
t),
b) < 0.f ? -1.f : 1.f);
84 if (
mesh.HasTextureCoords(0))
85 v.uv = {
mesh.mTextureCoords[0][i].x,
mesh.mTextureCoords[0][i].y};
89 if (
mesh.mNumAnimMeshes > 0) {
90 basePos.push_back(
v.pos.x);
91 basePos.push_back(
v.pos.y);
92 basePos.push_back(
v.pos.z);
93 baseNrm.push_back(
v.normal.x);
94 baseNrm.push_back(
v.normal.y);
95 baseNrm.push_back(
v.normal.z);
96 baseUv.push_back(
v.uv.x);
97 baseUv.push_back(
v.uv.y);
103 for (
unsigned f = 0;
f <
mesh.mNumFaces; ++
f) {
104 const aiFace &face =
mesh.mFaces[
f];
105 if (face.mNumIndices != 3)
continue;
106 indices.push_back(face.mIndices[0]);
107 indices.push_back(face.mIndices[1]);
108 indices.push_back(face.mIndices[2]);
110 if (
indices.empty())
throw Exception(
"newMeshFromAssimp: no triangle faces");
112 std::unique_ptr<GpuMesh>
gpu;
113 if (
mesh.mNumVertices <= 65535u) {
114 std::vector<uint16_t> idx16;
116 for (uint32_t i :
indices) idx16.push_back(uint16_t(i));
125 if (
mesh.mNumAnimMeshes > 0) {
126 handle->initMorphBase(
int(
mesh.mNumVertices), basePos.data(), baseNrm.data(), baseUv.data());
129 for (
unsigned m = 0;
m <
mesh.mNumAnimMeshes; ++
m) {
130 const aiAnimMesh *am =
mesh.mAnimMeshes[
m];
131 if (!am || !am->mVertices || am->mNumVertices !=
mesh.mNumVertices)
continue;
132 std::string morphName =
133 am->mName.length ? am->mName.C_Str() : (
"morph" + std::to_string(
m));
134 std::vector<float> absPos(
size_t(am->mNumVertices) * 3u);
135 for (
unsigned i = 0; i < am->mNumVertices; ++i) {
136 absPos[size_t(i) * 3u + 0] = am->mVertices[i].x;
137 absPos[size_t(i) * 3u + 1] = am->mVertices[i].y;
138 absPos[size_t(i) * 3u + 2] = am->mVertices[i].z;
140 handle->addMorphTargetAbsolute(morphName, absPos.data());
142 std::vector<float> deltaNormals(
size_t(am->mNumVertices) * 3u);
143 for (
unsigned i = 0; i < am->mNumVertices; ++i) {
144 deltaNormals[size_t(i) * 3] = am->mNormals[i].x - baseNrm[size_t(i) * 3];
145 deltaNormals[size_t(i) * 3 + 1] = am->mNormals[i].y - baseNrm[size_t(i) * 3 + 1];
146 deltaNormals[size_t(i) * 3 + 2] = am->mNormals[i].z - baseNrm[size_t(i) * 3 + 2];
148 auto normalResult =
handle->setMorphNormalDeltas(morphName, deltaNormals);
149 if (!normalResult.ok())
throw Exception(
"Invalid imported morph normals: %s", morphName.c_str());
156 ownedGpuMeshes.push_back(std::move(
gpu));
157 ownedMeshes.push_back(std::move(
handle));
163 if (!initialized)
throw Exception(
"newMeshFromAssimp: graphics not initialized");
164 if (
mesh.mNumVertices == 0 ||
mesh.mNumFaces == 0)
165 throw Exception(
"newMeshFromAssimp: empty mesh");
168 const aiMatrix4x4 world(worldTransform[0][0], worldTransform[1][0], worldTransform[2][0], worldTransform[3][0],
169 worldTransform[0][1], worldTransform[1][1], worldTransform[2][1], worldTransform[3][1],
170 worldTransform[0][2], worldTransform[1][2], worldTransform[2][2], worldTransform[3][2],
171 worldTransform[0][3], worldTransform[1][3], worldTransform[2][3], worldTransform[3][3]);
174 std::vector<aiVector3D>
normals(
mesh.mNumVertices);
175 std::vector<aiVector3D> tangents;
176 std::vector<aiVector3D> bitangents;
177 if (
mesh.HasTangentsAndBitangents()) {
178 tangents.resize(
mesh.mNumVertices);
179 bitangents.resize(
mesh.mNumVertices);
180 const aiMatrix3x3
linear(world);
181 for (
unsigned i = 0; i <
mesh.mNumVertices; ++i) {
184 tangents[i].Normalize();
185 bitangents[i].Normalize();
188 aiMatrix3x3 nmat(world);
189 const float ndet = nmat.Determinant();
190 if (std::fabs(ndet) > 1e-8f) {
194 for (
unsigned i = 0; i <
mesh.mNumVertices; ++i) {
196 if (
mesh.HasNormals()) {
200 normals[i] = aiVector3D(0.f, 1.f, 0.f);
206 const bool flipWinding = world.Determinant() < 0.f;
207 std::vector<aiFace> flippedFaces;
208 std::vector<unsigned> flippedIdx;
210 flippedFaces.resize(
mesh.mNumFaces);
211 flippedIdx.resize(
size_t(
mesh.mNumFaces) * 3u);
212 for (
unsigned f = 0;
f <
mesh.mNumFaces; ++
f) {
213 const aiFace &src =
mesh.mFaces[
f];
214 aiFace &dst = flippedFaces[
f];
215 dst.mNumIndices = src.mNumIndices;
216 if (src.mNumIndices == 3 && src.mIndices) {
217 unsigned *
idx = flippedIdx.data() + size_t(
f) * 3u;
218 idx[0] = src.mIndices[0];
219 idx[1] = src.mIndices[2];
220 idx[2] = src.mIndices[1];
223 dst.mIndices = src.mIndices;
230 tmp.mPrimitiveTypes =
mesh.mPrimitiveTypes;
231 tmp.mNumVertices =
mesh.mNumVertices;
234 tmp.mTangents = tangents.empty() ? nullptr : tangents.data();
235 tmp.mBitangents = bitangents.empty() ? nullptr : bitangents.data();
236 tmp.mNumFaces =
mesh.mNumFaces;
237 tmp.mFaces = flipWinding ? flippedFaces.data() :
mesh.mFaces;
238 tmp.mMaterialIndex =
mesh.mMaterialIndex;
239 tmp.mNumAnimMeshes =
mesh.mNumAnimMeshes;
240 tmp.mAnimMeshes =
mesh.mAnimMeshes;
241 if (
mesh.HasTextureCoords(0)) {
242 tmp.mTextureCoords[0] =
mesh.mTextureCoords[0];
243 tmp.mNumUVComponents[0] =
mesh.mNumUVComponents[0];
245 const auto detach = [&]() {
246 tmp.mVertices =
nullptr;
247 tmp.mNormals =
nullptr;
248 tmp.mTangents =
nullptr;
249 tmp.mBitangents =
nullptr;
250 tmp.mFaces =
nullptr;
251 tmp.mTextureCoords[0] =
nullptr;
252 tmp.mAnimMeshes =
nullptr;
274 if (!initialized)
throw Exception(
"newMeshFromArrays: graphics not initialized");
277 if (
indexCount % 3 != 0)
throw Exception(
"newMeshFromArrays: indexCount must be multiple of 3");
282 v.
pos = {posXYZ[size_t(i) * 3u], posXYZ[size_t(i) * 3u + 1u], posXYZ[size_t(i) * 3u + 2u]};
284 v.normal = {nrmXYZ[size_t(i) * 3u], nrmXYZ[size_t(i) * 3u + 1u],
285 nrmXYZ[size_t(i) * 3u + 2u]};
287 v.normal = {0.f, 1.f, 0.f};
289 v.uv = {uvST[size_t(i) * 2u], uvST[size_t(i) * 2u + 1u]};
293 v.color = {colorRGBA[size_t(i)*4u],colorRGBA[size_t(i)*4u+1u],
294 colorRGBA[size_t(i)*4u+2u],colorRGBA[size_t(i)*4u+3u]};
298 for (uint32_t
id :
idx) {
306 registerMeshRecord(
gpu.get());
307 ownedGpuMeshes.push_back(std::move(
gpu));
308 ownedMeshes.push_back(std::move(
handle));
318 std::find_if(ownedGpuMeshes.begin(), ownedGpuMeshes.end(),
319 [
gpu](
const std::unique_ptr<GpuMesh> &candidate) { return candidate.get() == gpu; });
320 if (
owned == ownedGpuMeshes.end())
325 gpu->indexType == vk::IndexType::eUint16 ? 2u : 4u});
329 if (!
mesh || !
mesh->gpuHandle || !
mesh->hasMorphData() || !
mesh->isMorphDirty())
return false;
330 if (!initialized)
return false;
332 std::vector<float>
pos;
333 std::vector<float> nrm;
334 mesh->computeMorphedPositions(
pos, nrm);
335 const int vc =
mesh->getVertexCount();
336 if (vc <= 0 ||
int(
pos.size()) < vc * 3)
return false;
337 mesh->computeBounds(
pos.data(), vc);
339 std::vector<MeshVertex>
verts(
static_cast<size_t>(vc));
341 if (
mesh->hasGpuSkinning()) {
344 void *mapped =
source.map();
345 if (!mapped)
return false;
349 const auto &
uv =
mesh->baseUv();
350 for (
int i = 0; i < vc; ++i) {
352 v.
pos = {
pos[size_t(i) * 3u + 0],
pos[size_t(i) * 3u + 1],
pos[size_t(i) * 3u + 2]};
353 if (
int(nrm.size()) >= (i + 1) * 3)
354 v.normal = {nrm[size_t(i) * 3u + 0], nrm[size_t(i) * 3u + 1], nrm[size_t(i) * 3u + 2]};
356 v.normal = {0.f, 1.f, 0.f};
357 if (
int(
uv.size()) >= (i + 1) * 2)
358 v.uv = {
uv[size_t(i) * 2u + 0],
uv[size_t(i) * 2u + 1]};
366 ensureDynamicRing(*
gpu);
367 writeDynamicMesh(*
gpu,
verts, getDevice(), frameToken(),
nullptr, 0);
368 mesh->markMorphClean();
375 if (!initialized || !
mesh || !
mesh->gpuHandle)
return false;
387 v.
pos = {posXYZ[size_t(i) * 3u], posXYZ[size_t(i) * 3u + 1u], posXYZ[size_t(i) * 3u + 2u]};
389 v.normal = {nrmXYZ[size_t(i) * 3u], nrmXYZ[size_t(i) * 3u + 1u],
390 nrmXYZ[size_t(i) * 3u + 2u]};
392 v.normal = {0.f, 1.f, 0.f};
394 v.uv = {uvST[size_t(i) * 2u], uvST[size_t(i) * 2u + 1u]};
402 ensureDynamicRing(*
gpu);
404 mesh->gpuVertexCount = int(
gpu->vertexCount);
405 mesh->indexCount = int(
gpu->indexCount);
411 if (!initialized || !
mesh || !
mesh->gpuHandle || !joints4 || !weights4)
return false;
417 void *mapped =
source.map();
418 if (!mapped)
return false;
422 const size_t base =
static_cast<size_t>(i) * 4u;
423 verts[
static_cast<size_t>(i)].joints =
424 glm::u16vec4(joints4[base], joints4[base + 1], joints4[base + 2], joints4[base + 3]);
426 glm::vec4(weights4[base], weights4[base + 1], weights4[base + 2], weights4[base + 3]);
428 ensureDynamicRing(*
gpu);
429 writeDynamicMesh(*
gpu,
verts, getDevice(), frameToken(),
nullptr, 0);
430 mesh->markGpuSkinned(
true);
435 if (!
mesh || !
mesh->gpuHandle)
return false;
438 auto gpuIt = std::find_if(ownedGpuMeshes.begin(), ownedGpuMeshes.end(),
439 [&](
const std::unique_ptr<GpuMesh> &
g) {
440 return g.get() == gpu;
442 if (gpuIt == ownedGpuMeshes.end())
return false;
444 auto meshIt = std::find_if(ownedMeshes.begin(), ownedMeshes.end(),
445 [&](
const std::unique_ptr<Mesh> &
m) {
446 return m.get() == mesh;
448 if (meshIt == ownedMeshes.end())
return false;
451 waitForSharedGpuResources();
452 mesh->gpuHandle =
nullptr;
453 ownedGpuMeshes.erase(gpuIt);
455 (void)meshIt->release();
456 ownedMeshes.erase(meshIt);
462 if (!initialized)
throw Exception(
"newMeshSphere: graphics not initialized");
463 if (slices < 3) slices = 3;
464 if (stacks < 2) stacks = 2;
465 if (slices > 256) slices = 256;
466 if (stacks > 128) stacks = 128;
468 constexpr float kPi = 3.14159265358979323846f;
469 constexpr float kTwoPi = kPi * 2.f;
477 const int stride = slices + 1;
478 const int rows = stacks + 1;
479 std::vector<MeshVertex>
verts;
480 verts.reserve(
size_t(stride) *
size_t(
rows));
482 auto pushVert = [&](
float px,
float py,
float pz,
float u,
float v) {
490 for (
int y = 0;
y <= stacks; ++
y) {
491 const float fv = float(
y) / float(stacks);
492 const float phi = fv * kPi;
493 const float sinPhi = std::sin(
phi);
494 const float cosPhi = std::cos(
phi);
495 for (
int x = 0;
x <= slices; ++
x) {
496 const float u = float(
x) / float(slices);
497 const float theta =
u * kTwoPi;
500 pushVert(0.f, 1.f, 0.f,
u, 0.f);
501 else if (
y == stacks)
502 pushVert(0.f, -1.f, 0.f,
u, 1.f);
504 pushVert(sinPhi * std::cos(theta), cosPhi, sinPhi * std::sin(theta),
u, fv);
509 indices.reserve(
size_t(slices) *
size_t(stacks) * 6u);
512 for (
int y = 0;
y < stacks; ++
y) {
513 const uint32_t row0 = uint32_t(
y * stride);
514 const uint32_t row1 = uint32_t((
y + 1) * stride);
515 for (
int x = 0;
x < slices; ++
x) {
516 const uint32_t
i0 = row0 + uint32_t(
x);
517 const uint32_t
i1 = row0 + uint32_t(
x + 1);
518 const uint32_t
i2 = row1 + uint32_t(
x);
519 const uint32_t i3 = row1 + uint32_t(
x + 1);
533 registerMeshRecord(
gpu.get());
534 ownedGpuMeshes.push_back(std::move(
gpu));
535 ownedMeshes.push_back(std::move(
handle));
541 if (!initialized)
throw Exception(
"newMeshCylinder: graphics not initialized");
542 if (slices < 3) slices = 3;
543 if (stacks < 1) stacks = 1;
544 if (slices > 256) slices = 256;
545 if (stacks > 128) stacks = 128;
547 constexpr float kPi = 3.14159265358979323846f;
548 constexpr float kTwoPi = kPi * 2.f;
549 constexpr float kRadius = 1.f;
550 constexpr float kHalfH = 1.f;
552 const int stride = slices + 1;
553 const int sideRows = stacks + 1;
554 std::vector<MeshVertex>
verts;
555 verts.reserve(
size_t(stride) *
size_t(sideRows) +
size_t(
caps ? 2 * (slices + 2) : 0));
557 auto pushVert = [&](
float px,
float py,
float pz,
float nx,
float ny,
float nz,
float u,
567 for (
int y = 0;
y <= stacks; ++
y) {
568 const float fv = float(
y) / float(stacks);
569 const float py = kHalfH - fv * (2.f * kHalfH);
570 for (
int x = 0;
x <= slices; ++
x) {
571 const float u = float(
x) / float(slices);
572 const float theta =
u * kTwoPi;
573 const float cx = std::cos(theta);
574 const float sz = std::sin(theta);
575 pushVert(kRadius *
cx,
py, kRadius *
sz,
cx, 0.f,
sz,
u, fv);
580 indices.reserve(
size_t(slices) *
size_t(stacks) * 6u +
581 size_t(
caps ? slices * 2 * 3 : 0));
583 for (
int y = 0;
y < stacks; ++
y) {
584 const uint32_t row0 = uint32_t(
y * stride);
585 const uint32_t row1 = uint32_t((
y + 1) * stride);
586 for (
int x = 0;
x < slices; ++
x) {
587 const uint32_t
i0 = row0 + uint32_t(
x);
588 const uint32_t
i1 = row0 + uint32_t(
x + 1);
589 const uint32_t
i2 = row1 + uint32_t(
x);
590 const uint32_t i3 = row1 + uint32_t(
x + 1);
602 const uint32_t topCenter = uint32_t(
verts.size());
603 pushVert(0.f, kHalfH, 0.f, 0.f, 1.f, 0.f, 0.5f, 0.5f);
604 const uint32_t topRing = uint32_t(
verts.size());
605 for (
int x = 0;
x <= slices; ++
x) {
606 const float u = float(
x) / float(slices);
607 const float theta =
u * kTwoPi;
608 const float cx = std::cos(theta);
609 const float sz = std::sin(theta);
610 pushVert(kRadius *
cx, kHalfH, kRadius *
sz, 0.f, 1.f, 0.f, 0.5f + 0.5f *
cx,
613 for (
int x = 0;
x < slices; ++
x) {
615 indices.push_back(topRing + uint32_t(
x + 1));
616 indices.push_back(topRing + uint32_t(
x));
620 const uint32_t botCenter = uint32_t(
verts.size());
621 pushVert(0.f, -kHalfH, 0.f, 0.f, -1.f, 0.f, 0.5f, 0.5f);
622 const uint32_t botRing = uint32_t(
verts.size());
623 for (
int x = 0;
x <= slices; ++
x) {
624 const float u = float(
x) / float(slices);
625 const float theta =
u * kTwoPi;
626 const float cx = std::cos(theta);
627 const float sz = std::sin(theta);
628 pushVert(kRadius *
cx, -kHalfH, kRadius *
sz, 0.f, -1.f, 0.f, 0.5f + 0.5f *
cx,
631 for (
int x = 0;
x < slices; ++
x) {
633 indices.push_back(botRing + uint32_t(
x));
634 indices.push_back(botRing + uint32_t(
x + 1));
642 registerMeshRecord(
gpu.get());
643 ownedGpuMeshes.push_back(std::move(
gpu));
644 ownedMeshes.push_back(std::move(
handle));
652 std::find_if(ownedMeshes.begin(), ownedMeshes.end(), [&](
const auto &item) { return item.get() == &mesh; });
655 mesh.hasGpuSkinning() || (!swapchainPassOpen && !offscreen3DPassOpen))
657 "Expected same-device resident vertices in an open pass",
658 "graphics.residentMesh"));
663 "Resident vertex stream is too small",
"graphics.residentMesh"));
665 static_assert(
sizeof(
raw) <=
sizeof(
source.nativeHandle));
667 gpu.residentVertexOverride =
raw;
668 gpu.residentVertexOffset =
source.offsetBytes;
669 struct ClearOverride {
673 mesh.residentVertexOffset = 0;
679 }
catch (
const std::exception &e) {
695 const auto invalid = [](
const char *
message) {
699 if (!initialized || !
mesh.gpuHandle ||
700 std::none_of(ownedMeshes.begin(), ownedMeshes.end(), [&](
const auto &
owned) { return owned.get() == &mesh; }) ||
701 (!swapchainPassOpen && !offscreen3DPassOpen))
702 return invalid(
"Expected an owned mesh inside an open 3D pass");
704 (!
texture->get().gpuHandle || std::none_of(ownedTextures.begin(), ownedTextures.end(),
705 [&](
const auto &
owned) { return owned.get() == &texture->get(); })))
706 return invalid(
"Albedo texture belongs to another provider");
710 "graphics.meshInstances"));
711 if (models.size() > UINT32_MAX ||
712 models.size_bytes() >
device.physical_device.properties.limits.maxStorageBufferRange)
713 return invalid(
"Transform batch exceeds device storage range");
714 for (
const auto &
model : models)
716 for (
int row = 0; row < 4; ++row)
717 if (!std::isfinite(
model[
column][row]))
return invalid(
"Nonfinite instance transform");
718 for (
int i = 0; i < 4; ++i)
719 if (!std::isfinite(
tint[i]))
return invalid(
"Nonfinite instance tint");
721 const auto &
slots = currentMesh3dFrameSlots();
724 "graphics.meshInstances"));
727 uint32_t(models.size()), models);
729 }
catch (
const std::exception &
error) {
736 auto fail = [](
const char *
message) {
739 auto ownedShader = std::find_if(ownedGpuShaders.begin(), ownedGpuShaders.end(),
740 [&](
const auto &item) { return item->owner == &shader; });
742 std::find_if(ownedMeshes.begin(), ownedMeshes.end(), [&](
const auto &item) { return item.get() == &mesh; });
743 if (!initialized || ownedShader == ownedGpuShaders.end() || ownedMesh == ownedMeshes.end() ||
744 !(*ownedShader)->isMesh3D || (*ownedShader)->isHair3D ||
shader.isXray() || !
mesh.gpuHandle ||
745 (!swapchainPassOpen && !offscreen3DPassOpen))
746 return fail(
"Expected owned mesh resources inside an open 3D pass");
747 const auto size = meshResourceInstanceCount(**ownedShader);
749 return fail(
"Instance range exceeds the immutable matrix buffer");
750 for (
int col = 0; col < 4; ++col)
751 for (
int row = 0; row < 4; ++row)
752 if (!std::isfinite(
model[col][row]))
return fail(
"Nonfinite model matrix");
753 for (
int i = 0; i < 4; ++i)
754 if (!std::isfinite(
tint[i]))
return fail(
"Nonfinite instance tint");
759 }
catch (
const std::exception &
error) {
766 std::span<const glm::mat4> models) {
768 ASSERT(
mesh !=
nullptr);
769 if (!initialized)
throw Exception(
"drawMesh: graphics not initialized");
771 if (!swapchainPassOpen && !offscreen3DPassOpen)
772 throw Exception(
"drawMesh: call begin3DFrame first");
773 createMesh3DPipeline();
774 if (!mesh3dPipeline)
throw Exception(
"drawMesh: mesh3d pipeline missing");
778 throw Exception(
"drawMesh: shader is not a Mesh3D shader (use newMeshShader*)");
779 if (!
shader->gpuHandle)
throw Exception(
"drawMesh: shader has no GPU pipeline");
782 if (pbrSurface_ && !
shader) {
786 auto *gpuMesh =
static_cast<GpuMesh *
>(
mesh->gpuHandle);
788 if (!tex || !tex->gpuHandle)
throw Exception(
"drawMesh: missing texture");
789 auto *gpuTex =
static_cast<GpuTexture *
>(tex->gpuHandle);
791 ensureFlatNormalTexture3D();
792 Texture *ntex = mesh3dNormalTexture ? mesh3dNormalTexture : flatNormalTexture3D;
793 if (!ntex || !ntex->gpuHandle)
throw Exception(
"drawMesh: missing normal texture");
794 auto *gpuNormal =
static_cast<GpuTexture *
>(ntex->gpuHandle);
796 ensureFlatHeightTexture3D();
797 Texture *htex = mesh3dHeightTexture ? mesh3dHeightTexture : flatHeightTexture3D;
798 if (!htex || !htex->gpuHandle)
throw Exception(
"drawMesh: missing height texture");
799 auto *gpuHeight =
static_cast<GpuTexture *
>(htex->gpuHandle);
801 Texture *depthTex = mesh3dSceneDepthTexture ? mesh3dSceneDepthTexture : whiteTexture;
802 if (!depthTex || !depthTex->gpuHandle)
throw Exception(
"drawMesh: missing scene depth texture");
803 auto *gpuDepth =
static_cast<GpuTexture *
>(depthTex->gpuHandle);
808 ensureDecalPlaceholders();
809 GpuTexture *gpuDecalAlb =
nullptr;
810 GpuTexture *gpuDecalNrm =
nullptr;
811 GpuTexture *gpuDecalPrm =
nullptr;
812 if (decalLayerFresh) {
813 if (
auto *dslot = currentDecalSlot()) {
814 gpuDecalAlb = &dslot->albedoGpu;
815 gpuDecalNrm = &dslot->normalGpu;
816 gpuDecalPrm = &dslot->paramsGpu;
820 gpuDecalAlb =
static_cast<GpuTexture *
>(decalFlatAlbedo->gpuHandle);
821 gpuDecalNrm =
static_cast<GpuTexture *
>(decalFlatNormal->gpuHandle);
822 gpuDecalPrm =
static_cast<GpuTexture *
>(decalFlatParams->gpuHandle);
825 ensureDefaultEnvCubemap();
826 Texture *envTex = mesh3dEnvTexture ? mesh3dEnvTexture : defaultEnvCubemap;
827 if (!envTex || !envTex->gpuHandle)
throw Exception(
"drawMesh: missing env cubemap");
828 auto *gpuEnv =
static_cast<GpuTexture *
>(envTex->gpuHandle);
829 if (!gpuEnv->isCube)
throw Exception(
"drawMesh: env texture is not a cubemap");
830 const float envIntensity = (mesh3dEnvTexture && mesh3dEnvIntensity > 0.f) ? mesh3dEnvIntensity : 0.f;
832 const bool useClustered = mesh3dClusteredActive && !
shader && mesh3dClusteredPipeline &&
834 auto &cb = currentPresentCb();
836 auto makeShadowUbo = [&]() {
837 ShadowUBO
s = mesh3dShadows.ubo;
838 if (!mesh3dShadows.active) {
842 s.bias.z = mesh3dShadowReceive ? 1.f : 0.f;
847 Mesh3DClusteredUBO ubo{};
849 ubo.mvp = mesh3dFrameUbo.mvp *
model;
850 ubo.view = mesh3dClustered.view;
851 ubo.lightDir = mesh3dClustered.primaryDir;
852 ubo.lightColor = glm::vec4(glm::vec3(mesh3dClustered.primaryColor), envIntensity);
854 ubo.cameraPos = glm::vec4(glm::vec3(mesh3dFrameUbo.cameraPos), mesh3dRoughness);
855 ubo.ambient = glm::vec4(glm::vec3(mesh3dClustered.ambient), mesh3dMetallic);
856 ubo.gridInfo = mesh3dClustered.gridInfo;
857 ubo.clipInfo = mesh3dClustered.clipInfo;
858 float surfaceCode = float(
int(mesh3dSurfaceMode));
862 mesh3dAlphaTechnique ==
"coverage")
864 ubo.texBomb = glm::vec4(mesh3dTexBombScale, mesh3dTexBombStrength, mesh3dTexBombRot,
867 glm::vec4(mesh3dParallaxScale, mesh3dParallaxMinLayers, mesh3dParallaxMaxLayers,
869 ubo.virtualTexture = mesh3dVirtualTexture;
870 ubo.virtualAtlas = mesh3dVirtualAtlas;
871 ubo.envProbeCenter = glm::vec4(mesh3dEnvProbeCenter, 1.f);
872 ubo.envProbeExtent = glm::vec4(mesh3dEnvProbeExtent, 0.f);
874 if (i >= mesh3dReflectionProbes.count)
continue;
875 const auto &probe = mesh3dReflectionProbes.probes[i];
876 if (!probe.cubemap || !probe.cubemap->gpuHandle ||
877 !
static_cast<GpuTexture *
>(probe.cubemap->gpuHandle)->isCube)
879 ubo.reflectionProbeCenter[i] = glm::vec4(probe.center, probe.intensity);
880 ubo.reflectionProbeExtent[i] = glm::vec4(probe.extent, probe.blendDistance);
883 auto &cfslots = currentMesh3dClusteredFrameSlots();
884 if (cfslots.drawIndex >= cfslots.capacity) {
886 "[vulkan] clustered mesh3d UBO ring exhausted (%zu draws); draw skipped\n",
890 const size_t slot = cfslots.drawIndex++;
891 ensureMesh3dStrides();
892 const uint32_t uboOffset = uint32_t(
slot) * mesh3dClusteredUboStride;
893 const uint32_t shadowOffset = uint32_t(
slot) * shadowUboStride;
894 updateRingLocal(cfslots.uboRing, uboOffset, &ubo,
sizeof(ubo));
895 const ShadowUBO shadow = makeShadowUbo();
896 updateRingLocal(cfslots.shadowRing, shadowOffset, &shadow,
sizeof(shadow));
897 vk::DescriptorSet set =
898 mesh3dClusteredSetFor(gpuTex, gpuNormal, gpuEnv, gpuHeight, gpuDecalAlb, gpuDecalNrm,
899 gpuDecalPrm, cfslots);
900 const uint32_t dynOffsets[2] = {uboOffset, shadowOffset};
902 if (mesh3dClusteredPipeline != lastMesh3dClusteredPipeline) {
903 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh3dClusteredPipeline);
904 lastMesh3dClusteredPipeline = mesh3dClusteredPipeline;
906 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dClusteredPipelineLayout, 0, 1,
907 &set, 2, dynOffsets);
908 drawIndexedMesh(cb, *gpuMesh);
912 Mesh3DUBO ubo = mesh3dFrameUbo;
914 ubo.mvp = mesh3dFrameUbo.mvp *
model;
915 ubo.skinInfo.z = models.empty() ? 0.f : 1.f;
917 ubo.ambient = glm::vec4(glm::vec3(mesh3dLighting.ambient), mesh3dMetallic);
919 ubo.lightDir.w = float(lightCount);
920 ubo.cameraPos.w = mesh3dRoughness;
921 ubo.lightColor.w = envIntensity;
922 float surfaceCode = float(
int(mesh3dSurfaceMode));
927 ubo.texBomb = glm::vec4(mesh3dTexBombScale, mesh3dTexBombStrength, mesh3dTexBombRot,
930 glm::vec4(mesh3dParallaxScale, mesh3dParallaxMinLayers, mesh3dParallaxMaxLayers,
932 ubo.virtualTexture = mesh3dVirtualTexture;
933 ubo.virtualAtlas = mesh3dVirtualAtlas;
934 ubo.lodFade = mesh3dLodFade;
936 if (i >= mesh3dReflectionProbes.count)
continue;
937 const auto &probe = mesh3dReflectionProbes.probes[i];
938 if (!probe.cubemap || !probe.cubemap->gpuHandle ||
939 !
static_cast<GpuTexture *
>(probe.cubemap->gpuHandle)->isCube)
941 ubo.reflectionProbeCenter[i] = glm::vec4(probe.center, probe.intensity);
942 ubo.reflectionProbeExtent[i] = glm::vec4(probe.extent, probe.blendDistance);
944 if (
mesh->hasGpuSkinning()) {
945 ubo.skinInfo.x =
static_cast<float>(
mesh->getSkinPaletteCount());
946 ubo.skinInfo.y =
static_cast<float>(mesh3dSkinInfluenceLimit);
948 for (
int i = 0; i < lightCount; ++i) ubo.lights[i] = mesh3dLighting.lights[i];
950 for (
int i = 0; i < lightCount; ++i) {
951 if (mesh3dLighting.lights[i].posRadius.w <= 0.f) {
957 glm::vec3
d(mesh3dLighting.lights[dirI].posRadius);
958 if (glm::length(
d) < 1e-6f)
d = glm::vec3(0.f, 1.f, 0.f);
959 else d = glm::normalize(
d);
960 ubo.lightDir = glm::vec4(
d,
float(lightCount));
961 ubo.lightColor = glm::vec4(glm::vec3(mesh3dLighting.lights[dirI].color), envIntensity);
963 ubo.lightDir = glm::vec4(0.f, 1.f, 0.f,
float(lightCount));
964 ubo.lightColor = glm::vec4(0.f, 0.f, 0.f, envIntensity);
967 auto &fslots = currentMesh3dFrameSlots();
968 if (fslots.drawIndex >= fslots.capacity) {
969 std::fprintf(stderr,
"[vulkan] mesh3d UBO ring exhausted (%zu draws); draw skipped\n",
973 if (models.empty()) {
974 uploadSkinPalette(
mesh, fslots);
979 const size_t matrixSlot = fslots.drawIndex + 1;
980 if (fslots.palettes.size() <= matrixSlot) fslots.palettes.resize(matrixSlot + 1);
981 auto &
buffer = fslots.palettes[matrixSlot];
982 if (!
buffer.buffer ||
buffer.capacity < models.size_bytes()) {
983 buffer.allocate(frameToken(),
device, vk::BufferUsageFlagBits::eStorageBuffer, models.size_bytes(),
984 kHostVisibleCoherent);
986 fslots.skinSets.clear();
988 updateRingLocal(
buffer, 0, models.data(), models.size_bytes());
989 fslots.activePalette = matrixSlot;
991 const size_t slot = fslots.drawIndex++;
992 ensureMesh3dStrides();
993 const uint32_t uboOffset = uint32_t(
slot) * mesh3dUboStride;
994 const uint32_t shadowOffset = uint32_t(
slot) * shadowUboStride;
995 updateRingLocal(fslots.uboRing, uboOffset, &ubo,
sizeof(ubo));
996 const ShadowUBO shadow = makeShadowUbo();
997 updateRingLocal(fslots.shadowRing, shadowOffset, &shadow,
sizeof(shadow));
998 auto *gpuSceneColor = mesh3dSceneColorTexture && mesh3dSceneColorTexture->gpuHandle
999 ?
static_cast<GpuTexture *
>(mesh3dSceneColorTexture->gpuHandle)
1000 : sceneColorHistoryValid && completedSceneColorSlot < sceneColorSlots.
size()
1001 ? &sceneColorSlots[completedSceneColorSlot].colorGpu
1002 : static_cast<GpuTexture *>(whiteTexture->gpuHandle);
1006 GpuTexture **
slots[] = {&gpuDecalAlb, &gpuDecalNrm, &gpuDecalPrm, &gpuSceneColor};
1009 if (!custom->gpuHandle)
throw Exception(
"drawMesh: custom texture has no GPU resource");
1010 auto *gpuCustom =
static_cast<GpuTexture *
>(custom->gpuHandle);
1011 if (gpuCustom->isCube)
throw Exception(
"drawMesh: custom texture must be two-dimensional");
1016 vk::DescriptorSet set = mesh3dSetFor(
1017 gpuTex, gpuNormal, gpuEnv, gpuHeight, gpuDepth, gpuSceneColor, gpuDecalAlb, gpuDecalNrm, gpuDecalPrm, fslots,
1018 shader ?
static_cast<GpuShader *
>(
shader->gpuHandle)->resourceFrameLayout : vk::DescriptorSetLayout{});
1019 const uint32_t dynOffsets[2] = {uboOffset, shadowOffset};
1022 auto *gs =
static_cast<GpuShader *
>(
shader->gpuHandle);
1023 vk::Pipeline activePipeline = offscreen3DPassOpen
1024 ? (offscreen3DHDRActive
1025 ? gs->mesh3dHdrOffscreenPipeline
1026 : gs->mesh3dOffscreenPipeline)
1027 : gs->mesh3dPipeline;
1028 if (
shader->isXray() && !offscreen3DPassOpen) {
1033 activePipeline = gs->mesh3dXrayPipeline;
1035 if (!activePipeline)
return;
1036 if (activePipeline != lastMesh3dPipeline) {
1037 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, activePipeline);
1038 lastMesh3dPipeline = activePipeline;
1040 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gs->pipelineLayout, 0, 1, &set, 2, dynOffsets);
1042 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gs->pipelineLayout, 1, 1, &gs->resourceSet, 0,
1044 cb.pushConstants(gs->pipelineLayout, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
1049 const bool depthWrite = !transparent || mesh3dSurfaceDepthWrite;
1050 const size_t pipelineIndex =
1051 mesh3dPipelineIndex(
blend, depthWrite, mesh3dSurfaceDoubleSided);
1052 const vk::Pipeline pipe = offscreen3DPassOpen
1053 ? (offscreen3DHDRActive
1054 ? hdrOffscreen3DSurfacePipelines[pipelineIndex]
1055 : offscreen3DSurfacePipelines[pipelineIndex])
1056 : mesh3dSurfacePipelines[pipelineIndex];
1057 if (pipe != lastMesh3dPipeline) {
1058 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
1059 lastMesh3dPipeline = pipe;
1061 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dPipelineLayout, 0, 1, &set, 2,
std::vector< std::uint32_t > verts
std::uint32_t vertexCount
std::uint32_t firstInstance
std::uint32_t instanceCount
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
std::shared_ptr< OceanGpuSpectrum > gpu
std::unique_ptr< gpgpu::GpuBuffer > buffer
Local-probe upload record kept off the high-fanout IGraphics3D header.
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
std::vector< double > phi
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
virtual void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth)=0
Clears .
virtual bool releaseMesh(Mesh *mesh)
Eagerly releases a mesh created by this Graphics.
virtual Mesh * newMeshCylinder(int slices=32, int stacks=1, bool caps=true)=0
Procedural Y-up cylinder (radius 1, height 2 centered at origin). slices = longitude divisions; stack...
virtual void drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint)=0
Draw one mesh with model matrix. Requires begin3DFrame() (or an open swapchain pass).
virtual Mesh * newMeshFromAssimp(const ::aiMesh &mesh)=0
Creates a mesh from assimp. @ownership Caller deletes unless documented otherwise.
virtual bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
In-place update of a mesh's vertex/index data (CPU -> host-visible VBO). Only call when content chang...
virtual Result< void > drawMeshInstances(Mesh &mesh, std::span< const glm::mat4 > models, OptionalRef< Texture > texture, const Color &tint)
Draw a batch of static meshes using the current ordinary material and lighting bindings.
virtual Result< void > drawMeshShaderInstances(Mesh &mesh, Shader &shader, const glm::mat4 &model, const Color &tint, std::uint32_t first, std::uint32_t count)
Draw a checked range from a resource shader's immutable instance matrix buffer. @ownership Mesh and S...
virtual bool setMeshSkinningData(Mesh *mesh, const uint16_t *joints4, const float *weights4, int vertexCount)
Upload four joint indices and weights per vertex for built-in GPU skinning.
virtual bool bakeMeshMorph(Mesh *mesh)=0
If mesh morph weights are dirty, bake blended positions and upload to the GPU VBO....
virtual Result< void > drawMeshResidentVertices(Mesh &mesh, const GpuResidentBufferView &source)
Draw a mesh using a producer-owned packed resident vertex stream. Stream ABI: 22 float words per vert...
virtual void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint, Shader *shader)=0
Draw mesh with an explicit Mesh3D Shader (nullptr = default PBR pipeline).
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
virtual eve::Result< MeshBackendDescriptor > describeMesh(Mesh *mesh) const
Describe a live mesh created by this Graphics backend.
virtual Mesh * newMeshFromArraysColored(const float *posXYZ, const float *nrmXYZ, const float *uvST, const float *colorRGBA, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh with an optional packed RGBA color per vertex.
virtual Mesh * newMeshSphere(int slices=32, int stacks=16)=0
Procedural UV sphere (radius 1, Y-up). Owned by Graphics. slices = longitude divisions,...
GPU mesh handle (+ optional CPU morph targets).
void computeBounds(const float *posXYZ, int vertexCount)
Compute the bounding sphere (centroid + max radius) from positions.
static constexpr uint32_t kPushConstantBytes
static constexpr std::size_t kMaxMeshTextures
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Mesh * newMeshFromAssimp(const ::aiMesh &mesh) override
Creates a mesh from assimp. @ownership Caller deletes unless documented otherwise.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Transient backend buffer slice shared between sibling GPU modules. @ownership Non-owning; nativeHandl...
static constexpr int kMaxLights
Backend-owned layout facts for a mesh uploaded through Graphics.
std::uint32_t vertexCount
static constexpr int kMaxProbes
vk::Buffer residentVertexOverride
std::vector< MeshVertex > updateVertices