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

OperationInfill.cs « Operations « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 74c4835def9e4908d10e0b53e16f2d13dae94139 (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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
 *                     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 Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;

namespace UVtools.Core.Operations;


public sealed class OperationInfill : Operation
{
    #region Members
    private InfillAlgorithm _infillType = InfillAlgorithm.CubicCrossAlternating;
    private ushort _wallThickness = 64;
    private ushort _infillThickness = 45;
    private ushort _infillSpacing = 300;
    private byte _infillBrightness = 255;
    private bool _reinforceInfill;

    #endregion

    #region Overrides
    public override string IconClass => "mdi-checkerboard";
    public override string Title => "Infill";

    public override string Description =>
        $"Generate infill patterns in the model.\n\nNOTES:\n1) You must exclude floor and ceil layers from the range.\n2) You must take care of drain holes after the operation.";

    public override string ConfirmationText =>
        $"infill model with {InfillType} from layers {LayerIndexStart} through {LayerIndexEnd}?";

    public override string ProgressTitle =>
        $"Infill model with {InfillType} from layers {LayerIndexStart} through {LayerIndexEnd}";

    public override string ProgressAction => "Infilled layers";

    #endregion

    #region Enums
    public enum InfillAlgorithm
    {
        //Rhombus,
        [Description("Straight pillars (Weak)")]
        Pillars,

        [Description("Concentric (Weak)")]
        Concentric,

        [Description("Waves (Medium)")]
        Waves,

        [Description("Cubic cross: Fixed pilars with crossing sections (Optimal)")]
        CubicCross,

        [Description("Cubic alternating cross: Fixed pilars with crossing sections alternating in directions (Optimal)")]
        CubicCrossAlternating,

        [Description("Cubic star: Fixed pilars with crossing sections in star pattern (Strong)")]
        CubicStar,

        [Description("Honeycomb (Strong)")]
        Honeycomb,

        [Description("Gyroid (Strong)")]
        Gyroid,
    }
    #endregion

    #region Properties
    public InfillAlgorithm InfillType
    {
        get => _infillType;
        set => RaiseAndSetIfChanged(ref _infillType, value);
    }

    public ushort WallThickness
    {
        get => _wallThickness;
        set => RaiseAndSetIfChanged(ref _wallThickness, value);
    }

    public byte InfillBrightness
    {
        get => _infillBrightness;
        set => RaiseAndSetIfChanged(ref _infillBrightness, value);
    }

    public ushort InfillThickness
    {
        get => _infillThickness;
        set => RaiseAndSetIfChanged(ref _infillThickness, value);
    }

    public ushort InfillSpacing
    {
        get => _infillSpacing;
        set => RaiseAndSetIfChanged(ref _infillSpacing, value);
    }

    public bool ReinforceInfill
    {
        get => _reinforceInfill;
        set => RaiseAndSetIfChanged(ref _reinforceInfill, value);
    }

    public override string ToString()
    {
        var result = $"[{_infillType}] [Wall: {_wallThickness}px] [B: {_infillBrightness}px] [T: {_infillThickness}px] [S: {_infillSpacing}px] [R: {_reinforceInfill}]" + LayerRangeString;
        if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
        return result;
    }

    #endregion

    #region Constructor

    public OperationInfill() { }

    public OperationInfill(FileFormat slicerFile) : base(slicerFile) { }

    #endregion

    #region Equality

    private bool Equals(OperationInfill other)
    {
        return _infillType == other._infillType && _wallThickness == other._wallThickness && _infillThickness == other._infillThickness && _infillSpacing == other._infillSpacing && _infillBrightness == other._infillBrightness && _reinforceInfill == other._reinforceInfill;
    }

    public override bool Equals(object? obj)
    {
        return ReferenceEquals(this, obj) || obj is OperationInfill other && Equals(other);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine((int) _infillType, _wallThickness, _infillThickness, _infillSpacing, _infillBrightness, _reinforceInfill);
    }

    #endregion

    #region Methods

    protected override bool ExecuteInternally(OperationProgress progress)
    {
        Mat? mask = null;
        if (_infillType == InfillAlgorithm.Honeycomb)
        {
            mask = GetHoneycombMask(GetRoiSizeOrVolumeSize());
        }
        else if (_infillType == InfillAlgorithm.Concentric)
        {
            mask = GetConcentricMask(GetRoiSizeOrVolumeSize());
        }

        Parallel.For(LayerIndexStart, LayerIndexEnd + 1, CoreSettings.GetParallelOptions(progress), layerIndex =>
        {
            using var mat = SlicerFile[layerIndex].LayerMat;
            Execute(mat, layerIndex, mask!);
            SlicerFile[layerIndex].LayerMat = mat;

            progress.LockAndIncrement();
        });
        mask?.Dispose();
        return !progress.Token.IsCancellationRequested;
    }

    public override bool Execute(Mat mat, params object[]? arguments)
    {
        if (arguments is null || arguments.Length < 1) return false;

        var kernel = EmguExtensions.Kernel3x3Rectangle;
        uint index = Convert.ToUInt32(arguments[0]);
        uint layerIndex = index - LayerIndexStart;
        var infillColor = new MCvScalar(_infillBrightness);

        Mat? patternMask = null;
        using Mat erode = new ();
        using Mat diff = new ();
        var target = GetRoiOrVolumeBounds(mat);
        using var mask = GetMask(mat);
        bool disposeTargetMask = true;
             
        if (_infillType is InfillAlgorithm.Pillars 
            or InfillAlgorithm.CubicCross 
            or InfillAlgorithm.CubicCrossAlternating 
            or InfillAlgorithm.CubicStar)
        {
            using var infillPattern = EmguExtensions.InitMat(new Size(_infillSpacing, _infillSpacing));
            using var matPattern = mat.NewBlank();
            bool firstPattern = true;
            uint accumulator = 0;
            bool dynamicCenter = false;
            while (accumulator < layerIndex)
            {
                dynamicCenter = !dynamicCenter;
                firstPattern = true;
                accumulator += _infillSpacing;

                if (accumulator >= layerIndex) break;

                if (_reinforceInfill)
                {
                    firstPattern = false;
                    accumulator += _infillThickness;
                }
            }

            if (firstPattern)
            {
                int thickness = _infillThickness / 2;
                // Top Left
                CvInvoke.Rectangle(infillPattern,
                    new Rectangle(0, 0, thickness, thickness),
                    infillColor, -1);

                // Top Right
                CvInvoke.Rectangle(infillPattern,
                    new Rectangle(infillPattern.Width - thickness, 0, thickness, thickness),
                    infillColor, -1);

                // Bottom Left
                CvInvoke.Rectangle(infillPattern,
                    new Rectangle(0, infillPattern.Height - thickness, thickness, thickness),
                    infillColor, -1);

                // Bottom Right
                CvInvoke.Rectangle(infillPattern,
                    new Rectangle(infillPattern.Width - thickness, infillPattern.Height - thickness,
                        thickness, thickness),
                    infillColor, -1);

                // Center cross
                int margin = (int) (InfillSpacing - accumulator + layerIndex) - thickness;
                int marginInv = (int) (accumulator - layerIndex) - thickness;

                if (_infillType == InfillAlgorithm.CubicCross ||
                    (_infillType == InfillAlgorithm.CubicCrossAlternating &&
                     dynamicCenter) ||
                    _infillType == InfillAlgorithm.CubicStar)
                {

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(margin, margin, _infillThickness, _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(marginInv, marginInv, _infillThickness,
                            _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(margin, marginInv, _infillThickness,
                            _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(marginInv, margin, _infillThickness,
                            _infillThickness),
                        infillColor, -1);
                }


                if (_infillType == InfillAlgorithm.CubicStar ||
                    (_infillType == InfillAlgorithm.CubicCrossAlternating &&
                     !dynamicCenter))
                {
                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(margin, -thickness, _infillThickness,
                            _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(marginInv, -thickness, _infillThickness,
                            _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(-thickness, margin, _infillThickness,
                            _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(-thickness, marginInv, _infillThickness,
                            _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(InfillSpacing - thickness, margin,
                            _infillThickness, _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(InfillSpacing - thickness, marginInv,
                            _infillThickness, _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(margin, InfillSpacing - thickness,
                            _infillThickness, _infillThickness),
                        infillColor, -1);

                    CvInvoke.Rectangle(infillPattern,
                        new Rectangle(marginInv, InfillSpacing - thickness,
                            _infillThickness, _infillThickness),
                        infillColor, -1);
                }
            }
            else
            {
                CvInvoke.Rectangle(infillPattern,
                    new Rectangle(0, 0, _infillSpacing, _infillSpacing),
                    infillColor, _infillThickness);
            }


            CvInvoke.Repeat(infillPattern, target.Rows / infillPattern.Rows + 1,
                target.Cols / infillPattern.Cols + 1, matPattern);
            patternMask = matPattern.Roi(target);
            disposeTargetMask = true;
        }
        else if (_infillType == InfillAlgorithm.Honeycomb)
        {
            if (arguments.Length >= 2)
            {
                patternMask = (Mat)arguments[1];
                disposeTargetMask = false;
            }
            else
            {
                patternMask = GetHoneycombMask(target.Size);
                disposeTargetMask = true;
            }
        }
        else if (_infillType == InfillAlgorithm.Concentric)
        {
            if (arguments.Length >= 2)
            {
                patternMask = (Mat)arguments[1];
                disposeTargetMask = false;
            }
            else
            {
                patternMask = GetConcentricMask(target.Size);
                disposeTargetMask = true;
            }
        }
        else if (_infillType == InfillAlgorithm.Waves)
        {
            var sineHeight = 100;
            var sineWidth = 100;
            var radius = (ushort)(_infillThickness / 2);

            var points = new List<Point>();

            bool isHorizontal = true;
            float accumulator = 0;
            for (int i = 0; i <= layerIndex; i++)
            {
                accumulator += SlicerFile[index].RelativePositionZ;
                if (accumulator >= 2)
                {
                    isHorizontal = !isHorizontal;
                    accumulator = 0;
                }
            }

            //using var infillPattern = EmguExtensions.InitMat(new Size(_infillSpacing, _infillSpacing));
            //using var matPattern = new Mat();
            using var infillPattern = mat.NewBlank();

            int maxY = 0;

            if (isHorizontal)
            {
                for (int x = 0; x < mat.Width; x += radius)
                {
                    int y = (int) (Math.Sin((double) x / sineWidth /*+ sineWidth * layerIndex*/) * sineHeight / 2.0 +
                                   sineHeight / 2.0 + radius);
                    points.Add(new Point(x, y));
                    maxY = Math.Max(maxY, y);
                }
                var infillPatternRoi = infillPattern.Roi(new Size(infillPattern.Width, maxY + radius + 2 + _infillSpacing));
                CvInvoke.Polylines(infillPatternRoi, points.ToArray(), false, infillColor, _infillThickness);

                CvInvoke.Repeat(infillPatternRoi, target.Rows / infillPatternRoi.Rows + 1, 1, infillPattern);
            }
            else
            {
                for (int y = 0; y < mat.Height; y += radius)
                {
                    int x = (int)(Math.Sin((double)y / sineWidth /*+ sineWidth * layerIndex*/) * sineHeight / 2.0 +
                                  sineHeight / 2.0 + radius);
                    points.Add(new Point(x, y));
                    maxY = Math.Max(maxY, x);
                }
                var infillPatternRoi = infillPattern.Roi(new Size(maxY + radius + 2 + _infillSpacing, infillPattern.Height));
                CvInvoke.Polylines(infillPatternRoi, points.ToArray(), false, infillColor, _infillThickness);
                CvInvoke.Repeat(infillPatternRoi, 1, target.Cols / infillPatternRoi.Cols + 1, infillPattern);
                
            }
            points.Clear();

            patternMask = infillPattern.Roi(target);
            disposeTargetMask = true;
        }
        else if (_infillType == InfillAlgorithm.Gyroid)
        {
            patternMask = target.NewBlank();

            var scaleRatio = 0.0012 / (_infillSpacing + _infillThickness / 2);
            //var scaleX = 0.04 * _infillSpacing * Math.PI / target.Width;
            //var scaleY = 0.04 * _infillSpacing * Math.PI / target.Height;
            var scaleX = scaleRatio * mat.Width;
            var scaleY = scaleRatio * mat.Height;
            
            //const double scaleZ = 2.0 * Math.PI;
            //var dz = 2.0 * scaleZ / LayerRangeCount; // z step
            //var zz = 0.05 * (SlicerFile[index].LayerHeight / 0.05f) * (layerIndex + 1);
            float zz = 0;
            for (var i = LayerIndexStart; i <= index; i++)
            {
                zz += SlicerFile[i].RelativePositionZ;
            }

            for (int y = 0; y < patternMask.Height; y++)
            {
                var span = patternMask.GetRowSpan<byte>(y);
                var yy = y * scaleY; // y position of pixel
                for (int x = 0; x < patternMask.Width; x++)
                {
                    var xx = x * scaleX; // x position of pixel                

                    var d = Math.Sin(xx) * Math.Cos(yy) // compute gyroid equation
                            + Math.Sin(yy) * Math.Cos(zz)
                            + Math.Sin(zz) * Math.Cos(xx);
                    //if (d > 1e-6) continue; // Far from surface
                    if (Math.Abs(d) - 0.006*_infillThickness > 0) continue;
                    //if (d - 0.05 > 1e-6) continue;

                    span[x] = _infillBrightness;
                }
            }


            //using var contours = patternMask.FindContours();
            //CvInvoke.DrawContours(patternMask, contours, -1, infillColor, _infillThickness);

            disposeTargetMask = true;
        }


        //patternMask.Save("D:\\pattern.png");
        CvInvoke.Erode(target, erode, kernel, EmguExtensions.AnchorCenter, WallThickness, BorderType.Reflect101,
            default);
        CvInvoke.Subtract(target, erode, diff);

        CvInvoke.BitwiseAnd(erode, patternMask, target, mask);
        CvInvoke.Add(target, diff, target, mask);

        if (disposeTargetMask)
        {
            patternMask!.Dispose();
        }

        return true;
    }

    public Mat GetHoneycombMask(Size targetSize)
    {
        var patternMask = EmguExtensions.InitMat(targetSize);

        var halfInfillSpacing = _infillSpacing / 2;
        var halfThickenss = _infillThickness / 2;
        int width = (int)Math.Round(4 * (_infillSpacing / 2.0 / Math.Sqrt(3)));
        var infillColor = new MCvScalar(_infillBrightness);

        for (int col = 0; col <= targetSize.Width / _infillSpacing; col++)
        {
            for (int row = 0; row <= targetSize.Height / _infillSpacing; row++)
            {
                // Move over for the column number.
                int x = (int)Math.Round(col * (width * 0.75f));

                // Move down the required number of rows.
                int y = row * _infillSpacing;

                // If the column is odd, move down half a hex more.
                if (col % 2 == 1) y += halfInfillSpacing;

                var points = new Point[]
                {
                    new(x, y),
                    new((int) Math.Round(x + width * 0.25f), y - _infillSpacing / 2),
                    new((int) Math.Round(x + width * 0.75f), y - _infillSpacing / 2),
                    new(x + width, y),
                    new((int) Math.Round(x + width * 0.75f), y + _infillSpacing / 2),
                    new((int) Math.Round(x + width * 0.25f), y + _infillSpacing / 2),
                };

                CvInvoke.Polylines(patternMask, points, true, infillColor, _infillThickness);
            }
        }

        return patternMask;
    }

    public Mat GetConcentricMask(Size targetSize)
    {
        var patternMask = EmguExtensions.InitMat(targetSize);

        //var halfInfillSpacing = _infillSpacing / 2;
        //var halfThickenss = _infillThickness / 2;
        int multiplicator = 1;
        byte position = 0;

        int x = patternMask.Width / 2;
        int y = patternMask.Height / 2;

        Point[] directions = {
            new(0, -_infillSpacing), // top
            new(_infillSpacing, 0), // right
            new(0, _infillSpacing), // bottom
            new(-_infillSpacing, 0), // left
        };

        bool[] hitLimits =
        {
            false,
            false,
            false,
            false
        };

        var points = new List<Point> {new(x, y)};

        while (hitLimits.Any(hitLimit => !hitLimit))
        {
            x += directions[position].X * multiplicator;
            y += directions[position].Y * multiplicator;
            if (x < 0 || y < 0 || x >= patternMask.Width || y >= patternMask.Height) hitLimits[position] = true;
            points.Add(new Point(x, y));
            position++;
            if (position == 2)
            {
                multiplicator++;
            }
            else if (position == 4)
            {
                multiplicator++;
                position = 0;
            }
        }
        

        CvInvoke.Polylines(patternMask, points.ToArray(), false, new MCvScalar(_infillBrightness), _infillThickness);

        return patternMask;
    }

    #endregion
}