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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
|
/*
* 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.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Util;
using UVtools.Core.Extensions;
using UVtools.Core.Operations;
namespace UVtools.Core.FileFormats
{
#region Wanhao
[Serializable]
[XmlRoot(ElementName = "manifest")]
public sealed class CWSManifest
{
public const string FileName = "manifest.xml";
[XmlAttribute]
public byte FileVersion { get; set; } = 1;
public sealed class Model
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("tag")]
public string Tag { get; set; }
}
public sealed class Slice
{
[XmlElement("name")]
public string Name { get; set; }
public Slice()
{
}
public Slice(string name)
{
Name = name;
}
}
[XmlArrayItem("model")]
public Model[] Models { get; set; }
public Slice[] Slices { get; set; }
public Slice SliceProfile { get; set; } = new Slice();
public Slice GCode { get; set; } = new Slice();
}
[Serializable]
[XmlRoot(ElementName = "SliceBuildConfig")]
public sealed class CWSSliceBuildConfig
{
public const string GCODESTART =
";********** Header Start ********\r\n" +
"G21 ; Set units to be mm\r\n" +
"G91 ; Relative Positioning\r\n" +
"M17 ; Enable motors\r\n" +
"; G28 Z ; Auto-home on print - commented by default";
public const string GCODEEND =
";********** Footer ********\r\n" +
"@cmdCloseShutter ; UV off\r\n" +
"G4 P0 ; wait for last lift to complete\r\n" +
"G1 Z40.0 F150.0 ; lift model clear of resin\r\n" +
"G4 P0 ; sync\r\n" +
"M18 ; Disable Motors\r\n" +
";<Completed>";
public const string GCODELIFT =
";********** Lift Sequence %d$CURSLICE ********\r\n" +
"G1 Z($ZLiftDist * $ZDir) F{$CURSLICE < $NumFirstLayers?$ZBottomLiftRate:$ZLiftRate}\r\n;" +
"<Takes> {$CURSLICE<$NumFirstLayers?%d($ZLiftDist*1000*60/$ZBottomLiftRate):%d($ZLiftDist*1000*60/$ZLiftRate)}\r\n" +
"G4 P0 ; Wait for lift rise to complete\r\n;" +
"<Delay> %d$TopTime\r\n" +
"G1 Z(($LayerThickness-$ZLiftDist) * $ZDir) F$ZRetractRate\r\n" +
";<Takes> %d(($ZLiftDist*1000-$LayerThickness*1000)*60/$ZRetractRate)";
public const string GCODELAYER =
";********** Layer %d$CURSLICE ********\r\n" +
";<Slice> %d$CURSLICE\r\n" +
"@cmdOpenShutter ; UV on\r\n" +
";{$CURSLICE<$NumFirstLayers?<Delay> %d$FirstLayerTime:<Delay> %d$LayerTime}\r\n" +
"@cmdCloseShutter ; UV off\r\n" +
";<Slice> Blank\r\n" +
";<Delay> %d$BlankTime";
public sealed class InkConfig
{
public string Name { get; set; }
public float SliceHeight { get; set; }
public uint LayerTime { get; set; }
public uint FirstLayerTime { get; set; }
public ushort NumberofBottomLayers { get; set; }
public float ResinPriceL { get; set; }
}
[XmlAttribute]
public byte FileVersion { get; set; } = 2;
public float DotsPermmX { get; set; } = 21.164f;
public float DotsPermmY { get; set; } = 21.164f;
public ushort XResolution { get; set; }
public ushort YResolution { get; set; }
public uint BlankTime { get; set; }
public uint TopTime { get; set; }
public uint PlatformTemp { get; set; } = 75;
public byte ExportSVG { get; set; }
public string Export { get; set; } = "False";
public string ExportPNG { get; set; } = "False";
public string CalcSliceSize { get; set; } = "False";
public uint XOffset { get; set; }
public uint YOffset { get; set; }
public string Direction { get; set; } = "Bottom_Up";
public float LiftDistance { get; set; } = 6;
public float SlideTiltValue { get; set; }
public uint SettleTime { get; set; } = 1600;
public string AntiAliasing { get; set; } = "True";
public string UseMainLiftGCode { get; set; } = "False";
public uint AntiAliasingValue { get; set; } = 4;
public float LiftFeedRate { get; set; } = 40;
public float BottomLiftFeedRate { get; set; } = 25;
public float LiftRetractRate { get; set; } = 80;
public string ExportOption { get; set; } = "ZIP";
public string RenderOutlines { get; set; } = "False";
public uint OutlineWidth_Inset { get; set; } = 2;
public uint OutlineWidth_Outset { get; set; }
public string FlipX { get; set; } = "False";
public string FlipY { get; set; } = "False";
public string Notes { get; set; } =
"Use these as a place to start; tune them for your specific printer and resins.\r\nAlways run a calibration on your resin to dial in for your machine.\r\nProfiles created by Earl Miller for CW v1.0.0.75.";
public string GCodeHeader { get; set; } = GCODESTART;
public string GCodeFooter { get; set; } = GCODEEND;
public string GCodeLift { get; set; } = GCODELIFT;
public string GCodeLayer { get; set; } = GCODELAYER;
[XmlElement("InkConfig")]
public List<InkConfig> InkConfigs { get; set; }
public string SelectedInk { get; set; }
public uint MinTestExposure { get; set; } = 5000;
public uint TestExposureStep { get; set; } = 100;
public string ExportPreview { get; set; } = "None";
public string UseMask { get; set; } = "False";
public string MaskFilename { get; set; } = "False";
}
#endregion
public class CWSFile : FileFormat
{
#region Constants
public const string GCodeStart = "G28 ;Auto Home{0}" +
"G21 ;Set units to be mm{0}" +
"G91 ;Relative Positioning{0}" +
"M17 ;Enable motors{0}" +
"<Slice> Blank{0}" +
"M106 S0{0}{0}";
public const string GCodeEnd = "M106 S0{0} ; UV off" +
"G1 Z{1}{0}" +
"{0}M18 ;Disable Motors{0}" +
";<Completed>{0}";
public const string GCodeKeywordSlice = ";<Slice>";
public const string GCodeKeywordSliceBlank = ";<Slice> Blank";
public const string GCodeKeywordDelay = ";<Delay>";
public const string GCodeKeywordTakes = ";<Takes>";
public const string WanhaoStartGCode =
";********** Header Start ********{0}" +
"G21 ; Set units to be mm{0}" +
"G91 ; Relative Positioning{0}" +
"M17 ; Enable motors{0}" +
"; G28 Z ; Auto-home on print - commented by default{0}";
public const string WanhaoPreSliceGCode =
";********** Pre-Slice {1} ********{0}" +
"G4 P0; Make sure any previous relative moves are complete{0}" +
";<Delay> {2}{0}" +
";********** Layer {1} ********{0}";
public const string WanhaoGCodeEnd =
";********** Footer ********{0}" +
"M106 S0 ; UV off{0}" +
"G4 P0 ; wait for last lift to complete{0}" +
"G1 Z40.0 F150.0 ; lift model clear of resin{0}" +
"G4 P0 ; sync{0}" +
"M18 ; Disable Motors{0}" +
";<Completed>{0}";
#endregion
#region Sub Classes
public class Output
{
// ;(****Build and Slicing Parameters****)
[DisplayName("Pix per mm X")] public float PixPermmX { get; set; } = 19.324f;
[DisplayName("Pix per mm Y")] public float PixPermmY { get; set; } = 19.324f;
[DisplayName("X Resolution")] public ushort XResolution { get; set; }
[DisplayName("Y Resolution")] public ushort YResolution { get; set; }
[DisplayName("Layer Thickness")] public float LayerThickness { get; set; }
[DisplayName("Layer Time")] public uint LayerTime { get; set; } = 5500;
[DisplayName("Render Outlines")] public bool RenderOutlines { get; set; } = false;
[DisplayName("Outline Width Inset")] public ushort OutlineWidthInset { get; set; } = 2;
[DisplayName("Outline Width Outset")] public ushort OutlineWidthOutset { get; set; } = 0;
[DisplayName("Bottom Layers Time")] public uint BottomLayersTime { get; set; } = 35000;
[DisplayName("Number of Bottom Layers")] public ushort NumberBottomLayers { get; set; } = 3;
[DisplayName("Blanking Layer Time")] public uint BlankingLayerTime { get; set; } = 1000;
[DisplayName("Build Direction")] public string BuildDirection { get; set; } = "Bottom_Up";
[DisplayName("Lift Distance")] public float LiftDistance { get; set; } = 4;
[DisplayName("Slide/Tilt Value")] public byte TiltValue { get; set; }
[DisplayName("Use Mainlift GCode Tab")] public bool UseMainliftGCodeTab { get; set; }
[DisplayName("Settle Time")] public uint SettleTime { get; set; } = 1600;
[DisplayName("Anti Aliasing")] public bool AntiAliasing { get; set; } = true;
[DisplayName("Anti Aliasing Value")] public float AntiAliasingValue { get; set; } = 2;
[DisplayName("Z Lift Feed Rate")] public float ZLiftFeedRate { get; set; } = 120;
[DisplayName("Z Bottom Lift Feed Rate")] public float ZBottomLiftFeedRate { get; set; } = 120;
[DisplayName("Z Lift Retract Rate")] public float ZLiftRetractRate { get; set; } = 120;
[DisplayName("Flip X")] public bool FlipX { get; set; }
[DisplayName("Flip Y")] public bool FlipY { get; set; }
[DisplayName("Number of Slices")] public uint LayersNum { get; set; }
// ;(****Machine Configuration ******)
[DisplayName("Platform X Size")] public float PlatformXSize { get; set; }
[DisplayName("Platform Y Size")] public float PlatformYSize { get; set; }
[DisplayName("Platform Z Size")] public float PlatformZSize { get; set; }
[DisplayName("Max X Feedrate")] public ushort MaxXFeedrate { get; set; } = 200;
[DisplayName("Max Y Feedrate")] public ushort MaxYFeedrate { get; set; } = 200;
[DisplayName("Max Z Feedrate")] public ushort MaxZFeedrate { get; set; } = 200;
[DisplayName("Machine Type")] public string MachineType { get; set; } = "UV_LCD";
// ;(****UVtools Configuration ******)
[DisplayName("Bottom Layer Light PWM")] public byte BottomLightPWM { get; set; } = 255;
[DisplayName("Layer Light PWM")] public byte LightPWM { get; set; } = 255;
}
public class Slice
{
[DisplayName("xppm")] public float Xppm { get; set; } = 19.324f;
[DisplayName("yppm")] public float Yppm { get; set; } = 19.324f;
[DisplayName("xres")] public ushort Xres { get; set; }
[DisplayName("yres")] public ushort Yres { get; set; }
[DisplayName("thickness")] public float Thickness { get; set; }
[DisplayName("layers_num")] public uint LayersNum { get; set; }
[DisplayName("head_layers_num")] public ushort HeadLayersNum { get; set; } = 3;
[DisplayName("layers_expo_ms")] public uint LayersExpoMs { get; set; } = 5500;
[DisplayName("head_layers_expo_ms")] public uint HeadLayersExpoMs { get; set; } = 35000;
[DisplayName("wait_before_expo_ms")] public uint WaitBeforeExpoMs { get; set; } = 2000;
[DisplayName("lift_distance")] public float LiftDistance { get; set; } = 4;
[DisplayName("lift_up_speed")] public float LiftUpSpeed { get; set; } = 120;
[DisplayName("lift_down_speed")] public float LiftDownSpeed { get; set; } = 120;
[DisplayName("lift_when_finished")] public byte LiftWhenFinished { get; set; } = 80;
}
#endregion
#region Properties
public Slice SliceSettings { get; } = new Slice();
public Output OutputSettings { get; } = new Output();
public CWSSliceBuildConfig SliceBuildConfig { get; set; } = new CWSSliceBuildConfig();
public override FileFormatType FileType => FileFormatType.Archive;
public enum PrinterType : byte
{
Unknown,
Elfin,
BeneMono,
Wanhao,
}
public PrinterType Printer { get; set; } = PrinterType.Unknown;
public override FileExtension[] FileExtensions { get; } = {
new ("cws", "NovaMaker CWS"),
new ("rgb.cws", "NovaMaker Bene4 Mono / Elfin2 Mono SE (CWS)"),
new ("xml.cws", "Creation Workshop X (CWS)"),
};
public override PrintParameterModifier[] PrintParameterModifiers { get; } = {
PrintParameterModifier.BottomLayerCount,
PrintParameterModifier.BottomExposureSeconds,
PrintParameterModifier.ExposureSeconds,
PrintParameterModifier.BottomLiftSpeed,
PrintParameterModifier.LiftHeight,
PrintParameterModifier.RetractSpeed,
PrintParameterModifier.LiftSpeed,
PrintParameterModifier.BottomLightPWM,
PrintParameterModifier.LightPWM,
};
public override PrintParameterModifier[] PrintParameterPerLayerModifiers { get; } = {
PrintParameterModifier.ExposureSeconds,
PrintParameterModifier.LiftHeight,
PrintParameterModifier.LiftSpeed,
PrintParameterModifier.RetractSpeed,
PrintParameterModifier.LightPWM,
};
public override byte ThumbnailsCount { get; } = 0;
public override System.Drawing.Size[] ThumbnailsOriginalSize { get; } = null;
public override uint ResolutionX
{
get => SliceSettings.Xres > 0 ? SliceSettings.Xres : SliceBuildConfig.XResolution;
set
{
SliceBuildConfig.XResolution =
OutputSettings.XResolution =
SliceSettings.Xres = (ushort) value;
RaisePropertyChanged();
}
}
public override uint ResolutionY
{
get => SliceSettings.Yres > 0 ? SliceSettings.Yres : SliceBuildConfig.YResolution;
set
{
SliceBuildConfig.YResolution =
OutputSettings.YResolution =
SliceSettings.Yres = (ushort) value;
RaisePropertyChanged();
}
}
public override float DisplayWidth
{
get => OutputSettings.PlatformXSize;
set
{
OutputSettings.PlatformXSize = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override float DisplayHeight
{
get => OutputSettings.PlatformYSize;
set
{
OutputSettings.PlatformYSize = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override float MaxPrintHeight
{
get => OutputSettings.PlatformZSize;
set
{
OutputSettings.PlatformZSize = (float) Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override bool MirrorDisplay
{
get => OutputSettings.FlipX;
set
{
OutputSettings.FlipX = value;
OutputSettings.FlipY = false;
RaisePropertyChanged();
}
}
public override byte AntiAliasing
{
get => (byte) OutputSettings.AntiAliasingValue;
set
{
OutputSettings.AntiAliasingValue = value.Clamp(1, 16);
OutputSettings.AntiAliasing = OutputSettings.AntiAliasingValue > 1;
RaisePropertyChanged();
}
}
public override float LayerHeight
{
get => SliceSettings.Thickness > 0 ? SliceSettings.Thickness : OutputSettings.LayerThickness;
set
{
OutputSettings.LayerThickness = SliceSettings.Thickness = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override uint LayerCount
{
set
{
OutputSettings.LayersNum = LayerCount;
SliceSettings.LayersNum = LayerCount;
RaisePropertyChanged();
RaisePropertyChanged(nameof(NormalLayerCount));
}
}
public override ushort BottomLayerCount
{
get => SliceSettings.HeadLayersNum;
set
{
SliceSettings.HeadLayersNum = value;
RaisePropertyChanged();
}
}
public override float BottomExposureTime
{
get => (float) Math.Round(SliceSettings.HeadLayersExpoMs / 1000f, 2);
set
{
OutputSettings.BottomLayersTime =
SliceSettings.HeadLayersExpoMs = (uint) (value * 1000f);
RaisePropertyChanged();
}
}
public override float ExposureTime
{
get => (float) Math.Round(SliceSettings.LayersExpoMs / 1000f, 2);
set
{
OutputSettings.LayerTime =
SliceSettings.LayersExpoMs = (uint) (value * 1000f);
RaisePropertyChanged();
}
}
public override float BottomLiftSpeed
{
get => OutputSettings.ZBottomLiftFeedRate;
set
{
OutputSettings.ZBottomLiftFeedRate = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override float LiftHeight
{
get => SliceSettings.LiftDistance;
set
{
OutputSettings.LiftDistance =
SliceSettings.LiftDistance = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override float LiftSpeed
{
get => SliceSettings.LiftDownSpeed;
set
{
OutputSettings.ZLiftFeedRate =
SliceSettings.LiftUpSpeed =
SliceSettings.LiftDownSpeed = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override float RetractSpeed
{
get => OutputSettings.ZLiftRetractRate;
set
{
OutputSettings.ZLiftRetractRate = (float)Math.Round(value, 2);
RaisePropertyChanged();
}
}
public override byte BottomLightPWM
{
get => OutputSettings.BottomLightPWM;
set
{
OutputSettings.BottomLightPWM = value;
RaisePropertyChanged();
}
}
public override byte LightPWM
{
get => OutputSettings.LightPWM;
set
{
OutputSettings.LightPWM = value;
RaisePropertyChanged();
}
}
public override object[] Configs => Printer == PrinterType.Wanhao ? new object[] { SliceBuildConfig, OutputSettings } : new object[] { SliceSettings, OutputSettings};
#endregion
#region Methods
public override void Clear()
{
base.Clear();
GCode = null;
}
protected override void EncodeInternally(string fileFullPath, OperationProgress progress)
{
//var filename = fileFullPath.EndsWith(TemporaryFileAppend) ? Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileFullPath)) : Path.GetFileNameWithoutExtension(fileFullPath);
if (Printer == PrinterType.Unknown)
{
Printer = PrinterType.Elfin;
for (int i = 0; i < FileExtensions.Length; i++)
{
if (!fileFullPath.EndsWith(FileExtensions[i].Extension) && !fileFullPath.EndsWith($"{FileExtensions[i].Extension}{TemporaryFileAppend}")) continue;
Printer = (PrinterType) i+1;
}
}
var filename = Path.GetFileName(fileFullPath);
filename = filename.Substring(0, filename.IndexOf('.'));
using (ZipArchive outputFile = ZipFile.Open(fileFullPath, ZipArchiveMode.Create))
{
if (Printer == PrinterType.Wanhao)
{
var manifest = new CWSManifest
{
GCode = {Name = $"{filename}.gcode"},
Slices = new CWSManifest.Slice[LayerCount],
SliceProfile = {Name = $"{filename}.slicing"}
};
for (int layerIndex = 0; layerIndex < LayerCount; layerIndex++)
{
manifest.Slices[layerIndex] = new CWSManifest.Slice(this[layerIndex].FormatFileName(filename));
}
XmlSerializer serializer = new XmlSerializer(manifest.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
var entry = outputFile.CreateEntry(CWSManifest.FileName);
using (var stream = entry.Open())
{
serializer.Serialize(stream, manifest, ns);
}
serializer = new XmlSerializer(SliceBuildConfig.GetType());
entry = outputFile.CreateEntry($"{filename}.slicing");
using (var stream = entry.Open())
{
serializer.Serialize(stream, SliceBuildConfig, ns);
}
}
else
{
string arch = Environment.Is64BitOperatingSystem ? "64-bits" : "32-bits";
var entry = outputFile.CreateEntry("slice.conf");
using (TextWriter tw = new StreamWriter(entry.Open()))
{
tw.WriteLine($"# {About.Website} {About.Software} {Assembly.GetExecutingAssembly().GetName().Version} {arch} {DateTime.Now}");
tw.WriteLine("# conf version 1.0");
tw.WriteLine("");
foreach (var propertyInfo in SliceSettings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var displayNameAttribute = propertyInfo.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault();
if (ReferenceEquals(displayNameAttribute, null)) continue;
tw.WriteLine($"{displayNameAttribute.DisplayName.PadRight(24)}= {propertyInfo.GetValue(SliceSettings)}");
}
}
}
//for (uint layerIndex = 0; layerIndex < LayerCount; layerIndex++)
Parallel.For(0, LayerCount,
new ParallelOptions{MaxDegreeOfParallelism = Printer == PrinterType.BeneMono ? 1 : 1 },
layerIndex =>
{
if (progress.Token.IsCancellationRequested) return;
Layer layer = this[layerIndex];
var layerImagePath = layer.FormatFileName(filename);
if (Printer == PrinterType.BeneMono)
{
using (var mat = layer.LayerMat)
using (var matEncode = new Mat(mat.Height, mat.Step / 3, DepthType.Cv8U, 3))
{
var span = mat.GetPixelSpan<byte>();
var spanEncode = matEncode.GetPixelSpan<byte>();
for (int i = 0; i < span.Length; i++)
{
spanEncode[i] = span[i];
}
using (VectorOfByte vec = new VectorOfByte())
{
CvInvoke.Imencode(".png", matEncode, vec);
lock (progress.Mutex)
{
outputFile.PutFileContent(layerImagePath, vec.ToArray(), ZipArchiveMode.Create);
}
}
}
}
else
{
outputFile.PutFileContent(layerImagePath, layer.CompressedBytes, ZipArchiveMode.Create);
}
lock (progress.Mutex)
{
progress++;
}
});
RebuildGCode();
outputFile.PutFileContent($"{filename}.gcode", GCode.ToString(), ZipArchiveMode.Create);
}
}
protected override void DecodeInternally(string fileFullPath, OperationProgress progress)
{
using (var inputFile = ZipFile.Open(fileFullPath, ZipArchiveMode.Read))
{
var entry = inputFile.GetEntry("manifest.xml");
if (entry is not null) // Wanhao
{
//DecodeXML(fileFullPath, inputFile, progress);
Printer = PrinterType.Wanhao;
try
{
var serializer = new XmlSerializer(typeof(CWSManifest));
using (var stream = entry.Open())
{
var manifest = (CWSManifest)serializer.Deserialize(stream);
OutputSettings.LayersNum = (uint) manifest.Slices.Length;
}
}
catch (Exception e)
{
Clear();
throw new FileLoadException($"Unable to deserialize '{entry.Name}'\n{e}", fileFullPath);
}
entry = inputFile.Entries.FirstOrDefault(e => e.Name.EndsWith(".slicing"));
if (!(entry is null))
{
//Clear();
//throw new FileLoadException(".slicing file not found, unable to proceed.", fileFullPath);
try
{
var serializer = new XmlSerializer(typeof(CWSSliceBuildConfig));
using (var stream = entry.Open())
{
SliceBuildConfig = (CWSSliceBuildConfig)serializer.Deserialize(stream);
}
}
catch (Exception e)
{
Clear();
throw new FileLoadException($"Unable to deserialize '{entry.Name}'\n{e}", fileFullPath);
}
}
}
else // Novamaker
{
entry = inputFile.GetEntry("slice.conf");
if (ReferenceEquals(entry, null))
{
Clear();
throw new FileLoadException("slice.conf not found", fileFullPath);
}
using (TextReader tr = new StreamReader(entry.Open()))
{
string line;
while ((line = tr.ReadLine()) != null)
{
line = line.Replace("# ", string.Empty);
if (string.IsNullOrEmpty(line)) continue;
//if(line[0] == '#') continue;
var splitLine = line.Split('=');
if (splitLine.Length < 2) continue;
foreach (var propertyInfo in SliceSettings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var displayNameAttribute = propertyInfo.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault();
if (ReferenceEquals(displayNameAttribute, null)) continue;
if (!splitLine[0].Trim().Equals(displayNameAttribute.DisplayName)) continue;
Helpers.SetPropertyValue(propertyInfo, SliceSettings, splitLine[1].Trim());
}
}
tr.Close();
}
}
entry = inputFile.Entries.FirstOrDefault(e => e.Name.EndsWith(".gcode"));
if (entry is null)
{
Clear();
throw new FileLoadException("Unable to find .gcode file",
fileFullPath);
}
using (TextReader tr = new StreamReader(entry.Open()))
{
string line;
GCode = new StringBuilder();
while ((line = tr.ReadLine()) != null)
{
GCode.AppendLine(line);
if (string.IsNullOrEmpty(line)) continue;
if (line[0] != ';')
{
continue;
}
var splitLine = line.Split('=');
if (splitLine.Length < 2) continue;
foreach (var propertyInfo in OutputSettings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var displayNameAttribute = propertyInfo.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault();
if (ReferenceEquals(displayNameAttribute, null)) continue;
if (!splitLine[0].Trim(' ', ';', '(').Equals(displayNameAttribute.DisplayName)) continue;
try
{
Helpers.SetPropertyValue(propertyInfo, OutputSettings, splitLine[1].Trim(' ', ')', 'p', 'x', 'm', 'n', 's', '/'));
}
catch
{
// ignored
}
//Debug.WriteLine(splitLine[1].Trim(' ', ')', 'm', 'n', '/'));
}
}
tr.Close();
}
LayerManager = new LayerManager(OutputSettings.LayersNum, this);
progress.ItemCount = OutputSettings.LayersNum;
var gcode = GCode.ToString();
//float currentHeight = 0;
inputFile.Entries.AsParallel().ForAllInApproximateOrder(zipArchiveEntry =>
//foreach (var zipArchiveEntry in inputFile.Entries)
{
if (!zipArchiveEntry.Name.EndsWith(".png") || progress.Token.IsCancellationRequested) return;
var layerIndexStr = string.Empty;
var layerStr = zipArchiveEntry.Name.Substring(0, zipArchiveEntry.Name.Length - 4);
for (int i = layerStr.Length-1; i >= 0; i--)
{
if(layerStr[i] < '0' || layerStr[i] > '9') break;
layerIndexStr = $"{layerStr[i]}{layerIndexStr}";
}
if (string.IsNullOrEmpty(layerIndexStr)) return;
// - .png - 4 numbers
// string layerStr = zipArchiveEntry.Name.Substring(zipArchiveEntry.Name.Length - 4 - layerSize, layerSize);
uint layerIndex = uint.Parse(layerIndexStr);
var startStr = $"{GCodeKeywordSlice} {layerIndex}";
var stripGcode =
gcode.Substring(gcode.IndexOf(startStr, StringComparison.InvariantCultureIgnoreCase) +
startStr.Length);
var endStr = $"{GCodeKeywordSlice} {layerIndex + 1}";
var endIndex = stripGcode.IndexOf(endStr, StringComparison.InvariantCulture);
if (endIndex < 0) endIndex = stripGcode.Length;
stripGcode = stripGcode
.Substring(0, endIndex)
.Trim(' ', '\n', '\r', '\t');
//var startCurrPos = stripGcode.Remove(0, ";currPos:".Length);
float liftHeight = 0;
float liftSpeed = GetInitialLayerValueOrNormal(layerIndex, BottomLiftSpeed, LiftSpeed);
float retractSpeed = RetractSpeed;
float lightOffDelay = GetInitialLayerValueOrNormal(layerIndex, BottomLightOffDelay, LightOffDelay);
byte pwm = GetInitialLayerValueOrNormal(layerIndex, BottomLightPWM, LightPWM); ;
float exposureTime = GetInitialLayerValueOrNormal(layerIndex, BottomExposureTime, ExposureTime);
//var currPos = Regex.Match(stripGcode, "G1 Z([+-]?([0-9]*[.])?[0-9]+)", RegexOptions.IgnoreCase);
var moveG1Regex = Regex.Match(stripGcode, @"G1 Z([+-]?([0-9]*[.])?[0-9]+) F(\d+)", RegexOptions.IgnoreCase);
var pwmM106Regex = Regex.Match(stripGcode, @"M106 S(\d+)", RegexOptions.IgnoreCase);
var exposureTimeRegex = Regex.Match(stripGcode, ";<Delay> (\\d+)", RegexOptions.IgnoreCase);
if (moveG1Regex.Success)
{
var liftHeightTemp = float.Parse(moveG1Regex.Groups[1].Value, CultureInfo.InvariantCulture);
var liftSpeedTemp = float.Parse(moveG1Regex.Groups[3].Value, CultureInfo.InvariantCulture);
moveG1Regex = moveG1Regex.NextMatch();
if (moveG1Regex.Success)
{
liftHeight = liftHeightTemp;
liftSpeed = liftSpeedTemp;
retractSpeed = float.Parse(moveG1Regex.Groups[3].Value, CultureInfo.InvariantCulture);
}
}
if (pwmM106Regex.Success)
{
pwm = byte.Parse(pwmM106Regex.Groups[1].Value);
}
if (layerIndex == 0)
{
OutputSettings.BottomLightPWM = pwm;
}
if (exposureTimeRegex.Success)
{
exposureTime = (float)Math.Round(float.Parse(exposureTimeRegex.Groups[1].Value, CultureInfo.InvariantCulture) / 1000f, 2);
}
/*var pwm = Regex.Match(stripGcode, "M106 S(\\d+)", RegexOptions.IgnoreCase);
if (layerIndex < InitialLayerCount)
{
OutputSettings.BottomLayerLightPWM = byte.Parse(pwm.Groups[1].Value);
}
else
{
OutputSettings.LayerLightPWM = byte.Parse(pwm.Groups[1].Value);
}*/
/*if (currPos.Success)
{
var nextMatch = currPos.NextMatch();
if (nextMatch.Success)
{
currentHeight =
(float) Math.Round(
currentHeight + float.Parse(currPos.Groups[1].Value) +
float.Parse(currPos.NextMatch().Groups[1].Value), 2);
}
else
{
currentHeight = (float) Math.Round(currentHeight + float.Parse(currPos.Groups[1].Value), 2);
}
}*/
byte[] buffer;
lock (progress)
{
using (var stream = zipArchiveEntry.Open())
{
buffer = stream.ToArray();
if (Printer == PrinterType.Unknown)
{
using (Mat mat = new Mat())
{
CvInvoke.Imdecode(buffer, ImreadModes.AnyColor, mat);
Printer = mat.NumberOfChannels == 1 ? PrinterType.Elfin : PrinterType.BeneMono;
}
}
stream.Close();
}
}
if (Printer == PrinterType.BeneMono)
{
using (Mat mat = new Mat())
{
CvInvoke.Imdecode(buffer, ImreadModes.Color, mat);
using (Mat matDecode = new Mat(mat.Height, mat.Step, DepthType.Cv8U, 1))
{
var span = mat.GetPixelSpan<byte>();
var spanDecode = matDecode.GetPixelSpan<byte>();
for (int i = 0; i < span.Length; i++)
{
spanDecode[i] = span[i];
}
this[layerIndex] =
new Layer(layerIndex, matDecode, LayerManager)
{
ExposureTime = exposureTime,
LiftHeight = liftHeight,
LiftSpeed = liftSpeed,
RetractSpeed = retractSpeed,
LightOffDelay = lightOffDelay,
LightPWM = pwm,
};
}
}
}
else
{
this[layerIndex] =
new Layer(layerIndex, buffer, LayerManager)
{
ExposureTime = exposureTime,
LiftHeight = liftHeight,
LiftSpeed = liftSpeed,
RetractSpeed = retractSpeed,
LightOffDelay = lightOffDelay,
LightPWM = pwm,
};
}
progress++;
});
}
LayerManager.GetBoundingRectangle(progress);
}
public override void RebuildGCode()
{
string arch = Environment.Is64BitOperatingSystem ? "64-bits" : "32-bits";
GCode = new StringBuilder();
GCode.AppendLine($"; {About.Website} {About.Software} {Assembly.GetExecutingAssembly().GetName().Version} {arch} {DateTime.Now}");
GCode.AppendLine(";(****Build and Slicing Parameters ****)");
foreach (var propertyInfo in OutputSettings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var displayNameAttribute = propertyInfo.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault();
if (ReferenceEquals(displayNameAttribute, null)) continue;
if (propertyInfo.Name.Equals(nameof(OutputSettings.LayersNum)))
{
GCode.AppendLine($";{displayNameAttribute.DisplayName.PadRight(24)} = {propertyInfo.GetValue(OutputSettings)}");
}
else
{
GCode.AppendLine($";({displayNameAttribute.DisplayName.PadRight(24)} = {propertyInfo.GetValue(OutputSettings)})");
}
}
GCode.AppendLine();
GCode.AppendFormat(Printer == PrinterType.Wanhao ? WanhaoStartGCode : GCodeStart, Environment.NewLine);
float lastZPosition = 0;
for (uint layerIndex = 0; layerIndex < LayerCount; layerIndex++)
{
Layer layer = this[layerIndex];
if (Printer == PrinterType.Wanhao)
{
GCode.AppendFormat(WanhaoPreSliceGCode, Environment.NewLine, layerIndex, OutputSettings.SettleTime);
}
GCode.AppendLine($"{GCodeKeywordSlice} {layerIndex}");
if (layer.ExposureTime > 0 && layer.LightPWM > 0)
{
GCode.AppendLine($"M106 S{layer.LightPWM} ; UV on");
GCode.AppendLine($"{GCodeKeywordDelay} {layer.ExposureTime * 1000}");
GCode.AppendLine("M106 S0 ; UV off");
}
GCode.AppendLine(GCodeKeywordSliceBlank);
if (Printer == PrinterType.Wanhao)
{
GCode.AppendLine($"{GCodeKeywordDelay} 0");
}
if (lastZPosition != layer.PositionZ)
{
if (layer.LiftHeight > 0)
{
float downPos = (float) Math.Round(layer.LiftHeight - layer.PositionZ + lastZPosition, 2);
if (Printer == PrinterType.Wanhao)
{
GCode.AppendLine($";********** Lift Sequence {layerIndex} ********");
}
GCode.AppendLine($"G1 Z{layer.LiftHeight} F{layer.LiftSpeed}");
if (Printer == PrinterType.Wanhao)
{
GCode.AppendLine($"{GCodeKeywordTakes} {OperationCalculator.LightOffDelayC.CalculateMillisecondsLiftOnly(layer.LiftHeight, layer.LiftSpeed)}");
GCode.AppendLine($"G4 P0 ; Wait for lift rise to complete");
GCode.AppendLine($"{GCodeKeywordDelay} 0");
}
GCode.AppendLine($"G1 Z-{downPos} F{layer.RetractSpeed}");
if (Printer == PrinterType.Wanhao)
{
GCode.AppendLine($"{GCodeKeywordTakes} {OperationCalculator.LightOffDelayC.CalculateMillisecondsLiftOnly(downPos, layer.RetractSpeed)}");
}
}
else
{
GCode.AppendLine($"G1 Z{Math.Round(layer.PositionZ - lastZPosition, 2)} F{layer.LiftSpeed}");
}
}
if (Printer != PrinterType.Wanhao)
{
// delay = max(extra['wait'], 500) + int(((int(lift)/(extra['lift_feed']/60)) + (int(lift)/(extra['lift_retract']/60)))*1000)
uint extraDelay =
OperationCalculator.LightOffDelayC.CalculateMilliseconds(layer.LiftHeight, layer.LiftSpeed,
layer.RetractSpeed);
if (layerIndex < BottomLayerCount)
{
extraDelay = (uint) Math.Max(extraDelay + 10000, layer.ExposureTime * 1000);
}
else
{
extraDelay += Math.Max(OutputSettings.BlankingLayerTime, 500);
}
GCode.AppendLine($"{GCodeKeywordDelay} {extraDelay}");
GCode.AppendLine();
}
lastZPosition = layer.PositionZ;
}
GCode.AppendFormat(Printer == PrinterType.Wanhao ? WanhaoGCodeEnd : GCodeEnd, Environment.NewLine, SliceSettings.LiftWhenFinished);
}
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 = ZipFile.Open(FileFullPath, ZipArchiveMode.Update))
{
string arch = Environment.Is64BitOperatingSystem ? "64-bits" : "32-bits";
var entry = outputFile.GetPutFile("slice.conf");
var stream = entry.Open();
stream.SetLength(0);
using (TextWriter tw = new StreamWriter(stream))
{
tw.WriteLine($"# {About.Website} {About.Software} {Assembly.GetExecutingAssembly().GetName().Version} {arch} {DateTime.Now}");
tw.WriteLine("# conf version 1.0");
tw.WriteLine("");
foreach (var propertyInfo in SliceSettings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var displayNameAttribute = propertyInfo.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault();
if (ReferenceEquals(displayNameAttribute, null)) continue;
tw.WriteLine($"{displayNameAttribute.DisplayName.PadRight(24)}= {propertyInfo.GetValue(SliceSettings)}");
}
}
foreach (var zipentry in outputFile.Entries)
{
if (zipentry.Name.EndsWith(".gcode"))
{
zipentry.Delete();
break;
}
}
outputFile.PutFileContent($"{Path.GetFileNameWithoutExtension(FileFullPath)}.gcode", GCode.ToString(), ZipArchiveMode.Update);
/*foreach (var layer in this)
{
if (!layer.IsModified) continue;
outputFile.PutFileContent(layer.Filename, layer.CompressedBytes, ZipArchiveMode.Update);
layer.IsModified = false;
}*/
}
//Decode(FileFullPath, progress);
}
#endregion
}
}
|