Rise
The Vieneo Province
Loading...
Searching...
No Matches
WindshieldRain.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <array>
5#include <cmath>
6#include <cstdint>
7#include <vector>
8#if defined(_M_IX86) || defined(_M_X64)
9#include <emmintrin.h>
10#endif
11
12// Water stays in glass coordinates, independent of the camera. Units are metres
13// and seconds; the fixed step makes spawning and streaks independent of FPS.
15{
16inline constexpr float WiperCyclesPerSecond = .6f;
17inline float AdvanceWiper(float phase, float elapsed, bool powered, bool raining, bool* moving = nullptr)
18{
19 if (moving) *moving = false;
20 if (!powered || elapsed <= 0 || (!raining && phase == 0)) return phase;
21 phase += (std::min)(elapsed, .25f) * WiperCyclesPerSecond;
22 if (phase >= 1.f) phase = raining ? phase - std::floor(phase) : 0.f;
23 if (moving) *moving = raining || phase != 0.f;
24 return phase;
25}
26// Fade through the high cloud layer using altitude above mean sea level (km).
27// Smooth endpoints prevent a visible switch as the vehicle crosses 10 or 5 km.
28inline float AltitudeRainFactor(float altitudeKm)
29{
30 const float t = (std::clamp)((10.f-altitudeKm)/5.f, 0.f, 1.f);
31 return t*t*(3.f-2.f*t);
32}
33// The local cloud field modulates impacts, not existing beads. Blend to normal
34// falling rain through the lowest 500 m so rain continues below the cloud base.
35inline float CloudRainFactor(float density, float belowBaseKm, bool volumeEnabled)
36{
37 if (!volumeEnabled) return 1.f;
38 float inLayer = (std::clamp)(-belowBaseKm/.5f, 0.f, 1.f);
39 inLayer = inLayer*inLayer*(3.f-2.f*inLayer);
40 return 1.f + ((std::clamp)(density, 0.f, 1.f)-1.f)*inLayer;
41}
42// Use the whole weather range: drizzle starts at 3, downpour peaks at 16.
43inline float PrecipitationIntensity(float precipitation, float altitudeKm = 0.f)
44{
45 return (std::clamp)((precipitation - 3.f) / 13.f, 0.f, 1.f) * AltitudeRainFactor(altitudeKm);
46}
47inline float LiquidRainIntensity(float precipitation, float snowBlend, bool exposed, float altitudeKm = 0.f)
48{
49 return exposed ? PrecipitationIntensity(precipitation, altitudeKm)
50 * (1.f - (std::clamp)(snowBlend, 0.f, 1.f)) : 0.f;
51}
52// Stable particle indices fade through a band before entering/leaving the draw
53// count. Count alone would pop groups of streaks across cloud/altitude changes.
54inline float ExteriorDropBudget(float intensity, int maximum)
55{
56 return (std::clamp)(intensity, 0.f, 1.f) * (maximum + 128.f);
57}
58inline int ExteriorDropCount(float intensity, int maximum)
59{
60 return (std::min)(maximum, (int(std::ceil(ExteriorDropBudget(intensity, maximum))) + 1) & ~1);
61}
62inline float ExteriorDropOpacity(int index, float intensity, int maximum)
63{
64 return (std::clamp)((ExteriorDropBudget(intensity, maximum) - index) / 128.f, 0.f, 1.f);
65}
66struct Point { float x = 0, y = 0; };
67// Regulated rain air enters at the aircraft-bottom edge, not a texture edge.
68// The unit tangent and projected bounds are supplied by the authored glass.
69struct AirJet
70{
72 float speed = 0, bottom = 0, top = 1;
73 float HeightFraction(Point p) const
74 {
75 return (std::clamp)((p.x*direction.x+p.y*direction.y-bottom)
76 / (std::max)(top-bottom,.001f),0.f,1.f);
77 }
78 float SpeedAtHeight(float t) const
79 {
80 // Smooth expansion/entrainment: 30% speed (9% load) at the top.
81 return speed*(1.f-.7f*t*t*(3.f-2.f*t));
82 }
83};
84struct Drop { Point position, velocity; float radius; float runoffDistance = 0; Point wake; };
86{
87public:
88 static constexpr int Resolution = 256;
89 static constexpr size_t MaxDrops = 8192; // Hard per-patch ceiling, independent of mesh vertices.
90 static constexpr float TrailHalfLifeSeconds = 12.f;
91 using Field = std::vector<float>; // Heap storage keeps larger fields off the Win32 stack.
92 Surface(float width = 1, float height = 1, uint32_t seed = 9)
93 : width((std::max)(width, .05f)), height((std::max)(height, .05f)), random(seed) {}
94
95 void Clear()
96 {
97 ++revision;
98 drops.clear(); std::fill(trail.begin(),trail.end(),0.f); std::fill(water.begin(),water.end(),0.f);
99 waterDrops.clear();
102 }
103 void Impact(Point position, float radius, bool coalesce = true)
104 {
105 if (radius <= 0) return;
106 ++revision;
107 const Drop incoming{position, {}, radius, 0, position};
108 // Rain hitting an existing bead adds water even at the particle limit.
109 if (coalesce)
110 for (auto& drop : drops)
111 if (Touching(drop, incoming)) { Merge(drop, incoming); return; }
112 if (drops.size() < DropLimit()) drops.push_back(incoming);
113 }
114 // An impact breaks into separated satellites, not one perfectly beading
115 // sphere. Split the incoming volume; reserve capacity for moving parents.
116 void Splash(Point position, float radius, Point velocity = {}, bool coalesce = true)
117 {
118 float volume=radius*radius*radius;
119 if (radius>.0012f && drops.size()+4<DropLimit() && splashPopulation+3<DropLimit()/5)
120 {
121 const float angle=Random()*6.2831853f;
122 for (int i=0;i<3;++i)
123 {
124 const float r=.0005f+Random()*.00018f;
125 const float direction=angle+i*2.0943951f;
126 const float reach=radius+ .004f+Random()*.008f;
127 const Point p{position.x+std::cos(direction)*reach,position.y+std::sin(direction)*reach};
128 if (p.x<0 || p.y<0 || p.x>width || p.y>height) continue;
129 Impact(p,r,false);
131 volume-=r*r*r;
132 }
133 }
134 const size_t count=drops.size();
135 Impact(position,std::cbrt((std::max)(volume,0.f)),coalesce);
136 if (drops.size()>count) drops.back().velocity=velocity;
137 }
138 // wind is tangent flow in m/s; full airspeed includes normal impacts.
139 // airDensity is relative to one atmosphere, not the game's surface scalar.
140 void Update(float elapsed, float rain, Point acceleration, Point wind, float airDensity, float airSpeed = -1.f,
141 AirJet airJet = {})
142 {
143 if (!std::isfinite(elapsed) || elapsed <= 0) return;
144 accumulator += (std::min)(elapsed, .25f); // no burst after a stalled frame
145 constexpr float tick = 1.f / 30;
146 const int ticks = int((accumulator + .000001f) / tick);
147 lastStepCount = (std::min)(ticks, 2);
148 if (!lastStepCount) return;
149 // Catch up the same bounded elapsed time in at most two stable steps.
150 // Replaying eight full collision/field rebuilds makes a slow frame
151 // cause another slow frame, including after precipitation is disabled.
152 const float step = ticks * tick / lastStepCount;
153 accumulator = (std::max)(0.f, accumulator - ticks * tick);
154 const float density = (std::max)(airDensity, 0.f);
155 const float speed = (std::max)(airSpeed, std::hypot(wind.x,wind.y));
156 // Blend by dynamic pressure (equivalent airspeed), not groundspeed.
157 // At 200 knots in dense air, impacts break up and are rapidly shed.
158 // A regulated nozzle has its own pressure. Do not multiply its load by
159 // ambient density or replace the real relative wind when protection is on.
160 const float equivalentSpeed=speed*std::sqrt(density);
161 const auto sheddingAt = [&](float jetSpeed) {
162 const float t=(std::clamp)(((std::max)(equivalentSpeed,jetSpeed)-25.f)/55.f,0.f,1.f);
163 return t*t*(3.f-2.f*t);
164 };
165 const float ambientShedding=sheddingAt(0);
166 const bool coalesce=ambientShedding<1.f;
167 const auto decayAt = [&](float shedding) {
168 return std::exp2(-step*((1.f-shedding)/TrailHalfLifeSeconds+shedding/.045f));
169 };
170 const float trailDecay=decayAt(ambientShedding);
171 // A small 1-D table avoids per-texel exponentials. Residue near the
172 // nozzle dries faster without stripping the whole pane's upper trails.
173 std::array<float,64> jetDecay{};
174 const bool localDrying=airJet.speed>0 && ambientShedding<1.f;
175 if (localDrying)
176 for (size_t i=0;i<jetDecay.size();++i)
177 jetDecay[i]=decayAt(sheddingAt(airJet.SpeedAtHeight(float(i)/(jetDecay.size()-1))));
178 struct Flow { Point jetDrive; float shedding; };
179 const auto flowAt = [&](Point p) -> Flow {
180 if (airJet.speed<=0) return {{},ambientShedding};
181 const float localSpeed=airJet.SpeedAtHeight(airJet.HeightFraction(p));
182 const float load=.00012f*(std::min)(localSpeed*localSpeed,10000.f);
183 return {{airJet.direction.x*load,airJet.direction.y*load},sheddingAt(localSpeed)};
184 };
185 // Vector magnitudes keep the force independent of the pane's UV axes.
186 const float accelerationScale = .06f * (std::min)(1.f,
187 40.f / (std::max)(std::hypot(acceleration.x, acceleration.y), .000001f));
188 // Surface drag must overcome gravity at road speeds in dense air.
189 // Keep the existing high-speed terminal flow rather than increasing it
190 // tenfold as well. Density still multiplies force exactly once.
191 const float moving=(std::clamp)((speed-5.f)/10.f,0.f,1.f);
192 const float roadScale=.0012f*moving*moving*(3.f-2.f*moving)
193 * (std::min)(speed,625.f/(std::max)(speed,.000001f));
194 const float fastScale=.00012f*(std::min)(speed,
195 10000.f / (std::max)(speed, .000001f));
196 // Hold the extra low-speed load until the ordinary quadratic term
197 // overtakes it: accelerating must never reduce aerodynamic force.
198 const float windScale=density*(std::max)(roadScale,fastScale);
199 std::vector<Drop> deposited;
200 for (int iteration=0; iteration<lastStepCount; ++iteration)
201 {
202 // Discard invisible residue instead of accumulating denormal floats.
203 if (localDrying)
204 for (int y=0;y<Resolution;++y) for (int x=0;x<Resolution;++x)
205 {
206 auto& value=trail[y*Resolution+x];
207 if (value<=.001f) {value=0;continue;}
208 const Point p{(x+.5f)*width/Resolution,(y+.5f)*height/Resolution};
209 const float t=airJet.HeightFraction(p)*(jetDecay.size()-1);
210 const int a=int(t),b=(std::min)(a+1,int(jetDecay.size()-1));
211 value*=jetDecay[a]+(jetDecay[b]-jetDecay[a])*(t-a);
212 }
213 else
214 for (auto& value : trail) value = value > .001f ? value * trailDecay : 0.f;
215 splashPopulation=std::count_if(drops.begin(),drops.end(),[](const Drop& d) { return d.radius<=.0007f; });
216 rain = (std::clamp)(rain, 0.f, 1.f);
217 spawnCredit += rain * (std::min)(width * height, 4.f) * 1040.f * step;
218 CappedImpactIndex cappedImpacts;
219 while (spawnCredit >= 1)
220 {
221 const Point position{Random() * width, Random() * height};
222 const auto flow=flowAt(position);
223 const float shedding=flow.shedding;
224 const float size=Random();
225 // Numerous millimetre-scale beads, with fewer large impacts.
226 const float parkedRadius=.0007f + size*size*.0018f;
227 const float flyingRadius=.00045f + size*.00081f;
228 // Batch new impacts into the sorted coalescence pass instead of
229 // scanning every live bead per birth. At the cap, still let an
230 // impact add water to an existing bead without allocating more.
231 const float radius=parkedRadius+(flyingRadius-parkedRadius)*shedding;
232 const Point velocity{(wind.x*windScale+flow.jetDrive.x)*.72f*shedding,
233 (wind.y*windScale+flow.jetDrive.y)*.72f*shedding};
234 if (shedding<.5f)
235 {
236 if (coalesce && drops.size()>=DropLimit())
237 CappedImpact(position,std::cbrt(radius*radius*radius),cappedImpacts);
238 else
239 Splash(position,radius,velocity,false);
240 }
241 else
242 {
243 const size_t count=drops.size();
244 Impact(position,radius,false);
245 if (drops.size()>count) drops.back().velocity=velocity;
246 }
247 --spawnCredit;
248 }
249 if (coalesce) Coalesce();
250 deposited.clear();
251 for (auto& drop : drops)
252 {
253 const Point previous = drop.position;
254 const auto flow=flowAt(previous);
255 const float shedding=flow.shedding;
256 const float trailAmount=.6f*(1.f-shedding)*(1.f-shedding)+.28f*shedding;
257 if (shedding > 0.f)
258 drop.radius = (std::min)(drop.radius, .0013f / (shedding * shedding));
259 // Surface tension pins small beads. Larger beads run and lose
260 // water into a fading trail. Only wind drag scales with density.
261 // Apply density after the airspeed cap so thin air stays weaker.
262 const float mobility = (std::clamp)((drop.radius * drop.radius - .0009f * .0009f)
263 / (.0025f * .0025f - .0009f * .0009f), 0.f, 8.f);
264 // Strong flow carries even tiny fragments that surface tension
265 // would pin at rest. Keep gravity separate from aerodynamic load.
266 const float windMobility = mobility + (12.f-mobility) * shedding;
267 // Imperfections perturb a run; they must not steer heavy beads
268 // like swimmers. Once water overcomes pinning, its weight makes
269 // the downhill direction increasingly dominant.
270 const float deflection=(1.f-shedding)/(1.f+mobility);
271 float bend=0,adhesion=1;
272 if (mobility>0 && shedding<1.f)
273 {
274 bend=.08f*Roughness({drop.position.x+.137f,drop.position.y+.071f})*deflection;
275 adhesion+=.15f*Roughness(drop.position)*deflection;
276 }
277 const float gx=acceleration.x-acceleration.y*bend;
278 const float gy=acceleration.y+acceleration.x*bend;
279 float driveX=mobility*accelerationScale*gx*adhesion+windMobility*(wind.x*windScale+flow.jetDrive.x);
280 float driveY=mobility*accelerationScale*gy*adhesion+windMobility*(wind.y*windScale+flow.jetDrive.y);
281 // Larger beads roll faster; old wet paths reduce resistance
282 // further. Keep pinned satellites and fast aerodynamic
283 // fragments in their existing regimes.
284 float drag=5.f+(2.2f-5.f)*(1.f-shedding);
285 const float drive=mobility>0.f && shedding<1.f ? std::hypot(driveX,driveY) : 0.f;
286 if (drive>.000001f)
287 {
288 const float tx=driveX/drive,ty=driveY/drive;
289 const float cell=(std::max)(width,height)/Resolution;
290 const float reach=(std::max)(drop.radius*2.f,cell);
291 const Point ahead{drop.position.x+tx*reach,drop.position.y+ty*reach};
292 const float middle=TrailAt(ahead);
293 const float left=TrailAt({ahead.x-ty*reach,ahead.y+tx*reach});
294 const float right=TrailAt({ahead.x+ty*reach,ahead.y-tx*reach});
295 // Undo sub-texel coverage only for the physical query.
296 // Rendering retains the narrow, area-filtered residue.
297 const float r2=drop.radius*drop.radius*.36f;
298 const float reference=.18f*r2/(r2+.5625f*cell*cell);
299 const float wet=(std::clamp)((std::max)(middle,.5f*(std::max)(left,right))/reference,0.f,1.f);
300 const float turn=(std::clamp)((left-right)/reference,-.12f,.12f)*deflection;
301 driveX-=ty*drive*turn;
302 driveY+=tx*drive*turn;
303 drag-=(2.2f-.8f)*wet*(1.f-shedding);
304 }
305 drop.velocity.x += (driveX - drag * drop.velocity.x) * step;
306 drop.velocity.y += (driveY - drag * drop.velocity.y) * step;
307 drop.position.x += drop.velocity.x * step;
308 drop.position.y += drop.velocity.y * step;
309 const float dx = drop.position.x - previous.x, dy = drop.position.y - previous.y;
310 const float distance = std::sqrt(dx * dx + dy * dy);
311 // A short, metric-width wake follows the recent path. Its
312 // analytic shape is independent of the coarse residue texels.
313 const float follow = (std::min)(1.f, step / .18f);
314 drop.wake.x += (previous.x-drop.wake.x)*follow;
315 drop.wake.y += (previous.y-drop.wake.y)*follow;
316 const float wx=drop.wake.x-drop.position.x, wy=drop.wake.y-drop.position.y;
317 const float length=std::hypot(wx,wy);
318 const float maximum=(std::min)(.06f,drop.radius*48.f);
319 if (length>maximum) drop.wake={drop.position.x+wx*maximum/length,
320 drop.position.y+wy*maximum/length};
321 const int samples = (std::min)(32, 1 + int(distance / .002f));
322 if (distance > .00001f && trailAmount > 0.f)
323 StampTrail(previous, {dx,dy}, drop.radius * .6f, trailAmount, samples);
324 // Intermittent pinning leaves small daughter beads in the wake.
325 // Debit their volume from the parent, keep them behind its rim,
326 // and append after iteration so references stay valid. The same
327 // area budget bounds rain and runoff, even in a downpour.
328 drop.runoffDistance += distance;
329 if (shedding < .5f && drop.radius > .0012f && drop.runoffDistance >= .035f
330 && distance > .00001f && drops.size()+deposited.size() < DropLimit())
331 {
332 const float radius = (std::max)(.00035f,
333 (std::min)(drop.radius*.25f, .00065f) * (.8f+.2f*Random()));
334 const float behind = 2.f*(drop.radius+radius);
335 const Point position{drop.position.x-dx/distance*behind, drop.position.y-dy/distance*behind};
336 if (position.x>=0 && position.y>=0 && position.x<=width && position.y<=height)
337 {
338 deposited.push_back({position,{},radius,0,position});
339 drop.radius = std::cbrt((std::max)(0.f, Volume(drop)-radius*radius*radius));
340 }
341 drop.runoffDistance = Random()*.012f;
342 }
343 // Lose water to film and evaporation; aerodynamic breakup must
344 // leave enough transit time to read movement before disappearing.
345 drop.radius -= step * (.00001f + .00089f * shedding) + distance * .001f * (1.f-shedding);
346 }
347 drops.insert(drops.end(),deposited.begin(),deposited.end());
348 drops.erase(std::remove_if(drops.begin(), drops.end(), [&](const Drop& d) {
349 const float minimumRadius=.0003f-.00015f*flowAt(d.position).shedding;
350 return d.radius < minimumRadius || d.position.x < 0 || d.position.y < 0
351 || d.position.x > width || d.position.y > height;
352 }), drops.end());
353 if (coalesce) Coalesce();
354 // Only the final field is consumed by rendering.
355 }
356 Rebuild();
357 }
358 // Swept blade triangles clear both beads and their old trails, leaving the
359 // rest of the glass untouched. New impacts can wet the cleared area again.
361 {
362 const auto cross = [](Point p, Point q, Point r) {
363 return (q.x-p.x)*(r.y-p.y) - (q.y-p.y)*(r.x-p.x);
364 };
365 if (std::abs(cross(a,b,c)) < 1.e-9f) return;
367 ++revision;
368 const auto inside = [&](Point p) {
369 const float x = cross(a,b,p), y = cross(b,c,p), z = cross(c,a,p);
370 return (x >= 0 && y >= 0 && z >= 0) || (x <= 0 && y <= 0 && z <= 0);
371 };
372 drops.erase(std::remove_if(drops.begin(), drops.end(), [&](const Drop& d) {
373 return inside(d.position);
374 }), drops.end());
375 // A blade crossing the wake clears it even if the parent is outside
376 // the swept triangle. Droplets themselves retain their original test.
377 const auto crossing=[&](Point p,Point q,Point r,Point s) {
378 return (std::max)(p.x,q.x)>=(std::min)(r.x,s.x)
379 && (std::max)(r.x,s.x)>=(std::min)(p.x,q.x)
380 && (std::max)(p.y,q.y)>=(std::min)(r.y,s.y)
381 && (std::max)(r.y,s.y)>=(std::min)(p.y,q.y)
382 && cross(p,q,r)*cross(p,q,s)<=0 && cross(r,s,p)*cross(r,s,q)<=0;
383 };
384 for (auto& d:drops)
385 if (inside(d.wake) || crossing(d.position,d.wake,a,b)
386 || crossing(d.position,d.wake,b,c) || crossing(d.position,d.wake,c,a))
387 d.wake=d.position;
388 const int x0 = Pixel((std::min)({a.x,b.x,c.x}), width);
389 const int x1 = Pixel((std::max)({a.x,b.x,c.x}), width);
390 const int y0 = Pixel((std::min)({a.y,b.y,c.y}), height);
391 const int y1 = Pixel((std::max)({a.y,b.y,c.y}), height);
392 for (int y = y0; y <= y1; ++y) for (int x = x0; x <= x1; ++x)
393 if (inside({(x+.5f)*width/Resolution, (y+.5f)*height/Resolution}))
394 trail[y*Resolution+x] = water[y*Resolution+x] = 0;
395 }
396 struct BladeSweep { Point previous[3], current[3]; };
397 // Batch the authored blade mesh: testing every bead against every triangle
398 // was much more expensive than the rain simulation itself. The coarse bins
399 // only select candidates; contact still uses the exact swept triangles.
400 void SweepBlades(const std::vector<BladeSweep>& sweeps, float elapsed)
401 {
402 if (sweeps.empty() || !std::isfinite(elapsed) || elapsed<=0) return;
403 struct Region { Point a,b,c,lo,hi,direction,velocity; float front; };
404 std::vector<Region> regions;
405 constexpr int grid=32;
406 std::array<std::vector<size_t>,grid*grid> bins;
407 const auto bin=[=](float value,float extent) { return (std::clamp)(int(value/extent*grid),0,grid-1); };
408 const auto cross=[](Point a,Point b,Point p) { return (b.x-a.x)*(p.y-a.y)-(b.y-a.y)*(p.x-a.x); };
409 const auto inside=[&](const Region& r,Point p) {
410 if(p.x<r.lo.x || p.y<r.lo.y || p.x>r.hi.x || p.y>r.hi.y) return false;
411 const float a=cross(r.a,r.b,p),b=cross(r.b,r.c,p),c=cross(r.c,r.a,p);
412 return (a>=0 && b>=0 && c>=0) || (a<=0 && b<=0 && c<=0);
413 };
414 for(const auto& sweep:sweeps)
415 {
416 Point motion{};
417 for(int j=0;j<3;++j) { motion.x+=(sweep.current[j].x-sweep.previous[j].x)/3;
418 motion.y+=(sweep.current[j].y-sweep.previous[j].y)/3; }
419 const float distance=std::hypot(motion.x,motion.y);
420 if(distance<.000001f) continue;
421 const Point direction{motion.x/distance,motion.y/distance};
422 // Keep a stalled frame or asset jump from firing beads across the
423 // entire cockpit. Normal blade-tip speeds retain their momentum.
424 const float speed=(std::min)(distance/elapsed,4.f);
425 const Point velocity{direction.x*speed,direction.y*speed};
426 float front=-1.e10f;
427 for(const auto& p:sweep.current) front=(std::max)(front,p.x*direction.x+p.y*direction.y);
428 const auto add=[&](Point a,Point b,Point c) {
429 if(std::abs(cross(a,b,c))<1.e-9f) return;
430 const Point lo{(std::min)({a.x,b.x,c.x}),(std::min)({a.y,b.y,c.y})};
431 const Point hi{(std::max)({a.x,b.x,c.x}),(std::max)({a.y,b.y,c.y})};
432 if(hi.x<0 || hi.y<0 || lo.x>width || lo.y>height) return;
433 const size_t index=regions.size();
434 regions.push_back({a,b,c,lo,hi,direction,velocity,front});
435 for(int y=bin(lo.y,height);y<=bin(hi.y,height);++y)
436 for(int x=bin(lo.x,width);x<=bin(hi.x,width);++x) bins[y*grid+x].push_back(index);
437 };
438 add(sweep.previous[0],sweep.previous[1],sweep.previous[2]);
439 add(sweep.current[0],sweep.current[1],sweep.current[2]);
440 for(int j=0;j<3;++j) { const int k=(j+1)%3;
441 add(sweep.previous[j],sweep.previous[k],sweep.current[k]);
442 add(sweep.previous[j],sweep.current[k],sweep.current[j]); }
443 }
444 if(regions.empty()) return;
445 const auto crossing=[&](Point p,Point q,Point r,Point s) {
446 return (std::max)(p.x,q.x)>=(std::min)(r.x,s.x) && (std::max)(r.x,s.x)>=(std::min)(p.x,q.x)
447 && (std::max)(p.y,q.y)>=(std::min)(r.y,s.y) && (std::max)(r.y,s.y)>=(std::min)(p.y,q.y)
448 && cross(p,q,r)*cross(p,q,s)<=0 && cross(r,s,p)*cross(r,s,q)<=0;
449 };
450 for(auto& drop:drops)
451 {
452 const Region* hit=nullptr; float push=0;
453 for(size_t index:bins[bin(drop.position.y,height)*grid+bin(drop.position.x,width)])
454 {
455 const auto& r=regions[index];
456 if(!inside(r,drop.position)) continue;
457 const float reach=r.front-drop.position.x*r.direction.x-drop.position.y*r.direction.y
458 +drop.radius*1.5f+.001f;
459 if(reach>push) { push=reach;hit=&r; }
460 }
461 if(hit)
462 {
463 // Carry collected water just ahead of the rubber and release
464 // it with blade velocity. Volume is retained until it runs off
465 // the pane; the return stroke can collect it again.
466 drop.position.x+=hit->direction.x*push; drop.position.y+=hit->direction.y*push;
467 drop.velocity=hit->velocity; drop.runoffDistance=0;
468 drop.wake=drop.position;
469 continue;
470 }
471 if(drop.wake.x==drop.position.x && drop.wake.y==drop.position.y) continue;
472 bool cut=false;
473 const Point lo{(std::min)(drop.position.x,drop.wake.x),(std::min)(drop.position.y,drop.wake.y)};
474 const Point hi{(std::max)(drop.position.x,drop.wake.x),(std::max)(drop.position.y,drop.wake.y)};
475 for(int y=bin(lo.y,height);y<=bin(hi.y,height) && !cut;++y)
476 for(int x=bin(lo.x,width);x<=bin(hi.x,width) && !cut;++x)
477 for(size_t index:bins[y*grid+x])
478 {
479 const auto& r=regions[index];
480 if(r.hi.x<lo.x || r.hi.y<lo.y || r.lo.x>hi.x || r.lo.y>hi.y) continue;
481 if(inside(r,drop.wake) || crossing(drop.position,drop.wake,r.a,r.b)
482 || crossing(drop.position,drop.wake,r.b,r.c) || crossing(drop.position,drop.wake,r.c,r.a))
483 { cut=true;break; }
484 }
485 if(cut) drop.wake=drop.position;
486 }
487 // Clear old film once per covered texel, irrespective of mesh overlap.
488 for(const auto& r:regions)
489 for(int y=Pixel(r.lo.y,height);y<=Pixel(r.hi.y,height);++y)
490 for(int x=Pixel(r.lo.x,width);x<=Pixel(r.hi.x,width);++x)
491 if(trail[y*Resolution+x]>0 && inside(r,{(x+.5f)*width/Resolution,(y+.5f)*height/Resolution}))
492 trail[y*Resolution+x]=0;
493 drops.erase(std::remove_if(drops.begin(),drops.end(),[&](const Drop& d) {
494 return d.position.x<0 || d.position.y<0 || d.position.x>width || d.position.y>height;
495 }),drops.end());
496 Rebuild();
497 }
498 void Rebuild()
499 {
500 ++revision;
501 water = trail;
502 // The renderer consumes residue and analytic bead geometry, not this
503 // conservative CPU field. Preserve its exact rebuild snapshot, but
504 // rasterize beads only if a diagnostic/physics caller asks for it.
505 waterDrops.clear();
506 for (const auto& drop : drops) waterDrops.push_back({drop.position,drop.radius});
507 }
508 struct BeadSample { float x=0, y=0, radius=0, unused=0; };
509 struct WakeSample { float x=0, y=0, radius=0, strength=0; };
510 // Modest optical emphasis for cockpit viewing distances, independent of
511 // simulation volume, coalescence, runoff and high-speed breakup.
512 static constexpr float BeadRadiusScale = 1.25f;
513 // A point-sampled lookup of bead geometry, not an enlarged height image.
514 // The shader evaluates the cap in metres at each screen pixel. Texture
515 // resolution no longer imposes a minimum visible droplet diameter.
516 void BeadMap(std::vector<BeadSample>& map, std::vector<WakeSample>* wakes=nullptr,
517 std::vector<float>* scratchDistances=nullptr) const
518 {
519 map.assign(Resolution*Resolution,{});
520 if (wakes) wakes->assign(Resolution*Resolution,{});
521 std::vector<float> localDistances;
522 auto& distances=scratchDistances ? *scratchDistances : localDistances;
523 distances.resize(Resolution*Resolution);
524 const float pad=(std::max)(width,height)/Resolution;
525 for (const auto& d:drops)
526 {
527 const float radius=d.radius*BeadRadiusScale;
528 const Point tail=wakes ? d.wake : d.position;
529#if defined(_M_IX86) || defined(_M_X64)
530 // Bounds and row coordinates are constant throughout this stamp.
531 // Keep the same floating-point operations and winner order.
532 const int x0=Pixel((std::min)(d.position.x,tail.x)-radius-pad,width);
533 const int x1=Pixel((std::max)(d.position.x,tail.x)+radius+pad,width);
534 const int y0=Pixel((std::min)(d.position.y,tail.y)-radius-pad,height);
535 const int y1=Pixel((std::max)(d.position.y,tail.y)+radius+pad,height);
536 const float vx=tail.x-d.position.x,vy=tail.y-d.position.y,length2=vx*vx+vy*vy;
537 const auto sx=_mm_set1_ps(d.position.x),sy=_mm_set1_ps(d.position.y);
538 const auto svx=_mm_set1_ps(vx),svy=_mm_set1_ps(vy),sr=_mm_set1_ps(radius);
539 const auto sw=_mm_set1_ps(width),resolution=_mm_set1_ps(float(Resolution));
540 const auto sl2=_mm_set1_ps(length2),one=_mm_set1_ps(1.f),zero=_mm_setzero_ps();
541 const BeadSample bead{d.position.x,d.position.y,radius,0};
542 const WakeSample wake{tail.x,tail.y,radius*.7f,.85f};
543 for(int y=y0;y<=y1;++y)
544 {
545 const auto py=_mm_set1_ps((y+.5f)*height/Resolution);
546 const auto ay=_mm_sub_ps(py,sy);
547 for(int x=x0;x<=x1;x+=4)
548 {
549 const auto px=_mm_div_ps(_mm_mul_ps(_mm_setr_ps(x+.5f,x+1.5f,x+2.5f,x+3.5f),sw),resolution);
550 const auto ax=_mm_sub_ps(px,sx);
551 auto t=zero;
552 if(length2>1.e-12f)
553 t=_mm_min_ps(one,_mm_max_ps(zero,_mm_div_ps(
554 _mm_add_ps(_mm_mul_ps(ax,svx),_mm_mul_ps(ay,svy)),sl2)));
555 const auto dx=_mm_div_ps(_mm_sub_ps(ax,_mm_mul_ps(svx,t)),sr);
556 const auto dy=_mm_div_ps(_mm_sub_ps(ay,_mm_mul_ps(svy,t)),sr);
557 float candidates[4];_mm_storeu_ps(candidates,_mm_add_ps(_mm_mul_ps(dx,dx),_mm_mul_ps(dy,dy)));
558 for(int lane=0;lane<4 && x+lane<=x1;++lane)
559 {
560 const size_t index=y*Resolution+x+lane;auto& sample=map[index];
561 if(sample.radius==0 || candidates[lane]<distances[index])
562 {
563 distances[index]=candidates[lane];sample=bead;
564 if(wakes)(*wakes)[index]=wake;
565 }
566 }
567 }
568 }
569#else
570 for (int y=Pixel((std::min)(d.position.y,tail.y)-radius-pad,height);
571 y<=Pixel((std::max)(d.position.y,tail.y)+radius+pad,height); ++y)
572 for (int x=Pixel((std::min)(d.position.x,tail.x)-radius-pad,width);
573 x<=Pixel((std::max)(d.position.x,tail.x)+radius+pad,width); ++x)
574 {
575 const float px=(x+.5f)*width/Resolution, py=(y+.5f)*height/Resolution;
576 auto& sample=map[y*Resolution+x];
577 const auto distance=[&](float cx,float cy,float r,Point end) {
578 const float vx=end.x-cx,vy=end.y-cy, length2=vx*vx+vy*vy;
579 const float t=length2>1.e-12f ? (std::clamp)(((px-cx)*vx+(py-cy)*vy)/length2,0.f,1.f) : 0.f;
580 const float dx=(px-cx-vx*t)/r,dy=(py-cy-vy*t)/r;
581 return dx*dx+dy*dy;
582 };
583 const size_t index=y*Resolution+x;
584 const float candidate=distance(d.position.x,d.position.y,radius,tail);
585 // The winner's geometry has not changed since it was
586 // written. Retain that exact metric rather than evaluating
587 // it again for every overlapping bead. Empty texels never
588 // read scratch memory left over from a previous map.
589 if (sample.radius==0 || candidate<distances[index])
590 {
591 distances[index]=candidate;
592 sample={d.position.x,d.position.y,radius,0};
593 if (wakes) (*wakes)[index]={tail.x,tail.y,radius*.7f,.85f};
594 }
595 }
596#endif
597 }
598 }
599 // Rendering can reuse its uploads until simulation, impacts or wiping change water.
600 uint64_t Revision() const { return revision; }
601 int LastStepCount() const { return lastStepCount; }
602 const Field& Water() const { MaterializeWater(); return water; }
603 const Field& Residue() const { return trail; }
604 const std::vector<Drop>& Drops() const { return drops; }
605 size_t DropLimit() const
606 {
607 // Equal rain coverage on large front panes and small side windows.
608 return size_t(std::ceil((std::clamp)(width * height * 3072.f, 512.f, float(MaxDrops))));
609 }
610 float Width() const { return width; }
611 float Height() const { return height; }
612 bool Wet() const { if(!drops.empty())return true;MaterializeWater();return *std::max_element(water.begin(), water.end()) > .01f; }
613 float Wetness() const
614 {
615 float area = 0.f;
616 for (const auto& drop : drops) area += 3.14159265f * drop.radius * drop.radius;
617 return (std::clamp)(area / (width * height), 0.f, 1.f);
618 }
619private:
621 uint32_t random;
624 uint64_t revision = 0;
625 std::vector<Drop> drops;
629 mutable std::vector<WaterDrop> waterDrops;
631 {
632 static constexpr int Cells = 32;
633 std::vector<int> heads, next;
634 std::vector<Point> positions;
635 float maxRadius = 0, maxShift = 0;
636 static int Cell(float value, float extent)
637 { return (std::clamp)(int(value / extent * Cells), 0, Cells-1); }
638 };
639 void CappedImpact(Point position, float radius, CappedImpactIndex& index)
640 {
641 // A full pane cannot spawn satellites or append beads. Index it once
642 // per birth batch instead of scanning all 8192 beads for every impact.
643 if (index.heads.empty())
644 {
646 index.next.resize(drops.size());
647 index.positions.reserve(drops.size());
648 for (size_t i=0;i<drops.size();++i)
649 {
650 const auto& drop=drops[i];
651 const int cell=CappedImpactIndex::Cell(drop.position.y,height)*CappedImpactIndex::Cells
652 + CappedImpactIndex::Cell(drop.position.x,width);
653 index.next[i]=index.heads[cell]; index.heads[cell]=int(i);
654 index.positions.push_back(drop.position);
655 index.maxRadius=(std::max)(index.maxRadius,drop.radius);
656 }
657 }
658 ++revision;
659 const Drop incoming{position,{},radius,0,position};
660 // Merges move/grow centres during this batch. Expand queries against
661 // the original indexed positions so later impacts cannot miss them.
662 const float reach=radius+index.maxRadius+index.maxShift+.000001f;
663 size_t hit=drops.size();
664 for (int y=CappedImpactIndex::Cell(position.y-reach,height);
665 y<=CappedImpactIndex::Cell(position.y+reach,height);++y)
666 for (int x=CappedImpactIndex::Cell(position.x-reach,width);
667 x<=CappedImpactIndex::Cell(position.x+reach,width);++x)
668 for (int i=index.heads[y*CappedImpactIndex::Cells+x];i>=0;i=index.next[i])
669 if (size_t(i)<hit && Touching(drops[i],incoming)) hit=size_t(i);
670 if (hit==drops.size()) return;
671 // Match Impact's first touching bead, independent of cell/list order.
672 Merge(drops[hit],incoming);
673 index.maxRadius=(std::max)(index.maxRadius,drops[hit].radius);
674 index.maxShift=(std::max)(index.maxShift,(std::max)(
675 std::abs(drops[hit].position.x-index.positions[hit].x),
676 std::abs(drops[hit].position.y-index.positions[hit].y)));
677 }
678 void MaterializeWater() const
679 {
680 for(const auto& drop:waterDrops)
681 {
682 const float coverage = (std::min)(1.f, drop.radius * drop.radius / (.0015f * .0015f));
683 Stamp(water, drop.position, drop.radius, coverage);
684 }
685 waterDrops.clear();
686 }
687 static float Volume(const Drop& drop) { return drop.radius * drop.radius * drop.radius; }
688 static bool Touching(const Drop& a, const Drop& b)
689 {
690 const float dx = a.position.x - b.position.x, dy = a.position.y - b.position.y;
691 const float reach = a.radius + b.radius;
692 return dx * dx + dy * dy <= reach * reach;
693 }
694 static void Merge(Drop& a, const Drop& b)
695 {
696 const float va = Volume(a), vb = Volume(b), total = va + vb;
697 const float blend = vb / total;
698 // Mixing centres is not travel across the glass. Blend actual wake
699 // offsets so stationary impacts cannot invent tails in arbitrary
700 // directions, and a moving bead retains its real runoff direction.
701 const Point wake{(a.wake.x-a.position.x)*(1.f-blend)+(b.wake.x-b.position.x)*blend,
702 (a.wake.y-a.position.y)*(1.f-blend)+(b.wake.y-b.position.y)*blend};
703 a.position.x += (b.position.x - a.position.x) * blend;
704 a.position.y += (b.position.y - a.position.y) * blend;
705 a.wake={a.position.x+wake.x,a.position.y+wake.y};
706 a.velocity.x += (b.velocity.x - a.velocity.x) * blend;
707 a.velocity.y += (b.velocity.y - a.velocity.y) * blend;
708 a.radius = std::cbrt(total); // conserve water volume, not summed radii
709 }
710 void Coalesce()
711 {
712 // Sweep along X to avoid testing every pair on a sparsely wet pane.
713 std::sort(drops.begin(), drops.end(), [](const Drop& a, const Drop& b) {
714 return a.position.x - a.radius < b.position.x - b.radius;
715 });
716 for (size_t i = 0; i < drops.size(); ++i)
717 {
718 if (drops[i].radius == 0) continue;
719 for (size_t j = i + 1; j < drops.size(); ++j)
720 {
721 if (drops[j].radius == 0) continue;
722 if (drops[j].position.x - drops[j].radius > drops[i].position.x + drops[i].radius) break;
723 if (!Touching(drops[i], drops[j])) continue;
724 Merge(drops[i], drops[j]);
725 drops[j].radius = 0;
726 }
727 }
728 drops.erase(std::remove_if(drops.begin(), drops.end(), [](const Drop& d) {
729 return d.radius == 0;
730 }), drops.end());
731 }
732 static float Roughness(Point p)
733 {
734 // Bilinear value noise with smooth cell boundaries, in metres.
735 const float x=p.x*55.f,y=p.y*55.f;
736 const int ix=int(std::floor(x)),iy=int(std::floor(y));
737 const float fx=x-ix,fy=y-iy,tx=fx*fx*(3.f-2.f*fx),ty=fy*fy*(3.f-2.f*fy);
738 const auto hash=[](int a,int b) {
739 uint32_t h=uint32_t(a)*0x8da6b343u ^ uint32_t(b)*0xd8163841u;
740 h^=h>>13; h*=0x85ebca6bu; h^=h>>16;
741 return float(h>>8)*(2.f/16777216.f)-1.f;
742 };
743 const float a=hash(ix,iy),b=hash(ix+1,iy),c=hash(ix,iy+1),d=hash(ix+1,iy+1);
744 return (a+(b-a)*tx)*(1.f-ty)+(c+(d-c)*tx)*ty;
745 }
746 float Random()
747 {
748 random = random * 1664525u + 1013904223u;
749 return float(random >> 8) / 16777216.f;
750 }
751 static int Pixel(float v, float extent)
752 {
753 return (std::clamp)(int(v / extent * Resolution), 0, Resolution-1);
754 }
755 float TrailAt(Point p) const
756 {
757 if (p.x<0 || p.y<0 || p.x>width || p.y>height) return 0.f;
758 const float x=(std::clamp)(p.x/width*Resolution-.5f,0.f,float(Resolution-1));
759 const float y=(std::clamp)(p.y/height*Resolution-.5f,0.f,float(Resolution-1));
760 const int x0=int(x),y0=int(y),x1=(std::min)(x0+1,Resolution-1),y1=(std::min)(y0+1,Resolution-1);
761 const float a=trail[y0*Resolution+x0],b=trail[y0*Resolution+x1];
762 const float c=trail[y1*Resolution+x0],d=trail[y1*Resolution+x1];
763 return (a+(b-a)*(x-x0))*(1.f-(y-y0))+(c+(d-c)*(x-x0))*(y-y0);
764 }
765 void Stamp(Field& field, Point p, float radius, float amount, bool residue=false) const
766 {
767 // Prefilter the cap by the texel footprint without clamping every
768 // small bead to the same size. One metric radius on both axes keeps
769 // rectangular panes from stretching round drops into wide lozenges.
770 const float footprint = .75f * (std::max)(width,height) / Resolution;
771 const float rx = std::sqrt(radius*radius + footprint*footprint);
772 const float ry = rx;
773 // Conserve sub-texel coverage: a tiny wake must not become a full-height
774 // texel-wide ridge. Analytic wakes carry the visible narrow rivulets.
775 if (residue) amount *= radius*radius/(rx*rx);
776 for (int y = Pixel(p.y-ry,height); y <= Pixel(p.y+ry,height); ++y)
777 for (int x = Pixel(p.x-rx,width); x <= Pixel(p.x+rx,width); ++x)
778 {
779 const float dx = ((x+.5f)*width/Resolution-p.x)/rx;
780 const float dy = ((y+.5f)*height/Resolution-p.y)/ry;
781 const float h = (std::max)(0.f, 1.f-dx*dx-dy*dy) * amount;
782 field[y*Resolution+x] = (std::max)(field[y*Resolution+x], h);
783 }
784 }
785 void StampTrail(Point start, Point delta, float radius, float amount, int samples)
786 {
787 // Stamps combine by maximum, not addition. Rasterize their union once:
788 // along a straight segment only the nearest sample can win. Check its
789 // neighbours too so float rounding preserves the original cap values.
790 const float footprint=.75f*(std::max)(width,height)/Resolution;
791 const float reach=std::sqrt(radius*radius+footprint*footprint);
792 std::array<Point,32> points;
793 for(int i=0;i<samples;++i)
794 {
795 const float t=float(i)/samples;
796 points[i]={start.x+delta.x*t,start.y+delta.y*t};
797 }
798 const auto end=points[samples-1];
799 const int x0=Pixel((std::min)(start.x,end.x)-reach,width);
800 const int x1=Pixel((std::max)(start.x,end.x)+reach,width);
801 const int y0=Pixel((std::min)(start.y,end.y)-reach,height);
802 const int y1=Pixel((std::max)(start.y,end.y)+reach,height);
803 // Long diagonal runs can have mostly empty bounding rectangles. Keep
804 // the sparse stamps for those, and for runs with little overlap.
805 const float stampPixels=(2.f*reach*Resolution/width+2.f)*(2.f*reach*Resolution/height+2.f);
806 if(samples<4 || (x1-x0+1)*(y1-y0+1)>samples*stampPixels)
807 {
808 for(int i=0;i<samples;++i)Stamp(trail,points[i],radius,amount,true);
809 return;
810 }
811 amount*=radius*radius/(reach*reach);
812 const float lengthSquared=delta.x*delta.x+delta.y*delta.y;
813 for(int y=y0;y<=y1;++y)for(int x=x0;x<=x1;++x)
814 {
815 const Point pixel{(x+.5f)*width/Resolution,(y+.5f)*height/Resolution};
816 const float projected=((pixel.x-start.x)*delta.x+(pixel.y-start.y)*delta.y)/lengthSquared;
817 const int nearest=(std::clamp)(int(projected*samples+.5f),0,samples-1);
818 float& value=trail[y*Resolution+x];
819 for(int i=(std::max)(0,nearest-1);i<=(std::min)(samples-1,nearest+1);++i)
820 {
821 const float dx=(pixel.x-points[i].x)/reach;
822 const float dy=(pixel.y-points[i].y)/reach;
823 const float h=(std::max)(0.f,1.f-dx*dx-dy*dy)*amount;
824 value=(std::max)(value,h);
825 }
826 }
827 }
828};
829}
SCRIPT_CONTROL SCRIPT_STATE const void int
void BeadMap(std::vector< BeadSample > &map, std::vector< WakeSample > *wakes=nullptr, std::vector< float > *scratchDistances=nullptr) const
const std::vector< Drop > & Drops() const
Surface(float width=1, float height=1, uint32_t seed=9)
std::vector< float > Field
static bool Touching(const Drop &a, const Drop &b)
std::vector< Drop > drops
void Splash(Point position, float radius, Point velocity={}, bool coalesce=true)
std::vector< WaterDrop > waterDrops
static constexpr int Resolution
const Field & Residue() const
static constexpr float TrailHalfLifeSeconds
void SweepBlades(const std::vector< BladeSweep > &sweeps, float elapsed)
static float Roughness(Point p)
static constexpr float BeadRadiusScale
uint64_t Revision() const
void Stamp(Field &field, Point p, float radius, float amount, bool residue=false) const
void Impact(Point position, float radius, bool coalesce=true)
float TrailAt(Point p) const
void WipeTriangle(Point a, Point b, Point c)
void StampTrail(Point start, Point delta, float radius, float amount, int samples)
static float Volume(const Drop &drop)
const Field & Water() const
static constexpr size_t MaxDrops
static void Merge(Drop &a, const Drop &b)
static int Pixel(float v, float extent)
void Update(float elapsed, float rain, Point acceleration, Point wind, float airDensity, float airSpeed=-1.f, AirJet airJet={})
void CappedImpact(Point position, float radius, CappedImpactIndex &index)
Definition grid.h:14
char area[3]
Definition globals.cpp:87
Point Flow(const Region &region, Point drift, float height)
float ExteriorDropOpacity(int index, float intensity, int maximum)
constexpr float WiperCyclesPerSecond
float PrecipitationIntensity(float precipitation, float altitudeKm=0.f)
float LiquidRainIntensity(float precipitation, float snowBlend, bool exposed, float altitudeKm=0.f)
float AdvanceWiper(float phase, float elapsed, bool powered, bool raining, bool *moving=nullptr)
float AltitudeRainFactor(float altitudeKm)
float ExteriorDropBudget(float intensity, int maximum)
float CloudRainFactor(float density, float belowBaseKm, bool volumeEnabled)
int ExteriorDropCount(float intensity, int maximum)
float x
float y
float SpeedAtHeight(float t) const
float HeightFraction(Point p) const
static int Cell(float value, float extent)