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

PhotonSFile.cs « FileFormats « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d881a4f3bc42566e452790f10f7a0ed79f05711c (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
/*
 *                     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.
 */

// https://github.com/cbiffle/catibo/blob/master/doc/cbddlp-ctb.adoc

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using BinarySerialization;
using Emgu.CV;
using Emgu.CV.CvEnum;
using UVtools.Core.Extensions;
using UVtools.Core.Operations;

namespace UVtools.Core.FileFormats
{
    public class PhotonSFile : FileFormat
    {
        public const byte RLEEncodingLimit = 0x7f - 2; // 128;

        #region Sub Classes

        #region Header

        public class Header
        {
            public const uint ResolutionX = 1440;
            public const uint ResolutionY = 2560;

            public const float DisplayWidth = 68.04f;
            public const float DisplayHeight = 120.96f;
            public const float BuildZ = 150f;

            public const uint TAG1 = 2;
            public const ushort TAG2 = 49;


            [FieldOrder(0)] [FieldEndianness(Endianness.Big)] public uint Tag1 { get; set; } = TAG1; // 2
            [FieldOrder(1)] [FieldEndianness(Endianness.Big)] public ushort Tag2 { get; set; } = TAG2; // 49
            [FieldOrder(2)] [FieldEndianness(Endianness.Big)] public double XYPixelSize { get; set; } = 0.04725; // 0.04725
            [FieldOrder(3)] [FieldEndianness(Endianness.Big)] public double LayerHeight { get; set; }
            [FieldOrder(4)] [FieldEndianness(Endianness.Big)] public double ExposureSeconds { get; set; }
            [FieldOrder(5)] [FieldEndianness(Endianness.Big)] public double LightOffDelay { get; set; }
            [FieldOrder(6)] [FieldEndianness(Endianness.Big)] public double BottomExposureSeconds { get; set; }
            [FieldOrder(7)] [FieldEndianness(Endianness.Big)] public uint BottomLayerCount { get; set; }
            [FieldOrder(8)] [FieldEndianness(Endianness.Big)] public double LiftHeight { get; set; } // mm
            [FieldOrder(9)] [FieldEndianness(Endianness.Big)] public double LiftSpeed { get; set; } // mm/s
            [FieldOrder(10)] [FieldEndianness(Endianness.Big)] public double RetractSpeed { get; set; } // mm/s
            [FieldOrder(11)] [FieldEndianness(Endianness.Big)] public double VolumeMl { get; set; } // ml
            [FieldOrder(12)] [FieldEndianness(Endianness.Big)] public uint PreviewResolutionX { get; set; } = 225;
            [FieldOrder(13)] [FieldEndianness(Endianness.Big)] public uint Unknown2 { get; set; } = 42;
            [FieldOrder(14)] [FieldEndianness(Endianness.Big)] public uint PreviewResolutionY { get; set; } = 168;
            [FieldOrder(15)] [FieldEndianness(Endianness.Big)] public uint Unknown4 { get; set; } = 10;

            public override string ToString()
            {
                return $"{nameof(Tag1)}: {Tag1}, {nameof(Tag2)}: {Tag2}, {nameof(XYPixelSize)}: {XYPixelSize}, {nameof(LayerHeight)}: {LayerHeight}, {nameof(ExposureSeconds)}: {ExposureSeconds}, {nameof(LightOffDelay)}: {LightOffDelay}, {nameof(BottomExposureSeconds)}: {BottomExposureSeconds}, {nameof(BottomLayerCount)}: {BottomLayerCount}, {nameof(LiftHeight)}: {LiftHeight}, {nameof(LiftSpeed)}: {LiftSpeed}, {nameof(RetractSpeed)}: {RetractSpeed}, {nameof(VolumeMl)}: {VolumeMl}, {nameof(PreviewResolutionX)}: {PreviewResolutionX}, {nameof(Unknown2)}: {Unknown2}, {nameof(PreviewResolutionY)}: {PreviewResolutionY}, {nameof(Unknown4)}: {Unknown4}";
            }
        }

        public class LayerHeader
        {
            [FieldOrder(0)] [FieldEndianness(Endianness.Big)] public uint LayerCount { get; set; }

            public override string ToString()
            {
                return $"{nameof(LayerCount)}: {LayerCount}";
            }
        }

        #endregion

        #region LayerDef

        public class LayerData
        {
            [FieldOrder(0)] [FieldEndianness(Endianness.Big)] public uint Unknown1 { get; set; } = 44944;
            [FieldOrder(1)] [FieldEndianness(Endianness.Big)] public uint Unknown2 { get; set; } = 0;
            [FieldOrder(2)] [FieldEndianness(Endianness.Big)] public uint Unknown3 { get; set; } = 0;
            [FieldOrder(3)] [FieldEndianness(Endianness.Big)] public uint ResolutionX { get; set; } = 1440;
            [FieldOrder(4)] [FieldEndianness(Endianness.Big)] public uint ResolutionY { get; set; } = 2560;
            [FieldOrder(5)] [FieldEndianness(Endianness.Big)] public uint DataSize { get; set; }
            [Ignore] public uint RleDataSize => (DataSize >> 3) - 4;
            [FieldOrder(6)] [FieldEndianness(Endianness.Big)] public uint Unknown5 { get; set; } = 2684702720;

            [Ignore] public byte[] EncodedRle { get; set; }

            public override string ToString()
            {
                return $"{nameof(Unknown1)}: {Unknown1}, {nameof(Unknown2)}: {Unknown2}, {nameof(Unknown3)}: {Unknown3}, {nameof(ResolutionX)}: {ResolutionX}, {nameof(ResolutionY)}: {ResolutionY}, {nameof(DataSize)}: {DataSize}, {nameof(RleDataSize)}: {RleDataSize}, {nameof(Unknown5)}: {Unknown5}, {nameof(EncodedRle)}: {EncodedRle.Length}";
            }

            public unsafe byte[] Encode(Mat mat)
            {
                List<byte> rawData = new List<byte>();
                var spanMat = mat.GetBytePointer();
                var imageLength = mat.GetLength();

                int rep = 0;
                byte color = 0;

                void AddRep()
                {
                    if (rep <= 0) return;
                    rep--;
                    byte rle = 
                        (byte) (((rep & 1) > 0 ? 128 : 0) |
                                ((rep & 2) > 0 ? 64 : 0) |
                                ((rep & 4) > 0 ? 32 : 0) |
                                ((rep & 8) > 0 ? 16 : 0) |
                                ((rep & 16) > 0 ? 8 : 0) |
                                ((rep & 32) > 0 ? 4 : 0) |
                                ((rep & 64) > 0 ? 2 : 0) | color);

                    rawData.Add(rle);
                }

                for (int i = 0; i < imageLength; i++)
                {
                    //color = color <= 127 ? 0 : 255; // Sanitize no AA
                    byte thisColor = spanMat[i] <= 127 ? byte.MinValue : byte.MaxValue; // Sanitize no AA
                    if (thisColor != color)
                    {
                        AddRep();
                        color = thisColor; // Sanitize no AA
                        rep = 1;
                    }
                    else
                    {
                        rep++;
                        if (rep == RLEEncodingLimit)
                        {
                            AddRep();
                            rep = 0;
                        }
                    }
                }

                AddRep();

                EncodedRle = rawData.ToArray();
                DataSize = (uint)(EncodedRle.Length * 8 + 4);
                return EncodedRle;
            }

            public unsafe Mat Decode(bool consumeRle = true)
            {
                var mat = EmguExtensions.InitMat(new Size((int) ResolutionX, (int) ResolutionY));
                var matSpan = mat.GetBytePointer();
                var imageLength = mat.GetLength();

                int pixel = 0;
                foreach (var run in EncodedRle)
                {
                    byte col = (byte) ((run & 0x01) * 255);

                    var numPixelsInRun =
                        (((run & 128) > 0 ? 1 : 0) |
                         ((run & 64) > 0 ? 2 : 0) |
                         ((run & 32) > 0 ? 4 : 0) |
                         ((run & 16) > 0 ? 8 : 0) |
                         ((run &  8) > 0 ? 16 : 0) |
                         ((run &  4) > 0 ? 32 : 0) |
                         ((run &  2) > 0 ? 64 : 0)) + 1;
                    
                    for (; numPixelsInRun > 0; numPixelsInRun--)
                    {
                        if (pixel > imageLength)
                        {
                            mat.Dispose();
                            throw new FileLoadException($"Error image ran off the end, expecting {imageLength} pixels");
                        }
                        matSpan[pixel++] = col;
                    }
                }

                // Not required as mat is all black by default
                //for (;pixel < imageLength; pixel++) matSpan[pixel] = 0;

                if (consumeRle)
                    EncodedRle = null;

                return mat;
            }
        }
        #endregion

        #endregion

        #region Properties

        public Header HeaderSettings { get; protected internal set; } = new Header();
        public LayerHeader LayerSettings { get; protected internal set; } = new LayerHeader();
        public override FileFormatType FileType => FileFormatType.Binary;

        public override FileExtension[] FileExtensions { get; } = {
            new("photons", "Chitubox PhotonS"),
        };

        public override PrintParameterModifier[] PrintParameterModifiers { get; } =
        {
            PrintParameterModifier.BottomLayerCount,
            PrintParameterModifier.BottomExposureSeconds,
            PrintParameterModifier.ExposureSeconds,

            //PrintParameterModifier.BottomLightOffDelay,
            PrintParameterModifier.LightOffDelay,
            //PrintParameterModifier.BottomLiftHeight,
            //PrintParameterModifier.BottomLiftSpeed,
            PrintParameterModifier.LiftHeight,
            PrintParameterModifier.LiftSpeed,
            PrintParameterModifier.RetractSpeed,
        };

        public override byte ThumbnailsCount { get; } = 1;

        public override Size[] ThumbnailsOriginalSize { get; } = {new Size(225, 168) };

        public override uint ResolutionX
        {
            get => Header.ResolutionX;
            set { }
        }

        public override uint ResolutionY
        {
            get => Header.ResolutionY;
            set { }
        }

        public override float DisplayWidth
        {
            get => Header.DisplayWidth;
            set { }
        }

        public override float DisplayHeight
        {
            get => Header.DisplayHeight;
            set { }
        }

        public override bool MirrorDisplay
        {
            get => true;
            set { }
        }

        public override byte AntiAliasing
        {
            get => 1;
            set { }
        }

        public override float LayerHeight
        {
            get => (float) Math.Round(HeaderSettings.LayerHeight);
            set
            {
                HeaderSettings.LayerHeight = Layer.RoundHeight(value);
                RaisePropertyChanged();
            }
        }

        public override uint LayerCount
        {
            get => base.LayerCount;
            set => base.LayerCount = LayerSettings.LayerCount = LayerCount;
        }

        public override ushort BottomLayerCount
        {
            get => (ushort) HeaderSettings.BottomLayerCount;
            set => base.BottomLayerCount = (ushort) (HeaderSettings.BottomLayerCount = value);
        }

        public override float BottomExposureTime
        {
            get => (float) HeaderSettings.BottomExposureSeconds;
            set => base.BottomExposureTime = (float) (HeaderSettings.BottomExposureSeconds = value);
        }

        public override float ExposureTime
        {
            get => (float) HeaderSettings.ExposureSeconds;
            set => base.ExposureTime = (float) (HeaderSettings.ExposureSeconds = Math.Round(value, 2));
        }

        public override float BottomLiftHeight => LightOffDelay;
        
        public override float LiftHeight
        {
            get => (float) HeaderSettings.LiftHeight;
            set => base.LiftHeight = (float) (HeaderSettings.LiftHeight = Math.Round(value, 2));
        }

        public override float BottomLiftSpeed => LiftSpeed;

        public override float LiftSpeed
        {
            get => (float) Math.Round(HeaderSettings.LiftSpeed * 60.0, 2);
            set
            {
                HeaderSettings.LiftSpeed = Math.Round(value / 60.0, 2);
                base.LiftSpeed = value;
            }
        }

        public override float RetractSpeed
        {
            get => (float)Math.Round(HeaderSettings.RetractSpeed * 60.0, 2);
            set
            {
                HeaderSettings.RetractSpeed = (float) Math.Round(value / 60.0, 2);
                base.RetractSpeed = value;
            }
        }

        public override float BottomLightOffDelay => LightOffDelay;

        public override float LightOffDelay
        {
            get => (float)HeaderSettings.LightOffDelay;
            set => base.LightOffDelay = (float)(HeaderSettings.LightOffDelay = Math.Round(value, 2));
        }

        
        public override float MaterialMilliliters
        {
            get => base.MaterialMilliliters;
            set
            {
                base.MaterialMilliliters = value;
                HeaderSettings.VolumeMl = base.MaterialMilliliters;
            }
        }

        public override string MachineName => "Anycubic Photon S";
        
        public override object[] Configs => new object[] { HeaderSettings };

        #endregion

        #region Constructors
        public PhotonSFile()
        {
        }
        #endregion

        #region Methods

        public unsafe byte[] PreviewEncode(Mat mat)
        {
            byte[] bytes = new byte[mat.Width * mat.Height * 2];
            var span = mat.GetBytePointer();
            var imageLength = mat.GetLength();

            int index = 0;
            for (int i = 0; i < imageLength; i+=3)
            {
                byte b = span[i];
                byte g = span[i+1];
                byte r = span[i+2];

                ushort rgb15 = (ushort) (((r >> 3) << 11) | ((g >> 3) << 6) | ((b >> 3) << 0));

                bytes[index++] = (byte) (rgb15 >> 8);
                bytes[index++] = (byte) (rgb15 & 0xff);
            }

            if (index != bytes.Length)
            {
                throw new FileLoadException($"Preview encode incomplete encode, expected: {bytes.Length}, encoded: {index}");
            }

            return bytes;
        }

        protected override void EncodeInternally(string fileFullPath, OperationProgress progress)
        {
            throw new NotSupportedException("PhotonS is read-only format, please use pws instead!");
            //uint currentOffset = (uint)Helpers.Serializer.SizeOf(HeaderSettings);
            using (var outputFile = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write))
            {
                outputFile.WriteSerialize(HeaderSettings);
                outputFile.WriteBytes(PreviewEncode(Thumbnails[0]));
                LayerSettings.LayerCount = LayerCount;
                outputFile.WriteSerialize(LayerSettings);

                LayerData[] layerData = new LayerData[LayerCount];

                Parallel.For(0, LayerCount, layerIndex =>
                {
                    if (progress.Token.IsCancellationRequested) return;
                    using (var mat = this[layerIndex].LayerMat)
                    {
                        layerData[layerIndex] = new LayerData();
                        layerData[layerIndex].Encode(mat);
                    }

                    progress.LockAndIncrement();
                });

                progress.ItemName = "Saving layers";
                progress.ProcessedItems = 0;

                for (uint layerIndex = 0; layerIndex < LayerCount; layerIndex++)
                {
                    progress.Token.ThrowIfCancellationRequested();
                    outputFile.WriteSerialize(layerData[layerIndex]);
                    outputFile.WriteBytes(layerData[layerIndex].EncodedRle);
                    progress++;
                }
            }

            Debug.WriteLine("Encode Results:");
            Debug.WriteLine(HeaderSettings);
            Debug.WriteLine("-End-");
        }

        public unsafe Mat PreviewDecode(byte []data)
        {
            Mat mat = new Mat((int) HeaderSettings.PreviewResolutionX, (int)HeaderSettings.PreviewResolutionY, DepthType.Cv8U, 3);
            var span = mat.GetBytePointer();
            int spanIndex = 0;
            for (int i = 0; i < data.Length; i+=2)
            {
                ushort color16 = (ushort)(data[i] + (data[i + 1] << 8));

                var r = (color16 >> 11) & 0x1F;
                var g = (color16 >> 5) & 0x3F;
                var b = (color16 >> 0) & 0x1F;

                /*span[spanIndex++] = (byte)(b << 3);
                span[spanIndex++] = (byte)(g << 2);
                span[spanIndex++] = (byte)(r << 3);*/

                span[spanIndex++] = (byte)((b << 3) | (b & 0x7));
                span[spanIndex++] = (byte)((g << 2) | (g & 0x3));
                span[spanIndex++] = (byte)((r << 3) | (r & 0x7));
            }

            return mat;
        }

        protected override void DecodeInternally(string fileFullPath, OperationProgress progress)
        {
            using (var inputFile = new FileStream(fileFullPath, FileMode.Open, FileAccess.Read))
            {
                HeaderSettings = Helpers.Deserialize<Header>(inputFile);
                if (HeaderSettings.Tag1 != Header.TAG1 || HeaderSettings.Tag2 != Header.TAG2)
                {
                    throw new FileLoadException("Not a valid PHOTONS file! TAGs doesn't match", fileFullPath);
                }

                int previewSize = (int) (HeaderSettings.PreviewResolutionX * HeaderSettings.PreviewResolutionY * 2);
                byte[] previewData = new byte[previewSize];


                uint currentOffset = (uint) Helpers.Serializer.SizeOf(HeaderSettings);
                currentOffset += inputFile.ReadBytes(previewData);
                Thumbnails[0] = PreviewDecode(previewData);

                LayerSettings = Helpers.Deserialize<LayerHeader>(inputFile);
                currentOffset += (uint)Helpers.Serializer.SizeOf(LayerSettings);

                Debug.WriteLine(HeaderSettings);
                Debug.WriteLine(LayerSettings);
  

                LayerData[] layerData = new LayerData[LayerSettings.LayerCount];
                progress.Reset(OperationProgress.StatusGatherLayers, LayerSettings.LayerCount);

                for (int layerIndex = 0; layerIndex < LayerSettings.LayerCount; layerIndex++)
                {
                    progress.Token.ThrowIfCancellationRequested();
                    layerData[layerIndex] = Helpers.Deserialize<LayerData>(inputFile);
                    layerData[layerIndex].EncodedRle = new byte[layerData[layerIndex].RleDataSize];
                    currentOffset += inputFile.ReadBytes(layerData[layerIndex].EncodedRle);
                    Debug.WriteLine($"Layer {layerIndex} -> {layerData[layerIndex]}");
                }

                LayerManager.Init(LayerSettings.LayerCount);
                progress.Reset(OperationProgress.StatusDecodeLayers, LayerCount);

                Parallel.For(0, LayerCount, 
                    //new ParallelOptions{MaxDegreeOfParallelism = 1},
                    layerIndex =>
                {
                    if (progress.Token.IsCancellationRequested) return;

                    using var image = layerData[layerIndex].Decode();
                    this[layerIndex] = new Layer((uint) layerIndex, image, LayerManager);
                    progress.LockAndIncrement();
                });

                LayerManager.RebuildLayersProperties();
            }
        }

        public override void SaveAs(string filePath = null, OperationProgress progress = null)
        {
            if (RequireFullEncode)
            {
                if (!string.IsNullOrEmpty(filePath))
                {
                    FileFullPath = filePath;
                }
                Encode(FileFullPath, progress);
                return;
            }


            if (!string.IsNullOrEmpty(filePath))
            {
                File.Copy(FileFullPath, filePath, true);
                FileFullPath = filePath;
            }

            using (var outputFile = new FileStream(FileFullPath, FileMode.Open, FileAccess.Write))
            {

                outputFile.Seek(0, SeekOrigin.Begin);
                Helpers.SerializeWriteFileStream(outputFile, HeaderSettings);
            }
        }

        #endregion
    }
}