载入中...
搜索中...
未找到
PbrVariantSource.cpp
浏览该文件的文档.
3
4#include <cstddef>
5#include <cstdint>
6#include <string>
7#include <array>
8
9#include "graphics/shaders/pbr_gbuffer.frag_wgsl.inc"
10#include "graphics/shaders/pbr_surface.frag_wgsl.inc"
11#include "graphics/shaders/pbr_surface.vert_wgsl.inc"
12
13namespace eve::graphics::webgpu {
14namespace {
15std::string_view sourceView(const std::uint32_t* words, std::size_t count) {
16 std::string_view source(reinterpret_cast<const char*>(words), count * sizeof(std::uint32_t));
17 while (!source.empty() && source.back() == '\0') source.remove_suffix(1);
18 return source;
19}
20
21void eraseDeclaration(std::string& source, std::string_view variable) {
22 const std::string marker = " var " + std::string(variable) + " :";
23 auto position = source.find(marker);
24 if (position == std::string::npos) return;
25 auto begin = source.rfind('\n', position);
26 begin = begin == std::string::npos ? 0 : begin + 1;
27 auto end = source.find('\n', position);
28 end = end == std::string::npos ? source.size() : end + 1;
29 source.erase(begin, end - begin);
30}
31
32void eraseKeepalive(std::string& source, std::string_view variable) {
33 const std::string marker = "_ = " + std::string(variable) + ";";
34 std::size_t position = 0;
35 while ((position = source.find(marker, position)) != std::string::npos) {
36 auto begin = source.rfind('\n', position);
37 begin = begin == std::string::npos ? 0 : begin + 1;
38 auto end = source.find('\n', position);
39 end = end == std::string::npos ? source.size() : end + 1;
40 source.erase(begin, end - begin);
41 }
42}
43
44void replaceAll(std::string& source, std::string_view from, std::string_view to) {
45 std::size_t position = 0;
46 while ((position = source.find(from, position)) != std::string::npos) {
47 source.replace(position, from.size(), to);
48 position += to.size();
49 }
50}
51
52std::string samplerName(std::uint32_t resource) {
53 constexpr auto canonicalCount = std::uint32_t(PbrTextureSlot::Count);
54 if (resource < canonicalCount) return "map" + std::to_string(resource) + "_sampler";
55 return "detailMap" + std::to_string(resource - canonicalCount) + "_sampler";
56}
57
58void coalesceSampler(std::string& source, std::string_view resource, std::uint32_t resourceIndex,
59 std::uint32_t representative) {
60 if (representative == PbrVariantPlan::NoSampler || representative == resourceIndex) return;
61 const std::string sampler = std::string(resource) + "_sampler";
62 eraseDeclaration(source, sampler);
63 eraseKeepalive(source, sampler);
64 replaceAll(source, sampler, samplerName(representative));
65}
66
67void replaceResourceCalls(std::string& source, std::string_view function, std::string_view resource,
68 std::string_view replacement) {
69 const std::string prefix = std::string(function) + "(" + std::string(resource);
70 std::size_t begin = 0;
71 while ((begin = source.find(prefix, begin)) != std::string::npos) {
72 const auto delimiter = begin + prefix.size();
73 if (delimiter >= source.size() || (source[delimiter] != ',' && source[delimiter] != ')')) {
74 begin = delimiter;
75 continue;
76 }
77 std::size_t depth = 0;
78 std::size_t end = begin;
79 for (; end < source.size(); ++end) {
80 if (source[end] == '(') ++depth;
81 if (source[end] == ')' && --depth == 0) {
82 ++end;
83 break;
84 }
85 }
86 source.replace(begin, end - begin, replacement);
87 begin += replacement.size();
88 }
89}
90
91void removeSampledResource(std::string& source, std::string_view base,
92 std::string_view replacement = "vec4<f32>(1.0f)") {
93 const std::string image = std::string(base) + "_image";
94 const std::string sampler = std::string(base) + "_sampler";
95 replaceResourceCalls(source, "textureSampleLevel", image, replacement);
96 replaceResourceCalls(source, "textureSampleCompare", image, "1.0f");
97 replaceResourceCalls(source, "textureSample", image, replacement);
98 eraseDeclaration(source, image);
99 eraseDeclaration(source, sampler);
100 eraseKeepalive(source, image);
101 eraseKeepalive(source, sampler);
102}
103} // namespace
104
106 return {sourceView(pbr_surface_vert_wgsl, pbr_surface_vert_wgsl_count),
107 sourceView(pbr_surface_frag_wgsl, pbr_surface_frag_wgsl_count)};
108}
109
111 auto base = pbrVariantBaseSources();
112 if (gbuffer) base.fragment = sourceView(pbr_gbuffer_frag_wgsl, pbr_gbuffer_frag_wgsl_count);
113 PbrSpecializedSources result{std::string(base.vertex), std::string(base.fragment)};
114 static constexpr std::array<std::string_view, 11> maps{
115 "map0", "map1", "map2", "map3", "map4", "map5", "map6", "map7", "map8", "map9", "map10"};
116 static constexpr std::array<std::string_view, 3> detailMaps{"detailMap0", "detailMap1", "detailMap2"};
117 for (std::uint32_t index = 0; index < maps.size(); ++index)
118 if ((plan.canonicalTextureMask & (1u << index)) == 0u)
119 removeSampledResource(result.fragment, maps[index]);
120 for (std::uint32_t index = 0; index < detailMaps.size(); ++index)
121 if ((plan.detailTextureMask & (1u << index)) == 0u)
122 removeSampledResource(result.fragment, detailMaps[index]);
123 for (std::uint32_t index = 0; index < maps.size(); ++index)
124 if ((plan.canonicalTextureMask & (1u << index)) != 0u)
125 coalesceSampler(result.fragment, maps[index], index,
126 plan.canonicalSamplerRepresentatives[index]);
127 for (std::uint32_t index = 0; index < detailMaps.size(); ++index)
128 if ((plan.detailTextureMask & (1u << index)) != 0u)
129 coalesceSampler(result.fragment, detailMaps[index],
130 std::uint32_t(PbrTextureSlot::Count) + index,
131 plan.detailSamplerRepresentatives[index]);
132 if ((plan.fragmentFlags & PbrExtras) == 0u) removeSampledResource(result.fragment, "extrasMap");
133 if ((plan.fragmentFlags & PbrColors) == 0u) removeSampledResource(result.fragment, "colorsMap");
134 if ((plan.fragmentFlags & PbrFadeNoise) == 0u)
135 removeSampledResource(result.fragment, "vegetationFadeNoise",
136 "vec4<f32>(0.0f, 0.0f, 0.0f, 1.0f)");
137 if ((plan.fragmentFlags & PbrEnvironment) == 0u) {
138 replaceResourceCalls(result.fragment, "textureNumLevels", "environmentMap_image", "1u");
139 removeSampledResource(result.fragment, "environmentMap");
140 }
141 if ((plan.fragmentFlags & PbrShadows) == 0u) {
142 replaceResourceCalls(result.fragment, "textureDimensions", "shadowMap_image", "vec2<u32>(1u)");
143 replaceResourceCalls(result.fragment, "textureNumLayers", "shadowMap_image", "1u");
144 removeSampledResource(result.fragment, "shadowMap", "1.0f");
145 }
146 if ((plan.vertexFlags & PbrVertexField) == 0u) removeSampledResource(result.vertex, "vertexField");
147 if ((plan.vertexFlags & PbrMotionField) == 0u) removeSampledResource(result.vertex, "motionField");
148 if ((plan.vertexFlags & PbrMotionNoise) == 0u) removeSampledResource(result.vertex, "motionNoise");
149 return result;
150}
151
155
157 if (!device || !instance)
159 Diagnostic::error(DiagnosticCode::PreconditionViolation, "WebGPU device is not initialized"));
160 device.PushErrorScope(wgpu::ErrorFilter::Validation);
161 auto makeModule = [&](std::string_view source) {
162 wgpu::ShaderSourceWGSL wgsl{};
163 wgsl.code = source.data();
164 wgpu::ShaderModuleDescriptor descriptor{};
165 descriptor.nextInChain = &wgsl;
166 return device.CreateShaderModule(&descriptor);
167 };
168 auto vertex = makeModule(sources.vertex);
169 auto fragment = makeModule(sources.fragment);
170
171 bool done = false;
172 wgpu::ErrorType error = wgpu::ErrorType::Unknown;
173 std::string message;
174 device.PopErrorScope(
175 wgpu::CallbackMode::AllowProcessEvents,
176 [&](wgpu::PopErrorScopeStatus status, wgpu::ErrorType type, wgpu::StringView text) {
177 error = status == wgpu::PopErrorScopeStatus::Success ? type : wgpu::ErrorType::Unknown;
178 if (text.data) message.assign(text.data, text.length);
179 done = true;
180 });
181 while (!done) wgpuInstanceProcessEvents(instance.Get());
182 if (!vertex || !fragment || error != wgpu::ErrorType::NoError)
185 message.empty() ? "WebGPU rejected generated PBR WGSL" : message));
186 return Result<void>::success();
187}
188
191 if (!modules) return modules;
192
193 device.PushErrorScope(wgpu::ErrorFilter::Validation);
194 auto makeModule = [&](std::string_view source) {
195 wgpu::ShaderSourceWGSL wgsl{};
196 wgsl.code = source.data();
197 wgpu::ShaderModuleDescriptor moduleDescriptor{};
198 moduleDescriptor.nextInChain = &wgsl;
199 return device.CreateShaderModule(&moduleDescriptor);
200 };
201 auto vertex = makeModule(sources.vertex);
202 auto fragment = makeModule(sources.fragment);
203
204 std::array<wgpu::VertexAttribute, 16> attributes{};
205 auto attribute = [&](std::size_t index, wgpu::VertexFormat format, std::uint64_t offset,
206 std::uint32_t location) {
207 attributes[index].format = format;
208 attributes[index].offset = offset;
209 attributes[index].shaderLocation = location;
210 };
211 attribute(0, wgpu::VertexFormat::Float32x3, 0, 0);
212 attribute(1, wgpu::VertexFormat::Float32x3, 12, 1);
213 attribute(2, wgpu::VertexFormat::Float32x2, 24, 2);
214 attribute(3, wgpu::VertexFormat::Uint16x4, 32, 3);
215 attribute(4, wgpu::VertexFormat::Float32x4, 40, 4);
216 for (std::uint32_t index = 0; index < 11; ++index)
217 attribute(index + 5, wgpu::VertexFormat::Float32x2, std::uint64_t(index) * 8u, index + 5);
218 std::array<wgpu::VertexBufferLayout, 2> buffers{};
219 buffers[0].arrayStride = 56;
220 buffers[0].attributeCount = 5;
221 buffers[0].attributes = attributes.data();
222 buffers[1].arrayStride = 88;
223 buffers[1].attributeCount = 11;
224 buffers[1].attributes = attributes.data() + 5;
225
226 wgpu::ColorTargetState target{};
227 target.format = wgpu::TextureFormat::RGBA8Unorm;
228 wgpu::FragmentState fragmentState{};
229 fragmentState.module = fragment;
230 fragmentState.entryPoint = "main";
231 fragmentState.targetCount = 1;
232 fragmentState.targets = &target;
233 wgpu::RenderPipelineDescriptor descriptor{};
234 descriptor.vertex.module = vertex;
235 descriptor.vertex.entryPoint = "main";
236 descriptor.vertex.bufferCount = buffers.size();
237 descriptor.vertex.buffers = buffers.data();
238 descriptor.fragment = &fragmentState;
239 descriptor.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
240 descriptor.multisample.count = 1;
241 auto pipeline = device.CreateRenderPipeline(&descriptor);
242
243 bool done = false;
244 wgpu::ErrorType error = wgpu::ErrorType::Unknown;
245 std::string message;
246 device.PopErrorScope(
247 wgpu::CallbackMode::AllowProcessEvents,
248 [&](wgpu::PopErrorScopeStatus status, wgpu::ErrorType type, wgpu::StringView text) {
249 error = status == wgpu::PopErrorScopeStatus::Success ? type : wgpu::ErrorType::Unknown;
250 if (text.data) message.assign(text.data, text.length);
251 done = true;
252 });
253 while (!done) wgpuInstanceProcessEvents(instance.Get());
254 if (!pipeline || error != wgpu::ErrorType::NoError)
256 DiagnosticCode::Failed, message.empty() ? "WebGPU rejected generated PBR pipeline" : message));
257 return Result<void>::success();
258}
259
260} // namespace eve::graphics::webgpu
LogicalId target
std::string descriptor
std::string message
vk::UniqueSampler sampler
vk::UniqueImage image
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
size_t offset
std::array< float, 3 > position
std::string to
std::string from
Poco::JSON::Object::Ptr result
bool done
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::string error
Definition Package.cpp:174
std::map< std::string, double > attributes
std::string attribute
MigrationFunction function
std::string text
std::string_view source
size_t begin
size_t end
int count
std::uint32_t depth
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
Result< void > debugValidatePbrVariantBaseSources()
Compile the generated full PBR WGSL stages under a validation scope.
Result< void > debugValidatePbrVariantSources(const PbrVariantSources &sources)
Compile caller-provided PBR WGSL stages under a validation scope.
Result< void > debugValidatePbrVariantPipeline(const PbrVariantSources &sources)
Compile and link a specialized PBR pair through a real Dawn render pipeline.
PbrSpecializedSources specializePbrVariantSources(const PbrVariantPlan &plan, bool gbuffer)
Specialize the generated WGSL for the resource reachability encoded by a checked plan.
PbrVariantSources pbrVariantBaseSources()
Return immutable full PBR WGSL generated from the canonical GLSL implementation.
Owning WGSL stages after unreachable texture operations and declarations are removed.
Stable resource-layout key and checked stage counts for a PBR snapshot.
static constexpr std::uint32_t NoSampler
Reproducibly generated full PBR WGSL sources before resource specialization.