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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
|
/*
* 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/sn4k3/UVtools/blob/master/Documentation/osla.md
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using BinarySerialization;
using UVtools.Core.Extensions;
using UVtools.Core.GCode;
using UVtools.Core.Layers;
using UVtools.Core.Operations;
namespace UVtools.Core.FileFormats
{
public class OSLAFile : FileFormat
{
#region Constants
public const string MARKER = "OSLATiCo";
#endregion
#region Sub Classes
#region Header
public class FileDef
{
[FieldOrder(0)]
[FieldLength(8)]
public string Marker { get; set; } = MARKER;
[FieldOrder(1)]
public ushort Version { get; set; } = 0;
[FieldOrder(2)]
[FieldLength(20)]
public string CreatedDateTime { get; set; } = DateTime.UtcNow.ToString("u");
[FieldOrder(3)]
[FieldLength(50)]
[SerializeAs(SerializedType.TerminatedString)]
public string CreatedBy { get; set; } = About.SoftwareWithVersion;
[FieldOrder(4)]
[FieldLength(20)]
public string ModifiedDateTime { get; set; } = DateTime.UtcNow.ToString("u");
[FieldOrder(5)]
[FieldLength(50)]
[SerializeAs(SerializedType.TerminatedString)]
public string ModifiedBy { get; set; } = About.SoftwareWithVersion;
public override string ToString()
{
return $"{nameof(Marker)}: {Marker}, {nameof(Version)}: {Version}, {nameof(CreatedDateTime)}: {CreatedDateTime}, {nameof(CreatedBy)}: {CreatedBy}, {nameof(ModifiedDateTime)}: {ModifiedDateTime}, {nameof(ModifiedBy)}: {ModifiedBy}";
}
public void Update()
{
ModifiedDateTime= DateTime.UtcNow.ToString("u");
ModifiedBy = About.SoftwareWithVersion;;
}
public void Validate()
{
if (Marker != MARKER)
{
throw new FileLoadException($"Invalid marker: {Marker}, not a valid OSLA file.");
}
}
}
public class Header
{
[FieldOrder(0)] public uint TableSize { get; set; }
[FieldOrder(1)] public uint ResolutionX { get; set; }
[FieldOrder(2)] public uint ResolutionY { get; set; }
[FieldOrder(3)] public float MachineZ { get; set; }
[FieldOrder(4)] public float DisplayWidth { get; set; }
[FieldOrder(5)] public float DisplayHeight { get; set; }
[FieldOrder(6)] public byte DisplayMirror { get; set; } // 0 = No mirror | 1 = Horizontally | 2 = Vertically | 3 = Horizontally+Vertically | >3 = No mirror
[FieldOrder(7)] [FieldLength(16)] [SerializeAs(SerializedType.TerminatedString)] public string PreviewDataType { get; set; } = "RGB565";
[FieldOrder(8)] [FieldLength(16)] [SerializeAs(SerializedType.TerminatedString)] public string LayerDataType { get; set; } = "PNG";
[FieldOrder(9)] public uint PreviewTableSize { get; set; } = 8;
[FieldOrder(10)] public uint PreviewCount { get; set; }
[FieldOrder(11)] public float LayerHeight { get; set; } = 0.05f;
[FieldOrder(12)] public ushort BottomLayersCount { get; set; } = 4;
[FieldOrder(13)] public uint LayerCount { get; set; }
[FieldOrder(14)] public uint LayerTableSize { get; set; } = 69;
[FieldOrder(15)] public uint LayerDefinitionsAddress { get; set; }
[FieldOrder(16)] public uint GCodeAddress { get; set; }
[FieldOrder(17)] public uint PrintTime { get; set; }
[FieldOrder(18)] public float MaterialMilliliters { get; set; }
[FieldOrder(19)] public float MaterialCost { get; set; }
[FieldOrder(20)] [FieldLength(50)] [SerializeAs(SerializedType.TerminatedString)] public string MaterialName { get; set; }
[FieldOrder(21)] [FieldLength(50)] [SerializeAs(SerializedType.TerminatedString)] public string MachineName { get; set; } = "Unknown";
public override string ToString()
{
return $"{nameof(TableSize)}: {TableSize}, {nameof(ResolutionX)}: {ResolutionX}, {nameof(ResolutionY)}: {ResolutionY}, {nameof(MachineZ)}: {MachineZ}, {nameof(DisplayWidth)}: {DisplayWidth}, {nameof(DisplayHeight)}: {DisplayHeight}, {nameof(DisplayMirror)}: {DisplayMirror}, {nameof(PreviewDataType)}: {PreviewDataType}, {nameof(LayerDataType)}: {LayerDataType}, {nameof(PreviewTableSize)}: {PreviewTableSize}, {nameof(PreviewCount)}: {PreviewCount}, {nameof(LayerTableSize)}: {LayerTableSize}, {nameof(BottomLayersCount)}: {BottomLayersCount}, {nameof(LayerCount)}: {LayerCount}, {nameof(LayerDefinitionsAddress)}: {LayerDefinitionsAddress}, {nameof(GCodeAddress)}: {GCodeAddress}, {nameof(PrintTime)}: {PrintTime}, {nameof(MaterialMilliliters)}: {MaterialMilliliters}, {nameof(MaterialCost)}: {MaterialCost}, {nameof(MaterialName)}: {MaterialName}, {nameof(MachineName)}: {MachineName}";
}
}
#endregion
#region Custom Table
public class CustomTable
{
[FieldOrder(0)] public uint TableSize { get; set; }
[FieldOrder(1)] [FieldCount(nameof(TableSize))] public byte[] Bytes { get; set; } = Array.Empty<byte>();
public override string ToString()
{
return $"{nameof(TableSize)}: {TableSize}, {nameof(Bytes)}: {Bytes.Length}";
}
}
#endregion
#region Preview
public class Preview
{
/// <summary>
/// Gets the X dimension of the preview image, in pixels.
/// </summary>
[FieldOrder(0)] public ushort ResolutionX { get; set; }
/// <summary>
/// Gets the Y dimension of the preview image, in pixels.
/// </summary>
[FieldOrder(1)] public ushort ResolutionY { get; set; }
/// <summary>
/// Gets the image length in bytes.
/// </summary>
[FieldOrder(2)] public uint ImageLength { get; set; }
//[FieldOrder(3)] [FieldCount(nameof(ImageLength))] public byte[] ImageData { get; set; }
public override string ToString()
{
return $"{nameof(ResolutionX)}: {ResolutionX}, {nameof(ResolutionY)}: {ResolutionY}, {nameof(ImageLength)}: {ImageLength}";
}
}
#endregion
#region Layer
public class LayerDef
{
//[FieldOrder(0)] public uint DataAddress { get; set; }
[FieldOrder(1)] public float PositionZ { get; set; }
[FieldOrder(2)] public float LiftHeight { get; set; }
[FieldOrder(3)] public float LiftSpeed { get; set; }
[FieldOrder(4)] public float LiftHeight2 { get; set; }
[FieldOrder(5)] public float LiftSpeed2 { get; set; }
[FieldOrder(6)] public float WaitTimeAfterLift { get; set; }
[FieldOrder(7)] public float RetractSpeed { get; set; }
[FieldOrder(8)] public float RetractHeight2 { get; set; }
[FieldOrder(9)] public float RetractSpeed2 { get; set; }
[FieldOrder(10)] public float WaitTimeBeforeCure { get; set; }
[FieldOrder(11)] public float ExposureTime { get; set; }
[FieldOrder(12)] public float WaitTimeAfterCure { get; set; }
[FieldOrder(13)] public byte LightPWM { get; set; }
[FieldOrder(14)] public uint BoundingRectangleX { get; set; }
[FieldOrder(15)] public uint BoundingRectangleY { get; set; }
[FieldOrder(16)] public uint BoundingRectangleWidth { get; set; }
[FieldOrder(17)] public uint BoundingRectangleHeight { get; set; }
//[Ignore] public byte[] ImageData { get; set; }
public LayerDef()
{
}
public LayerDef(Layer layer)
{
PositionZ = layer.PositionZ;
LiftHeight = layer.LiftHeight;
LiftSpeed = layer.LiftSpeed;
LiftHeight2 = layer.LiftHeight2;
LiftSpeed2 = layer.LiftSpeed2;
WaitTimeAfterLift = layer.WaitTimeAfterLift;
RetractSpeed = layer.RetractSpeed;
RetractHeight2 = layer.RetractHeight2;
RetractSpeed2 = layer.RetractSpeed2;
WaitTimeBeforeCure = layer.WaitTimeBeforeCure;
ExposureTime = layer.ExposureTime;
WaitTimeAfterCure = layer.WaitTimeAfterCure;
LightPWM = layer.LightPWM;
BoundingRectangleX = (uint)layer.BoundingRectangle.X;
BoundingRectangleY = (uint)layer.BoundingRectangle.Y;
BoundingRectangleWidth = (uint)layer.BoundingRectangle.Width;
BoundingRectangleHeight = (uint)layer.BoundingRectangle.Height;
}
public void CopyTo(Layer layer)
{
layer.PositionZ = PositionZ;
layer.LiftHeight = LiftHeight;
layer.LiftSpeed = LiftSpeed;
layer.LiftHeight2 = LiftHeight2;
layer.LiftSpeed2 = LiftSpeed2;
layer.WaitTimeAfterLift = WaitTimeAfterLift;
layer.RetractSpeed = RetractSpeed;
layer.RetractHeight2 = RetractHeight2;
layer.RetractSpeed2 = RetractSpeed2;
layer.WaitTimeBeforeCure = WaitTimeBeforeCure;
layer.ExposureTime = ExposureTime;
layer.WaitTimeAfterCure = WaitTimeAfterCure;
layer.LightPWM = LightPWM;
}
}
#endregion
#region GCode
public class GCodeDef
{
[FieldOrder(0)]
public uint GCodeSize { get; set; }
[FieldOrder(1)] [FieldLength(nameof(GCodeSize))]
public string GCodeText { get; set; }
}
#endregion
#endregion
#region Properties
public FileDef FileSettings { get; protected internal set; } = new();
public Header HeaderSettings { get; protected internal set; } = new();
public CustomTable CustomTableSettings { get; protected internal set; } = new();
public Preview[] Previews { get; protected internal set; }
public override FileFormatType FileType => FileFormatType.Binary;
public override FileExtension[] FileExtensions { get; } = {
new (typeof(OSLAFile), "osla", "Open SLA universal binary file"),
//new ("omsla", "Open mSLA universal binary file"),
//new ("odlp", "Open DLP universal binary file"),
};
public override PrintParameterModifier[] PrintParameterModifiers { get; } = {
PrintParameterModifier.BottomLayerCount,
PrintParameterModifier.BottomWaitTimeBeforeCure,
PrintParameterModifier.WaitTimeBeforeCure,
PrintParameterModifier.BottomExposureTime,
PrintParameterModifier.ExposureTime,
PrintParameterModifier.BottomWaitTimeAfterCure,
PrintParameterModifier.WaitTimeAfterCure,
PrintParameterModifier.BottomLiftHeight,
PrintParameterModifier.BottomLiftSpeed,
PrintParameterModifier.LiftHeight,
PrintParameterModifier.LiftSpeed,
PrintParameterModifier.BottomLiftHeight2,
PrintParameterModifier.BottomLiftSpeed2,
PrintParameterModifier.LiftHeight2,
PrintParameterModifier.LiftSpeed2,
PrintParameterModifier.BottomWaitTimeAfterLift,
PrintParameterModifier.WaitTimeAfterLift,
PrintParameterModifier.BottomRetractSpeed,
PrintParameterModifier.RetractSpeed,
PrintParameterModifier.BottomRetractHeight2,
PrintParameterModifier.BottomRetractSpeed2,
PrintParameterModifier.RetractHeight2,
PrintParameterModifier.RetractSpeed2,
PrintParameterModifier.BottomLightPWM,
PrintParameterModifier.LightPWM,
};
public override PrintParameterModifier[] PrintParameterPerLayerModifiers { get; } = {
PrintParameterModifier.WaitTimeBeforeCure,
PrintParameterModifier.ExposureTime,
PrintParameterModifier.WaitTimeAfterCure,
PrintParameterModifier.LiftHeight,
PrintParameterModifier.LiftSpeed,
PrintParameterModifier.LiftHeight2,
PrintParameterModifier.LiftSpeed2,
PrintParameterModifier.WaitTimeAfterLift,
PrintParameterModifier.RetractSpeed,
PrintParameterModifier.RetractHeight2,
PrintParameterModifier.RetractSpeed2,
PrintParameterModifier.LightPWM,
};
public override Size[] ThumbnailsOriginalSize { get; } =
{
new(400, 400),
new(200, 200)
};
public override uint ResolutionX
{
get => HeaderSettings.ResolutionX;
set
{
HeaderSettings.ResolutionX = value;
RaisePropertyChanged();
}
}
public override uint ResolutionY
{
get => HeaderSettings.ResolutionY;
set
{
HeaderSettings.ResolutionY = value;
RaisePropertyChanged();
}
}
public override float DisplayWidth
{
get => HeaderSettings.DisplayWidth;
set
{
HeaderSettings.DisplayWidth = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override float DisplayHeight
{
get => HeaderSettings.DisplayHeight;
set
{
HeaderSettings.DisplayHeight = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override float MachineZ
{
get => HeaderSettings.MachineZ > 0 ? HeaderSettings.MachineZ : base.MachineZ;
set
{
HeaderSettings.MachineZ = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override Enumerations.FlipDirection DisplayMirror
{
get => (Enumerations.FlipDirection)HeaderSettings.DisplayMirror;
set
{
HeaderSettings.DisplayMirror = (byte)value;
RaisePropertyChanged();
}
}
public override float LayerHeight
{
get => HeaderSettings.LayerHeight;
set
{
HeaderSettings.LayerHeight = Layer.RoundHeight(value);
RaisePropertyChanged();
}
}
public override uint LayerCount
{
get => base.LayerCount;
set => HeaderSettings.LayerCount = base.LayerCount;
}
public override ushort BottomLayerCount
{
get => HeaderSettings.BottomLayersCount;
set => base.BottomLayerCount = HeaderSettings.BottomLayersCount = value;
}
public override float PrintTime
{
get => base.PrintTime;
set
{
base.PrintTime = value;
HeaderSettings.PrintTime = (uint)base.PrintTime;
}
}
public override float MaterialMilliliters
{
get => base.MaterialMilliliters;
set
{
base.MaterialMilliliters = value;
HeaderSettings.MaterialMilliliters = base.MaterialMilliliters;
}
}
public override float MaterialCost
{
get => (float) Math.Round(HeaderSettings.MaterialCost, 3);
set => base.MaterialCost = HeaderSettings.MaterialCost = (float)Math.Round(value, 3);
}
public override string MaterialName
{
get => HeaderSettings.MaterialName;
set => base.MaterialName = HeaderSettings.MaterialName = value;
}
public override string MachineName
{
get => HeaderSettings.MachineName;
set => base.MachineName = HeaderSettings.MachineName = value;
}
public override object[] Configs => new object[] { FileSettings, HeaderSettings };
#endregion
#region Constructors
public OSLAFile()
{
//Previews = new Preview[ThumbnailsCount];
GCode = new GCodeBuilder
{
UseTailComma = true,
UseComments = true,
GCodePositioningType = GCodeBuilder.GCodePositioningTypes.Absolute,
GCodeSpeedUnit = GCodeBuilder.GCodeSpeedUnits.MillimetersPerMinute,
GCodeTimeUnit = GCodeBuilder.GCodeTimeUnits.Milliseconds,
GCodeShowImageType = GCodeBuilder.GCodeShowImageTypes.LayerIndex0Started,
LayerMoveCommand = GCodeBuilder.GCodeMoveCommands.G0,
EndGCodeMoveCommand = GCodeBuilder.GCodeMoveCommands.G0,
CommandShowImageM6054 = {Arguments = "{0}"},
};
}
#endregion
#region Methods
public override void Clear()
{
base.Clear();
Previews = null;
}
protected override void EncodeInternally(string fileFullPath, OperationProgress progress)
{
using var outputFile = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write);
FileSettings.Update();
var fileDefSize = Helpers.SerializeWriteFileStream(outputFile, FileSettings);
HeaderSettings.TableSize = (uint)Helpers.Serializer.SizeOf(HeaderSettings);
outputFile.Seek((int)HeaderSettings.TableSize, SeekOrigin.Current);
Helpers.SerializeWriteFileStream(outputFile, CustomTableSettings); // Custom table
// Previews
progress.Reset(OperationProgress.StatusEncodePreviews, ThumbnailsCount);
HeaderSettings.PreviewCount = 0;
uint sizeofPreview = 0;
for (byte i = 0; i < ThumbnailsCount; i++)
{
var image = Thumbnails[i];
if(image is null) continue;
progress.Token.ThrowIfCancellationRequested();
var bytes = EncodeImage(HeaderSettings.PreviewDataType, image);
if (bytes.Length == 0) continue;
var preview = new Preview
{
ResolutionX = (ushort) image.Width,
ResolutionY = (ushort) image.Height,
ImageLength = (uint) bytes.Length,
};
if (sizeofPreview == 0)
{
sizeofPreview = (uint) Helpers.Serializer.SizeOf(preview);
}
HeaderSettings.PreviewCount++;
Helpers.SerializeWriteFileStream(outputFile, preview);
// Need to fill what we don't know
if (HeaderSettings.PreviewTableSize > sizeofPreview)
{
outputFile.Seek(HeaderSettings.LayerTableSize - sizeofPreview, SeekOrigin.Current);
}
outputFile.WriteBytes(bytes);
progress++;
}
uint[] layerDataAddresses = new uint[LayerCount];
progress.Reset(OperationProgress.StatusEncodeLayers, LayerCount);
HeaderSettings.LayerDefinitionsAddress = (uint) outputFile.Position;
outputFile.Seek(HeaderSettings.LayerTableSize * LayerCount, SeekOrigin.Current); // Start of layer data
var layersHash = new Dictionary<string, uint>();
foreach (var batch in BatchLayersIndexes())
{
var layerBytes = new byte[LayerCount][];
Parallel.ForEach(batch, CoreSettings.ParallelOptions, layerIndex =>
{
if (progress.Token.IsCancellationRequested) return;
using (var mat = this[layerIndex].LayerMat)
{
layerBytes[layerIndex] = EncodeImage(HeaderSettings.LayerDataType, mat);
}
progress.LockAndIncrement();
});
foreach (var layerIndex in batch)
{
progress.Token.ThrowIfCancellationRequested();
// Try to reuse layers
var hash = CryptExtensions.ComputeSHA1Hash(layerBytes[layerIndex]);
if (layersHash.TryGetValue(hash, out var address))
{
layerDataAddresses[layerIndex] = address;
}
else
{
layerDataAddresses[layerIndex] = (uint)outputFile.Position;
outputFile.WriteUIntLittleEndian((uint)layerBytes[layerIndex].Length);
outputFile.WriteBytes(layerBytes[layerIndex]);
layersHash.Add(hash, layerDataAddresses[layerIndex]);
}
layerBytes[layerIndex] = null; // Free this
}
}
HeaderSettings.GCodeAddress = (uint)outputFile.Position;
uint layerTableSize = 0;
outputFile.Seek(HeaderSettings.LayerDefinitionsAddress, SeekOrigin.Begin);
for (int layerIndex = 0; layerIndex < layerDataAddresses.Length; layerIndex++)
{
progress.Token.ThrowIfCancellationRequested();
var layer = this[layerIndex];
var layerdef = new LayerDef(layer);
outputFile.WriteUIntLittleEndian(layerDataAddresses[layerIndex]);
Helpers.SerializeWriteFileStream(outputFile, layerdef);
if (layerTableSize == 0)
{
layerTableSize = 4 + (uint)Helpers.Serializer.SizeOf(layerdef);
}
if (HeaderSettings.LayerTableSize > layerTableSize)
{
outputFile.Seek(HeaderSettings.LayerTableSize - layerTableSize, SeekOrigin.Current);
}
}
progress.Reset(OperationProgress.StatusEncodeGcode);
outputFile.Seek(HeaderSettings.GCodeAddress, SeekOrigin.Begin);
RebuildGCode();
var gcodeSettings = new GCodeDef { GCodeText = GCodeStr };
gcodeSettings.GCodeSize = (uint)gcodeSettings.GCodeText.Length;
Helpers.SerializeWriteFileStream(outputFile, gcodeSettings);
outputFile.Seek(fileDefSize, SeekOrigin.Begin);
Helpers.SerializeWriteFileStream(outputFile, HeaderSettings);
Debug.WriteLine("Encode Results:");
Debug.WriteLine(FileSettings);
Debug.WriteLine(HeaderSettings);
Debug.WriteLine("-End-");
}
protected override void DecodeInternally(string fileFullPath, OperationProgress progress)
{
using var inputFile = new FileStream(fileFullPath, FileMode.Open, FileAccess.Read);
FileSettings = Helpers.Deserialize<FileDef>(inputFile);
Debug.Write("File -> ");
Debug.WriteLine(FileSettings);
FileSettings.Validate();
HeaderSettings = Helpers.Deserialize<Header>(inputFile);
Debug.Write("Header -> ");
Debug.WriteLine(HeaderSettings);
var headerSize = Helpers.Serializer.SizeOf(HeaderSettings);
if (HeaderSettings.TableSize > headerSize) // By pass what we dont know
{
inputFile.Seek(HeaderSettings.TableSize - headerSize, SeekOrigin.Current);
}
CustomTableSettings = Helpers.Deserialize<CustomTable>(inputFile);
Debug.Write("Custom table -> ");
Debug.WriteLine(CustomTableSettings);
progress.Reset(OperationProgress.StatusDecodePreviews, ThumbnailsCount);
Previews = new Preview[HeaderSettings.PreviewCount];
for (byte i = 0; i < HeaderSettings.PreviewCount; i++)
{
progress.Token.ThrowIfCancellationRequested();
Previews[i] = Helpers.Deserialize<Preview>(inputFile);
Debug.Write($"Preview {i} -> ");
Debug.WriteLine(Previews[i]);
// Need to fill what we don't know
if (HeaderSettings.PreviewTableSize > 8)
{
inputFile.Seek(HeaderSettings.LayerTableSize - 8, SeekOrigin.Current);
}
var bytes = inputFile.ReadBytes((int)Previews[i].ImageLength);
Thumbnails[i] = DecodeImage(HeaderSettings.PreviewDataType, bytes, Previews[i].ResolutionX, Previews[i].ResolutionY);
progress++;
}
inputFile.Seek(HeaderSettings.LayerDefinitionsAddress, SeekOrigin.Begin);
LayerManager.Init(HeaderSettings.LayerCount);
var layerDef = new LayerDef[LayerCount];
progress.Reset(OperationProgress.StatusGatherLayers, HeaderSettings.LayerCount);
uint[] layerDataAddresses = new uint[LayerCount];
uint layerTableSize = 0;
for (uint layerIndex = 0; layerIndex < HeaderSettings.LayerCount; layerIndex++)
{
progress.Token.ThrowIfCancellationRequested();
layerDataAddresses[layerIndex] = inputFile.ReadUIntLittleEndian();
layerDef[layerIndex] = Helpers.Deserialize<LayerDef>(inputFile);
if (layerTableSize == 0)
{
layerTableSize = 4 + (uint)Helpers.Serializer.SizeOf(layerDef[layerIndex]);
}
if (HeaderSettings.LayerTableSize > layerTableSize)
{
inputFile.Seek(HeaderSettings.LayerTableSize - layerTableSize, SeekOrigin.Current);
}
progress++;
}
progress.Reset(OperationProgress.StatusDecodeLayers, HeaderSettings.LayerCount);
foreach (var batch in BatchLayersIndexes())
{
var layerBytes = new byte[LayerCount][];
foreach (var layerIndex in batch)
{
progress.Token.ThrowIfCancellationRequested();
inputFile.Seek(layerDataAddresses[layerIndex], SeekOrigin.Begin);
layerBytes[layerIndex] = inputFile.ReadBytes(inputFile.ReadUIntLittleEndian());
}
Parallel.ForEach(batch, CoreSettings.ParallelOptions, layerIndex =>
{
if (progress.Token.IsCancellationRequested) return;
using (var mat = DecodeImage(HeaderSettings.LayerDataType, layerBytes[layerIndex], Resolution))
{
layerBytes[layerIndex] = null; // Clean
var layer = new Layer((uint)layerIndex, mat, this);
layerDef[layerIndex].CopyTo(layer);
this[layerIndex] = layer;
}
progress.LockAndIncrement();
});
}
progress.Reset(OperationProgress.StatusDecodeGcode);
inputFile.Seek(HeaderSettings.GCodeAddress, SeekOrigin.Begin);
var gcodeDef = Helpers.Deserialize<GCodeDef>(inputFile);
GCodeStr = gcodeDef.GCodeText;
//GCode.ParseLayersFromGCode(this);
UpdateGlobalPropertiesFromLayers();
}
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);
FileSettings.Update();
Helpers.SerializeWriteFileStream(outputFile, FileSettings);
Helpers.SerializeWriteFileStream(outputFile, HeaderSettings);
outputFile.Seek(HeaderSettings.LayerDefinitionsAddress, SeekOrigin.Begin);
foreach (var layer in this)
{
outputFile.Seek(4, SeekOrigin.Current); // skip address
Helpers.SerializeWriteFileStream(outputFile, new LayerDef(layer)); // Update layer values
}
if (HeaderSettings.GCodeAddress > 0)
{
outputFile.Seek(HeaderSettings.GCodeAddress, SeekOrigin.Begin);
outputFile.SetLength(HeaderSettings.GCodeAddress);
RebuildGCode();
var gcodeSettings = new GCodeDef { GCodeText = GCodeStr };
gcodeSettings.GCodeSize = (uint)gcodeSettings.GCodeText.Length;
Helpers.SerializeWriteFileStream(outputFile, gcodeSettings);
}
}
#endregion
#region Static Methods
#endregion
}
}
|