Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
DirectDarknessOverlay.cs
1using System.Drawing;
7using SkiaSharp;
8
10
53{
54 private readonly List<RevealSource> _revealSources = [];
55 private readonly List<TrackedLightReveal> _trackedLightReveals = [];
56 private readonly List<TrackedLightLayerReveal> _trackedLightLayers = [];
57
58 private readonly SKPaint _darknessPaint = new()
59 {
60 IsAntialias = true,
61 BlendMode = SKBlendMode.SrcOver,
62 Style = SKPaintStyle.Fill
63 };
64
65 private Color _darknessColor = Color.Black;
66 private byte _darknessOpacity = 190;
67 private float _innerClearRadiusRatio = 0.20f;
68 private float _midpointRadiusRatio = 0.62f;
69 private float _midpointStrength = 0.45f;
70
82 RenderSurfaceHostBase renderSurfaceHost,
83 View view,
84 SceneLayer projectionLayer,
85 string? nickname = null)
86 : base(
87 renderSurfaceHost,
89 sceneLayer: null,
90 view: view,
91 screenBounds: view.Viewport.TargetRectPx,
92 worldBounds: null,
93 nickname: nickname)
94 {
95 ProjectionLayer = projectionLayer ?? throw new ArgumentNullException(nameof(projectionLayer));
96 ZOrder = 20_000;
97 RebuildDarknessPaint();
98 }
99
104
108 public IReadOnlyList<RevealSource> RevealSources => _revealSources;
109
113 public Color DarknessColor
114 {
115 get => _darknessColor;
116 set
117 {
118 if (_darknessColor == value)
119 return;
120
121 _darknessColor = value;
122 RebuildDarknessPaint();
123 ForceRefresh();
124 }
125 }
126
130 public byte DarknessOpacity
131 {
132 get => _darknessOpacity;
133 set
134 {
135 if (_darknessOpacity == value)
136 return;
137
138 _darknessOpacity = value;
139 RebuildDarknessPaint();
140 ForceRefresh();
141 }
142 }
143
152 {
153 get => _innerClearRadiusRatio;
154 set
155 {
156 float clamped = Math.Clamp(value, 0f, 1f);
157
158 if (Math.Abs(_innerClearRadiusRatio - clamped) < 0.0001f)
159 return;
160
161 _innerClearRadiusRatio = clamped;
162
163 if (_midpointRadiusRatio < _innerClearRadiusRatio)
164 _midpointRadiusRatio = _innerClearRadiusRatio;
165
166 ForceRefresh();
167 }
168 }
169
174 {
175 get => _midpointRadiusRatio;
176 set
177 {
178 float clamped = Math.Clamp(value, 0f, 1f);
179 clamped = Math.Max(clamped, _innerClearRadiusRatio);
180
181 if (Math.Abs(_midpointRadiusRatio - clamped) < 0.0001f)
182 return;
183
184 _midpointRadiusRatio = clamped;
185 ForceRefresh();
186 }
187 }
188
195 public float MidpointStrength
196 {
197 get => _midpointStrength;
198 set
199 {
200 float clamped = Math.Clamp(value, 0f, 1f);
201
202 if (Math.Abs(_midpointStrength - clamped) < 0.0001f)
203 return;
204
205 _midpointStrength = clamped;
206 ForceRefresh();
207 }
208 }
209
217 public RevealSource AddRevealSource(PointF centerWorldPx, float radiusWorldPx, string? nickname = null)
218 {
219 var source = new RevealSource(
220 this,
221 centerWorldPx,
222 radiusWorldPx,
223 nickname);
224
225 _revealSources.Add(source);
226 ForceRefresh();
227 return source;
228 }
229
250 DirectRadialLight light,
251 float radiusScale = 1f,
252 float intensityScale = 1f,
253 bool trackIntensity = true,
254 string? nickname = null)
255 {
256 if (light is null)
257 throw new ArgumentNullException(nameof(light));
258
259 if (_trackedLightReveals.Any(t => ReferenceEquals(t.Light, light)))
260 return _trackedLightReveals.First(t => ReferenceEquals(t.Light, light)).Source;
261
262 var source = new RevealSource(
263 this,
264 light.CenterWorldPx,
265 light.RadiusWorldPx * Math.Max(0f, radiusScale),
266 nickname ?? light.Nickname);
267
268 _revealSources.Add(source);
269
270 var tracked = new TrackedLightReveal(
271 light,
272 source,
273 Math.Max(0f, radiusScale),
274 Math.Max(0f, intensityScale),
275 trackIntensity);
276
277 _trackedLightReveals.Add(tracked);
278
279 light.Changed += OnTrackedLightChanged;
280 light.Disposing += OnTrackedLightDisposing;
281
282 SyncTrackedLight(tracked);
283 ForceRefresh();
284 return source;
285 }
286
304 public void TrackLightLayer(
305 DirectLightLayer lightLayer,
306 float radiusScale = 1f,
307 float intensityScale = 1f,
308 bool trackIntensity = true)
309 {
310 if (lightLayer is null)
311 throw new ArgumentNullException(nameof(lightLayer));
312
313 if (_trackedLightLayers.Any(t => ReferenceEquals(t.LightLayer, lightLayer)))
314 return;
315
316 var trackedLayer = new TrackedLightLayerReveal(
317 lightLayer,
318 Math.Max(0f, radiusScale),
319 Math.Max(0f, intensityScale),
320 trackIntensity);
321
322 _trackedLightLayers.Add(trackedLayer);
323
324 foreach (var light in lightLayer.Lights)
326 light,
327 trackedLayer.RadiusScale,
328 trackedLayer.IntensityScale,
329 trackedLayer.TrackIntensity);
330
331 lightLayer.LightAdded += OnTrackedLayerLightAdded;
332 lightLayer.LightRemoving += OnTrackedLayerLightRemoving;
333 }
334
341 {
342 var tracked = _trackedLightReveals.FirstOrDefault(t => ReferenceEquals(t.Light, light));
343
344 if (tracked is null)
345 return false;
346
347 UntrackLight(tracked, removeRevealSource: true);
348 return true;
349 }
350
357 {
358 if (source is null)
359 return false;
360
361 var tracked = _trackedLightReveals.FirstOrDefault(t => ReferenceEquals(t.Source, source));
362
363 if (tracked is not null)
364 UntrackLight(tracked, removeRevealSource: false);
365
366 bool removed = _revealSources.Remove(source);
367
368 if (removed)
369 ForceRefresh();
370
371 return removed;
372 }
373
377 public void ClearRevealSources()
378 {
379 if (_revealSources.Count == 0 && _trackedLightReveals.Count == 0 && _trackedLightLayers.Count == 0)
380 return;
381
382 foreach (var trackedLayer in _trackedLightLayers.ToArray())
383 {
384 trackedLayer.LightLayer.LightAdded -= OnTrackedLayerLightAdded;
385 trackedLayer.LightLayer.LightRemoving -= OnTrackedLayerLightRemoving;
386 }
387
388 _trackedLightLayers.Clear();
389
390 foreach (var tracked in _trackedLightReveals.ToArray())
391 UntrackLight(tracked, removeRevealSource: false);
392
393 _revealSources.Clear();
394 ForceRefresh();
395 }
396
403 {
404 DarknessColor = color;
405 return this;
406 }
407
414 {
415 DarknessOpacity = opacity;
416 return this;
417 }
418
425 {
426 InnerClearRadiusRatio = ratio;
427 return this;
428 }
429
436 {
437 MidpointRadiusRatio = ratio;
438 return this;
439 }
440
447 {
448 MidpointStrength = strength;
449 return this;
450 }
451
453 public override void Update(long tick)
454 {
455 // Keep the overlay pinned to the current viewport bounds.
456 var targetRect = View!.Viewport.TargetRectPx;
457
458 if (ScreenBounds != targetRect)
459 ScreenBounds = targetRect;
460
461 base.Update(tick);
462 }
463
465 protected override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
466 {
467 var canvas = backbuffer.Canvas;
468 var destRect = destRectScreen.ToSKRect();
469
470 // Work in an isolated layer so "holes" reveal the already-rendered scene beneath,
471 // rather than clearing the backbuffer itself.
472 canvas.SaveLayer(destRect, null);
473
474 canvas.DrawRect(destRect, _darknessPaint);
475
476 for (int i = 0; i < _revealSources.Count; i++)
477 {
478 var source = _revealSources[i];
479
480 if (!source.Enabled || source.RadiusWorldPx <= 0.01f || source.Intensity <= 0.001f)
481 continue;
482
483 var centerScreen = View!.WorldPxToScreenPx(ProjectionLayer, source.CenterWorldPx);
484
485 var radiusProbeWorld = new PointF(source.CenterWorldPx.X + source.RadiusWorldPx, source.CenterWorldPx.Y);
486 var radiusProbeScreen = View.WorldPxToScreenPx(ProjectionLayer, radiusProbeWorld);
487 float screenRadius = Math.Abs(radiusProbeScreen.X - centerScreen.X);
488
489 if (screenRadius <= 0.01f)
490 continue;
491
492 using var revealShader = BuildRevealShader(centerScreen, screenRadius, source.Intensity);
493
494 using var revealPaint = new SKPaint
495 {
496 IsAntialias = true,
497 BlendMode = SKBlendMode.DstOut,
498 Shader = revealShader,
499 Style = SKPaintStyle.Fill
500 };
501
502 canvas.DrawRect(destRect, revealPaint);
503 }
504
505 canvas.Restore();
506 }
507
508 internal void RefreshFromSourceChange()
509 {
510 ForceRefresh();
511 }
512
513 private void OnTrackedLightChanged(DirectRadialLight light)
514 {
515 foreach (var tracked in _trackedLightReveals.Where(t => ReferenceEquals(t.Light, light)).ToArray())
516 SyncTrackedLight(tracked);
517 }
518
519 private void OnTrackedLightDisposing(object? sender, IDirectDrawable drawing)
520 {
521 if (drawing is DirectRadialLight light)
522 UntrackLight(light);
523 }
524
525 private void OnTrackedLayerLightAdded(DirectRadialLight light)
526 {
527 foreach (var trackedLayer in _trackedLightLayers.Where(t => t.LightLayer.Lights.Contains(light)).ToArray())
529 light,
530 trackedLayer.RadiusScale,
531 trackedLayer.IntensityScale,
532 trackedLayer.TrackIntensity);
533 }
534
535 private void OnTrackedLayerLightRemoving(DirectRadialLight light)
536 {
537 UntrackLight(light);
538 }
539
540 private void SyncTrackedLight(TrackedLightReveal tracked)
541 {
542 var light = tracked.Light;
543
544 float intensity = tracked.TrackIntensity
545 ? light.EffectiveIntensity * tracked.IntensityScale
546 : tracked.IntensityScale;
547
548 tracked.Source.SyncFromTrackedLight(
549 light.CenterWorldPx,
550 light.RadiusWorldPx * tracked.RadiusScale,
551 intensity);
552 }
553
554 private void UntrackLight(TrackedLightReveal tracked, bool removeRevealSource)
555 {
556 tracked.Light.Changed -= OnTrackedLightChanged;
557 tracked.Light.Disposing -= OnTrackedLightDisposing;
558 _trackedLightReveals.Remove(tracked);
559
560 if (removeRevealSource)
561 _revealSources.Remove(tracked.Source);
562
563 ForceRefresh();
564 }
565
566 private void RebuildDarknessPaint()
567 {
568 _darknessPaint.Color = Color.FromArgb(_darknessOpacity, _darknessColor).ToSKColor();
569 }
570
571 private SKShader BuildRevealShader(PointF centerScreenPx, float radiusScreenPx, float intensity)
572 {
573 byte centerAlpha = (byte)Math.Clamp((int)Math.Round(255f * Math.Clamp(intensity, 0f, 1f)), 0, 255);
574
575 byte midAlpha = (byte)Math.Clamp(
576 (int)Math.Round(255f * Math.Clamp(intensity, 0f, 1f) * _midpointStrength),
577 0,
578 255);
579
580 return SKShader.CreateRadialGradient(
581 new SKPoint(centerScreenPx.X, centerScreenPx.Y),
582 radiusScreenPx,
583 colors:
584 [
585 new SKColor(
586 255,
587 255,
588 255,
589 centerAlpha),
590 new SKColor(
591 255,
592 255,
593 255,
594 centerAlpha),
595 new SKColor(
596 255,
597 255,
598 255,
599 midAlpha),
600 new SKColor(
601 255,
602 255,
603 255,
604 0)
605 ],
606 colorPos:
607 [
608 0f,
609 _innerClearRadiusRatio,
610 _midpointRadiusRatio,
611 1f
612 ],
613 mode: SKShaderTileMode.Clamp);
614 }
615
617 protected override void Dispose(bool disposing)
618 {
619 if (disposing)
620 {
622 _darknessPaint.Dispose();
623 }
624
625 base.Dispose(disposing);
626 }
627
628 private sealed class TrackedLightReveal(
629 DirectRadialLight light,
630 RevealSource source,
631 float radiusScale,
632 float intensityScale,
633 bool trackIntensity)
634 {
638 public DirectRadialLight Light { get; } = light;
639
643 public RevealSource Source { get; } = source;
644
648 public float RadiusScale { get; } = radiusScale;
649
653 public float IntensityScale { get; } = intensityScale;
654
658 public bool TrackIntensity { get; } = trackIntensity;
659 }
660
661 private sealed class TrackedLightLayerReveal(
662 DirectLightLayer lightLayer,
663 float radiusScale,
664 float intensityScale,
665 bool trackIntensity)
666 {
670 public DirectLightLayer LightLayer { get; } = lightLayer;
671
675 public float RadiusScale { get; } = radiusScale;
676
680 public float IntensityScale { get; } = intensityScale;
681
685 public bool TrackIntensity { get; } = trackIntensity;
686 }
687
691 public sealed class RevealSource
692 {
693 private readonly DirectDarknessOverlay _owner;
694 private PointF _centerWorldPx;
695 private float _radiusWorldPx;
696 private float _intensity = 1f;
697 private bool _enabled = true;
698
699 internal RevealSource(
701 PointF centerWorldPx,
702 float radiusWorldPx,
703 string? nickname)
704 {
705 _owner = owner;
706 _centerWorldPx = centerWorldPx;
707 _radiusWorldPx = Math.Max(0f, radiusWorldPx);
708 Nickname = nickname;
709 }
710
714 public string? Nickname { get; }
715
719 public bool Enabled
720 {
721 get => _enabled;
722 set
723 {
724 if (_enabled == value)
725 return;
726
727 _enabled = value;
728 _owner.RefreshFromSourceChange();
729 }
730 }
731
735 public PointF CenterWorldPx
736 {
737 get => _centerWorldPx;
738 set
739 {
740 if (_centerWorldPx == value)
741 return;
742
743 _centerWorldPx = value;
744 _owner.RefreshFromSourceChange();
745 }
746 }
747
751 public float RadiusWorldPx
752 {
753 get => _radiusWorldPx;
754 set
755 {
756 float clamped = Math.Max(0f, value);
757
758 if (Math.Abs(_radiusWorldPx - clamped) < 0.0001f)
759 return;
760
761 _radiusWorldPx = clamped;
762 _owner.RefreshFromSourceChange();
763 }
764 }
765
772 public float Intensity
773 {
774 get => _intensity;
775 set
776 {
777 float clamped = Math.Clamp(value, 0f, 1f);
778
779 if (Math.Abs(_intensity - clamped) < 0.0001f)
780 return;
781
782 _intensity = clamped;
783 _owner.RefreshFromSourceChange();
784 }
785 }
786
791 public void MoveTo(PointF centerWorldPx)
792 {
793 CenterWorldPx = centerWorldPx;
794 }
795
800 public void SetRadius(float radiusWorldPx)
801 {
802 RadiusWorldPx = radiusWorldPx;
803 }
804
805 internal void SyncFromTrackedLight(PointF centerWorldPx, float radiusWorldPx, float intensity)
806 {
807 bool changed =
808 _centerWorldPx != centerWorldPx ||
809 Math.Abs(_radiusWorldPx - radiusWorldPx) >= 0.0001f ||
810 Math.Abs(_intensity - intensity) >= 0.0001f;
811
812 if (!changed)
813 return;
814
815 _centerWorldPx = centerWorldPx;
816 _radiusWorldPx = Math.Max(0f, radiusWorldPx);
817 _intensity = Math.Clamp(intensity, 0f, 1f);
818 _owner.RefreshFromSourceChange();
819 }
820 }
821}
Represents a single world-space reveal source used by a DirectDarknessOverlay.
void MoveTo(PointF centerWorldPx)
Moves the reveal source to a new world-space position.
bool Enabled
Gets or sets whether this reveal source is currently active.
void SetRadius(float radiusWorldPx)
Sets the reveal radius in world-space pixels.
float RadiusWorldPx
Gets or sets the reveal radius in world-space pixels.
float Intensity
Gets or sets the reveal intensity from 0..1.
string? Nickname
Optional human-readable name for debugging and lookup.
PointF CenterWorldPx
Gets or sets the reveal center in world-space pixels.
byte DarknessOpacity
Gets or sets the opacity of the darkness overlay.
void ClearRevealSources()
Removes all reveal sources and stops all automatic tracking.
RevealSource AddRevealSource(PointF centerWorldPx, float radiusWorldPx, string? nickname=null)
Adds a new manually controlled reveal source in world-space.
DirectDarknessOverlay(RenderSurfaceHostBase renderSurfaceHost, View view, SceneLayer projectionLayer, string? nickname=null)
Initializes a new darkness/fog overlay that covers a specific view.
float MidpointRadiusRatio
Gets or sets the radius ratio of the midpoint alpha stop used for reveal falloff.
float MidpointStrength
Gets or sets the removal strength at the midpoint stop.
float InnerClearRadiusRatio
Gets or sets the radius ratio that remains fully revealed before falloff begins.
DirectDarknessOverlay SetDarknessColor(Color color)
Fluent helper to set the darkness tint.
bool UntrackLight(DirectRadialLight light)
Stops tracking a specific light and removes its reveal source.
void TrackLightLayer(DirectLightLayer lightLayer, float radiusScale=1f, float intensityScale=1f, bool trackIntensity=true)
Tracks every current and future light in a DirectLightLayer.
DirectDarknessOverlay SetInnerClearRadiusRatio(float ratio)
Fluent helper to set the fully-revealed radius ratio.
SceneLayer ProjectionLayer
Gets the scene layer used to project reveal source world positions into screen coordinates.
bool RemoveRevealSource(RevealSource source)
Removes a reveal source from this overlay.
RevealSource TrackLight(DirectRadialLight light, float radiusScale=1f, float intensityScale=1f, bool trackIntensity=true, string? nickname=null)
Adds a reveal source that automatically tracks a DirectRadialLight.
Color DarknessColor
Gets or sets the tint color of the overlay.
DirectDarknessOverlay SetDarknessOpacity(byte opacity)
Fluent helper to set the darkness opacity.
override void Update(long tick)
Performs per-frame update logic for this direct drawing, including fade and reveal animations....
IReadOnlyList< RevealSource > RevealSources
Gets a live, ordered list of reveal sources used by this overlay.
override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
DirectDarknessOverlay SetMidpointStrength(float strength)
Fluent helper to set the midpoint reveal strength.
override void Dispose(bool disposing)
Releases resources used by this DirectDrawingBase instance.When disposing is true,...
DirectDarknessOverlay SetMidpointRadiusRatio(float ratio)
Fluent helper to set the midpoint radius ratio.
int ZOrder
Gets or sets the Z-order (depth) used for sorting this direct drawing relative to other drawables.
View? View
Gets the view to which this direct drawing is attached, or null if the drawing is in scene-layer mode...
string? Nickname
Gets the optional human-readable name for this direct drawing.
SceneLayer? SceneLayer
Gets the scene layer to which this direct drawing is attached, or null if the drawing is in view mode...
DirectDrawingBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, SceneLayer? sceneLayer, View? view, Rectangle? screenBounds, Rectangle? worldBounds, string? nickname=null)
Initializes a new instance of the DirectDrawingBase class.
Rectangle ScreenBounds
Gets or sets the screen-space bounds of this direct drawing in pixels.
Convenience owner for a group of scene-layer radial lights.
Draws a bounded, radial light effect as a scene-layer direct drawing.
float RadiusWorldPx
Gets the light radius in world pixels.
PointF CenterWorldPx
Gets the light center in world pixels.
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
SKCanvas Canvas
Gets the SkiaSharp canvas used for drawing operations on this backbuffer.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
A rectangular window on the render target with its own zoom and placement. Viewport never moves the w...
Definition Viewport.cs:10
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.