载入中...
搜索中...
未找到
Graphics.h
浏览该文件的文档.
1#pragma once
2
3#include "common/Export.h"
4#include "graphics/Batcher.h"
7#include "graphics/Graphics.h"
10#include "graphics/Light.h"
11#include "graphics/Mesh.h"
12#include "graphics/PbrSurface.h"
15#include "graphics/Shader.h"
16#include "graphics/Shadow.h"
18#include "graphics/Texture.h"
19
20#if defined(__EMSCRIPTEN__) && __has_include(<webgpu/webgpu_cpp.h>)
21#include <webgpu/webgpu_cpp.h>
22#else
23#include <dawn/webgpu_cpp.h>
24#endif
25
27
28#include <array>
29#include <atomic>
30#include <cstdint>
31#include <map>
32#include <memory>
33#include <tuple>
34#include <unordered_map>
35#include <vector>
36
37#include <glm/ext/vector_uint4_sized.hpp>
38#include <glm/mat4x4.hpp>
39#include <glm/vec2.hpp>
40#include <glm/vec3.hpp>
41#include <glm/vec4.hpp>
42
43namespace eve::graphics::webgpu {
44
45class OffscreenCanvas;
46struct DeviceDone;
47struct PbrVariantSources;
48
54struct Mesh3DUBO {
55 glm::mat4 mvp{1.f};
56 glm::mat4 model{1.f};
57 glm::vec4 lightDir{0.4f, 1.f, 0.3f, 0.f}; // xyz = primary dir; w = lightCount
58 glm::vec4 lightColor{1.f, 1.f, 1.f, 0.f}; // rgb = primary color; w = envIntensity
59 glm::vec4 tint{1.f, 1.f, 1.f, 1.f};
60 glm::vec4 cameraPos{0.f, 0.f, 3.f, 0.45f}; // xyz = eye; w = roughness
61 glm::vec4 ambient{0.12f, 0.12f, 0.14f, 0.f}; // rgb = ambient; w = metallic
63 glm::vec4 texBomb{4.f, 0.f, 1.f, 0.f}; // x=cellScale, y=strength, z=rotAmount
64 glm::vec4 parallax{0.f, 8.f, 32.f, 0.f}; // x=scale, y=minLayers, z=maxLayers
65 glm::vec4 surface{0.f, 0.5f, 0.f, 0.f}; // mode, alphaCutoff, ssao, reserved
66 glm::mat4 view{1.f};
67 glm::vec4 clipInfo{0.1f, 100.f, 0.f, 0.f}; // x=near, y=far
68 glm::vec4 cloud{0.f, 1.5f, 0.f, 0.f}; // x=strength(0=off), y=worldCell, z=time
69 glm::vec4 cloudWind{4.f, 0.f, 0.55f, 0.5f}; // xy=wind vel, z=coverage, w=detail
70 glm::vec4 virtualTexture{0.f}; // enabled, pageCountX, pageCountY, border/extent
71 glm::vec4 virtualAtlas{0.f}; // slotsX, slotsY
72 glm::vec4 envProbeCenter{0.f};
73 glm::vec4 envProbeExtent{0.f};
74 glm::vec4 skinInfo{0.f};
77 glm::vec4 diffuseProbeSh[9]{};
78 glm::vec4 diffuseProbeInfo{0.f}; // x = enabled
82 glm::vec4 diffuseVolumeInfo{0.f}; // x = probe count
83 glm::vec4 lodFade{1.f, 0.f, 0.f, 0.f}; // coverage, complementary pattern, enabled
84};
85static_assert(sizeof(Mesh3DUBO) == 2496, "Mesh3DUBO layout must match the WGSL Frame block");
86
88struct MeshVertex {
89 glm::vec3 pos;
90 glm::vec3 normal;
91 glm::vec2 uv;
92 glm::u16vec4 joints{0};
93 glm::vec4 weights{0.f};
94 glm::vec4 color{1.f};
95};
96static_assert(sizeof(MeshVertex) == 72);
97
100 glm::mat4 mvp{1.f};
101 glm::mat4 model{1.f};
102 glm::vec4 clip{0.f};
103 glm::vec4 skinInfo{0.f};
104};
105static_assert(sizeof(SkinPassUBO) == 160);
106
112 glm::mat4 mvp{1.f};
113 glm::mat4 model{1.f};
114 glm::mat4 view{1.f};
115 glm::vec4 lightDir{0.4f, 1.f, 0.3f, 0.f}; // xyz = primary dir; w = 1 if valid
116 glm::vec4 lightColor{1.f, 1.f, 1.f, 0.f}; // rgb = primary; w = envIntensity
117 glm::vec4 tint{1.f, 1.f, 1.f, 1.f};
118 glm::vec4 cameraPos{0.f, 0.f, 3.f, 0.45f}; // xyz = eye; w = roughness
119 glm::vec4 ambient{0.12f, 0.12f, 0.14f, 0.f}; // rgb = ambient; w = metallic
120 glm::vec4 gridInfo{16.f, 9.f, 24.f, 0.f}; // tilesX, tilesY, slices, pointCount
121 glm::vec4 clipInfo{0.1f, 100.f, 1.f, 1.f}; // near, far, screenW, screenH
122 glm::vec4 texBomb{4.f, 0.f, 1.f, 0.f}; // x=cellScale, y=strength, z=rotAmount, w=AO
123 glm::vec4 parallax{0.f, 8.f, 32.f, 0.f}; // x=scale, y=minLayers, z=maxLayers
124 glm::vec4 surface{0.f, 0.5f, 0.f, 0.f}; // mode, alphaCutoff, ssao, reserved
125 glm::vec4 virtualTexture{0.f};
126 glm::vec4 virtualAtlas{0.f};
127 glm::vec4 envProbeCenter{0.f};
128 glm::vec4 envProbeExtent{0.f};
131};
132static_assert(sizeof(Mesh3DClusteredUBO) == 480, "Mesh3DClusteredUBO layout must match the WGSL clustered Frame block");
133
138 wgpu::Texture texture;
139 wgpu::TextureView view;
140 wgpu::Sampler sampler;
141 // Bind group for the unified 2D layout (color at 0, depth at 1).
142 wgpu::BindGroup tex2DGroup;
143 // Bind group for the mesh3d layout (albedo at 1, normal at 2, env at 3,
144 // height at 6). Rebuilt when the mesh3d pipeline re-creates its layout.
145 wgpu::BindGroup meshGroup;
146 bool isCube = false;
147 bool isArray = false;
148 bool isVolume = false;
149 bool isHDR = false;
150 int width = 0;
151 int height = 0;
152 uint32_t mipLevels = 1;
154};
155
159struct GpuMesh {
160 wgpu::Buffer vertexBuffer;
161 wgpu::Buffer indexBuffer;
162 uint64_t vertexCapacity = 0;
163 uint64_t indexCapacity = 0;
164 uint32_t indexCount = 0;
165 uint32_t vertexCount = 0;
166 uint32_t vertexStride = 0;
167 wgpu::IndexFormat indexFormat = wgpu::IndexFormat::Uint32;
168 std::vector<MeshVertex> cpuVertices;
169 std::vector<float> updateVertices;
170 std::vector<uint16_t> updateIndices16;
171};
172
177struct GpuShader {
178 wgpu::RenderPipeline swapchainPipeline; // 2D/offscreen color format
179 wgpu::RenderPipeline offscreenPipeline; // RGBA8Unorm canvas format
180 wgpu::RenderPipeline swapchainOpaquePipeline;
181 wgpu::RenderPipeline offscreenOpaquePipeline;
182 wgpu::RenderPipeline hdrOffscreenPipeline;
183 wgpu::RenderPipeline hdrOffscreenOpaquePipeline;
184 wgpu::RenderPipeline mesh3dPipeline; // scene color format
185 wgpu::RenderPipeline mesh3dXrayPipeline; // depth test/write off + alpha blend
186 wgpu::RenderPipeline shadowPipeline; // depth-only
187 wgpu::RenderPipeline gbufferPipeline; // MRT gbuffer
188 wgpu::PipelineLayout pipelineLayout;
189 wgpu::BindGroupLayout setLayout;
190 bool isMesh3D = false;
191 bool isHair3D = false;
192 bool isShadow = false;
193 bool isGbuffer = false;
194 std::string wgslVert;
195 std::string wgslFrag;
196};
197
200public:
201 // Keep the base draw(Drawable*, mat4) overload visible alongside the
202 // canvas composite overloads below.
204
206 Graphics();
208 ~Graphics() override;
209
211 std::string getBackendName() const override { return "webgpu"; }
213 bool supportsGBufferPost() const override { return caps.supportsFiveTargetGBuffer(); }
215 bool supportsDeferredLighting() const override { return caps.supportsFiveTargetGBuffer(); }
217 void drawDeferredLighting() override;
219 bool supportsGpuDriven3D() const override { return caps.supportsFiveTargetGBuffer(); }
221 bool gpuDrivenEnabled() const override { return gpuDrivenEnabled_; }
223 void gpuDrivenSetEnabled(bool enabled) override { gpuDrivenEnabled_ = enabled; }
225 uint32_t gpuDrivenMeshRecord(Mesh *mesh) override;
227 uint32_t gpuDrivenMaterialRecord(Material *material) override;
229 bool gpuDrivenMaterialUsable(Material *material) override;
231 bool gpuDrivenSubmitOpaque(const GpuInstance *instances, uint32_t instanceCount) override;
233 GpuResidentSubmitStatus gpuDrivenSubmitResident(const GpuResidentInstanceBatch &batch) override;
235 bool gpuDrivenCullEnabled() const override { return gpuDrivenEnabled_; }
237 bool gpuDrivenCullBegin(const GpuInstance *instances, uint32_t instanceCount) override;
239 void gpuDrivenCullEmit(const glm::mat4& viewProj, const glm::vec3& eye, float fovYDeg, float nearZ,
240 float farZ) override;
242 void gpuDrivenDrawOpaque() override;
244 bool gpuDrivenResolveWanted() const override;
246 void gpuDrivenRecordVisPass() override;
248 void gpuDrivenResolve() override;
250 uint32_t gpuDrivenVgUpload(const GpuVgAssetUpload &asset) override;
252 uint32_t gpuDrivenVgAssetId(Mesh *mesh) const override;
254 bool gpuDrivenVgAttachToMesh(Mesh *mesh, uint32_t vgAssetId) override;
257 bool gpuDrivenVgSetInstance(uint32_t vgAssetId, const glm::mat4& model, uint32_t materialId) override;
259 void gpuDrivenVgComputeSection(const glm::mat4& viewProj, const glm::vec3& eye, float fovYDeg, float nearZ,
260 float farZ) override;
262 uint32_t debugGpuDrivenVisibleCount() const { return static_cast<uint32_t>(gpuDrivenVisible_.size()); }
264 uint32_t debugGpuDrivenDispatchCount() const { return gpuDrivenDispatchCount_; }
266 uint32_t debugGpuDrivenIndirectDrawCount() const { return gpuDrivenLastIndirectDrawCount_; }
268 uint32_t debugGpuDrivenGpuVisibleCount();
270 uint32_t debugGpuDrivenHzbMipCount() const { return static_cast<uint32_t>(gpuDrivenHzbOffsets_.size()); }
272 uint32_t debugGpuDrivenVgDispatchCount() const { return gpuDrivenVgVisibleDiagnostic_; }
274 uint32_t debugGpuDrivenVgIndirectDrawCount() const { return gpuDrivenVgLastIndirectDrawCount_; }
276 uint32_t debugGpuDrivenVgGpuVisibleCount();
278 [[nodiscard]] Result<void> gpuDrivenReleaseMaterialRecord(Material *material) override;
280 [[nodiscard]] Result<void> debugValidatePbrVariantBaseSources();
282 [[nodiscard]] Result<void> debugValidatePbrVariantSources(const PbrVariantSources &sources);
284 [[nodiscard]] Result<void> debugValidatePbrVariantPipeline(const PbrVariantSources &sources);
285
286 void initHeadless(int width, int height) override;
287
297 void initHeadlessFromDevice(int width, int height, DeviceDone&& dev);
299 void initWithWindow(void *nativeWindow) override;
301 void present() override;
303 void pushValidationScope() override;
305 void popValidationScope() override;
307 void setMsaaSamples(int samples) override;
309 void requestSurfaceRecreate() override { surfaceNeedsRecreate = true; }
311 void setVSync(bool enabled) override;
313 int getMsaaSamples() const override { return msaaSamples; }
315 void setViewportSize(int width, int height, int pixelwidth, int pixelheight) override;
317 void drawSolidRect(float x, float y, float w, float h, const Color &color,
318 BlendMode blend = BlendMode::Alpha) override;
320 void drawPrimitiveCanvas(const PrimitiveCanvas2D &canvas) override;
322 void drawSolidRectRotated(float cx, float cy, float w, float h, float degrees,
323 const Color &color,
324 BlendMode blend = BlendMode::Alpha) override;
325
327 Texture *newTexture(int width, int height, const uint8_t *rgba, bool repeatU = false,
328 bool repeatV = false) override;
330 Texture *newTexture(int width, int height, const uint8_t *rgba,
331 const TextureCreateInfo &info) override;
334 [[nodiscard]] Result<Texture *> newTextureMipChain(uint32_t width, uint32_t height,
335 uint32_t levels,
336 std::span<const uint8_t> rgba) override;
339 [[nodiscard]] Result<Texture *> newTextureArrayRgba16f(
340 uint32_t width, uint32_t height, uint32_t layers,
341 std::span<const uint16_t> rgbaHalf) override;
344 [[nodiscard]] Result<Texture *> newTexture3DRgba8(uint32_t width, uint32_t height,
345 uint32_t depth,
346 std::span<const uint8_t> rgba) override;
348 Texture *newCubemap(int faceSize, const uint8_t *rgbaFaces) override;
350 Texture *newCubemap(int faceSize, const uint8_t *rgbaFaces,
351 const TextureCreateInfo &info) override;
354 Texture *newHDRCubemap(int faceSize) override;
357 bool copyHDRCanvasToCubemapFace(Canvas *source, Texture *cubemap, int face) override;
359 bool copyHDRCanvasesToCubemap(Canvas *const *sources, int faceCount,
360 Texture *cubemap) override;
363 bool filterHDRReflectionCubemap(Texture *cubemap, int sampleCount = 64) override;
365 Texture *newTexture(image::ImageData *data) override;
367 Texture *newTexture(image::ImageData *data, const TextureCreateInfo &info) override;
369 [[nodiscard]] ResultRef<Texture> newSharedTexture(image::ImageData *data, const std::string &contentKey) override;
371 void setTextureSampler(Texture *texture, const TextureSampler &sampler) override;
373 float getMaxAnisotropy() const override;
376 bool reloadTextureFromFile(const std::string &filename) override;
378 bool uploadDeferredFileTexture(Texture *texture, image::ImageData *data) override;
380 bool releaseTexture(Texture *texture) override;
382 bool updateTexture(Texture *texture, int width, int height,
383 const uint8_t *rgba) override;
385 eve::Result<void> updateTextureRegion(Texture *texture, int x, int y, int width,
386 int height, std::span<const std::uint8_t> rgba,
387 std::size_t bytesPerRow = 0) override;
389 eve::Result<void> updateTextureRegions(
390 Texture *texture, std::span<const TextureRegionUpload> regions) override;
391
393 void drawTexturedRect(Texture *texture, float x, float y, float w, float h,
394 const Color &color) override;
396 void drawTexturedRectShader(Texture *texture, Shader *shader, float x, float y, float w, float h,
397 const Color &color) override;
399 void drawTexturedRectUV(Texture *texture, float x, float y, float w, float h, float u0, float v0,
400 float u1, float v1, const Color &color) override;
402 void drawTexturedRectShaderUV(Texture *texture, Shader *shader, float x, float y, float w,
403 float h, float u0, float v0, float u1, float v1,
404 const Color &color, bool rotatedUV = false,
405 BlendMode blend = BlendMode::Alpha) override;
407 void drawTexturedRectShaderUVRotated(Texture *texture, Shader *shader, float cx, float cy,
408 float w, float h, float degrees, float u0, float v0,
409 float u1, float v1, const Color &color,
410 bool rotatedUV = false,
411 BlendMode blend = BlendMode::Alpha) override;
413 void drawTexturedRectShaderDepth(Texture *color, Texture *depth, Shader *shader, float x, float y,
414 float w, float h, const Color &tint) override;
416 void drawTexturedRectShaderDepthMotion(Texture *color, Texture *depth, Texture *motion,
417 Shader *shader, float x, float y, float w, float h,
418 const Color &tint) override;
420 void drawTexturedRectShader4(Texture *color, Texture *depth, Texture *motion, Texture *extra,
421 Shader *shader, float x, float y, float w, float h,
422 const Color &tint) override;
424 void drawTexturedRectShader5(Texture *color, Texture *depth, Texture *motion, Texture *extra,
425 Texture *specular, Shader *shader, float x, float y, float w,
426 float h, const Color &tint) override;
428 void drawTexturedRectLitUV(Texture *albedo, Texture *normal, float x, float y, float w, float h, float u0, float v0,
429 float u1, float v1, const Color &color, BlendMode blend = BlendMode::Alpha) override;
431 void drawTexturedRectLitUVRotated(Texture *albedo, Texture *normal, float cx, float cy, float w, float h,
432 float degrees, float u0, float v0, float u1, float v1, const Color &color,
433 BlendMode blend = BlendMode::Alpha) override;
435 void setLighting2D(const Lighting2DUBO &ubo) override;
436
438 Shader *newShaderFromSpv(const std::vector<uint32_t> &vertSpv,
439 const std::vector<uint32_t> &fragSpv) override;
441 Shader *newShaderFromSpvFile(const std::string &vertPath, const std::string &fragPath) override;
443 Shader *newShaderFromWgsl(const std::string &vertWgsl,
444 const std::string &fragWgsl) override;
446 [[nodiscard]] Result<void> replaceShaderFromSpv(
447 Shader &shader, const std::vector<uint32_t> &vertSpv,
448 const std::vector<uint32_t> &fragSpv) override;
450 [[nodiscard]] Result<void> replaceShaderFromWgsl(
451 Shader &shader, const std::string &vertWgsl,
452 const std::string &fragWgsl) override;
454 [[nodiscard]] Result<void> replaceShaderFromGlsl(
455 Shader &shader, const std::string &vertGlsl,
456 const std::string &fragGlsl) override;
458 Shader *newShader(const std::string &vertGlsl, const std::string &fragGlsl) override;
460 Shader *newMeshShaderFromSpv(const std::vector<uint32_t> &vertSpv,
461 const std::vector<uint32_t> &fragSpv) override;
463 Shader *newMeshShaderFromWgsl(const std::string &vertWgsl,
464 const std::string &fragWgsl) override;
466 eve::Result<void> configureMeshShaderSurface(Shader& shader, BlendMode blend,
467 bool depthWrite, bool doubleSided) override;
469 Shader *newMeshShader(const std::string &vertGlsl, const std::string &fragGlsl) override;
471 Shader *newHairShaderFromSpv(const std::vector<uint32_t> &vertSpv,
472 const std::vector<uint32_t> &fragSpv) override;
474 Shader *newHairShaderFromWgsl(const std::string &vertWgsl,
475 const std::string &fragWgsl) override;
477 bool releaseShader(Shader *shader) override;
478
480 Mesh *newMeshFromAssimp(const ::aiMesh &mesh) override;
482 Mesh* newMeshFromAssimp(const ::aiMesh& mesh, const glm::mat4& worldTransform) override;
484 Mesh *newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST,
485 int vertexCount, const uint32_t *indices, int indexCount) override;
493 Mesh *newMeshFromArraysColored(const float *posXYZ, const float *nrmXYZ, const float *uvST,
494 const float *colorRGBA, int vertexCount,
495 const uint32_t *indices, int indexCount) override;
497 [[nodiscard]] eve::Result<eve::graphics::MeshBackendDescriptor> describeMesh(Mesh* mesh) const override;
498 bool bakeMeshMorph(Mesh *mesh) override;
500 bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST,
501 int vertexCount, const uint32_t *indices, int indexCount) override;
503 bool setMeshSkinningData(Mesh *mesh, const uint16_t *joints4, const float *weights4,
504 int vertexCount) override;
506 Mesh *newMeshSphere(int slices = 32, int stacks = 16) override;
508 Mesh *newMeshCylinder(int slices = 32, int stacks = 1, bool caps = true) override;
510 bool releaseMesh(Mesh *mesh) override;
511
513 void begin3DFrame() override;
515 void begin3DFrameToCanvas(Canvas *canvas) override;
517 void end3DFrameToCanvas() override;
519 void drawPrimitiveScene(const PrimitiveSceneCanvas3D &canvas) override;
521 float getLastOffscreen3DGpuDurationMs() const override {
522 return completedOffscreenTimestampMs.exchange(0.f);
523 }
525 void setMesh3DViewProj(const glm::mat4 &viewProj) override;
527 void setMesh3DView(const glm::mat4 &view) override;
529 void setMesh3DClip(float nearZ, float farZ) override;
531 Texture *getSceneColorTexture() override;
537 Texture *getSceneLinearDepthTexture() override;
539 void drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint) override;
541 void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint,
542 Shader *shader) override;
544 void drawVoxelFaceInstances(const uint32_t *packed, int count, float originX, float originY,
545 float originZ, const std::string &faceDir, Texture *atlas,
546 int tilesPerRow = 16, const uint32_t *ao = nullptr) override;
548 void setMesh3DNormalTexture(Texture *normal) override;
550 void setMesh3DPackedNormalMask(bool enabled) override;
552 void setMesh3DHeightTexture(Texture *height) override;
554 void setMesh3DVirtualTexture(bool enabled, int pageCountX, int pageCountY,
555 int atlasSlotsX, int atlasSlotsY,
556 float borderFraction) override;
558 void setMesh3DSceneDepth(Texture *depth) override;
560 void setMesh3DSceneColor(Texture *color) override;
562 [[nodiscard]] Mesh3DSceneColorCaptureStatus captureMesh3DSceneColor() override;
564 void setMesh3DMaterial(float metallic, float roughness) override;
566 [[nodiscard]] Result<void> setMesh3DPbrSurface(const PbrSurface *surface) override;
568 void setMesh3DSurface(SurfaceMode mode, BlendMode blend, bool depthWrite,
569 bool doubleSided, float alphaCutoff,
570 const std::string &alphaTechnique = "cutoff") override;
572 void setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount = 1.f) override;
574 void setMesh3DParallax(float scale, float minLayers = 8.f, float maxLayers = 32.f) override;
576 void setMesh3DLodDither(float weight, bool reverse, bool enabled) override;
578 void setMesh3DLighting(const Lighting3DPack &pack) override;
580 void setCloudShadows(float strength, float worldCell, float time, float windSpeed, float windAngle, float coverage,
581 float detail) override;
583 void setMesh3DClusteredLighting(const ClusteredLightingUpload &upload) override;
585 void setMesh3DClusteredActive(bool active) override;
587 void setMesh3DSSAO(float intensity) override;
589 void setMesh3DLight(const glm::vec3 &dir, const glm::vec3 &color) override;
591 void setMesh3DCameraPos(const glm::vec3 &eye) override;
593 void setMesh3DEnv(Texture *cube, float intensity) override;
595 void setMesh3DEnvProbe(const glm::vec3 &center, const glm::vec3 &extent) override;
597 void setMesh3DReflectionProbes(const ReflectionProbeUpload &upload) override;
599 void setSceneExposure(float exposure) override { sceneExposure = std::max(exposure, 0.f); }
601 float getSceneExposure() const override { return sceneExposure; }
603 void setSceneColorFilter(const RgbF& color) override {
604 sceneColorFilter = glm::max(glm::vec3(color.r, color.g, color.b), glm::vec3(0.f));
605 }
607 RgbF getSceneColorFilter() const override { return {sceneColorFilter.r, sceneColorFilter.g, sceneColorFilter.b}; }
609 void setSceneLiftGammaGain(const RgbF& lift, const RgbF& inverseGamma, const RgbF& gain) override {
610 sceneLift = glm::vec3(lift.r, lift.g, lift.b);
611 sceneInverseGamma = glm::max(glm::vec3(inverseGamma.r, inverseGamma.g, inverseGamma.b), glm::vec3(0.001F));
612 sceneGain = glm::vec3(gain.r, gain.g, gain.b);
613 }
615 RgbF getSceneLift() const override { return {sceneLift.r, sceneLift.g, sceneLift.b}; }
617 RgbF getSceneInverseGamma() const override {
618 return {sceneInverseGamma.r, sceneInverseGamma.g, sceneInverseGamma.b};
619 }
621 RgbF getSceneGain() const override { return {sceneGain.r, sceneGain.g, sceneGain.b}; }
623 void setSceneTransitionFx(float vignette, float vignetteSmoothness, float lensDistortion,
624 float lensScale) override {
625 sceneTransitionVignette = std::clamp(vignette, 0.0F, 1.0F);
626 sceneTransitionVignetteSmoothness = std::clamp(vignetteSmoothness, 0.01F, 1.0F);
627 sceneTransitionLensDistortion = std::clamp(lensDistortion, 0.0F, 1.0F);
628 sceneTransitionLensScale = std::clamp(lensScale, 0.01F, 5.0F);
629 }
631 float getSceneTransitionVignette() const override { return sceneTransitionVignette; }
633 float getSceneTransitionVignetteSmoothness() const override { return sceneTransitionVignetteSmoothness; }
635 float getSceneTransitionLensDistortion() const override { return sceneTransitionLensDistortion; }
637 float getSceneTransitionLensScale() const override { return sceneTransitionLensScale; }
639 void setSceneAutoExposure(bool enabled, float minEV, float maxEV) override {
640 sceneAutoExposure = enabled;
641 sceneAutoExposureMinEV = minEV;
642 sceneAutoExposureMaxEV = maxEV;
643 }
645 bool getSceneAutoExposure() const override { return sceneAutoExposure; }
647 float getSceneAutoExposureMinEV() const override { return sceneAutoExposureMinEV; }
649 float getSceneAutoExposureMaxEV() const override { return sceneAutoExposureMaxEV; }
651 void setSceneBloom(float intensity, float threshold) override {
652 sceneBloomIntensity = intensity;
653 sceneBloomThreshold = threshold;
654 }
656 float getSceneBloomIntensity() const override { return sceneBloomIntensity; }
658 float getSceneBloomThreshold() const override { return sceneBloomThreshold; }
660 void setSceneDepthOfField(float focusDistance, float maxBlurPx, float focusRange, float nearZ,
661 float farZ) override {
662 sceneDofFocusDistance = focusDistance;
663 sceneDofMaxBlurPx = maxBlurPx;
664 sceneDofFocusRange = focusRange;
665 sceneDofNearZ = nearZ;
666 sceneDofFarZ = farZ;
667 }
669 float getSceneDofFocusDistance() const override { return sceneDofFocusDistance; }
671 float getSceneDofMaxBlur() const override { return sceneDofMaxBlurPx; }
673 float getSceneDofFocusRange() const override { return sceneDofFocusRange; }
675 float getSceneDofNearZ() const override { return sceneDofNearZ; }
677 float getSceneDofFarZ() const override { return sceneDofFarZ; }
679 void setMesh3DShadows(const ShadowUpload &upload) override;
681 void setMesh3DShadowReceive(bool receive) override;
683 void setMesh3DSkinInfluenceLimit(SkinInfluenceLimit count) override;
685 void beginShadowPass(int cascadeIndex) override;
687 void drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided = true) override;
689 void drawMeshShadowAlpha(Mesh *mesh, const glm::mat4 &lightMVP, Texture *albedo = nullptr,
690 bool doubleSided = true, float lodWeight = 1.f,
691 bool lodFadeReverse = false, bool lodDither = false) override;
693 void endShadowPass() override;
694
696 void beginGBufferPass(int width, int height) override;
698 void drawMeshGBuffer(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ,
699 Texture *albedo = nullptr, float tintR = 1.f, float tintG = 1.f, float tintB = 1.f,
700 float motionX = 0.f, float motionY = 0.f, float roughness = 0.45f, float metallic = 0.f,
701 float tintA = 1.f) override;
703 void drawMeshGBufferAlpha(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ,
704 Texture *albedo = nullptr, float tintR = 1.f, float tintG = 1.f, float tintB = 1.f,
705 float motionX = 0.f, float motionY = 0.f, float roughness = 0.45f, float metallic = 0.f,
706 float tintA = 1.f) override;
708 void endGBufferPass() override;
710 image::ImageData *readGBufferToImageData(const std::string &attachment) override;
711
713 bool supportsDecal() const override { return true; }
715 void beginDecalPass(int width, int height) override;
717 void setDecalCamera(const glm::mat4 &viewProj, float nearZ, float farZ) override;
719 void drawDecal(const glm::mat4 &model, Texture *albedo, Texture *normal, Texture *params,
720 const float uvRect[4], float fade, float normalStrength, float roughnessStrength,
721 float metalStrength, float emissiveStrength, int blendMode = 0,
722 int projectionMode = 0, float blendSharpness = 4.f,
723 float parallaxScale = 0.f, float parallaxMinLayers = 8.f,
724 float parallaxMaxLayers = 24.f, float edgeFadeWidth = 0.06f) override;
726 void endDecalPass() override;
728 image::ImageData *readDecalLayerToImageData(const std::string &attachment) override;
729
731 Canvas *newCanvas(int width, int height) override;
734 Canvas *newHDRCanvas(int width, int height) override;
736 void setCanvas(Canvas *canvas) override;
738 bool isCanvasActive() const override;
740 Canvas *getCanvas() const override;
741
743 Texture *getTexture() override;
745 image::ImageData *newImageData() override;
747 bool beginFrameReadback(const std::string &path) override;
749 int frameReadbackStatus() const override;
751 void pumpReadback();
753 void draw(eve::graphics::Graphics* gfx, const glm::mat4& matrix) const override;
755 void draw(Canvas* C, const glm::mat4& matrix) const override;
757 void clear(std::optional<Color> color, std::optional<int> stencil, std::optional<double> depth) override;
759 Color getPixel(int x, int y) override;
760
762 void flush2DToCanvas(OffscreenCanvas *canvas);
764 Color getPixelImpl(OffscreenCanvas *canvas, int x, int y);
766 image::ImageData *newImageDataImpl(OffscreenCanvas *canvas);
769 image::ImageData *newHDRImageDataImpl(OffscreenCanvas *canvas);
770
772 wgpu::Instance &getInstance() { return instance; }
774 wgpu::Device &getDevice() { return device; }
776 wgpu::Queue &getQueue() { return queue; }
778 wgpu::Surface &getSurface() { return surface; }
780 WGPUTextureFormat getSurfaceFormat() const { return surfaceFormat; }
782 void *getSdlWindow() const { return sdlWindow; }
784 bool isReady() const { return initialized; }
785
786 // The present overlay is rendered inside the swapchain render pass. The
787 // void* payload is a WGPURenderPassEncoder* on the WebGPU backend.
789
790 friend class OffscreenCanvas;
791
793 struct SolidBatch {
794 BlendMode blend = BlendMode::Alpha;
796 };
798 Texture *texture = nullptr;
799 Texture *depth = nullptr;
800 Shader *shader = nullptr;
801 BlendMode blend = BlendMode::Alpha;
803 Texture *motion = nullptr;
804 Texture *extra = nullptr;
805 Texture *specular = nullptr;
806 };
807 struct LitBatch {
808 Texture *albedo = nullptr;
809 Texture *normal = nullptr;
810 BlendMode blend = BlendMode::Alpha;
812 };
813
814private:
815 struct Mesh3dDraw {
816 Mesh *mesh = nullptr;
817 Texture *texture = nullptr;
818 Texture *normalTexture = nullptr;
819 Texture *heightTexture = nullptr;
820 glm::vec4 virtualTexture{0.f};
821 glm::vec4 virtualAtlas{0.f};
822 glm::mat4 model{1.f};
823 Color tint{1.f};
824 Shader *shader = nullptr;
825 SurfaceMode surfaceMode = SurfaceMode::Opaque;
826 BlendMode surfaceBlend = BlendMode::Alpha;
827 bool depthWrite = false;
828 bool doubleSided = false;
829 bool shadowReceive = true;
830 float metallic = 0.f;
831 float roughness = 1.f;
832 glm::mat4 viewProj{1.f};
833 glm::mat4 view{1.f};
834 glm::vec3 cameraPos{};
835 Lighting3DPack lighting{};
836 ShadowUpload shadows{};
837 Texture *environment = nullptr;
838 float environmentIntensity = 0.f;
839 int skinInfluenceLimit = 4;
840 float alphaCutoff = 0.5f;
841 std::string alphaTechnique = "cutoff";
842 glm::vec4 lodFade{1.f, 0.f, 0.f, 0.f};
843 std::optional<PbrSurface> pbrSurface;
844 std::optional<glm::vec4> gbufferClip;
845 glm::mat4 gbufferMvp{1.f};
846 wgpu::Buffer skinBuffer;
847 uint32_t frameUboOffset = 0;
848 uint32_t pushUboOffset = 0;
849 uint32_t shadowUboOffset = 0;
850 uint32_t clusteredUboOffset = 0;
851 };
852 struct ShadowDraw {
853 Mesh *mesh = nullptr;
854 Texture *albedo = nullptr;
855 glm::mat4 mvp{1.f};
856 bool alphaTest = false;
857 bool doubleSided = true;
858 glm::vec4 lodFade{1.f, 0.f, 0.f, 0.f};
859 int skinInfluenceLimit = 4;
860 };
861 struct GbufferDraw {
862 std::optional<Mesh3dDraw> pbrDraw;
863 Mesh *mesh = nullptr;
864 Texture *albedo = nullptr;
865 glm::mat4 mvp{1.f};
866 glm::mat4 model{1.f};
867 float nearZ = 0.1f;
868 float farZ = 100.f;
869 glm::vec4 tint{1.f};
870 glm::vec2 motion{0.f};
871 float roughness = 0.45f;
872 float metallic = 0.f;
873 bool alphaTest = false;
874 int skinInfluenceLimit = 4;
875 uint32_t pushUboOffset = 0;
876 };
877 struct VoxelDraw {
878 uint32_t instanceBufferOffset = 0;
879 uint32_t aoBufferOffset = 0;
880 uint32_t count = 0;
881 GpuTexture *atlas = nullptr;
882 glm::mat4 viewProj{1.f};
883 glm::vec4 chunkOrigin{0.f};
884 glm::vec4 atlasInfo{16.f, 0.f, 0.f, 0.f};
885 glm::vec4 tint{1.f};
886 uint32_t pushUboOffset = 0;
887 };
888 struct DecalDraw {
889 glm::mat4 model{1.f};
890 Texture *albedo = nullptr;
891 Texture *normal = nullptr;
892 Texture *params = nullptr;
893 glm::vec4 uvRect{0.f, 0.f, 1.f, 1.f};
894 glm::vec4 fadeParams{1.f, 0.f, 0.f, 0.f};
895 glm::vec4 extraParams{0.f};
896 glm::vec4 surfaceParams{0.f, 8.f, 24.f, 0.06f};
897 };
898
899 void configureSurface(int width, int height);
900 void createDefaultTextures();
901 void createPipelineResources();
902 void create2DPipelines();
903 void createMesh3DPipelines();
904 wgpu::RenderPipeline get2DColorPipeline(BlendMode blend, bool offscreen);
905 wgpu::RenderPipeline get2DTexturedPipeline(BlendMode blend, bool offscreen);
906 wgpu::RenderPipeline get2DLitPipeline(BlendMode blend, WGPUTextureFormat format);
907 wgpu::RenderPipeline getMesh3DPipeline(BlendMode blend, bool depthWrite, bool doubleSided, bool canvasTarget);
908 void createMesh3DClusteredPipeline();
909 void createShadowPipelines();
910 void createGbufferPipelines();
911 void createDecalPipeline();
912 void createVoxelPipelines();
913 void ensureGpuDrivenResources(uint32_t instanceCount, uint32_t bucketCount);
914 void recordGpuDrivenCompute(wgpu::CommandEncoder encoder);
915 void flushGpuDrivenDraws(wgpu::RenderPassEncoder pass, bool canvasTarget,
916 bool hdrCanvas = false);
917 void ensureGpuDrivenVisibilityResources();
918 void recordGpuDrivenVisibility(wgpu::CommandEncoder encoder);
919 void flushGpuDrivenResolve(wgpu::RenderPassEncoder pass);
920 void ensureGpuDrivenVgResources();
921 void recordGpuDrivenVgCompute(wgpu::CommandEncoder encoder);
922 void recordGpuDrivenVgVisibility(wgpu::CommandEncoder encoder);
923 void flushGpuDrivenVgResolve(wgpu::RenderPassEncoder pass);
924 void createSceneColorResources(int width, int height);
925 void destroySceneColorResources();
926 void createShadowResources();
927 void destroyShadowResources();
928 void createGbufferResources(int width, int height);
929 void destroyGbufferResources();
930 void createDecalResources(int width, int height);
931 void destroyDecalResources();
932
933 wgpu::RenderPipeline createPipelineForShader(GpuShader* gs, wgpu::TextureFormat format, bool depth, bool mesh3d,
934 bool hair, bool shadow, bool gbuffer, wgpu::PipelineLayout layout);
935 wgpu::BindGroupLayout make2DBindGroupLayout();
936 wgpu::BindGroupLayout makeMesh3DBindGroupLayout();
937 wgpu::BindGroupLayout makeMesh3DClusteredBindGroupLayout();
938 wgpu::BindGroupLayout makeShadowBindGroupLayout();
939 wgpu::BindGroupLayout makeGbufferBindGroupLayout();
940 wgpu::BindGroupLayout makeDecalBindGroupLayout();
941 wgpu::BindGroupLayout makeVoxelBindGroupLayout();
942 wgpu::PipelineLayout make2DPipelineLayout();
943 wgpu::PipelineLayout makeMesh3DPipelineLayout();
944 wgpu::PipelineLayout makeMesh3DClusteredPipelineLayout();
945 wgpu::PipelineLayout makeShadowPipelineLayout();
946 wgpu::PipelineLayout makeGbufferPipelineLayout();
947 wgpu::PipelineLayout makeDecalPipelineLayout();
948 wgpu::PipelineLayout makeVoxelPipelineLayout();
949
950 GpuTexture *gpuForTexture(Texture *t) const;
951 GpuTexture *gpuForTextureOrWhite(Texture *t) const;
952 wgpu::BindGroup makeTex2DBindGroup(GpuTexture *color, GpuTexture *depth,
953 GpuTexture *motion = nullptr, GpuTexture *extra = nullptr,
954 GpuTexture *specular = nullptr);
955 wgpu::BindGroup makeMeshBindGroup(GpuTexture* albedo, GpuTexture* normal, GpuTexture* env, GpuTexture* height,
956 GpuTexture* depth, GpuTexture* sceneColor, uint32_t frameUboOffset,
957 uint32_t shadowUboOffset, uint32_t pushUboOffset, const wgpu::Buffer& skinBuffer);
958 wgpu::BindGroup makeMesh3DClusteredBindGroup(GpuTexture *albedo, GpuTexture *normal,
959 GpuTexture *env, GpuTexture *height,
960 GpuTexture *depth, wgpu::TextureView aoView,
961 uint32_t frameUboOffset, uint32_t shadowUboOffset);
962 void uploadClusteredLighting(const ClusteredLightingUpload &upload);
963 void ensureMeshBindGroupsForDraw(Mesh3dDraw &d);
964 void applyPendingResourceChanges() override;
965 [[nodiscard]] ResultRef<Texture> requestFileTexture(const std::string &filename) override;
966 bool samplerChangesPending_ = false;
967 struct CachedSampler {
968 TextureSampler state;
969 uint32_t mipLevels;
970 wgpu::Sampler sampler;
971 };
972 std::vector<CachedSampler> cachedSamplers_;
973 wgpu::Sampler makeSampler(const TextureSampler &sampler, uint32_t mipLevels) const;
974
975 void uploadTexturePixels(GpuTexture *gt, const uint8_t *rgba, int w, int h,
976 const TextureCreateInfo &info);
977 void uploadTexturePixelsMips(GpuTexture *gt, const uint8_t *rgba, int w, int h);
978 void flush2D(wgpu::RenderPassEncoder pass, int viewW, int viewH, WGPUTextureFormat format);
979 void drawTexturedBatch(wgpu::RenderPassEncoder pass, TexturedBatch &tb, int viewW, int viewH,
980 WGPUTextureFormat format, bool offscreen);
981 void drawLitBatch(wgpu::RenderPassEncoder pass, LitBatch &lb, int viewW, int viewH,
982 WGPUTextureFormat format);
983 void flushMesh3D(wgpu::RenderPassEncoder pass, WGPUTextureFormat format,
984 bool canvasTarget = false);
985 bool drawPbrMesh(wgpu::RenderPassEncoder pass, WGPUTextureFormat format,
986 bool canvasTarget, Mesh3dDraw &draw, GpuMesh &mesh);
987 void flushPrimitive3D(wgpu::RenderPassEncoder pass, WGPUTextureFormat format, uint32_t sampleCount);
988 wgpu::RenderPipeline getPrimitive3DPipeline(PrimitiveDepthMode depth, BlendMode blend, PrimitiveCullMode cull,
989 WGPUTextureFormat format, uint32_t sampleCount);
990 void flushShadowPass(wgpu::RenderPassEncoder pass, int cascade);
991 void recordDirectionalShadowPasses(wgpu::CommandEncoder encoder);
992 void flushGbufferPass(wgpu::RenderPassEncoder pass);
993 void flushDecalPass(wgpu::RenderPassEncoder pass);
994 void submitPendingDeferredPasses();
995 void createDeferredLightingPipeline();
996 void destroyDeferredLightingResources();
997 void ensureDeferredLightingClusteredUpload();
999 void flushDeferredLighting(wgpu::RenderPassEncoder pass);
1005 bool flushGBufferPassInto(wgpu::CommandEncoder& encoder, bool runAo);
1006 void flushVoxelDraws(wgpu::RenderPassEncoder pass, WGPUTextureFormat format);
1007
1008 // UBO arena: one growable uniform buffer per in-flight frame slot.
1009 struct UboArena {
1010 wgpu::Buffer buffer;
1011 uint64_t capacity = 0;
1012 uint64_t used = 0;
1014 uint32_t alloc(uint64_t size, uint64_t alignment);
1015 std::vector<wgpu::Buffer> palettes;
1016 size_t paletteIndex = 0;
1018 void reset() {
1019 used = 0;
1020 paletteIndex = 0;
1021 }
1022 };
1023 wgpu::Buffer uploadSkinPalette(Mesh* mesh);
1024 UboArena &currentUboArena();
1025 void ensureUboArena(UboArena &arena, uint64_t bytes);
1026
1027 // Vertex arena for batched 2D vertices (one per frame slot).
1028 struct VertexArena {
1029 wgpu::Buffer buffer;
1030 uint64_t capacity = 0;
1031 uint64_t used = 0;
1033 uint64_t alloc(uint64_t bytes);
1035 void reset() { used = 0; }
1036 };
1037 VertexArena &currentVertexArena();
1038 void ensureVertexArena(VertexArena &arena, uint64_t bytes);
1039
1040 uint32_t frameSlotCount() const { return kFramesInFlight; }
1041 uint32_t currentFrameSlot() const { return frameIndex % kFramesInFlight; }
1042
1043 // Per-frame instance arena for voxel faces (packed rect words).
1044 VertexArena voxelInstanceArena;
1045 // Parallel per-frame arena for the AO word (2 bits per corner).
1046 VertexArena voxelAoArena;
1047
1048 // ---- state ----
1049 bool initialized = false;
1050 bool deviceInitDone = false;
1051 bool headless_ = false;
1052 void *sdlWindow = nullptr;
1053 int logicalW = 0, logicalH = 0;
1054 int pixelW = 0, pixelH = 0;
1055 float maxSamplerAnisotropy = 1.f;
1056
1057 wgpu::Instance instance;
1058 wgpu::Adapter adapter;
1059 wgpu::Device device;
1060 wgpu::Queue queue;
1061 wgpu::Surface surface;
1062 Capabilities caps;
1063 WGPUTextureFormat surfaceFormat = WGPUTextureFormat_BGRA8Unorm;
1064 std::atomic<bool> surfaceNeedsRecreate{false};
1065 bool swapchainConfigured = false;
1066
1067 // Per-frame command state (single command buffer per frame).
1068 uint32_t frameIndex = 0;
1069 // Slot rendered by the most recent present (the readback source).
1070 uint32_t lastPresentSlot = 0;
1071 bool sceneColorHistoryValid = false;
1072 std::optional<size_t> mesh3dSceneColorCaptureIndex;
1073 static constexpr uint32_t kFramesInFlight = 2;
1074 std::vector<UboArena> uboArenas;
1075 std::vector<VertexArena> vertexArenas;
1076 wgpu::Buffer mesh3dFrameUboPool;
1077 uint32_t mesh3dFrameUboSlots[kFramesInFlight]{};
1078 wgpu::Buffer shadowUboPool;
1079 uint32_t shadowUboSlots[kFramesInFlight]{};
1080 wgpu::Buffer pushUboPool;
1081 uint32_t pushUboSlots[kFramesInFlight]{};
1082
1083 // Default / placeholder resources.
1084 GpuTexture *whiteTexture = nullptr;
1085 GpuTexture *flatNormalTexture = nullptr;
1086 GpuTexture *flatNormalTexture3D = nullptr;
1087 GpuTexture *flatHeightTexture3D = nullptr;
1088 GpuTexture *flatDepthTexture3D = nullptr;
1089 GpuTexture *defaultEnvCubemap = nullptr;
1090 wgpu::BindGroupLayout reflectionProbeFilterSetLayout;
1091 wgpu::PipelineLayout reflectionProbeFilterPipelineLayout;
1092 wgpu::RenderPipeline reflectionProbeFilterPipeline;
1093 GpuTexture *shadowDepthArray = nullptr;
1094 // 1x1x3 depth-array + comparison sampler used for the mesh3d shadow
1095 // bindings (5/8) when no shadow map exists yet — the bind group layout
1096 // requires those bindings on every draw.
1097 GpuTexture *defaultShadowTex = nullptr;
1098
1099 // Pipelines / layouts.
1100 wgpu::PipelineLayout tex2DPipelineLayout;
1101 wgpu::PipelineLayout mesh3dPipelineLayout;
1102 wgpu::RenderPipeline mesh3dCanvasPipeline;
1103 wgpu::BindGroupLayout mesh3dClusteredSetLayout;
1104 wgpu::PipelineLayout mesh3dClusteredPipelineLayout;
1105 wgpu::RenderPipeline mesh3dClusteredPipeline;
1106 // Double-buffered storage ring for the clustered-forward SSBOs (lights /
1107 // cluster table / light indices), one slot per frame in flight.
1108 struct ClusteredStorage {
1109 wgpu::Buffer lights;
1110 wgpu::Buffer table;
1111 wgpu::Buffer indices;
1112 uint64_t lightsCap = 0;
1113 uint64_t tableCap = 0;
1114 uint64_t indicesCap = 0;
1115 } clusteredStorage[kFramesInFlight];
1116 wgpu::PipelineLayout shadowPipelineLayout;
1117 wgpu::PipelineLayout gbufferPipelineLayout;
1118 wgpu::PipelineLayout decalPipelineLayout;
1119 wgpu::PipelineLayout voxelPipelineLayout;
1120 wgpu::BindGroupLayout tex2DSetLayout;
1121 wgpu::BindGroupLayout mesh3dSetLayout;
1122 wgpu::BindGroupLayout shadowSetLayout;
1123 wgpu::BindGroupLayout gbufferSetLayout;
1124 wgpu::BindGroupLayout decalSetLayout;
1125 wgpu::BindGroupLayout voxelSetLayout;
1126 // Phase D: Hybrid clustered deferred lighting (fullscreen into scene color).
1127 wgpu::BindGroupLayout deferredLightingSetLayout;
1128 wgpu::PipelineLayout deferredLightingPipelineLayout;
1129 wgpu::RenderPipeline deferredLightingPipeline;
1130 wgpu::Sampler deferredLightingNearestSampler;
1131 bool deferredLightingPending_ = false;
1132
1133 // SSAO (screen-space ambient occlusion) resources. The AO pass runs after
1134 // the G-buffer fill and writes aoTex[aoWriteIndex]; the forward mesh pass
1135 // samples the other slot (one frame of latency).
1136 wgpu::PipelineLayout aoPipelineLayout;
1137 wgpu::RenderPipeline aoPipeline;
1138 wgpu::BindGroupLayout aoSetLayout;
1139 wgpu::Texture aoTex[2];
1140 wgpu::TextureView aoView[2];
1141 uint32_t aoWriteIndex = 0;
1142 bool aoReady = false;
1143 wgpu::Buffer aoUbo;
1144 void ensureAOResources(int width, int height);
1145 wgpu::BindGroup makeAOBindGroup(wgpu::TextureView depthView);
1146 // Shared filtering sampler for bindings declared as `sampler` in WGSL
1147 // (e.g. mesh3d's @binding(7) mainSamp).
1148 wgpu::Sampler mainSampler;
1149 wgpu::RenderPipeline colorPipeline; // 2D solid
1150 wgpu::RenderPipeline texturedPipeline; // 2D textured
1151 wgpu::RenderPipeline colorAdditivePipeline;
1152 wgpu::RenderPipeline texturedAdditivePipeline;
1153 wgpu::RenderPipeline colorPremultipliedPipeline;
1154 wgpu::RenderPipeline texturedPremultipliedPipeline;
1155 wgpu::RenderPipeline colorMultiplyPipeline;
1156 wgpu::RenderPipeline texturedMultiplyPipeline;
1157 wgpu::RenderPipeline colorOpaquePipeline;
1158 wgpu::RenderPipeline texturedOpaquePipeline;
1159 wgpu::RenderPipeline sceneTonemapPipeline;
1160 float sceneExposure = 1.f;
1161 glm::vec3 sceneColorFilter{1.f};
1162 glm::vec3 sceneLift{0.f};
1163 glm::vec3 sceneInverseGamma{1.f};
1164 glm::vec3 sceneGain{1.f};
1165 float sceneTransitionVignette = 0.0F;
1166 float sceneTransitionVignetteSmoothness = 0.2F;
1167 float sceneTransitionLensDistortion = 0.0F;
1168 float sceneTransitionLensScale = 1.0F;
1169 bool sceneAutoExposure = false;
1170 float sceneAutoExposureMinEV = -8.f;
1171 float sceneAutoExposureMaxEV = 8.f;
1172 float sceneBloomIntensity = 0.f;
1173 float sceneBloomThreshold = 1.f;
1174 float sceneDofFocusDistance = 0.f;
1175 float sceneDofMaxBlurPx = 0.f;
1176 float sceneDofFocusRange = 8.f;
1177 float sceneDofNearZ = 0.1f;
1178 float sceneDofFarZ = 100.f;
1179 wgpu::RenderPipeline mesh3dPipeline;
1180 wgpu::RenderPipeline mesh3dTransparentPipeline;
1181 static constexpr size_t kMeshPipelineVariants = 20;
1182 std::array<wgpu::RenderPipeline, kMeshPipelineVariants> mesh3dPipelines;
1183 std::array<wgpu::RenderPipeline, kMeshPipelineVariants> mesh3dCanvasPipelines;
1184 wgpu::RenderPipeline mesh3dShadowPipeline;
1185 wgpu::RenderPipeline mesh3dShadowSingleSidedPipeline;
1186 wgpu::RenderPipeline mesh3dShadowAlphaPipeline;
1187 wgpu::RenderPipeline mesh3dShadowAlphaSingleSidedPipeline;
1188 wgpu::RenderPipeline mesh3dGbufferPipeline;
1189 wgpu::RenderPipeline mesh3dGbufferAlphaPipeline;
1190 wgpu::RenderPipeline decalPipeline;
1191 wgpu::RenderPipeline voxelRectPipeline;
1192 wgpu::RenderPipeline lit2dPipeline;
1193 wgpu::RenderPipeline lit2dAdditivePipeline;
1194 wgpu::RenderPipeline lit2dPremultipliedPipeline;
1195 wgpu::RenderPipeline lit2dMultiplyPipeline;
1196 wgpu::RenderPipeline lit2dOpaquePipeline;
1197 // RGBA8Unorm (offscreen canvas / scene) variants of the 2D pipelines.
1198 wgpu::RenderPipeline offscreenColorPipeline;
1199 wgpu::RenderPipeline offscreenTexturedPipeline;
1200 wgpu::RenderPipeline offscreenColorAdditivePipeline;
1201 wgpu::RenderPipeline offscreenTexturedAdditivePipeline;
1202 wgpu::RenderPipeline offscreenColorPremultipliedPipeline;
1203 wgpu::RenderPipeline offscreenTexturedPremultipliedPipeline;
1204 wgpu::RenderPipeline offscreenColorMultiplyPipeline;
1205 wgpu::RenderPipeline offscreenTexturedMultiplyPipeline;
1206 wgpu::RenderPipeline offscreenColorOpaquePipeline;
1207 wgpu::RenderPipeline offscreenTexturedOpaquePipeline;
1208 wgpu::RenderPipeline hdrOffscreenTexturedPipeline;
1209 wgpu::RenderPipeline hdrOffscreenTexturedOpaquePipeline;
1210 wgpu::RenderPipeline offscreenLitPipeline;
1211 wgpu::RenderPipeline offscreenLitAdditivePipeline;
1212 wgpu::RenderPipeline offscreenLitPremultipliedPipeline;
1213 wgpu::RenderPipeline offscreenLitMultiplyPipeline;
1214 wgpu::RenderPipeline offscreenLitOpaquePipeline;
1215 wgpu::RenderPipeline hdrOffscreenLitPipeline;
1216 wgpu::RenderPipeline hdrOffscreenLitAdditivePipeline;
1217 wgpu::RenderPipeline hdrOffscreenLitPremultipliedPipeline;
1218 wgpu::RenderPipeline hdrOffscreenLitMultiplyPipeline;
1219 wgpu::RenderPipeline hdrOffscreenLitOpaquePipeline;
1220 // Fullscreen quad used to composite the scene color into the swapchain.
1221 wgpu::Buffer fullscreenQuadVb;
1222 wgpu::Buffer toneMapQuadVb;
1223 wgpu::Buffer fullscreenQuadIb;
1224 bool fullscreenQuadReady = false;
1225
1226 // 2D batch state.
1227 std::vector<SolidBatch> solidBatches;
1228 std::vector<TexturedBatch> texturedBatches;
1229 std::vector<LitBatch> litBatches;
1230 Lighting2DUBO lighting2dFrame{};
1231 enum class OverlayKind : uint8_t { Solid, Textured, Lit };
1232 struct OverlaySpan {
1233 OverlayKind kind = OverlayKind::Solid;
1234 uint32_t index = 0;
1235 uint32_t vertBegin = 0;
1236 uint32_t vertCount = 0;
1237 };
1238 std::vector<OverlaySpan> overlaySpans;
1239 bool sceneColorComposited = false;
1240 void noteSolidOverlay(uint32_t batchIndex);
1241 void noteTexturedOverlay(Texture *tex, uint32_t batchIndex);
1242 void noteLitOverlay(uint32_t batchIndex);
1243 void clear2DBatches();
1244
1245 // 3D frame state.
1246 bool frame3DStarted = false;
1247 bool sceneColorPassOpen = false;
1248 // Non-null between begin3DFrameToCanvas and the frame's present: the 3D
1249 // scene pass renders into this canvas instead of the scene color target.
1250 OffscreenCanvas *active3DCanvas = nullptr;
1251 bool offscreenTimestampSupported = false;
1252 wgpu::QuerySet offscreenTimestampQuerySet;
1253 wgpu::Buffer offscreenTimestampResolveBuffer;
1254 struct OffscreenTimestampReadback {
1255 Graphics *owner = nullptr;
1256 wgpu::Buffer buffer;
1257 bool pending = false;
1258 };
1259 std::array<OffscreenTimestampReadback, 3> offscreenTimestampReadbacks{};
1260 size_t offscreenTimestampReadbackCursor = 0;
1261 mutable std::atomic<float> completedOffscreenTimestampMs{0.f};
1262 // Most recent 3D render target (scene color or canvas), used by the async
1263 // frame readback.
1264 // Owned copy of the last composed surface, captured only when requested.
1265 wgpu::Texture presentedReadback;
1266 int presentedReadbackW = 0, presentedReadbackH = 0;
1267 WGPUTextureFormat presentedReadbackFormat = WGPUTextureFormat_Undefined;
1268 bool surfaceCanCopySrc = false;
1269 void recordPresentedReadback(wgpu::CommandEncoder &encoder, const wgpu::Texture &surfaceTexture);
1270 wgpu::Texture lastReadbackTex;
1271 int lastReadbackW = 0;
1272 int lastReadbackH = 0;
1273 glm::mat4 mesh3dViewProj{1.f};
1274 glm::mat4 mesh3dView{1.f};
1275 float mesh3dNear = 0.1f, mesh3dFar = 100.f;
1276 struct Primitive3DVertex {
1277 glm::vec4 clipPosition{0.f};
1278 glm::vec4 color{1.f};
1279 };
1280 struct Primitive3DDraw {
1281 ScenePrimitivePaint paint;
1282 float averageDepth = 0.f;
1283 std::size_t sequence = 0;
1284 std::vector<Primitive3DVertex> vertices;
1285 };
1286 std::vector<Primitive3DDraw> primitive3DDraws;
1287 std::unordered_map<std::uint64_t, wgpu::RenderPipeline> primitive3DPipelines;
1288 Texture *sceneColorTexture = nullptr;
1289 Texture *mesh3dNormalTexture = nullptr;
1290 Texture *mesh3dHeightTexture = nullptr;
1291 Texture *mesh3dEnvTexture = nullptr;
1292 Texture *mesh3dSceneDepthTexture = nullptr;
1293 Texture *mesh3dSceneColorTexture = nullptr;
1294 float mesh3dEnvIntensity = 0.f;
1295 glm::vec3 mesh3dEnvProbeCenter{0.f};
1296 glm::vec3 mesh3dEnvProbeExtent{0.f};
1297 ReflectionProbeUpload mesh3dReflectionProbes{};
1298 float mesh3dMetallic = 0.f;
1299 float mesh3dRoughness = 0.45f;
1300 SurfaceMode mesh3dSurfaceMode = SurfaceMode::Opaque;
1301 BlendMode mesh3dSurfaceBlend = BlendMode::Alpha;
1302 bool mesh3dSurfaceDepthWrite = false;
1303 bool mesh3dSurfaceDoubleSided = false;
1304 float mesh3dAlphaCutoff = 0.5f;
1305 std::string mesh3dAlphaTechnique = "cutoff";
1306 glm::vec4 mesh3dLodFade{1.f, 0.f, 0.f, 0.f};
1307 float mesh3dTexBombScale = 4.f, mesh3dTexBombStrength = 0.f, mesh3dTexBombRot = 1.f;
1308 float mesh3dParallaxScale = 0.f, mesh3dParallaxMin = 8.f, mesh3dParallaxMax = 32.f;
1309 glm::vec4 mesh3dVirtualTexture{0.f};
1310 glm::vec4 mesh3dVirtualAtlas{0.f};
1311 float mesh3dSsaoIntensity = 1.f;
1312 glm::vec4 mesh3dCloud{0.f, 1.5f, 0.f, 0.f};
1313 glm::vec4 mesh3dCloudWind{4.f, 0.f, 0.55f, 0.5f};
1314 Lighting3DPack mesh3dLighting{};
1315 ShadowUpload mesh3dShadows{};
1316 bool mesh3dShadowReceive = true;
1317 int mesh3dSkinInfluenceLimit = 4;
1318 bool mesh3dClusteredActive = false;
1319 ClusteredLightingUpload mesh3dClustered{};
1320 glm::vec3 mesh3dCameraPos{0.f, 0.f, 3.f};
1321 bool frameHad3DThisFrame = false;
1322 std::vector<Mesh3dDraw> mesh3dDraws;
1323 std::optional<PbrSurface> mesh3dPbrSurface;
1324 struct PbrResources;
1325 static void deletePbrResources(PbrResources *resources);
1326 std::unique_ptr<PbrResources, void (*)(PbrResources *)> pbrResources_{
1327 nullptr, &deletePbrResources};
1328 Color clearColor{0.1f, 0.1f, 0.12f, 1.f};
1329 bool hasPendingClear = true;
1330
1331 // Shadow pass state.
1332 int shadowPassCascade = -1;
1333 std::vector<ShadowDraw> shadowPassDraws;
1334 std::vector<ShadowDraw> shadowCascadeDraws[ShadowConfig::kTotalLayers];
1335
1336 // GBuffer pass state.
1337 bool gbufferPassActive = false;
1338 bool gbufferPassPending = false;
1339 std::vector<GbufferDraw> gbufferPassDraws;
1340
1341 // Voxel state.
1342 std::vector<VoxelDraw> voxelDraws;
1343 wgpu::Buffer voxelUnitQuadVerts;
1344 wgpu::Buffer voxelUnitQuadIndices;
1345 // Scene color (offscreen 3D) target.
1346 struct SceneColorSlot {
1347 wgpu::Texture msaaColor;
1348 wgpu::TextureView msaaView;
1349 wgpu::Texture color;
1350 wgpu::TextureView colorView;
1351 wgpu::Texture depth;
1352 wgpu::TextureView depthView;
1353 GpuTexture colorGpu;
1354 Texture colorTex;
1355 uint32_t sampleCount = 1;
1356 };
1357 int sceneColorWidth = 0, sceneColorHeight = 0;
1358 // Internal 3D lighting target. Script-created Canvas textures remain
1359 // RGBA8Unorm and are composited after the scene resolve.
1360 WGPUTextureFormat sceneColorFormat = WGPUTextureFormat_RGBA8Unorm;
1361 uint32_t sceneColorSamples = 1;
1362 std::vector<SceneColorSlot> sceneColorSlots;
1363
1364 // Shadow map state (CSM, 3 cascade layers).
1365 struct ShadowMapSlot {
1366 wgpu::Texture texture;
1367 wgpu::TextureView view;
1368 };
1369 std::vector<ShadowMapSlot> shadowMaps;
1370 int shadowMapSize = ShadowConfig::kMapSize;
1371
1372 // GBuffer targets (Phase B: 5 color + depth).
1373 struct GbufferSlot {
1374 wgpu::Texture normal;
1375 wgpu::TextureView normalView;
1376 wgpu::Texture depthColor;
1377 wgpu::TextureView depthColorView;
1378 wgpu::Texture albedo;
1379 wgpu::TextureView albedoView;
1380 wgpu::Texture pbrParams;
1381 wgpu::TextureView pbrParamsView;
1382 wgpu::Texture emissive;
1383 wgpu::TextureView emissiveView;
1384 wgpu::Texture depth;
1385 wgpu::TextureView depthView;
1386 wgpu::Texture visID;
1387 wgpu::TextureView visIDView;
1388 wgpu::Texture visBary;
1389 wgpu::TextureView visBaryView;
1390 GpuTexture normalGpu;
1391 GpuTexture depthColorGpu;
1392 GpuTexture albedoGpu;
1393 GpuTexture pbrParamsGpu;
1394 GpuTexture emissiveGpu;
1395 GpuTexture depthGpu;
1396 Texture normalTex;
1397 Texture depthColorTex;
1398 Texture albedoTex;
1399 Texture pbrParamsTex;
1400 Texture emissiveTex;
1401 Texture depthTex;
1402 };
1403 int gbufferWidth = 0, gbufferHeight = 0;
1404 std::vector<GbufferSlot> gbufferSlots;
1405 uint32_t lastGbufferSlot = 0;
1406 bool gbufferDepthValid_ = false;
1407
1408 struct DecalSlot {
1409 wgpu::Texture albedo;
1410 wgpu::TextureView albedoView;
1411 wgpu::Texture normal;
1412 wgpu::TextureView normalView;
1413 wgpu::Texture params;
1414 wgpu::TextureView paramsView;
1415 };
1416 int decalWidth = 0, decalHeight = 0;
1417 std::vector<DecalSlot> decalSlots;
1418 std::vector<DecalDraw> decalPassDraws;
1419 glm::mat4 decalViewProj{1.f};
1420 bool decalPassActive = false;
1421 bool decalPassPending = false;
1422 bool decalReady = false;
1423 uint32_t lastDecalSlot = 0;
1424 Texture *decalFlatAlbedo = nullptr;
1425 Texture *decalFlatNormal = nullptr;
1426 Texture *decalFlatParams = nullptr;
1427
1428 // Canvas state.
1429 Canvas *activeCanvas = nullptr;
1430 std::vector<std::unique_ptr<eve::graphics::Canvas>> ownedCanvases;
1431
1432 // Owned resources.
1433 std::vector<std::unique_ptr<Texture>> ownedTextures;
1434 std::vector<std::unique_ptr<GpuTexture>> ownedGpuTextures;
1435 std::unordered_map<std::string, Texture *> texturesByPath;
1436 std::unordered_map<std::string, Texture *> sharedTexturesByContent;
1437 std::vector<std::unique_ptr<Mesh>> ownedMeshes;
1438 std::vector<std::unique_ptr<GpuMesh>> ownedGpuMeshes;
1439 std::vector<std::unique_ptr<Shader>> ownedShaders;
1440 std::vector<std::unique_ptr<GpuShader>> ownedGpuShaders;
1441
1442 // GPU-driven resource tables. WebGPU groups instances into conventional
1443 // mesh/material buckets (portable replacement for Vulkan descriptor indexing),
1444 // then compute-compacts visible transforms and emits indirect commands.
1445 bool gpuDrivenEnabled_ = false;
1446 std::vector<Mesh *> gpuDrivenMeshes_;
1447 std::vector<Material *> gpuDrivenMaterials_;
1448 std::vector<uint32_t> gpuDrivenMaterialFree_;
1449 std::unordered_map<Mesh *, uint32_t> gpuDrivenMeshIds_;
1450 std::unordered_map<Material *, uint32_t> gpuDrivenMaterialIds_;
1451 std::vector<GpuInstance> gpuDrivenPending_;
1452 // CPU mirror is diagnostic-only; rendering consumes the compute output.
1453 std::vector<GpuInstance> gpuDrivenVisible_;
1454 struct GpuDrivenBucket {
1455 Mesh *mesh = nullptr;
1456 Material *material = nullptr;
1457 uint32_t outputBase = 0;
1458 uint32_t inputCount = 0;
1459 };
1460 std::vector<GpuDrivenBucket> gpuDrivenBuckets_;
1461 wgpu::BindGroupLayout gpuDrivenComputeSetLayout_;
1462 wgpu::BindGroupLayout gpuDrivenRenderSetLayout_;
1463 wgpu::PipelineLayout gpuDrivenComputePipelineLayout_;
1464 wgpu::PipelineLayout gpuDrivenRenderPipelineLayout_;
1465 wgpu::ComputePipeline gpuDrivenCullPipeline_;
1466 wgpu::BindGroupLayout gpuDrivenHzbSetLayout_;
1467 wgpu::PipelineLayout gpuDrivenHzbPipelineLayout_;
1468 wgpu::ComputePipeline gpuDrivenHzbPipeline_;
1469 wgpu::Buffer gpuDrivenHzbBuffer_;
1470 wgpu::Buffer gpuDrivenHzbParamsBuffer_;
1471 wgpu::BindGroup gpuDrivenHzbBindGroup_;
1472 std::vector<uint32_t> gpuDrivenHzbOffsets_;
1473 uint32_t gpuDrivenHzbWidth_ = 0;
1474 uint32_t gpuDrivenHzbHeight_ = 0;
1475 uint64_t gpuDrivenHzbCapacity_ = 0;
1476 wgpu::RenderPipeline gpuDrivenRenderPipeline_;
1477 wgpu::RenderPipeline gpuDrivenCanvasPipeline_;
1478 wgpu::RenderPipeline gpuDrivenHdrCanvasPipeline_;
1479 wgpu::RenderPipeline gpuDrivenResidentRenderPipeline_;
1480 wgpu::RenderPipeline gpuDrivenResidentCanvasPipeline_;
1481 wgpu::RenderPipeline gpuDrivenResidentHdrCanvasPipeline_;
1482 wgpu::Buffer gpuDrivenParamsBuffer_;
1483 wgpu::Buffer gpuDrivenInputBuffer_;
1484 wgpu::Buffer gpuDrivenVisibleBuffer_;
1485 wgpu::Buffer gpuDrivenIndirectBuffer_;
1486 wgpu::Buffer gpuDrivenVisIndirectBuffer_;
1487 wgpu::BindGroup gpuDrivenComputeBindGroup_;
1488 wgpu::BindGroup gpuDrivenRenderBindGroup_;
1489 uint64_t gpuDrivenInputCapacity_ = 0;
1490 uint64_t gpuDrivenVisibleCapacity_ = 0;
1491 uint64_t gpuDrivenIndirectCapacity_ = 0;
1492 uint64_t gpuDrivenVisIndirectCapacity_ = 0;
1493 uint32_t gpuDrivenDispatchCount_ = 0;
1494 uint32_t gpuDrivenLastIndirectDrawCount_ = 0;
1495 uint32_t gpuDrivenLastBucketCount_ = 0;
1496 bool gpuDrivenComputePending_ = false;
1497 bool gpuDrivenDrawPending_ = false;
1498 bool gpuDrivenResidentDrawPending_ = false;
1499 WGPUBuffer gpuDrivenResidentBuffer_ = nullptr;
1500 uint64_t gpuDrivenResidentOffset_ = 0;
1501 uint64_t gpuDrivenResidentSize_ = 0;
1502 bool gpuDrivenVisPending_ = false;
1503 bool gpuDrivenResolvePending_ = false;
1504 wgpu::BindGroupLayout gpuDrivenVisSetLayout_;
1505 wgpu::BindGroupLayout gpuDrivenResolveSetLayout_;
1506 wgpu::PipelineLayout gpuDrivenVisPipelineLayout_;
1507 wgpu::PipelineLayout gpuDrivenResolvePipelineLayout_;
1508 wgpu::RenderPipeline gpuDrivenVisPipeline_;
1509 wgpu::RenderPipeline gpuDrivenResolvePipeline_;
1510
1511 struct GpuDrivenVgAsset {
1512 wgpu::Buffer positions;
1513 wgpu::Buffer triangles;
1514 wgpu::Buffer clusters;
1515 wgpu::Buffer indirect;
1516 wgpu::Buffer params;
1517 uint32_t vertexCount = 0;
1518 uint32_t triangleCount = 0;
1519 uint32_t clusterCount = 0;
1520 Mesh *mesh = nullptr;
1521 glm::mat4 model{1.f};
1522 uint32_t materialId = kInvalidGpuDrivenSlot;
1523 bool active = false;
1524 };
1525 std::vector<GpuDrivenVgAsset> gpuDrivenVgAssets_;
1526 std::unordered_map<Mesh *, uint32_t> gpuDrivenVgMeshIds_;
1527 wgpu::BindGroupLayout gpuDrivenVgComputeSetLayout_;
1528 wgpu::BindGroupLayout gpuDrivenVgVisSetLayout_;
1529 wgpu::BindGroupLayout gpuDrivenVgResolveSetLayout_;
1530 wgpu::PipelineLayout gpuDrivenVgComputePipelineLayout_;
1531 wgpu::PipelineLayout gpuDrivenVgVisPipelineLayout_;
1532 wgpu::PipelineLayout gpuDrivenVgResolvePipelineLayout_;
1533 wgpu::ComputePipeline gpuDrivenVgCullPipeline_;
1534 wgpu::RenderPipeline gpuDrivenVgVisPipeline_;
1535 wgpu::RenderPipeline gpuDrivenVgResolvePipeline_;
1536 glm::mat4 gpuDrivenVgViewProj_{1.f};
1537 glm::vec3 gpuDrivenVgCameraPos_{0.f};
1538 float gpuDrivenVgFovYDeg_ = 60.f;
1539 float gpuDrivenVgNear_ = 0.1f;
1540 float gpuDrivenVgFar_ = 100.f;
1541 glm::vec4 gpuDrivenVgPlanes_[6]{};
1542 uint32_t gpuDrivenVgVisibleDiagnostic_ = 0;
1543 uint32_t gpuDrivenVgLastIndirectDrawCount_ = 0;
1544 bool gpuDrivenVgComputePending_ = false;
1545 bool gpuDrivenVgVisPending_ = false;
1546 bool gpuDrivenVgResolvePending_ = false;
1547
1548 // Browser async frame readback (avoids ASYNCIFY sleep inside deep
1549 // JS->Squirrel->Graphics call chains).
1550 struct PendingReadback {
1551 std::string path;
1552 int width = 0, height = 0;
1553 uint64_t bytesPerRow = 0;
1554 wgpu::Buffer dst;
1555 bool mapped = false, done = false, ok = false;
1556 bool hdr = false, bgra = false;
1557 };
1558 std::unique_ptr<PendingReadback> pendingReadback_;
1559
1560 // Cached mesh3d bind groups keyed by the frame-slot UBO buffer, texture
1561 // views and shadow resources. Dynamic offsets reuse a group within one
1562 // frame slot; the buffer identity prevents a group from retaining another
1563 // in-flight slot's UBO arena.
1564 using MeshBindGroupKey =
1565 std::tuple<uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t,
1566 uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t>;
1567 std::map<MeshBindGroupKey, wgpu::BindGroup> meshBindGroupCache_;
1568 static constexpr size_t kMaxMeshBindGroupCache = 128;
1569 void clearMeshBindGroupCache() { meshBindGroupCache_.clear(); }
1570
1571 void markSwapchainDirty() override { swapchainConfigured = false; }
1572 void rebuildSwapchainIfNeeded();
1573 bool acquireSurfaceTexture(wgpu::TextureView &view, wgpu::Texture &texture);
1574};
1575
1576} // namespace eve::graphics::webgpu
double y
double x
bool & active
float w
Definition AnimClip.cpp:738
std::vector< QuestEvent > pending
float ao
float normalStrength
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
float degrees
Definition CardTypes.cpp:38
graphics::Texture * albedo
#define EVENGINE_API_BACKENDS
Definition Export.h:108
std::string layout
float strength
std::uint32_t vertexCount
std::uint32_t indexCount
std::vector< eve::ProcgenProbeDesc > lights
vkb::Device & device
std::uint32_t instanceCount
std::uint32_t capacity
POD RGB triple for Graphics tone-map controls without glm headers.
vk::UniqueSampler sampler
glm::vec4 tint
glm::mat4 mvp
Entity-ID / isolated visibility capture kept off Graphics.h.
std::vector< std::uint32_t > indices
std::vector< float > positions
float blend
int h
std::uint32_t height
std::uint32_t width
std::array< float, 3 > scale
ActionGuidePack pack
bool present
std::string coverage
bool done
uint64_t used
std::vector< RecipeParam > params
std::uint64_t bytes
std::vector< TriangleRef > triangles
MeshVfxBatchedDraw draw
float roughness
float tb
bool doubleSided
Texture * normal
float alphaCutoff
float metallic
std::shared_ptr< OceanGpuSpectrum > owner
OceanMeshSettings mesh
glm::dvec2 center
OceanSprayView view
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::vector< std::weak_ptr< DeviceBytes > > resources
Definition OnnxGpgpu.cpp:55
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::array< uint32_t, 16 > material
Texture * texture
std::string path
Definition PlayHost.cpp:111
float d
int detail
float t
Local-probe upload record kept off the high-fanout IGraphics3D header.
bool lodFadeReverse
glm::vec3 eye
float lodWeight
glm::mat4 viewProj
Shader * shader
bool hair
Lighting3DPack lighting
SurfaceMode surfaceMode
glm::mat4 model
int skinInfluenceLimit
Color clearColor
glm::dmat4 matrix
bool repeatV
bool repeatU
std::string_view source
std::string kind
int count
std::string_view adapter
std::array< double, 2 > vertices[3]
float size
Definition TreeMesh.cpp:158
int caps
Definition TreeMesh.cpp:164
V3 dir
Definition TreeMesh.cpp:151
std::uint32_t depth
double weight
uint32_t index
double gain
Move-only operation result carrying either a value or Status.
Definition Result.h:176
Accumulates solid / textured quads in logical (Y-down) coordinates. Used by RenderSystem; not a publi...
Definition Batcher.h:23
Canvas public API.
Definition Canvas.h:17
virtual void draw(Drawable *drawable, const glm::mat4 &m)
Draws .
bool(*)(void *userdata, void *commandBuffer) PresentOverlayFn
Optional overlay drawn inside the swapchain render pass (before end). Used by declarative UI (ImGui)....
Definition Graphics.h:1671
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Frame-local Skia-style recorder for 2D line primitives.
Frame-local scene recorder for 3D line primitives.
Custom GPU program.
Definition Shader.h:41
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
EVENGINE_API_BACKENDS public API.
Definition Graphics.h:199
wgpu::Queue & getQueue()
Returns the queue.
Definition Graphics.h:776
uint32_t debugGpuDrivenIndirectDrawCount() const
Return indexed-indirect commands recorded by the last scene pass.
Definition Graphics.h:266
float getSceneExposure() const override
Returns the scene exposure.
Definition Graphics.h:601
void * getSdlWindow() const
Returns the sdl window.
Definition Graphics.h:782
float getSceneDofMaxBlur() const override
Returns the scene dof max blur.
Definition Graphics.h:671
int getMsaaSamples() const override
Returns the msaa samples.
Definition Graphics.h:313
void setSceneDepthOfField(float focusDistance, float maxBlurPx, float focusRange, float nearZ, float farZ) override
Sets the scene depth of field.
Definition Graphics.h:660
RgbF getSceneInverseGamma() const override
Returns the scene inverse gamma.
Definition Graphics.h:617
eve::graphics::Graphics::PresentOverlayFn PresentOverlayFn
Definition Graphics.h:788
bool getSceneAutoExposure() const override
Returns the scene auto exposure.
Definition Graphics.h:645
WGPUTextureFormat getSurfaceFormat() const
Returns the surface format.
Definition Graphics.h:780
void setSceneBloom(float intensity, float threshold) override
Sets the scene bloom.
Definition Graphics.h:651
bool isReady() const
True when ready.
Definition Graphics.h:784
uint32_t debugGpuDrivenVisibleCount() const
Return the last CPU compatibility-cull result for backend parity tests.
Definition Graphics.h:262
void setSceneColorFilter(const RgbF &color) override
Sets the scene color filter.
Definition Graphics.h:603
bool gpuDrivenCullEnabled() const override
Gpu driven cull enabled.
Definition Graphics.h:235
std::string getBackendName() const override
Returns the backend name.
Definition Graphics.h:211
float getSceneTransitionVignette() const override
Returns the scene transition vignette.
Definition Graphics.h:631
uint32_t debugGpuDrivenHzbMipCount() const
Return the active hierarchical-depth mip count for conformance tests.
Definition Graphics.h:270
void setSceneAutoExposure(bool enabled, float minEV, float maxEV) override
Sets the scene auto exposure.
Definition Graphics.h:639
float getSceneDofFarZ() const override
Returns the scene dof far z.
Definition Graphics.h:677
bool supportsDeferredLighting() const override
Supports deferred lighting.
Definition Graphics.h:215
uint32_t debugGpuDrivenDispatchCount() const
Return instances dispatched by the last WebGPU compute cull.
Definition Graphics.h:264
uint32_t debugGpuDrivenVgDispatchCount() const
Return VG clusters dispatched by the last WebGPU compute section.
Definition Graphics.h:272
float getSceneTransitionLensDistortion() const override
Returns the scene transition lens distortion.
Definition Graphics.h:635
bool supportsDecal() const override
Supports decal.
Definition Graphics.h:713
wgpu::Instance & getInstance()
Returns the instance.
Definition Graphics.h:772
void setSceneTransitionFx(float vignette, float vignetteSmoothness, float lensDistortion, float lensScale) override
Sets the scene transition fx.
Definition Graphics.h:623
bool supportsGBufferPost() const override
Supports g buffer post.
Definition Graphics.h:213
RgbF getSceneColorFilter() const override
Returns the scene color filter.
Definition Graphics.h:607
float getSceneAutoExposureMaxEV() const override
Returns the scene auto exposure max ev.
Definition Graphics.h:649
float getSceneDofFocusDistance() const override
Returns the scene dof focus distance.
Definition Graphics.h:669
wgpu::Surface & getSurface()
Returns the surface.
Definition Graphics.h:778
float getLastOffscreen3DGpuDurationMs() const override
Returns the last offscreen 3 d gpu duration ms.
Definition Graphics.h:521
float getSceneTransitionVignetteSmoothness() const override
Returns the scene transition vignette smoothness.
Definition Graphics.h:633
RgbF getSceneGain() const override
Returns the scene gain.
Definition Graphics.h:621
float getSceneBloomIntensity() const override
Returns the scene bloom intensity.
Definition Graphics.h:656
void gpuDrivenSetEnabled(bool enabled) override
Gpu driven set enabled.
Definition Graphics.h:223
bool gpuDrivenEnabled() const override
Gpu driven enabled.
Definition Graphics.h:221
float getSceneBloomThreshold() const override
Returns the scene bloom threshold.
Definition Graphics.h:658
float getSceneDofNearZ() const override
Returns the scene dof near z.
Definition Graphics.h:675
float getSceneTransitionLensScale() const override
Returns the scene transition lens scale.
Definition Graphics.h:637
void setSceneExposure(float exposure) override
Sets the scene exposure.
Definition Graphics.h:599
wgpu::Device & getDevice()
Returns the device.
Definition Graphics.h:774
RgbF getSceneLift() const override
Returns the scene lift.
Definition Graphics.h:615
float getSceneAutoExposureMinEV() const override
Returns the scene auto exposure min ev.
Definition Graphics.h:647
float getSceneDofFocusRange() const override
Returns the scene dof focus range.
Definition Graphics.h:673
void setSceneLiftGammaGain(const RgbF &lift, const RgbF &inverseGamma, const RgbF &gain) override
Sets the scene lift gamma gain.
Definition Graphics.h:609
bool supportsGpuDriven3D() const override
Supports gpu driven 3 d.
Definition Graphics.h:219
void requestSurfaceRecreate() override
Request surface recreate.
Definition Graphics.h:309
uint32_t debugGpuDrivenVgIndirectDrawCount() const
Return per-cluster indirect commands recorded by the VG visibility pass.
Definition Graphics.h:274
Offscreen render target (RGBA8Unorm color, optional Depth32Float). 2D batches are flushed into the ca...
Definition Canvas.h:17
Represents raw pixel data.
Definition ImageData.h:38
SurfaceMode
How a 3D surface contributes to depth and color passes.
Definition SurfaceMode.h:6
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
constexpr uint32_t kInvalidGpuDrivenSlot
GPU-driven API surface without GLM layout records.
SkinInfluenceLimit
Number of strongest vertex influences retained by GPU skinning.
Definition IGraphics3D.h:20
GpuResidentSubmitStatus
Structured result for direct resident-instance submission.
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Definition RenderTypes.h:11
glm::vec4 Color
Render-neutral RGBA color shared by graphics-facing modules.
Definition RenderTypes.h:8
bool enabled
CPU-built clustered lighting upload for one frame/camera. Point lights are clustered; directional lig...
Per-instance GPU record (std430). Mirrors GLSL GpuInstance.
Direct-render description for a GPU-authored array of GpuInstance records. @ownership buckets and buf...
Neutral GPU upload for one virtual-geometry asset. Raw arrays so the graphics module does not depend ...
GPU light packing for mesh3d / PBR (std140-friendly).
Definition Light.h:160
Lighting2DUBO public API.
Definition Light.h:52
Lighting3DPack public API.
Definition Light.h:171
static constexpr int kMaxLights
Definition Light.h:172
static constexpr int kMaxDiffuseVolumeProbes
Definition Light.h:178
Owning material parameter snapshot; texture pointers remain borrowed. Base color/metallic/roughness c...
Definition PbrSurface.h:240
ReflectionProbeUpload public API.
Linear RGB triple used by scene color-grade getters/setters.
Definition GraphicsRgb.h:11
ShadowUpload public API.
Definition Shadow.h:62
Options for Graphics::newTexture / newCubemap. When generateMipmaps is true and sampler....
Sampler state for a Texture (filter, wrap, mip LOD, anisotropy). Defaults match historical engine beh...
Instance + adapter + device + queue + capability snapshot.
Definition InitFlow.h:31
Vertex/index buffers for one mesh.
Definition Graphics.h:159
std::vector< float > updateVertices
Definition Graphics.h:169
wgpu::IndexFormat indexFormat
Definition Graphics.h:167
std::vector< uint16_t > updateIndices16
Definition Graphics.h:170
std::vector< MeshVertex > cpuVertices
Definition Graphics.h:168
A compiled shader: one WebGPU pipeline + layout. Also holds the WGSL sources so custom shaders can be...
Definition Graphics.h:177
wgpu::RenderPipeline mesh3dPipeline
Definition Graphics.h:184
wgpu::RenderPipeline offscreenOpaquePipeline
Definition Graphics.h:181
wgpu::RenderPipeline swapchainOpaquePipeline
Definition Graphics.h:180
wgpu::RenderPipeline swapchainPipeline
Definition Graphics.h:178
wgpu::BindGroupLayout setLayout
Definition Graphics.h:189
wgpu::PipelineLayout pipelineLayout
Definition Graphics.h:188
wgpu::RenderPipeline mesh3dXrayPipeline
Definition Graphics.h:185
wgpu::RenderPipeline offscreenPipeline
Definition Graphics.h:179
wgpu::RenderPipeline gbufferPipeline
Definition Graphics.h:187
wgpu::RenderPipeline shadowPipeline
Definition Graphics.h:186
wgpu::RenderPipeline hdrOffscreenOpaquePipeline
Definition Graphics.h:183
wgpu::RenderPipeline hdrOffscreenPipeline
Definition Graphics.h:182
Texture resources backed by a wgpu texture + view + sampler + bind groups.
Definition Graphics.h:137
Clustered-forward mesh UBO (matches the Vulkan Mesh3DClusteredUBO and the WGSL clustered Frame block)...
Definition Graphics.h:111
glm::vec4 reflectionProbeCenter[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:129
glm::vec4 reflectionProbeExtent[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:130
Frame UBO for the mesh3d pipeline. Mirrors the std140 layout of the WGSL Frame block and the legacy V...
Definition Graphics.h:54
glm::vec4 diffuseVolumeExtent[Lighting3DPack::kMaxDiffuseVolumeProbes]
Definition Graphics.h:80
Light3DGpu lights[Lighting3DPack::kMaxLights]
Definition Graphics.h:62
glm::vec4 reflectionProbeCenter[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:75
glm::vec4 diffuseVolumeSh[Lighting3DPack::kMaxDiffuseVolumeProbes *9]
Definition Graphics.h:81
glm::vec4 reflectionProbeExtent[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:76
glm::vec4 diffuseVolumePosition[Lighting3DPack::kMaxDiffuseVolumeProbes]
Definition Graphics.h:79
MeshVertex public API.
Definition Graphics.h:88
Reproducibly generated full PBR WGSL sources before resource specialization.
SkinPassUBO public API.
Definition Graphics.h:99
glm::vec4 cameraPos
uint32_t outputBase
glm::uvec4 info
glm::vec4 color