载入中...
搜索中...
未找到
GraphicsGpuDriven.cpp
浏览该文件的文档.
1#include "common/Exception.h"
4
5#include "graphics/Material.h"
8
9#include <algorithm>
10#include <cmath>
11#include <cstring>
12#include <map>
13#include <numeric>
14#include <string>
15#include <utility>
16
17#include <glm/gtc/matrix_access.hpp>
18
19namespace eve::graphics::webgpu {
20namespace {
21
22WGPUStringView label(const char* s) {
23 WGPUStringView out{};
24 out.data = s;
25 out.length = WGPU_STRLEN;
26 return out;
27}
28
29wgpu::ShaderModule shaderModule(wgpu::Device device, const char* source) {
30 WGPUShaderSourceWGSL wgsl{};
31 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
32 wgsl.code = label(source);
33 WGPUShaderModuleDescriptor desc{};
34 desc.nextInChain = &wgsl.chain;
35 return device.CreateShaderModule(reinterpret_cast<const wgpu::ShaderModuleDescriptor*>(&desc));
36}
37
38wgpu::ShaderModule shaderModule(wgpu::Device device, const std::string& source) {
39 WGPUShaderSourceWGSL wgsl{};
40 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
41 wgsl.code.data = source.data();
42 wgsl.code.length = source.size();
43 WGPUShaderModuleDescriptor desc{};
44 desc.nextInChain = &wgsl.chain;
45 return device.CreateShaderModule(reinterpret_cast<const wgpu::ShaderModuleDescriptor*>(&desc));
46}
47
48struct CullInput {
49 glm::mat4 model{1.f};
50 glm::vec4 bounds{0.f};
51 glm::vec4 color{1.f};
52 glm::vec4 terrainWave{};
53 glm::vec4 terrainWaveTint{1.f};
54 uint32_t bucket = 0;
55 uint32_t outputBase = 0;
56 uint32_t pad[2]{};
57};
58static_assert(sizeof(CullInput) == 144);
59
60using VisibleInstance = GpuInstance;
61static_assert(sizeof(VisibleInstance) == 208);
62
63struct CullParams {
64 glm::mat4 viewProj{1.f};
65 glm::vec4 planes[6]{};
66 glm::vec4 cameraPos{};
67 glm::vec4 screen{};
68 glm::vec4 clipNearFar{};
69 glm::vec4 hzbInfo{};
70 glm::uvec4 counts{};
71};
72static_assert(sizeof(CullParams) == 240);
73
74struct VisIndirectCommand {
75 uint32_t vertexCount = 0;
76 uint32_t instanceCount = 0;
77 uint32_t firstVertex = 0;
78 uint32_t firstInstance = 0;
79};
80static_assert(sizeof(VisIndirectCommand) == 16);
81
82struct HzbBuildParams {
83 glm::uvec4 info{}; // mip, width, height, previous-mip word offset
84 glm::uvec4 source{}; // previous width, previous height
85};
86static_assert(sizeof(HzbBuildParams) == 32);
87
88constexpr uint32_t kMaxHzbMips = 16;
89constexpr uint32_t kHzbHeaderWords = 16;
90
91constexpr const char* kHzbBuildWgsl = R"wgsl(
92struct BuildParams { info: vec4u, source: vec4u };
93@group(0) @binding(0) var<uniform> params: BuildParams;
94@group(0) @binding(1) var sourceDepth: texture_depth_2d;
95@group(0) @binding(2) var<storage, read_write> hzb: array<u32>;
96
97fn readHzb(base: u32, width: u32, height: u32, p: vec2i) -> f32 {
98 let q = clamp(p, vec2i(0), vec2i(i32(width) - 1, i32(height) - 1));
99 return bitcast<f32>(hzb[base + u32(q.y) * width + u32(q.x)]);
100}
101
102@compute @workgroup_size(8, 8)
103fn cs_main(@builtin(global_invocation_id) gid: vec3u) {
104 let mip = params.info.x;
105 let width = params.info.y;
106 let height = params.info.z;
107 if (gid.x >= width || gid.y >= height) { return; }
108 var depth: f32;
109 if (mip == 0u) {
110 depth = textureLoad(sourceDepth, vec2i(gid.xy), 0);
111 } else {
112 let previousWidth = params.source.x;
113 let previousHeight = params.source.y;
114 let previousBase = 16u + params.info.w;
115 let p = vec2i(gid.xy * 2u);
116 depth = max(readHzb(previousBase, previousWidth, previousHeight, p),
117 max(readHzb(previousBase, previousWidth, previousHeight, p + vec2i(1, 0)),
118 max(readHzb(previousBase, previousWidth, previousHeight, p + vec2i(0, 1)),
119 readHzb(previousBase, previousWidth, previousHeight, p + vec2i(1, 1)))));
120 }
121 let outputBase = 16u + hzb[mip];
122 hzb[outputBase + gid.y * width + gid.x] = bitcast<u32>(depth);
123}
124)wgsl";
125
126constexpr const char* kCullWgsl = R"wgsl(
127struct CullInput {
128 model: mat4x4f,
129 bounds: vec4f,
130 color: vec4f,
131 terrainWave: vec4f,
132 terrainWaveTint: vec4f,
133 bucket: u32,
134 outputBase: u32,
135 pad1: u32,
136 pad2: u32,
137};
138struct VisibleInstance {
139 model: mat4x4f,
140 meshId: u32,
141 materialId: u32,
142 flags: u32,
143 lodGroupId: u32,
144 reflectionProbeSlots: vec4u,
145 reflectionProbeCenter: array<vec4f, 2>,
146 reflectionProbeExtent: array<vec4f, 2>,
147 color: vec4f,
148 terrainWave: vec4f,
149 terrainWaveTint: vec4f,
150};
151struct CullParams {
152 viewProj: mat4x4f,
153 planes: array<vec4f, 6>,
154 cameraPos: vec4f,
155 screen: vec4f,
156 clipNearFar: vec4f,
157 hzbInfo: vec4f,
158 counts: vec4u,
159};
160struct IndirectCommand {
161 indexCount: u32,
162 instanceCount: atomic<u32>,
163 firstIndex: u32,
164 baseVertex: u32,
165 firstInstance: u32,
166};
167struct VisIndirectCommand {
168 vertexCount: u32,
169 instanceCount: atomic<u32>,
170 firstVertex: u32,
171 firstInstance: u32,
172};
173@group(0) @binding(0) var<uniform> params: CullParams;
174@group(0) @binding(1) var<storage, read> inputs: array<CullInput>;
175@group(0) @binding(2) var<storage, read_write> visibleInstances: array<VisibleInstance>;
176@group(0) @binding(3) var<storage, read_write> commands: array<IndirectCommand>;
177@group(0) @binding(4) var<storage, read_write> visCommands: array<VisIndirectCommand>;
178@group(0) @binding(5) var<storage, read> hzb: array<u32>;
179
180fn remainsVisibleAgainstDepth(center: vec3f, radius: f32) -> bool {
181 if (params.clipNearFar.w < 0.5) { return true; }
182 let clip = params.viewProj * vec4f(center, 1.0);
183 if (clip.w <= params.clipNearFar.x) { return true; }
184 let ndc = clip.xyz / clip.w;
185 if (abs(ndc.x) > 1.0 || abs(ndc.y) > 1.0 || ndc.z > 1.0) { return true; }
186
187 let toEye = normalize(params.cameraPos.xyz - center);
188 let frontClip = params.viewProj * vec4f(center + toEye * radius, 1.0);
189 let frontZ = frontClip.z / max(frontClip.w, 1e-6);
190 let viewDepth = max(length(center - params.cameraPos.xyz), 1e-4);
191 let radiusPx = radius * params.clipNearFar.z / viewDepth;
192 let diameterPx = max(radiusPx * 2.0, 1.0);
193 let mip = min(u32(ceil(log2(diameterPx))), u32(params.hzbInfo.x));
194 let width = max(u32(params.hzbInfo.z) >> mip, 1u);
195 let height = max(u32(params.hzbInfo.w) >> mip, 1u);
196 let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
197 let p0 = clamp(vec2i(uv * vec2f(f32(width), f32(height))) - vec2i(1),
198 vec2i(0), vec2i(i32(width) - 1, i32(height) - 1));
199 let p1 = min(p0 + vec2i(1), vec2i(i32(width) - 1, i32(height) - 1));
200 let base = 16u + hzb[mip];
201 let a = bitcast<f32>(hzb[base + u32(p0.y) * width + u32(p0.x)]);
202 let b = bitcast<f32>(hzb[base + u32(p0.y) * width + u32(p1.x)]);
203 let c = bitcast<f32>(hzb[base + u32(p1.y) * width + u32(p0.x)]);
204 let d = bitcast<f32>(hzb[base + u32(p1.y) * width + u32(p1.x)]);
205 let blocker = min(min(a, b), min(c, d));
206 // All conservative samples must contain geometry closer than the sphere.
207 // The epsilon prevents the object's own previous-frame depth from culling it.
208 return blocker >= 0.9999 || frontZ <= blocker + 0.002;
209}
210
211@compute @workgroup_size(64)
212fn cs_main(@builtin(global_invocation_id) gid: vec3u) {
213 let index = gid.x;
214 if (index >= params.counts.x) { return; }
215 let input = inputs[index];
216 let center = (input.model * vec4f(input.bounds.xyz, 1.0)).xyz;
217 let scale = max(length(input.model[0].xyz),
218 max(length(input.model[1].xyz), length(input.model[2].xyz)));
219 let radius = input.bounds.w * scale;
220 for (var p = 0u; p < 6u; p = p + 1u) {
221 let plane = params.planes[p];
222 if (dot(plane.xyz, center) + plane.w < -radius) { return; }
223 }
224 if (!remainsVisibleAgainstDepth(center, radius)) { return; }
225 let local = atomicAdd(&commands[input.bucket].instanceCount, 1u);
226 atomicAdd(&visCommands[input.bucket].instanceCount, 1u);
227 var visible: VisibleInstance;
228 visible.model = input.model;
229 visible.meshId = 0u;
230 visible.materialId = 0u;
231 visible.flags = 0u;
232 visible.lodGroupId = 0u;
233 visible.reflectionProbeSlots = vec4u(0u);
234 visible.reflectionProbeCenter[0] = vec4f(0.0);
235 visible.reflectionProbeCenter[1] = vec4f(0.0);
236 visible.reflectionProbeExtent[0] = vec4f(0.0);
237 visible.reflectionProbeExtent[1] = vec4f(0.0);
238 visible.color = input.color;
239 visible.terrainWave = input.terrainWave;
240 visible.terrainWaveTint = input.terrainWaveTint;
241 visibleInstances[input.outputBase + local] = visible;
242}
243)wgsl";
244
245constexpr const char* kGpuDrivenVertWgsl = R"wgsl(
246struct Light3D { posRadius: vec4f, color: vec4f };
247struct Frame {
248 mvp: mat4x4f,
249 model: mat4x4f,
250 lightDir: vec4f,
251 lightColor: vec4f,
252 tint: vec4f,
253 cameraPos: vec4f,
254 ambient: vec4f,
255 lights: array<Light3D, 8>,
256 texBomb: vec4f,
257 parallax: vec4f,
258 surface: vec4f,
259 view: mat4x4f,
260 clipInfo: vec4f,
261 cloud: vec4f,
262 cloudWind: vec4f,
263};
264struct VSIn {
265 @location(0) pos: vec3f,
266 @location(1) normal: vec3f,
267 @location(2) uv: vec2f,
268};
269struct VSOut {
270 @builtin(position) pos: vec4f,
271 @location(0) vNormal: vec3f,
272 @location(1) vUV: vec2f,
273 @location(2) vTint: vec4f,
274 @location(3) vWorldPos: vec3f,
275 @location(4) vCameraPos: vec3f,
276 @location(5) vViewPos: vec3f,
277};
278@group(0) @binding(0) var<uniform> ubo: Frame;
279struct VisibleInstance {
280 model: mat4x4f,
281 meshId: u32,
282 materialId: u32,
283 flags: u32,
284 lodGroupId: u32,
285 reflectionProbeSlots: vec4u,
286 reflectionProbeCenter: array<vec4f, 2>,
287 reflectionProbeExtent: array<vec4f, 2>,
288 color: vec4f,
289 terrainWave: vec4f,
290 terrainWaveTint: vec4f,
291};
292@group(1) @binding(0) var<storage, read> visibleInstances: array<VisibleInstance>;
293
294fn inverse3x3(m: mat3x3f) -> mat3x3f {
295 let a = m[0].x; let b = m[1].x; let c = m[2].x;
296 let d = m[0].y; let e = m[1].y; let f = m[2].y;
297 let g = m[0].z; let h = m[1].z; let i = m[2].z;
298 let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
299 return mat3x3f(
300 vec3f((e * i - f * h) / det, (f * g - d * i) / det, (d * h - e * g) / det),
301 vec3f((c * h - b * i) / det, (a * i - c * g) / det, (b * g - a * h) / det),
302 vec3f((b * f - c * e) / det, (c * d - a * f) / det, (a * e - b * d) / det));
303}
304
305fn terrainFastSinCos(value: vec4f) -> vec4f {
306 var x = fract(value * 0.15915494309189535);
307 x = x * 2.0 - 1.0;
308 let x2 = x * x;
309 let sine = x * (7.61 - 35.2 * x2) / (1.0 + x2 * (11.2 + 3.6 * x2));
310 return sine * sine;
311}
312
313fn terrainDetailWave(worldPosition: ptr<function, vec3f>, heightMask: f32,
314 terrainWave: vec4f, terrainWaveTint: vec4f) -> vec3f {
315 if (terrainWave.w < 0.5) { return vec3f(1.0); }
316 let waveXSize = vec4f(0.012, 0.02, 0.06, 0.024) * terrainWave.y;
317 let waveZSize = vec4f(0.006, 0.02, 0.02, 0.05) * terrainWave.y;
318 var waves = (*worldPosition).x * waveXSize + (*worldPosition).z * waveZSize;
319 waves += terrainWave.x * vec4f(0.3, 0.5, 0.4, 1.2) * 4.0;
320 waves = terrainFastSinCos(waves);
321 let lighting = dot(waves, vec4f(0.6742, 0.6742, 0.2697, 0.1349)) * 0.7;
322 let displacement = vec2f(dot(waves, vec4f(0.024, 0.04, -0.12, 0.096)),
323 dot(waves, vec4f(0.006, 0.02, -0.02, 0.1))) * heightMask;
324 let offset = displacement * terrainWave.z;
325 *worldPosition = vec3f((*worldPosition).x - offset.x, (*worldPosition).y,
326 (*worldPosition).z - offset.y);
327 return 2.0 * mix(vec3f(0.5), terrainWaveTint.rgb, vec3f(lighting));
328}
329
330@vertex
331fn vs_main(in: VSIn, @builtin(instance_index) instanceIndex: u32) -> VSOut {
332 let sourceModel = visibleInstances[instanceIndex].model;
333 let instanceColor = visibleInstances[instanceIndex].color;
334 let terrainWave = visibleInstances[instanceIndex].terrainWave;
335 let terrainWaveTint = visibleInstances[instanceIndex].terrainWaveTint;
336 var model = sourceModel;
337 if (ubo.surface.w > 0.5) {
338 let origin = sourceModel[3].xyz;
339 var forward = vec3f(ubo.cameraPos.x - origin.x, 0.0, ubo.cameraPos.z - origin.z);
340 forward = select(vec3f(0, 0, 1), normalize(forward), length(forward) > 1e-6);
341 let right = vec3f(forward.z, 0, -forward.x);
342 model = mat4x4f(vec4f(right * length(sourceModel[0].xyz), 0),
343 vec4f(0, length(sourceModel[1].xyz), 0, 0),
344 vec4f(forward * length(sourceModel[2].xyz), 0), sourceModel[3]);
345 }
346 var worldPosition = (model * vec4f(in.pos, 1.0)).xyz;
347 let waveTint = terrainDetailWave(&worldPosition, in.uv.y, terrainWave, terrainWaveTint);
348 let world = vec4f(worldPosition, 1.0);
349 var out: VSOut;
350 out.pos = ubo.mvp * world;
351 out.pos.y = -out.pos.y;
352 out.vWorldPos = world.xyz;
353 out.vViewPos = (ubo.view * world).xyz;
354 let normalMatrix = transpose(inverse3x3(mat3x3f(model[0].xyz, model[1].xyz,
355 model[2].xyz)));
356 out.vNormal = normalize(normalMatrix * in.normal);
357 out.vUV = in.uv;
358 out.vTint = ubo.tint * instanceColor * vec4f(waveTint, 1.0);
359 out.vCameraPos = ubo.cameraPos.xyz;
360 return out;
361}
362)wgsl";
363
364uint64_t grownCapacity(uint64_t current, uint64_t required) {
365 uint64_t value = std::max<uint64_t>(current, 256);
366 while (value < required) value *= 2;
367 return value;
368}
369
370} // namespace
371
373 if (!mesh || !mesh->gpuHandle) return kInvalidGpuDrivenSlot;
374 auto found = gpuDrivenMeshIds_.find(mesh);
375 if (found != gpuDrivenMeshIds_.end()) return found->second;
376 const uint32_t id = static_cast<uint32_t>(gpuDrivenMeshes_.size());
377 gpuDrivenMeshes_.push_back(mesh);
378 gpuDrivenMeshIds_.emplace(mesh, id);
379 return id;
380}
381
384 auto found = gpuDrivenMaterialIds_.find(material);
385 if (found != gpuDrivenMaterialIds_.end()) return found->second;
386 uint32_t id = 0;
387 if (!gpuDrivenMaterialFree_.empty()) {
388 id = gpuDrivenMaterialFree_.back();
389 gpuDrivenMaterialFree_.pop_back();
390 gpuDrivenMaterials_[id] = material;
391 } else {
392 id = static_cast<uint32_t>(gpuDrivenMaterials_.size());
393 gpuDrivenMaterials_.push_back(material);
394 }
395 gpuDrivenMaterialIds_.emplace(material, id);
396 return id;
397}
398
400 if (!material || material->virtualTextureMode() == MaterialVirtualTextureMode::AtlasPageTable) return false;
401 if (material->surfaceMode() == SurfaceMode::Transparent || material->hasPbrSurface() ||
402 material->effectiveShader() != nullptr || material->isTransparentHair())
403 return false;
404 return material->getShadingModel() == "pbr" && material->getReceiveLight();
405}
406
408 if (!material)
410 "cannot release a null GPU-driven material"));
411 const auto found = gpuDrivenMaterialIds_.find(material);
412 if (found == gpuDrivenMaterialIds_.end()) return Result<void>::success();
413 const uint32_t slot = found->second;
414 gpuDrivenMaterialIds_.erase(found);
415 gpuDrivenMaterials_[slot] = nullptr;
416 gpuDrivenMaterialFree_.push_back(slot);
417 return Result<void>::success();
418}
419
421 if (!gpuDrivenEnabled_ || !device || gpuDrivenComputePending_ || gpuDrivenDrawPending_ || !instances ||
422 instanceCount == 0)
423 return false;
424 using BucketKey = std::pair<uint32_t, uint32_t>;
425 std::map<BucketKey, std::vector<const GpuInstance*>> grouped;
426 for (uint32_t i = 0; i < instanceCount; ++i) {
427 const GpuInstance& instance = instances[i];
428 if (instance.meshId >= gpuDrivenMeshes_.size() || instance.materialId >= gpuDrivenMaterials_.size())
429 return false;
430 Mesh* mesh = gpuDrivenMeshes_[instance.meshId];
431 Material* material = gpuDrivenMaterials_[instance.materialId];
432 if (!mesh || !mesh->gpuHandle || !material || !gpuDrivenMaterialUsable(material)) return false;
433 grouped[{instance.meshId, instance.materialId}].push_back(&instance);
434 }
435
436 const uint32_t paddedCount = std::accumulate(
437 grouped.begin(), grouped.end(), 0u, [](uint32_t count, const auto& entry) {
438 return count + ((static_cast<uint32_t>(entry.second.size()) + 15u) & ~uint32_t(15u));
439 });
440 ensureGpuDrivenResources(paddedCount, static_cast<uint32_t>(grouped.size()));
441 if (!gpuDrivenRenderPipeline_ || !gpuDrivenVisibleBuffer_ || !gpuDrivenIndirectBuffer_) return false;
442
443 std::vector<VisibleInstance> visible(paddedCount);
444 std::vector<GpuIndirectCommand> commands;
445 commands.reserve(grouped.size());
446 gpuDrivenBuckets_.clear();
447 uint32_t outputBase = 0;
448 for (const auto& [key, bucketInstances] : grouped) {
449 Mesh* mesh = gpuDrivenMeshes_[key.first];
450 Material* material = gpuDrivenMaterials_[key.second];
451 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
452 auto bound = material->bind(*this);
453 if (!bound) throw Exception("%s", bound.error()->message().c_str());
454 GpuIndirectCommand command{};
455 command.indexCount = gpu->indexCount;
456 command.instanceCount = static_cast<uint32_t>(bucketInstances.size());
457 commands.push_back(command);
458 gpuDrivenBuckets_.push_back(
459 {mesh, material, outputBase, static_cast<uint32_t>(bucketInstances.size())});
460 for (uint32_t i = 0; i < bucketInstances.size(); ++i) {
461 const GpuInstance& source = *bucketInstances[i];
463 }
464 outputBase += (static_cast<uint32_t>(bucketInstances.size()) + 15u) & ~uint32_t(15u);
465 }
466 queue.WriteBuffer(gpuDrivenVisibleBuffer_, 0, visible.data(), visible.size() * sizeof(VisibleInstance));
467 queue.WriteBuffer(gpuDrivenIndirectBuffer_, 0, commands.data(), commands.size() * sizeof(GpuIndirectCommand));
468 gpuDrivenDrawPending_ = true;
469 frameHad3DThisFrame = true;
470 frameHad3D = true;
471 return true;
472}
473
475 if (!gpuDrivenEnabled_ || !device || gpuDrivenComputePending_ || gpuDrivenDrawPending_)
479 batch.buffer.strideBytes != sizeof(GpuInstance) || !batch.buckets || batch.bucketCount == 0 ||
480 batch.instanceCount == 0)
482 const uint64_t required = batch.buffer.offsetBytes + uint64_t(batch.instanceCount) * sizeof(GpuInstance);
483 if (required < batch.buffer.offsetBytes || required > batch.buffer.sizeBytes)
485
486 std::vector<GpuIndirectCommand> commands(batch.bucketCount);
487 std::vector<GpuDrivenBucket> buckets(batch.bucketCount);
488 uint64_t coveredInstances = 0;
489 for (uint32_t i = 0; i < batch.bucketCount; ++i) {
490 const GpuResidentInstanceBucket& bucket = batch.buckets[i];
491 const uint64_t end = uint64_t(bucket.firstInstance) + bucket.instanceCount;
492 if (bucket.instanceCount == 0 || bucket.firstInstance != coveredInstances || end > batch.instanceCount ||
493 bucket.meshId >= gpuDrivenMeshes_.size() || bucket.materialId >= gpuDrivenMaterials_.size())
495 Mesh* mesh = gpuDrivenMeshes_[bucket.meshId];
496 Material* material = gpuDrivenMaterials_[bucket.materialId];
497 if (!mesh || !mesh->gpuHandle || !gpuDrivenMaterialUsable(material))
499 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
500 commands[i] = {gpu->indexCount, bucket.instanceCount, 0, 0, bucket.firstInstance};
501 buckets[i] = {mesh, material, bucket.firstInstance, bucket.instanceCount};
502 coveredInstances = end;
503 }
504 if (coveredInstances != batch.instanceCount) return GpuResidentSubmitStatus::InvalidArgument;
505
506 ensureGpuDrivenResources(batch.instanceCount, batch.bucketCount);
507 if (!gpuDrivenResidentRenderPipeline_ || !gpuDrivenIndirectBuffer_)
509 queue.WriteBuffer(gpuDrivenIndirectBuffer_, 0, commands.data(), commands.size() * sizeof(GpuIndirectCommand));
510 WGPUBuffer rawBuffer{};
511 static_assert(sizeof(rawBuffer) <= sizeof(batch.buffer.nativeHandle));
512 std::memcpy(&rawBuffer, &batch.buffer.nativeHandle, sizeof(rawBuffer));
514 gpuDrivenBuckets_ = std::move(buckets);
515 gpuDrivenResidentBuffer_ = rawBuffer;
516 gpuDrivenResidentOffset_ = batch.buffer.offsetBytes;
517 gpuDrivenResidentSize_ = uint64_t(batch.instanceCount) * sizeof(GpuInstance);
518 gpuDrivenResidentDrawPending_ = true;
519 gpuDrivenDrawPending_ = true;
520 frameHad3DThisFrame = true;
521 frameHad3D = true;
523}
524
525void Graphics::ensureGpuDrivenResources(uint32_t instanceCount, uint32_t bucketCount) {
526 if (!gpuDrivenCullPipeline_) {
527 WGPUBindGroupLayoutEntry computeEntries[6]{};
528 computeEntries[0].binding = 0;
529 computeEntries[0].visibility = WGPUShaderStage_Compute;
530 computeEntries[0].buffer.type = WGPUBufferBindingType_Uniform;
531 computeEntries[0].buffer.minBindingSize = sizeof(CullParams);
532 for (uint32_t i = 1; i < 5; ++i) {
533 computeEntries[i].binding = i;
534 computeEntries[i].visibility = WGPUShaderStage_Compute;
535 computeEntries[i].buffer.type =
536 i == 1 ? WGPUBufferBindingType_ReadOnlyStorage : WGPUBufferBindingType_Storage;
537 }
538 computeEntries[1].buffer.minBindingSize = sizeof(CullInput);
539 computeEntries[2].buffer.minBindingSize = sizeof(VisibleInstance);
540 computeEntries[3].buffer.minBindingSize = sizeof(uint32_t) * 5;
541 computeEntries[4].buffer.minBindingSize = sizeof(VisIndirectCommand);
542 WGPUBindGroupLayoutDescriptor cbgl{};
543 cbgl.label = label("eve_gpu_driven_compute_bgl");
544 computeEntries[5].binding = 5;
545 computeEntries[5].visibility = WGPUShaderStage_Compute;
546 computeEntries[5].buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
547 cbgl.entryCount = 6;
548 cbgl.entries = computeEntries;
549 gpuDrivenComputeSetLayout_ =
550 device.CreateBindGroupLayout(reinterpret_cast<const wgpu::BindGroupLayoutDescriptor*>(&cbgl));
551
552 WGPUBindGroupLayoutEntry renderEntry{};
553 renderEntry.binding = 0;
554 renderEntry.visibility = WGPUShaderStage_Vertex;
555 renderEntry.buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
556 renderEntry.buffer.minBindingSize = sizeof(VisibleInstance);
557 WGPUBindGroupLayoutDescriptor rbgl{};
558 rbgl.label = label("eve_gpu_driven_render_bgl");
559 rbgl.entryCount = 1;
560 rbgl.entries = &renderEntry;
561 gpuDrivenRenderSetLayout_ =
562 device.CreateBindGroupLayout(reinterpret_cast<const wgpu::BindGroupLayoutDescriptor*>(&rbgl));
563
564 WGPUBindGroupLayout computeLayout = gpuDrivenComputeSetLayout_.Get();
565 WGPUPipelineLayoutDescriptor cpl{};
566 cpl.label = label("eve_gpu_driven_compute_layout");
567 cpl.bindGroupLayoutCount = 1;
568 cpl.bindGroupLayouts = &computeLayout;
569 gpuDrivenComputePipelineLayout_ =
570 device.CreatePipelineLayout(reinterpret_cast<const wgpu::PipelineLayoutDescriptor*>(&cpl));
571
572 WGPUBindGroupLayout renderLayouts[2] = {mesh3dSetLayout.Get(), gpuDrivenRenderSetLayout_.Get()};
573 WGPUPipelineLayoutDescriptor rpl{};
574 rpl.label = label("eve_gpu_driven_render_layout");
575 rpl.bindGroupLayoutCount = 2;
576 rpl.bindGroupLayouts = renderLayouts;
577 gpuDrivenRenderPipelineLayout_ =
578 device.CreatePipelineLayout(reinterpret_cast<const wgpu::PipelineLayoutDescriptor*>(&rpl));
579
580 wgpu::ShaderModule cullModule = shaderModule(device, kCullWgsl);
581 WGPUComputePipelineDescriptor cpd{};
582 cpd.label = label("eve_gpu_driven_cull");
583 cpd.layout = gpuDrivenComputePipelineLayout_.Get();
584 cpd.compute.module = cullModule.Get();
585 cpd.compute.entryPoint = label("cs_main");
586 gpuDrivenCullPipeline_ =
587 device.CreateComputePipeline(reinterpret_cast<const wgpu::ComputePipelineDescriptor*>(&cpd));
588
589 WGPUBindGroupLayoutEntry hzbEntries[3]{};
590 hzbEntries[0].binding = 0;
591 hzbEntries[0].visibility = WGPUShaderStage_Compute;
592 hzbEntries[0].buffer.type = WGPUBufferBindingType_Uniform;
593 hzbEntries[0].buffer.hasDynamicOffset = true;
594 hzbEntries[0].buffer.minBindingSize = sizeof(HzbBuildParams);
595 hzbEntries[1].binding = 1;
596 hzbEntries[1].visibility = WGPUShaderStage_Compute;
597 hzbEntries[1].texture.sampleType = WGPUTextureSampleType_Depth;
598 hzbEntries[1].texture.viewDimension = WGPUTextureViewDimension_2D;
599 hzbEntries[2].binding = 2;
600 hzbEntries[2].visibility = WGPUShaderStage_Compute;
601 hzbEntries[2].buffer.type = WGPUBufferBindingType_Storage;
602 WGPUBindGroupLayoutDescriptor hzbBgl{};
603 hzbBgl.label = label("eve_gpu_driven_hzb_bgl");
604 hzbBgl.entryCount = 3;
605 hzbBgl.entries = hzbEntries;
606 gpuDrivenHzbSetLayout_ =
607 device.CreateBindGroupLayout(reinterpret_cast<const wgpu::BindGroupLayoutDescriptor*>(&hzbBgl));
608 WGPUBindGroupLayout hzbLayout = gpuDrivenHzbSetLayout_.Get();
609 WGPUPipelineLayoutDescriptor hzbPl{};
610 hzbPl.bindGroupLayoutCount = 1;
611 hzbPl.bindGroupLayouts = &hzbLayout;
612 gpuDrivenHzbPipelineLayout_ =
613 device.CreatePipelineLayout(reinterpret_cast<const wgpu::PipelineLayoutDescriptor*>(&hzbPl));
614 wgpu::ShaderModule hzbModule = shaderModule(device, kHzbBuildWgsl);
615 WGPUComputePipelineDescriptor hzbPd{};
616 hzbPd.label = label("eve_gpu_driven_hzb_build");
617 hzbPd.layout = gpuDrivenHzbPipelineLayout_.Get();
618 hzbPd.compute.module = hzbModule.Get();
619 hzbPd.compute.entryPoint = label("cs_main");
620 gpuDrivenHzbPipeline_ =
621 device.CreateComputePipeline(reinterpret_cast<const wgpu::ComputePipelineDescriptor*>(&hzbPd));
622
623 WGPUVertexAttribute attrs[3]{};
624 attrs[0].format = WGPUVertexFormat_Float32x3;
625 attrs[0].offset = 0;
626 attrs[0].shaderLocation = 0;
627 attrs[1].format = WGPUVertexFormat_Float32x3;
628 attrs[1].offset = 12;
629 attrs[1].shaderLocation = 1;
630 attrs[2].format = WGPUVertexFormat_Float32x2;
631 attrs[2].offset = 24;
632 attrs[2].shaderLocation = 2;
633 WGPUVertexBufferLayout vb{};
634 vb.arrayStride = 32;
635 vb.stepMode = WGPUVertexStepMode_Vertex;
636 vb.attributeCount = 3;
637 vb.attributes = attrs;
638 WGPUDepthStencilState depth{};
639 depth.format = WGPUTextureFormat_Depth32Float;
640 depth.depthWriteEnabled = WGPUOptionalBool_True;
641 depth.depthCompare = WGPUCompareFunction_Less;
642 WGPUColorTargetState target{};
643 target.format = sceneColorFormat;
644 target.writeMask = WGPUColorWriteMask_All;
645 wgpu::ShaderModule vertModule = shaderModule(device, kGpuDrivenVertWgsl);
646 std::string residentVertSource = kGpuDrivenVertWgsl;
647 const std::string modelsDecl =
648 "struct VisibleInstance {\n"
649 " model: mat4x4f,\n"
650 " meshId: u32,\n"
651 " materialId: u32,\n"
652 " flags: u32,\n"
653 " lodGroupId: u32,\n"
654 " reflectionProbeSlots: vec4u,\n"
655 " reflectionProbeCenter: array<vec4f, 2>,\n"
656 " reflectionProbeExtent: array<vec4f, 2>,\n"
657 " color: vec4f,\n"
658 " terrainWave: vec4f,\n"
659 " terrainWaveTint: vec4f,\n"
660 "};\n"
661 "@group(1) @binding(0) var<storage, read> visibleInstances: array<VisibleInstance>;";
662 const std::string residentDecl =
663 "struct ResidentInstance { model: mat4x4f, meshId: u32, materialId: u32, "
664 "flags: u32, lodGroupId: u32, reflectionProbeSlots: vec4u, "
665 "reflectionProbeCenter: array<vec4f, 2>, reflectionProbeExtent: array<vec4f, 2>, color: vec4f, "
666 "terrainWave: vec4f, terrainWaveTint: vec4f };\n"
667 "@group(1) @binding(0) var<storage, read> residentInstances: "
668 "array<ResidentInstance>;";
669 residentVertSource.replace(residentVertSource.find(modelsDecl), modelsDecl.size(), residentDecl);
670 const std::string modelRead =
671 "let sourceModel = visibleInstances[instanceIndex].model;\n"
672 " let instanceColor = visibleInstances[instanceIndex].color;\n"
673 " let terrainWave = visibleInstances[instanceIndex].terrainWave;\n"
674 " let terrainWaveTint = visibleInstances[instanceIndex].terrainWaveTint;";
675 residentVertSource.replace(residentVertSource.find(modelRead), modelRead.size(),
676 "let sourceModel = residentInstances[instanceIndex].model;\n"
677 " let instanceColor = residentInstances[instanceIndex].color;\n"
678 " let terrainWave = residentInstances[instanceIndex].terrainWave;\n"
679 " let terrainWaveTint = residentInstances[instanceIndex].terrainWaveTint;");
680 wgpu::ShaderModule residentVertModule = shaderModule(device, residentVertSource);
681 wgpu::ShaderModule fragModule = shaderModule(device, kMesh3DFragWgsl);
682 WGPUFragmentState fs{};
683 fs.module = fragModule.Get();
684 fs.entryPoint = label("fs_main");
685 fs.targetCount = 1;
686 fs.targets = &target;
687 WGPURenderPipelineDescriptor rpd{};
688 rpd.label = label("eve_gpu_driven_render");
689 rpd.layout = gpuDrivenRenderPipelineLayout_.Get();
690 rpd.vertex.module = vertModule.Get();
691 rpd.vertex.entryPoint = label("vs_main");
692 rpd.vertex.bufferCount = 1;
693 rpd.vertex.buffers = &vb;
694 rpd.fragment = &fs;
695 rpd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
696 rpd.primitive.frontFace = WGPUFrontFace_CW;
697 rpd.primitive.cullMode = WGPUCullMode_None;
698 rpd.depthStencil = &depth;
699 rpd.multisample.count = sceneColorSamples;
700 rpd.multisample.mask = 0xFFFFFFFFu;
701 gpuDrivenRenderPipeline_ =
702 device.CreateRenderPipeline(reinterpret_cast<const wgpu::RenderPipelineDescriptor*>(&rpd));
703 rpd.label = label("eve_gpu_driven_resident_render");
704 rpd.vertex.module = residentVertModule.Get();
705 gpuDrivenResidentRenderPipeline_ =
706 device.CreateRenderPipeline(reinterpret_cast<const wgpu::RenderPipelineDescriptor*>(&rpd));
707 rpd.label = label("eve_gpu_driven_canvas");
708 rpd.vertex.module = vertModule.Get();
709 target.format = WGPUTextureFormat_RGBA8Unorm;
710 rpd.multisample.count = 1;
711 gpuDrivenCanvasPipeline_ =
712 device.CreateRenderPipeline(reinterpret_cast<const wgpu::RenderPipelineDescriptor*>(&rpd));
713 rpd.label = label("eve_gpu_driven_resident_canvas");
714 rpd.vertex.module = residentVertModule.Get();
715 gpuDrivenResidentCanvasPipeline_ =
716 device.CreateRenderPipeline(reinterpret_cast<const wgpu::RenderPipelineDescriptor*>(&rpd));
717 rpd.label = label("eve_gpu_driven_hdr_canvas");
718 rpd.vertex.module = vertModule.Get();
719 target.format = WGPUTextureFormat_RGBA16Float;
720 gpuDrivenHdrCanvasPipeline_ =
721 device.CreateRenderPipeline(reinterpret_cast<const wgpu::RenderPipelineDescriptor*>(&rpd));
722 rpd.label = label("eve_gpu_driven_resident_hdr_canvas");
723 rpd.vertex.module = residentVertModule.Get();
724 gpuDrivenResidentHdrCanvasPipeline_ =
725 device.CreateRenderPipeline(reinterpret_cast<const wgpu::RenderPipelineDescriptor*>(&rpd));
726
727 WGPUBufferDescriptor pbd{};
728 pbd.label = label("eve_gpu_driven_params");
729 pbd.size = sizeof(CullParams);
730 pbd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform;
731 gpuDrivenParamsBuffer_ = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&pbd));
732 pbd.label = label("eve_gpu_driven_hzb_params");
733 pbd.size = kMaxHzbMips * 256u;
734 gpuDrivenHzbParamsBuffer_ = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&pbd));
735 }
736
737 bool recreateGroups = false;
738 const uint32_t hzbWidth = std::max(gbufferWidth, 1);
739 const uint32_t hzbHeight = std::max(gbufferHeight, 1);
740 if (!gpuDrivenHzbBuffer_ || gpuDrivenHzbWidth_ != hzbWidth || gpuDrivenHzbHeight_ != hzbHeight) {
741 gpuDrivenHzbWidth_ = hzbWidth;
742 gpuDrivenHzbHeight_ = hzbHeight;
743 gpuDrivenHzbOffsets_.clear();
744 uint32_t words = kHzbHeaderWords;
745 for (uint32_t w = hzbWidth, h = hzbHeight; gpuDrivenHzbOffsets_.size() < kMaxHzbMips;
746 w = std::max(w >> 1u, 1u), h = std::max(h >> 1u, 1u)) {
747 gpuDrivenHzbOffsets_.push_back(words - kHzbHeaderWords);
748 words += w * h;
749 if (w == 1 && h == 1) break;
750 }
751 WGPUBufferDescriptor hzbBd{};
752 hzbBd.label = label("eve_gpu_driven_hzb");
753 hzbBd.size = uint64_t(words) * sizeof(uint32_t);
754 gpuDrivenHzbCapacity_ = hzbBd.size;
755 hzbBd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage;
756 gpuDrivenHzbBuffer_ = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&hzbBd));
757 queue.WriteBuffer(gpuDrivenHzbBuffer_, 0, gpuDrivenHzbOffsets_.data(),
758 gpuDrivenHzbOffsets_.size() * sizeof(uint32_t));
759 recreateGroups = true;
760 }
761
762 const uint64_t inputBytes = uint64_t(instanceCount) * sizeof(CullInput);
763 if (!gpuDrivenInputBuffer_ || gpuDrivenInputCapacity_ < inputBytes) {
764 gpuDrivenInputCapacity_ = grownCapacity(gpuDrivenInputCapacity_, inputBytes);
765 WGPUBufferDescriptor bd{};
766 bd.label = label("eve_gpu_driven_inputs");
767 bd.size = gpuDrivenInputCapacity_;
768 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage;
769 gpuDrivenInputBuffer_ = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
770 recreateGroups = true;
771 }
772 const uint64_t visibleBytes = uint64_t(instanceCount) * sizeof(VisibleInstance);
773 if (!gpuDrivenVisibleBuffer_ || gpuDrivenVisibleCapacity_ < visibleBytes) {
774 gpuDrivenVisibleCapacity_ = grownCapacity(gpuDrivenVisibleCapacity_, visibleBytes);
775 WGPUBufferDescriptor bd{};
776 bd.label = label("eve_gpu_driven_visible");
777 bd.size = gpuDrivenVisibleCapacity_;
778 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage;
779 gpuDrivenVisibleBuffer_ = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
780 recreateGroups = true;
781 }
782 const uint64_t indirectBytes = uint64_t(bucketCount) * sizeof(GpuIndirectCommand);
783 if (!gpuDrivenIndirectBuffer_ || gpuDrivenIndirectCapacity_ < indirectBytes) {
784 gpuDrivenIndirectCapacity_ = grownCapacity(gpuDrivenIndirectCapacity_, indirectBytes);
785 WGPUBufferDescriptor bd{};
786 bd.label = label("eve_gpu_driven_indirect");
787 bd.size = gpuDrivenIndirectCapacity_;
788 bd.usage =
789 WGPUBufferUsage_CopyDst | WGPUBufferUsage_CopySrc | WGPUBufferUsage_Storage | WGPUBufferUsage_Indirect;
790 gpuDrivenIndirectBuffer_ = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
791 recreateGroups = true;
792 }
793 const uint64_t visIndirectBytes = uint64_t(bucketCount) * sizeof(VisIndirectCommand);
794 if (!gpuDrivenVisIndirectBuffer_ || gpuDrivenVisIndirectCapacity_ < visIndirectBytes) {
795 gpuDrivenVisIndirectCapacity_ = grownCapacity(gpuDrivenVisIndirectCapacity_, visIndirectBytes);
796 WGPUBufferDescriptor bd{};
797 bd.label = label("eve_gpu_driven_vis_indirect");
798 bd.size = gpuDrivenVisIndirectCapacity_;
799 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage | WGPUBufferUsage_Indirect;
800 gpuDrivenVisIndirectBuffer_ = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
801 recreateGroups = true;
802 }
803 // The previous-frame depth view rotates with the frame slot, so refresh
804 // the compute group even when the storage-buffer capacities are unchanged.
805 recreateGroups = true;
806 if (recreateGroups || !gpuDrivenComputeBindGroup_) {
807 WGPUBindGroupEntry entries[6]{};
808 entries[0].binding = 0;
809 entries[0].buffer = gpuDrivenParamsBuffer_.Get();
810 entries[0].size = sizeof(CullParams);
811 entries[1].binding = 1;
812 entries[1].buffer = gpuDrivenInputBuffer_.Get();
813 entries[1].size = gpuDrivenInputCapacity_;
814 entries[2].binding = 2;
815 entries[2].buffer = gpuDrivenVisibleBuffer_.Get();
816 entries[2].size = gpuDrivenVisibleCapacity_;
817 entries[3].binding = 3;
818 entries[3].buffer = gpuDrivenIndirectBuffer_.Get();
819 entries[3].size = gpuDrivenIndirectCapacity_;
820 entries[4].binding = 4;
821 entries[4].buffer = gpuDrivenVisIndirectBuffer_.Get();
822 entries[4].size = gpuDrivenVisIndirectCapacity_;
823 entries[5].binding = 5;
824 const uint32_t depthSlot = gbufferDepthValid_ ? lastGbufferSlot : currentFrameSlot();
825 entries[5].buffer = gpuDrivenHzbBuffer_.Get();
826 entries[5].size = gpuDrivenHzbCapacity_;
827 WGPUBindGroupDescriptor bgd{};
828 bgd.label = label("eve_gpu_driven_compute_bg");
829 bgd.layout = gpuDrivenComputeSetLayout_.Get();
830 bgd.entryCount = 6;
831 bgd.entries = entries;
832 gpuDrivenComputeBindGroup_ = device.CreateBindGroup(reinterpret_cast<const wgpu::BindGroupDescriptor*>(&bgd));
833
834 WGPUBindGroupEntry renderEntry{};
835 renderEntry.binding = 0;
836 renderEntry.buffer = gpuDrivenVisibleBuffer_.Get();
837 renderEntry.size = gpuDrivenVisibleCapacity_;
838 WGPUBindGroupDescriptor rbgd{};
839 rbgd.label = label("eve_gpu_driven_render_bg");
840 rbgd.layout = gpuDrivenRenderSetLayout_.Get();
841 rbgd.entryCount = 1;
842 rbgd.entries = &renderEntry;
843 gpuDrivenRenderBindGroup_ = device.CreateBindGroup(reinterpret_cast<const wgpu::BindGroupDescriptor*>(&rbgd));
844
845 WGPUBindGroupEntry hzbEntries[3]{};
846 hzbEntries[0].binding = 0;
847 hzbEntries[0].buffer = gpuDrivenHzbParamsBuffer_.Get();
848 hzbEntries[0].size = sizeof(HzbBuildParams);
849 hzbEntries[1].binding = 1;
850 hzbEntries[1].textureView = gbufferSlots[depthSlot].depthView.Get();
851 hzbEntries[2].binding = 2;
852 hzbEntries[2].buffer = gpuDrivenHzbBuffer_.Get();
853 hzbEntries[2].size = gpuDrivenHzbCapacity_;
854 WGPUBindGroupDescriptor hzbBg{};
855 hzbBg.label = label("eve_gpu_driven_hzb_bg");
856 hzbBg.layout = gpuDrivenHzbSetLayout_.Get();
857 hzbBg.entryCount = 3;
858 hzbBg.entries = hzbEntries;
859 gpuDrivenHzbBindGroup_ = device.CreateBindGroup(reinterpret_cast<const wgpu::BindGroupDescriptor*>(&hzbBg));
860 }
861}
862
864 if (!gpuDrivenEnabled_ || !instances || instanceCount == 0) return false;
865 for (uint32_t i = 0; i < instanceCount; ++i) {
866 if (instances[i].meshId >= gpuDrivenMeshes_.size()) return false;
867 auto* gpu = static_cast<GpuMesh*>(gpuDrivenMeshes_[instances[i].meshId]->gpuHandle);
868 if (!gpu || !gpu->indexBuffer) return false;
869 }
870 gpuDrivenPending_.assign(instances, instances + instanceCount);
871 gpuDrivenVisible_.clear();
872 gpuDrivenBuckets_.clear();
873 gpuDrivenComputePending_ = false;
874 gpuDrivenDrawPending_ = false;
875 return true;
876}
877
878void Graphics::gpuDrivenCullEmit(const glm::mat4& viewProj, const glm::vec3& eye, float fovYDeg, float nearZ,
879 float farZ) {
880 if (sceneColorWidth > 0 && sceneColorHeight > 0) createSceneColorResources(sceneColorWidth, sceneColorHeight);
881 if (gbufferSlots.empty() && sceneColorWidth > 0 && sceneColorHeight > 0)
882 createGbufferResources(sceneColorWidth, sceneColorHeight);
883 CullParams params{};
884 params.viewProj = viewProj;
885 params.planes[0] = glm::row(viewProj, 3) + glm::row(viewProj, 0);
886 params.planes[1] = glm::row(viewProj, 3) - glm::row(viewProj, 0);
887 params.planes[2] = glm::row(viewProj, 3) + glm::row(viewProj, 1);
888 params.planes[3] = glm::row(viewProj, 3) - glm::row(viewProj, 1);
889 params.planes[4] = glm::row(viewProj, 2);
890 params.planes[5] = glm::row(viewProj, 3) - glm::row(viewProj, 2);
891 for (glm::vec4& plane : params.planes) {
892 const float length = glm::length(glm::vec3(plane));
893 if (length > 1e-6f) plane /= length;
894 }
895 params.cameraPos = glm::vec4(eye, 1.f);
896 params.screen =
897 glm::vec4(float(gbufferWidth), float(gbufferHeight), gbufferWidth > 0 ? 1.f / float(gbufferWidth) : 0.f,
898 gbufferHeight > 0 ? 1.f / float(gbufferHeight) : 0.f);
899 const float projScaleY = float(gbufferHeight) / (2.f * std::tan(glm::radians(fovYDeg) * 0.5f));
900 params.clipNearFar = glm::vec4(nearZ, farZ, projScaleY, gbufferDepthValid_ ? 1.f : 0.f);
901 params.hzbInfo =
902 glm::vec4(float(gpuDrivenHzbOffsets_.size() - 1u), 0.f, float(gpuDrivenHzbWidth_), float(gpuDrivenHzbHeight_));
903 uint32_t mipWidth = gpuDrivenHzbWidth_;
904 uint32_t mipHeight = gpuDrivenHzbHeight_;
905 uint32_t previousWidth = mipWidth;
906 uint32_t previousHeight = mipHeight;
907 for (uint32_t mip = 0; mip < gpuDrivenHzbOffsets_.size(); ++mip) {
908 HzbBuildParams build{};
909 build.info = glm::uvec4(mip, mipWidth, mipHeight, mip == 0 ? 0u : gpuDrivenHzbOffsets_[mip - 1]);
910 build.source = glm::uvec4(previousWidth, previousHeight, 0u, 0u);
911 queue.WriteBuffer(gpuDrivenHzbParamsBuffer_, uint64_t(mip) * 256u, &build, sizeof(build));
912 previousWidth = mipWidth;
913 previousHeight = mipHeight;
914 mipWidth = std::max(mipWidth >> 1u, 1u);
915 mipHeight = std::max(mipHeight >> 1u, 1u);
916 }
917
918 using BucketKey = std::pair<uint32_t, uint32_t>;
919 std::map<BucketKey, std::vector<const GpuInstance*>> grouped;
920 for (const GpuInstance& instance : gpuDrivenPending_)
921 grouped[{instance.meshId, instance.materialId}].push_back(&instance);
922
923 std::vector<CullInput> inputs;
924 std::vector<GpuIndirectCommand> commands;
925 std::vector<VisIndirectCommand> visCommands;
926 inputs.reserve(gpuDrivenPending_.size());
927 commands.reserve(grouped.size());
928 visCommands.reserve(grouped.size());
929 uint32_t outputBase = 0;
930 for (const auto& [key, bucketInstances] : grouped) {
931 Mesh* mesh = gpuDrivenMeshes_[key.first];
932 Material* material = gpuDrivenMaterials_[key.second];
933 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
934 const uint32_t bucketIndex = static_cast<uint32_t>(gpuDrivenBuckets_.size());
935 gpuDrivenBuckets_.push_back({mesh, material, outputBase, static_cast<uint32_t>(bucketInstances.size())});
936 GpuIndirectCommand command{};
937 command.indexCount = gpu->indexCount;
938 // Keep firstInstance zero: it is optional in WebGPU and requires the
939 // IndirectFirstInstance feature on adapters that expose it. The
940 // bucket's compacted model range is selected through the storage
941 // binding offset when drawing.
942 command.firstInstance = 0;
943 commands.push_back(command);
944 VisIndirectCommand visCommand{};
945 visCommand.vertexCount = gpu->indexCount;
946 visCommand.firstInstance = 0;
947 visCommands.push_back(visCommand);
948 for (const GpuInstance* instance : bucketInstances) {
949 CullInput input{};
950 input.model = instance->model;
951 input.color = instance->color;
952 input.terrainWave = instance->terrainWave;
953 input.terrainWaveTint = instance->terrainWaveTint;
954 input.bounds = mesh->hasBounds()
955 ? glm::vec4(mesh->boundsCx, mesh->boundsCy, mesh->boundsCz, mesh->boundsRadius)
956 : glm::vec4(0.f, 0.f, 0.f, 1e20f);
957 input.bucket = bucketIndex;
958 input.outputBase = outputBase;
959 inputs.push_back(input);
960
961 const glm::vec3 center = glm::vec3(input.model * glm::vec4(glm::vec3(input.bounds), 1.f));
962 const float scale =
963 std::max({glm::length(glm::vec3(input.model[0])), glm::length(glm::vec3(input.model[1])),
964 glm::length(glm::vec3(input.model[2]))});
965 bool visible = true;
966 for (const glm::vec4& plane : params.planes) {
967 if (glm::dot(glm::vec3(plane), center) + plane.w < -input.bounds.w * scale) {
968 visible = false;
969 break;
970 }
971 }
972 if (visible) gpuDrivenVisible_.push_back(*instance);
973 }
974 // Storage-buffer binding offsets are aligned to WebGPU's common
975 // 256-byte limit. Sixteen 208-byte records advance by 3328 bytes,
976 // keeping every bucket offset aligned.
977 outputBase += (static_cast<uint32_t>(bucketInstances.size()) + 15u) & ~uint32_t(15u);
978 }
979
980 ensureGpuDrivenResources(outputBase, static_cast<uint32_t>(commands.size()));
981 params.counts.x = static_cast<uint32_t>(inputs.size());
982 queue.WriteBuffer(gpuDrivenParamsBuffer_, 0, &params, sizeof(params));
983 queue.WriteBuffer(gpuDrivenInputBuffer_, 0, inputs.data(), inputs.size() * sizeof(CullInput));
984 queue.WriteBuffer(gpuDrivenIndirectBuffer_, 0, commands.data(), commands.size() * sizeof(GpuIndirectCommand));
985 queue.WriteBuffer(gpuDrivenVisIndirectBuffer_, 0, visCommands.data(),
986 visCommands.size() * sizeof(VisIndirectCommand));
987 gpuDrivenDispatchCount_ = static_cast<uint32_t>(inputs.size());
988 gpuDrivenLastBucketCount_ = static_cast<uint32_t>(commands.size());
989 gpuDrivenComputePending_ = !inputs.empty() && !commands.empty();
990}
991
993#if defined(__EMSCRIPTEN__)
994 return static_cast<uint32_t>(gpuDrivenVisible_.size());
995#else
996 if (!gpuDrivenIndirectBuffer_ || gpuDrivenLastBucketCount_ == 0) return 0;
997 const uint64_t size = uint64_t(gpuDrivenLastBucketCount_) * sizeof(GpuIndirectCommand);
998 WGPUBufferDescriptor bd{};
999 bd.label = label("eve_gpu_driven_debug_readback");
1000 bd.size = size;
1001 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
1002 wgpu::Buffer dst = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
1003 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
1004 encoder.CopyBufferToBuffer(gpuDrivenIndirectBuffer_, 0, dst, 0, size);
1005 wgpu::CommandBuffer command = encoder.Finish();
1006 queue.Submit(1, &command);
1007
1008 struct MapState {
1009 bool ok = false;
1010 } state;
1011 WGPUBufferMapCallbackInfo callback{};
1012 callback.mode = WGPUCallbackMode_WaitAnyOnly;
1013 callback.callback = [](WGPUMapAsyncStatus status, WGPUStringView, void* userdata1, void*) {
1014 static_cast<MapState*>(userdata1)->ok = status == WGPUMapAsyncStatus_Success;
1015 };
1016 callback.userdata1 = &state;
1017 WGPUFuture future = wgpuBufferMapAsync(dst.Get(), WGPUMapMode_Read, 0, size, callback);
1018 WGPUFutureWaitInfo wait{};
1019 wait.future = future;
1020 (void)wgpuInstanceWaitAny(instance.Get(), 1, &wait, UINT64_MAX);
1021 if (!state.ok) return 0;
1022 const auto* commands = static_cast<const GpuIndirectCommand*>(dst.GetConstMappedRange(0, size));
1023 uint32_t visible = 0;
1024 if (commands) {
1025 for (uint32_t i = 0; i < gpuDrivenLastBucketCount_; ++i) visible += commands[i].instanceCount;
1026 }
1027 dst.Unmap();
1028 return visible;
1029#endif
1030}
1031
1033 if (!gpuDrivenComputePending_ || gpuDrivenBuckets_.empty()) return;
1034 frameHad3DThisFrame = true;
1035 frameHad3D = true;
1036 gpuDrivenDrawPending_ = true;
1037 gpuDrivenPending_.clear();
1038}
1039
1040void Graphics::recordGpuDrivenCompute(wgpu::CommandEncoder encoder) {
1041 if ((gpuDrivenComputePending_ || gpuDrivenVgComputePending_) && gbufferDepthValid_ && gpuDrivenHzbPipeline_ &&
1042 gpuDrivenHzbBindGroup_) {
1043 uint32_t width = gpuDrivenHzbWidth_;
1044 uint32_t height = gpuDrivenHzbHeight_;
1045 for (uint32_t mip = 0; mip < gpuDrivenHzbOffsets_.size(); ++mip) {
1046 wgpu::ComputePassEncoder hzbPass = encoder.BeginComputePass();
1047 hzbPass.SetPipeline(gpuDrivenHzbPipeline_);
1048 const uint32_t dynamicOffset = mip * 256u;
1049 hzbPass.SetBindGroup(0, gpuDrivenHzbBindGroup_, 1, &dynamicOffset);
1050 hzbPass.DispatchWorkgroups((width + 7u) / 8u, (height + 7u) / 8u, 1);
1051 hzbPass.End();
1052 width = std::max(width >> 1u, 1u);
1053 height = std::max(height >> 1u, 1u);
1054 }
1055 }
1056 if (gpuDrivenComputePending_ && gpuDrivenCullPipeline_ && gpuDrivenComputeBindGroup_) {
1057 wgpu::ComputePassEncoder pass = encoder.BeginComputePass();
1058 pass.SetPipeline(gpuDrivenCullPipeline_);
1059 pass.SetBindGroup(0, gpuDrivenComputeBindGroup_, 0, nullptr);
1060 pass.DispatchWorkgroups((gpuDrivenDispatchCount_ + 63u) / 64u, 1, 1);
1061 pass.End();
1062 gpuDrivenComputePending_ = false;
1063 }
1064 recordGpuDrivenVgCompute(encoder);
1065}
1066
1067void Graphics::flushGpuDrivenDraws(wgpu::RenderPassEncoder pass, bool canvasTarget, bool hdrCanvas) {
1068 if (!gpuDrivenDrawPending_ ||
1069 (gpuDrivenResidentDrawPending_ ? !gpuDrivenResidentBuffer_ : !gpuDrivenVisibleBuffer_))
1070 return;
1071 auto& arena = currentUboArena();
1072 ensureUboArena(arena, arena.used + gpuDrivenBuckets_.size() * 2048);
1073 const wgpu::RenderPipeline& pipeline =
1074 gpuDrivenResidentDrawPending_
1075 ? (canvasTarget ? (hdrCanvas ? gpuDrivenResidentHdrCanvasPipeline_
1076 : gpuDrivenResidentCanvasPipeline_)
1077 : gpuDrivenResidentRenderPipeline_)
1078 : (canvasTarget ? (hdrCanvas ? gpuDrivenHdrCanvasPipeline_ : gpuDrivenCanvasPipeline_)
1079 : gpuDrivenRenderPipeline_);
1080 if (!pipeline) return;
1081 pass.SetPipeline(pipeline);
1082 gpuDrivenLastIndirectDrawCount_ = 0;
1083
1084 for (uint32_t i = 0; i < gpuDrivenBuckets_.size(); ++i) {
1085 const GpuDrivenBucket& bucket = gpuDrivenBuckets_[i];
1086 auto* gpu = static_cast<GpuMesh*>(bucket.mesh->gpuHandle);
1087 Material* material = bucket.material;
1088 if (!gpu || !gpu->vertexBuffer || !gpu->indexBuffer || !material) continue;
1089
1090 Mesh3DUBO ubo{};
1091 ubo.mvp = mesh3dViewProj;
1092 ubo.model = glm::mat4(1.f);
1093 ubo.lightDir = glm::vec4(glm::vec3(mesh3dLighting.lights[0].posRadius), float(mesh3dLighting.count));
1094 ubo.lightColor = mesh3dLighting.lights[0].color;
1095 ubo.lightColor.w = mesh3dEnvIntensity;
1096 ubo.tint = glm::vec4(material->getTintR(), material->getTintG(), material->getTintB(), material->getTintA());
1097 ubo.cameraPos = glm::vec4(mesh3dCameraPos, material->getRoughness());
1098 ubo.ambient = glm::vec4(glm::vec3(mesh3dLighting.ambient), material->getMetallic());
1099 for (int light = 0; light < Lighting3DPack::kMaxLights; ++light)
1100 ubo.lights[light] = mesh3dLighting.lights[light];
1101 ubo.texBomb = glm::vec4(material->getTexCellBombScale(), material->getTexCellBombStrength(),
1102 material->getTexCellBombRotation(), 0.f);
1103 ubo.parallax = glm::vec4(material->getParallaxScale(), material->getParallaxMinLayers(),
1104 material->getParallaxMaxLayers(), 0.f);
1105 const float ao = renderControl_ && renderControl_->isEnabled("ao") ? mesh3dSsaoIntensity : 0.f;
1106 const float surfaceCode = material->surfaceMode() == SurfaceMode::Masked ? 1.f : 0.f;
1107 ubo.surface = glm::vec4(surfaceCode, material->getAlphaCutoff(), ao,
1108 material->getCameraFacing() ? 1.f : 0.f);
1109 ubo.view = mesh3dView;
1110 ubo.clipInfo = glm::vec4(mesh3dNear, mesh3dFar, 0.f, 0.f);
1111 ubo.cloud = mesh3dCloud;
1112 ubo.cloudWind = mesh3dCloudWind;
1113 ubo.envProbeCenter = glm::vec4(mesh3dEnvProbeCenter, 1.f);
1114 ubo.envProbeExtent = glm::vec4(mesh3dEnvProbeExtent, 0.f);
1115 for (int probeIndex = 0; probeIndex < ReflectionProbeUpload::kMaxProbes; ++probeIndex) {
1116 if (probeIndex >= mesh3dReflectionProbes.count) continue;
1117 const auto& probe = mesh3dReflectionProbes.probes[probeIndex];
1118 GpuTexture* gpuProbe = gpuForTexture(probe.cubemap);
1119 if (!gpuProbe || !gpuProbe->isCube) continue;
1120 ubo.reflectionProbeCenter[probeIndex] = glm::vec4(probe.center, probe.intensity);
1121 ubo.reflectionProbeExtent[probeIndex] = glm::vec4(probe.extent, probe.blendDistance);
1122 }
1123
1124 const uint32_t frameOffset = arena.alloc(sizeof(Mesh3DUBO), 256);
1125 const uint32_t shadowOffset = arena.alloc(sizeof(ShadowUBO), 256);
1126 queue.WriteBuffer(arena.buffer, frameOffset, &ubo, sizeof(ubo));
1127 ShadowUBO shadow = mesh3dShadows.ubo;
1128 if (!mesh3dShadows.active || !material->getReceiveShadow()) shadow.bias.y = 0.f;
1129 queue.WriteBuffer(arena.buffer, shadowOffset, &shadow, sizeof(shadow));
1130
1131 GpuTexture* depth = mesh3dSceneDepthTexture ? gpuForTexture(mesh3dSceneDepthTexture) : flatDepthTexture3D;
1132 wgpu::BindGroup bindGroup =
1133 makeMeshBindGroup(gpuForTexture(material->getAlbedoTexture()), gpuForTexture(material->getNormalTexture()),
1134 gpuForTexture(mesh3dEnvTexture), gpuForTexture(material->getHeightTexture()), depth,
1135 nullptr, frameOffset, shadowOffset, 0, uploadSkinPalette(nullptr));
1136 const uint32_t offsets[3] = {frameOffset, shadowOffset, 0};
1137 pass.SetBindGroup(0, bindGroup, 3, offsets);
1138 WGPUBindGroupEntry modelEntry{};
1139 modelEntry.binding = 0;
1140 modelEntry.buffer = gpuDrivenResidentDrawPending_ ? gpuDrivenResidentBuffer_ : gpuDrivenVisibleBuffer_.Get();
1141 modelEntry.offset =
1142 gpuDrivenResidentDrawPending_ ? gpuDrivenResidentOffset_ :
1143 uint64_t(bucket.outputBase) * sizeof(VisibleInstance);
1144 modelEntry.size =
1145 gpuDrivenResidentDrawPending_ ? gpuDrivenResidentSize_ :
1146 uint64_t(bucket.inputCount) * sizeof(VisibleInstance);
1147 WGPUBindGroupDescriptor modelDesc{};
1148 modelDesc.layout = gpuDrivenRenderSetLayout_.Get();
1149 modelDesc.entryCount = 1;
1150 modelDesc.entries = &modelEntry;
1151 wgpu::BindGroup modelGroup =
1152 device.CreateBindGroup(reinterpret_cast<const wgpu::BindGroupDescriptor*>(&modelDesc));
1153 pass.SetBindGroup(1, modelGroup, 0, nullptr);
1154 pass.SetVertexBuffer(0, gpu->vertexBuffer, 0, gpu->vertexCount * 32ull);
1155 const uint64_t indexBytes = gpu->indexFormat == wgpu::IndexFormat::Uint16 ? 2u : 4u;
1156 pass.SetIndexBuffer(gpu->indexBuffer, gpu->indexFormat, 0, uint64_t(gpu->indexCount) * indexBytes);
1157 pass.DrawIndexedIndirect(gpuDrivenIndirectBuffer_, uint64_t(i) * sizeof(GpuIndirectCommand));
1158 ++gpuDrivenLastIndirectDrawCount_;
1159 }
1160 gpuDrivenDrawPending_ = false;
1161 gpuDrivenResidentDrawPending_ = false;
1162 gpuDrivenResidentBuffer_ = nullptr;
1163 gpuDrivenResidentOffset_ = 0;
1164 gpuDrivenResidentSize_ = 0;
1165 gpuDrivenBuckets_.clear();
1166}
1167
1168} // namespace eve::graphics::webgpu
LogicalId target
float w
Definition AnimClip.cpp:738
const std::string & s
std::unordered_map< std::string, QuestRuntime > entries
float ao
float planes[6][4]
SQObjectPtr key
Definition ECS.cpp:155
scene::NodeDesc desc
EvpackChunkInput input
Definition Evpack.cpp:170
std::uint32_t vertexCount
vkb::Device & device
std::uint32_t firstVertex
std::uint32_t firstInstance
std::uint32_t paddedCount
std::uint32_t instanceCount
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
int inputs
Definition GridGraph.cpp:23
int h
float length
std::array< float, 3 > scale
bool required
std::string label
std::string id
std::future< JobOutput > future
std::vector< RecipeParam > params
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
glm::dvec2 center
std::array< uint32_t, 16 > material
Object::Ptr value
std::string build
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
glm::vec3 eye
glm::mat4 viewProj
glm::mat4 model
bool found
ScriptStructure out
std::string_view source
size_t end
double current
Light3D::Data * light
Definition Shadow.cpp:147
int count
bool visible
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
std::vector< VegetationPresetCommand > commands
ViewPreparation callback
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.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
std::unique_ptr< RenderControl > renderControl_
Definition Graphics.h:2340
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
void gpuDrivenCullEmit(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg, float nearZ, float farZ) override
Gpu driven cull emit.
void gpuDrivenDrawOpaque() override
Gpu driven draw opaque.
uint32_t gpuDrivenMaterialRecord(Material *material) override
Gpu driven material record.
bool gpuDrivenCullBegin(const GpuInstance *instances, uint32_t instanceCount) override
Gpu driven cull begin.
bool gpuDrivenMaterialUsable(Material *material) override
Gpu driven material usable.
uint32_t gpuDrivenMeshRecord(Mesh *mesh) override
Gpu driven mesh record.
Result< void > gpuDrivenReleaseMaterialRecord(Material *material) override
Gpu driven release material record.
GpuResidentSubmitStatus gpuDrivenSubmitResident(const GpuResidentInstanceBatch &batch) override
Gpu driven submit resident.
bool gpuDrivenSubmitOpaque(const GpuInstance *instances, uint32_t instanceCount) override
Gpu driven submit opaque.
uint32_t debugGpuDrivenGpuVisibleCount()
Read back the last GPU-written indirect instance total (native tests).
eve::graphics::GpuIndirectCommand GpuIndirectCommand
Definition GpuDriven.h:18
constexpr uint32_t kMaxHzbMips
Definition GpuDriven.h:25
eve::graphics::GpuInstance GpuInstance
Definition GpuDriven.h:17
const char * kMesh3DFragWgsl
constexpr uint32_t kInvalidGpuDrivenSlot
GPU-driven API surface without GLM layout records.
GpuResidentSubmitStatus
Structured result for direct resident-instance submission.
std::vector< int64_t > attrs(const Node &n, const char *key, std::vector< int64_t > fallback)
Attrs.
constexpr uint64_t kGpuResidentStorageOffsetAlignment
Portable alignment required for resident storage-buffer slice offsets.
Indirect draw command; layout identical to VkDrawIndexedIndirectCommand.
Per-instance GPU record (std430). Mirrors GLSL GpuInstance.
Direct-render description for a GPU-authored array of GpuInstance records. @ownership buckets and buf...
const GpuResidentInstanceBucket * buckets
One contiguous mesh/material bucket in a sorted resident instance buffer.
static constexpr int kMaxLights
Definition Light.h:172
Light3DGpu lights[kMaxLights]
Definition Light.h:174
Vertex/index buffers for one mesh.
Definition Graphics.h:159
glm::vec4 cameraPos
uint32_t outputBase
uint32_t bucket
glm::vec4 hzbInfo
glm::vec4 terrainWaveTint
glm::uvec4 counts
glm::vec4 screen
glm::vec4 bounds
glm::uvec4 info
glm::vec4 clipNearFar
uint32_t pad[2]
glm::vec4 color
glm::vec4 terrainWave