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
DirectSceneLayerDarknessOverlay.cs
1using System.Drawing;
6using SkiaSharp;
7
9
32{
33 private readonly List<RevealSource> _revealSources = [];
34 private readonly List<TrackedLightReveal> _trackedLightReveals = [];
35 private readonly List<TrackedLightLayerReveal> _trackedLightLayers = [];
36
37 private readonly SKPaint _darknessPaint = new()
38 {
39 IsAntialias = true,
40 BlendMode = SKBlendMode.SrcOver,
41 Style = SKPaintStyle.Fill
42 };
43
44 private Color _darknessColor = Color.Black;
45 private byte _darknessOpacity = 190;
46 private float _innerClearRadiusRatio = 0.20f;
47 private float _midpointRadiusRatio = 0.62f;
48 private float _midpointStrength = 0.45f;
49
58 RenderSurfaceHostBase renderSurfaceHost,
59 SceneLayer sceneLayer,
60 Rectangle worldBounds,
61 string? nickname = null)
62 : base(
63 renderSurfaceHost,
65 sceneLayer,
66 view: null,
67 screenBounds: null,
68 worldBounds: worldBounds,
69 nickname: nickname)
70 {
71 ZOrder = 20_000;
72 RebuildDarknessPaint();
73 }
74
78 public IReadOnlyList<RevealSource> RevealSources => _revealSources;
79
83 public Rectangle DarknessWorldBounds
84 {
85 get => WorldBounds;
86 set => WorldBounds = value;
87 }
88
92 public Color DarknessColor
93 {
94 get => _darknessColor;
95 set
96 {
97 if (_darknessColor == value)
98 return;
99
100 _darknessColor = value;
101 RebuildDarknessPaint();
102 ForceRefresh();
103 }
104 }
105
109 public byte DarknessOpacity
110 {
111 get => _darknessOpacity;
112 set
113 {
114 if (_darknessOpacity == value)
115 return;
116
117 _darknessOpacity = value;
118 RebuildDarknessPaint();
119 ForceRefresh();
120 }
121 }
122
127 {
128 get => _innerClearRadiusRatio;
129 set
130 {
131 float clamped = Math.Clamp(value, 0f, 1f);
132
133 if (Math.Abs(_innerClearRadiusRatio - clamped) < 0.0001f)
134 return;
135
136 _innerClearRadiusRatio = clamped;
137
138 if (_midpointRadiusRatio < _innerClearRadiusRatio)
139 _midpointRadiusRatio = _innerClearRadiusRatio;
140
141 ForceRefresh();
142 }
143 }
144
149 {
150 get => _midpointRadiusRatio;
151 set
152 {
153 float clamped = Math.Clamp(value, 0f, 1f);
154 clamped = Math.Max(clamped, _innerClearRadiusRatio);
155
156 if (Math.Abs(_midpointRadiusRatio - clamped) < 0.0001f)
157 return;
158
159 _midpointRadiusRatio = clamped;
160 ForceRefresh();
161 }
162 }
163
167 public float MidpointStrength
168 {
169 get => _midpointStrength;
170 set
171 {
172 float clamped = Math.Clamp(value, 0f, 1f);
173
174 if (Math.Abs(_midpointStrength - clamped) < 0.0001f)
175 return;
176
177 _midpointStrength = clamped;
178 ForceRefresh();
179 }
180 }
181
189 public RevealSource AddRevealSource(PointF centerWorldPx, float radiusWorldPx, string? nickname = null)
190 {
191 var source = new RevealSource(
192 this,
193 centerWorldPx,
194 radiusWorldPx,
195 nickname);
196
197 _revealSources.Add(source);
198 ForceRefresh();
199 return source;
200 }
201
218 DirectRadialLight light,
219 float radiusScale = 1f,
220 float intensityScale = 1f,
221 bool trackIntensity = true,
222 string? nickname = null)
223 {
224 if (light is null)
225 throw new ArgumentNullException(nameof(light));
226
227 EnsureSameSceneLayer(light);
228
229 if (_trackedLightReveals.Any(t => ReferenceEquals(t.Light, light)))
230 return _trackedLightReveals.First(t => ReferenceEquals(t.Light, light)).Source;
231
232 var source = new RevealSource(
233 this,
234 light.CenterWorldPx,
235 light.RadiusWorldPx * Math.Max(0f, radiusScale),
236 nickname ?? light.Nickname);
237
238 _revealSources.Add(source);
239
240 var tracked = new TrackedLightReveal(
241 light,
242 source,
243 Math.Max(0f, radiusScale),
244 Math.Max(0f, intensityScale),
245 trackIntensity);
246
247 _trackedLightReveals.Add(tracked);
248
249 light.Changed += OnTrackedLightChanged;
250 light.Disposing += OnTrackedLightDisposing;
251
252 SyncTrackedLight(tracked);
253 ForceRefresh();
254 return source;
255 }
256
268 public void TrackLightLayer(
269 DirectLightLayer lightLayer,
270 float radiusScale = 1f,
271 float intensityScale = 1f,
272 bool trackIntensity = true)
273 {
274 if (lightLayer is null)
275 throw new ArgumentNullException(nameof(lightLayer));
276
277 if (!ReferenceEquals(lightLayer.SceneLayer, SceneLayer))
278 throw new ArgumentException(
279 "SceneLayer-bound darkness can only track a DirectLightLayer attached to the same SceneLayer.",
280 nameof(lightLayer));
281
282 if (_trackedLightLayers.Any(t => ReferenceEquals(t.LightLayer, lightLayer)))
283 return;
284
285 var trackedLayer = new TrackedLightLayerReveal(
286 lightLayer,
287 Math.Max(0f, radiusScale),
288 Math.Max(0f, intensityScale),
289 trackIntensity);
290
291 _trackedLightLayers.Add(trackedLayer);
292
293 foreach (var light in lightLayer.Lights)
295 light,
296 trackedLayer.RadiusScale,
297 trackedLayer.IntensityScale,
298 trackedLayer.TrackIntensity);
299
300 lightLayer.LightAdded += OnTrackedLayerLightAdded;
301 lightLayer.LightRemoving += OnTrackedLayerLightRemoving;
302 }
303
310 {
311 var tracked = _trackedLightReveals.FirstOrDefault(t => ReferenceEquals(t.Light, light));
312
313 if (tracked is null)
314 return false;
315
316 UntrackLight(tracked, removeRevealSource: true);
317 return true;
318 }
319
326 {
327 if (source is null)
328 return false;
329
330 var tracked = _trackedLightReveals.FirstOrDefault(t => ReferenceEquals(t.Source, source));
331
332 if (tracked is not null)
333 UntrackLight(tracked, removeRevealSource: false);
334
335 bool removed = _revealSources.Remove(source);
336
337 if (removed)
338 ForceRefresh();
339
340 return removed;
341 }
342
346 public void ClearRevealSources()
347 {
348 if (_revealSources.Count == 0 && _trackedLightReveals.Count == 0 && _trackedLightLayers.Count == 0)
349 return;
350
351 foreach (var trackedLayer in _trackedLightLayers.ToArray())
352 {
353 trackedLayer.LightLayer.LightAdded -= OnTrackedLayerLightAdded;
354 trackedLayer.LightLayer.LightRemoving -= OnTrackedLayerLightRemoving;
355 }
356
357 _trackedLightLayers.Clear();
358
359 foreach (var tracked in _trackedLightReveals.ToArray())
360 UntrackLight(tracked, removeRevealSource: false);
361
362 _revealSources.Clear();
363 ForceRefresh();
364 }
365
372 {
373 DarknessWorldBounds = worldBounds;
374 return this;
375 }
376
383 {
384 DarknessColor = color;
385 return this;
386 }
387
394 {
395 DarknessOpacity = opacity;
396 return this;
397 }
398
405 {
406 InnerClearRadiusRatio = ratio;
407 return this;
408 }
409
416 {
417 MidpointRadiusRatio = ratio;
418 return this;
419 }
420
427 {
428 MidpointStrength = strength;
429 return this;
430 }
431
433 protected override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
434 {
435 if (destRectScreen.Width <= 0f || destRectScreen.Height <= 0f || WorldBounds.Width <= 0 ||
436 WorldBounds.Height <= 0)
437 return;
438
439 var canvas = backbuffer.Canvas;
440 var destRect = destRectScreen.ToSKRect();
441
442 // Work in an isolated layer so DstOut reveal holes affect only this overlay,
443 // not the already-rendered scene content beneath it.
444 canvas.SaveLayer(destRect, null);
445
446 canvas.DrawRect(destRect, _darknessPaint);
447
448 for (int i = 0; i < _revealSources.Count; i++)
449 {
450 var source = _revealSources[i];
451
452 if (!source.Enabled || source.RadiusWorldPx <= 0.01f || source.Intensity <= 0.001f)
453 continue;
454
455 var centerScreen = WorldPointToDrawRect(source.CenterWorldPx, destRectScreen);
456 float radiusScreen = WorldRadiusToDrawRadius(source.RadiusWorldPx, destRectScreen);
457
458 if (radiusScreen <= 0.01f)
459 continue;
460
461 using var revealShader = BuildRevealShader(centerScreen, radiusScreen, source.Intensity);
462
463 using var revealPaint = new SKPaint
464 {
465 IsAntialias = true,
466 BlendMode = SKBlendMode.DstOut,
467 Shader = revealShader,
468 Style = SKPaintStyle.Fill
469 };
470
471 canvas.DrawRect(destRect, revealPaint);
472 }
473
474 canvas.Restore();
475 }
476
477 internal void RefreshFromSourceChange()
478 {
479 ForceRefresh();
480 }
481
482 private void OnTrackedLightChanged(DirectRadialLight light)
483 {
484 foreach (var tracked in _trackedLightReveals.Where(t => ReferenceEquals(t.Light, light)).ToArray())
485 SyncTrackedLight(tracked);
486 }
487
488 private void OnTrackedLightDisposing(object? sender, IDirectDrawable drawing)
489 {
490 if (drawing is DirectRadialLight light)
491 UntrackLight(light);
492 }
493
494 private void OnTrackedLayerLightAdded(DirectRadialLight light)
495 {
496 if (!ReferenceEquals(light.SceneLayer, SceneLayer))
497 return;
498
499 foreach (var trackedLayer in _trackedLightLayers.Where(t => t.LightLayer.Lights.Contains(light)).ToArray())
501 light,
502 trackedLayer.RadiusScale,
503 trackedLayer.IntensityScale,
504 trackedLayer.TrackIntensity);
505 }
506
507 private void OnTrackedLayerLightRemoving(DirectRadialLight light)
508 {
509 UntrackLight(light);
510 }
511
512 private void SyncTrackedLight(TrackedLightReveal tracked)
513 {
514 var light = tracked.Light;
515
516 float intensity = tracked.TrackIntensity
517 ? light.EffectiveIntensity * tracked.IntensityScale
518 : tracked.IntensityScale;
519
520 tracked.Source.SyncFromTrackedLight(
521 light.CenterWorldPx,
522 light.RadiusWorldPx * tracked.RadiusScale,
523 intensity);
524 }
525
526 private void UntrackLight(TrackedLightReveal tracked, bool removeRevealSource)
527 {
528 tracked.Light.Changed -= OnTrackedLightChanged;
529 tracked.Light.Disposing -= OnTrackedLightDisposing;
530 _trackedLightReveals.Remove(tracked);
531
532 if (removeRevealSource)
533 _revealSources.Remove(tracked.Source);
534
535 ForceRefresh();
536 }
537
538 private void EnsureSameSceneLayer(DirectRadialLight light)
539 {
540 if (!ReferenceEquals(light.SceneLayer, SceneLayer))
541 throw new ArgumentException(
542 "SceneLayer-bound darkness can only track lights attached to the same SceneLayer.",
543 nameof(light));
544 }
545
546 private PointF WorldPointToDrawRect(PointF worldPx, RectangleF destRectScreen)
547 {
548 float scaleX = destRectScreen.Width / WorldBounds.Width;
549 float scaleY = destRectScreen.Height / WorldBounds.Height;
550
551 return new PointF(
552 destRectScreen.Left + (worldPx.X - WorldBounds.Left) * scaleX,
553 destRectScreen.Top + (worldPx.Y - WorldBounds.Top) * scaleY);
554 }
555
556 private float WorldRadiusToDrawRadius(float radiusWorldPx, RectangleF destRectScreen)
557 {
558 float scaleX = destRectScreen.Width / WorldBounds.Width;
559 float scaleY = destRectScreen.Height / WorldBounds.Height;
560
561 return Math.Max(Math.Abs(radiusWorldPx * scaleX), Math.Abs(radiusWorldPx * scaleY));
562 }
563
564 private void RebuildDarknessPaint()
565 {
566 _darknessPaint.Color = Color.FromArgb(_darknessOpacity, _darknessColor).ToSKColor();
567 }
568
569 private SKShader BuildRevealShader(PointF centerScreenPx, float radiusScreenPx, float intensity)
570 {
571 byte centerAlpha = (byte)Math.Clamp((int)Math.Round(255f * Math.Clamp(intensity, 0f, 1f)), 0, 255);
572
573 byte midAlpha = (byte)Math.Clamp(
574 (int)Math.Round(255f * Math.Clamp(intensity, 0f, 1f) * _midpointStrength),
575 0,
576 255);
577
578 return SKShader.CreateRadialGradient(
579 new SKPoint(centerScreenPx.X, centerScreenPx.Y),
580 radiusScreenPx,
581 colors:
582 [
583 new SKColor(
584 255,
585 255,
586 255,
587 centerAlpha),
588 new SKColor(
589 255,
590 255,
591 255,
592 centerAlpha),
593 new SKColor(
594 255,
595 255,
596 255,
597 midAlpha),
598 new SKColor(
599 255,
600 255,
601 255,
602 0)
603 ],
604 colorPos:
605 [
606 0f,
607 _innerClearRadiusRatio,
608 _midpointRadiusRatio,
609 1f
610 ],
611 mode: SKShaderTileMode.Clamp);
612 }
613
615 protected override void Dispose(bool disposing)
616 {
617 if (disposing)
618 {
620 _darknessPaint.Dispose();
621 }
622
623 base.Dispose(disposing);
624 }
625
626 private sealed class TrackedLightReveal(
627 DirectRadialLight light,
628 RevealSource source,
629 float radiusScale,
630 float intensityScale,
631 bool trackIntensity)
632 {
636 public DirectRadialLight Light { get; } = light;
637
641 public RevealSource Source { get; } = source;
642
646 public float RadiusScale { get; } = radiusScale;
647
651 public float IntensityScale { get; } = intensityScale;
652
656 public bool TrackIntensity { get; } = trackIntensity;
657 }
658
659 private sealed class TrackedLightLayerReveal(
660 DirectLightLayer lightLayer,
661 float radiusScale,
662 float intensityScale,
663 bool trackIntensity)
664 {
668 public DirectLightLayer LightLayer { get; } = lightLayer;
669
673 public float RadiusScale { get; } = radiusScale;
674
678 public float IntensityScale { get; } = intensityScale;
679
683 public bool TrackIntensity { get; } = trackIntensity;
684 }
685
689 public sealed class RevealSource
690 {
691 private readonly DirectSceneLayerDarknessOverlay _owner;
692 private PointF _centerWorldPx;
693 private float _radiusWorldPx;
694 private float _intensity = 1f;
695 private bool _enabled = true;
696
697 internal RevealSource(
699 PointF centerWorldPx,
700 float radiusWorldPx,
701 string? nickname)
702 {
703 _owner = owner;
704 _centerWorldPx = centerWorldPx;
705 _radiusWorldPx = Math.Max(0f, radiusWorldPx);
706 Nickname = nickname;
707 }
708
712 public string? Nickname { get; }
713
717 public bool Enabled
718 {
719 get => _enabled;
720 set
721 {
722 if (_enabled == value)
723 return;
724
725 _enabled = value;
726 _owner.RefreshFromSourceChange();
727 }
728 }
729
733 public PointF CenterWorldPx
734 {
735 get => _centerWorldPx;
736 set
737 {
738 if (_centerWorldPx == value)
739 return;
740
741 _centerWorldPx = value;
742 _owner.RefreshFromSourceChange();
743 }
744 }
745
749 public float RadiusWorldPx
750 {
751 get => _radiusWorldPx;
752 set
753 {
754 float clamped = Math.Max(0f, value);
755
756 if (Math.Abs(_radiusWorldPx - clamped) < 0.0001f)
757 return;
758
759 _radiusWorldPx = clamped;
760 _owner.RefreshFromSourceChange();
761 }
762 }
763
767 public float Intensity
768 {
769 get => _intensity;
770 set
771 {
772 float clamped = Math.Clamp(value, 0f, 1f);
773
774 if (Math.Abs(_intensity - clamped) < 0.0001f)
775 return;
776
777 _intensity = clamped;
778 _owner.RefreshFromSourceChange();
779 }
780 }
781
786 public void MoveTo(PointF centerWorldPx)
787 {
788 CenterWorldPx = centerWorldPx;
789 }
790
795 public void SetRadius(float radiusWorldPx)
796 {
797 RadiusWorldPx = radiusWorldPx;
798 }
799
800 internal void SyncFromTrackedLight(PointF centerWorldPx, float radiusWorldPx, float intensity)
801 {
802 bool changed =
803 _centerWorldPx != centerWorldPx ||
804 Math.Abs(_radiusWorldPx - radiusWorldPx) >= 0.0001f ||
805 Math.Abs(_intensity - intensity) >= 0.0001f;
806
807 if (!changed)
808 return;
809
810 _centerWorldPx = centerWorldPx;
811 _radiusWorldPx = Math.Max(0f, radiusWorldPx);
812 _intensity = Math.Clamp(intensity, 0f, 1f);
813 _owner.RefreshFromSourceChange();
814 }
815 }
816}
int ZOrder
Gets or sets the Z-order (depth) used for sorting this direct drawing relative to other drawables.
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...
Rectangle WorldBounds
Gets or sets the world-space bounds of this direct drawing in pixels.
DirectDrawingBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, SceneLayer? sceneLayer, View? view, Rectangle? screenBounds, Rectangle? worldBounds, string? nickname=null)
Initializes a new instance of the DirectDrawingBase class.
Convenience owner for a group of scene-layer radial lights.
SceneLayer SceneLayer
Gets the scene layer where lights are drawn.
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 single world-space reveal source used by a DirectSceneLayerDarknessOverlay.
PointF CenterWorldPx
Gets or sets the reveal center in world-space pixels.
bool Enabled
Gets or sets whether this reveal source is currently active.
string? Nickname
Optional human-readable name for debugging and lookup.
void MoveTo(PointF centerWorldPx)
Moves the reveal source to a new world-space position.
void SetRadius(float radiusWorldPx)
Sets the reveal radius in world-space pixels.
float RadiusWorldPx
Gets or sets the reveal radius in world-space pixels.
DirectSceneLayerDarknessOverlay(RenderSurfaceHostBase renderSurfaceHost, SceneLayer sceneLayer, Rectangle worldBounds, string? nickname=null)
Initializes a new scene-layer darkness/fog 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 on this same SceneLayer.
DirectSceneLayerDarknessOverlay SetMidpointStrength(float strength)
Fluent helper to set the midpoint reveal strength.
bool RemoveRevealSource(RevealSource source)
Removes a reveal source from this overlay.
byte DarknessOpacity
Gets or sets the opacity of the darkness overlay.
void ClearRevealSources()
Removes all reveal sources and stops all automatic tracking.
Rectangle DarknessWorldBounds
Gets or sets the world-space region affected by the darkness/fog.
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.
IReadOnlyList< RevealSource > RevealSources
Gets a live, ordered list of reveal sources used by this overlay.
void TrackLightLayer(DirectLightLayer lightLayer, float radiusScale=1f, float intensityScale=1f, bool trackIntensity=true)
Tracks every current and future light in a DirectLightLayer attached to this same SceneLayer.
override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
DirectSceneLayerDarknessOverlay SetDarknessWorldBounds(Rectangle worldBounds)
Fluent helper to set the darkness/fog world bounds.
float MidpointRadiusRatio
Gets or sets the radius ratio of the midpoint alpha stop used for reveal falloff.
DirectSceneLayerDarknessOverlay SetDarknessColor(Color color)
Fluent helper to set the darkness tint.
DirectSceneLayerDarknessOverlay SetDarknessOpacity(byte opacity)
Fluent helper to set the darkness opacity.
Color DarknessColor
Gets or sets the tint color of the overlay.
override void Dispose(bool disposing)
Releases resources used by this DirectDrawingBase instance.When disposing is true,...
DirectSceneLayerDarknessOverlay SetInnerClearRadiusRatio(float ratio)
Fluent helper to set the fully-revealed radius ratio.
bool UntrackLight(DirectRadialLight light)
Stops tracking a specific light and removes its reveal source.
RevealSource AddRevealSource(PointF centerWorldPx, float radiusWorldPx, string? nickname=null)
Adds a new manually controlled reveal source in world-space.
DirectSceneLayerDarknessOverlay SetMidpointRadiusRatio(float ratio)
Fluent helper to set the midpoint radius ratio.
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 ...
Represents a single layer within a Scene, containing a grid of tiles and supporting various coordinat...
Definition SceneLayer.cs:40
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.