载入中...
搜索中...
未找到
Weather.cpp
浏览该文件的文档.
1#include "weather/Weather.h"
2#include "weather/Lightning.h"
5
7#include "common/Capability.h"
8
9#include "graphics/Graphics.h"
10#include "graphics/Material.h"
11#include "graphics/Mesh.h"
12#include "graphics/Shader.h"
14
15#include <cmath>
16#include <cstdint>
17#include <cstring>
18#include <stdexcept>
19#include <string>
20#include <vector>
21
22#include <simplesquirrel/simplesquirrel.hpp>
23
24#include "weather/shaders/weather_vert_spv.inc"
25#include "weather/shaders/weather_frag_spv.inc"
26#include "weather/shaders/bolt_vert_spv.inc"
27#include "weather/shaders/bolt_frag_spv.inc"
28
29namespace eve::weather {
30
31namespace {
32
33// ---- tiny deterministic RNG (no dependency on <random>) ----
34struct Lcg {
35 uint32_t s = 0x9e3779b9u;
36 uint32_t next() {
37 s = s * 1664525u + 1013904223u;
38 return s;
39 }
40 float unit() { return float(next() % 10000u) / 9999.f; } // [0,1]
41 float range(float a, float b) { return a + (b - a) * unit(); }
42};
43
44constexpr int kRainCount = 1600;
45constexpr int kSnowCount = 1400;
46constexpr int kBoltCount = 4;
47
48constexpr float kBoxXZ = 26.f; // half extent on X/Z
49constexpr float kBoxY = 20.f; // fall band height
50
51// Push-constant slots are fixed and must match the shaders and
52// declareWeatherParams(): 0=time 1=windX 2=windZ 3=speed 4=length 5=width
53// 6=intensity 7..9=fog rgb 10=fogDensity 11=flash.
54
55// ---------------------------------------------------------------------------
56// Texture generation
57// ---------------------------------------------------------------------------
58
59// Vertical rain streak: bright core, alpha falloff toward the edges/ends.
60void genRainTexture(std::vector<uint8_t> &rgba) {
61 const int w = 8, h = 32;
62 rgba.resize(size_t(w) * h * 4);
63 for (int y = 0; y < h; ++y) {
64 const float v = (float(y) + 0.5f) / float(h); // 0 top -> 1 bottom
65 const float endFade = 1.f - 2.f * std::fabs(v - 0.5f); // 0 at ends, 1 center
66 for (int x = 0; x < w; ++x) {
67 const float u = (float(x) + 0.5f) / float(w);
68 const float edge = 1.f - 2.f * std::fabs(u - 0.5f); // 0 at sides
69 const float alpha = std::pow(edge, 2.f) * std::pow(endFade, 2.5f);
70 const int i = (y * w + x) * 4;
71 rgba[i + 0] = 255;
72 rgba[i + 1] = 250;
73 rgba[i + 2] = 255;
74 rgba[i + 3] = uint8_t(std::min(255.f, alpha * 255.f));
75 }
76 }
77}
78
79// Soft round snowflake.
80void genSnowTexture(std::vector<uint8_t> &rgba) {
81 const int w = 16, h = 16;
82 rgba.resize(size_t(w) * h * 4);
83 const float cx = (float(w) - 1.f) * 0.5f;
84 const float cy = (float(h) - 1.f) * 0.5f;
85 for (int y = 0; y < h; ++y) {
86 for (int x = 0; x < w; ++x) {
87 const float dx = (float(x) - cx) / cx;
88 const float dy = (float(y) - cy) / cy;
89 const float r = std::sqrt(dx * dx + dy * dy);
90 float alpha = 1.f - r;
91 if (alpha < 0.f) alpha = 0.f;
92 alpha = std::pow(alpha, 2.2f);
93 const int i = (y * w + x) * 4;
94 rgba[i + 0] = 255;
95 rgba[i + 1] = 255;
96 rgba[i + 2] = 255;
97 rgba[i + 3] = uint8_t(std::min(255.f, alpha * 255.f));
98 }
99 }
100}
101
102// ---------------------------------------------------------------------------
103// Mesh builders
104// ---------------------------------------------------------------------------
105
106// A field of billboarded quads. Each quad shares an anchor in inPos; inUV
107// encodes the local offset. `count` quads, `len` = quad height, `width` = width.
108graphics::Mesh *buildFieldMesh(graphics::Graphics *gfx, Lcg &rng, int count, float len,
109 float width) {
110 (void)len;
111 (void)width;
112 const int vertCount = count * 4;
113 const int idxCount = count * 6;
114 std::vector<float> pos(vertCount * 3);
115 std::vector<float> nrm(vertCount * 3, 0.f);
116 std::vector<float> uv(vertCount * 2);
117 std::vector<uint32_t> idx(idxCount);
118
119 for (int i = 0; i < count; ++i) {
120 const float ax = rng.range(-kBoxXZ, kBoxXZ);
121 const float ay = rng.range(0.f, kBoxY);
122 const float az = rng.range(-kBoxXZ, kBoxXZ);
123 const int v0 = i * 4;
124 const int b = v0 * 3, t = v0 * 2;
125
126 // bottom-left / top-left / top-right / bottom-right (uv-driven billboard).
127 pos[b + 0] = ax; pos[b + 1] = ay; pos[b + 2] = az;
128 pos[b + 3] = ax; pos[b + 4] = ay; pos[b + 5] = az;
129 pos[b + 6] = ax; pos[b + 7] = ay; pos[b + 8] = az;
130 pos[b + 9] = ax; pos[b + 10] = ay; pos[b + 11] = az;
131
132 // Pack per-particle variation in the otherwise unused normal.
133 const float lengthScale = rng.range(0.55f, 1.45f);
134 const float widthScale = rng.range(0.65f, 1.25f);
135 const float speedScale = rng.range(0.82f, 1.18f);
136 for (int j = 0; j < 4; ++j) {
137 nrm[b + j * 3 + 0] = lengthScale;
138 nrm[b + j * 3 + 1] = widthScale;
139 nrm[b + j * 3 + 2] = speedScale;
140 }
141
142 // uv.x = horizontal offset, uv.y = vertical offset (in [0,1]).
143 uv[t + 0] = -0.5f; uv[t + 1] = 0.f;
144 uv[t + 2] = -0.5f; uv[t + 3] = 1.f;
145 uv[t + 4] = 0.5f; uv[t + 5] = 1.f;
146 uv[t + 6] = 0.5f; uv[t + 7] = 0.f;
147
148 const uint32_t base = uint32_t(v0);
149 idx[i * 6 + 0] = base + 0;
150 idx[i * 6 + 1] = base + 1;
151 idx[i * 6 + 2] = base + 2;
152 idx[i * 6 + 3] = base + 0;
153 idx[i * 6 + 4] = base + 2;
154 idx[i * 6 + 5] = base + 3;
155 }
156
157 return gfx->newMeshFromArrays(pos.data(), nrm.data(), uv.data(), vertCount, idx.data(),
158 idxCount);
159}
160
161
162} // namespace
163
164// ---------------------------------------------------------------------------
165
168 bool built = false;
169 float time = 0.f;
170 float windOffsetX = 0.f;
171 float windOffsetZ = 0.f;
172
173 // state
174 int preset = 0; // index into kPresetNames
175 float intensity = 0.f; // 0..1
176 float intensityCur = 0.f;
177 float windSpeed = 0.f;
178 float windDirDeg = 0.f;
179 bool snowWindOverride = false;
180 float snowWindX = 0.f, snowWindY = -1.15f, snowWindZ = 0.f;
181 bool lightningEnabled = true;
182 float flash = 0.f;
183 float flashTimer = 0.f;
184 float nextStrike = 4.f;
186 bool pcgMode = false, pcgWeatherEnabled = false, pcgRain = false, pcgSnow = false, pcgWindOverride = false;
187 bool interiorWeather = false;
192
193 // mood
194 float skyR = 0.45f, skyG = 0.53f, skyB = 0.62f;
195 float sunIntensity = 1.f;
196 float fogR = 0.55f, fogG = 0.58f, fogB = 0.62f;
197 float fogDensity = 0.004f;
198
199 // renderables
202 std::vector<graphics::Renderable3D *> bolts;
205 std::vector<graphics::Material *> boltMats;
206 int activeBolt = -1;
207 float boltLife = 0.f;
208 bool boltOnceFired = false;
209
210 Lcg rng;
211};
212
213const char *const Weather::kPresetNames[] = {"clear", "drizzle", "rain", "storm", "snow", "fog", "wind", "blizzard"};
214const int Weather::kPresetCount = 8;
215
216Weather::Weather() : impl_(new Impl()) { cap::addListener<IPhotoModeFieldSink>(this); }
217
218Weather::~Weather() { cap::removeListener<IPhotoModeFieldSink>(this); delete impl_; }
219
220// ---------------------------------------------------------------------------
221// Private setup
222// ---------------------------------------------------------------------------
223
224namespace {
225void pushWeatherParams(graphics::Material *mat, float time, float windX, float windZ,
226 float speed, float length, float width, float intensity,
227 float fogR, float fogG, float fogB, float fogDensity, float flash) {
228 mat->setFloat("uTime", time);
229 mat->setFloat("uWindX", windX);
230 mat->setFloat("uWindZ", windZ);
231 mat->setFloat("uSpeed", speed);
232 mat->setFloat("uLength", length);
233 mat->setFloat("uWidth", width);
234 mat->setFloat("uIntensity", intensity);
235 mat->setFloat("uFogR", fogR);
236 mat->setFloat("uFogG", fogG);
237 mat->setFloat("uFogB", fogB);
238 mat->setFloat("uFogDensity", fogDensity);
239 mat->setFloat("uFlash", flash);
240}
241
242// Declare the push-constant slots on a shader in the exact order above.
243void declareWeatherParams(graphics::Shader *shader) {
244 shader->declareFloat("uTime");
245 shader->declareFloat("uWindX");
246 shader->declareFloat("uWindZ");
247 shader->declareFloat("uSpeed");
248 shader->declareFloat("uLength");
249 shader->declareFloat("uWidth");
250 shader->declareFloat("uIntensity");
251 shader->declareFloat("uFogR");
252 shader->declareFloat("uFogG");
253 shader->declareFloat("uFogB");
254 shader->declareFloat("uFogDensity");
255 shader->declareFloat("uFlash");
256 shader->declareFloat("uKind");
257 shader->declareFloat("uWindOffsetX");
258 shader->declareFloat("uWindOffsetZ");
259}
260} // namespace
261
263 if (impl_->built) return;
264 impl_->built = true;
265 impl_->gfx = gfx;
266 if (!gfx) return;
267
268 // ---- textures ----
269 std::vector<uint8_t> rainRgba, snowRgba;
270 genRainTexture(rainRgba);
271 genSnowTexture(snowRgba);
272 graphics::Texture *rainTex = gfx->newTexture(8, 32, rainRgba.data(), true, true);
273 graphics::Texture *snowTex = gfx->newTexture(16, 16, snowRgba.data(), true, true);
274
275 // ---- shaders (precompiled SPIR-V; runtime GLSL compile is not available on Windows) ----
276 std::vector<uint32_t> wv(weather_vert_spv, weather_vert_spv + weather_vert_spv_count);
277 std::vector<uint32_t> wf(weather_frag_spv, weather_frag_spv + weather_frag_spv_count);
278 std::vector<uint32_t> bv(bolt_vert_spv, bolt_vert_spv + bolt_vert_spv_count);
279 std::vector<uint32_t> bf(bolt_frag_spv, bolt_frag_spv + bolt_frag_spv_count);
280 graphics::Shader *weatherVert = nullptr;
281 graphics::Shader *boltShader = nullptr;
282 if (gfx->getBackendName() == "webgpu") {
287 } else {
288 weatherVert = gfx->newMeshShaderFromSpv(wv, wf);
289 boltShader = gfx->newMeshShaderFromSpv(bv, bf);
290 }
291 declareWeatherParams(weatherVert);
292 declareWeatherParams(boltShader);
293
294 // ---- rain ----
295 graphics::Mesh *rainMesh = buildFieldMesh(gfx, impl_->rng, kRainCount, 0.82f, 0.024f);
296 impl_->rain = graphics::Renderable3D::create();
297 impl_->rain->setMesh(rainMesh);
298 impl_->rainMat = gfx->newMaterial();
299 impl_->rainMat->setAlbedoTexture(rainTex);
300 impl_->rainMat->setShadingModel("unlit");
301 impl_->rainMat->setReceiveLight(false);
302 impl_->rainMat->setReceiveShadow(false);
303 impl_->rainMat->setCastShadow(false);
304 impl_->rainMat->setCastOcclusion(false);
305 impl_->rainMat->setTint(0.72f, 0.80f, 0.88f, 1.0f);
306 impl_->rainMat->setShader(weatherVert);
307 impl_->rain->setMaterial(impl_->rainMat);
308 impl_->rain->setVisible(false);
309
310 // ---- snow ----
311 graphics::Mesh *snowMesh = buildFieldMesh(gfx, impl_->rng, kSnowCount, 0.22f, 0.10f);
312 impl_->snow = graphics::Renderable3D::create();
313 impl_->snow->setMesh(snowMesh);
314 impl_->snowMat = gfx->newMaterial();
315 impl_->snowMat->setAlbedoTexture(snowTex);
316 impl_->snowMat->setShadingModel("unlit");
317 impl_->snowMat->setReceiveLight(false);
318 impl_->snowMat->setReceiveShadow(false);
319 impl_->snowMat->setCastShadow(false);
320 impl_->snowMat->setCastOcclusion(false);
321 impl_->snowMat->setTint(1.0f, 1.0f, 1.0f, 1.0f);
322 impl_->snowMat->setShader(weatherVert);
323 impl_->snow->setMaterial(impl_->snowMat);
324 impl_->snow->setVisible(false);
325
326 // ---- lightning bolts ----
327 for (int i = 0; i < kBoltCount; ++i) {
329 settings.width = 0.20f;
330 settings.displacement = 3.2f;
331 settings.seed = static_cast<int>(impl_->rng.next() & 0x7fffffffu);
333 if (!geometry) throw std::runtime_error("Invalid weather lightning geometry");
334 auto &g = geometry.value();
335 graphics::Mesh *m = gfx->newMeshFromArrays(g.positions.data(), g.normals.data(), g.uv.data(),
336 static_cast<int>(g.positions.size() / 3), g.indices.data(),
337 static_cast<int>(g.indices.size()));
338 graphics::Renderable3D *b = graphics::Renderable3D::create();
339 b->setMesh(m);
340 b->setPosition(impl_->rng.range(-4.f, 4.f), kBoxY, impl_->rng.range(-4.f, 4.f));
341 b->setRotation(0.f, 3.14159265f, 0.f);
342 b->setScale(1.f, kBoxY, 1.f);
343 graphics::Material *mm = gfx->newMaterial();
344 mm->setShadingModel("unlit");
345 mm->setReceiveLight(false);
346 mm->setReceiveShadow(false);
347 mm->setCastShadow(false);
348 mm->setTint(1.0f, 1.0f, 1.0f, 1.0f);
349 mm->setShader(boltShader);
350 b->setMaterial(mm);
351 b->setVisible(false);
352 impl_->bolts.push_back(b);
353 impl_->boltMats.push_back(mm);
354 }
355
356 pushWeatherParams(impl_->rainMat, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f);
357 pushWeatherParams(impl_->snowMat, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f);
358}
359
360// ---------------------------------------------------------------------------
361// Public API
362// ---------------------------------------------------------------------------
363
369 "invalid Pcg weather photo-mode assignment",a.field,{},"weather.photoMode"));};
370 if(a.domain!=PhotoModeDomain::Weather)return bad();
371 if(a.field=="m_pcgWeatherEnabled"){auto*v=std::get_if<bool>(&a.value);if(!v)return bad();impl_->pcgWeatherEnabled=*v;}
372 else if(a.field=="m_pcgWeatherRain"){auto*v=std::get_if<bool>(&a.value);if(!v)return bad();impl_->pcgRain=*v;}
373 else if(a.field=="m_pcgWeatherSnow"){auto*v=std::get_if<bool>(&a.value);if(!v)return bad();impl_->pcgSnow=*v;}
374 else if(a.field=="m_pcgWindSettingsOverride"){auto*v=std::get_if<bool>(&a.value);if(!v)return bad();impl_->pcgWindOverride=*v;}
375 else if(a.field=="m_pcgWindDirection"){auto*v=std::get_if<float>(&a.value);if(!v||!std::isfinite(*v))return bad();impl_->windDirDeg=*v;}
376 else if(a.field=="m_pcgWindSpeed"){auto*v=std::get_if<float>(&a.value);if(!v||!std::isfinite(*v)||*v<0)return bad();impl_->windSpeed=*v;}
377 else return bad();
378 impl_->pcgMode=true;return Result<void>::success();
379}
381bool Weather::getPcgRainEnabled()const{return impl_->pcgRain;}
382bool Weather::getPcgSnowEnabled()const{return impl_->pcgSnow;}
384void Weather::setPreset(const std::string &name) {
385 for (int i = 0; i < kPresetCount; ++i) {
386 if (name == kPresetNames[i]) {
387 impl_->preset = i;
388 impl_->pcgMode = false;
389 return;
390 }
391 }
392}
393
394std::string Weather::getPreset() const { return kPresetNames[impl_->preset]; }
395
397 impl_->intensity = v < 0.f ? 0.f : (v > 1.f ? 1.f : v);
398}
399float Weather::getIntensity() const { return impl_->intensity; }
400
401void Weather::setWindSpeed(float v) { impl_->windSpeed = v < 0.f ? 0.f : v; }
402float Weather::getWindSpeed() const { return impl_->windSpeed; }
403
404void Weather::setWindDirection(float deg) { impl_->windDirDeg = deg; }
405float Weather::getWindDirection() const { return impl_->windDirDeg; }
407 if(!std::isfinite(x)||!std::isfinite(y)||!std::isfinite(z))
409 "Snow wind must be finite","weather.snowWind"));
410 impl_->snowWindOverride=true; impl_->snowWindX=x; impl_->snowWindY=y; impl_->snowWindZ=z;
411 return Result<void>::success();
412}
414bool Weather::hasSnowWind()const{return impl_->snowWindOverride;}
415float Weather::getSnowWindX()const{return impl_->snowWindX;}
416float Weather::getSnowWindY()const{return impl_->snowWindY;}
417float Weather::getSnowWindZ()const{return impl_->snowWindZ;}
418
431
433 const PcgInteriorWeatherVolume& volume, float x, float y, float z) {
434 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
436 DiagnosticCode::InvalidArgument, "sample position must be finite", "weather.interiorVolume"));
437 return setInteriorVolumeState(volume, volume.contains(x, y, z));
438}
439
441 impl_->interiorWeather = false;
443}
449
450void Weather::setLightningEnabled(bool on) { impl_->lightningEnabled = on; }
451bool Weather::isLightningEnabled() const { return impl_->lightningEnabled; }
452
454 if (!impl_->built || impl_->bolts.empty()) return;
455 impl_->activeBolt = impl_->rng.next() % int(impl_->bolts.size());
456 impl_->boltLife = 0.0f;
457 impl_->boltOnceFired = false;
458 impl_->flash = 1.0f;
459 impl_->flashTimer = 0.12f;
460 impl_->nextStrike = 3.0f + impl_->rng.unit() * 6.0f;
461}
462
463float Weather::getFlash() const { return impl_->flash; }
464
465void Weather::setSkyColor(float r, float g, float b) {
466 impl_->skyR = r; impl_->skyG = g; impl_->skyB = b;
467}
468float Weather::getSkyColorR() const { return impl_->skyR; }
469float Weather::getSkyColorG() const { return impl_->skyG; }
470float Weather::getSkyColorB() const { return impl_->skyB; }
471
472void Weather::setSunIntensity(float v) { impl_->sunIntensity = std::clamp(v, 0.f, 1.f); }
473float Weather::getSunIntensity() const { return impl_->sunIntensity; }
474
475void Weather::setFogColor(float r, float g, float b) {
476 impl_->fogR = r; impl_->fogG = g; impl_->fogB = b;
477}
478float Weather::getFogColorR() const { return impl_->fogR; }
479float Weather::getFogColorG() const { return impl_->fogG; }
480float Weather::getFogColorB() const { return impl_->fogB; }
481
482void Weather::setFogDensity(float v) { impl_->fogDensity = v < 0.f ? 0.f : v; }
483float Weather::getFogDensity() const { return impl_->fogDensity; }
484
487
489 const float cloudiness = (impl_->preset >= 1 && impl_->preset <= 3) ? impl_->intensityCur : 0.f;
490 return 0.35f + (1.f - cloudiness) * 0.55f;
491}
492
493// ---------------------------------------------------------------------------
494// Update
495// ---------------------------------------------------------------------------
496
498 if (!impl_->built) init(gfx);
499 if (!impl_->gfx) return;
500 impl_->time += dt;
501
502 // Smooth intensity toward target.
503 const bool pcgPrecipitation=impl_->pcgMode&&impl_->pcgWeatherEnabled&&(impl_->pcgRain||impl_->pcgSnow);
504 const float target = pcgPrecipitation?1.f:impl_->intensity;
505 impl_->intensityCur += (target - impl_->intensityCur) * std::min(1.f, dt * 3.f);
506 if (std::fabs(target - impl_->intensityCur) < 0.002f) impl_->intensityCur = target;
507
508 // Wind vector in world space (dirDeg 0 -> +Z, 90 -> -X).
509 const float rad = impl_->windDirDeg * 0.0174532925f;
510 const float windX = -std::sin(rad) * impl_->windSpeed;
511 const float windZ = std::cos(rad) * impl_->windSpeed;
512
513 // Integrate drift rather than multiplying the current wind by elapsed
514 // time: changing a slider must not teleport the whole particle field.
515 impl_->windOffsetX = std::fmod(impl_->windOffsetX + windX * dt, 52.f);
516 impl_->windOffsetZ = std::fmod(impl_->windOffsetZ + windZ * dt, 52.f);
517 for (auto *mat : {impl_->rainMat, impl_->snowMat}) {
518 mat->setFloat("uWindOffsetX", impl_->windOffsetX);
519 mat->setFloat("uWindOffsetZ", impl_->windOffsetZ);
520 }
521 const float time = impl_->time;
522 const float fogR = impl_->fogR, fogG = impl_->fogG, fogB = impl_->fogB;
523 const float fogD = impl_->fogDensity;
524 const float intensity = impl_->intensityCur;
525
526 // Rain visible for drizzle/rain/storm.
527 const bool windOn = impl_->preset == 6;
528 const bool rainOn = impl_->pcgMode ? (impl_->pcgWeatherEnabled && impl_->pcgRain) :
529 ((impl_->preset >= 1 && impl_->preset <= 3) || windOn);
530 const bool suppressRain = impl_->interiorWeather;
531 impl_->rain->setVisible(rainOn && intensity > 0.01f && !suppressRain);
532 if (rainOn) {
533 const float speed = windOn ? 0.15f : 18.f;
534 impl_->rainMat->setFloat("uKind", windOn ? 2.f : 0.f);
535 pushWeatherParams(impl_->rainMat, time, windX, windZ, speed, windOn ? 9.0f : 0.65f, windOn ? 1.1f : 0.045f,
536 windOn ? intensity * std::min(1.f, impl_->windSpeed / 8.f) * 0.22f : intensity, fogR, fogG,
537 fogB, fogD, 0.f);
538 }
539
540 // Snow.
541 const bool snowOn = impl_->pcgMode ? (impl_->pcgWeatherEnabled && impl_->pcgSnow) :
542 (impl_->preset == 4 || impl_->preset == 7);
543 const bool suppressSnow = impl_->interiorWeather &&
545 impl_->snow->setVisible(snowOn && intensity > 0.01f && !suppressSnow);
546 if (snowOn) {
547 impl_->snowMat->setFloat("uKind", 1.f);
548 pushWeatherParams(impl_->snowMat, time, impl_->snowWindOverride?impl_->snowWindX:windX,
549 impl_->snowWindOverride?impl_->snowWindZ:windZ,
550 impl_->snowWindOverride?-impl_->snowWindY:1.15f, 0.22f, 0.22f, intensity, fogR, fogG, fogB, fogD,
551 0.f);
552 }
553
554 // Lightning during storm.
555 const bool storm = !impl_->pcgMode && impl_->preset == 3;
556 if (storm && impl_->lightningEnabled) {
557 impl_->nextStrike -= dt;
558 if (impl_->nextStrike <= 0.f && impl_->activeBolt < 0) strike();
559 }
560
561 // Drive the active bolt's flash decay.
562 if (impl_->activeBolt >= 0) {
563 impl_->boltLife += dt;
564 impl_->flashTimer -= dt;
565 impl_->flash = lightningEnvelope(impl_->boltLife / 0.5f);
566
567 const int bi = impl_->activeBolt;
568 impl_->bolts[bi]->setVisible(impl_->flash > 0.02f);
569 pushWeatherParams(impl_->boltMats[bi], time, windX, windZ, 0.f, 0.f, 0.f, 1.f, fogR, fogG,
570 fogB, fogD, impl_->flash);
571
572 if (impl_->boltLife > 0.50f) {
573 impl_->bolts[bi]->setVisible(false);
574 impl_->activeBolt = -1;
575 impl_->flash = 0.f;
576 }
577 } else {
578 impl_->flash *= std::max(0.f, 1.f - dt * 8.f);
579 }
580
581 // Push ambient/sky mood onto the graphics state each frame.
582 if (gfx && impl_->environmentEnabled) {
583 const float cloudiness = (impl_->preset >= 1 && impl_->preset <= 3) ? impl_->intensityCur : 0.f;
584 const float dark = 1.f - 0.35f * cloudiness;
585 const float skyFlash = impl_->flash * 0.55f;
587 std::min(1.f, impl_->skyR * dark + skyFlash * 0.68f),
588 std::min(1.f, impl_->skyG * dark + skyFlash * 0.78f),
589 std::min(1.f, impl_->skyB * dark + skyFlash), 1.f);
590 const float flashLight = impl_->flash * 1.35f;
591 gfx->setDirectionalLight(-0.4f, 0.75f, 0.5f,
592 impl_->sunIntensity * (1.f - 0.35f * cloudiness) + flashLight * 0.72f,
593 impl_->sunIntensity * (1.f - 0.35f * cloudiness) * 0.95f + flashLight * 0.84f,
594 impl_->sunIntensity * (1.f - 0.35f * cloudiness) * 0.88f + flashLight);
595 }
596}
597
598// ---------------------------------------------------------------------------
599// Script binding
600// ---------------------------------------------------------------------------
601
602void Weather::expose(ssq::Table &table) {
603 auto cls = table.addClass(name, Weather::create, false);
604 expose(cls);
605 exposeLightning(table, cls);
606 auto interior = table.addClass("PcgInteriorWeatherVolume", ssq::Class::Ctor<PcgInteriorWeatherVolume()>());
607 interior.addFunc("configureBox", [vm=table.getHandle()](PcgInteriorWeatherVolume* self,
608 float x,float y,float z,float sx,float sy,float sz,int mode,int insideReverb,int outsideReverb) {
609 return eve::script::projectResult(vm,self->configureBox(x,y,z,sx,sy,sz,mode,insideReverb,outsideReverb));
610 });
611 interior.addFunc("configureSphere", [vm=table.getHandle()](PcgInteriorWeatherVolume* self,
612 float x,float y,float z,float radius,int mode,int insideReverb,int outsideReverb) {
613 return eve::script::projectResult(vm,self->configureSphere(x,y,z,radius,mode,insideReverb,outsideReverb));
614 });
615 interior.addFunc("contains", [](PcgInteriorWeatherVolume* self,float x,float y,float z) {
616 return self && self->contains(x,y,z);
617 });
618 auto settings = table.addClass("ThunderStrikeSettings", ssq::Class::Ctor<ThunderStrikeSettings()>());
619 settings.addVar("intensity", &ThunderStrikeSettings::intensity);
620 settings.addVar("radius", &ThunderStrikeSettings::radius);
621 settings.addVar("volume", &ThunderStrikeSettings::volume);
622 settings.addVar("audioClipCount", &ThunderStrikeSettings::audioClipCount);
623 auto state = table.addClass("ThunderStrikeState", ssq::Class::Ctor<ThunderStrikeState()>());
624 state.addVar("playing", &ThunderStrikeState::playing);
625 state.addVar("intensity", &ThunderStrikeState::intensity);
626 table.addFunc("triggerThunderStrike", [vm=table.getHandle()](ThunderStrikeState* state,
627 const ThunderStrikeSettings* settings, float x, float y, float z, std::uint32_t seed) {
628 auto result=state&&settings?triggerThunderStrike(*state,*settings,x,y,z,seed)
629 :Result<ThunderStrikeReceipt>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument,"state and settings required"));
630 return eve::script::projectResult(vm, std::move(result), [](const ThunderStrikeReceipt &value) {
631 return Value::object({{"x", value.x},
632 {"y", value.y},
633 {"z", value.z},
634 {"intensity", value.intensity},
635 {"radius", value.radius},
636 {"volume", value.volume},
637 {"audioClipIndex", value.audioClipIndex}});
638 });
639 });
640 table.addFunc("advanceThunderStrike", [vm=table.getHandle()](ThunderStrikeState* state,float dt) {
642 :Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument,"state required"));
643 return eve::script::projectResult(vm,std::move(result));
644 });
645}
646
647void Weather::expose(ssq::Class &cls) {
648 cls.addFunc("getName", &Weather::getName);
649 cls.addFunc("init", &Weather::init);
650 cls.addFunc("update", &Weather::update);
651 cls.addFunc("setPreset", &Weather::setPreset);
652 cls.addFunc("getPreset", &Weather::getPreset);
653 cls.addFunc("setIntensity", &Weather::setIntensity);
654 cls.addFunc("getIntensity", &Weather::getIntensity);
655 cls.addFunc("setWindSpeed", &Weather::setWindSpeed);
656 cls.addFunc("getWindSpeed", &Weather::getWindSpeed);
657 cls.addFunc("setWindDirection", &Weather::setWindDirection);
658 cls.addFunc("getWindDirection", &Weather::getWindDirection);
659 cls.addFunc("setSnowWind",[vm=cls.getHandle()](Weather* self,float x,float y,float z){
660 return eve::script::projectResult(vm,self->setSnowWind(x,y,z));
661 });
662 cls.addFunc("clearSnowWind",&Weather::clearSnowWind);
663 cls.addFunc("hasSnowWind",&Weather::hasSnowWind);
664 cls.addFunc("getSnowWindX",&Weather::getSnowWindX);
665 cls.addFunc("getSnowWindY",&Weather::getSnowWindY);
666 cls.addFunc("getSnowWindZ",&Weather::getSnowWindZ);
667 cls.addFunc("applyInteriorVolume", [vm=cls.getHandle()](Weather* self,
668 const PcgInteriorWeatherVolume* volume,float x,float y,float z) {
669 auto result = volume ? self->applyInteriorVolume(*volume,x,y,z) :
670 Result<PcgInteriorWeatherTransition>::failure(Diagnostic::error(
671 DiagnosticCode::InvalidArgument,"interior volume required","weather.interiorVolume"));
672 return eve::script::projectResult(vm,std::move(result),[](PcgInteriorWeatherTransition value) {
673 return static_cast<int>(value);
674 });
675 });
676 cls.addFunc("setInteriorVolumeState", [vm=cls.getHandle()](Weather* self,
677 const PcgInteriorWeatherVolume* volume,bool inside) {
678 auto result = volume ? self->setInteriorVolumeState(*volume,inside) :
680 DiagnosticCode::InvalidArgument,"interior volume required","weather.interiorVolume"));
681 return eve::script::projectResult(vm,std::move(result),[](PcgInteriorWeatherTransition value) {
682 return static_cast<int>(value);
683 });
684 });
685 cls.addFunc("clearInteriorWeather",&Weather::clearInteriorWeather);
686 cls.addFunc("isInsideInteriorWeather",&Weather::isInsideInteriorWeather);
687 cls.addFunc("isInteriorWeatherCollisionRequested",&Weather::isInteriorWeatherCollisionRequested);
688 cls.addFunc("getCurrentWeatherReverbPreset",&Weather::getCurrentWeatherReverbPreset);
689 cls.addFunc("setLightningEnabled", &Weather::setLightningEnabled);
690 cls.addFunc("isLightningEnabled", &Weather::isLightningEnabled);
691 cls.addFunc("strike", &Weather::strike);
692 cls.addFunc("getFlash", &Weather::getFlash);
693 cls.addFunc("setSkyColor", &Weather::setSkyColor);
694 cls.addFunc("getSkyColorR", &Weather::getSkyColorR);
695 cls.addFunc("getSkyColorG", &Weather::getSkyColorG);
696 cls.addFunc("getSkyColorB", &Weather::getSkyColorB);
697 cls.addFunc("setSunIntensity", &Weather::setSunIntensity);
698 cls.addFunc("getSunIntensity", &Weather::getSunIntensity);
699 cls.addFunc("setFogColor", &Weather::setFogColor);
700 cls.addFunc("getFogColorR", &Weather::getFogColorR);
701 cls.addFunc("getFogColorG", &Weather::getFogColorG);
702 cls.addFunc("getFogColorB", &Weather::getFogColorB);
703 cls.addFunc("setFogDensity", &Weather::setFogDensity);
704 cls.addFunc("getFogDensity", &Weather::getFogDensity);
705 cls.addFunc("setEnvironmentEnabled", &Weather::setEnvironmentEnabled);
706 cls.addFunc("isEnvironmentEnabled", &Weather::isEnvironmentEnabled);
707 cls.addFunc("getAmbientBrightness", &Weather::getAmbientBrightness);
708}
709
711
712} // namespace eve::weather
double z
double y
double m[16]
double x
LogicalId target
float w
Definition AnimClip.cpp:738
double volume
const std::string & s
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
float uv
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
tensor::Graph g
Definition GpuGraph.cpp:7
float u
Definition Grass.cpp:233
double r
float v
int h
std::uint32_t width
float length
Range range
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
OceanWakeSettings settings
glm::dvec3 dx
double dt
std::string error
Definition Package.cpp:174
int idx
Object::Ptr value
float t
Shader * shader
std::string geometry
float dy
Definition Shadow.cpp:151
int count
The single Squirrel projection for common Result, Status and Value.
TacticalUnit * unit
uint32_t seed
Definition TreeMesh.cpp:276
std::vector< char > inside
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
virtual std::string getBackendName() const =0
Renderer backend id used by sibling modules (e.g. Gpgpu).
virtual void setDirectionalLight(float dx, float dy, float dz, float r=1.f, float g=1.f, float b=1.f)
Sets the directional light.
Definition Graphics.cpp:273
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....
virtual void setBackgroundColorRGBA(float r, float g, float b, float a=1.f)
Sets the background color rgba.
virtual Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false)=0
Creates a texture. @ownership Caller deletes unless documented otherwise.
Material * newMaterial()
Create a Material asset (shading model + textures + PBR knobs). Caller owns Material*; not tracked by...
Definition Graphics.cpp:277
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...
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
void setAlbedoTexture(Texture *texture)
Set the borrowed material texture. @ownership Graphics factory owns the resource. @lifetime Keep aliv...
Definition Material.h:123
void setCastShadow(bool cast)
Sets the cast shadow.
Definition Material.h:277
void setCastOcclusion(bool cast)
Sets the cast occlusion.
Definition Material.h:287
void setReceiveShadow(bool receive)
Sets the receive shadow.
Definition Material.h:282
void setReceiveLight(bool receive)
Sets the receive light.
Definition Material.h:272
void setShadingModel(const std::string &model)
"pbr" | "unlit" | "hair" | "custom" (unknown → pbr).
Definition Material.cpp:106
void setTint(float r, float g, float b, float a=1.f)
Sets the tint.
Definition Material.cpp:124
void setFloat(const std::string &name, float value)
Sets the float.
Definition Material.cpp:207
void setShader(Shader *shader)
Set an optional Mesh3D / hair shader; nullptr selects the built-in shading path.
Definition Material.h:227
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
EVENGINE_API_BACKENDS public API.
void setMaterial(Material *material)
Attach a Material that packages shading method + surface params.
void setVisible(bool visible)
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
Caller-owned, immutable-after-configuration Pcg interior-weather volume. @ownership This value owns a...
bool contains(float x, float y, float z) const noexcept
Return whether a finite world-space position lies inside, including the boundary.
Weather module — real-time precipitation / lightning / wind system.
Definition Weather.h:36
static const char *const kPresetNames[]
Definition Weather.h:55
void setSunIntensity(float v)
Sets the sun intensity.
Definition Weather.cpp:472
float getFogColorB() const
Returns the fog color b.
Definition Weather.cpp:480
void clearInteriorWeather()
Clear interior state and restore the last sampled exterior reverb preset.
Definition Weather.cpp:440
static const int kPresetCount
Definition Weather.h:56
float getFogDensity() const
Returns the fog density.
Definition Weather.cpp:483
void setWindSpeed(float v)
Sets the wind speed.
Definition Weather.cpp:401
float getSnowWindY() const
Returns the snow wind y.
Definition Weather.cpp:416
void init(graphics::Graphics *gfx)
Idempotent; builds meshes/shaders on first call.
Definition Weather.cpp:262
Result< void > setSnowWind(float x, float y, float z)
Override snow world velocity exactly as Pcg SnowWindDir.
Definition Weather.cpp:406
void setLightningEnabled(bool on)
Sets the lightning enabled.
Definition Weather.cpp:450
void setIntensity(float v)
Sets the intensity.
Definition Weather.cpp:396
bool getPcgWindOverride() const
Return whether photo mode overrides the captured wind.
Definition Weather.cpp:383
float getFogColorG() const
Returns the fog color g.
Definition Weather.cpp:479
void strike()
Force a bolt strike this frame (useful for manual testing).
Definition Weather.cpp:453
void setSkyColor(float r, float g, float b)
Sets the sky color.
Definition Weather.cpp:465
float getWindDirection() const
Returns the wind direction.
Definition Weather.cpp:405
void clearSnowWind()
Return to horizontal wind plus the native default fall speed.
Definition Weather.cpp:413
bool getPcgSnowEnabled() const
Return Pcg's independent snow playback state.
Definition Weather.cpp:382
Result< PcgInteriorWeatherTransition > setInteriorVolumeState(const PcgInteriorWeatherVolume &volume, bool inside)
Apply a trigger-driven enter/exit event without retaining the volume.
Definition Weather.cpp:419
void setFogDensity(float v)
Sets the fog density.
Definition Weather.cpp:482
std::string getPreset() const
Returns the preset.
Definition Weather.cpp:394
void setEnvironmentEnabled(bool enabled)
Enable legacy weather-owned sky and directional lighting.
Definition Weather.cpp:485
float getFogColorR() const
Returns the fog color r.
Definition Weather.cpp:478
int getCurrentWeatherReverbPreset() const
Returns the current weather reverb preset.
Definition Weather.cpp:448
float getSunIntensity() const
Returns the sun intensity.
Definition Weather.cpp:473
float getSkyColorG() const
Returns the sky color g.
Definition Weather.cpp:469
float getSkyColorB() const
Returns the sky color b.
Definition Weather.cpp:470
float getSnowWindZ() const
Returns the snow wind z.
Definition Weather.cpp:417
Result< PcgInteriorWeatherTransition > applyInteriorVolume(const PcgInteriorWeatherVolume &volume, float x, float y, float z)
Sample a bounds-driven interior volume and atomically apply an enter/exit transition.
Definition Weather.cpp:432
bool isInteriorWeatherCollisionRequested() const
True when interior weather collision requested.
Definition Weather.cpp:445
float getSnowWindX() const
Returns the snow wind x.
Definition Weather.cpp:415
void setPreset(const std::string &name)
Sets the preset.
Definition Weather.cpp:384
bool isLightningEnabled() const
True when lightning enabled.
Definition Weather.cpp:451
float getWindSpeed() const
Returns the wind speed.
Definition Weather.cpp:402
float getFlash() const
How bright the current flash is (0..1), sampled by the scene for a key light.
Definition Weather.cpp:463
float getAmbientBrightness() const
Ambient multiplier that the example should feed into camera.setAmbient().
Definition Weather.cpp:488
PhotoModeFieldAcceptance acceptsPhotoModeField(const PhotoModeAssignment &assignment) const noexcept override
Return whether this module owns a Pcg weather photo-mode field.
Definition Weather.cpp:364
void update(float dt, graphics::Graphics *gfx)
Advance sim + push per-frame uniforms; must run before gfx.render3D().
Definition Weather.cpp:497
void setFogColor(float r, float g, float b)
Sets the fog color.
Definition Weather.cpp:475
bool hasSnowWind() const
Return whether a Pcg snow velocity override is active.
Definition Weather.cpp:414
float getIntensity() const
Returns the intensity.
Definition Weather.cpp:399
void setWindDirection(float degrees)
Wind direction in degrees; 0 = toward +Z, 90 = toward -X.
Definition Weather.cpp:404
bool isInsideInteriorWeather() const
True when inside interior weather.
Definition Weather.cpp:444
float getSkyColorR() const
Returns the sky color r.
Definition Weather.cpp:468
bool isEnvironmentEnabled() const
True when environment enabled.
Definition Weather.cpp:486
bool getPcgRainEnabled() const
Return Pcg's independent rain playback state.
Definition Weather.cpp:381
bool getPcgWeatherEnabled() const
Return Pcg's master weather-enabled state.
Definition Weather.cpp:380
~Weather() override
Weather.
Definition Weather.cpp:218
Result< void > applyPhotoModeField(const PhotoModeAssignment &assignment) override
Atomically apply one Pcg weather field to this authoritative weather state.
Definition Weather.cpp:367
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
constexpr const char * kWeatherFragWgsl
Definition WeatherWgsl.h:54
constexpr const char * kWeatherVertWgsl
Definition WeatherWgsl.h:5
constexpr const char * kBoltFragWgsl
Definition WeatherWgsl.h:86
constexpr const char * kBoltVertWgsl
Definition WeatherWgsl.h:82
EVENGINE_API_ORCHESTRATION float lightningEnvelope(float age)
Weather return-stroke envelope, normalized age [0,1]; side-effect free.
PcgInteriorWeatherMode
Interior precipitation policy mirrored from Pcg.
void exposeLightning(ssq::Table &table, ssq::Class &weather)
Register preparation/settings and owned Lightning methods on Weather.
EVENGINE_API_ORCHESTRATION Result< LightningGeometry > buildLightningGeometry(const LightningSettings &settings, unsigned variant)
Deterministic CPU preparation, explicit variant stream; identical inputs give identical geometry on o...
Result< void > advanceThunderStrike(ThunderStrikeState &state, float dt)
Apply Pcg's clamped Lerp(intensity,0,dt*2) decay and 0.15 stop threshold.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
PhotoModeFieldAcceptance
Capability implemented by the composition root that routes assignments to domain owners.
bool enabled
One reversible field assignment in a photo-mode transaction.
Copied preparation settings. Width and displacement are world units, independent of endpoint distance...
Definition Lightning.h:16
graphics::Renderable3D * rain
Definition Weather.cpp:200
graphics::Renderable3D * snow
Definition Weather.cpp:201
graphics::Material * rainMat
Definition Weather.cpp:203
PcgInteriorWeatherMode interiorMode
Definition Weather.cpp:188
graphics::Graphics * gfx
Definition Weather.cpp:167
std::vector< graphics::Renderable3D * > bolts
Definition Weather.cpp:202
std::vector< graphics::Material * > boltMats
Definition Weather.cpp:205
graphics::Material * snowMat
Definition Weather.cpp:204