using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Color;
using Chronos.Core.Project;
namespace Chronos.Core.Render;
///
/// The last pixel step of every output frame (owner review 1, R6), shared by the render, the editor's preview, the server
/// and the render nodes: the colour look () and then the highlight knee, in linear light, after
/// stacking, interpolation and motion blur and before the encoder. The knee comes last so it compresses any overshoot the
/// look leaves. Measuring, flow and stacking never see either.
///
public static class FrameFinish
{
///
/// The knee a render applies: when it lies in (0, 1), else none, with
/// Export.Render.KneeIgnored added to for a value out of range.
///
public static double? Knee(double? highlightKnee, ICollection? warnings = null)
{
if (highlightKnee is not { } knee) return null;
if (knee is > 0 and < 1) return knee;
warnings?.Add(new RenderWarning("Export.Render.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture)));
return null;
}
///
/// The look a render applies: null for none, the identity, or a filter this Chronos does not know, which adds
/// Export.Render.LookIgnored to .
///
public static LookSettings? Look(LookSettings? look, ICollection? warnings = null)
{
if (look is null || look.IsIdentity) return null;
if (LookFilter.IsKnown(look.Filter)) return look;
warnings?.Add(new RenderWarning("Export.Render.LookIgnored", look.Filter ?? string.Empty));
return null;
}
/// The share of a look applied: its strength clamped to 0..1, 1 when not given (or not finite).
public static double Strength(LookSettings look)
{
ArgumentNullException.ThrowIfNull(look);
return look.Strength is { } strength && double.IsFinite(strength) ? double.Clamp(strength, 0, 1) : 1;
}
/// Neither a look nor a knee would change a frame.
public static bool IsIdentity(LookSettings? look, double? knee) => (look is null || look.IsIdentity || !LookFilter.IsKnown(look.Filter)) && knee is not (> 0 and < 1);
///
/// Finishes a linear-light output in place: (none when null, the
/// identity or unknown), then the soft highlight knee when lies in (0, 1).
///
public static void Apply(ImageBuffer frame, LookSettings? look, double? knee)
{
ArgumentNullException.ThrowIfNull(frame);
if (look is { IsIdentity: false } && LookFilter.IsKnown(look.Filter)) LookFilter.Apply(frame, look.Filter, Strength(look));
if (knee is > 0 and < 1 and var k) ExposureProcessor.Apply(frame, 0, null, k);
}
}