Rise
The Vieneo Province
Loading...
Searching...
No Matches
CloudLightning.h
Go to the documentation of this file.
1#pragma once
2#include "CloudVolume.h"
3#include "LightningChain.h"
4#include <chrono>
5#include <random>
6
7// Cosmetic, client-local events. Neither the camera nor the legacy lightning
8// RNG influences the natural planetary schedule or storm selection.
10{
11 constexpr double FlashesPerSecond=100;
12 constexpr unsigned MaxEvents=128, MaxLights=32;
13 constexpr double Pi=3.14159265358979323846;
15 inline float Weight(float convection)
16 {
17 const float storm=CloudVolume::Saturate((convection-.35f)/.65f);
18 return storm*storm*storm;
19 }
20 struct Flash
21 {
23 Point axis{1,0,0};
24 float width=.65f;
25 float radius=12, energy=0;
27 void Start(uint32_t seed,double elapsed=0)
28 {
29 LightningChain::Path path;path.count=1;
30 path.segments[0].start=path.segments[0].end={position.x,position.y,position.z};
31 path.segments[0].seed=seed;
32 animation.Start(seed,path);
33 Update(elapsed);
34 }
35 void StartChain(const CloudVolume::Parameters& params,uint32_t cloudSeed,uint32_t eventSeed,double elapsed=0);
36 void Update(double elapsed)
37 {
38 animation.Update(elapsed);
40 }
41 float Brightness() const
42 {
44 }
45 };
46 inline Point SourcePosition(const Point& normal,const CloudVolume::Parameters& params,
47 uint32_t cloudSeed,float depthFraction)
48 {
49 using namespace CloudVolume;
50 if(!params.organic || CloudOrganicShape::Weight(params)<=0)
51 {
52 const auto column=Boundaries(Scale(normal,params.radius),params,cloudSeed);
53 return Scale(normal,params.radius+column.top-.8f-depthFraction*.8f);
54 }
55 const auto region=CloudOrganicShape::Regional(Scale(normal,params.radius),params,cloudSeed);
56 const auto density=[&](float altitude) {
57 return CloudOrganicShape::Evaluate(Scale(normal,params.radius+altitude),params,cloudSeed,&region).density;
58 };
59 // Find the first occupied component from above before choosing depth.
60 // Subtracting a fixed 0.8-1.6 km first could jump through a thin crown
61 // into a clear pocket, then search all the way down to the 10 km deck.
62 constexpr float step=.025f;
63 const float envelope=(std::max)(region.top,params.top+.65f);
64 float upper=envelope;
65 for(int i=0;i<900 && upper>params.base+.25f && density(upper)<.01f;++i)upper-=step;
66 if(density(upper)<.01f)return Scale(normal,params.radius+upper);
67 float lower=upper;
68 // Only need the uppermost 1.6 km; never cross a clear gap to get depth.
69 for(int i=0;i<64 && lower-step>params.base+.25f && density(lower-step)>=.01f;++i)lower-=step;
70 const float altitude=CloudVolume::Lerp(upper,lower,CloudVolume::Lerp(.2f,.8f,Saturate(depthFraction)));
71 const auto selected=Scale(normal,params.radius+altitude);
72 return Density(selected,params,cloudSeed)>=.01f ? selected : Scale(normal,params.radius+upper);
73 }
74
75 inline void Flash::StartChain(const CloudVolume::Parameters& params,uint32_t cloudSeed,uint32_t eventSeed,double elapsed)
76 {
77 using namespace CloudVolume;
78 // Shape and sequence draws are private to this event: adding cloud hops
79 // must not perturb the natural planetary arrival/position RNG stream.
80 ProceduralLightning::Random random{eventSeed^0x91e10da5u};
81 const Point up=Scale(position,1/Length(position));
82 Point east=std::abs(up.z)<.9f ? Point{-up.y,up.x,0} : Point{0,-up.z,up.y};
83 east=Scale(east,1/Length(east));
84 const Point north=CloudOrganicShape::Cross(up,east);
85 float heading=random.Next()*float(2*Pi);
86 axis=Add(Scale(east,std::cos(heading)),Scale(north,std::sin(heading)));
87 width=.5f+.3f*random.Next();
88 const int requested=1+int(random.Next()*(LightningTiming::MaxChainedBolts+1));
89 LightningChain::Path path;path.count=1;
90 path.segments[0].start={position.x,position.y,position.z};
91 Point current=position;
92 for(int i=1;i<requested;++i)
93 {
95 const Point direction=Add(Scale(east,std::cos(heading)),Scale(north,std::sin(heading)));
96 const float span=LightningTiming::CloudHopMinKm
98 const Point delta=Add(Scale(direction,span),Scale(up,random.Signed()*LightningTiming::CloudHopMaxRiseKm));
99 bool found=false;
100 for(int retry=0;retry<4 && !found;++retry)
101 {
102 const Point candidate=Add(current,Scale(delta,std::ldexp(1.f,-retry)));
103 bool occupied=true;
104 // Thin organic shoulders can contain gaps between the old
105 // sixteen probes. Resolve a hop at the CPU surface-query's
106 // 10 m spacing, with a small density margin at its edges.
107 const Point hop{candidate.x-current.x,candidate.y-current.y,candidate.z-current.z};
108 const int probes=(std::max)(16,int(std::ceil(Length(hop)/.01f)));
109 for(int sample=1;sample<=probes && occupied;++sample)
110 occupied=Density(Add(current,Scale(hop,float(sample)/probes)),params,cloudSeed)>=.012f;
111 if(!occupied)continue;
112 path.segments[path.count++].start={candidate.x,candidate.y,candidate.z};
113 current=candidate;found=true;
114 }
115 if(!found)break;
116 }
117 for(int i=0;i<path.count;++i)
118 {
119 auto& segment=path.segments[i];
120 segment.end=i+1<path.count ? path.segments[i+1].start : segment.start;
121 segment.seed=i==0 ? eventSeed : eventSeed+0x9e3779b9u*uint32_t(i);
122 segment.begin=float(i)/path.count;segment.finish=float(i+1)/path.count;
123 }
124 animation.Start(eventSeed,path);Update(elapsed);
125 }
126
127 // Artificial, client-local visibility test. It has its own RNG and slots;
128 // enabling it must not change the natural planetary schedule or weather.
130 {
131 public:
132 static constexpr unsigned MaxEvents=4;
133 static constexpr double DurationSeconds=30,IntervalSeconds=.5;
134 static constexpr float RadiusKm=100;
136 static double MonotonicSeconds()
137 {return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();}
139 void StartAt(double now)
140 {
141 Reset();if(!std::isfinite(now))return;
142 startedAt=updatedAt=now;remaining=DurationSeconds;random.seed(0x43424f4cu);
143 }
144 bool Active() const {return remaining>0;}
145 const std::array<Flash,MaxEvents>& Events() const {return flashes;}
146 uint64_t Generated() const {return generated;}
147 // The weather caller supplies a physics-clamped delta. Use a separate
148 // monotonic wall clock for this explicitly timed visibility test.
149 void Update(const CloudVolume::Parameters& params,double /*physicsElapsed*/,uint32_t cloudSeed,const Point& observer,
150 double now=MonotonicSeconds())
151 {UpdateAt(params,now,cloudSeed,observer);}
152 void UpdateAt(const CloudVolume::Parameters& params,double now,uint32_t cloudSeed,const Point& observer)
153 {
154 if(!Active())return;
155 const float length=CloudVolume::Length(observer);
156 if(!std::isfinite(length) || length<=params.radius+params.top+CloudVolume::MaxTopRiseKm
157 || (!params.weather.current && !params.weather.previous)
158 || !std::isfinite(now))
159 {Reset();return;}
160 // Repeated updates cannot double-charge the clock or spawn twice.
161 // Ignore an out-of-order sample without moving the clock backward.
162 if(now<=updatedAt)return;
163 if(now-startedAt>=DurationSeconds){Reset();return;}
164 const double elapsed=now-updatedAt;updatedAt=now;
166 if(elapsed>1)
167 {
168 // Do not replay missed flashes after a stall or suspension.
169 // The absolute 30-second deadline still applies on resuming.
170 flashes={};next=0;
171 }
172 else
173 {
174 for(auto& flash:flashes)flash.Update(elapsed);
175 next-=elapsed;
176 }
177 const Point up=CloudVolume::Scale(observer,1/length);
178 // A stable tangent basis at all latitudes, including both poles.
179 Point east=std::abs(up.z)<.9f ? Point{-up.y,up.x,0} : Point{0,-up.z,up.y};
180 east=CloudVolume::Scale(east,1/CloudVolume::Length(east));
181 const Point north{up.y*east.z-up.z*east.y,up.z*east.x-up.x*east.z,up.x*east.y-up.y*east.x};
182 while(next<=0)
183 {
184 const double angle=2*Pi*Uniform();
185 const double cosine=1-Uniform()*(1-std::cos(RadiusKm/params.radius));
186 const double sine=std::sqrt((std::max)(0.,1-cosine*cosine));
187 const Point normal{
188 float(up.x*cosine+sine*(east.x*std::cos(angle)+north.x*std::sin(angle))),
189 float(up.y*cosine+sine*(east.y*std::cos(angle)+north.y*std::sin(angle))),
190 float(up.z*cosine+sine*(east.z*std::cos(angle)+north.z*std::sin(angle)))};
191 for(auto& flash:flashes)if(!flash.animation.inuse)
192 {
193 flash.position=SourcePosition(normal,params,cloudSeed,float(Uniform()));
194 // Force an event, not a cloud: keep the live density field.
195 if(CloudVolume::Density(flash.position,params,cloudSeed)<.01f)break;
196 flash.radius=7+float(Uniform())*13;
197 flash.energy=1.4f+float(Uniform())*2.2f;
198 flash.StartChain(params,cloudSeed,uint32_t(random()),-next);
199 ++generated;
200 break;
201 }
203 }
204 }
205 private:
206 double Uniform() {return (double(random())+.5)/4294967296.;}
207 std::mt19937 random{0x43424f4cu};
208 std::array<Flash,MaxEvents> flashes{};
210 uint64_t generated=0;
211 };
213 {
215 std::vector<double> cumulative;
216 double total=0;
217 void Build(const CloudWeather::MapPtr& source)
218 {
219 map=source; cumulative.clear(); total=0;
220 if (!map || map->mips.empty()) return;
221 const auto& m=map->mips.front();
222 cumulative.reserve(m.pixels.size());
223 for (unsigned y=0;y<m.height;++y)
224 {
225 // Exact spherical cell area, including the polar rows.
226 const double area=(std::cos(Pi*y/m.height)-std::cos(Pi*(y+1)/m.height))/m.width;
227 for (unsigned x=0;x<m.width;++x)
228 {
229 total+=area*Weight(m.pixels[size_t(y)*m.width+x]/255.f);
230 cumulative.push_back(total);
231 }
232 }
233 }
234 Point Sample(double choose,double longitudeJitter,double latitudeJitter) const
235 {
236 const auto& m=map->mips.front();
237 const size_t index=(std::min)(size_t(std::upper_bound(cumulative.begin(),cumulative.end(),choose*total)-cumulative.begin()),cumulative.size()-1);
238 const unsigned x=unsigned(index%m.width),y=unsigned(index/m.width);
239 const double longitude=-Pi+2*Pi*(x+longitudeJitter)/m.width;
240 const double north=std::cos(Pi*y/m.height),south=std::cos(Pi*(y+1)/m.height);
241 const double z=north+(south-north)*latitudeJitter;
242 const double equator=std::sqrt((std::max)(0.,1-z*z));
243 return {float(-std::sin(longitude)*equator),float(std::cos(longitude)*equator),float(z)};
244 }
245 };
246 class System
247 {
248 public:
249 explicit System(uint32_t seed=0x4c495447u):random(seed) { next=Interval(); }
250 void Reset() { flashes={}; previous={}; current={}; next=Interval(); }
251 void Seed(uint32_t seed) { random.seed(seed); Reset(); }
252 const std::array<Flash,MaxEvents>& Events() const { return flashes; }
253 uint64_t Generated() const { return generated; }
254 void Update(const CloudVolume::Parameters& params,double elapsed,uint32_t cloudSeed)
255 {
256 if (!params.weather.current && !params.weather.previous) { Reset(); return; }
257 if (!std::isfinite(elapsed) || elapsed<=0) return;
258 // Reuse distributions when the published pair advances. No map
259 // scanning or allocation in steady-state frames.
260 if (previous.map!=params.weather.previous)
261 {
262 if (current.map==params.weather.previous) previous=std::move(current);
263 else previous.Build(params.weather.previous);
264 }
265 if (current.map!=params.weather.current) current.Build(params.weather.current);
266 // Suspend/resume must not replay thousands of missed flashes.
267 if (elapsed>1) { flashes={}; next=Interval(); elapsed=1; }
268 for (auto& flash:flashes) flash.Update(elapsed);
269 const double blend=CloudVolume::Saturate(params.weather.blend);
270 const double oldMass=previous.total*(1-blend),newMass=current.total*blend;
271 if (oldMass+newMass<=0) { flashes={}; next=Interval(); return; }
272 next-=elapsed;
273 while (next<=0)
274 {
275 const Distribution& distribution=Uniform()*(oldMass+newMass)<oldMass ? previous : current;
276 const double choice=Uniform(),longitude=Uniform(),latitude=Uniform();
277 const Point normal=distribution.Sample(choice,longitude,latitude);
278 const float convection=CloudWeather::Sample(params.weather,normal.x,normal.y,normal.z);
279 // Bilinear edges and map transitions must not flash in calm
280 // cells simply because an endpoint distribution contains them.
281 const float strength=Weight(convection);
282 if (strength>0)
283 {
284 for (auto& flash:flashes) if (!flash.animation.inuse)
285 {
286 flash.position=SourcePosition(normal,params,cloudSeed,float(Uniform()));
287 flash.radius=7+float(Uniform())*13;
288 flash.energy=(1.4f+float(Uniform())*2.2f)*std::sqrt(strength);
289 // Consume one local RNG draw, as the old repeat timing
290 // did, to preserve the planetary event schedule/positions.
291 flash.StartChain(params,cloudSeed,uint32_t(random()),-next);
292 ++generated;
293 break;
294 }
295 }
296 next+=Interval();
297 }
298 }
299 private:
300 double Uniform() { return (double(random())+.5)/4294967296.; }
301 double Interval() { return -std::log(Uniform())/FlashesPerSecond; }
302 std::mt19937 random;
303 double next=0;
304 uint64_t generated=0;
306 std::array<Flash,MaxEvents> flashes{};
307 };
308}
SCRIPT_CONTROL SCRIPT_STATE const void int
const std::array< Flash, MaxEvents > & Events() const
void UpdateAt(const CloudVolume::Parameters &params, double now, uint32_t cloudSeed, const Point &observer)
static constexpr unsigned MaxEvents
static constexpr double DurationSeconds
std::array< Flash, MaxEvents > flashes
static double MonotonicSeconds()
void Update(const CloudVolume::Parameters &params, double, uint32_t cloudSeed, const Point &observer, double now=MonotonicSeconds())
static constexpr double IntervalSeconds
static constexpr float RadiusKm
System(uint32_t seed=0x4c495447u)
void Update(const CloudVolume::Parameters &params, double elapsed, uint32_t cloudSeed)
std::array< Flash, MaxEvents > flashes
void Seed(uint32_t seed)
uint64_t Generated() const
const std::array< Flash, MaxEvents > & Events() const
char area[3]
Definition globals.cpp:87
constexpr double FlashesPerSecond
constexpr unsigned MaxLights
constexpr double Pi
constexpr unsigned MaxEvents
float Weight(float convection)
Point SourcePosition(const Point &normal, const CloudVolume::Parameters &params, uint32_t cloudSeed, float depthFraction)
Point Cross(Point a, Point b)
Region Regional(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
Sample Evaluate(Point p, const Parameters &params, uint32_t seed=DefaultSeed, const Region *prepared=nullptr)
float Weight(const Parameters &params)
constexpr float MaxTopRiseKm
Definition CloudVolume.h:23
float Lerp(float a, float b, float t)
Definition CloudVolume.h:50
Point Scale(Point p, float s)
Definition CloudVolume.h:93
Point Add(Point a, Point b)
Definition CloudVolume.h:95
Column Boundaries(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float Saturate(float x)
Definition CloudVolume.h:49
float Density(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float Length(Point p)
Definition CloudVolume.h:94
float Sample(const MapPtr &map, float u, float v)
std::shared_ptr< const Map > MapPtr
constexpr float CloudHopMaxRiseKm
constexpr int MaxChainedBolts
constexpr float CloudHopMinKm
constexpr float CloudHopMaxKm
constexpr float CloudHopTurnRadians
void Build(const CloudWeather::MapPtr &source)
std::vector< double > cumulative
Point Sample(double choose, double longitudeJitter, double latitudeJitter) const
LightningChain::Animation animation
void Start(uint32_t seed, double elapsed=0)
void StartChain(const CloudVolume::Parameters &params, uint32_t cloudSeed, uint32_t eventSeed, double elapsed=0)
float Brightness() const
void Update(double elapsed)
CloudWeather::Frame weather
Definition CloudVolume.h:35
void Update(double elapsed)
void Start(uint32_t packetSeed, const Path &geometry)