Files
UVtools/UVtools.Core/Operations/OperationLightBleedCompensation.cs
T
Tiago Conceição 57b8a9dc84 v3.2.0
- **Core:**
   - (Add) Machine presets and able to load machine collection from PrusaSlicer
   - (Improvement) Core: Reference EmguCV runtimes into core instead of the UI project
- **File formats:**
   - **CXDLP:**
      - (Add) Detection support for Halot One Pro
      - (Add) Detection support for Halot One Plus
      - (Add) Detection support for Halot Sky Plus
      - (Add) Detection support for Halot Lite
      - (Improvement) Better handling and detection of printer model when converting
      - (Improvement) Discovered more fields meanings on format
      - (Fix) Exposure time in format is `round(time * 10, 1)`
      - (Fix) Speeds in format are in mm/s, was using mm/min before
   - (Add) JXS format for Uniformation GKone [Zip+GCode]
   - (Improvement) Saving and converting files now handle the file backup on Core instead on the UI, which prevents scripts and other projects lose the original file in case of error while saving
   - (Fix) After load files they was flagged as requiring a full encode, preventing fast save a fresh file
- **UVtoolsCmd:**
   - Bring back the commandline project
   - Consult README to see the available commands and syntax
   - Old terminal commands on UVtools still works for now, but consider switch to UVtoolsCmd or redirect the command using `UVtools --cmd "commands"`
- **Tools:**
   - **Change print resolution:**
      - (Add) Allow to change the display size to match the new printer
      - (Add) Machine presets to help set both resolution and display size to a correct printer and auto set fix pixel ratio
      - (Improvement) Real pixel pitch fixer due new display size information, this allow full transfers between different printers "without" invalidating the model size
      - (Improvement) Better arrangement of  the layout
   - (Add) Infill: Option "Reinforce infill if possible", it was always on before, now default is off and configurable
   - (Improvement) Always allow to export settings from tools
- **GCode:**
   - (Improvement) After print the last layer, do one lift with the same layer settings before attempt a fast move to top
   - (Improvement) Use the highest defined speed to send the build plate to top after finish print
   - (Improvement) Append a wait sync command in the end of gcode if needed
   - (Fix) When lift without a retract it still output the motor sync delay for the retract time and the wait time after retract
- **PrusaSlicer:**
   - (Add) Printer: Creality Halot One Pro CL-70
   - (Add) Printer: Creality Halot One Plus CL-79
   - (Add) Printer: Creality Halot Sky Plus CL-92
   - (Add) Printer: Creality Halot Lite CL-89L
   - (Add) Printer: Creality Halot Lite CL-89L
   - (Add) Printer: Creality CT133 Pro
   - (Add) Printer: Creality CT-005 Pro
   - (Add) Printer: Uniformation GKone
   - (Add) Printer: FlashForge Foto 8.9S
   - (Add) Printer: Elegoo Mars 2
   - (Improvement) Rename all Creality printers
   - (Fix) Creality model in print notes
2022-03-26 03:38:39 +00:00

274 lines
8.6 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 Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;
namespace UVtools.Core.Operations;
[Serializable]
public class OperationLightBleedCompensation : Operation
{
#region Enums
public enum LightBleedCompensationLookupMode : byte
{
[Description("Previous: Look for sequential pixels relative to the previous layers")]
Previous,
[Description("Next: Look for sequential pixels relative to the next layers")]
Next,
[Description("Both: Look for sequential pixels relative to the previous and next layers")]
Both
}
#endregion
#region Members
private LightBleedCompensationLookupMode _lookupMode = LightBleedCompensationLookupMode.Next;
private string _dimBy = "25,15,10,5";
#endregion
#region Overrides
public override LayerRangeSelection StartLayerRangeSelection => LayerRangeSelection.Normal;
public override string IconClass => "mdi-lightbulb-on";
public override string Title => "Light bleed compensation";
public override string Description =>
"Compensate the over-curing and light bleed from clear resins by dimming the sequential pixels.\n" +
"Note: You need to find the optimal minimum pixel brightness that such resin can print in order to optimize this process.\n" +
"With more translucent resins you can go with lower brightness but stick to a limit that can form the layer without loss." +
" Tiny details can be lost when using low brightness level.\n" +
"After apply a light bleed compensation, do not apply or re-run this tool over.";
public override string ConfirmationText =>
$"compensate layers {LayerIndexStart} through {LayerIndexEnd}?";
public override string ProgressTitle =>
$"Compensate layers {LayerIndexStart} through {LayerIndexEnd}";
public override string ProgressAction => "Compensated layers";
public override string? ValidateInternally()
{
StringBuilder sb = new();
if (DimByArray.Length == 0)
{
sb.AppendLine($"The dim levels are invalid or not set.");
}
if (MaximumSubtraction >= byte.MaxValue)
{
sb.AppendLine($"The sum of dim levels are producing black pixels.");
}
return sb.ToString();
}
public override string ToString()
{
var result = $"[Lookup: {_lookupMode}]" +
$" [Dim by: {_dimBy}]" + LayerRangeString;
if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
return result;
}
#endregion
#region Constructor
public OperationLightBleedCompensation() { }
public OperationLightBleedCompensation(FileFormat slicerFile) : base(slicerFile) { }
#endregion
#region Properties
public LightBleedCompensationLookupMode LookupMode
{
get => _lookupMode;
set => RaiseAndSetIfChanged(ref _lookupMode, value);
}
public string DimBy
{
get => _dimBy;
set
{
if(!RaiseAndSetIfChanged(ref _dimBy, value)) return;
RaisePropertyChanged(nameof(MinimumBrightness));
RaisePropertyChanged(nameof(MaximumSubtraction));
}
}
public int MinimumBrightness => 255 - MaximumSubtraction;
public int MaximumSubtraction => DimByArray.Aggregate(0, (current, dim) => current + dim);
public byte[] DimByArray
{
get
{
List<byte> levels = new();
var split = _dimBy.Split(',', StringSplitOptions.TrimEntries);
foreach (var str in split)
{
if (!byte.TryParse(str, out var brightness)) continue;
if (brightness is byte.MinValue or byte.MaxValue) continue;
levels.Add(brightness);
}
return levels.ToArray();
}
}
public MCvScalar[] DimByMCvScalar
{
get
{
List<MCvScalar> levels = new();
var split = _dimBy.Split(',', StringSplitOptions.TrimEntries);
foreach (var str in split)
{
if (!byte.TryParse(str, out var brightness)) continue;
if (brightness is byte.MinValue or byte.MaxValue) continue;
levels.Add(new MCvScalar(brightness));
}
return levels.ToArray();
}
}
#endregion
#region Equality
protected bool Equals(OperationLightBleedCompensation other)
{
return _lookupMode == other._lookupMode && _dimBy == other._dimBy;
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((OperationLightBleedCompensation) obj);
}
public override int GetHashCode()
{
return HashCode.Combine((int) _lookupMode, _dimBy);
}
#endregion
#region Methods
/// <summary>
/// Get the cached dim mat's
/// </summary>
/// <returns></returns>
public Mat[] GetDimMats()
{
var dimLevels = DimByMCvScalar;
if (dimLevels.Length == 0) return Array.Empty<Mat>();
var mats = new Mat[dimLevels.Length];
var matSize = GetRoiSizeOrDefault();
for (var i = 0; i < mats.Length; i++)
{
mats[i] = EmguExtensions.InitMat(matSize, dimLevels[i]);
}
return mats;
}
protected override bool ExecuteInternally(OperationProgress progress)
{
var dimMats = GetDimMats();
if (dimMats.Length == 0) return false;
Parallel.For(LayerIndexStart, LayerIndexEnd + 1, CoreSettings.GetParallelOptions(progress), layerIndex =>
{
var layer = SlicerFile[layerIndex];
using var mat = layer.LayerMat;
using var original = mat.Clone();
var target = GetRoiOrDefault(mat);
for (byte i = 0; i < dimMats.Length; i++)
{
Mat? mask = null;
Mat? previousMat = null;
Mat? previousMatRoi = null;
Mat? nextMat = null;
Mat? nextMatRoi = null;
if (_lookupMode is LightBleedCompensationLookupMode.Previous or LightBleedCompensationLookupMode.Both)
{
int layerPreviousIndex = (int)layerIndex - i - 1;
if (layerPreviousIndex >= LayerIndexStart)
{
previousMat = SlicerFile[layerPreviousIndex].LayerMat;
mask = previousMatRoi = GetRoiOrDefault(previousMat);
}
}
if (_lookupMode is LightBleedCompensationLookupMode.Next or LightBleedCompensationLookupMode.Both)
{
uint layerIndexNext = (uint) (layerIndex + i + 1);
if (layerIndexNext <= LayerIndexEnd)
{
nextMat = SlicerFile[layerIndexNext].LayerMat;
mask = nextMatRoi = GetRoiOrDefault(nextMat);
}
}
if (previousMat is null && nextMat is null) break; // Nothing more to do
if (previousMat is not null && nextMat is not null) // both, need to merge previous with next layer
{
CvInvoke.Add(previousMatRoi, nextMatRoi, previousMatRoi);
mask = previousMatRoi;
}
CvInvoke.Subtract(target, dimMats[i], target, mask);
previousMat?.Dispose();
nextMat?.Dispose();
}
// Apply the results only to the selected masked area, if user selected one
ApplyMask(original, target);
// Set current layer image with the modified mat we just manipulated
layer.LayerMat = mat;
// Increment progress bar by 1
progress.LockAndIncrement();
});
foreach (var dimMat in dimMats)
{
dimMat.Dispose();
}
// return true if not cancelled by user
return !progress.Token.IsCancellationRequested;
}
#endregion
}