BioGTK  6.5.0
A .NET library & program for annotating, editing various microscopy imaging formats using Bioformats supported images. Including whole slide, pyramidal, and series.
Loading...
Searching...
No Matches
SKSlideRenderer.cs
1using SkiaSharp;
2using System;
3using System.Threading;
4using System.Threading.Tasks;
5using AForge;
6using BioLib;
7using SkiaSharp.Views.Gtk;
8
9namespace BioGTK
10{
15 public class SKSlideRenderer : IDisposable
16 {
17 #region Fields and Properties
18 private SkiaStitchingPipeline _stitchingPipeline;
19
20 // Current rendering state
21 private SKImage _currentRenderedImage;
22 private PointD _lastOrigin;
23 private double _lastResolution;
24 private ZCT _lastCoordinate;
25 private int _lastWidth;
26 private int _lastHeight;
27
28 // Source tracking
29 private OpenSlideGTK.OpenSlideBase _openSlideSource;
30 private SlideBase _slideSource;
31 private bool _isOpenSlide;
32 private bool _hasSource;
33
34 public int MaxCacheSizeMB { get; set; } = 512;
35 public int TileSize { get; set; } = 256;
36 public SKSamplingOptions Sampling { get; set; } = SKSamplingOptions.Default;
37 public bool EnablePrefetch { get; set; } = true;
38
39 // State tracking
40 public bool IsRendering { get; private set; }
41 public bool HasValidImage => _currentRenderedImage != null;
42
43 #endregion
44
45 #region Constructor
46
50 public SKSlideRenderer(SKDrawingArea sk)
51 {
52 InitializeDefaults();
53 }
54
55 private void InitializeDefaults()
56 {
57 _lastOrigin = new PointD(0, 0);
58 _lastResolution = 1.0;
59 _lastCoordinate = new ZCT(0, 0, 0);
60 _lastWidth = 600;
61 _lastHeight = 400;
62 }
63
64 #endregion
65
66 #region Source Management
67
71 public void SetSource(OpenSlideGTK.OpenSlideBase openSlideSource)
72 {
73 if (openSlideSource == null)
74 throw new ArgumentNullException(nameof(openSlideSource));
75
76 ClearCurrentSource();
77
78 _openSlideSource = openSlideSource;
79 _isOpenSlide = true;
80 _hasSource = true;
81
82 InitializeStitchingPipeline();
83 }
84
88 public void SetSource(SlideBase slideSource)
89 {
90 if (slideSource == null)
91 throw new ArgumentNullException(nameof(slideSource));
92
93 ClearCurrentSource();
94
95 _slideSource = slideSource;
96 _isOpenSlide = false;
97 _hasSource = true;
98
99 InitializeStitchingPipeline();
100 }
101
105 private void InitializeStitchingPipeline()
106 {
107 _stitchingPipeline?.Dispose();
108
109 if (_isOpenSlide)
110 {
111 _stitchingPipeline = new SkiaStitchingPipeline(_openSlideSource, MaxCacheSizeMB);
112 }
113 else
114 {
115 _stitchingPipeline = new SkiaStitchingPipeline(_slideSource, MaxCacheSizeMB);
116 }
117
118 // Apply configuration
119 _stitchingPipeline.TileSize = TileSize;
120 //_stitchingPipeline.FilterQuality = FilterQuality;
121 _stitchingPipeline.EnablePrefetch = EnablePrefetch;
122 }
123
127 private void ClearCurrentSource()
128 {
129 _currentRenderedImage?.Dispose();
130 _currentRenderedImage = null;
131
132 _stitchingPipeline?.Dispose();
133 _stitchingPipeline = null;
134
135 _hasSource = false;
136 }
137
138 #endregion
139
140 #region Async View Update
141
145 public async Task UpdateViewAsync(
146 PointD origin,
147 double resolution,
148 ZCT coordinate,
149 int width = 600,
150 int height = 400)
151 {
152 if (!_hasSource || _stitchingPipeline == null)
153 return;
154 /*
155 // Check if update is needed
156 if (!forceUpdate && !NeedsUpdate(origin, width, height, resolution, coordinate))
157 return;
158 */
159 // Cancel any in-progress render
160 //CancelCurrentRender();
161
162 // Acquire update lock
163 //await _updateSemaphore.WaitAsync();
164
165 try
166 {
167 IsRendering = true;
168 /*
169 // Create new cancellation token for this render
170 _renderCancellation = new CancellationTokenSource();
171 var cancellationToken = _renderCancellation.Token;
172 */
173 // Store current parameters
174 _lastOrigin = origin;
175 _lastResolution = resolution;
176 _lastCoordinate = coordinate;
177 _lastWidth = width;
178 _lastHeight = height;
179 /*
180 // Progressive rendering: render low-res preview first if enabled
181 if (_useProgressiveRendering && ShouldRenderPreview(resolution))
182 {
183 await RenderLowResPreviewAsync(origin, width, height, resolution, coordinate);
184 }
185 */
186 // Render full quality
187 await RenderFullQualityAsync(origin, resolution, coordinate, width, height);
188 }
189 catch (Exception ex)
190 {
191 Console.WriteLine($"Error during view update: {ex.Message}");
192 }
193 finally
194 {
195 IsRendering = false;
196 }
197 }
198
202 private async Task RenderLowResPreviewAsync(
203 PointD origin,
204 int width,
205 int height,
206 double resolution,
207 ZCT coordinate)
208 {
209 try
210 {
211 // Use a lower resolution for preview (e.g., 4x lower)
212 double previewResolution = resolution * 4.0;
213 int previewWidth = width / 2;
214 int previewHeight = height / 2;
215
216 // Create preview with stitching pipeline
217 var previewImage = await _stitchingPipeline.StitchViewportAsync(
218 origin,
219 previewResolution,
220 coordinate,
221 previewWidth,
222 previewHeight
223 );
224 /*
225 if (previewImage != null)
226 {
227 _lowResPreview?.Dispose();
228 _lowResPreview = previewImage;
229
230 // Request immediate redraw with preview
231 //RequestRedraw();
232 }
233 */
234 }
235 catch (Exception ex)
236 {
237 Console.WriteLine($"Preview render error: {ex.Message}");
238 }
239 }
240
244 private async Task RenderFullQualityAsync(
245 PointD origin,
246 double resolution,
247 ZCT coordinate,
248 int width = 600,
249 int height = 400)
250 {
251 try
252 {
253 // Use stitching pipeline to create full quality composite
254 var stitchedImage = await _stitchingPipeline.StitchViewportAsync(
255 origin,
256 resolution,
257 coordinate,
258 width,
259 height
260 );
261
262 if (stitchedImage != null)
263 {
264 _currentRenderedImage?.Dispose();
265 _currentRenderedImage = stitchedImage;
266
267 // Request redraw with new image
268 //RequestRedraw();
269 }
270 }
271 catch (Exception ex)
272 {
273 Console.WriteLine($"Full quality render error: {ex.Message}");
274 }
275 }
276
277 #endregion
278
279 #region Synchronous Rendering Methods
280
284 public SKImage RenderRegion(
285 RectangleD region,
286 int level,
287 ZCT coordinate, double resolution, int pxwidth, int pxheight)
288 {
289 if (!_hasSource || _stitchingPipeline == null)
290 return null;
291
292 return _stitchingPipeline.StitchRegion(region, level, coordinate, resolution, pxwidth, pxheight);
293 }
294
298 public SKImage RenderCurrentViewSync()
299 {
300 if (!_hasSource || _stitchingPipeline == null)
301 return null;
302
303 return _stitchingPipeline.StitchViewportAsync(
304 _lastOrigin,
305 _lastResolution,
306 _lastCoordinate,
307 _lastWidth,
308 _lastHeight
309 ).Result;
310 }
311
312 #endregion
313
314 #region Image Access for Rendering
315
320 public SKImage GetCurrentImage()
321 {
322 // Return full quality if available, otherwise preview
323 return _currentRenderedImage;
324 }
325
330 public void DrawToCanvas(SKCanvas canvas, int canvasWidth, int canvasHeight)
331 {
332 if (canvas == null)
333 return;
334
335 var image = GetCurrentImage();
336 if (image == null)
337 return;
338 try
339 {
340 using (var paint = new SKPaint
341 {
342 IsAntialias = true,
343 BlendMode = SKBlendMode.SrcOver
344 })
345 {
346 // Draw image to fill canvas
347 var destRect = new SKRect(0, 0, canvasWidth, canvasHeight);
348 canvas.DrawImage(image, destRect, paint);
349 }
350 }
351 catch (Exception ex)
352 {
353 Console.WriteLine($"Error drawing to canvas: {ex.Message}");
354 }
355 }
356
357 #endregion
358
359 #region Update Management
360
364 private bool NeedsUpdate(
365 PointD origin,
366 int width,
367 int height,
368 double resolution,
369 ZCT coordinate)
370 {
371 const double EPSILON = 0.0001;
372
373 return Math.Abs(origin.X - _lastOrigin.X) > EPSILON ||
374 Math.Abs(origin.Y - _lastOrigin.Y) > EPSILON ||
375 Math.Abs(resolution - _lastResolution) > EPSILON ||
376 width != _lastWidth ||
377 height != _lastHeight ||
378 coordinate.Z != _lastCoordinate.Z ||
379 coordinate.C != _lastCoordinate.C ||
380 coordinate.T != _lastCoordinate.T;
381 }
382
386 private bool ShouldRenderPreview(double resolution)
387 {
388 // Use preview for high-resolution views where full quality takes time
389 return resolution < 1.0; // Zoomed in significantly
390 }
391
395 private void RequestRedraw()
396 {
397 Gtk.Application.Invoke((sender, args) =>
398 {
399 App.viewer.RequestDeferredRender();
400 });
401 }
402
403 #endregion
404
405 #region Cache Management
406
410 public void ClearCache()
411 {
412 _stitchingPipeline?.ClearCache();
413 }
414
419 {
420 // Could be extended to expose actual stats from pipeline
421 return new CacheStatistics
422 {
423 IsEnabled = _stitchingPipeline != null,
424 MaxSizeMB = MaxCacheSizeMB,
425 TileSize = TileSize
426 };
427 }
428
429 public class CacheStatistics
430 {
431 public bool IsEnabled { get; set; }
432 public int MaxSizeMB { get; set; }
433 public int TileSize { get; set; }
434 }
435
436 #endregion
437
438 #region Configuration Updates
439
444 int? maxCacheSizeMB = null,
445 int? tileSize = null,
446 SKSamplingOptions? sampling = null,
447 bool? enablePrefetch = null,
448 bool? enableProgressiveRendering = null)
449 {
450 bool needsReinit = false;
451
452 if (maxCacheSizeMB.HasValue && maxCacheSizeMB.Value != MaxCacheSizeMB)
453 {
454 MaxCacheSizeMB = maxCacheSizeMB.Value;
455 needsReinit = true;
456 }
457
458 if (tileSize.HasValue && tileSize.Value != TileSize)
459 {
460 TileSize = tileSize.Value;
461 needsReinit = true;
462 }
463
464 // Reinitialize pipeline if structural changes were made
465 if (needsReinit && _hasSource)
466 {
467 InitializeStitchingPipeline();
468 }
469 }
470
471 #endregion
472
473 #region Disposal
474
475 public void Dispose()
476 {
477 _currentRenderedImage?.Dispose();
478 _stitchingPipeline?.Dispose();
479 _currentRenderedImage = null;
480 _stitchingPipeline = null;
481 }
482
483 #endregion
484 }
485}
Manages slide rendering by coordinating between the SkiaStitchingPipeline and SlideGLArea Handles asy...
SKSlideRenderer(SKDrawingArea sk)
Initialize renderer for a specific GLArea widget.
async Task UpdateViewAsync(PointD origin, double resolution, ZCT coordinate, int width=600, int height=400)
Update the rendered view asynchronously - main entry point for rendering.
CacheStatistics GetCacheStatistics()
Get cache statistics for monitoring.
void SetSource(OpenSlideGTK.OpenSlideBase openSlideSource)
Set OpenSlide source and initialize pipeline.
void ClearCache()
Clear the tile cache.
SKImage RenderRegion(RectangleD region, int level, ZCT coordinate, double resolution, int pxwidth, int pxheight)
Render a specific region synchronously (for exports, small areas)
void DrawToCanvas(SKCanvas canvas, int canvasWidth, int canvasHeight)
Draw the current image to a canvas with proper scaling Called during the Skia render callback from Sl...
void SetSource(SlideBase slideSource)
Set BioLib slide source and initialize pipeline.
void UpdateConfiguration(int? maxCacheSizeMB=null, int? tileSize=null, SKSamplingOptions? sampling=null, bool? enablePrefetch=null, bool? enableProgressiveRendering=null)
Update renderer configuration and reinitialize if needed.
SKImage RenderCurrentViewSync()
Render current viewport synchronously (blocking)
SKImage GetCurrentImage()
Get the current image for rendering - called by GLArea during draw Returns the best available image (...
SkiaSharp-based tile stitching pipeline for compositing large pyramidal images.
Definition SkiaStitch.cs:21
void ClearCache()
Clear entire cache.
SKImage StitchRegion(RectangleD region, int level, ZCT coordinate, double resolution, int pxwidth, int pxheight)
Stitch a specific region synchronously (for smaller areas)
async Task< SKImage > StitchViewportAsync(PointD origin, double resolution, ZCT coordinate, int viewportWidth=600, int viewportHeight=400)
Stitch tiles for a given viewport asynchronously.
Definition ML.cs:17