Welcome to mirror list, hosted at ThFree Co, Russian Federation.

OperationLithophane.cs « Operations « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e40caa7a009894f3fe2669f284d30d86ff887b04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/*
 *                     GNU AFFERO GENERAL PUBLIC LICENSE
 *                       Version 3, 19 November 2007
 *  Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 *  Everyone is permitted to copy and distribute verbatim copies
 *  of this license document, but changing it is not allowed.
 */

using System;
using System.Collections.Concurrent;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;
using UVtools.Core.Layers;

namespace UVtools.Core.Operations;

[Serializable]
public class OperationLithophane : Operation
{
    #region Enum

    public enum LithophaneBaseType : byte
    {
        None,
        Square,
        Model
    }

    #endregion

    #region Members
    private decimal _layerHeight;
    private ushort _bottomLayerCount;
    private decimal _bottomExposure;
    private decimal _normalExposure;

    private string? _filePath;
    private RotateDirection _rotate = RotateDirection.None;
    private bool _mirror;
    private bool _invertColor;
    private decimal _resizeFactor = 100;
    private bool _enhanceContrast;
    private sbyte _brightnessGain;
    private byte _gapClosingIterations = 4;
    private byte _removeNoiseIterations = 4;
    private byte _gaussianBlur;
    private byte _startThresholdRange = 1;
    private byte _endThresholdRange = byte.MaxValue;
    private decimal _baseThickness = 2;
    private LithophaneBaseType _baseType = LithophaneBaseType.Square;
    private ushort _baseMargin = 80;
    private decimal _lithophaneHeight = 3;
    private bool _oneLayerPerThreshold;
    private bool _enableAntiAliasing = true;

    #endregion

    #region Overrides

    public override LayerRangeSelection StartLayerRangeSelection => LayerRangeSelection.None;
    public override string IconClass => "fas fa-portrait";
    public override string Title => "Lithophane";
    public override string Description =>
        "Generate lithophane from a picture.\n" +
        "Note: The current opened file will be overwritten with this lithophane, use a dummy or a not needed file.";

    public override string ConfirmationText =>
        "generate the lithophane?";

    public override string ProgressTitle =>
        "Generating lithophane";

    public override string ProgressAction => "Threshold levels";

    public override string? ValidateInternally()
    {
        var sb = new StringBuilder();
        if (string.IsNullOrWhiteSpace(_filePath))
        {
            sb.AppendLine("The selected file is empty");
        }
        else if(!File.Exists(_filePath))
        {
            sb.AppendLine("The selected file does not exists");
        }
        else
        {
            using var mat = GetSourceMat();
            if (mat is null)
            {
                sb.AppendLine("Unable to generate the mat from source file, is it a valid image file?");
            }
            else
            {
                if (SlicerFile.ResolutionX < mat.Width * _resizeFactor / 100 || SlicerFile.ResolutionY < mat.Height * _resizeFactor / 100)
                {
                    //int differenceX = (int)SlicerFile.ResolutionX - mat.Width;
                    //int differenceY = (int)SlicerFile.ResolutionY - mat.Height;
                    var scaleX = SlicerFile.ResolutionX * 100f / mat.Width;
                    var scaleY = SlicerFile.ResolutionY * 100f / mat.Height;
                    var maxScale = Math.Min(scaleX, scaleY);

                    sb.AppendLine($"The printer resolution is not enough to accomodate the lithophane image, please scale down to a maximum of {maxScale:F0}%");
                }
            }
        }

        if (_startThresholdRange > _endThresholdRange)
        {
            sb.AppendLine("Start threshold can't be higher than end threshold");
        }

        return sb.ToString();
    }

    public override string ToString()
    {
        var result = $"{(FileExists ? $"{Path.GetFileName(_filePath)} ({Math.Abs(GetHashCode())})" : $"Lithophane {Math.Abs(GetHashCode())}")}";
        if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
        return result;
    }
    #endregion

    #region Constructor

    public OperationLithophane() { }

    public OperationLithophane(FileFormat slicerFile) : base(slicerFile)
    {
        if (_layerHeight <= 0) _layerHeight = (decimal)SlicerFile.LayerHeight;
        if (_bottomExposure <= 0) _bottomExposure = (decimal)SlicerFile.BottomExposureTime;
        if (_normalExposure <= 0) _normalExposure = (decimal)SlicerFile.ExposureTime;
        if (_bottomLayerCount <= 0) _bottomLayerCount = SlicerFile.BottomLayerCount;
        _mirror = SlicerFile.DisplayMirror != FlipDirection.None;
    }

    #endregion

    #region Properties
    public decimal LayerHeight
    {
        get => _layerHeight;
        set => RaiseAndSetIfChanged(ref _layerHeight, Layer.RoundHeight(value));
    }

    public ushort BottomLayerCount
    {
        get => _bottomLayerCount;
        set => RaiseAndSetIfChanged(ref _bottomLayerCount, value);
    }

    public decimal BottomExposure
    {
        get => _bottomExposure;
        set => RaiseAndSetIfChanged(ref _bottomExposure, Math.Round(value, 2));
    }

    public decimal NormalExposure
    {
        get => _normalExposure;
        set => RaiseAndSetIfChanged(ref _normalExposure, Math.Round(value, 2));
    }

    public string? FilePath
    {
        get => _filePath;
        set => RaiseAndSetIfChanged(ref _filePath, value);
    }

    public bool FileExists => !string.IsNullOrWhiteSpace(_filePath) && File.Exists(_filePath);

    public RotateDirection Rotate
    {
        get => _rotate;
        set => RaiseAndSetIfChanged(ref _rotate, value);
    }

    public bool Mirror
    {
        get => _mirror;
        set => RaiseAndSetIfChanged(ref _mirror, value);
    }

    public bool InvertColor
    {
        get => _invertColor;
        set => RaiseAndSetIfChanged(ref _invertColor, value);
    }

    public decimal ResizeFactor
    {
        get => _resizeFactor;
        set => RaiseAndSetIfChanged(ref _resizeFactor, Math.Max(1, value));
    }

    public bool EnhanceContrast
    {
        get => _enhanceContrast;
        set => RaiseAndSetIfChanged(ref _enhanceContrast, value);
    }

    public sbyte BrightnessGain
    {
        get => _brightnessGain;
        set => RaiseAndSetIfChanged(ref _brightnessGain, value);
    }

    public byte GapClosingIterations
    {
        get => _gapClosingIterations;
        set => RaiseAndSetIfChanged(ref _gapClosingIterations, value);
    }

    public byte RemoveNoiseIterations
    {
        get => _removeNoiseIterations;
        set => RaiseAndSetIfChanged(ref _removeNoiseIterations, value);
    }

    public byte GaussianBlur
    {
        get => _gaussianBlur;
        set => RaiseAndSetIfChanged(ref _gaussianBlur, value);
    }

    public byte StartThresholdRange
    {
        get => _startThresholdRange;
        set => RaiseAndSetIfChanged(ref _startThresholdRange, Math.Max((byte)1, value));
    }

    public byte EndThresholdRange
    {
        get => _endThresholdRange;
        set => RaiseAndSetIfChanged(ref _endThresholdRange, Math.Max((byte)1, value));
    }

    public decimal BaseThickness
    {
        get => _baseThickness;
        set => RaiseAndSetIfChanged(ref _baseThickness, Math.Max(0, value));
    }

    public LithophaneBaseType BaseType
    {
        get => _baseType;
        set => RaiseAndSetIfChanged(ref _baseType, value);
    }

    public ushort BaseMargin
    {
        get => _baseMargin;
        set => RaiseAndSetIfChanged(ref _baseMargin, value);
    }

    public decimal LithophaneHeight
    {
        get => _lithophaneHeight;
        set => RaiseAndSetIfChanged(ref _lithophaneHeight, Math.Max(0.01m, value));
    }

    public bool OneLayerPerThreshold
    {
        get => _oneLayerPerThreshold;
        set => RaiseAndSetIfChanged(ref _oneLayerPerThreshold, value);
    }

    public bool EnableAntiAliasing
    {
        get => _enableAntiAliasing;
        set => RaiseAndSetIfChanged(ref _enableAntiAliasing, value);
    }

    #endregion

    #region Equality

    protected bool Equals(OperationLithophane other)
    {
        return _layerHeight == other._layerHeight && _bottomLayerCount == other._bottomLayerCount && _bottomExposure == other._bottomExposure && _normalExposure == other._normalExposure && _filePath == other._filePath && _rotate == other._rotate && _mirror == other._mirror && _invertColor == other._invertColor && _enhanceContrast == other._enhanceContrast && _resizeFactor == other._resizeFactor && _brightnessGain == other._brightnessGain && _gapClosingIterations == other._gapClosingIterations && _removeNoiseIterations == other._removeNoiseIterations && _gaussianBlur == other._gaussianBlur && _startThresholdRange == other._startThresholdRange && _endThresholdRange == other._endThresholdRange && _baseThickness == other._baseThickness && _baseType == other._baseType && _baseMargin == other._baseMargin && _lithophaneHeight == other._lithophaneHeight && _oneLayerPerThreshold == other._oneLayerPerThreshold && _enableAntiAliasing == other._enableAntiAliasing;
    }

    public override bool Equals(object? obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((OperationLithophane) obj);
    }

    public override int GetHashCode()
    {
        var hashCode = new HashCode();
        hashCode.Add(_layerHeight);
        hashCode.Add(_bottomLayerCount);
        hashCode.Add(_bottomExposure);
        hashCode.Add(_normalExposure);
        hashCode.Add(_filePath);
        hashCode.Add((int) _rotate);
        hashCode.Add(_mirror);
        hashCode.Add(_invertColor);
        hashCode.Add(_enhanceContrast);
        hashCode.Add(_resizeFactor);
        hashCode.Add(_brightnessGain);
        hashCode.Add(_gapClosingIterations);
        hashCode.Add(_removeNoiseIterations);
        hashCode.Add(_gaussianBlur);
        hashCode.Add(_startThresholdRange);
        hashCode.Add(_endThresholdRange);
        hashCode.Add(_baseThickness);
        hashCode.Add((int) _baseType);
        hashCode.Add(_baseMargin);
        hashCode.Add(_lithophaneHeight);
        hashCode.Add(_oneLayerPerThreshold);
        hashCode.Add(_enableAntiAliasing);
        return hashCode.ToHashCode();
    }

    #endregion

    #region Methods

    public Mat? GetSourceMat()
    {
        if (!FileExists) return null;
        try
        {
            var mat = CvInvoke.Imread(_filePath, ImreadModes.Grayscale);
            if (_invertColor) CvInvoke.BitwiseNot(mat, mat);
            mat = mat.CropByBounds();
            return mat.Size == Size.Empty ? null : mat;
        }
        catch
        {
            // ignored
        }

        return null;
    }

    public Mat? GetTargetMat()
    {
        var mat = GetSourceMat();
        if (mat is null) return null;
        
        if (_resizeFactor != 100) mat.Resize((double)_resizeFactor / 100.0);
        
        if (_enhanceContrast) CvInvoke.EqualizeHist(mat, mat);
        if (_brightnessGain != 0)
        {
            using var mask = mat.NewSetTo(new MCvScalar(Math.Abs(_brightnessGain)));
            if(_brightnessGain > 0) CvInvoke.Add(mat, mask, mat, mat);
            else CvInvoke.Subtract(mat, mask, mat, mat);
        }

        if (_gaussianBlur > 0)
        {
            var ksize = 1 + _gaussianBlur * 2;
            CvInvoke.GaussianBlur(mat, mat, new Size(ksize, ksize), 0);
        }

        if (_removeNoiseIterations > 0) CvInvoke.MorphologyEx(mat, mat, MorphOp.Open, EmguExtensions.Kernel3x3Rectangle, new Point(-1, -1), _removeNoiseIterations, BorderType.Reflect101, default);
        if (_gapClosingIterations > 0) CvInvoke.MorphologyEx(mat, mat, MorphOp.Close, EmguExtensions.Kernel3x3Rectangle, new Point(-1, -1), _gapClosingIterations, BorderType.Reflect101, default);
        
        if (_rotate != RotateDirection.None) CvInvoke.Rotate(mat, mat, (RotateFlags) _rotate);
        if (_mirror)
        {
            var flip = SlicerFile.DisplayMirror;
            if (flip == FlipDirection.None) flip = FlipDirection.Horizontally;
            CvInvoke.Flip(mat, mat, (FlipType)flip);
        }

        return mat;
    }

    protected override bool ExecuteInternally(OperationProgress progress)
    {
        using var mat = GetTargetMat();
        if (mat is null) return false;
        
        var layersBag = new ConcurrentDictionary<byte, Layer>();
        progress.Reset("Threshold levels", byte.MaxValue);
        Parallel.For(_startThresholdRange, _endThresholdRange, CoreSettings.GetParallelOptions(progress), threshold =>
        {
            using var thresholdMat = new Mat();
            CvInvoke.Threshold(mat, thresholdMat, threshold, byte.MaxValue, ThresholdType.Binary);
            if (CvInvoke.CountNonZero(thresholdMat) == 0) return;

            if (_enableAntiAliasing)
            {
                CvInvoke.GaussianBlur(thresholdMat, thresholdMat, new Size(3, 3), 0);
            }

            using var layerMat = EmguExtensions.InitMat(SlicerFile.Resolution);
            thresholdMat.CopyToCenter(layerMat);
            layersBag.TryAdd((byte)threshold, new Layer(layerMat, SlicerFile));
            progress.LockAndIncrement();
        });

        var thresholdLayers = layersBag.OrderBy(pair => pair.Key).Select(pair => pair.Value).ToArray();

        if (!_oneLayerPerThreshold)
        {
            var layerIncrementF = thresholdLayers.Length * _layerHeight / Math.Max(_layerHeight, _lithophaneHeight);
            if (layerIncrementF >= 2)
            {
                var layerIncrement = (uint) layerIncrementF;
                var indexes = new int[(int)Math.Ceiling(thresholdLayers.Length / (float)layerIncrement)];
                var newLayers = new Layer[indexes.Length];
                var count = 0;
                for (int index = 0; index < thresholdLayers.Length; index++)
                {
                    if (index % layerIncrement != 0) continue;
                    newLayers[count] = thresholdLayers[index];
                    indexes[count++] = index;
                    
                }

                progress.ResetNameAndProcessed("Packed layers");
                Parallel.ForEach(indexes, CoreSettings.GetParallelOptions(progress), i =>
                {
                    progress.LockAndIncrement();
                    using var mat = thresholdLayers[i].LayerMat;
                    for (int index = i+1; index < i + layerIncrement && index < thresholdLayers.Length; index++)
                    {
                        using var nextMat = thresholdLayers[index].LayerMat;
                        CvInvoke.Max(mat, nextMat, mat);
                        progress.LockAndIncrement();
                    }

                    thresholdLayers[i].LayerMat = mat;
                });


                thresholdLayers = newLayers;
            }
            else if (layerIncrementF < 1)
            {
                var layerIncrement = (uint)(1/layerIncrementF);
                if (layerIncrement > 1)
                {
                    progress.Reset("Packed layers");
                    var newLayers = new Layer[thresholdLayers.Length * layerIncrement];
                    for (int i = 0; i < thresholdLayers.Length; i++)
                    {
                        var layer = thresholdLayers[i];
                        var newIndex = i * layerIncrement;
                        newLayers[newIndex] = layer;
                        for (int x = 1; x < layerIncrement; x++)
                        {
                            newLayers[++newIndex] = layer.Clone();
                        }

                    }
                    thresholdLayers = newLayers;
                }
            }
        }

        if (_baseType != LithophaneBaseType.None && _baseThickness > 0)
        {
            int baseLayerCount = (int)(_baseThickness / _layerHeight);
            var newLayers = new Layer[thresholdLayers.Length + baseLayerCount];
            using var baseMat = SlicerFile.CreateMat();
            
            switch (_baseType)
            {
                case LithophaneBaseType.Square:
                {
                    var rectangle = new Rectangle(
                        baseMat.Width / 2 - mat.Width / 2 - _baseMargin / 2,
                        baseMat.Height / 2 - mat.Height / 2 - _baseMargin / 2, 
                        mat.Width + _baseMargin, 
                        mat.Height + _baseMargin);
                    CvInvoke.Rectangle(baseMat, rectangle, EmguExtensions.WhiteColor, -1, _enableAntiAliasing ? LineType.AntiAlias : LineType.EightConnected);
                    break;
                }
                case LithophaneBaseType.Model:
                {
                    using var dilatedMat = new Mat();
                    CvInvoke.Threshold(mat, dilatedMat, 1, byte.MaxValue, ThresholdType.Binary);
                    CvInvoke.Dilate(dilatedMat, dilatedMat, EmguExtensions.Kernel3x3Rectangle, new Point(-1, -1), _baseMargin, BorderType.Reflect101, default);
                    dilatedMat.CopyToCenter(baseMat);
                    break;
                }
            }
            
            var baseLayer = new Layer(baseMat, SlicerFile);
            newLayers[0] = baseLayer;
            for (int i = 1; i < baseLayerCount; i++)
            {
                newLayers[i] = baseLayer.Clone();
            }
            Array.Copy(thresholdLayers, 0, newLayers, baseLayerCount, thresholdLayers.Length);
            thresholdLayers = newLayers;
        }

        SlicerFile.SuppressRebuildPropertiesWork(() =>
        {
            SlicerFile.LayerHeight = (float) _layerHeight;
            SlicerFile.BottomLayerCount = _bottomLayerCount;
            SlicerFile.BottomExposureTime = (float) _bottomExposure;
            SlicerFile.ExposureTime = (float) _normalExposure;

            SlicerFile.Layers = thresholdLayers;
        }, true);
        

        using var bgrMat = new Mat();
        CvInvoke.CvtColor(mat, bgrMat, ColorConversion.Gray2Bgr);
        int baseLine = 0;
        var textSize = CvInvoke.GetTextSize("UVtools Lithophane", FontFace.HersheyDuplex, 2, 3, ref baseLine);
        CvInvoke.PutText(bgrMat, "UVtools Lithophane", new Point(bgrMat.Width / 2 - textSize.Width / 2, 60), FontFace.HersheyDuplex, 2, new MCvScalar(255, 27, 245), 3);
        SlicerFile.SetThumbnails(bgrMat);

        return !progress.Token.IsCancellationRequested;
    }


    #endregion
}