16using SamplerKey = std::array<std::uint32_t, 4>;
18wgpu::AddressMode addressMode(std::uint32_t
value) {
19 return value == 33071 ? wgpu::AddressMode::ClampToEdge
20 :
value == 33648 ? wgpu::AddressMode::MirrorRepeat
21 : wgpu::AddressMode::Repeat;
24wgpu::Sampler makePbrSampler(
const wgpu::Device&
device,
const PbrTextureBinding&
binding) {
25 const auto nearestMin =
binding.minFilter == 9728 ||
binding.minFilter == 9984 ||
binding.minFilter == 9986;
26 return SamplerBuilder()
27 .address(addressMode(
binding.wrapS), addressMode(
binding.wrapT), wgpu::AddressMode::Repeat)
31 0.f,
binding.minFilter >= 9984 ? 1000.f : 0.f)
36 return std::size_t(
blend) * 16u + (depthWrite ? 8u : 0
u) + (alphaToCoverage ? 4u : 0
u) +
44 WGPUTextureFormat
format = WGPUTextureFormat_Undefined;
58 mesh3dPbrSurface.reset();
65 const auto ownedTexture =
66 std::find_if(ownedTextures.begin(), ownedTextures.end(),
67 [
texture](
const std::unique_ptr<Texture>& candidate) { return candidate.get() == texture; });
68 if (ownedTexture == ownedTextures.end())
73 std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
74 [
gpu](
const std::unique_ptr<GpuTexture>& candidate) { return candidate.get() == gpu; });
75 if (!
gpu || ownedGpu == ownedGpuTextures.end())
85 (array && std::uint32_t(
texture->layers) < minimumLayers))
91 auto ready = requireGpu(
binding.texture,
"PBR texture");
92 if (!ready)
return ready;
93 ready = requireKind(
binding.texture,
"PBR texture",
false,
false);
94 if (!ready)
return ready;
97 auto ready = requireGpu(
binding.texture,
"PBR detail texture");
98 if (!ready)
return ready;
99 ready = requireKind(
binding.texture,
"PBR detail texture",
false,
false);
100 if (!ready)
return ready;
102 for (
auto [
texture, role] : std::array<std::pair<Texture*, const char*>, 6>{
109 auto ready = requireGpu(
texture, role);
110 if (!ready)
return ready;
113 std::array<std::tuple<Texture*, const char*, std::uint32_t>, 4>{
118 auto ready = requireKind(
texture, role,
true,
false,
layer + 1u);
119 if (!ready)
return ready;
122 if (!ready)
return ready;
124 if (!ready)
return ready;
129 mesh3dPbrSurface = *surface;
133bool Graphics::drawPbrMesh(wgpu::RenderPassEncoder pass, WGPUTextureFormat format,
bool canvasTarget,
135 const auto& surface = *
draw.pbrSurface;
136 const bool gbuffer =
draw.gbufferClip.has_value();
137 const bool environment =
138 !gbuffer &&
draw.environment && gpuForTexture(
draw.environment) && gpuForTexture(
draw.environment)->
isCube;
139 const bool shadows = !gbuffer &&
draw.shadows.active &&
draw.shadowReceive && shadowDepthArray;
142 auto evaluationSurface = surface;
147 evaluationSurface.textures[
slot].texture =
nullptr;
150 if (!planned)
throw Exception(
"%s", planned.error()->message().c_str());
151 const auto& plan = planned.value();
153 if (!pbrResources_) pbrResources_.reset(
new PbrResources());
157 const bool depthWrite = !transparent ||
draw.depthWrite;
162 const std::uint32_t samples = canvasTarget ? 1u : sceneColorSamples;
163 const auto raster = rasterKey(
blend, depthWrite, cull, alphaToCoverage) | (gbuffer ? 256u : 0
u);
165 return candidate.plan == plan && candidate.format == format && candidate.samples == samples &&
166 candidate.raster == raster;
170 wgpu::ShaderSourceWGSL vertexWgsl{};
171 vertexWgsl.code =
source.vertex.c_str();
172 wgpu::ShaderModuleDescriptor vertexDescriptor{};
173 vertexDescriptor.nextInChain = &vertexWgsl;
174 auto vertex =
device.CreateShaderModule(&vertexDescriptor);
175 wgpu::ShaderSourceWGSL fragmentWgsl{};
176 fragmentWgsl.code =
source.fragment.c_str();
177 wgpu::ShaderModuleDescriptor fragmentDescriptor{};
178 fragmentDescriptor.nextInChain = &fragmentWgsl;
179 auto fragment =
device.CreateShaderModule(&fragmentDescriptor);
181 std::array<wgpu::VertexAttribute, 16>
attributes{};
183 std::uint32_t location) {
188 attribute(0, wgpu::VertexFormat::Float32x3, 0, 0);
189 attribute(1, wgpu::VertexFormat::Float32x3, 12, 1);
190 attribute(2, wgpu::VertexFormat::Float32x2, 24, 2);
191 attribute(3, wgpu::VertexFormat::Uint16x4, 32, 3);
192 attribute(4, wgpu::VertexFormat::Float32x4, 40, 4);
195 std::array<wgpu::VertexBufferLayout, 2> buffers{};
196 buffers[0].arrayStride =
sizeof(MeshVertex);
197 buffers[0].attributeCount = 5;
199 buffers[1].arrayStride = 11u * 2u *
sizeof(float);
200 buffers[1].attributeCount = 11;
201 buffers[1].attributes =
attributes.data() + 5;
204 blendState.color.operation = wgpu::BlendOperation::Add;
205 blendState.alpha.operation = wgpu::BlendOperation::Add;
208 : wgpu::BlendFactor::SrcAlpha;
210 : wgpu::BlendFactor::OneMinusSrcAlpha;
211 blendState.alpha.srcFactor = wgpu::BlendFactor::One;
212 blendState.alpha.dstFactor = wgpu::BlendFactor::OneMinusSrcAlpha;
214 blendState.color.srcFactor = wgpu::BlendFactor::Dst;
215 blendState.color.dstFactor = wgpu::BlendFactor::Zero;
217 wgpu::ColorTargetState
target{};
218 target.format = wgpu::TextureFormat(format);
220 target.writeMask = wgpu::ColorWriteMask::All;
221 wgpu::FragmentState fragmentState{};
222 fragmentState.module = fragment;
223 fragmentState.entryPoint =
"main";
224 std::array<wgpu::ColorTargetState, 5>
targets;
226 if (gbuffer)
targets[4].format = wgpu::TextureFormat::RGBA16Float;
227 fragmentState.targetCount = gbuffer ? 5u : 1u;
228 fragmentState.targets =
targets.data();
229 wgpu::DepthStencilState
depth{};
230 depth.format = wgpu::TextureFormat::Depth32Float;
231 depth.depthWriteEnabled = depthWrite ? wgpu::OptionalBool::True : wgpu::OptionalBool::False;
234 blend ==
BlendMode::Opaque && depthWrite ? wgpu::CompareFunction::LessEqual : wgpu::CompareFunction::Less;
238 descriptor.vertex.bufferCount = buffers.size();
241 descriptor.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
242 descriptor.primitive.frontFace = wgpu::FrontFace::CCW;
245 : wgpu::CullMode::Back;
249 descriptor.multisample.alphaToCoverageEnabled = alphaToCoverage;
250 PbrResources::Pipeline candidate{plan, format, samples, raster};
252 candidate.layout = candidate.pipeline.GetBindGroupLayout(0);
253 resources.pipelines.push_back(std::move(candidate));
257 float surfaceCode = float(
int(
draw.surfaceMode));
260 const std::uint32_t skinCount =
draw.mesh->hasGpuSkinning() ?
draw.mesh->getSkinPaletteCount() : 0;
264 draw.lighting,
draw.metallic,
draw.roughness, surfaceCode,
draw.alphaCutoff,
265 environment ?
draw.environmentIntensity : 0.f, skinCount});
269 uniform.lights[0].posRadius = *
draw.gbufferClip;
273 for (std::size_t
slot = 0;
slot < surface.textures.size(); ++
slot) {
277 throw Exception(
"PBR texture references missing mesh UV channel");
278 if (!
values.empty()) uniform.uvInfo[
slot].offset = 0
u;
279 for (std::size_t vertexIndex = 0; vertexIndex <
vertexCount; ++vertexIndex) {
280 const auto fallback =
mesh.cpuVertices[vertexIndex].uv;
281 uv[vertexIndex * 22u +
slot * 2u] =
values.empty() ? fallback.x :
values[vertexIndex * 2u];
282 uv[vertexIndex * 22u +
slot * 2u + 1u] =
values.empty() ? fallback.y :
values[vertexIndex * 2u + 1u];
288 uniform.tangentInfo = {std::uint32_t(
attributes.size()), 1u, 0
u, 0
u};
289 const auto& tangents =
draw.mesh->importedTangents();
290 const auto& bitangents =
draw.mesh->importedBitangents();
296 const auto highlights =
draw.mesh->motionHighlights();
297 if (!highlights.empty()) {
298 uniform.tangentInfo.z = std::uint32_t(
attributes.size());
299 uniform.tangentInfo.w = 1u;
302 const auto factors =
draw.mesh->vegetationFactors();
303 if (!factors.empty()) {
304 uniform.vegetationInfo.x = std::uint32_t(
attributes.size());
305 uniform.vegetationInfo.y = 1u;
308 const auto deformation =
draw.mesh->vegetationDeformationFactors();
309 if (!deformation.empty()) {
310 uniform.vertexInfo.z = std::uint32_t(
attributes.size());
311 uniform.vertexInfo.w = 1u;
315 throw Exception(
"PBR GPU vegetation motion requires a nine-float rest-deformation stream");
317 auto& arena = currentUboArena();
318 const auto uniformOffset = arena.alloc(
sizeof(uniform), 256);
319 const auto shadowOffset = arena.alloc(
sizeof(ShadowUBO), 256);
320 queue.WriteBuffer(arena.buffer, uniformOffset, &uniform,
sizeof(uniform));
321 auto shadow =
draw.shadows.ubo;
324 shadow.splits.w = 0.f;
326 shadow.bias.z =
draw.shadowReceive ? 1.f : 0.f;
327 queue.WriteBuffer(arena.buffer, shadowOffset, &shadow,
sizeof(shadow));
329 const auto allocateAux = [&](
const void* data, std::uint64_t
bytes) {
330 const auto index = arena.paletteIndex++;
331 if (arena.palettes.size() <=
index) arena.palettes.resize(
index + 1u);
336 descriptor.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Storage | wgpu::BufferUsage::Vertex;
342 auto uvBuffer = allocateAux(
uv.data(),
uv.size() *
sizeof(
float));
344 auto skinBuffer = uploadSkinPalette(
draw.mesh);
346 std::vector<wgpu::BindGroupEntry>
entries;
347 const auto addBuffer = [&](std::uint32_t
binding,
const wgpu::Buffer&
buffer, std::uint64_t
offset,
348 std::uint64_t
size) {
349 wgpu::BindGroupEntry entry{};
356 const auto addTexture = [&](std::uint32_t
binding, GpuTexture*
texture) {
357 wgpu::BindGroupEntry entry{};
359 entry.textureView =
texture->view;
362 const auto addSampler = [&](std::uint32_t
binding,
const wgpu::Sampler&
sampler) {
363 wgpu::BindGroupEntry entry{};
368 addBuffer(0, arena.buffer, uniformOffset,
sizeof(uniform));
369 addBuffer(2, attributeBuffer, 0,
attributes.size() *
sizeof(
float));
370 addBuffer(3, skinBuffer, 0, skinBuffer.GetSize());
371 if (!gbuffer) addBuffer(6, arena.buffer, shadowOffset,
sizeof(shadow));
373 const auto samplerFor = [&](
const PbrTextureBinding&
binding) ->
const wgpu::Sampler& {
380 for (std::uint32_t
slot = 0;
slot < std::uint32_t(surface.textures.size()); ++
slot) {
381 if ((plan.canonicalTextureMask & (1u <<
slot)) == 0
u)
continue;
382 addTexture(20u +
slot * 2u, gpuForTexture(surface.textures[
slot].texture));
383 if (plan.canonicalSamplerRepresentatives[
slot] ==
slot)
384 addSampler(21u +
slot * 2u, samplerFor(surface.textures[
slot]));
386 for (std::uint32_t
slot = 0;
slot < std::uint32_t(surface.vegetationDetail.textures.size()); ++
slot) {
387 if ((plan.detailTextureMask & (1u <<
slot)) == 0
u)
continue;
388 addTexture(42u +
slot * 2u, gpuForTexture(surface.vegetationDetail.textures[
slot].texture));
390 addSampler(43u +
slot * 2u, samplerFor(surface.vegetationDetail.textures[
slot]));
395 addSampler(5,
texture->sampler);
398 addTexture(7, shadowDepthArray);
399 addSampler(8, shadowDepthArray->
sampler);
402 auto*
texture = gpuForTexture(surface.vegetationExtras.texture);
404 addSampler(10,
texture->sampler);
407 auto*
texture = gpuForTexture(surface.vegetationColors.texture);
409 addSampler(12,
texture->sampler);
412 auto*
texture = gpuForTexture(surface.vegetationAlpha.noise);
414 addSampler(14,
texture->sampler);
417 auto*
texture = gpuForTexture(surface.vegetationVertex.texture);
419 addSampler(51,
texture->sampler);
422 auto*
texture = gpuForTexture(surface.vegetationMotion.texture);
424 addSampler(53,
texture->sampler);
427 auto*
texture = gpuForTexture(surface.vegetationMotion.noise);
429 addSampler(55,
texture->sampler);
432 wgpu::BindGroupDescriptor bindDescriptor{};
433 bindDescriptor.layout =
found->layout;
434 bindDescriptor.entryCount =
entries.size();
435 bindDescriptor.entries =
entries.data();
436 auto bindGroup =
device.CreateBindGroup(&bindDescriptor);
437 pass.SetPipeline(
found->pipeline);
438 pass.SetBindGroup(0, bindGroup);
439 pass.SetVertexBuffer(0,
mesh.vertexBuffer, 0, std::uint64_t(
mesh.vertexCount) *
mesh.vertexStride);
440 pass.SetVertexBuffer(1, uvBuffer, 0,
uv.size() *
sizeof(
float));
441 if (
mesh.indexBuffer) {
442 const auto indexBytes =
mesh.indexFormat == wgpu::IndexFormat::Uint16 ? 2u : 4u;
443 pass.SetIndexBuffer(
mesh.indexBuffer,
mesh.indexFormat, 0, std::uint64_t(
mesh.indexCount) * indexBytes);
444 pass.DrawIndexed(
mesh.indexCount, 1, 0, 0, 0);
446 pass.Draw(
mesh.vertexCount, 1, 0, 0);
std::unordered_map< std::string, QuestRuntime > entries
std::vector< FieldTarget > targets
std::uint32_t vertexCount
vk::UniqueSampler sampler
std::shared_ptr< OceanGpuSpectrum > gpu
std::vector< std::weak_ptr< DeviceBytes > > resources
std::unique_ptr< gpgpu::GpuBuffer > buffer
eve::action::ActionVfxBinding binding
std::set< std::string > values
std::map< std::string, double > attributes
const AssetImportLimits & limits
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
uint32_t maxSamplersPerShaderStage() const
Maximum samplers visible to one shader stage.
uint32_t maxSampledTexturesPerShaderStage() const
Maximum sampled textures visible to one shader stage.
Result< void > setMesh3DPbrSurface(const PbrSurface *surface) override
Sets the mesh 3 d pbr surface.
PbrUniformGpu buildPbrUniformGpu(const PbrUniformBuildInputs &inputs)
Build all material and scene fields; mesh stream offsets remain disabled for the backend to fill.
WGPUBlendState blendState(BlendMode mode)
Internal WebGPU pipeline/descriptor helper; render-thread only.
PbrSpecializedSources specializePbrVariantSources(const PbrVariantPlan &plan, bool gbuffer)
Specialize the generated WGSL for the resource reachability encoded by a checked plan.
Result< PbrVariantPlan > planPbrVariant(const PbrSurface &surface, bool environment, bool shadows, const PbrVariantLimits &limits)
Plan only resources reachable for an immutable PBR draw snapshot.
FilterMode
Mag/min filter for texture sampling.
PbrCullMode
Raster face culling requested by a PBR material.
Result< void > validatePbrSurface(const PbrSurface &s)
Validate finite material factors and sampler enums without changing the input.
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Owning material parameter snapshot; texture pointers remain borrowed. Base color/metallic/roughness c...
PbrVegetationMotion vegetationMotion
PbrVegetationExtras vegetationExtras
std::array< PbrTextureBinding, std::size_t(PbrTextureSlot::Count)> textures
PbrVegetationVertex vegetationVertex
PbrVegetationColors vegetationColors
PbrVegetationDetail vegetationDetail
PbrVegetationAlpha vegetationAlpha
std::array< PbrTextureBinding, 3 > textures
Vertex/index buffers for one mesh.
wgpu::BindGroupLayout layout
wgpu::RenderPipeline pipeline
std::map< SamplerKey, wgpu::Sampler > samplers
std::vector< Pipeline > pipelines
Device resource limits relevant to one extended PBR shader variant.
Stable resource-layout key and checked stage counts for a PBR snapshot.