using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Amphora; using Annulus; using Azimuth; using Blacklight.Core; using Clave; using Glass; using Glass.Text; using Prism; using Tessera.Text; namespace Konis.Testbed { /// /// A panel of fields for the tunable properties of one effect's def. An edit goes straight into the def, so an /// emitter that reads the property as it runs shows it at once and a newly started one always does. /// public class TuningPanel { private const double NameWidth = 120; private const double FieldWidth = 66; private const double ColumnGap = 4; private const double RowGap = 2; private const double SectionGap = 8; private const int PreviewPixels = 64; private const int PlotWidth = (int)FieldWidth; private const int PlotHeight = 40; private const int SpriteColumns = 3; private const string EditText = "Edit"; private const string RespawnText = "Respawn selected"; private const string CopyChangesText = "Copy changes"; private const string CopyAllText = "Copy all"; private class Row { public TunableProperty Property; // A number's field, or the low end of a range. public NumberField Minimum; public NumberField Maximum; public Dropdown Choice; public Checkbox Toggle; // A gradient's swatch, and the button that opens the window that edits it. public GradientBar Preview; public Button Edit; // A function's plot, and the button that opens the window that edits it. public FunctionPlot Plot; public Button FunctionEdit; // How many slabs a def clips to, and the button that opens the window that edits them. public Label Summary; public Button SlabEdit; } private readonly TestbedSkin skin; private readonly NumberFieldBehavior fieldBehavior = new NumberFieldBehavior { AllowsTyping = true }; private readonly List rows = new List(); private readonly Panel content; private readonly Label problemLabel; private readonly Label statusLabel; // The size of everything above the messages, which are the only part that comes and goes. private readonly Scalar bodyWidth; private readonly Scalar bodyHeight; private readonly Func copy; private readonly WindowHandle window; private readonly GradientWindow gradients; private readonly FunctionWindow functions; private readonly SlabWindow slabs; private readonly SpritePreviews previews; private EmitterDef def; private Row gradientRow; // The function row the window is editing, which it keeps editing on the next def. private Row openFunctionRow; private Row slabRow; private string title = ""; private TunableSnapshot snapshot; // Set while the panel puts a def's values into the fields, so that doing so isn't taken for an edit. private bool showing; /// /// Builds the panel. One button calls , and two hand text to , which returns whether it took the text. A gradient is edited in , and its swatch is a texture made through . A function is /// edited in , and the clip slabs in . The sprite list /// shows a picture of each sprite from . /// public TuningPanel(TestbedSkin skin, Tooltip respawnTooltip, Action respawn, Func copy, WindowHandle window, GradientWindow gradients, FunctionWindow functions, SlabWindow slabs, SpritePreviews previews) { this.skin = skin; this.copy = copy ?? throw new ArgumentNullException(nameof(copy)); this.window = window ?? throw new ArgumentNullException(nameof(window)); this.gradients = gradients ?? throw new ArgumentNullException(nameof(gradients)); this.functions = functions ?? throw new ArgumentNullException(nameof(functions)); this.slabs = slabs ?? throw new ArgumentNullException(nameof(slabs)); this.previews = previews ?? throw new ArgumentNullException(nameof(previews)); content = new Panel { Material = Glass.Material.Invisible, AbsorbsMouse = false }; Scalar fieldHeight = skin.NumberField.BoundsSizeFor(new Vector(0, skin.ButtonText.SingleLineHeight)).Y; Scalar lineHeight = skin.Text.SingleLineHeight; Vector editSize = skin.ButtonSizeFor(EditText); Vector respawnSize = skin.ButtonSizeFor(RespawnText); Vector changesSize = skin.ButtonSizeFor(CopyChangesText); Vector copyAllSize = skin.ButtonSizeFor(CopyAllText); // The panel is as wide as its widest row needs, so no button is cut short of its text. var numberRow = new RectAggregator(new Vector(ColumnGap, 0)); numberRow.NewCol(NameWidth); numberRow.NewCols(FieldWidth, 2); var editRow = new RectAggregator(new Vector(ColumnGap, 0)); editRow.NewCol(NameWidth); editRow.NewCol(FieldWidth); editRow.NewCol(editSize.X); var copyButtons = new RectAggregator(new Vector(ColumnGap, 0)); copyButtons.NewCol(changesSize.X); copyButtons.NewCol(copyAllSize.X); Scalar width = Scalar.Max( Scalar.Max(numberRow.Rect.Width, editRow.Rect.Width), Scalar.Max(copyButtons.Rect.Width, respawnSize.X)); var stack = new RectAggregator(Rect.FromPositionAndSize(Vector.Zero, new Vector(width, 0)), new Vector(0, RowGap)); Rect legendSlot = stack.NewRow(lineHeight); content.CanvasChildren.Add(new Label( skin.RespawnHeadingText, "amber: takes effect on respawn", Constraints.Tight(legendSlot.Size)) { Bounds = legendSlot, }); Scalar buttonHeight = skin.Button.BoundsSizeFor(new Vector(0, lineHeight)).Y; foreach (TunableProperty property in Tunables.Of(Effects.All[0].Def)) { if (property.Kind != TunableKind.Computed) { // A button has more to it than a field, so a row that holds one is as tall as a button. A plot // needs room to show a shape. Scalar height = property.Kind == TunableKind.Gradient ? buttonHeight : fieldHeight; if (property.Kind == TunableKind.Function) { height = PlotHeight; } rows.Add(BuildRow(content, stack.NewRow(height), property)); } } content.CanvasChildren.Add(BuildButton( stack.NewRow(buttonHeight, margin: SectionGap), RespawnText, respawnTooltip, respawn)); Rect copyRow = stack.NewRow(buttonHeight); Rect changesSlot = copyRow.NewCol(changesSize.X, HorizontalJustification.Left, ColumnGap); content.CanvasChildren.Add(BuildButton(changesSlot, CopyChangesText, skin.TooltipFor("Copy C# for the values changed since this effect was picked"), CopyChanges)); content.CanvasChildren.Add(BuildButton(copyRow, CopyAllText, skin.TooltipFor("Copy C# for every value of this effect"), CopyAll)); bodyWidth = width; bodyHeight = stack.Rect.Height; statusLabel = new Label(skin.HeadingText, "", Constraints.Unbounded) { DebugName = "status" }; problemLabel = new Label(skin.ProblemText, "", Constraints.Unbounded) { DebugName = "problem" }; content.CanvasChildren.Add(statusLabel); content.CanvasChildren.Add(problemLabel); // The fields are laid out at one size, so there is nothing for resizing to do. Frame = new Window { DebugName = "tuning", TitleStyle = skin.HeadingText, WindowMaterial = skin.Window, Resizable = false, Visible = false, }; Frame.CanvasChildren.Add(content); Frame.Title = "Tuning"; Frame.CloseButton.CanvasChildren.Add( new Label(skin.ButtonText, "x", Constraints.Tight(Frame.CloseButton.CanvasRect.Size))); LayOutMessages(); } /// /// Gets the window to add to the world. /// public Window Frame { get; } /// /// Gets the def the fields show and change, or null before one is shown. /// public EmitterDef Def => def; private static string Trimmed(decimal value, NumberFormat numberFormat) { decimal rounded = decimal.Round(value, 3, MidpointRounding.AwayFromZero); int decimals = 0; while (decimals < 3 && decimal.Round(rounded, decimals) != rounded) { ++decimals; } return numberFormat.ToStringFixed(rounded, decimals, grouped: false); } /// /// Returns what to tell the user after copying , where says /// whether the clipboard took it. /// public static string CopyMessage(string text, bool copied) { if (text.Length == 0) { return "Nothing has changed"; } if (!copied) { return "The clipboard is busy"; } int lines = 0; int at = text.IndexOf(Environment.NewLine, StringComparison.Ordinal); while (at >= 0) { lines++; at = text.IndexOf(Environment.NewLine, at + Environment.NewLine.Length, StringComparison.Ordinal); } return lines == 1 ? "Copied 1 line" : $"Copied {lines} lines"; } /// /// Returns what the slab row says about , such as "2 slabs". /// public static string SlabSummary(Slab[] slabs) { if (slabs == null || slabs.Length == 0) { return "none"; } return slabs.Length == 1 ? "1 slab" : $"{slabs.Length} slabs"; } // A function the window can't edit, such as one made of code, closes it rather than leaving it on the last one. private void EditFunction(Row row) { if (def == null) { return; } object function = row.Property.Get(def); if (!FunctionWindow.CanEdit((IScalarFunction)function)) { openFunctionRow = null; functions.Close(); return; } openFunctionRow = row; functions.Edit( (IScalarFunction)function, edited => ApplyFromWindow(row, edited), FriendlyName(row.Property.Name) + ": " + title); } private void EditSlabs(Row row) { if (def == null) { return; } slabRow = row; slabs.Edit( (Slab[])row.Property.Get(def), edited => Apply(row, edited), FriendlyName(row.Property.Name) + ": " + title); } private Button BuildButton(Rect slot, string text, Tooltip tooltip, Action action) { var button = new Button(ButtonBehavior.Default) { ButtonMaterial = skin.Button, Bounds = slot, DebugName = text + " button", Tooltip = tooltip, }; button.CanvasChildren.Add(new Label(skin.ButtonText, text, Constraints.Tight(button.CanvasRect.Size))); button.OnActivate += (ButtonBase _, in KeyboardSnapshot __, KeyboardManager ___) => action(); return button; } // A message that isn't showing takes no room, so the window is as tall as what it holds. private void PlaceMessage(Label message, ref RectAggregator stack) { if (message.Text.ToString().Length == 0) { message.Visible = false; return; } Vector wanted = message.PreferredSize(Constraints.Loose(new Vector(bodyWidth, Scalar.PositiveInfinity))); message.Visible = true; message.Bounds = stack.NewRow(wanted.Y); } private void LayOutMessages() { var stack = new RectAggregator( Rect.FromPositionAndSize(Vector.Zero, new Vector(bodyWidth, 0)), new Vector(0, RowGap)); stack.NewRow(bodyHeight); PlaceMessage(statusLabel, ref stack); PlaceMessage(problemLabel, ref stack); content.Bounds = stack.Rect; Frame.MinContentSize = stack.Rect.Size; Frame.Bounds = Frame.Bounds.WithSize(skin.Window.BoundsSizeFor(stack.Rect.Size, Frame.TitleBarHeight)); } private void ShowStatus(string text) { statusLabel.Text = text; LayOutMessages(); } /// /// Shows under the buttons as what a def refused, or shows nothing when it is empty. /// public void ShowProblem(string text) { problemLabel.Text = text; LayOutMessages(); } private void Copy(string text) { bool copied = text.Length > 0 && copy(text); ShowStatus(CopyMessage(text, copied)); } /// /// Copies initializer lines for the values changed since the def was bound. /// public void CopyChanges() { if (def != null) { Copy(DefText.Write(def, snapshot)); } } /// /// Copies initializer lines for every value of the bound def. /// public void CopyAll() { if (def != null) { Copy(DefText.Write(def, null)); } } /// /// Returns the words a property goes by on screen, such as "sort by" for SortBy. /// public static string FriendlyName(string propertyName) { if (propertyName == nameof(StandardEmitterDef.AngularVelocity)) { return "spin"; } var returnMe = new StringBuilder(); for (int i = 0; i < propertyName.Length; i++) { char letter = propertyName[i]; if (char.IsUpper(letter) && i > 0) { returnMe.Append(' '); } returnMe.Append(char.ToLowerInvariant(letter)); } return returnMe.ToString(); } private NumberField BuildField(Rect slot, string name, NumberGrid grid) { return new NumberField(fieldBehavior, new NumberField.Data { Grid = grid, Value = grid.Min, Format = Trimmed }) { NumberFieldMaterial = skin.NumberField, Bounds = slot, DebugName = name, }; } private void Apply(Row row, object value) { Status set = row.Property.Set(def, value); ShowProblem(set.IsOk ? "" : set.Describe()); // Shows what the def now holds, which puts back a refused value and moves the end of a range that the other // end pushed. Show(row); } // An editing window says for itself why a value was refused, so none is shown here. private Status ApplyFromWindow(Row row, object value) { ShowProblem(""); Status set = row.Property.Set(def, value); Show(row); return set; } private void EditGradient(Row row) { if (def == null) { return; } gradients.Edit( (Gradient)row.Property.Get(def), gradient => ApplyFromWindow(row, gradient), FriendlyName(row.Property.Name) + ": " + title); } private void EditedNumber(Row row, bool isMaximum, decimal value) { if (showing || def == null) { return; } if (row.Property.Kind == TunableKind.Whole) { Apply(row, (int)value); return; } if (row.Property.Kind == TunableKind.Number) { Apply(row, (Scalar)(double)value); return; } var current = (Variation)row.Property.Get(def); Apply(row, isMaximum ? RangeEdit.WithMaximum(current, (double)value) : RangeEdit.WithMinimum(current, (double)value)); } private Control BuildChoiceRow(TunableProperty property, object choice) { if (property.Kind == TunableKind.Sprite) { return previews.CellFor(SpriteChoices.Find((SpriteDef)choice), skin.Text); } return new Label(skin.Text, property.LabelOf(choice), Constraints.Unbounded); } private Row BuildRow(Panel content, Rect slot, TunableProperty property) { var row = new Row { Property = property }; string text = FriendlyName(property.Name); if (property.Kind == TunableKind.Toggle) { row.Toggle = new Checkbox(ButtonBehavior.Default) { UncheckedMaterial = skin.CheckOff, CheckedMaterial = skin.CheckOn, Bounds = slot, DebugName = text + " checkbox", }; row.Toggle.CanvasChildren.Add( new Label(skin.Text, text, Constraints.Tight(row.Toggle.CanvasRect.Size))); row.Toggle.OnCheckedChanged += isChecked => { if (!showing && def != null) { Apply(row, isChecked); } }; content.CanvasChildren.Add(row.Toggle); return row; } Rect remainder = slot; Rect nameSlot = remainder.NewCol(NameWidth, HorizontalJustification.Left, ColumnGap); TextMaterialStyle nameStyle = property.Effect == TuneEffect.Respawn ? skin.RespawnHeadingText : skin.HeadingText; content.CanvasChildren.Add( new Label(nameStyle, text, Constraints.Tight(nameSlot.Size)) { Bounds = nameSlot }); if (property.Kind == TunableKind.Gradient) { Rect previewSlot = remainder.NewCol(FieldWidth, HorizontalJustification.Left, ColumnGap); row.Preview = new GradientBar(window, PreviewPixels); content.CanvasChildren.Add(new Panel { Material = row.Preview.Material, Bounds = previewSlot, DebugName = text + " preview", }); row.Edit = BuildButton(remainder, EditText, skin.TooltipFor("Edit the gradient in its own window"), () => EditGradient(row)); content.CanvasChildren.Add(row.Edit); gradientRow = row; return row; } if (property.Kind == TunableKind.Slabs) { Rect summarySlot = remainder.NewCol(FieldWidth, HorizontalJustification.Left, ColumnGap); row.Summary = new Label(skin.Text, "", Constraints.Tight(summarySlot.Size)) { Bounds = summarySlot, DebugName = text + " summary", }; content.CanvasChildren.Add(row.Summary); row.SlabEdit = BuildButton(remainder, EditText, skin.TooltipFor("Edit the slabs in their own window"), () => EditSlabs(row)); row.SlabEdit.DebugName = text + " edit button"; content.CanvasChildren.Add(row.SlabEdit); return row; } if (property.Kind == TunableKind.Function) { Rect plotSlot = remainder.NewCol(FieldWidth, HorizontalJustification.Left, ColumnGap); row.Plot = new FunctionPlot(window, PlotWidth, PlotHeight); content.CanvasChildren.Add(new Panel { Material = row.Plot.Material, Bounds = plotSlot, DebugName = text + " plot", }); // A button is shorter than the plot, so it sits in the middle of the row. Scalar buttonHeight = skin.Button.BoundsSizeFor(new Vector(0, skin.Text.SingleLineHeight)).Y; var buttonSize = new Vector(remainder.Width, buttonHeight); Rect buttonSlot = remainder; buttonSlot.Center(buttonSize, Shortfall.UseWhatIsLeft); row.FunctionEdit = BuildButton( buttonSlot, EditText, skin.TooltipFor("Edit the function in its own window"), () => EditFunction(row)); row.FunctionEdit.DebugName = text + " edit button"; content.CanvasChildren.Add(row.FunctionEdit); return row; } if (property.Kind == TunableKind.Choice || property.Kind == TunableKind.Sprite) { row.Choice = new Dropdown { DebugName = text + " dropdown", DropdownMaterial = skin.Dropdown }; row.Choice.Bounds = remainder; row.Choice.Rebuild(property.Choices, buildRow: choice => BuildChoiceRow(property, choice), buildFace: choice => new Label(skin.Text, property.LabelOf(choice))); if (property.Kind == TunableKind.Sprite) { row.Choice.Columns = SpriteColumns; } row.Choice.OnSelectionChanged += index => { if (!showing && def != null && index.HasValue) { Apply(row, property.Choices[index.Value]); } }; content.CanvasChildren.Add(row.Choice); return row; } NumberGrid grid = TuningGrids.For(property.Name); Rect minimumSlot = remainder.NewCol(FieldWidth, HorizontalJustification.Left, ColumnGap); row.Minimum = BuildField(minimumSlot, text + " field", grid); row.Minimum.OnValueChanged += (_, __, now) => EditedNumber(row, isMaximum: false, now); content.CanvasChildren.Add(row.Minimum); if (property.Kind == TunableKind.Range) { row.Maximum = BuildField(remainder, text + " maximum field", grid); row.Maximum.OnValueChanged += (_, __, now) => EditedNumber(row, isMaximum: true, now); content.CanvasChildren.Add(row.Maximum); } return row; } private void Show(Row row) { object value = row.Property.Get(def); showing = true; try { switch (row.Property.Kind) { case TunableKind.Whole: row.Minimum.Value = (int)value; break; case TunableKind.Number: row.Minimum.Value = (decimal)((Scalar)value).Value; break; case TunableKind.Range: var range = (Variation)value; row.Minimum.Value = (decimal)range.Minimum.Value; row.Maximum.Value = (decimal)range.Maximum.Value; break; case TunableKind.Choice: row.Choice.Select(IndexOf(row.Property.Choices, value)); break; case TunableKind.Sprite: // A def with no sprite shows nothing picked. row.Choice.Select(value == null ? (int?)null : IndexOf(row.Property.Choices, value)); break; case TunableKind.Toggle: row.Toggle.Checked = (bool)value; break; case TunableKind.Gradient: row.Preview.Show((Gradient)value); break; case TunableKind.Slabs: row.Summary.Text = SlabSummary((Slab[])value); break; case TunableKind.Function: row.Plot.Show((IScalarFunction)value); row.FunctionEdit.Enabled = FunctionWindow.CanEdit((IScalarFunction)value); break; } } finally { showing = false; } } private static int IndexOf(IReadOnlyList choices, object value) { for (int i = 0; i < choices.Count; i++) { if (choices[i].Equals(value)) { return i; } } throw new InvalidOperationException($"{value} isn't one of the choices."); } /// /// Shows 's values under , and sends every edit to it. /// public void Bind(EmitterDef newDef, string newTitle) { def = newDef ?? throw new ArgumentNullException(nameof(newDef)); title = newTitle; snapshot = new TunableSnapshot(newDef); Frame.Title = "Tuning " + newTitle; problemLabel.Text = ""; statusLabel.Text = ""; LayOutMessages(); foreach (Row row in rows) { Show(row); } // An open editor follows the panel to the new effect, so its edits never land on the old one. if (gradients.IsOpen) { EditGradient(gradientRow); } if (functions.IsOpen && openFunctionRow != null) { EditFunction(openFunctionRow); } if (slabs.IsOpen) { EditSlabs(slabRow); } } } }