Files
UVtools/UVtools.Core/FileFormats/VDAFile.cs
T
Tiago Conceição 4600e81b08 v3.0.0
- **(Add) Suggestions:**
   - A new module that detect bad or parameters out of a defined range and suggest a change on the file, those can be auto applied if configured to do so
   - **Avaliable suggestions:**
      - **Bottom layer count:** Bottom layers should be kept to a minimum, usually from 2 to 3, it function is to provide a good adhesion to the first layer on the build plate, using a high count have disadvantages.
      - **Wait time before cure:** Rest some time before cure the layer is crucial to let the resin settle after the lift sequence and allow some time for the arm settle at the correct Z position as the resin will offer some resistance and push the structure.
                                   This lead to better quality with more successful prints, less lamination problems, better first layers with more success of stick to the build plate and less elephant foot effect.
      - **Wait time after cure:** Rest some time after cure the layer and before the lift sequence can be important to allow the layer to cooldown a bit and detach better from the FEP.
      - **Layer height:** Using the right layer height is important to get successful prints:
                          Thin layers may cause problems on adhesion, lamination, will print much slower and have no real visual benefits.
                          Thick layers may not fully cure no matter the exposure time you use, causing lamination and other hazards. Read your resin dtasheet to know the limits.
                          Using layer height with too many decimal digits may produce a wrong positioning due stepper step loss and/or Z axis quality.
- **Core:**
   - Convert the project to Nullable aware and "null-safe"
- **File Formats:**
   - (Add) `Volume` property to get the total model volume
   - (Add) `SanitizeLayers` method to reassign indexes and force attribute parent file
   - (Improvement) Merge `LayerManager` into `FileFormat` and cleanup: This affects the whole project and external scripts.
   If using scripts please update them, search for `.LayerManager.` and replace by `.`
   - (Change) Chitubox encrypted format can now be saved as normal
   - (Fix) Converted files layers was pointing to the source file and related to it
- **Layers:**
   - (Add) Methods: `ResetParameters`, `CopyParametersTo`, `CopyExposureTo`, `CopyWaitTimesTo`
   - (Improvement) `IsBottomLayer` property will also return true when the index is inside bottom layer count
- **Scripting:**
   - (Add) Configuration variable: `MinimumVersionToRun` - Sets the minimum version able to run the script
   - (Improvement) Allow run scripts written in C# 10 with the new namespace; style as well as nullables methods
   - (Improvement) Convert scripts to use Nullable code
- **UI:**
   - (Add) Fluent Dark theme
   - (Add) Default Light theme
   - (Add) Default Dark theme
   - (Change) Use fontawesome and material design to render the icons instead of static png images
   - (Change) Some icons
   - (Change) Move log tab to clipboard tab
   - (Change) Tooltip overlay default color
   - (Improvement) Windows position for tool windows, sometimes framework can return negative values affecting positions, now limits to 0 (#387)
   - (Fix) Center image icon for layer action button
   - (Fix) Center image icon for save layer image button
- **Tools:**
   - (Add) Layer re-height: Offset mode, change layers position by a defined offset (#423)
   - (Improvement) Rotate: Unable to use an angle of 0
   - (Improvement) Remove layers: Will not recalcualte and reset properties of layers anymore, allowing removing layers on dynamic layer height models and others
   - (Improvement) Clone layers: Will not recalcualte and reset properties of layers anymore, allowing cloning layers on dynamic layer height models and others
   - (Fix) Exposure time finder: Very small printers may not print the stock object as it is configured, lead to a unknown error while generating the test. It will now show a better error message and advice a solution (#426)
- **Terminal:**
   - (Add) More default namespaces
   - (Improvement) Set a MinHeight for the rows to prevent spliter from eat the elements
   - (Change) Set working space to the MainWindow instead of TerminalWindow
- **(Upgrade) .NET from 5.0.14 to 6.0.3**
   - This brings big performance improvements, better JIT, faster I/O operations and others
   - Read more: https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-6
   - Due this macOS requirement starts at 10.15 (Catalina)
   - Read more: https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md
- (Add) Native support for MacOS ARM64 architecture (Mac M1 and upcomming Mac's) (#187)
- (Exchange) Dependency Newtonsoft Json by System.Text.Json to parse the json documents
- (Remove) "Automations - Light-off delay" in favor of new suggestion "wait time before cure" module
- (Fix) File - Send to: Winrar or 7zip have a wrong extension on the list (uvt) when should be (uvj)
- (Upgrade) AvaloniaUI from 0.10.12 to 0.10.13
2022-03-12 21:04:47 +00:00

420 lines
12 KiB
C#

/*
* 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.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Xml.Serialization;
using UVtools.Core.Extensions;
using UVtools.Core.Layers;
using UVtools.Core.Operations;
namespace UVtools.Core.FileFormats;
#region Sub Classes
[Serializable]
[XmlRoot(ElementName = "root")]
public class VDARoot
{
[Serializable]
public class VDAFileInfo
{
[Serializable]
public class VDAVersion
{
public ushort Major { get; set; } = 1;
public ushort Minor { get; set; } = 2;
}
[Serializable]
public class VDAWritten
{
[Serializable]
[XmlRoot(ElementName = "By")]
public class VDABy
{
[XmlAttribute]
public string ApplicationName { get; set; } = About.Software;
[XmlAttribute]
public string ApplicationVersion { get; set; } = About.VersionStr;
public override string ToString()
{
return $"{ApplicationName} v{ApplicationVersion}";
}
public void Reset()
{
ApplicationName = About.Software;
ApplicationVersion = About.VersionStr;
}
}
public VDABy By { get; set; } = new();
public string When { get; set; } = DateTime.UtcNow.ToString("u");
public void Reset()
{
When = DateTime.UtcNow.ToString("u");
By.Reset();
}
}
public VDAVersion Version { get; set; } = new();
public VDAWritten Written { get; set; } = new();
}
[Serializable]
public class VDASlices
{
public ushort Count { get; set; } = 1;
[XmlElement("thickness")]
public float LayerHeight { get; set; }
[XmlElement("startHeight")]
public float StartHeight { get; set; }
[XmlElement("endHeight")]
public float EndHeight { get; set; }
[XmlElement("layersCount")]
public uint LayerCount { get; set; }
}
[Serializable]
public class VDAMachines
{
public string FileType { get; set; } = "ZIP File";
public string Resolution { get; set; } = "1920*1080P";
public string PixelXSize { get; set; } = "50um";
public string PixelYSize { get; set; } = "50um";
[XmlElement("Anti-Aliasing")]
public byte AntiAliasing { get; set; } = 1;
public float XLength { get; set; }
public float YWidth { get; set; }
public float ZHeight { get; set; }
}
public class VDALayer
{
[XmlElement("Index")]
public uint Index { get; set; }
[XmlElement("zvalue")]
public float ZPosition { get; set; }
[XmlElement("filename")]
public string? Filename { get; set; }
public VDALayer()
{
}
public VDALayer(uint index, float zPosition, string? filename)
{
Index = index;
ZPosition = zPosition;
Filename = filename;
}
}
public VDAFileInfo FileInfo { get; set; } = new();
public VDASlices Slices { get; set; } = new();
public VDAMachines Machines { get; set; } = new();
public List<VDALayer> Layers { get; set; } = new();
}
#endregion
public class VDAFile : FileFormat
{
#region Constants
#endregion
#region Properties
public VDARoot ManifestFile { get; set; } = new ();
public override FileFormatType FileType => FileFormatType.Archive;
public override FileExtension[] FileExtensions { get; } = {
new(typeof(VDAFile), "zip", "Voxeldance Additive Zip")
};
public override uint ResolutionX
{
get
{
var resolution = ManifestFile.Machines.Resolution.Split('*', StringSplitOptions.TrimEntries);
if (resolution.Length < 2) return 0;
uint.TryParse(resolution[0], out var xRes);
return xRes;
}
set
{
ManifestFile.Machines.Resolution = $"{value}*{ResolutionY}P";
RaisePropertyChanged();
}
}
public override uint ResolutionY
{
get
{
var resolution = ManifestFile.Machines.Resolution.Split('*', StringSplitOptions.TrimEntries);
if (resolution.Length < 2) return 0;
resolution[1] = resolution[1].TrimEnd('P');
uint.TryParse(resolution[1], out var yRes);
return yRes;
}
set
{
ManifestFile.Machines.Resolution = $"{ResolutionX}*{value}P";
RaisePropertyChanged();
}
}
public override float DisplayWidth
{
get
{
if (ManifestFile.Machines.XLength > 0) return ManifestFile.Machines.XLength;
var umStr= ManifestFile.Machines.PixelXSize.Replace("um", string.Empty, StringComparison.OrdinalIgnoreCase);
if (ushort.TryParse(umStr, out var um) && um > 0)
{
return (float) Math.Round(ResolutionX * um / 1000f, 2);
}
return ManifestFile.Machines.XLength;
}
set
{
ManifestFile.Machines.XLength = (float) Math.Round(value, 2);
ManifestFile.Machines.PixelXSize = $"{Math.Round(value / ResolutionX * 1000, 2)}um";
RaisePropertyChanged();
}
}
public override float DisplayHeight
{
get
{
if (ManifestFile.Machines.YWidth > 0) return ManifestFile.Machines.YWidth;
var umStr = ManifestFile.Machines.PixelYSize.Replace("um", string.Empty, StringComparison.OrdinalIgnoreCase);
if (ushort.TryParse(umStr, out var um) && um > 0)
{
return (float)Math.Round(ResolutionY * um / 1000f, 2);
}
return ManifestFile.Machines.YWidth;
}
set
{
ManifestFile.Machines.YWidth = (float)Math.Round(value, 2);
ManifestFile.Machines.PixelYSize = $"{Math.Round(value / ResolutionY * 1000, 2)}um";
RaisePropertyChanged();
}
}
public override float MachineZ
{
get => ManifestFile.Machines.ZHeight > 0 ? ManifestFile.Machines.ZHeight : base.MachineZ;
set
{
ManifestFile.Machines.ZHeight = value;
RaisePropertyChanged();
}
}
public override byte AntiAliasing
{
get => ManifestFile.Machines.AntiAliasing;
set => base.AntiAliasing = ManifestFile.Machines.AntiAliasing = value.Clamp(1, 16);
}
public override float LayerHeight
{
get => ManifestFile.Slices.LayerHeight;
set
{
ManifestFile.Slices.LayerHeight = Layer.RoundHeight(value);
RaisePropertyChanged();
}
}
public override uint LayerCount
{
get => base.LayerCount;
set => base.LayerCount = ManifestFile.Slices.LayerCount = base.LayerCount;
}
public override object[] Configs => new object[] {
ManifestFile.FileInfo.Version,
ManifestFile.FileInfo.Written,
ManifestFile.Machines,
ManifestFile.Slices };
#endregion
#region Constructor
public VDAFile()
{ }
#endregion
#region Methods
public override bool CanProcess(string fileFullPath)
{
if(!base.CanProcess(fileFullPath)) return false;
try
{
using var zip = ZipFile.Open(fileFullPath, ZipArchiveMode.Read);
if (zip.Entries.Any(entry => entry.Name.EndsWith(".xml"))) return true;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
return false;
}
protected override void EncodeInternally(OperationProgress progress)
{
using var outputFile = ZipFile.Open(FileFullPath!, ZipArchiveMode.Create);
var manifestFilename = Filename!.
Replace($".{FileExtensions[0].Extension}{TemporaryFileAppend}", ".xml").
Replace($".{FileExtensions[0].Extension}", ".xml");
for (uint layerIndex = 0; layerIndex < LayerCount; layerIndex++)
{
progress.Token.ThrowIfCancellationRequested();
var layer = this[layerIndex];
var filename = $"{layerIndex + 1}".PadLeft(4, '0') + ".png";
outputFile.PutFileContent(filename, layer.CompressedBytes, ZipArchiveMode.Create);
progress++;
}
UpdateManifest();
var entry = outputFile.CreateEntry(manifestFilename);
using var stream = entry.Open();
XmlExtensions.Serialize(ManifestFile, stream, XmlExtensions.SettingsIndent, true);
}
protected override void DecodeInternally(OperationProgress progress)
{
using (var inputFile = ZipFile.Open(FileFullPath!, ZipArchiveMode.Read))
{
var entry = inputFile.Entries.FirstOrDefault(zipEntry => zipEntry.Name.EndsWith(".xml"));
if (entry is null)
{
Clear();
throw new FileLoadException($".xml manifest not found", FileFullPath);
}
try
{
using var stream = entry.Open();
ManifestFile = XmlExtensions.DeserializeFromStream<VDARoot>(stream);
}
catch (Exception e)
{
Clear();
throw new FileLoadException($"Unable to deserialize '{entry.Name}'\n{e}", FileFullPath);
}
Init(ManifestFile.Slices.LayerCount, DecodeType == FileDecodeType.Partial);
progress.Reset(OperationProgress.StatusDecodeLayers, LayerCount);
for (uint layerIndex = 0; layerIndex < LayerCount; layerIndex++)
{
if (progress.Token.IsCancellationRequested) break;
var filename = $"{layerIndex + 1}".PadLeft(4, '0')+".png";
entry = inputFile.GetEntry(filename);
if (entry is null)
{
Clear();
throw new FileLoadException($"Layer {filename} not found", FileFullPath);
}
if (DecodeType == FileDecodeType.Full)
{
using var stream = entry.Open();
this[layerIndex] = new Layer(layerIndex, stream, this);
}
progress++;
}
}
GetBoundingRectangle(progress);
}
protected override void PartialSaveInternally(OperationProgress progress)
{
using var outputFile = ZipFile.Open(FileFullPath!, ZipArchiveMode.Update);
bool deleted;
do
{
deleted = false;
foreach (var zipEntry in outputFile.Entries)
{
if (!zipEntry.Name.EndsWith(".xml")) continue;
zipEntry.Delete();
deleted = true;
break;
}
} while (deleted);
var manifestFilename = Path.GetFileName(FileFullPath)!.
Replace($".{FileExtensions[0].Extension}{TemporaryFileAppend}", ".xml").
Replace($".{FileExtensions[0].Extension}", ".xml");
UpdateManifest();
var entry = outputFile.CreateEntry(manifestFilename);
using var stream = entry.Open();
XmlExtensions.Serialize(ManifestFile, stream, XmlExtensions.SettingsIndent, true);
}
public void UpdateManifest()
{
ManifestFile.FileInfo.Written.Reset();
ManifestFile.Slices.StartHeight = FirstLayer?.PositionZ ?? 0;
ManifestFile.Slices.EndHeight = LastLayer?.PositionZ ?? 0;
ManifestFile.Layers.Clear();
for (uint layerIndex = 0; layerIndex < LayerCount; layerIndex++)
{
var layer = this[layerIndex];
ManifestFile.Layers.Add(new VDARoot.VDALayer(layerIndex, layer.PositionZ, layer.FormatFileName(4, false)));
}
}
#endregion
}