载入中...
搜索中...
未找到
Water.cpp
浏览该文件的文档.
1#include "graphics/Water.h"
2#include <algorithm>
3#include <cmath>
4#include <limits>
5#include <simplesquirrel/simplesquirrel.hpp>
6#include <string>
7#include <vector>
9#include "graphics/GBuffer.h"
10#include "graphics/Graphics.h"
11#include "graphics/Mesh.h"
15#include "graphics/Shader.h"
19#include "graphics/shaders/water_frag_spv.inc"
20#include "graphics/shaders/water_vert_spv.inc"
21#include "image/ImageData.h"
22
23// Water.cpp
24namespace eve::graphics {
25
26namespace {
27
28// Push-constant layout (data[32]):
29// 0 time, 1 waveSpeed, 2 waveAmp, 3 waveScale, 4 rippleAmp,
30// 5 rippleCount, 6 rippleInterval, 7 foamWidth, 8 foamSoftness,
31// 9 foamStrength, 10..12 deepColor, 13..15 shallowColor,
32// 16 depthDistance, 17..19 foamColor, 20 reflectionIntensity,
33// 21..23 reflectionTint, 24 sunIntensity, 25 fresnelPower,
34// 26 causticsStrength, 27 signedSsrStrength, 28 refractionStrength,
35// 29 signedOpacityAndDepthAvailability, 30 causticsScale, 31 waveSharpness.
36
37const char* kUniformNames[] = {
38 "time",
39 "waveSpeed",
40 "waveAmp",
41 "waveScale",
42 "rippleAmp",
43 "rippleCnt",
44 "rippleInt",
45 "foamWidth",
46 "foamSoftness",
47 "foamStrength",
48 "deepColor",
49 "shallowColor",
50 "depthDistance",
51 "foamColor",
52 "reflInten",
53 "reflTint",
54 "sunInten",
55 "fresnelPower",
56 "causticsStrength",
57 "ssrStrength",
58 "refractionStrength",
59 "opacityAndDepth",
60 "causticsScale",
61 "waveSharpness",
62};
63const int kUniformCount = int(sizeof(kUniformNames) / sizeof(kUniformNames[0]));
64
65} // namespace
66
67namespace {
68Result<glm::ivec2> waterPointCounts(const WaterMeshSettings& settings) {
70 !std::isfinite(settings.sizeX) || !std::isfinite(settings.sizeY) || !std::isfinite(settings.sizeZ) ||
71 !std::isfinite(settings.densityX) || !std::isfinite(settings.densityY) || !std::isfinite(settings.height) ||
72 settings.sizeX <= 0.0F || settings.sizeY <= 0.0F || settings.sizeZ <= 0.0F || settings.densityX <= 0.0F ||
73 settings.densityY <= 0.0F) {
76 "water.mesh: finite positive size/density and a supported shape are required"));
77 }
78 const double scale = settings.type == WaterMeshType::Plane ? 1.0 : 0.5;
79 const double rawX = double(settings.densityX) / 40.0 * double(settings.sizeX) * scale;
80 const double rawY = double(settings.densityY) / 40.0 * double(settings.sizeZ) * scale;
81 if (rawX > 4096.0 || rawY > 4096.0)
83 Diagnostic::error(DiagnosticCode::InvalidArgument, "water.mesh: generated axis point count exceeds 4096"));
84 int x = static_cast<int>(std::nearbyint(rawX));
85 int y = static_cast<int>(std::nearbyint(rawY));
86 if (settings.type == WaterMeshType::Plane) {
87 ++x;
88 ++y;
89 if (x < 2 || y < 2)
91 Diagnostic::error(DiagnosticCode::InvalidArgument, "water.mesh: plane requires at least one polygon"));
92 } else if (x < 1 || y < 1) {
94 Diagnostic::error(DiagnosticCode::InvalidArgument, "water.mesh: circle requires at least one ring"));
95 }
97}
98
99int waterCirclePoint(int ring, int extent) {
100 if (ring < 0) return 0;
101 const int count = (ring + 1) * 6;
102 extent %= count;
103 if (extent < 0) extent += count;
104 return 3 * ring * (ring + 1) + extent + 1;
105}
106
107template <typename Stop, typename Value, typename Project>
108Value sampleStops(const std::vector<Stop>& stops, float time, Project project) {
109 if (time <= stops.front().time) return project(stops.front());
110 if (time >= stops.back().time) return project(stops.back());
111 for (std::size_t i = 1; i < stops.size(); ++i)
112 if (time <= stops[i].time) {
113 const auto& a = stops[i - 1];
114 const auto& b = stops[i];
115 const float t = (time - a.time) / (b.time - a.time);
116 return project(a) + (project(b) - project(a)) * t;
117 }
118 return project(stops.back());
119}
120} // namespace
121
122Result<void> WaterDepthGradient::addColorStop(float time, float red, float green, float blue) {
123 if (!std::isfinite(time) || !std::isfinite(red) || !std::isfinite(green) || !std::isfinite(blue) || time < 0.0F ||
124 time > 1.0F || red < 0.0F || red > 1.0F || green < 0.0F || green > 1.0F || blue < 0.0F || blue > 1.0F)
126 Diagnostic::error(DiagnosticCode::InvalidArgument, "water.gradient: normalized finite RGB stop required"));
127 auto candidate = colorStops;
128 candidate.push_back({time, {red, green, blue}});
129 std::stable_sort(candidate.begin(), candidate.end(), [](const auto& a, const auto& b) { return a.time < b.time; });
130 colorStops = std::move(candidate);
131 return Result<void>::success();
132}
133
135 if (!std::isfinite(time) || !std::isfinite(alpha) || time < 0.0F || time > 1.0F || alpha < 0.0F || alpha > 1.0F)
137 "water.gradient: normalized finite alpha stop required"));
138 auto candidate = alphaStops;
139 candidate.push_back({time, alpha});
140 std::stable_sort(candidate.begin(), candidate.end(), [](const auto& a, const auto& b) { return a.time < b.time; });
141 alphaStops = std::move(candidate);
142 return Result<void>::success();
143}
144
146 colorStops.clear();
147 alphaStops.clear();
148}
149
151 auto counts = waterPointCounts(settings);
152 if (!counts) return Result<int>::failure(counts.status());
153 const std::int64_t triangles = settings.type == WaterMeshType::Plane
154 ? std::int64_t(counts.value().x - 1) * (counts.value().y - 1) * 2
155 : std::int64_t(counts.value().x) * counts.value().x * 6;
156 if (triangles <= 0 || triangles > std::numeric_limits<int>::max() / 3)
158 Diagnostic::error(DiagnosticCode::InvalidArgument, "water.mesh: triangle count is not representable"));
159 return Result<int>::success(static_cast<int>(triangles));
160}
161
163 // Use precompiled SPIR-V (not runtime glslc) so the water shader also works
164 // on platforms without a runtime compiler (e.g. Windows).
165 Shader* sh = nullptr;
166 if (gfx->getBackendName() == "webgpu") {
168 } else {
169 std::vector<uint32_t> vert(water_vert_spv, water_vert_spv + water_vert_spv_count);
170 std::vector<uint32_t> frag(water_frag_spv, water_frag_spv + water_frag_spv_count);
171 sh = gfx->newMeshShaderFromSpv(vert, frag);
172 }
173 gfx->configureMeshShaderSurface(*sh, BlendMode::Alpha, false, false)
174 .expect("water requires alpha blending with depth writes disabled");
175 for (int i = 0; i < kUniformCount; ++i) {
176 const std::string name(kUniformNames[i]);
177 if (name == "deepColor" || name == "shallowColor" || name == "foamColor" || name == "reflTint")
178 sh->declareVec3(kUniformNames[i]);
179 else
180 sh->declareFloat(kUniformNames[i]);
181 }
182 return sh;
183}
184
185int Water::paramCount() { return kUniformCount; }
186
187std::string Water::paramName(int index) {
188 if (index < 0 || index >= kUniformCount) return {};
189 return kUniformNames[index];
190}
191
192Water::Water(Graphics* gfx) : gfx_(gfx) {
193 shader_ = newWaterShader(gfx);
194 bindParams();
195 captureDrawerToken_ = RenderSystem3D::addCaptureExtraDrawer(
196 0xffffffffu, [this](Graphics&, const Camera3D::Data&, const glm::mat4&, float, uint32_t mask) {
197 if (!reflectionCaptureEnabled_ || (reflectionCaptureMask_ & mask) == 0u) return;
198 drawReflectionCapture();
199 });
200}
201
203
204void Water::createPlane(float sizeX, float sizeZ, int segX, int segZ) {
205 segX = std::max(1, segX);
206 segZ = std::max(1, segZ);
207 std::vector<float> pos, nrm, uv;
208 std::vector<uint32_t> idx;
209 for (int z = 0; z <= segZ; ++z) {
210 for (int x = 0; x <= segX; ++x) {
211 pos.push_back(-sizeX * 0.5f + sizeX * float(x) / segX);
212 pos.push_back(0.f);
213 pos.push_back(-sizeZ * 0.5f + sizeZ * float(z) / segZ);
214 nrm.push_back(0.f);
215 nrm.push_back(1.f);
216 nrm.push_back(0.f);
217 uv.push_back(float(x) / segX);
218 uv.push_back(float(z) / segZ);
219 }
220 }
221 for (int z = 0; z < segZ; ++z) {
222 for (int x = 0; x < segX; ++x) {
223 const uint32_t a = uint32_t(z * (segX + 1) + x);
224 const uint32_t b = a + 1;
225 const uint32_t c = a + uint32_t(segX + 1);
226 const uint32_t d = c + 1;
227 idx.push_back(a);
228 idx.push_back(c);
229 idx.push_back(b);
230 idx.push_back(b);
231 idx.push_back(c);
232 idx.push_back(d);
233 }
234 }
235 mesh_ =
236 gfx_->newMeshFromArrays(pos.data(), nrm.data(), uv.data(), int(pos.size() / 3), idx.data(), int(idx.size()));
237}
238
240 auto counts = waterPointCounts(settings);
241 if (!counts) return Result<int>::failure(counts.status());
242 auto triangleCount = calculateWaterMeshTriangles(settings);
243 if (!triangleCount) return Result<int>::failure(triangleCount.status());
244 if (!gfx_)
246 Diagnostic::error(DiagnosticCode::PreconditionViolation, "water.mesh: graphics owner is unavailable"));
247
248 std::vector<float> pos, nrm, uv;
249 std::vector<uint32_t> idx;
250 if (settings.type == WaterMeshType::Plane) {
251 const int nx = counts.value().x, nz = counts.value().y;
252 pos.reserve(std::size_t(nx) * nz * 3);
253 nrm.reserve(std::size_t(nx) * nz * 3);
254 uv.reserve(std::size_t(nx) * nz * 2);
255 idx.reserve(std::size_t(triangleCount.value()) * 3);
256 const float sx = settings.sizeX / float(nx - 1), sz = settings.sizeZ / float(nz - 1);
257 for (int z = 0; z < nz; ++z)
258 for (int x = 0; x < nx; ++x) {
259 pos.insert(pos.end(), {(float(nx - 1) * 0.5F - x) * sx, settings.height * settings.sizeY,
260 (float(nz - 1) * 0.5F - z) * sz});
261 nrm.insert(nrm.end(), {0.0F, 1.0F, 0.0F});
262 uv.insert(uv.end(), {(float(nx / 2) - x) / float(nx), (float(nz / 2) - z) / float(nz)});
263 }
264 for (int z = 0; z < nz - 1; ++z)
265 for (int x = 0; x < nx - 1; ++x) {
266 const uint32_t a = uint32_t(z * nx + x), b = a + 1, c = a + uint32_t(nx), d = c + 1;
267 idx.insert(idx.end(), {a, c, b, c, d, b});
268 }
269 } else {
270 const int rings = counts.value().x;
271 const std::size_t vertexCount = 1u + 3u * std::size_t(rings) * std::size_t(rings + 1);
272 pos.reserve(vertexCount * 3);
273 nrm.reserve(vertexCount * 3);
274 uv.reserve(vertexCount * 2);
275 idx.reserve(std::size_t(triangleCount.value()) * 3);
276 const float scaleX = (settings.sizeX * 0.5F) / float(rings);
277 const float scaleZ = (settings.sizeZ * 0.5F) / float(counts.value().y);
278 pos.insert(pos.end(), {0.0F, 0.0F, 0.0F});
279 nrm.insert(nrm.end(), {0.0F, 1.0F, 0.0F});
280 uv.insert(uv.end(), {0.0F, 0.0F});
281 for (int ring = 0; ring < rings; ++ring) {
282 const int ringPoints = (ring + 1) * 6;
283 const float step = 2.0F * 3.14159265358979323846F / float(ringPoints);
284 for (int point = 0; point < ringPoints; ++point) {
285 const float cx = std::cos(step * point) * float(ring + 1);
286 const float cz = std::sin(-step * point) * float(ring + 1);
287 pos.insert(pos.end(), {cx * scaleX, 0.0F, cz * scaleZ});
288 nrm.insert(nrm.end(), {0.0F, 1.0F, 0.0F});
289 uv.insert(uv.end(), {cx / settings.densityX, cz / settings.densityX});
290 }
291 }
292 for (int ring = 0; ring < rings; ++ring) {
293 int other = 0;
294 for (int point = 0; point < (ring + 1) * 6; ++point) {
295 if (point % (ring + 1) != 0) {
296 idx.insert(
297 idx.end(),
298 {uint32_t(waterCirclePoint(ring - 1, other + 1)), uint32_t(waterCirclePoint(ring - 1, other)),
299 uint32_t(waterCirclePoint(ring, point)), uint32_t(waterCirclePoint(ring, point)),
300 uint32_t(waterCirclePoint(ring, point + 1)), uint32_t(waterCirclePoint(ring - 1, other + 1))});
301 ++other;
302 } else {
303 idx.insert(idx.end(),
304 {uint32_t(waterCirclePoint(ring, point)), uint32_t(waterCirclePoint(ring, point + 1)),
305 uint32_t(waterCirclePoint(ring - 1, other))});
306 }
307 }
308 }
309 }
310 Mesh* candidate =
311 gfx_->newMeshFromArrays(pos.data(), nrm.data(), uv.data(), int(pos.size() / 3), idx.data(), int(idx.size()));
312 if (!candidate)
314 Diagnostic::error(DiagnosticCode::Failed, "water.mesh: graphics mesh allocation failed"));
315 mesh_ = candidate;
316 return Result<int>::success(int(pos.size() / 3));
317}
318
320 if (!gfx_ || resolution < 2 || resolution > 4096 || gradient.colorStops.empty() || gradient.alphaStops.empty())
323 "water.gradient: graphics, color/alpha keys and resolution 2..4096 required"));
324 for (std::size_t i = 1; i < gradient.colorStops.size(); ++i)
325 if (gradient.colorStops[i - 1].time == gradient.colorStops[i].time)
327 "water.gradient: duplicate color times are ambiguous"));
328 for (std::size_t i = 1; i < gradient.alphaStops.size(); ++i)
329 if (gradient.alphaStops[i - 1].time == gradient.alphaStops[i].time)
331 "water.gradient: duplicate alpha times are ambiguous"));
332 image::ImageData pixels(resolution, resolution, "RGBA8");
333 for (int x = 0; x < resolution; ++x) {
334 const float t = float(x) / float(resolution);
335 const glm::vec3 color = sampleStops<WaterGradientColorStop, glm::vec3>(
336 gradient.colorStops, t, [](const auto& stop) { return stop.color; });
337 const float alpha = sampleStops<WaterGradientAlphaStop, float>(gradient.alphaStops, t,
338 [](const auto& stop) { return stop.alpha; });
339 for (int y = 0; y < resolution; ++y)
340 pixels.setPixel(x, y, image::ImageData::Colorf{color.r, color.g, color.b, alpha});
341 }
342 Texture* candidate = gfx_->newTextureFromImageData(&pixels, false, false);
343 if (!candidate)
345 Diagnostic::error(DiagnosticCode::Failed, "water.gradient: texture allocation failed"));
346 depthGradientTexture_ = candidate;
347 return Result<int>::success(resolution * resolution);
348}
349
350void Water::update(float dt) {
351 time_ += dt;
352 bindParams();
353}
354
355void Water::setTime(float seconds) {
356 time_ = seconds;
357 bindParams();
358}
359
360void Water::setWaveSpeed(float v) { config_.waveSpeed = std::clamp(v, -20.0F, 20.0F); }
361void Water::setWaveAmplitude(float v) { config_.waveAmplitude = std::clamp(v, 0.0F, 4.0F); }
362void Water::setRippleAmplitude(float v) { config_.rippleAmplitude = std::clamp(v, 0.0F, 4.0F); }
363void Water::setEdgeFalloff(float v) { config_.foamWidth = std::clamp(v, 0.001F, 1000.0F); }
364void Water::setRippleCount(int v) { config_.rippleCount = std::clamp(v, 0, 8); }
365void Water::setRippleInterval(float v) { config_.rippleInterval = std::clamp(v, 0.05F, 60.0F); }
366void Water::setWaveScale(float v) { config_.waveScale = std::clamp(v, 0.01F, 256.0F); }
368 if (!std::isfinite(degrees))
370 Diagnostic::error(DiagnosticCode::InvalidArgument, "water.direction: finite degrees required"));
371 waveDirectionAngle_ = std::fmod(degrees, 360.0F);
372 if (waveDirectionAngle_ < 0.0F) waveDirectionAngle_ += 360.0F;
373 return Result<void>::success();
374}
375void Water::setWaterColor(float r, float g, float b) {
376 config_.deepColor = glm::max(glm::vec3(r, g, b), glm::vec3(0.0F));
377}
378void Water::setReflectionTint(float r, float g, float b) {
379 config_.reflectionTint = glm::max(glm::vec3(r, g, b), glm::vec3(0.0F));
380}
381void Water::setReflectionIntensity(float v) { config_.reflectionIntensity = std::clamp(v, 0.0F, 4.0F); }
382void Water::setSunIntensity(float v) { config_.sunIntensity = std::clamp(v, 0.0F, 8.0F); }
385 config_.screenSpaceReflectionStrength = std::clamp(strength, 0.0F, 4.0F);
386}
387void Water::setViewport(float w, float h) {
388 viewportW_ = std::max(0.f, w);
389 viewportH_ = std::max(0.f, h);
390}
391
393 if (!shader_) return;
394 shader_->sendFloat("time", time_);
395 shader_->sendFloat("waveSpeed", config_.waveSpeed);
396 shader_->sendFloat("waveAmp", config_.waveAmplitude);
397 shader_->sendFloat("waveScale", config_.waveScale);
398 shader_->sendFloat("rippleAmp", config_.rippleAmplitude);
399 // Preserve the 128-byte portable parameter block: the integer part is ripple count and
400 // [0,0.5) stores PWS_WaterSystem.directionAngle / 720. Shaders decode both independently.
401 shader_->sendFloat("rippleCnt", float(config_.rippleCount) + waveDirectionAngle_ / 720.0F);
402 shader_->sendFloat("rippleInt", config_.rippleInterval);
403 shader_->sendFloat("foamWidth", config_.foamWidth);
404 shader_->sendFloat("foamSoftness", config_.foamSoftness);
405 shader_->sendFloat("foamStrength", config_.foamStrength);
406 shader_->sendVec3("deepColor", config_.deepColor.x, config_.deepColor.y, config_.deepColor.z);
407 shader_->sendVec3("shallowColor", config_.shallowColor.x, config_.shallowColor.y, config_.shallowColor.z);
408 shader_->sendFloat("depthDistance", depthGradientTexture_ ? -config_.depthDistance : config_.depthDistance);
409 shader_->sendVec3("foamColor", config_.foamColor.x, config_.foamColor.y, config_.foamColor.z);
410 shader_->sendFloat("reflInten", config_.reflectionIntensity);
411 shader_->sendVec3("reflTint", config_.reflectionTint.x, config_.reflectionTint.y, config_.reflectionTint.z);
412 shader_->sendFloat("sunInten", config_.sunIntensity);
413 shader_->sendFloat("fresnelPower", config_.fresnelPower);
414 shader_->sendFloat("causticsStrength", config_.causticsStrength);
415 shader_->sendFloat("ssrStrength", config_.screenSpaceReflection ? config_.screenSpaceReflectionStrength : -1.0F);
416 shader_->sendFloat("refractionStrength", config_.refractionStrength);
417 shader_->sendFloat("opacityAndDepth", -(config_.opacity + 1.0F));
418 shader_->sendFloat("causticsScale", config_.causticsScale);
419 shader_->sendFloat("waveSharpness", config_.waveSharpness);
420}
421
422Result<void> Water::applyConfigJson(const std::string& json) {
423 auto candidate = WaterStyleConfig::fromJson(json);
424 if (!candidate) return Result<void>::failure(candidate.status());
425 config_ = std::move(candidate).takeValue();
426 bindParams();
427 return Result<void>::success();
428}
429
430Result<std::string> Water::configJson() const { return config_.toJson(); }
431
432void Water::draw() { drawWithReflection(nullptr, 0.0F); }
433
434void Water::drawWithPlanarReflection(Texture* planarReflection, float strength) {
435 drawWithReflection(planarReflection, std::clamp(strength, 0.0F, 4.0F));
436}
437
438void Water::drawWithReflection(Texture* requestedReflection, float requestedStrength) {
439 if (!gfx_ || !mesh_ || !shader_) return;
440 bindParams();
441 Texture* reflection = requestedReflection;
442 float reflectionStrength = requestedReflection ? requestedStrength : -1.0F;
443 RenderControl* rc = gfx_->getRenderControl();
444 if (!reflection && config_.screenSpaceReflection && rc && rc->isEnabled("ssr")) {
446 if (ssr->hasValidHistory()) {
447 reflection = ssr->getReflectionTexture();
448 reflectionStrength = config_.screenSpaceReflectionStrength;
449 }
450 }
451 shader_->sendFloat("ssrStrength", reflection ? reflectionStrength : -1.0F);
452 Texture* depth = rc && rc->getGBuffer() ? rc->getGBuffer()->getDepthTexture() : nullptr;
453 Texture* sceneColor = gfx_->getSceneColorTexture();
454 shader_->sendFloat("opacityAndDepth", depth ? config_.opacity : -(config_.opacity + 1.0F));
455 shader_->sendFloat("refractionStrength", sceneColor ? config_.refractionStrength : 0.0F);
456 gfx_->setMesh3DHeightTexture(reflection);
457 gfx_->setMesh3DNormalTexture(depthGradientTexture_);
459 gfx_->drawMeshShader(mesh_, glm::mat4(1.f), sceneColor, glm::vec4(1.f), shader_);
460 gfx_->setMesh3DHeightTexture(nullptr);
461 gfx_->setMesh3DNormalTexture(nullptr);
462 gfx_->setMesh3DSceneDepth(nullptr);
463}
464
465void Water::drawReflectionCapture() {
466 if (!gfx_ || !mesh_ || !shader_) return;
467 bindParams();
468 // Probe captures must never sample the main-view SSR history: that creates
469 // view-dependent feedback and recursively bakes an old reflection into the cube.
470 shader_->sendFloat("ssrStrength", -1.0F);
471 shader_->sendFloat("opacityAndDepth", -(config_.opacity + 1.0F));
472 shader_->sendFloat("refractionStrength", 0.0F);
473 gfx_->setMesh3DHeightTexture(nullptr);
474 gfx_->setMesh3DNormalTexture(depthGradientTexture_);
475 gfx_->drawMeshShader(mesh_, glm::mat4(1.f), nullptr, glm::vec4(1.f), shader_);
476 gfx_->setMesh3DNormalTexture(nullptr);
477 // Restore the authored state for a subsequent main-view draw in the same frame.
478 shader_->sendFloat("ssrStrength", config_.screenSpaceReflection ? config_.screenSpaceReflectionStrength : -1.0F);
479 shader_->sendFloat("refractionStrength", config_.refractionStrength);
480}
481
482} // namespace eve::graphics
483
484// WaterPlanarReflection.cpp
485namespace eve::graphics {
486namespace {
487bool finite3(const glm::vec3& v) { return std::isfinite(v.x) && std::isfinite(v.y) && std::isfinite(v.z); }
488
489float resolutionScale(WaterReflectionResolution value) {
490 switch (value) {
491 case WaterReflectionResolution::Full: return 1.0F;
492 case WaterReflectionResolution::Half: return 0.5F;
493 case WaterReflectionResolution::Third: return 0.33F;
494 case WaterReflectionResolution::Quarter: return 0.25F;
495 }
496 return 0.0F;
497}
498} // namespace
499
502 const float multiplier = resolutionScale(settings.resolutionMultiplier);
503 if (multiplier == 0.0F || settings.textureResolution <= 0 || settings.textureResolution > 16384 ||
504 !std::isfinite(settings.clipPlaneOffset) || !std::isfinite(settings.customRenderDistance) ||
505 settings.customRenderDistance < 0.0F || !std::isfinite(settings.lodBias) || settings.lodBias <= 0.0F ||
506 !finite3(input.cameraPosition) || !finite3(input.cameraForward) ||
507 glm::dot(input.cameraForward, input.cameraForward) <= 0.0F || !std::isfinite(input.waterPlaneY) ||
508 !std::isfinite(input.renderScale) || input.renderScale <= 0.0F) {
511 "water.planarReflection: finite camera, plane, scale and valid settings required"));
512 }
513 for (float distance : settings.customRenderDistances) {
514 if (!std::isfinite(distance) || distance < 0.0F)
517 "water.planarReflection: layer distances must be finite and nonnegative"));
518 }
519
521 const float planeY = input.waterPlaneY + settings.clipPlaneOffset;
522 plan.reflectionMatrix = glm::mat4(1.0F);
523 plan.reflectionMatrix[1][1] = -1.0F;
524 plan.reflectionMatrix[3][1] = 2.0F * planeY;
525 plan.cameraPosition = {input.cameraPosition.x, 2.0F * planeY - input.cameraPosition.y, input.cameraPosition.z};
526 plan.cameraForward =
527 glm::normalize(glm::vec3(input.cameraForward.x, -input.cameraForward.y, input.cameraForward.z));
528 plan.worldClipPlane = {0.0F, 1.0F, 0.0F, -planeY};
529 plan.cullingMask = settings.enabled ? (settings.reflectLayers & ~(1U << 4U)) : 0U;
530 plan.renderShadows = settings.shadows;
531 plan.shouldRender = settings.enabled && !settings.disableSkyboxReflections && !input.orthographic &&
532 !input.reflectionOrPreviewCamera;
533 const double pixels = static_cast<double>(settings.textureResolution) * input.renderScale * multiplier;
534 plan.textureWidth = plan.textureHeight = std::max(1, static_cast<int>(pixels));
535 if (settings.enableRenderDistance) {
536 if (settings.enablePerLayerDistances) {
537 for (std::size_t i = 0; i < plan.layerCullDistances.size(); ++i)
538 plan.layerCullDistances[i] = settings.customRenderDistances[i] * settings.lodBias;
539 } else
540 plan.layerCullDistances.fill(settings.customRenderDistance * settings.lodBias);
541 }
543}
544
545} // namespace eve::graphics
546
547// WaterPlanarReflectionBindings.cpp
548namespace eve::graphics {
549
550void exposeWaterPlanarReflectionBindings(ssq::Table& table) {
551 auto settings =
552 table.addClass("WaterPlanarReflectionSettings", ssq::Class::Ctor<WaterPlanarReflectionSettings()>());
554 settings.addVar("disableSkyboxReflections", &WaterPlanarReflectionSettings::disableSkyboxReflections);
558 settings.addVar("enableRenderDistance", &WaterPlanarReflectionSettings::enableRenderDistance);
559 settings.addVar("enablePerLayerDistances", &WaterPlanarReflectionSettings::enablePerLayerDistances);
560 settings.addVar("customRenderDistance", &WaterPlanarReflectionSettings::customRenderDistance);
563 settings.addFunc("setResolutionMultiplier", [](WaterPlanarReflectionSettings* value, int multiplier) {
564 value->resolutionMultiplier = static_cast<WaterReflectionResolution>(multiplier);
565 });
566 settings.addFunc("setLayerDistance", [](WaterPlanarReflectionSettings* value, int layer, float distance) {
567 if (value && layer >= 0 && layer < 32) value->customRenderDistances[static_cast<std::size_t>(layer)] = distance;
568 });
569
570 auto input = table.addClass("WaterPlanarReflectionInput", ssq::Class::Ctor<WaterPlanarReflectionInput()>());
571 input.addVar("waterPlaneY", &WaterPlanarReflectionInput::waterPlaneY);
572 input.addVar("renderScale", &WaterPlanarReflectionInput::renderScale);
573 input.addVar("orthographic", &WaterPlanarReflectionInput::orthographic);
574 input.addVar("reflectionOrPreviewCamera", &WaterPlanarReflectionInput::reflectionOrPreviewCamera);
575 input.addFunc("setCameraPosition", [](WaterPlanarReflectionInput* value, float x, float y, float z) {
576 value->cameraPosition = {x, y, z};
577 });
578 input.addFunc("setCameraForward", [](WaterPlanarReflectionInput* value, float x, float y, float z) {
579 value->cameraForward = {x, y, z};
580 });
581
582 auto plan = table.addClass("WaterPlanarReflectionPlan", ssq::Class::Ctor<WaterPlanarReflectionPlan()>());
583 plan.addVar("textureWidth", &WaterPlanarReflectionPlan::textureWidth);
584 plan.addVar("textureHeight", &WaterPlanarReflectionPlan::textureHeight);
585 plan.addVar("cullingMask", &WaterPlanarReflectionPlan::cullingMask);
586 plan.addVar("renderShadows", &WaterPlanarReflectionPlan::renderShadows);
587 plan.addVar("shouldRender", &WaterPlanarReflectionPlan::shouldRender);
588 plan.addFunc("getCameraX", [](const WaterPlanarReflectionPlan* value) { return value->cameraPosition.x; });
589 plan.addFunc("getCameraY", [](const WaterPlanarReflectionPlan* value) { return value->cameraPosition.y; });
590 plan.addFunc("getCameraZ", [](const WaterPlanarReflectionPlan* value) { return value->cameraPosition.z; });
591 plan.addFunc("getForwardY", [](const WaterPlanarReflectionPlan* value) { return value->cameraForward.y; });
592 plan.addFunc("getLayerDistance", [](const WaterPlanarReflectionPlan* value, int layer) {
593 return value && layer >= 0 && layer < 32 ? value->layerCullDistances[static_cast<std::size_t>(layer)] : -1.0F;
594 });
595 plan.addFunc("getReflectionMatrix", [](const WaterPlanarReflectionPlan* value, int column, int row) {
596 return value && column >= 0 && column < 4 && row >= 0 && row < 4
597 ? value->reflectionMatrix[static_cast<std::size_t>(column)][static_cast<std::size_t>(row)]
598 : 0.0F;
599 });
600
601 table.addFunc(
602 "buildWaterPlanarReflectionPlan",
605 if (!output || !settings || !input)
609 "water.planarReflection: non-null output, settings and input required")));
612 *output = std::move(result).takeValue();
614 });
615}
616
617} // namespace eve::graphics
618
619// WaterReflectionMasker.cpp
620namespace eve::graphics {
621namespace {
622bool finite6(float a, float b, float c, float d, float e, float f) {
623 return std::isfinite(a) && std::isfinite(b) && std::isfinite(c) && std::isfinite(d) && std::isfinite(e) &&
624 std::isfinite(f);
625}
626} // namespace
627
629 bool reflectionsEnabled) {
630 const int c = static_cast<int>(channel);
631 if (c < 0 || c > 4 || !std::isfinite(minimum) || !std::isfinite(maximum) || minimum > maximum)
633 "valid channel and finite ordered thresholds are required", {},
634 {}, "graphics.waterReflectionMasker"));
635 channel_ = channel;
636 minimum_ = minimum;
637 maximum_ = maximum;
638 enabled_ = reflectionsEnabled;
639 heightFeaturesEnabled_ = reflectionsEnabled;
640 return Result<void>::success();
641}
642
644 const int width = mask.getWidth(), height = mask.getHeight();
645 if (width <= 0 || height <= 0)
647 "mask dimensions must be positive", {}, {},
648 "graphics.waterReflectionMasker"));
649 std::vector<Pixel> next;
650 next.reserve(static_cast<size_t>(width) * static_cast<size_t>(height));
651 for (int y = 0; y < height; ++y)
652 for (int x = 0; x < width; ++x) {
653 const auto c = mask.getPixel(x, y);
654 next.push_back({c.r, c.g, c.b, c.a});
655 }
656 width_ = width;
657 height_ = height;
658 pixels_ = std::move(next);
659 sampleX_ = sampleY_ = -1;
660 return Result<void>::success();
661}
662
664 width_ = height_ = 0;
665 pixels_.clear();
666 sampleX_ = sampleY_ = -1;
667}
668
670 float terrainZ, float terrainWidth,
671 float terrainDepth,
673 if (!finite6(playerX, playerZ, terrainX, terrainZ, terrainWidth, terrainDepth) || terrainWidth <= 0.f ||
674 terrainDepth <= 0.f)
676 DiagnosticCode::InvalidArgument, "finite player, terrain origin and positive terrain size are required", {},
677 {}, "graphics.waterReflectionMasker"));
678 bool next = false;
679 sampleX_ = sampleY_ = -1;
680 const float u = (playerX - terrainX) / terrainWidth, v = (playerZ - terrainZ) / terrainDepth;
681 if (!pixels_.empty() && u >= 0.f && u <= 1.f && v >= 0.f && v <= 1.f) {
682 const int x = static_cast<int>(std::lround(u * static_cast<float>(width_)));
683 const int y = static_cast<int>(std::lround(v * static_cast<float>(height_)));
684 sampleX_ = x;
685 sampleY_ = y;
686 if (x >= 0 && x < width_ && y >= 0 && y < height_) {
687 const auto& p = pixels_[static_cast<size_t>(y) * static_cast<size_t>(width_) + static_cast<size_t>(x)];
688 const auto hit = [&](float value) { return value >= minimum_ && value <= maximum_; };
689 switch (channel_) {
690 case WaterReflectionMaskChannel::R: next = hit(p.r); break;
691 case WaterReflectionMaskChannel::G: next = hit(p.g); break;
692 case WaterReflectionMaskChannel::B: next = hit(p.b); break;
693 case WaterReflectionMaskChannel::A: next = hit(p.a); break;
694 case WaterReflectionMaskChannel::RGBA: next = hit(p.r) || hit(p.g) || hit(p.b) || hit(p.a); break;
695 }
696 }
697 }
698 if (next == enabled_)
700 enabled_ = next;
701 heightFeaturesEnabled_ = next;
702 settings.enabled = next;
705}
706
707void exposeWaterReflectionMaskerBindings(ssq::Table& table) {
708 auto c = table.addClass("WaterReflectionMasker", ssq::Class::Ctor<WaterReflectionMasker()>());
709 auto vm = table.getHandle();
710 c.addFunc("configure", [vm](WaterReflectionMasker* s, int channel, float min, float max, bool enabled) {
712 vm, s->configure(static_cast<WaterReflectionMaskChannel>(channel), min, max, enabled));
713 });
714 c.addFunc("setMask", [vm](WaterReflectionMasker* s, const image::ImageData* mask) {
715 auto r =
716 mask
717 ? s->setMask(*mask)
719 {}, {}, "graphics.waterReflectionMasker"));
720 return eve::script::projectResult(vm, std::move(r));
721 });
722 c.addFunc("clearMask", [](WaterReflectionMasker* s) { s->clearMask(); });
723 c.addFunc("evaluate", [vm](WaterReflectionMasker* s, float px, float pz, float tx, float tz, float tw, float td,
725 auto r = settings ? s->evaluate(px, pz, tx, tz, tw, td, *settings)
727 Diagnostic::error(DiagnosticCode::InvalidArgument, "reflection settings are required",
728 {}, {}, "graphics.waterReflectionMasker"));
730 vm, std::move(r), [](WaterReflectionMaskTransition v) { return eve::Value(static_cast<int>(v)); });
731 });
732 c.addFunc("getEnabled", [](const WaterReflectionMasker* s) { return s->getEnabled(); });
733 c.addFunc("getHeightFeaturesEnabled", [](const WaterReflectionMasker* s) { return s->getHeightFeaturesEnabled(); });
734 c.addFunc("getSampleX", [](const WaterReflectionMasker* s) { return s->getSampleX(); });
735 c.addFunc("getSampleY", [](const WaterReflectionMasker* s) { return s->getSampleY(); });
736}
737
738} // namespace eve::graphics
double z
double y
double x
float w
Definition AnimClip.cpp:738
std::string output
const std::string & s
int mask
float cx
Definition CardTypes.cpp:36
float degrees
Definition CardTypes.cpp:38
float uv
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
float strength
std::uint32_t vertexCount
float maximum[3]
float minimum[3]
tensor::Graph g
Definition GpuGraph.cpp:7
vk::ShaderModule vert
vk::ShaderModule frag
float u
Definition Grass.cpp:233
double r
float v
std::int32_t c
int h
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
std::array< float, 3 > scale
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
std::vector< TriangleRef > triangles
OceanWakeSettings settings
double dt
TileLayer * layer
int idx
float f
bool hit
Object::Ptr value
float d
float t
uint8_t * pixels
unsigned column
int count
The single Squirrel projection for common Result, Status and Value.
float opacity
float step
Definition TreeMesh.cpp:451
std::uint32_t depth
uint32_t index
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
void expect(std::string_view message) const
Require success for a void operation.
Definition Result.h:582
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
Texture * getDepthTexture() const
Returns the depth texture.
Definition GBuffer.h:51
ScreenSpaceReflection * pipelineScreenSpaceReflection()
Pipeline screen space reflection.
virtual std::string getBackendName() const =0
Renderer backend id used by sibling modules (e.g. Gpgpu).
virtual Shader * newMeshShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv)=0
Create a Mesh3D custom shader (MeshVertex + Frame UBO + albedo). Empty vert → default mesh3d....
Texture * newTextureFromImageData(image::ImageData *data, bool repeatU=false, bool repeatV=false)
Creates a texture from image data. @ownership Caller deletes unless documented otherwise.
virtual void setMesh3DSceneDepth(Texture *depth)=0
Optional scene hardware depth (G-buffer hwDepth, Vulkan NDC z) bound to mesh3d shader binding 7....
virtual eve::Result< void > configureMeshShaderSurface(Shader &, BlendMode, bool, bool)
Prepare a custom mesh shader's blend, depth and culling state.
Definition Graphics.h:1898
virtual Texture * getSceneColorTexture()
Sampleable 3D color target for the current frame (RGB = lit, A = linear depth). Valid after begin3DFr...
Definition Graphics.h:1075
virtual void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint, Shader *shader)=0
Draw mesh with an explicit Mesh3D Shader (nullptr = default PBR pipeline).
RenderControl * getRenderControl()
Shared compilable 3D render control (features → pass list + GBuffer). Owned by Graphics; valid for th...
Definition Graphics.cpp:279
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
virtual Shader * newMeshShaderFromWgsl(const std::string &vertWgsl, const std::string &fragWgsl)=0
Create a Mesh3D custom shader from WGSL source (WebGPU backend). The WGSL must declare the engine's F...
virtual void setMesh3DNormalTexture(Texture *normal)=0
Optional normal map for the next drawMesh / drawMeshShader (nullptr = flat).
virtual void setMesh3DHeightTexture(Texture *height)=0
Optional height map for parallax (R channel; nullptr = flat / off).
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Declarative, compilable 3D render control.
bool isEnabled(const std::string &feature) const
True when enabled.
GBuffer * getGBuffer()
Returns the g buffer.
static void removeCaptureExtraDrawer(uint64_t token)
Unregister an offscreen capture contributor.
static uint64_t addCaptureExtraDrawer(uint32_t reflectionCaptureMask, CaptureExtraDrawer drawer)
Register custom forward geometry for offscreen captures.
Screen-space reflections (SSR) as a fullscreen post pass. @lifetime All Graphics and texture argument...
bool hasValidHistory() const
True once a temporally resolved reflection frame is safe to sample.
Texture * getReflectionTexture()
The reflection texture from the owned canvas, or nullptr before first apply.
Custom GPU program.
Definition Shader.h:41
void sendFloat(const std::string &name, float x)
Definition Shader.cpp:107
void sendVec3(const std::string &name, float x, float y, float z)
Definition Shader.cpp:114
int declareVec3(const std::string &name)
Definition Shader.cpp:57
int declareFloat(const std::string &name)
Reserve sequential float slots in the push-constant block. Returns start index.
Definition Shader.cpp:55
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
Own a CPU snapshot of Pcg's planar-reflection mask and evaluate player movement against it.
void clearMask() noexcept
Clear the mask; subsequent evaluations disable reflections when state changes.
Definition Water.cpp:663
Result< void > setMask(const image::ImageData &mask)
Replace the owned mask snapshot from any readable ImageData format.
Definition Water.cpp:643
Result< WaterReflectionMaskTransition > evaluate(float playerX, float playerZ, float terrainX, float terrainZ, float terrainWidth, float terrainDepth, WaterPlanarReflectionSettings &settings)
Sample a player X/Z position in one terrain's origin and size and update planar reflection settings.
Definition Water.cpp:669
Result< void > configure(WaterReflectionMaskChannel channel, float minimum, float maximum, bool reflectionsEnabled)
Configure inclusive thresholds, channel selection and initial scene-profile state.
Definition Water.cpp:628
Result< void > setWaveDirectionAngle(float degrees)
Set Pcg PWS_WaterSystem wave direction in finite degrees around world Y.
Definition Water.cpp:367
void setScreenSpaceReflection(bool enabled, float strength=0.85f)
Optional screen-space reflection overlay. When enabled, the shader samples the temporally resolved SS...
Definition Water.cpp:383
void setWaveAmplitude(float amp)
Amplitude of the shore-edge waves.
Definition Water.cpp:361
Result< int > createProceduralMesh(const WaterMeshSettings &settings)
Validate, generate and atomically publish a Pcg-compatible plane or concentric-circle mesh.
Definition Water.cpp:239
static std::string paramName(int index)
Param name.
Definition Water.cpp:187
void setRippleAmplitude(float amp)
Amplitude of the occasional middle drop ripples.
Definition Water.cpp:362
Result< std::string > configJson() const
Return the canonical current eve.graphics.stylized-water/1 JSON snapshot.
Definition Water.cpp:430
void setWaveSpeed(float speed)
Sets the wave speed.
Definition Water.cpp:360
Water(Graphics *gfx)
Water.
Definition Water.cpp:192
void update(float dt)
Advance the animation clock by dt seconds.
Definition Water.cpp:350
void draw()
Draw the water plane (uses default mesh3d camera / lighting state).
Definition Water.cpp:432
void setEdgeFalloff(float edge)
Compatibility setter for the world-space shoreline foam width.
Definition Water.cpp:363
void createPlane(float sizeX, float sizeZ, int segX, int segZ)
Build a flat XZ plane (Y-up) sized sizeX × sizeZ with UVs in [0,1]².
Definition Water.cpp:204
void setSunIntensity(float intensity)
Sets the sun intensity.
Definition Water.cpp:382
void setReflectionTint(float r, float g, float b)
Sets the reflection tint.
Definition Water.cpp:378
void setTime(float seconds)
Sets the time.
Definition Water.cpp:355
void setReflectionIntensity(float intensity)
Sets the reflection intensity.
Definition Water.cpp:381
static int paramCount()
Names of the push-constant parameters (for UI / inspection).
Definition Water.cpp:185
void setWaveScale(float scale)
Sets the wave scale.
Definition Water.cpp:366
Result< int > setDepthGradient(const WaterDepthGradient &gradient, int resolution)
Bake Pcg GenerateColorDepth semantics and atomically publish the clamp-sampled texture.
Definition Water.cpp:319
void setRippleInterval(float seconds)
Seconds between drop ripples.
Definition Water.cpp:365
void bindParams()
Upload current params to the shader push constants.
Definition Water.cpp:392
void setViewport(float width, float height)
Window / target size in pixels, used to compute screen-space UVs.
Definition Water.cpp:387
void setRippleCount(int count)
How many expanding drop ripples exist.
Definition Water.cpp:364
void setWaterColor(float r, float g, float b)
Sets the water color.
Definition Water.cpp:375
Result< void > applyConfigJson(const std::string &json)
Atomically replace all authored parameters from eve.graphics.stylized-water/1 JSON.
Definition Water.cpp:422
void drawWithPlanarReflection(Texture *planarReflection, float strength=1.0F)
Draw with an optional caller-rendered planar reflection.
Definition Water.cpp:434
Represents raw pixel data.
Definition ImageData.h:38
medialoader::Colorf Colorf
Definition ImageData.h:41
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
constexpr char kWaterFragWgsl[]
Backend-parity stylized-water WGSL source with depth foam and scene-color refraction.
Definition WaterWgsl.h:40
constexpr char kWaterVertWgsl[]
Vertex-displaced low-frequency water layers for the WebGPU backend.
Definition WaterWgsl.h:6
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
Result< int > calculateWaterMeshTriangles(const WaterMeshSettings &settings)
Calculate Pcg PWS_WaterSystem's triangle count without allocating a mesh.
Definition Water.cpp:150
WaterReflectionResolution
Pcg-compatible render-size multiplier for planar water reflections.
WaterReflectionMaskChannel
Pcg ReflectionMasker channel selection.
void exposeWaterReflectionMaskerBindings(ssq::Table &table)
Register Pcg reflection-mask bindings.
Definition Water.cpp:707
WaterReflectionMaskTransition
Observable reflection-state transition after one player-position sample.
void exposeWaterPlanarReflectionBindings(ssq::Table &table)
Register planar water-reflection value types and checked planner with the VM owner thread.
Definition Water.cpp:550
Shader * newWaterShader(Graphics *gfx)
Create the embedded water fragment shader (owned by Graphics).
Definition Water.cpp:162
Result< WaterPlanarReflectionPlan > buildWaterPlanarReflectionPlan(const WaterPlanarReflectionSettings &settings, const WaterPlanarReflectionInput &input)
Build the mirror-camera plan used by PcgPlanarReflections without retaining scene objects.
Definition Water.cpp:500
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
bool enabled
Caller-owned color and alpha keys used to bake a water depth-ramp texture.
Definition Water.h:41
std::vector< WaterGradientAlphaStop > alphaStops
Definition Water.h:43
std::vector< WaterGradientColorStop > colorStops
Definition Water.h:42
Result< void > addAlphaStop(float time, float alpha)
Add a finite normalized alpha stop, preserving no external reference.
Definition Water.cpp:134
void clear()
Remove all owned color and alpha stops.
Definition Water.cpp:145
Result< void > addColorStop(float time, float red, float green, float blue)
Add a finite normalized RGB stop, preserving no external reference.
Definition Water.cpp:122
Authored dimensions and density for Pcg-compatible procedural water geometry.
Definition Water.h:17
Immutable camera and horizontal water-plane inputs for a reflection capture.
Complete, caller-owned plan for configuring a mirrored capture camera.
Authored planar-reflection policy with no camera or texture ownership.
Result< std::string > toJson() const
Serialize canonical JSON after validation.
static Result< WaterStyleConfig > fromJson(std::string_view json)
Parse JSON and decode version one transactionally.
glm::uvec4 counts
glm::vec4 color